hudson.security.FullControlOnceLoggedInAuthorizationStrategy Java Examples

The following examples show how to use hudson.security.FullControlOnceLoggedInAuthorizationStrategy. 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: HudsonPrivateSecurityRealmConfiguratorTest.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@Test
@ConfiguredWithReadme("embedded-userdatabase/README.md#0")
public void configure_local_security_and_admin_user() throws Exception {
    final Jenkins jenkins = Jenkins.get();
    final HudsonPrivateSecurityRealm securityRealm = (HudsonPrivateSecurityRealm) jenkins.getSecurityRealm();
    assertFalse(securityRealm.allowsSignup());
    final User admin = User.getById("admin", false);
    assertNotNull(admin);
    final HudsonPrivateSecurityRealm.Details details = admin.getProperty(HudsonPrivateSecurityRealm.Details.class);
    assertTrue(details.isPasswordCorrect("somethingsecret"));

    final FullControlOnceLoggedInAuthorizationStrategy authorizationStrategy = (FullControlOnceLoggedInAuthorizationStrategy) jenkins.getAuthorizationStrategy();
    assertTrue(authorizationStrategy.isAllowAnonymousRead());
}
 
Example #2
Source File: JenkinsConfiguratorTest.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@Test
@ConfiguredWithCode("HeteroDescribable.yml")
public void jenkins_abstract_describable_attributes() throws Exception {
    final Jenkins jenkins = Jenkins.get();
    assertTrue(jenkins.getSecurityRealm() instanceof HudsonPrivateSecurityRealm);
    assertTrue(jenkins.getAuthorizationStrategy() instanceof FullControlOnceLoggedInAuthorizationStrategy);
    assertFalse(((FullControlOnceLoggedInAuthorizationStrategy) jenkins.getAuthorizationStrategy()).isAllowAnonymousRead());
}
 
Example #3
Source File: JenkinsDemoTest.java    From configuration-as-code-plugin with MIT License 4 votes vote down vote up
@Test
@ConfiguredWithCode("jenkins/jenkins.yaml")
public void configure_demo_yaml() throws Exception {
    final Jenkins jenkins = Jenkins.get();
    assertEquals("Jenkins configured automatically by Jenkins Configuration as Code plugin\n\n", jenkins.getSystemMessage());
    assertEquals(5, jenkins.getNumExecutors());
    assertEquals(2, jenkins.getScmCheckoutRetryCount());
    assertEquals(Mode.NORMAL, jenkins.getMode());
    assertEquals("https://ci.example.com/", jenkins.getRootUrl());

    final FullControlOnceLoggedInAuthorizationStrategy strategy = (FullControlOnceLoggedInAuthorizationStrategy) jenkins.getAuthorizationStrategy();
    assertFalse(strategy.isAllowAnonymousRead());

    final DockerCloud docker = DockerCloud.getCloudByName("docker");
    assertNotNull(docker);
    assertNotNull(docker.getDockerApi());
    assertNotNull(docker.getDockerApi().getDockerHost());
    assertEquals("unix:///var/run/docker.sock", docker.getDockerApi().getDockerHost().getUri());

    final GitTool.DescriptorImpl gitTool = (GitTool.DescriptorImpl) jenkins.getDescriptor(GitTool.class);
    assertEquals(1, gitTool.getInstallations().length);

    assertEquals(1, GlobalLibraries.get().getLibraries().size());
    final LibraryConfiguration library = GlobalLibraries.get().getLibraries().get(0);
    assertEquals("awesome-lib", library.getName());

    final Mailer.DescriptorImpl descriptor = (Mailer.DescriptorImpl) jenkins.getDescriptor(Mailer.class);
    assertEquals("4441", descriptor.getSmtpPort());
    assertEquals("[email protected]", descriptor.getReplyToAddress());
    assertEquals("smtp.acme.org", descriptor.getSmtpHost() );

    final ArtifactoryBuilder.DescriptorImpl artifactory = (ArtifactoryBuilder.DescriptorImpl) jenkins.getDescriptor(ArtifactoryBuilder.class);
    assertTrue(artifactory.getUseCredentialsPlugin());

    final List<ArtifactoryServer> actifactoryServers = artifactory.getArtifactoryServers();
    assertThat(actifactoryServers, hasSize(1));
    assertThat(actifactoryServers.get(0).getName(), is(equalTo("artifactory")));
    assertThat(actifactoryServers.get(0).getUrl(), is(equalTo("http://acme.com/artifactory")));
    assertThat(actifactoryServers.get(0).getResolverCredentialsConfig().getUsername(), is(equalTo("artifactory_user")));
    assertThat(actifactoryServers.get(0).getResolverCredentialsConfig().getPassword(), is(equalTo("password123")));
}
 
