Java Code Examples for org.jvnet.hudson.test.JenkinsRule#WebClient

The following examples show how to use org.jvnet.hudson.test.JenkinsRule#WebClient . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: KubernetesPipelineTest.java    From kubernetes-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void computerCantBeConfigured() throws Exception {
    r.jenkins.setSecurityRealm(r.createDummySecurityRealm());
    r.jenkins.setAuthorizationStrategy(new MockAuthorizationStrategy().
            grant(Jenkins.ADMINISTER).everywhere().to("admin"));
    SemaphoreStep.waitForStart("pod/1", b);
    Optional<KubernetesSlave> optionalNode = r.jenkins.getNodes().stream().filter(KubernetesSlave.class::isInstance).map(KubernetesSlave.class::cast).findAny();
    assertTrue(optionalNode.isPresent());
    KubernetesSlave node = optionalNode.get();

    JenkinsRule.WebClient wc = r.createWebClient().login("admin");
    wc.getOptions().setPrintContentOnFailingStatusCode(false);

    HtmlPage nodeIndex = wc.getPage(node);
    assertNotXPath(nodeIndex, "//*[text() = 'configure']");
    wc.assertFails(node.toComputer().getUrl()+"configure", 403);
    SemaphoreStep.success("pod/1", null);
}
 
Example 2
Source File: RoundTripAbstractTest.java    From configuration-as-code-plugin with MIT License 6 votes vote down vote up
private void applyConfigViaWebUI(String jenkinsConfig) throws Exception {
    // The UI requires the path to the config file
    File f = tempFolder.newFile();
    writeToFile(jenkinsConfig, f.getAbsolutePath());

    // Call the replace url
    JenkinsRule.WebClient client = r.j.createWebClient();
    WebRequest request = new WebRequest(client.createCrumbedUrl("configuration-as-code/replace"), POST);
    NameValuePair param = new NameValuePair("_.newSource", f.toURI().toURL().toExternalForm());
    request.setRequestParameters(Collections.singletonList(param));
    request.setRequestParameters(Collections.singletonList(param));
    WebResponse response = client.loadWebResponse(request);
    assertEquals("Failed to POST to " + request.getUrl().toString(), 200, response.getStatusCode());
    String res = response.getContentAsString();
    /* The result page has:
    Configuration loaded from :
                    <ul>
                        <li>path</li>
                    </ul>
    path is the file used to store the configuration.
     */
    assertThat(res, containsString(f.toURI().toURL().toExternalForm()));
}
 
Example 3
Source File: Security1290Test.java    From configuration-as-code-plugin with MIT License 6 votes vote down vote up
@Test
public void configurationAsCodePagesPermissions() throws Exception {
    final String ADMIN = "admin";
    final String USER = "user";

    j.jenkins.setCrumbIssuer(null);
    j.jenkins.setSecurityRealm(j.createDummySecurityRealm());
    j.jenkins.setAuthorizationStrategy(new MockAuthorizationStrategy()
            .grant(Jenkins.ADMINISTER).everywhere().to(ADMIN)
            .grant(Jenkins.READ).everywhere().to(USER)
    );

    JenkinsRule.WebClient adminWc = j.createWebClient();
    adminWc.login(ADMIN);

    JenkinsRule.WebClient userWc = j.createWebClient()
            .withThrowExceptionOnFailingStatusCode(false);
    userWc.login(USER);

    assertRightPermissionConfigurations("configuration-as-code/schema", adminWc, userWc);
    assertRightPermissionConfigurations("configuration-as-code/reference", adminWc, userWc);
}
 
