Java源码示例:org.sonatype.nexus.security.role.Role

示例1
public Role findRoleByRoleId(String roleId) {
    String[] splits = roleId.split(":");
    String roleType = splits.length > 1 ? splits[0] : null;
    String roleSourceCode = splits.length > 2 ? splits[1] : null;
    String roleName = splits[splits.length - 1];

    if (!(roleSourceCode + "").equals(getSourceCode() + "")) {
        return null;
    }

    RoleRepresentation role;
    if (KeycloakMapper.REALM_GROUP_PREFIX.equals(roleType)) {
        GroupRepresentation group = this.keycloakAdminClient.getRealmGroupByGroupPath(roleName);

        return KeycloakMapper.toRole(getSource(), getSourceCode(), group);
    } else if (KeycloakMapper.REALM_ROLE_PREFIX.equals(roleType)) {
        role = this.keycloakAdminClient.getRealmRoleByRoleName(roleName);
    } else {
        String client = this.keycloakAdminClient.getConfig().getResource();
        role = this.keycloakAdminClient.getRealmClientRoleByRoleName(client, roleName);
    }

    return KeycloakMapper.toRole(getSource(), getSourceCode(), role);
}
 
示例2
public static Role toRole(String source, String sourceCode, RoleRepresentation representation) {
    if (representation == null) {
        return null;
    }

    Role role = new Role();
    String prefix = representation.getClientRole() ? CLIENT_ROLE_PREFIX : REALM_ROLE_PREFIX;
    String roleName = String.format("%s:%s%s",
                                    prefix,
                                    sourceCode != null ? sourceCode + ":" : "",
                                    representation.getName());

    // Use role name as role-id and role-name of Nexus3
    role.setRoleId(roleName);
    role.setName(roleName);
    if (representation.getDescription() != null && !representation.getDescription().isEmpty()) {
        role.setDescription(String.format("%s: %s", prefix, representation.getDescription()));
    }
    role.setReadOnly(true);
    role.setSource(source);

    return role;
}
 
示例3
public static Role toRole(String source, String sourceCode, GroupRepresentation representation) {
    if (representation == null) {
        return null;
    }

    Role role = new Role();
    String roleName = String.format("%s:%s%s",
                                    REALM_GROUP_PREFIX,
                                    sourceCode != null ? sourceCode + ":" : "",
                                    representation.getPath());

    role.setRoleId(roleName);
    role.setName(roleName);
    role.setReadOnly(true);
    role.setSource(source);

    return role;
}
 
示例4
private static Set<Role> toRoles(String source, String sourceCode, List<?>[] lists, boolean forCompatible) {
    Set<Role> roles = new LinkedHashSet<>();

    for (List<?> list : lists) {
        if (list == null || list.isEmpty()) {
            continue;
        }

        for (Object representation : list) {
            if (representation instanceof RoleRepresentation) {
                if (forCompatible && ((RoleRepresentation) representation).getClientRole()) {
                    roles.add(toCompatibleRole(source, (RoleRepresentation) representation));
                }

                roles.add(toRole(source, sourceCode, (RoleRepresentation) representation));
            } else if (representation instanceof GroupRepresentation) {
                roles.add(toRole(source, sourceCode, (GroupRepresentation) representation));
            }
        }
    }
    return roles;
}
 
示例5
public Role createRole(final String name, final String[] roleIds, final String[] privilegeNames) {
  List<Privilege> privileges =
      Arrays.stream(privilegeNames).map(this::getPrivilege).filter(Objects::nonNull).collect(Collectors.toList());

  if (privileges.size() != privilegeNames.length) {
    throw new IllegalStateException(
        String.format("Missing privileges names: %s privileges: %s", privilegeNames, privileges));
  }

  List<Role> roles = Arrays.stream(roleIds).map(this::getRole).filter(Objects::nonNull).collect(Collectors.toList());

  if (roles.size() != roleIds.length) {
    throw new IllegalStateException("Missing privileges names: ${roleIds} privileges: ${roles}");
  }

  return createRole(name, roles, privileges);
}
 
