Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Api token authc/z implementation with Cache #4992

Merged
merged 31 commits into from
Feb 4, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
9f695fa
Naive cluster permission authz and authc based on token validity
derek-ho Dec 24, 2024
d3fcc4a
Crude index permissions authz
derek-ho Dec 24, 2024
6904317
Fix tests
derek-ho Dec 26, 2024
17bca93
Revert mis-merge in abstractauditlog
derek-ho Dec 26, 2024
92d4e60
Add allowlist for authc, add basic test showing it works
derek-ho Dec 27, 2024
22cfbe8
Add more extensive tests for authenticator, switch to list of indexPe…
derek-ho Dec 27, 2024
665b9e9
Directly store permissions in the cache
derek-ho Dec 30, 2024
e39df0d
Remove permissions from jti
derek-ho Dec 30, 2024
ad63974
Onboard onto clusterPrivileges
derek-ho Dec 30, 2024
73eb2ab
Add index permissions api token eval
derek-ho Dec 31, 2024
6418226
Add testing for cluster and index priv
derek-ho Dec 31, 2024
bc8aacf
Use transport action
derek-ho Jan 6, 2025
b90bae9
Cleanup tests and constants
derek-ho Jan 6, 2025
552aeda
Fix test
derek-ho Jan 6, 2025
aa506e7
Remove unecessary id to jti map since we are reloading every time and…
derek-ho Jan 6, 2025
d9cf78d
PR review
derek-ho Jan 14, 2025
d7b7e47
Spotless
derek-ho Jan 14, 2025
6571d9d
Fix tests
derek-ho Jan 14, 2025
9fcb720
PR review
derek-ho Jan 14, 2025
e44072c
Inject
derek-ho Jan 14, 2025
0927d99
Fix
derek-ho Jan 15, 2025
fb79014
Fix tests
derek-ho Jan 16, 2025
0f60569
Final cleanup
derek-ho Jan 16, 2025
6634896
Merge branch 'feature/api-tokens' of github.com:opensearch-project/se…
derek-ho Jan 17, 2025
83769b1
Fix tests
derek-ho Jan 17, 2025
685dcfc
PR feedback
derek-ho Jan 21, 2025
6ffc060
Mock api tokenrepository behavior
derek-ho Jan 21, 2025
763a9ff
Refactor to abstract class
derek-ho Jan 22, 2025
a685951
Fix test and cleanup
derek-ho Jan 23, 2025
77ad6c3
Separate the calls out based on type
derek-ho Jan 23, 2025
7a20de3
PR comments
derek-ho Feb 4, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -38,14 +38,20 @@
import org.opensearch.common.util.concurrent.ThreadContext;
import org.opensearch.core.common.unit.ByteSizeUnit;
import org.opensearch.core.common.unit.ByteSizeValue;
import org.opensearch.security.action.apitokens.ApiToken;
import org.opensearch.security.action.apitokens.ApiTokenRepository;
import org.opensearch.security.action.apitokens.Permissions;
import org.opensearch.security.resolver.IndexResolverReplacer;
import org.opensearch.security.securityconf.FlattenedActionGroups;
import org.opensearch.security.securityconf.impl.CType;
import org.opensearch.security.securityconf.impl.SecurityDynamicConfiguration;
import org.opensearch.security.securityconf.impl.v7.ActionGroupsV7;
import org.opensearch.security.securityconf.impl.v7.RoleV7;
import org.opensearch.security.user.User;
import org.opensearch.security.util.MockIndexMetadataBuilder;

import org.mockito.Mockito;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.opensearch.security.privileges.PrivilegeEvaluatorResponseMatcher.isAllowed;
import static org.opensearch.security.privileges.PrivilegeEvaluatorResponseMatcher.isForbidden;
Expand Down Expand Up @@ -280,6 +286,69 @@ public void hasAny_wildcard() throws Exception {
isForbidden(missingPrivileges("cluster:whatever"))
);
}