Example 4
Source File: LockStepTest.java    From lockable-resources-plugin with MIT License 5 votes vote down vote up
@Test
public void unlockButtonWithWaitingRuns() throws Exception {
  LockableResourcesManager.get().createResource("resource1");
  WorkflowJob p = j.jenkins.createProject(WorkflowJob.class, "p");
  p.setDefinition(
      new CpsFlowDefinition(
          "retry(99) {\n"
              + "    lock('resource1') {\n"
              + "        semaphore('wait-inside')\n"
              + "     }\n"
              + "}",
          true));

  JenkinsRule.WebClient wc = j.createWebClient();

  WorkflowRun prevBuild = null;
  for (int i = 0; i < 3; i++) {
    WorkflowRun rNext = p.scheduleBuild2(0).waitForStart();
    if (prevBuild != null) {
      j.waitForMessage(
          "[resource1] is locked by " + prevBuild.getFullDisplayName() + ", waiting...", rNext);
      isPaused(rNext, 1, 1);
      wc.goTo("lockable-resources/unlock?resource=resource1");
    }

    j.waitForMessage("Lock acquired on [resource1]", rNext);
    SemaphoreStep.waitForStart("wait-inside/" + (i + 1), rNext);
    isPaused(rNext, 1, 0);

    if (prevBuild != null) {
      SemaphoreStep.success("wait-inside/" + i, null);
      j.assertBuildStatusSuccess(j.waitForCompletion(prevBuild));
    }
    prevBuild = rNext;
  }
  SemaphoreStep.success("wait-inside/3", null);
  j.assertBuildStatus(Result.SUCCESS, j.waitForCompletion(prevBuild));
}
 
Example 5
Source File: DockerTraceabilityRootActionTest.java    From docker-traceability-plugin with MIT License 5 votes vote down vote up
@Test
public void rawContainerDockerInspectSubmissions() throws Exception {
    
    // Read data from resources
    String inspectData = JSONSamples.inspectContainerData.readString();
    InspectContainerResponse inspectResponse = JSONSamples.inspectContainerData.
            readObject(InspectContainerResponse[].class)[0];
    final String containerId = inspectResponse.getId();
    final String imageId = inspectResponse.getImageId();
    
    // Init system data
    JenkinsRule.WebClient client = j.createWebClient();
    final DockerTraceabilityRootAction action = DockerTraceabilityRootAction.getInstance();
    assertNotNull(action);
         
    // Prepare a run with Fingerprints and referenced facets
    createTestBuildRefFacet(imageId, "test");
    
    // Submit JSON
    action.doSubmitContainerStatus(inspectData, null, null, null, 0, null, null);
    
    // Ensure there's a fingerprint for container, which refers the image
    final DockerDeploymentFacet containerFacet = assertExistsDeploymentFacet(containerId, imageId);
    
    // Ensure there's a fingerprint for image
    final DockerDeploymentRefFacet containerRefFacet = assertExistsDeploymentRefFacet(containerId, imageId);
    
    // Try to call the actions method to retrieve the data
    final Page res;
    try {
        res = client.goTo("docker-traceability/rawContainerInfo?id="+containerId, null);
    } catch (Exception ex) {
        ex.getMessage();
        throw new AssertionError("Cannot get a response from rawInfo page", ex);
    }
    final String responseJSON = res.getWebResponse().getContentAsString();
    ObjectMapper mapper= new ObjectMapper();
    final InspectContainerResponse[] parsedData = mapper.readValue(responseJSON, InspectContainerResponse[].class);
    assertEquals(1, parsedData.length);       
}
 
Example 6
Source File: EndpointTest.java    From github-branch-source-plugin with MIT License 5 votes vote down vote up
private Page post(String relative, String userName) throws Exception {
    final JenkinsRule.WebClient client;
    if (userName != null) {
        client = j.createWebClient().login(userName);
    } else {
        client = j.createWebClient();
    }

    final WebRequest request = new WebRequest(new URL(client.getContextPath() + relative), client.getBrowserVersion().getHtmlAcceptHeader());
    request.setHttpMethod(HttpMethod.POST);
    request.setRequestParameters(Arrays.asList(new NameValuePair(Functions.getCrumbRequestField(), Functions.getCrumb(null))));
    return client.getPage(request);
}
 
