hudson.security.AuthorizationStrategy Java Examples

The following examples show how to use hudson.security.AuthorizationStrategy. 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: FolderAuthorizationStrategyAPITest.java    From folder-auth-plugin with MIT License 6 votes vote down vote up
@Test
public void removeSidFromAgentRole() {
    String sid = "user1";
    AgentRole role = new AgentRole("bar", wrapPermissions(Item.READ), singleton("agentBar"));
    assertEquals(0, role.getSids().size());
    FolderAuthorizationStrategyAPI.addAgentRole(role);
    FolderAuthorizationStrategyAPI.assignSidToAgentRole(sid, "bar");
    FolderAuthorizationStrategyAPI.removeSidFromAgentRole(sid, "bar");

    AuthorizationStrategy a = j.jenkins.getAuthorizationStrategy();
    assertTrue(a instanceof FolderBasedAuthorizationStrategy);
    FolderBasedAuthorizationStrategy strategy = (FolderBasedAuthorizationStrategy) a;
    AgentRole updatedRole = strategy.getAgentRoles().stream().filter(r -> r.getName().equals("bar"))
                                .findAny().orElseThrow(() -> new RuntimeException("The created role should exist"));
    assertFalse(updatedRole.getSids().contains(sid));
}
 
Example #2
Source File: FolderAuthorizationStrategyAPITest.java    From folder-auth-plugin with MIT License 6 votes vote down vote up
@Test
public void removeSidFromFolderRole() {
    String sid = "user1";
    FolderRole role = new FolderRole("foo", wrapPermissions(Item.READ), singleton("folderFoo"));
    assertEquals(0, role.getSids().size());
    FolderAuthorizationStrategyAPI.addFolderRole(role);
    FolderAuthorizationStrategyAPI.assignSidToFolderRole(sid, "foo");
    FolderAuthorizationStrategyAPI.removeSidFromFolderRole(sid, "foo");

    AuthorizationStrategy a = j.jenkins.getAuthorizationStrategy();
    assertTrue(a instanceof FolderBasedAuthorizationStrategy);
    FolderBasedAuthorizationStrategy strategy = (FolderBasedAuthorizationStrategy) a;
    FolderRole updatedRole = strategy.getFolderRoles().stream().filter(r -> r.getName().equals("foo"))
                                 .findAny().orElseThrow(() -> new RuntimeException("The created role should exist"));
    assertFalse(updatedRole.getSids().contains(sid));
}
 
Example #3
Source File: FolderBasedAuthorizationStrategy.java    From folder-auth-plugin with MIT License 6 votes vote down vote up
@Nonnull
@Override
public FolderBasedAuthorizationStrategy newInstance(@Nullable StaplerRequest req, @Nonnull JSONObject formData) {
    AuthorizationStrategy strategy = Jenkins.get().getAuthorizationStrategy();
    if (strategy instanceof FolderBasedAuthorizationStrategy) {
        // this action was invoked from the 'Configure Global Security' page when the
        // old strategy was FolderBasedAuthorizationStrategy; return it back as formData would be empty
        return (FolderBasedAuthorizationStrategy) strategy;
    } else {
        // when this AuthorizationStrategy is selected for the first time, this makes the current
        // user admin (give all permissions) and prevents him/her from getting access denied.
        // The same thing happens in Role Strategy plugin. See RoleBasedStrategy.DESCRIPTOR.newInstance()

        HashSet<PermissionGroup> groups = new HashSet<>(PermissionGroup.getAll());
        groups.remove(PermissionGroup.get(Permission.class));
        Set<PermissionWrapper> adminPermissions = PermissionWrapper.wrapPermissions(
            FolderAuthorizationStrategyManagementLink.getSafePermissions(groups));

        GlobalRole adminRole = new GlobalRole(ADMIN_ROLE_NAME, adminPermissions,
            Collections.singleton(new PrincipalSid(Jenkins.getAuthentication()).getPrincipal()));

        return new FolderBasedAuthorizationStrategy(Collections.singleton(adminRole), Collections.emptySet(),
            Collections.emptySet());
    }
}
 