@Test
public void apiToken_explicit_failsWithWildcard() throws Exception {
SecurityDynamicConfiguration<RoleV7> roles = SecurityDynamicConfiguration.empty(CType.ROLES);
ActionPrivileges subject = new ActionPrivileges(roles, FlattenedActionGroups.EMPTY, null, Settings.EMPTY);
String token = "blah";
PermissionBasedPrivilegesEvaluationContext context = ctxForApiToken(
"apitoken:" + token,
new Permissions(List.of("*"), List.of())
);
// Explicit fails
assertThat(
subject.hasExplicitClusterPrivilege(context, "cluster:whatever"),
isForbidden(missingPrivileges("cluster:whatever"))
);
// Not explicit succeeds
assertThat(subject.hasClusterPrivilege(context, "cluster:whatever"), isAllowed());
// Any succeeds
assertThat(subject.hasAnyClusterPrivilege(context, ImmutableSet.of("cluster:whatever")), isAllowed());
}

@Test
public void apiToken_succeedsWithExactMatch() throws Exception {
SecurityDynamicConfiguration<RoleV7> roles = SecurityDynamicConfiguration.empty(CType.ROLES);
ActionPrivileges subject = new ActionPrivileges(roles, FlattenedActionGroups.EMPTY, null, Settings.EMPTY);
String token = "blah";
PermissionBasedPrivilegesEvaluationContext context = ctxForApiToken(
"apitoken:" + token,
new Permissions(List.of("cluster:whatever"), List.of())
);
// Explicit succeeds
assertThat(subject.hasExplicitClusterPrivilege(context, "cluster:whatever"), isAllowed());
// Not explicit succeeds
assertThat(subject.hasClusterPrivilege(context, "cluster:whatever"), isAllowed());
// Any succeeds
assertThat(subject.hasAnyClusterPrivilege(context, ImmutableSet.of("cluster:whatever")), isAllowed());
// Any succeeds
assertThat(subject.hasAnyClusterPrivilege(context, ImmutableSet.of("cluster:whatever", "cluster:other")), isAllowed());
}

@Test
public void apiToken_succeedsWithActionGroupsExapnded() throws Exception {
SecurityDynamicConfiguration<RoleV7> roles = SecurityDynamicConfiguration.empty(CType.ROLES);

SecurityDynamicConfiguration<ActionGroupsV7> config = SecurityDynamicConfiguration.fromYaml(
"CLUSTER_ALL:\n allowed_actions:\n - \"cluster:*\"",
CType.ACTIONGROUPS
);

FlattenedActionGroups actionGroups = new FlattenedActionGroups(config);
ActionPrivileges subject = new ActionPrivileges(roles, actionGroups, null, Settings.EMPTY);
String token = "blah";
PermissionBasedPrivilegesEvaluationContext context = ctxForApiToken(
"apitoken:" + token,
new Permissions(List.of("CLUSTER_ALL"), List.of())
);
// Explicit succeeds
assertThat(subject.hasExplicitClusterPrivilege(context, "cluster:whatever"), isAllowed());
// Not explicit succeeds
assertThat(subject.hasClusterPrivilege(context, "cluster:whatever"), isAllowed());
// Any succeeds
assertThat(subject.hasClusterPrivilege(context, "cluster:monitor/main"), isAllowed());
}
}