Example 7
Source File: GogsWebHookJenkinsTest.java    From gogs-webhook-plugin with MIT License 5 votes vote down vote up
@Test
@Issue("SECURITY-1438")
public void ensureTheSecretIsEncryptedInHtml() throws Exception {
    Secret secret = Secret.fromString("s3cr3t");
    FreeStyleProject p = prepareProjectWithGogsProperty(secret);

    JenkinsRule.WebClient wc = j.createWebClient();
    // there are some errors in the page and thus the status is 500 but the content is there
    wc.getOptions().setThrowExceptionOnFailingStatusCode(false);
    HtmlPage htmlPage = wc.goTo(p.getUrl() + "configure");
    String pageContent = htmlPage.getWebResponse().getContentAsString();
    assertThat(pageContent, not(containsString(secret.getPlainText())));
    assertThat(pageContent, containsString(secret.getEncryptedValue()));
}
 
Example 8
Source File: TryBlueOceanMenuTest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Test
public void testOpenBlueOcean() throws IOException, SAXException {
    JenkinsRule.WebClient webClient = j.createWebClient();
    HtmlPage page = webClient.getPage(j.getInstance());
    HtmlAnchor anchor = page.getAnchorByText(Messages.BlueOceanUrlAction_DisplayName());
    Assert.assertEquals("/jenkins/blue/organizations/jenkins/pipelines/", anchor.getHrefAttribute());
    Assert.assertEquals("task-link", anchor.getAttribute("class"));
}
 
Example 9
Source File: LockStepTest.java    From lockable-resources-plugin with MIT License 5 votes vote down vote up
@Issue("JENKINS-34433")
@Test
public void manualUnreserveUnblocksJob() throws Exception {
  LockableResourcesManager.get().createResource("resource1");
  JenkinsRule.WebClient wc = j.createWebClient();

  wc.goTo("lockable-resources/reserve?resource=resource1");
  LockableResource resource1 = LockableResourcesManager.get().fromName("resource1");
  assertNotNull(resource1);
  resource1.setReservedBy("someone");
  assertTrue(resource1.isReserved());

  JSONObject apiRes = TestHelpers.getResourceFromApi(j, "resource1", false);
  assertThat(apiRes, hasEntry("reserved", true));
  assertThat(apiRes, hasEntry("reservedBy", "someone"));

  WorkflowJob p = j.jenkins.createProject(WorkflowJob.class, "p");
  p.setDefinition(
      new CpsFlowDefinition(
          "retry(99) {\n"
              + "    lock('resource1') {\n"
              + "        semaphore('wait-inside')\n"
              + "     }\n"
              + "}",
          true));

  WorkflowRun r = p.scheduleBuild2(0).waitForStart();
  j.waitForMessage("[resource1] is locked, waiting...", r);
  wc.goTo("lockable-resources/unreserve?resource=resource1");
  SemaphoreStep.waitForStart("wait-inside/1", r);
  SemaphoreStep.success("wait-inside/1", null);
  j.assertBuildStatusSuccess(j.waitForCompletion(r));
}
 
Example 10
Source File: Migrate2_3xIT.java    From aws-codecommit-trigger-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldNotSeeMigrationButton() throws IOException, SAXException {
    JenkinsRule.WebClient webClient = jenkinsRule.createWebClient();
    DomElement configureSection = webClient.goTo("configure").getElementsByName("AwsCodeCommitTriggerPlugin").get(0);
    List<?> buttons = configureSection.getByXPath("//button[contains(.,'Migration')]");
    Assertions.assertThat(buttons).isEmpty();
}
 