示例6
@Override
protected Result check() throws Exception {
  if (!realmManager.isRealmEnabled(DefaultRoleRealm.NAME)) {
    return Result.healthy("Default Role Realm not in use.");
  }

  if (defaultRoleRealm.getRole() == null) {
    return Result.unhealthy("Default Role Realm is enabled but not configured.");
  }

  Role matched = securitySystem.listRoles(DEFAULT_SOURCE).stream()
      .filter(role -> role.getRoleId().equals(defaultRoleRealm.getRole())).findFirst().orElse(null);

  if (matched == null) {
    return Result
        .unhealthy("Default Role Realm configured to use role %s which doesn't exist.", defaultRoleRealm.getRole());
  }

  return Result.healthy("Default Role Realm configured to use role %s.", defaultRoleRealm.getRole());
}
 
示例7
@Subscribe
@AllowConcurrentEvents
public void on(final RoleEvent event) {
  if (isRecording()) {
    Role role = event.getRole();

    AuditData data = new AuditData();
    data.setDomain(DOMAIN);
    data.setType(type(event.getClass()));
    data.setContext(role.getRoleId());

    Map<String, Object> attributes = data.getAttributes();
    attributes.put("id", role.getRoleId());
    attributes.put("name", role.getName());
    attributes.put("source", role.getSource());
    attributes.put("roles", string(role.getRoles()));
    attributes.put("privileges", string(role.getPrivileges()));

    record(data);
  }
}
 
示例8
private CRole convert(final Role source) {
  CRole target = configuration.newRole();
  target.setId(source.getRoleId());
  target.setVersion(source.getVersion());
  target.setName(source.getName());
  target.setDescription(source.getDescription());
  target.setReadOnly(source.isReadOnly());

  if (source.getPrivileges() != null) {
    target.setPrivileges(Sets.newHashSet(source.getPrivileges()));
  }
  else {
    target.setPrivileges(Sets.<String>newHashSet());
  }

  if (source.getRoles() != null) {
    target.setRoles(Sets.newHashSet(source.getRoles()));
  }
  else {
    target.setRoles(Sets.<String>newHashSet());
  }

  return target;
}
 
示例9
@Test
public void testGetRoles() throws Exception {
  Role role1 = createRole("default", "id1", "role1", "role1", Arrays.asList("role1", "role2"),
      Arrays.asList("priv1", "priv2"));
  Role role2 = createRole("default", "id2", "role2", "role2", Arrays.asList("role2", "role3"),
      Arrays.asList("priv2", "priv3"));

  when(securitySystem.listRoles("default")).thenReturn(new LinkedHashSet<>(Arrays.asList(role2, role1)));

  List<RoleXOResponse> apiRoles = underTest.getRoles("default");

  assertThat(apiRoles.size(), is(2));

  assertApiRole(apiRoles.get(0), "default", "id1", "role1", "role1", Arrays.asList("role1", "role2"),
      Arrays.asList("priv1", "priv2"));
  assertApiRole(apiRoles.get(1), "default", "id2", "role2", "role2", Arrays.asList("role2", "role3"),
      Arrays.asList("priv2", "priv3"));
}
 
示例10
@Test
public void testGetRoles_allSources() throws Exception {
  Role role1 = createRole("default", "id1", "role1", "role1", Arrays.asList("role1", "role2"),
      Arrays.asList("priv1", "priv2"));
  Role role2 = createRole("another", "id2", "role2", "role2", Arrays.asList("role2", "role3"),
      Arrays.asList("priv2", "priv3"));

  when(securitySystem.listRoles()).thenReturn(new LinkedHashSet<>(Arrays.asList(role2, role1)));

  List<RoleXOResponse> apiRoles = underTest.getRoles(null);

  assertThat(apiRoles.size(), is(2));

  assertApiRole(apiRoles.get(0), "default", "id1", "role1", "role1", Arrays.asList("role1", "role2"),
      Arrays.asList("priv1", "priv2"));
  assertApiRole(apiRoles.get(1), "another", "id2", "role2", "role2", Arrays.asList("role2", "role3"),
      Arrays.asList("priv2", "priv3"));
}
 