Example #4
Source File: BlueOceanConfigStatePreloader.java    From blueocean-plugin with MIT License 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public String getStateJson() {
    StringWriter writer = new StringWriter();
    Jenkins jenkins = Jenkins.getInstance();
    VersionNumber versionNumber = Jenkins.getVersion();
    String version = versionNumber != null ? versionNumber.toString() : Jenkins.VERSION;

    AuthorizationStrategy authorizationStrategy = jenkins.getAuthorizationStrategy();
    boolean allowAnonymousRead = true;
    if(authorizationStrategy instanceof FullControlOnceLoggedInAuthorizationStrategy){
        allowAnonymousRead = ((FullControlOnceLoggedInAuthorizationStrategy) authorizationStrategy).isAllowAnonymousRead();
    }

    String jwtTokenEndpointHostUrl = Jenkins.getInstance().getRootUrl();
    JwtTokenServiceEndpoint jwtTokenServiceEndpoint = JwtTokenServiceEndpoint.first();
    if(jwtTokenServiceEndpoint != null){
        jwtTokenEndpointHostUrl = jwtTokenServiceEndpoint.getHostUrl();
    }
    addFeatures(new JSONBuilder(writer)
        .object()
            .key("version").value(getBlueOceanPluginVersion())
            .key("jenkinsConfig")
            .object()
                .key("analytics").value(Analytics.isAnalyticsEnabled())
                .key("version").value(version)
                .key("security")
                .object()
                    .key("enabled").value(jenkins.isUseSecurity())
                    .key("loginUrl").value(jenkins.getSecurityRealm() == SecurityRealm.NO_AUTHENTICATION ? null : jenkins.getSecurityRealm().getLoginUrl())
                    .key("authorizationStrategy").object()
                        .key("allowAnonymousRead").value(allowAnonymousRead)
                    .endObject()
                    .key("enableJWT").value(BlueOceanConfigProperties.BLUEOCEAN_FEATURE_JWT_AUTHENTICATION)
                    .key("jwtServiceHostUrl").value(jwtTokenEndpointHostUrl)
                .endObject()
            .endObject()
            ) // addFeatures here
        .endObject();

    return writer.toString();
}
 
Example #5
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 #6
Source File: BindingStepTest.java    From credentials-binding-plugin with MIT License 4 votes vote down vote up
@Issue("JENKINS-30326")
@Test
public void testGlobalBindingWithAuthorization() {
    story.addStep(new Statement() {
        @SuppressWarnings("deprecation") // using TestExtension would be better, as would calling ScriptApproval.preapprove
        @Override public void evaluate() throws Throwable {
            // configure security
            story.j.jenkins.setSecurityRealm(story.j.createDummySecurityRealm());
            story.j.jenkins.setAuthorizationStrategy(new FullControlOnceLoggedInAuthorizationStrategy());
            // create the user.
            User.get("dummy", true);
            
            // enable the run as user strategy for the AuthorizeProject plugin
            Map<String, Boolean> strategies = new HashMap<String, Boolean>();
            strategies.put(story.j.jenkins.getDescriptor(SpecificUsersAuthorizationStrategy.class).getId(), true);
            QueueItemAuthenticatorConfiguration.get().getAuthenticators().add(new ProjectQueueItemAuthenticator(strategies));

            // blanket whitelist all methods (easier than whitelisting Jenkins.getAuthentication)
            story.j.jenkins.getExtensionList(Whitelist.class).add(new BlanketWhitelist());

            String credentialsId = "creds";
            String secret = "s3cr3t";
            CredentialsProvider.lookupStores(story.j.jenkins).iterator().next().addCredentials(Domain.global(), new StringCredentialsImpl(CredentialsScope.GLOBAL, credentialsId, "sample", Secret.fromString(secret)));
            WorkflowJob p = story.j.jenkins.createProject(WorkflowJob.class, "p");

            p.setDefinition(new CpsFlowDefinition(""
                    + "node {\n"
                    + "  def authentication = Jenkins.getAuthentication()\n"
                    + "  echo \"running as user: $authentication.principal\"\n"
                    + "  withCredentials([string(credentialsId: '" + credentialsId + "', variable: 'SECRET')]) {\n"
                    + "    writeFile file:'test', text: \"$env.SECRET\"\n"
                    + "    def content = readFile 'test'\n"
                    + "    if (\"$content\" != \"" + secret + "\") {\n"
                    + "      error 'The credential was not bound into the workflow correctly'\n"
                    + "    }\n"
                    + "  }\n"
                    + "}", true));
            // run the job as a specific user
            SpecificUsersAuthorizationStrategy strategy = new SpecificUsersAuthorizationStrategy("dummy");
            strategy.setDontRestrictJobConfiguration(true);
            p.addProperty(new AuthorizeProjectProperty(strategy));

            // the build will fail if we can not locate the credentials
            WorkflowRun b = story.j.assertBuildStatusSuccess(p.scheduleBuild2(0).get());
            // make sure this was actually run as a user and not system
            story.j.assertLogContains("running as user: dummy", b);
        }
    });
}