Example 11
Source File: RoundTripAbstractTest.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
private void assertConfigViaWebUI(String jenkinsConfig) throws Exception {
    // The UI requires the path to the config file
    File f = tempFolder.newFile();
    writeToFile(jenkinsConfig, f.getAbsolutePath());

    // Call the check url
    JenkinsRule.WebClient client = r.j.createWebClient();
    WebRequest request = new WebRequest(client.createCrumbedUrl("configuration-as-code/checkNewSource"), POST);
    NameValuePair param = new NameValuePair("newSource", f.toURI().toURL().toExternalForm());
    request.setRequestParameters(Collections.singletonList(param));
    WebResponse response = client.loadWebResponse(request);
    assertEquals("Failed to POST to " + request.getUrl().toString(), 200, response.getStatusCode());
    String res = response.getContentAsString();
    assertThat(res, containsString("The configuration can be applied"));
}
 
Example 12
Source File: TestReportUiTest.java    From junit-plugin with MIT License 5 votes vote down vote up
/**
 * Validate CSS styles present to prevent duration text from wrapping
 */
@Issue("JENKINS-24352")
@Test
public void testDurationStyle() throws Exception {
    AbstractBuild b = configureTestBuild("render-test");

    JenkinsRule.WebClient wc = j.createWebClient();

    wc.setAlertHandler(new AlertHandler() {
        @Override
        public void handleAlert(Page page, String message) {
            throw new AssertionError();
        }
    });

    HtmlPage pg = wc.getPage(b, "testReport");

    // these are from the test result file:
    String duration14sec = Util.getTimeSpanString((long) (14.398 * 1000));
    String duration3_3sec = Util.getTimeSpanString((long) (3.377 * 1000));
    String duration2_5sec = Util.getTimeSpanString((long) (2.502 * 1000));

    Assert.assertNotNull(pg.getFirstByXPath("//td[contains(text(),'" + duration3_3sec + "')][contains(@class,'no-wrap')]"));

    pg = wc.getPage(b, "testReport/org.twia.vendor");

    Assert.assertNotNull(pg.getFirstByXPath("//td[contains(text(),'" + duration3_3sec + "')][contains(@class,'no-wrap')]"));
    Assert.assertNotNull(pg.getFirstByXPath("//td[contains(text(),'" + duration14sec + "')][contains(@class,'no-wrap')]"));

    pg = wc.getPage(b, "testReport/org.twia.vendor/VendorManagerTest");

    Assert.assertNotNull(pg.getFirstByXPath("//td[contains(text(),'" + duration2_5sec + "')][contains(@class,'no-wrap')]"));
}
 
Example 13
Source File: JwtAuthenticationServiceImplTest.java    From blueocean-plugin with MIT License 4 votes vote down vote up
@Test
    public void anonymousUserToken() throws Exception{
        j.jenkins.setSecurityRealm(j.createDummySecurityRealm());
        JenkinsRule.WebClient webClient = j.createWebClient();
        String token = getToken(webClient);
        Assert.assertNotNull(token);


        JsonWebStructure jsonWebStructure = JsonWebStructure.fromCompactSerialization(token);

        Assert.assertTrue(jsonWebStructure instanceof JsonWebSignature);

        JsonWebSignature jsw = (JsonWebSignature) jsonWebStructure;


        String kid = jsw.getHeader("kid");

        Assert.assertNotNull(kid);

        Page page = webClient.goTo("jwt-auth/jwks/"+kid+"/", "application/json");

//        for(NameValuePair valuePair: page.getWebResponse().getResponseHeaders()){
//            System.out.println(valuePair);
//        }

        JSONObject jsonObject = JSONObject.fromObject(page.getWebResponse().getContentAsString());
        RsaJsonWebKey rsaJsonWebKey = new RsaJsonWebKey(jsonObject,null);

        JwtConsumer jwtConsumer = new JwtConsumerBuilder()
            .setRequireExpirationTime() // the JWT must have an expiration time
            .setAllowedClockSkewInSeconds(30) // allow some leeway in validating time based claims to account for clock skew
            .setRequireSubject() // the JWT must have a subject claim
            .setVerificationKey(rsaJsonWebKey.getKey()) // verify the sign with the public key
            .build(); // create the JwtConsumer instance

        JwtClaims claims = jwtConsumer.processToClaims(token);
        Assert.assertEquals("anonymous",claims.getSubject());

        Map<String,Object> claimMap = claims.getClaimsMap();

        Map<String,Object> context = (Map<String, Object>) claimMap.get("context");
        Map<String,String> userContext = (Map<String, String>) context.get("user");
        Assert.assertEquals("anonymous", userContext.get("id"));
    }
 