示例11
@Test
public void testCreateRole() throws Exception {
  RoleXORequest roleXo = createApiRole("roleId", "roleName", "description", Collections.singleton("childRole"),
      Collections.singleton("priv"));

  Role createdRole = new Role();
  createdRole.setRoleId("roleId");
  createdRole.setSource("default");
  createdRole.setName("roleName");
  createdRole.setDescription("description");
  createdRole.setReadOnly(false);
  createdRole.setRoles(Collections.singleton("childRole"));
  createdRole.setPrivileges(Collections.singleton("priv"));

  when(authorizationManager.addRole(any())).thenReturn(createdRole);

  RoleXOResponse result = underTest.create(roleXo);

  assertApiRole(result, "default", "roleId", "roleName", "description", Collections.singleton("childRole"),
      Collections.singleton("priv"));
}
 
示例12
@Test
public void testUpdateRole() {
  Role role = createRole("default", "id1", "role1", "role1", Arrays.asList("role1", "role2"),
      Arrays.asList("priv1", "priv2"));
  when(authorizationManager.getRole("id1")).thenReturn(role);

  RoleXORequest roleXo = createApiRole("id1", "role2", "role2", Arrays.asList("role3", "role4"),
      Arrays.asList("priv3", "priv4"));

  underTest.update("id1", roleXo);

  ArgumentCaptor<Role> argument = ArgumentCaptor.forClass(Role.class);
  verify(authorizationManager).updateRole(argument.capture());
  assertRole(argument.getValue(), "default", "id1", "role2", "role2", Arrays.asList("role3", "role4"),
      Arrays.asList("priv3", "priv4"));
}
 
示例13
@Test
public void testUpdateRole_readOnly() {
  Role role = createRole("default", "id", "name", "description", Collections.singleton("role1"),
      Collections.singleton("priv1"));

  when(authorizationManager.getRole("id")).thenReturn(role);
  when(authorizationManager.updateRole(role)).thenThrow(ReadonlyRoleException.class);

  RoleXORequest roleXo = createApiRole("id", "name", "description", Collections.singleton("role1"),
      Collections.singleton("priv1"));

  try {
    underTest.update("id", roleXo);
    fail("exception should have been thrown for internal role");
  }
  catch (WebApplicationMessageException e) {
    assertThat(e.getResponse().getStatus(), is(400));
    assertThat(e.getResponse().getMediaType(), is(MediaType.APPLICATION_JSON_TYPE));
    assertThat(e.getResponse().getEntity().toString(),
        is("\"Role 'id' is internal and cannot be modified or deleted.\""));
  }
}
 
示例14
private Role createRole(final String source,
                        final String id,
                        final String name,
                        final String description,
                        final Collection<String> roles,
                        final Collection<String> privileges)
{
  Role role = new Role();
  role.setRoleId(id);
  role.setName(name);
  role.setDescription(description);
  role.setSource(source);
  roles.forEach(role::addRole);
  privileges.forEach(role::addPrivilege);

  return role;
}
 
示例15
private void assertRole(final Role role,
                        final String source,
                        final String id,
                        final String name,
                        final String description,
                        final Collection<String> roles,
                        final Collection<String> privileges)
{
  assertThat(role.getSource(), is(source));
  assertThat(role.getRoleId(), is(id));
  assertThat(role.getName(), is(name));
  assertThat(role.getDescription(), is(description));
  if (roles.isEmpty()) {
    assertThat(role.getRoles(), empty());
  }
  else {
    assertThat(role.getRoles(), containsInAnyOrder(roles.toArray(new String[] {})));
  }
  if (privileges.isEmpty()) {
    assertThat(role.getPrivileges(), empty());
  }
  else {
    assertThat(role.getPrivileges(), containsInAnyOrder(privileges.toArray(new String[] {})));
  }
}
 
示例16
@Override
public Set<Role> listRoles() {
  Set<Role> roles = new HashSet<Role>();

  Role role1 = new Role();
  role1.setSource(this.getSource());
  role1.setName("Role 1");
  role1.setRoleId("test-role1");
  role1.addPrivilege("from-role1:read");
  role1.addPrivilege("from-role1:delete");

  Role role2 = new Role();
  role2.setSource(this.getSource());
  role2.setName("Role 2");
  role2.setRoleId("test-role2");
  role2.addPrivilege("from-role2:read");
  role2.addPrivilege("from-role2:delete");

  roles.add(role1);
  roles.add(role2);

  return roles;
}
 