Example #4
Source File: FolderAuthorizationStrategyAPITest.java    From folder-auth-plugin with MIT License 6 votes vote down vote up
@Test
public void removeSidFromGlobalRole() {
    AuthorizationStrategy a = j.jenkins.getAuthorizationStrategy();
    assertTrue(a instanceof FolderBasedAuthorizationStrategy);
    final String adminRoleName = "admin";
    FolderAuthorizationStrategyAPI.assignSidToGlobalRole("user1", adminRoleName);
    FolderAuthorizationStrategyAPI.removeSidFromGlobalRole("user1", adminRoleName);

    // a new authorization strategy should have been set
    AuthorizationStrategy b = j.jenkins.getAuthorizationStrategy();
    assertTrue(b instanceof FolderBasedAuthorizationStrategy);
    assertNotSame("A new instance of FolderBasedAuthorizationStrategy should have been set.", a, b);
    FolderBasedAuthorizationStrategy newStrategy = (FolderBasedAuthorizationStrategy) b;
    GlobalRole role = newStrategy.getGlobalRoles().stream().filter(r -> r.getName().equals(adminRoleName))
                          .findAny().orElseThrow(() -> new RuntimeException("The admin role should exist"));
    assertFalse(role.getSids().contains("user1"));
}
 
Example #5
Source File: FolderAuthorizationStrategyAPITest.java    From folder-auth-plugin with MIT License 6 votes vote down vote up
@Test
public void assignSidToFolderRole() {
    String sid = "user1";
    FolderRole role = new FolderRole("foo", wrapPermissions(Item.READ), singleton("folderFoo"));
    assertEquals(0, role.getSids().size());
    FolderAuthorizationStrategyAPI.addFolderRole(role);
    FolderAuthorizationStrategyAPI.assignSidToFolderRole(sid, "foo");


    AuthorizationStrategy a = j.jenkins.getAuthorizationStrategy();
    assertTrue(a instanceof FolderBasedAuthorizationStrategy);
    FolderBasedAuthorizationStrategy strategy = (FolderBasedAuthorizationStrategy) a;
    FolderRole updatedRole = strategy.getFolderRoles().stream().filter(r -> r.getName().equals("foo"))
                                 .findAny().orElseThrow(() -> new RuntimeException("The created role should exist"));
    assertTrue(updatedRole.getSids().contains(sid));
}
 
Example #6
Source File: FolderAuthorizationStrategyManagementLink.java    From folder-auth-plugin with MIT License 5 votes vote down vote up
/**
 * Returns the {@link FolderRole}s used by the {@link FolderBasedAuthorizationStrategy}.
 *
 * @return the {@link FolderRole}s used by the {@link FolderBasedAuthorizationStrategy}
 * @throws IllegalStateException when {@link Jenkins#getAuthorizationStrategy()} is
 *                               not {@link FolderBasedAuthorizationStrategy}
 */
@Nonnull
@Restricted(NoExternalUse.class)
@SuppressWarnings("unused") // used by index.jelly
public SortedSet<FolderRole> getFolderRoles() {
    AuthorizationStrategy strategy = Jenkins.get().getAuthorizationStrategy();
    if (strategy instanceof FolderBasedAuthorizationStrategy) {
        return new TreeSet<>(((FolderBasedAuthorizationStrategy) strategy).getFolderRoles());
    } else {
        throw new IllegalStateException(Messages.FolderBasedAuthorizationStrategy_NotCurrentStrategy());
    }
}
 
Example #7
Source File: RoleStrategyTest.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@Test
@Issue("Issue #214")
@ConfiguredWithCode("RoleStrategy2.yml")
public void shouldHandleNullItemsAndAgentsCorrectly() throws Exception {
    AuthorizationStrategy s = j.jenkins.getAuthorizationStrategy();
    assertThat("Authorization Strategy has been read incorrectly",
        s, instanceOf(RoleBasedAuthorizationStrategy.class));
    RoleBasedAuthorizationStrategy rbas = (RoleBasedAuthorizationStrategy) s;

    Map<Role, Set<String>> globalRoles = rbas.getGrantedRoles(RoleBasedAuthorizationStrategy.GLOBAL);
    assertThat(globalRoles.size(), equalTo(2));
}
 