Example 14
Source File: UsernamePasswordBindingTest.java    From credentials-binding-plugin with MIT License 4 votes vote down vote up
@Test
public void theSecretBuildWrapperTracksUsage() throws Exception {
    SystemCredentialsProvider.getInstance().setDomainCredentialsMap(
    Collections.singletonMap(Domain.global(), Collections.<Credentials>emptyList()));
    for (CredentialsStore s : CredentialsProvider.lookupStores(Jenkins.getInstance())) {
        if (s.getProvider() instanceof SystemCredentialsProvider.ProviderImpl) {
            store = s;
            break;
        }
    }
    assertThat("The system credentials provider is enabled", store, notNullValue());

    UsernamePasswordCredentialsImpl credentials = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, "secret-id", "test credentials", "bob",
                            "secret");
    store.addCredentials(Domain.global(), credentials);
    
    Fingerprint fingerprint = CredentialsProvider.getFingerprintOf(credentials);
    assertThat("No fingerprint created until first use", fingerprint, nullValue());

    JenkinsRule.WebClient wc = r.createWebClient();
    HtmlPage page = wc.goTo("credentials/store/system/domain/_/credentials/secret-id");
    assertThat("Have usage tracking reported", page.getElementById("usage"), notNullValue());
    assertThat("No fingerprint created until first use", page.getElementById("usage-missing"), notNullValue());
    assertThat("No fingerprint created until first use", page.getElementById("usage-present"), nullValue());

    FreeStyleProject job = r.createFreeStyleProject();
    // add a parameter
    job.addProperty(new ParametersDefinitionProperty(
                new CredentialsParameterDefinition(
                          "SECRET",
                          "The secret",
                          "secret-id",
                          Credentials.class.getName(),
                          false
                    )));

    r.assertBuildStatusSuccess((Future) job.scheduleBuild2(0,
                    new ParametersAction(new CredentialsParameterValue("SECRET", "secret-id", "The secret", true))));

    fingerprint = CredentialsProvider.getFingerprintOf(credentials);
    assertThat("A job that does nothing does not use parameterized credentials", fingerprint, nullValue());

    page = wc.goTo("credentials/store/system/domain/_/credentials/secret-id");
    assertThat("Have usage tracking reported", page.getElementById("usage"), notNullValue());
    assertThat("No fingerprint created until first use", page.getElementById("usage-missing"), notNullValue());
    assertThat("No fingerprint created until first use", page.getElementById("usage-present"), nullValue());

    // check that the wrapper works as expected
    job.getBuildWrappersList().add(new SecretBuildWrapper(Collections.<Binding<?>>singletonList(new UsernamePasswordBinding("AUTH", credentials.getId()))));

    r.assertBuildStatusSuccess((Future) job.scheduleBuild2(0, new ParametersAction(new CredentialsParameterValue("SECRET", "secret-id", "The secret", true))));

    fingerprint = CredentialsProvider.getFingerprintOf(credentials);
    assertThat(fingerprint, notNullValue());
    assertThat(fingerprint.getJobs(), hasItem(is(job.getFullName())));
    Fingerprint.RangeSet rangeSet = fingerprint.getRangeSet(job);
    assertThat(rangeSet, notNullValue());
    assertThat(rangeSet.includes(job.getLastBuild().getNumber()), is(true));

    page = wc.goTo("credentials/store/system/domain/_/credentials/secret-id");
    assertThat(page.getElementById("usage-missing"), nullValue());
    assertThat(page.getElementById("usage-present"), notNullValue());
    assertThat(page.getAnchorByText(job.getFullDisplayName()), notNullValue());

    // check the API
    WebResponse response = wc.goTo(
              "credentials/store/system/domain/_/credentials/secret-id/api/xml?depth=1&xpath=*/fingerprint/usage",
              "application/xml").getWebResponse();
    assertThat(response.getContentAsString(), CompareMatcher.isSimilarTo("<usage>"
              + "<name>"+ Util.xmlEscape(job.getFullName())+"</name>"
              + "<ranges>"
              + "<range>"
              + "<end>"+(job.getLastBuild().getNumber()+1)+"</end>"
              + "<start>" + job.getLastBuild().getNumber()+"</start>"
              + "</range>"
              + "</ranges>"
              + "</usage>").ignoreWhitespace().ignoreComments());
}
 