示例17
@Test
public void testListRoles() throws Exception {
  AuthorizationManager authzManager = this.getAuthorizationManager();
  Set<Role> roles = authzManager.listRoles();

  Map<String, Role> roleMap = this.toRoleMap(roles);
  Assert.assertTrue(roleMap.containsKey("role1"));
  Assert.assertTrue(roleMap.containsKey("role2"));
  Assert.assertTrue(roleMap.containsKey("role3"));
  Assert.assertEquals(3, roles.size());

  Role role3 = roleMap.get("role3");

  Assert.assertEquals("role3", role3.getRoleId());
  Assert.assertEquals("RoleThree", role3.getName());
  Assert.assertEquals("Role Three", role3.getDescription());
  Assert.assertTrue(role3.getPrivileges().contains("1"));
  Assert.assertTrue(role3.getPrivileges().contains("4"));
  Assert.assertEquals(2, role3.getPrivileges().size());
}
 
示例18
@Test
public void testAddRole() throws Exception {
  AuthorizationManager authzManager = this.getAuthorizationManager();

  Role role = new Role();
  role.setRoleId("new-role");
  role.setName("new-name");
  role.setDescription("new-description");
  role.addPrivilege("2");
  role.addPrivilege("4");

  authzManager.addRole(role);

  CRole secRole = this.getConfigurationManager().readRole(role.getRoleId());

  Assert.assertEquals(role.getRoleId(), secRole.getId());
  Assert.assertEquals(role.getName(), secRole.getName());
  Assert.assertEquals(role.getDescription(), secRole.getDescription());
  Assert.assertTrue(secRole.getPrivileges().contains("2"));
  Assert.assertTrue(secRole.getPrivileges().contains("4"));
  Assert.assertEquals(2, secRole.getPrivileges().size());
}
 
示例19
@Test
public void testUpdateRole() throws Exception {
  AuthorizationManager authzManager = this.getAuthorizationManager();

  Role role2 = authzManager.getRole("role2");
  role2.setDescription("new description");
  role2.setName("new name");

  Set<String> permissions = new HashSet<String>();
  permissions.add("2");
  role2.setPrivileges(permissions);

  authzManager.updateRole(role2);

  CRole secRole = this.getConfigurationManager().readRole(role2.getRoleId());

  Assert.assertEquals(role2.getRoleId(), secRole.getId());
  Assert.assertEquals(role2.getName(), secRole.getName());
  Assert.assertEquals(role2.getDescription(), secRole.getDescription());
  Assert.assertTrue(secRole.getPrivileges().contains("2"));
  Assert.assertEquals(1, secRole.getPrivileges().size());
}
 
示例20
@Before
public void setup() throws Exception {
  when(applicationDirectories.getWorkDirectory()).thenReturn(util.createTempDir());
  adminPasswordFileManager = new AdminPasswordFileManagerImpl(applicationDirectories);
  underTest = new UserApiResource(securitySystem, adminPasswordFileManager);

  final User user = createUser();
  when(securitySystem.getUser(any(), any())).thenAnswer(i -> {
    if ("jdoe".equals(i.getArguments()[0]) && "LDAP".equals(i.getArguments()[1])) {
      throw new UserNotFoundException((String) i.getArguments()[0]);
    }
    return user;
  });
  when(securitySystem.getUser(user.getUserId())).thenReturn(user);

  UserManager ldap = mock(UserManager.class);
  when(ldap.supportsWrite()).thenReturn(false);
  when(securitySystem.getUserManager("LDAP")).thenReturn(ldap);

  when(securitySystem.getUserManager(UserManager.DEFAULT_SOURCE)).thenReturn(userManager);
  when(securitySystem.listRoles(UserManager.DEFAULT_SOURCE))
      .thenReturn(Collections.singleton(new Role("nx-admin", null, null, null, true, null, null)));
  when(userManager.supportsWrite()).thenReturn(true);
}
 