Example #8
Source File: FolderAuthorizationStrategyAPITest.java    From folder-auth-plugin with MIT License 5 votes vote down vote up
@Test
public void assignSidToAgentRole() {
    String sid = "user1";
    AgentRole role = new AgentRole("bar", wrapPermissions(Item.READ), singleton("agentBar"));
    assertEquals(0, role.getSids().size());
    FolderAuthorizationStrategyAPI.addAgentRole(role);
    FolderAuthorizationStrategyAPI.assignSidToAgentRole(sid, "bar");

    AuthorizationStrategy a = j.jenkins.getAuthorizationStrategy();
    assertTrue(a instanceof FolderBasedAuthorizationStrategy);
    FolderBasedAuthorizationStrategy strategy = (FolderBasedAuthorizationStrategy) a;
    AgentRole updatedRole = strategy.getAgentRoles().stream().filter(r -> r.getName().equals("bar"))
                                .findAny().orElseThrow(() -> new RuntimeException("The created role should exist"));
    assertTrue(updatedRole.getSids().contains(sid));
}
 
Example #9
Source File: FolderAuthorizationStrategyAPITest.java    From folder-auth-plugin with MIT License 5 votes vote down vote up
@Test
public void addAgentRole() {
    AgentRole role = new AgentRole("readEverything", wrapPermissions(Jenkins.READ),
        singleton("agent1"), singleton("user1"));
    FolderAuthorizationStrategyAPI.addAgentRole(role);
    AuthorizationStrategy a = j.jenkins.getAuthorizationStrategy();
    assertTrue(a instanceof FolderBasedAuthorizationStrategy);
    FolderBasedAuthorizationStrategy strategy = (FolderBasedAuthorizationStrategy) a;
    assertTrue(strategy.getAgentRoles().contains(role));
}
 
Example #10
Source File: FolderAuthorizationStrategyAPITest.java    From folder-auth-plugin with MIT License 5 votes vote down vote up
@Test
public void addFolderRole() {
    FolderRole role = new FolderRole("readEverything", wrapPermissions(Jenkins.READ),
        singleton("folder1"), singleton("user1"));
    FolderAuthorizationStrategyAPI.addFolderRole(role);
    AuthorizationStrategy a = j.jenkins.getAuthorizationStrategy();
    assertTrue(a instanceof FolderBasedAuthorizationStrategy);
    FolderBasedAuthorizationStrategy strategy = (FolderBasedAuthorizationStrategy) a;
    assertTrue(strategy.getFolderRoles().contains(role));
}
 
Example #11
Source File: FolderAuthorizationStrategyAPITest.java    From folder-auth-plugin with MIT License 5 votes vote down vote up
@Test
public void addGlobalRole() {
    GlobalRole readRole = new GlobalRole("readEverything", wrapPermissions(Jenkins.READ), singleton("user1"));
    FolderAuthorizationStrategyAPI.addGlobalRole(readRole);
    AuthorizationStrategy a = j.jenkins.getAuthorizationStrategy();
    assertTrue(a instanceof FolderBasedAuthorizationStrategy);
    FolderBasedAuthorizationStrategy strategy = (FolderBasedAuthorizationStrategy) a;
    assertTrue(strategy.getGlobalRoles().contains(readRole));
}
 
Example #12
Source File: RestartSurvivabilityTest.java    From folder-auth-plugin with MIT License 5 votes vote down vote up
private void checkConfiguration() {
    Jenkins jenkins = Jenkins.get();
    try (ACLContext ignored = ACL.as(User.getById("admin", true))) {
        assertTrue(jenkins.hasPermission(Jenkins.ADMINISTER));
    }

    try (ACLContext ignored = ACL.as(User.getById("user1", true))) {
        Folder folder = (Folder) jenkins.getItem("folder");
        assertNotNull(folder);
        assertTrue(jenkins.hasPermission(Jenkins.READ));
        assertTrue(folder.hasPermission(Item.READ));
        assertFalse(folder.hasPermission(Item.CONFIGURE));
        assertFalse(jenkins.hasPermission(Jenkins.ADMINISTER));

        Computer computer = jenkins.getComputer("foo");
        assertNotNull(computer);
        assertTrue(computer.hasPermission(Computer.CONFIGURE));
        assertFalse(computer.hasPermission(Computer.DELETE));
    }

    AuthorizationStrategy a = Jenkins.get().getAuthorizationStrategy();
    assertTrue(a instanceof FolderBasedAuthorizationStrategy);
    FolderBasedAuthorizationStrategy strategy = (FolderBasedAuthorizationStrategy) a;
    assertEquals(strategy.getGlobalRoles().size(), 2);
    assertEquals(strategy.getFolderRoles().size(), 1);
    assertEquals(strategy.getAgentRoles().size(), 1);
}
 