Example 15
Source File: Security1290Test.java    From configuration-as-code-plugin with MIT License 4 votes vote down vote up
private void assertRightPermissionConfigurations(String relativeUrl, JenkinsRule.WebClient adminWc, JenkinsRule.WebClient userWc) throws IOException {
    WebRequest request = new WebRequest(new URL(j.getURL() + relativeUrl), HttpMethod.GET);

    assertEquals(HttpURLConnection.HTTP_OK, adminWc.getPage(request).getWebResponse().getStatusCode());
    assertEquals(HttpURLConnection.HTTP_FORBIDDEN, userWc.getPage(request).getWebResponse().getStatusCode());
}
 
Example 16
Source File: LockableResourceRootActionSEC1361Test.java    From lockable-resources-plugin with MIT License 4 votes vote down vote up
private void checkXssWithResourceName(String resourceName) throws Exception {
  LockableResourcesManager.get().createResource(resourceName);

  j.jenkins.setSecurityRealm(j.createDummySecurityRealm());
  j.jenkins.setAuthorizationStrategy(new FullControlOnceLoggedInAuthorizationStrategy());

  JenkinsRule.WebClient wc = j.createWebClient();
  wc.login("user");

  final AtomicReference<String> lastAlertReceived = new AtomicReference<>();
  wc.setAlertHandler(
      new AlertHandler() {
        @Override
        public void handleAlert(Page page, String s) {
          lastAlertReceived.set(s);
        }
      });

  HtmlPage htmlPage = wc.goTo("lockable-resources");
  assertThat(lastAlertReceived.get(), nullValue());

  // currently only one button but perhaps in future version of the core/plugin,
  // other buttons will be added to the layout
  List<HtmlElement> allButtons = htmlPage.getDocumentElement().getElementsByTagName("button");
  assertThat(allButtons.size(), greaterThanOrEqualTo(1));

  HtmlElement reserveButton = null;
  for (HtmlElement b : allButtons) {
    String onClick = b.getAttribute("onClick");
    if (onClick != null && onClick.contains("reserve")) {
      reserveButton = b;
    }
  }
  assertThat(reserveButton, not(nullValue()));

  try {
    HtmlElementUtil.click(reserveButton);
  } catch (FailingHttpStatusCodeException e) {
    // only happen if we have a XSS, but it's managed using the AlertHandler to ensure it's a XSS
    // and not just an invalid page
  }
  assertThat(lastAlertReceived.get(), nullValue());
}
 
Example 17
Source File: DockerTraceabilityRootActionTest.java    From docker-traceability-plugin with MIT License 4 votes vote down vote up
/**
 * Checks {@link DockerEventsAction#doSubmitEvent(org.kohsuke.stapler.StaplerRequest, 
 * org.kohsuke.stapler.StaplerResponse, java.lang.String) }
 * @throws Exception test failure
 */