示例21
@Test
public void testAuthorizationManager() throws Exception {
  SecuritySystem securitySystem = this.getSecuritySystem();

  Set<Role> roles = securitySystem.listRoles("sourceB");
  Assert.assertEquals(2, roles.size());

  Map<String, Role> roleMap = new HashMap<String, Role>();
  for (Role role : roles) {
    roleMap.put(role.getRoleId(), role);
  }

  Assert.assertTrue(roleMap.containsKey("test-role1"));
  Assert.assertTrue(roleMap.containsKey("test-role2"));

  Role role1 = roleMap.get("test-role1");
  Assert.assertEquals("Role 1", role1.getName());

  Assert.assertTrue(role1.getPrivileges().contains("from-role1:read"));
  Assert.assertTrue(role1.getPrivileges().contains("from-role1:delete"));
}
 
示例22
protected void setUnauthorizedUser() {
  String randomRoleName = "role_" + UUID.randomUUID().toString();

  Role role = securityRule.createRole(randomRoleName, UNRELATED_PRIVILEGE);
  securityRule.createUser(randomRoleName, randomRoleName, role.getRoleId());
  credentials = new UsernamePasswordCredentials(randomRoleName, randomRoleName);
}
 
示例23
protected void setUnauthorizedUser() {
  String randomRoleName = "role_" + UUID.randomUUID().toString();

  Role role = securityRule.createRole(randomRoleName, UNRELATED_PRIVILEGE);
  securityRule.createUser(randomRoleName, randomRoleName, role.getRoleId());
  credentials = new UsernamePasswordCredentials(randomRoleName, randomRoleName);
}
 
示例24
protected void setUnauthorizedUser() {
  String randomRoleName = "role_" + UUID.randomUUID().toString();

  Role role = securityRule.createRole(randomRoleName, UNRELATED_PRIVILEGE);
  securityRule.createUser(randomRoleName, randomRoleName, role.getRoleId());
  credentials = new UsernamePasswordCredentials(randomRoleName, randomRoleName);
}
 
示例25
protected void setUnauthorizedUser() {
  String randomRoleName = "role_" + UUID.randomUUID().toString();

  Role role = securityRule.createRole(randomRoleName, UNRELATED_PRIVILEGE);
  securityRule.createUser(randomRoleName, randomRoleName, role.getRoleId());
  credentials = new UsernamePasswordCredentials(randomRoleName, randomRoleName);
}
 
示例26
@Override
public Role getRole(String roleId) throws NoSuchRoleException {
    Role role = this.client.findRoleByRoleId(roleId);
    if (role == null) {
        throw new NoSuchRoleException("Failed to get role " + roleId + " from Keycloak.");
    } else {
        return role;
    }
}
 
示例27
public Set<Role> findRoles() {
    String client = this.keycloakAdminClient.getConfig().getResource();

    List<RoleRepresentation> clientRoles = this.keycloakAdminClient.getRealmClientRoles(client);
    List<RoleRepresentation> realmRoles = this.keycloakAdminClient.getRealmRoles();
    List<GroupRepresentation> realmGroups = this.keycloakAdminClient.getRealmGroups();

    return KeycloakMapper.toRoles(getSource(), getSourceCode(), clientRoles, realmRoles, realmGroups);
}
 
示例28
private static Role toCompatibleRole(String source, RoleRepresentation representation) {
    Role role = new Role();

    role.setRoleId(representation.getName());
    role.setName(representation.getName());
    role.setDescription(representation.getDescription());
    role.setReadOnly(true);
    role.setSource(source);
    return role;
}
 
示例29
public Role getRole(final String roleId) {
  try {
    return securitySystemProvider.get().getAuthorizationManager(DEFAULT_SOURCE).listRoles().stream()
        .filter(role -> role.getRoleId().equals(roleId)).findFirst().orElse(null);
  }
  catch (NoSuchAuthorizationManagerException e) {
    log.debug("Failed to get role {}", roleId, e);
  }
  return null;
}
 
示例30
public Role createRole(final String name, final Role[] containedRoles, final Privilege[] privileges) {
  Role role =
      new Role(name, name, name, DEFAULT_SOURCE, false, Arrays.stream(containedRoles).map(Role::getRoleId).collect(
          Collectors.toSet()), Arrays.stream(privileges).map(Privilege::getId).collect(Collectors.toSet()));

  try {
    securitySystemProvider.get().getAuthorizationManager(DEFAULT_SOURCE).addRole(role);
    roles.add(role);
    return role;
  }
  catch (NoSuchAuthorizationManagerException e) {
    log.debug("Unable to add role {}", name, e);
  }
  return null;
}