Example #13
Source File: ConfigurationWithEmptyFolderRolesTest.java    From folder-auth-plugin with MIT License 5 votes vote down vote up
@Test
@ConfiguredWithCode("config2.yml")
public void shouldNotThrowErrorWithEmptyFolderRoles() {
    AuthorizationStrategy authorizationStrategy = j.jenkins.getAuthorizationStrategy();
    assertTrue(authorizationStrategy instanceof FolderBasedAuthorizationStrategy);
    FolderBasedAuthorizationStrategy strategy = (FolderBasedAuthorizationStrategy) authorizationStrategy;
    assertEquals(0, strategy.getFolderRoles().size());
    assertEquals(0, strategy.getAgentRoles().size());
    assertEquals(2, strategy.getGlobalRoles().size());
}
 
Example #14
Source File: FolderAuthorizationStrategyManagementLink.java    From folder-auth-plugin with MIT License 5 votes vote down vote up
@Nonnull
@Restricted(NoExternalUse.class)
@SuppressWarnings("unused") // used by index.jelly
public SortedSet<AgentRole> getAgentRoles() {
    AuthorizationStrategy strategy = Jenkins.get().getAuthorizationStrategy();
    if (strategy instanceof FolderBasedAuthorizationStrategy) {
        return new TreeSet<>(((FolderBasedAuthorizationStrategy) strategy).getAgentRoles());
    } else {
        throw new IllegalStateException(Messages.FolderBasedAuthorizationStrategy_NotCurrentStrategy());
    }
}
 
Example #15
Source File: FolderAuthorizationStrategyManagementLink.java    From folder-auth-plugin with MIT License 5 votes vote down vote up
@Nonnull
@Restricted(NoExternalUse.class)
@SuppressWarnings("unused") // used by index.jelly
public SortedSet<GlobalRole> getGlobalRoles() {
    AuthorizationStrategy strategy = Jenkins.get().getAuthorizationStrategy();
    if (strategy instanceof FolderBasedAuthorizationStrategy) {
        return new TreeSet<>(((FolderBasedAuthorizationStrategy) strategy).getGlobalRoles());
    } else {
        throw new IllegalStateException(Messages.FolderBasedAuthorizationStrategy_NotCurrentStrategy());
    }
}
 
Example #16
Source File: UnsecuredAuthorizationStrategyConfigurator.java    From configuration-as-code-plugin with MIT License 4 votes vote down vote up
@NonNull
@Override
public Class getImplementedAPI() {
    return AuthorizationStrategy.class;
}
 
Example #17
Source File: UnsecuredAuthorizationStrategyConfigurator.java    From configuration-as-code-plugin with MIT License 4 votes vote down vote up
@Override
protected Unsecured instance(Mapping mapping, ConfigurationContext context) {
    return (Unsecured)AuthorizationStrategy.UNSECURED;
}
 