@Test
public void submitEvent() throws Exception {
    // Read data from resources
    String reportString = JSONSamples.submitReport.readString();
    DockerTraceabilityReport report = JSONSamples.submitReport.
            readObject(DockerTraceabilityReport.class);
    final String containerId = report.getContainer().getId();
    final String imageId = report.getImageId();
    
    // Init system data
    // TODO: replace by a helper method from the branch
    JenkinsRule.WebClient client = j.createWebClient();
    @CheckForNull DockerTraceabilityRootAction action = null;
    for (Action rootAction : j.getInstance().getActions()) {
        if (rootAction instanceof DockerTraceabilityRootAction) {
            action = (DockerTraceabilityRootAction) rootAction;
            break;
        }
    }    
    assertNotNull(action);
    
    // Prepare a run with Fingerprints and referenced facets
    createTestBuildRefFacet(imageId, "test");
    
    // Submit JSON
    action.doSubmitReport(reportString);
    
    // Ensure there's are expected fingerprints
    final DockerDeploymentFacet containerFacet = assertExistsDeploymentFacet(containerId, imageId);
    final DockerDeploymentRefFacet containerRefFacet = assertExistsDeploymentRefFacet(containerId, imageId);
    final DockerInspectImageFacet inspectImageFacet = assertExistsInspectImageFacet(imageId);
    
    // Try to call the actions method to retrieve the data
    final Page res;
    try {
        res = client.goTo("docker-traceability/rawImageInfo?id="+imageId, null);
    } catch (Exception ex) {
        ex.getMessage();
        throw new AssertionError("Cannot get a response from rawInfo page", ex);
    }
    final String responseJSON = res.getWebResponse().getContentAsString();
    ObjectMapper mapper= new ObjectMapper();
    final InspectImageResponse[] parsedData = mapper.readValue(responseJSON, InspectImageResponse[].class);
    assertEquals(1, parsedData.length); 
    InspectImageResponse apiResponse = parsedData[0];
    assertEquals(imageId, apiResponse.getId()); 
}
 
Example 18
Source File: JwtAuthenticationServiceImplTest.java    From blueocean-plugin with MIT License 2 votes vote down vote up
@Test
    public void getToken() throws Exception {
        j.jenkins.setSecurityRealm(j.createDummySecurityRealm());

        User user = User.get("alice");
        user.setFullName("Alice Cooper");
        user.addProperty(new Mailer.UserProperty("[email protected]"));

        JenkinsRule.WebClient webClient = j.createWebClient();

        webClient.login("alice");

        String token = getToken(webClient);

        Assert.assertNotNull(token);

        JsonWebStructure jsonWebStructure = JsonWebStructure.fromCompactSerialization(token);

        Assert.assertTrue(jsonWebStructure instanceof JsonWebSignature);

        JsonWebSignature jsw = (JsonWebSignature) jsonWebStructure;

        System.out.println(token);
        System.out.println(jsw.toString());


        String kid = jsw.getHeader("kid");

        Assert.assertNotNull(kid);

        Page page = webClient.goTo("jwt-auth/jwks/"+kid+"/", "application/json");

//        for(NameValuePair valuePair: page.getWebResponse().getResponseHeaders()){
//            System.out.println(valuePair);
//        }

        JSONObject jsonObject = JSONObject.fromObject(page.getWebResponse().getContentAsString());
        System.out.println(jsonObject.toString());
        RsaJsonWebKey rsaJsonWebKey = new RsaJsonWebKey(jsonObject,null);

        JwtConsumer jwtConsumer = new JwtConsumerBuilder()
            .setRequireExpirationTime() // the JWT must have an expiration time
            .setAllowedClockSkewInSeconds(30) // allow some leeway in validating time based claims to account for clock skew
            .setRequireSubject() // the JWT must have a subject claim
            .setVerificationKey(rsaJsonWebKey.getKey()) // verify the sign with the public key
            .build(); // create the JwtConsumer instance

        JwtClaims claims = jwtConsumer.processToClaims(token);
        Assert.assertEquals("alice",claims.getSubject());

        Map<String,Object> claimMap = claims.getClaimsMap();

        Map<String,Object> context = (Map<String, Object>) claimMap.get("context");
        Map<String,String> userContext = (Map<String, String>) context.get("user");
        Assert.assertEquals("alice", userContext.get("id"));
        Assert.assertEquals("Alice Cooper", userContext.get("fullName"));
        Assert.assertEquals("[email protected]", userContext.get("email"));
    }
 