/**
Expand Down Expand Up @@ -314,9 +383,20 @@ public void positive_full() throws Exception {
assertThat(result, isAllowed());
}

@Test
public void apiTokens_positive_full() throws Exception {
String token = "blah";
PermissionBasedPrivilegesEvaluationContext context = ctxForApiToken(
"apitoken:" + token,
new Permissions(List.of("index_a11"), List.of(new ApiToken.IndexPermission(List.of("index_a11"), List.of("*"))))
);
PrivilegesEvaluatorResponse result = subject.hasIndexPrivilege(context, requiredActions, resolved("index_a11"));
assertThat(result, isAllowed());
}

@Test
public void positive_partial() throws Exception {
PrivilegesEvaluationContext ctx = ctx("test_role");
RoleBasedPrivilegesEvaluationContext ctx = ctx("test_role");
PrivilegesEvaluatorResponse result = subject.hasIndexPrivilege(ctx, requiredActions, resolved("index_a11", "index_a12"));

if (covers(ctx, "index_a11", "index_a12")) {
Expand All @@ -330,7 +410,7 @@ public void positive_partial() throws Exception {

@Test
public void positive_partial2() throws Exception {
PrivilegesEvaluationContext ctx = ctx("test_role");
RoleBasedPrivilegesEvaluationContext ctx = ctx("test_role");
PrivilegesEvaluatorResponse result = subject.hasIndexPrivilege(
ctx,
requiredActions,
Expand Down Expand Up @@ -363,14 +443,26 @@ public void positive_noLocal() throws Exception {

@Test
public void negative_wrongRole() throws Exception {
PrivilegesEvaluationContext ctx = ctx("other_role");
RoleBasedPrivilegesEvaluationContext ctx = ctx("other_role");
PrivilegesEvaluatorResponse result = subject.hasIndexPrivilege(ctx, requiredActions, resolved("index_a11"));
assertThat(result, isForbidden(missingPrivileges(requiredActions)));
}

@Test
public void apiToken_negative_noPermissions() throws Exception {
String token = "blah";
PermissionBasedPrivilegesEvaluationContext context = ctxForApiToken(
"apitoken:" + token,
new Permissions(List.of(), List.of(new ApiToken.IndexPermission(List.of(), List.of())))
);

PrivilegesEvaluatorResponse result = subject.hasIndexPrivilege(context, requiredActions, resolved("index_a11"));
assertThat(result, isForbidden());
}

@Test
public void negative_wrongAction() throws Exception {
PrivilegesEvaluationContext ctx = ctx("test_role");
RoleBasedPrivilegesEvaluationContext ctx = ctx("test_role");
PrivilegesEvaluatorResponse result = subject.hasIndexPrivilege(ctx, otherActions, resolved("index_a11"));

if (actionSpec.givenPrivs.contains("*")) {
Expand All @@ -382,7 +474,7 @@ public void negative_wrongAction() throws Exception {

@Test
public void positive_hasExplicit_full() {
PrivilegesEvaluationContext ctx = ctx("test_role");
RoleBasedPrivilegesEvaluationContext ctx = ctx("test_role");
PrivilegesEvaluatorResponse result = subject.hasExplicitIndexPrivilege(ctx, requiredActions, resolved("index_a11"));

if (actionSpec.givenPrivs.contains("*")) {
Expand All @@ -397,7 +489,21 @@ public void positive_hasExplicit_full() {
}
}

private boolean covers(PrivilegesEvaluationContext ctx, String... indices) {
@Test
public void apiTokens_positive_hasExplicit_full() {
String token = "blah";
PermissionBasedPrivilegesEvaluationContext context = ctxForApiToken(
"apitoken:" + token,
new Permissions(List.of("index_a11"), List.of(new ApiToken.IndexPermission(List.of("index_a11"), List.of("*"))))
);

PrivilegesEvaluatorResponse result = subject.hasExplicitIndexPrivilege(context, requiredActions, resolved("index_a11"));

assertThat(result, isForbidden());

}

private boolean covers(RoleBasedPrivilegesEvaluationContext ctx, String... indices) {
for (String index : indices) {
if (!indexSpec.covers(ctx.getUser(), index)) {
return false;
Expand Down Expand Up @@ -522,7 +628,7 @@ public static class DataStreams {

@Test
public void positive_full() throws Exception {
PrivilegesEvaluationContext ctx = ctx("test_role");
RoleBasedPrivilegesEvaluationContext ctx = ctx("test_role");
PrivilegesEvaluatorResponse result = subject.hasIndexPrivilege(ctx, requiredActions, resolved("data_stream_a11"));
if (covers(ctx, "data_stream_a11")) {
assertThat(result, isAllowed());
Expand All @@ -538,7 +644,7 @@ public void positive_full() throws Exception {

@Test
public void positive_partial() throws Exception {
PrivilegesEvaluationContext ctx = ctx("test_role");
RoleBasedPrivilegesEvaluationContext ctx = ctx("test_role");
PrivilegesEvaluatorResponse result = subject.hasIndexPrivilege(
ctx,
requiredActions,
Expand Down Expand Up @@ -569,19 +675,19 @@ public void positive_partial() throws Exception {

@Test
public void negative_wrongRole() throws Exception {
PrivilegesEvaluationContext ctx = ctx("other_role");
RoleBasedPrivilegesEvaluationContext ctx = ctx("other_role");
PrivilegesEvaluatorResponse result = subject.hasIndexPrivilege(ctx, requiredActions, resolved("data_stream_a11"));
assertThat(result, isForbidden(missingPrivileges(requiredActions)));
}

@Test
public void negative_wrongAction() throws Exception {
PrivilegesEvaluationContext ctx = ctx("test_role");
RoleBasedPrivilegesEvaluationContext ctx = ctx("test_role");
PrivilegesEvaluatorResponse result = subject.hasIndexPrivilege(ctx, otherActions, resolved("data_stream_a11"));
assertThat(result, isForbidden(missingPrivileges(otherActions)));
}

private boolean covers(PrivilegesEvaluationContext ctx, String... indices) {
private boolean covers(RoleBasedPrivilegesEvaluationContext ctx, String... indices) {
for (String index : indices) {
if (!indexSpec.covers(ctx.getUser(), index)) {
return false;
Expand Down Expand Up @@ -1039,10 +1145,15 @@ static SecurityDynamicConfiguration<RoleV7> createRoles(int numberOfRoles, int n
}
}

static PrivilegesEvaluationContext ctx(String... roles) {
User user = new User("test_user");
static RoleBasedPrivilegesEvaluationContext ctx(String... roles) {
return ctxWithUserName("test-user", roles);
}

static RoleBasedPrivilegesEvaluationContext ctxWithUserName(String userName, String... roles) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can the name ctxWithUserName() be somehow refined? Considering that ctxForApiToken() also accepts a userName param, it is unclear by the name what the difference to ctxWithUserName() is.

User user = new User(userName);
user.addAttributes(ImmutableMap.of("attrs.dept_no", "a11"));
return new PrivilegesEvaluationContext(
ApiTokenRepository mockRepository = Mockito.mock(ApiTokenRepository.class);
return new RoleBasedPrivilegesEvaluationContext(
user,
ImmutableSet.copyOf(roles),
null,
Expand All @@ -1054,10 +1165,25 @@ static PrivilegesEvaluationContext ctx(String... roles) {
);
}

static PrivilegesEvaluationContext ctxByUsername(String username) {
static PermissionBasedPrivilegesEvaluationContext ctxForApiToken(String userName, Permissions permissions) {
User user = new User(userName);
user.addAttributes(ImmutableMap.of("attrs.dept_no", "a11"));
return new PermissionBasedPrivilegesEvaluationContext(
user,
null,
null,
null,
null,
new IndexNameExpressionResolver(new ThreadContext(Settings.EMPTY)),
null,
permissions
);
}

static RoleBasedPrivilegesEvaluationContext ctxByUsername(String username) {
User user = new User(username);
user.addAttributes(ImmutableMap.of("attrs.dept_no", "a11"));
return new PrivilegesEvaluationContext(
return new RoleBasedPrivilegesEvaluationContext(
user,
ImmutableSet.of(),
null,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -231,14 +231,14 @@ public void equals() {
assertFalse(a1.equals(a1.toString()));
}

private static PrivilegesEvaluationContext ctx() {
private static RoleBasedPrivilegesEvaluationContext ctx() {
IndexNameExpressionResolver indexNameExpressionResolver = new IndexNameExpressionResolver(new ThreadContext(Settings.EMPTY));
IndexResolverReplacer indexResolverReplacer = new IndexResolverReplacer(indexNameExpressionResolver, () -> CLUSTER_STATE, null);
User user = new User("test_user");
user.addAttributes(ImmutableMap.of("attrs.a11", "a11"));
user.addAttributes(ImmutableMap.of("attrs.year", "year"));

return new PrivilegesEvaluationContext(
return new RoleBasedPrivilegesEvaluationContext(
user,
ImmutableSet.of(),
"indices:action/test",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -188,13 +188,13 @@ public void hasExplicitClusterPermissionPermissionForRestAdmin() {
.collect(Collectors.toList());
for (final Endpoint endpoint : noSslEndpoints) {
final String permission = ENDPOINTS_WITH_PERMISSIONS.get(endpoint).build();
final PrivilegesEvaluationContext ctx = ctx(restAdminApiRoleName(endpoint.name().toLowerCase(Locale.ROOT)));
final RoleBasedPrivilegesEvaluationContext ctx = ctx(restAdminApiRoleName(endpoint.name().toLowerCase(Locale.ROOT)));
Assert.assertTrue(endpoint.name(), actionPrivileges.hasExplicitClusterPrivilege(ctx, permission).isAllowed());
assertHasNoPermissionsForRestApiAdminOnePermissionRole(endpoint, ctx);
}
// verify SSL endpoint with 2 actions
for (final String sslAction : ImmutableSet.of(CERTS_INFO_ACTION, RELOAD_CERTS_ACTION)) {
final PrivilegesEvaluationContext ctx = ctx(restAdminApiRoleName(sslAction));
final RoleBasedPrivilegesEvaluationContext ctx = ctx(restAdminApiRoleName(sslAction));
final PermissionBuilder permissionBuilder = ENDPOINTS_WITH_PERMISSIONS.get(Endpoint.SSL);
Assert.assertTrue(
Endpoint.SSL + "/" + sslAction,
Expand All @@ -203,7 +203,7 @@ public void hasExplicitClusterPermissionPermissionForRestAdmin() {
assertHasNoPermissionsForRestApiAdminOnePermissionRole(Endpoint.SSL, ctx);
}
// verify CONFIG endpoint with 1 action
final PrivilegesEvaluationContext ctx = ctx(restAdminApiRoleName(SECURITY_CONFIG_UPDATE));
final RoleBasedPrivilegesEvaluationContext ctx = ctx(restAdminApiRoleName(SECURITY_CONFIG_UPDATE));
final PermissionBuilder permissionBuilder = ENDPOINTS_WITH_PERMISSIONS.get(Endpoint.CONFIG);
Assert.assertTrue(
Endpoint.SSL + "/" + SECURITY_CONFIG_UPDATE,
Expand All @@ -212,7 +212,10 @@ public void hasExplicitClusterPermissionPermissionForRestAdmin() {
assertHasNoPermissionsForRestApiAdminOnePermissionRole(Endpoint.CONFIG, ctx);
}

void assertHasNoPermissionsForRestApiAdminOnePermissionRole(final Endpoint allowEndpoint, final PrivilegesEvaluationContext ctx) {
void assertHasNoPermissionsForRestApiAdminOnePermissionRole(
final Endpoint allowEndpoint,
final RoleBasedPrivilegesEvaluationContext ctx
) {
final Collection<Endpoint> noPermissionEndpoints = ENDPOINTS_WITH_PERMISSIONS.keySet()
.stream()
.filter(e -> e != allowEndpoint)
Expand Down Expand Up @@ -250,8 +253,17 @@ static SecurityDynamicConfiguration<RoleV7> createRolesConfig() throws IOExcepti
return SecurityDynamicConfiguration.fromNode(rolesNode, CType.ROLES, 2, 0, 0);
}

static PrivilegesEvaluationContext ctx(String... roles) {
return new PrivilegesEvaluationContext(new User("test_user"), ImmutableSet.copyOf(roles), null, null, null, null, null, null);
static RoleBasedPrivilegesEvaluationContext ctx(String... roles) {
return new RoleBasedPrivilegesEvaluationContext(
new User("test_user"),
ImmutableSet.copyOf(roles),
null,
null,
null,
null,
null,
null
);
}

}
Loading
Loading