Example #18
Source File: RoleStrategyTest.java    From configuration-as-code-plugin with MIT License 4 votes vote down vote up
@Test
@Issue("Issue #48")
@ConfiguredWithCode("RoleStrategy1.yml")
public void shouldReadRolesCorrectly() throws Exception {
    j.jenkins.setSecurityRealm(j.createDummySecurityRealm());
    User admin = User.getById("admin", false);
    User user1 = User.getById("user1", false);
    User user2 = User.getById("user2", true);
    Computer agent1 = j.jenkins.getComputer("agent1");
    Computer agent2 = j.jenkins.getComputer("agent2");
    Folder folderA = j.jenkins.createProject(Folder.class, "A");
    FreeStyleProject jobA1 = folderA.createProject(FreeStyleProject.class, "1");
    Folder folderB = j.jenkins.createProject(Folder.class, "B");
    folderB.createProject(FreeStyleProject.class, "2");

    AuthorizationStrategy s = j.jenkins.getAuthorizationStrategy();
    assertThat("Authorization Strategy has been read incorrectly",
            s, instanceOf(RoleBasedAuthorizationStrategy.class));
    RoleBasedAuthorizationStrategy rbas = (RoleBasedAuthorizationStrategy) s;

    Map<Role, Set<String>> globalRoles = rbas.getGrantedRoles(RoleBasedAuthorizationStrategy.GLOBAL);
    assertThat(globalRoles.size(), equalTo(2));

    // Admin has configuration access
    assertHasPermission(admin, j.jenkins, Jenkins.ADMINISTER, Jenkins.READ);
    assertHasPermission(user1, j.jenkins, Jenkins.READ);
    assertHasNoPermission(user1, j.jenkins, Jenkins.ADMINISTER);

    // Folder A is restricted to admin
    assertHasPermission(admin, folderA, Item.CONFIGURE);
    assertHasPermission(user1, folderA, Item.READ, Item.DISCOVER);
    assertHasNoPermission(user1, folderA, Item.CONFIGURE, Item.DELETE, Item.BUILD);

    // But they have access to jobs in Folder A
    assertHasPermission(admin, folderA, Item.CONFIGURE, Item.CANCEL);
    assertHasPermission(user1, jobA1, Item.READ, Item.DISCOVER, Item.CONFIGURE, Item.BUILD, Item.DELETE);
    assertHasPermission(user2, jobA1, Item.READ, Item.DISCOVER, Item.CONFIGURE, Item.BUILD, Item.DELETE);
    assertHasNoPermission(user1, folderA, Item.CANCEL);

    // FolderB is editable by user2, but he cannot delete it
    assertHasPermission(user2, folderB, Item.READ, Item.DISCOVER, Item.CONFIGURE, Item.BUILD);
    assertHasNoPermission(user2, folderB, Item.DELETE);
    assertHasNoPermission(user1, folderB, Item.CONFIGURE, Item.BUILD, Item.DELETE);

    // Only user1 can run on agent1, but he still cannot configure it
    assertHasPermission(admin, agent1, Computer.CONFIGURE, Computer.DELETE, Computer.BUILD);
    assertHasPermission(user1, agent1, Computer.BUILD);
    assertHasNoPermission(user1, agent1, Computer.CONFIGURE, Computer.DISCONNECT);

    // Same user still cannot build on agent2
    assertHasNoPermission(user1, agent2, Computer.BUILD);
}
 
Example #19
Source File: UnsecuredAuthorizationStrategyConfiguratorTest.java    From configuration-as-code-plugin with MIT License 4 votes vote down vote up
@Test
@ConfiguredWithCode("UnsecuredAuthorizationStrategyConfiguratorTest.yml")
public void unsecured() throws Exception {
    assertSame(AuthorizationStrategy.UNSECURED, j.jenkins.getAuthorizationStrategy());
}
 
Example #20
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 #21
Source File: FolderAuthorizationStrategyAPI.java    From folder-auth-plugin with MIT License 3 votes vote down vote up
/**
 * Checks the {@link AuthorizationStrategy} and runs the {@link Consumer} when it is an instance of
 * {@link FolderBasedAuthorizationStrategy}.
 * <p>
 * All attempts to access the {@link FolderBasedAuthorizationStrategy} must go through this method
 * for thread-safety.
 *
 * @param runner a function that consumes the current {@link FolderBasedAuthorizationStrategy} and returns a non
 *               null {@link FolderBasedAuthorizationStrategy} object. The object may be the same as the one
 *               consumed if no modification was needed.
 * @throws IllegalStateException when {@link Jenkins#getAuthorizationStrategy()} is not
 *                               {@link FolderBasedAuthorizationStrategy}
 */
private synchronized static void run(Function<FolderBasedAuthorizationStrategy, FolderBasedAuthorizationStrategy> runner) {
    Jenkins jenkins = Jenkins.get();
    AuthorizationStrategy strategy = jenkins.getAuthorizationStrategy();
    if (strategy instanceof FolderBasedAuthorizationStrategy) {
        FolderBasedAuthorizationStrategy newStrategy = runner.apply((FolderBasedAuthorizationStrategy) strategy);
        jenkins.setAuthorizationStrategy(newStrategy);
    } else {
        throw new IllegalStateException("FolderBasedAuthorizationStrategy is not the" + " current authorization strategy");
    }
}
 
Example #22
Source File: JobRunnerForCauseTest.java    From github-integration-plugin with MIT License 3 votes vote down vote up
public void configRoundTripUnsecure(Job job) throws Exception {
        final AuthorizationStrategy before = j.getInstance().getAuthorizationStrategy();

        j.jenkins.setAuthorizationStrategy(new AuthorizationStrategy.Unsecured());

//        j.configRoundtrip(job);

        j.getInstance().setAuthorizationStrategy(before);
    }