Example 19
Source File: GitHubPRTriggerTest.java    From github-integration-plugin with MIT License 2 votes vote down vote up
@LocalData
@Test
public void buildButtonsPerms() throws Exception {
    j.getInstance().setNumExecutors(0);

    j.jenkins.setSecurityRealm(j.createDummySecurityRealm());
    ProjectMatrixAuthorizationStrategy auth = new ProjectMatrixAuthorizationStrategy();
    auth.add(Jenkins.READ, "alice");
    auth.add(Computer.BUILD, "alice");

    auth.add(Jenkins.ADMINISTER, "admin");

    auth.add(Jenkins.READ, "bob");
    auth.add(Computer.BUILD, "bob");

    j.jenkins.setAuthorizationStrategy(auth);

    final FreeStyleProject project =  (FreeStyleProject) j.getInstance().getItem("project");

    Map<Permission,Set<String>> perms = new HashMap<>();

    HashSet<String> users = new HashSet<>();
    users.add("alice");
    users.add("bob");

    perms.put(Item.READ, users);

    perms.put(Item.BUILD, Collections.singleton("bob"));

    project.addProperty(new AuthorizationMatrixProperty(perms));


    JenkinsRule.WebClient webClient = j.createWebClient();
    webClient = webClient.login("bob", "bob");

    HtmlPage repoPage = webClient.getPage(project, "github-pullrequest");
    HtmlForm form = repoPage.getFormByName("rebuildAllFailed");
    HtmlFormUtil.getButtonByCaption(form, "Rebuild all failed builds").click();
    HtmlPage page = (HtmlPage) submit(form);

    Queue.Item[] items = j.getInstance().getQueue().getItems();
    assertThat(items, arrayWithSize(0));
}
 
Example 20
Source File: GitHubBranchTriggerTest.java    From github-integration-plugin with MIT License 2 votes vote down vote up
@LocalData
@Test
public void buildButtonsPerms() throws Exception {
    jRule.getInstance().setNumExecutors(0);

    jRule.jenkins.setSecurityRealm(jRule.createDummySecurityRealm());
    ProjectMatrixAuthorizationStrategy auth = new ProjectMatrixAuthorizationStrategy();
    auth.add(Jenkins.READ, "alice");
    auth.add(Computer.BUILD, "alice");

    auth.add(Jenkins.ADMINISTER, "admin");

    auth.add(Jenkins.READ, "bob");
    auth.add(Computer.BUILD, "bob");

    jRule.jenkins.setAuthorizationStrategy(auth);

    final FreeStyleProject project = (FreeStyleProject) jRule.getInstance().getItem("project");

    Map<Permission, Set<String>> perms = new HashMap<>();

    HashSet<String> users = new HashSet<>();
    users.add("alice");
    users.add("bob");

    perms.put(Item.READ, users);

    perms.put(Item.BUILD, Collections.singleton("bob"));

    project.addProperty(new AuthorizationMatrixProperty(perms));


    JenkinsRule.WebClient webClient = jRule.createWebClient();
    webClient = webClient.login("bob", "bob");

    HtmlPage repoPage = webClient.getPage(project, "github-branch");
    HtmlForm form = repoPage.getFormByName("rebuildAllFailed");
    HtmlFormUtil.getButtonByCaption(form, "Rebuild all failed builds").click();
    HtmlPage page = (HtmlPage) submit(form);

    Queue.Item[] items = jRule.getInstance().getQueue().getItems();
    assertThat(items, arrayWithSize(0));

}