hudson.security.HudsonPrivateSecurityRealm Java Examples

The following examples show how to use hudson.security.HudsonPrivateSecurityRealm. 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: UserCreationListenerTest.java    From audit-log-plugin with MIT License 6 votes vote down vote up
@Issue("JENKINS-54088")
@Test
@Parameters({
        "1, alice, alicePassword",
        "1, bob, bobPassword",
        "1, charlie, charliePassword",
        "1, debbie, debbiePassword"
})
public void testUserCreationFromRealm(int expectedCount, String username, String password) throws Exception {
    assertEventCount(app.getEvents(), 0);

    HudsonPrivateSecurityRealm realm = new HudsonPrivateSecurityRealm(false, false, null);
    j.jenkins.setSecurityRealm(realm);

    User user = realm.createAccount(username, password);
    user.save();

    assertEventCount(app.getEvents(), expectedCount);
}
 
Example #2
Source File: UserCreationListenerTest.java    From audit-log-plugin with MIT License 6 votes vote down vote up
@Before
public void setup() throws Exception {
    // user ID conformance check
    Field field = HudsonPrivateSecurityRealm.class.getDeclaredField("ID_REGEX");
    field.setAccessible(true);
    field.set(null, null);

    // credentials of four Jenkins accounts
    USERS.put("alice", "alicePassword");
    USERS.put("bob", "bobPassword");
    USERS.put("charlie", "charliePassword");
    USERS.put("debbie", "debbiePassword");

    client = j.createWebClient();
    logout(client);

    app = ListAppender.getListAppender("AuditList").clear();
}
 
Example #3
Source File: PipelineApiTest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Test
public void PipelineSecureWithAnonymousUserPermissionTest() throws IOException {
    j.jenkins.setSecurityRealm(new HudsonPrivateSecurityRealm(false));
    j.jenkins.setAuthorizationStrategy(new LegacyAuthorizationStrategy());

    MockFolder folder = j.createFolder("folder1");

    Project p = folder.createProject(FreeStyleProject.class, "test1");

    Map response = get("/organizations/jenkins/pipelines/folder1/pipelines/test1");
    validatePipeline(p, response);

    Map<String,Boolean> permissions = (Map<String, Boolean>) response.get("permissions");
    Assert.assertFalse(permissions.get("create"));
    Assert.assertFalse(permissions.get("start"));
    Assert.assertFalse(permissions.get("stop"));
    assertTrue(permissions.get("read"));

    response = get("/organizations/jenkins/pipelines/folder1/");

    permissions = (Map<String, Boolean>) response.get("permissions");
    Assert.assertFalse(permissions.get("create"));
    Assert.assertFalse(permissions.get("start"));
    Assert.assertFalse(permissions.get("stop"));
    assertTrue(permissions.get("read"));
}
 
Example #4
Source File: ProfileApiTest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Test
public void shouldFailForUnauthorizedUser() throws IOException, UnirestException {
    HudsonPrivateSecurityRealm realm = new HudsonPrivateSecurityRealm(false);
    realm.createAccount("alice","alice");
    realm.createAccount("bob","bob");
    j.jenkins.setSecurityRealm(realm);

    GlobalMatrixAuthorizationStrategy as = new GlobalMatrixAuthorizationStrategy();
    j.jenkins.setAuthorizationStrategy(as);
    as.add(Hudson.READ,"alice");

    Map resp = new RequestBuilder(baseUrl)
            .status(403)
            .auth("bob", "bob")
            .get("/users/")
            .build(Map.class);
    assertEquals(403, resp.get("code"));
}
 
Example #5
Source File: HudsonPrivateSecurityRealmConfigurator.java    From configuration-as-code-plugin with MIT License 6 votes vote down vote up
private static Collection<UserWithPassword> getter(HudsonPrivateSecurityRealm target) {
    return target.getAllUsers().stream()
            .map(u -> {
                UserWithPassword user = new UserWithPassword(u.getId(), null);
                user.setName(u.getFullName());
                user.setDescription(u.getDescription());
                List<UserProperty> properties = u.getAllProperties()
                    .stream()
                    .filter(userProperty -> !userProperty.getClass().getName().equals("com.cloudbees.plugins.credentials.UserCredentialsProvider$UserCredentialsProperty"))
                    .collect(Collectors.toList());
                user.setProperties(properties);

                return user;
            })
            .collect(Collectors.toList());
}
 
Example #6
Source File: ProfileApiTest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Test
public void shouldSucceedForAnonymousRead() throws IOException {
    HudsonPrivateSecurityRealm realm = new HudsonPrivateSecurityRealm(false);
    realm.createAccount("alice","alice");
    j.jenkins.setSecurityRealm(realm);

    GlobalMatrixAuthorizationStrategy as = new GlobalMatrixAuthorizationStrategy();
    j.jenkins.setAuthorizationStrategy(as);
    as.add(Hudson.READ,"anonymous");

    List resp = new RequestBuilder(baseUrl)
            .status(200)
            .get("/users/")
            .build(List.class);
    assertEquals(1, resp.size());
}
 
Example #7
Source File: HudsonPrivateSecurityRealmConfigurator.java    From configuration-as-code-plugin with MIT License 6 votes vote down vote up
private static User createAccount(HudsonPrivateSecurityRealm target, UserWithPassword user)
    throws IOException {
    User updatedUser;
    if (StringUtils.isNotBlank(user.password)) {
        if (StringUtils.startsWith(user.password, HASHED_PASSWORD_PREFIX)) {
            try {
                updatedUser = target
                    .createAccountWithHashedPassword(user.id, user.password);
            } catch (IllegalArgumentException | IOException e) {
                logger.log(Level.WARNING,
                    "Failed to create user with presumed hashed password", e);
                // fallback, just create the account as is
                updatedUser = target.createAccount(user.id, user.password);
            }
        } else {
            updatedUser = target.createAccount(user.id, user.password);
        }
    } else {
        updatedUser = User.getById(user.id, true);
    }
    return updatedUser;
}
 
Example #8
Source File: ProfileApiTest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Test
public void shouldFailForAnonymousRead() throws IOException {
    HudsonPrivateSecurityRealm realm = new HudsonPrivateSecurityRealm(false);
    realm.createAccount("alice","alice");
    j.jenkins.setSecurityRealm(realm);

    GlobalMatrixAuthorizationStrategy as = new GlobalMatrixAuthorizationStrategy();
    j.jenkins.setAuthorizationStrategy(as);
    as.add(Hudson.READ,"alice");

    Map resp = new RequestBuilder(baseUrl)
            .status(403)
            .get("/users/")
            .build(Map.class);
    assertEquals(403, resp.get("code"));
}
 
Example #9
Source File: MultiBranchTest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Test
public void testMultiBranchPipelineBranchSecurePermissions() throws IOException, ExecutionException, InterruptedException {
    j.jenkins.setSecurityRealm(new HudsonPrivateSecurityRealm(false));
    j.jenkins.setAuthorizationStrategy(new LegacyAuthorizationStrategy());

    MockFolder folder1 = j.createFolder("folder1");
    WorkflowMultiBranchProject mp = folder1.createProject(WorkflowMultiBranchProject.class, "p");

    mp.getSourcesList().add(new BranchSource(new GitSCMSource(null, sampleRepo.toString(), "", "*", "", false),
        new DefaultBranchPropertyStrategy(new BranchProperty[0])));
    for (SCMSource source : mp.getSCMSources()) {
        assertEquals(mp, source.getOwner());
    }

    mp.scheduleBuild2(0).getFuture().get();


    Map r = get("/organizations/jenkins/pipelines/folder1/pipelines/p/");


    Map<String,Boolean> permissions = (Map<String, Boolean>) r.get("permissions");
    Assert.assertFalse(permissions.get("create"));
    Assert.assertTrue(permissions.get("read"));
    Assert.assertFalse(permissions.get("start"));
    Assert.assertFalse(permissions.get("stop"));



    r = get("/organizations/jenkins/pipelines/folder1/pipelines/p/branches/master/");

    permissions = (Map<String, Boolean>) r.get("permissions");
    Assert.assertFalse(permissions.get("create"));
    Assert.assertFalse(permissions.get("start"));
    Assert.assertFalse(permissions.get("stop"));
    Assert.assertTrue(permissions.get("read"));
}
 
Example #10
Source File: ArtifactsSecurity564.java    From blueocean-plugin with MIT License 5 votes vote down vote up
/**
 * Uses matrix-auth to provide artifacts permission.
 *
 * If hudson.security.ArtifactsPermission is set then the user must have Run.ARTIFACTS set.
 *
 * @throws Exception
 */
@Issue("SECURITY-564")
@Test
public void testArtifactsWithPermissions() throws Exception {
    String JOB_NAME = "artifactPermissions";
    String artifactPath = "a/b/c";
    HudsonPrivateSecurityRealm realm = new HudsonPrivateSecurityRealm(false);
    realm.createAccount("alice","alice");
    realm.createAccount("bob","bob");
    j.jenkins.setSecurityRealm(realm);

    GlobalMatrixAuthorizationStrategy as = new GlobalMatrixAuthorizationStrategy();
    j.jenkins.setAuthorizationStrategy(as);
    as.add(Hudson.READ,"alice");
    as.add(Item.READ,"alice");
    as.add(Run.ARTIFACTS,"alice");
    as.add(Hudson.READ,"bob");
    as.add(Item.READ,"bob");

    FreeStyleProject p = j.createFreeStyleProject(JOB_NAME);
    p.getBuildersList().add(new ArtifactBuilder(artifactPath, 100));
    p.getPublishersList().add(new ArtifactArchiver("**/*"));
    Run r = p.scheduleBuild2(0).waitForStart();

    r = j.waitForCompletion(r);

    List artifacts = request().authAlice().get("/organizations/jenkins/pipelines/"+JOB_NAME+"/runs/"+r.getId()+"/artifacts").build(List.class);

    Assert.assertEquals(100, artifacts.size());
    Assert.assertEquals(0, ((Map) artifacts.get(0)).get("size"));
    Assert.assertEquals(artifactPath + "/0.txt", ((Map) artifacts.get(0)).get("path"));
    Assert.assertEquals("/job/artifactPermissions/1/artifact/"+ artifactPath +"/0.txt", ((Map) artifacts.get(0)).get("url"));

    List artifactsBob = request().auth("bob", "bob").get("/organizations/jenkins/pipelines/"+JOB_NAME+"/runs/"+r.getId()+"/artifacts").build(List.class);

    Assert.assertEquals(0, artifactsBob.size());
}
 
Example #11
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 #12
Source File: HudsonPrivateSecurityRealmConfiguratorTest.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@Test
@ConfiguredWithReadme("embedded-userdatabase/README.md#1")
public void config_local_security_and_hashed_admin_user() {
    final User admin = User.getById("hashedadmin", false);
    assertNotNull(admin);
    final HudsonPrivateSecurityRealm.Details details = admin.getProperty(HudsonPrivateSecurityRealm.Details.class);
    assertTrue(details.isPasswordCorrect("password"));
}
 
Example #13
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 #14
Source File: HudsonPrivateSecurityRealmConfigurator.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
private static void setter(HudsonPrivateSecurityRealm target, Collection<UserWithPassword> value) throws IOException {
    for (UserWithPassword user : value) {
        User updatedUser = createAccount(target, user);
        updatedUser.setFullName(user.name);
        updatedUser.setDescription(user.description);
        if (user.getProperties() != null) {
            for (UserProperty property : user.getProperties()) {
                updatedUser.addProperty(property);
            }
        }
    }
}
 
Example #15
Source File: HudsonPrivateSecurityRealmConfigurator.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@CheckForNull
@Override
public CNode describe(HudsonPrivateSecurityRealm instance, ConfigurationContext context)
    throws Exception {
    // allow disabling exporting users if an instance has too many
    if (System.getProperty("io.jenkins.plugins.casc.core.HudsonPrivateSecurityRealmConfigurator.exportUsers", "true").equals("true")) {
        return super.describe(instance, context);
    }
    return null;
}
 
Example #16
Source File: UserCreationListenerTest.java    From audit-log-plugin with MIT License 5 votes vote down vote up
@Issue("JENKINS-54088")
@Test
public void testUserCreationAndLoginFromRealm() throws Exception {
    assertEventCount(app.getEvents(), 0);

    HudsonPrivateSecurityRealm realm = new HudsonPrivateSecurityRealm(false, false, null);
    j.jenkins.setSecurityRealm(realm);

    User u1 = realm.createAccount("charlie", USERS.get("charlie"));
    u1.save();
    client.login("charlie", USERS.get("charlie"));

    // verify the audit event log messages as user creation and user login events
    StructuredDataMessage logMessageOne = (StructuredDataMessage) app.getEvents().get(0).getMessage();
    StructuredDataMessage logMessageTwo = (StructuredDataMessage) app.getEvents().get(1).getMessage();

    assertTrue(logMessageOne.toString().contains("createUser"));
    assertTrue(logMessageTwo.toString().contains("login"));

    // verify a login event occurred
    client.executeOnServer(() -> {
        Authentication a = Jenkins.getAuthentication();
        assertEquals("charlie", a.getName());

        return null;
    });

    assertEventCount(app.getEvents(), 2);
}
 
Example #17
Source File: UserCreationListenerTest.java    From audit-log-plugin with MIT License 5 votes vote down vote up
@Issue("JENKINS-54088")
@Test
public void testUserCreationFromSignUp() throws Exception {
    assertEventCount(app.getEvents(), 0);

    HudsonPrivateSecurityRealm realm = new HudsonPrivateSecurityRealm(true, false, null);
    j.jenkins.setSecurityRealm(realm);

    SignupPage signup = new SignupPage(client.goTo("signup"));
    signup.enterUsername("debbie");
    signup.enterPassword(USERS.get("debbie"));
    signup.enterFullName("Debbie User");
    HtmlPage success = signup.submit(j);

    // user creation via a jenkins signup also automatically logs the user in
    assertEventCount(app.getEvents(), 2);

    // verify a login event occurred
    client.executeOnServer(() -> {
        Authentication a = Jenkins.getAuthentication();
        assertEquals("debbie", a.getName());

        return null;
    });

    assertThat(success.getElementById("main-panel").getTextContent(), containsString("Success"));
    assertEquals("Debbie User", realm.getUser("debbie").getDisplayName());
}
 
Example #18
Source File: HudsonPrivateSecurityRealmConfigurator.java    From configuration-as-code-plugin with MIT License 4 votes vote down vote up
public HudsonPrivateSecurityRealmConfigurator() {
    super(HudsonPrivateSecurityRealm.class);
}