diff --git a/src/main/java/org/opensearch/security/OpenSearchSecurityPlugin.java b/src/main/java/org/opensearch/security/OpenSearchSecurityPlugin.java index ed8b05d61f..a297961230 100644 --- a/src/main/java/org/opensearch/security/OpenSearchSecurityPlugin.java +++ b/src/main/java/org/opensearch/security/OpenSearchSecurityPlugin.java @@ -198,7 +198,12 @@ import org.opensearch.transport.TransportService; import org.opensearch.watcher.ResourceWatcherService; -public final class OpenSearchSecurityPlugin extends OpenSearchSecuritySSLPlugin implements ClusterPlugin, MapperPlugin, IdentityPlugin, ExtensionAwarePlugin { +public final class OpenSearchSecurityPlugin extends OpenSearchSecuritySSLPlugin + implements + ClusterPlugin, + MapperPlugin, + IdentityPlugin, + ExtensionAwarePlugin { private static final String KEYWORD = ".keyword"; private static final Logger actionTrace = LogManager.getLogger("opendistro_security_action_trace"); @@ -234,18 +239,16 @@ public final class OpenSearchSecurityPlugin extends OpenSearchSecuritySSLPlugin private volatile OpensearchDynamicSetting transportPassiveAuthSetting; public static Setting RESERVED_INDICES_SETTING = Setting.listSetting( - "reserved_indices", - List.of(), - Function.identity(), - Property.ExtensionScope + "reserved_indices", + List.of(), + Function.identity(), + Property.ExtensionScope ); public static Setting PERMISSIONS_SETTING = Setting.groupSetting("permissions.", Property.ExtensionScope); public static Setting SEND_BACKEND_ROLES_SETTING = Setting.boolSetting("send_backend_roles", false, Property.ExtensionScope); - - public static boolean isActionTraceEnabled() { return actionTrace.isTraceEnabled(); } @@ -1947,8 +1950,6 @@ public TokenManager getTokenManager() { return tokenManager; } - - public static class GuiceHolder implements LifecycleComponent { private static RepositoriesService repositoriesService; diff --git a/src/main/java/org/opensearch/security/action/onbehalf/CreateOnBehalfOfTokenAction.java b/src/main/java/org/opensearch/security/action/onbehalf/CreateOnBehalfOfTokenAction.java index 39d25cf619..96f7c13619 100644 --- a/src/main/java/org/opensearch/security/action/onbehalf/CreateOnBehalfOfTokenAction.java +++ b/src/main/java/org/opensearch/security/action/onbehalf/CreateOnBehalfOfTokenAction.java @@ -17,7 +17,6 @@ import java.util.Map; import java.util.Optional; import java.util.Set; -import java.util.stream.Collectors; import com.google.common.collect.ImmutableList; import org.greenrobot.eventbus.Subscribe; @@ -153,8 +152,8 @@ public void accept(RestChannel channel) throws Exception { user.getName(), service, tokenDuration, - new HashSet<>(mappedRoles), - new HashSet<>(user.getRoles()), + new HashSet<>(mappedRoles), + new HashSet<>(user.getRoles()), roleSecurityMode ); builder.field("authenticationToken", token); diff --git a/src/main/java/org/opensearch/security/auth/internal/NoOpAuthenticationBackend.java b/src/main/java/org/opensearch/security/auth/internal/NoOpAuthenticationBackend.java index 807312b3c8..299a1a4577 100644 --- a/src/main/java/org/opensearch/security/auth/internal/NoOpAuthenticationBackend.java +++ b/src/main/java/org/opensearch/security/auth/internal/NoOpAuthenticationBackend.java @@ -51,7 +51,6 @@ public User authenticate(final AuthCredentials credentials) { return user; } - @Override public boolean exists(User user) { return true; diff --git a/src/main/java/org/opensearch/security/authtoken/jwt/EncryptionDecryptionUtil.java b/src/main/java/org/opensearch/security/authtoken/jwt/EncryptionDecryptionUtil.java index 3ac585c2d6..77696fd743 100644 --- a/src/main/java/org/opensearch/security/authtoken/jwt/EncryptionDecryptionUtil.java +++ b/src/main/java/org/opensearch/security/authtoken/jwt/EncryptionDecryptionUtil.java @@ -70,5 +70,6 @@ private CipherMode(final int opmode) { } } - //TODO: RYAN PUT YOUR LOGIC HERE TO CONNECT WITH https://raw.githubusercontent.com/cwperks/security/bf22d4a4e7e716f818e4ce48767590a9f0e53f38/src/main/java/org/opensearch/security/authtoken/jwt/EncryptionDecryptionUtil.java + // TODO: RYAN PUT YOUR LOGIC HERE TO CONNECT WITH + // https://raw.githubusercontent.com/cwperks/security/bf22d4a4e7e716f818e4ce48767590a9f0e53f38/src/main/java/org/opensearch/security/authtoken/jwt/EncryptionDecryptionUtil.java } diff --git a/src/main/java/org/opensearch/security/authtoken/jwt/JwtVendor.java b/src/main/java/org/opensearch/security/authtoken/jwt/JwtVendor.java index 33a2c24981..df4d697987 100644 --- a/src/main/java/org/opensearch/security/authtoken/jwt/JwtVendor.java +++ b/src/main/java/org/opensearch/security/authtoken/jwt/JwtVendor.java @@ -12,8 +12,6 @@ package org.opensearch.security.authtoken.jwt; import java.time.Instant; -import java.util.Collection; -import java.util.List; import java.util.Optional; import java.util.Set; import java.util.function.LongSupplier; @@ -32,10 +30,7 @@ import org.apache.logging.log4j.Logger; import org.opensearch.common.settings.Settings; -import org.opensearch.extensions.ExtensionsSettings; -import org.opensearch.security.OpenSearchSecurityPlugin; import org.opensearch.security.ssl.util.ExceptionUtils; -import static org.opensearch.security.OpenSearchSecurityPlugin.SEND_BACKEND_ROLES_SETTING; public class JwtVendor { private static final Logger logger = LogManager.getLogger(JwtVendor.class); @@ -95,7 +90,7 @@ static JsonWebKey createJwkFromSettings(Settings settings) throws Exception { if (jwkSettings.isEmpty()) { throw new Exception( - "Settings for signing key is missing. Please specify at least the option signing_key with a shared secret." + "Settings for signing key is missing. Please specify at least the option signing_key with a shared secret." ); } @@ -110,13 +105,13 @@ static JsonWebKey createJwkFromSettings(Settings settings) throws Exception { } public String createJwt( - String issuer, - String subject, - String audience, - Integer expirySeconds, - Set roles, - Set backendRoles, - boolean roleSecurityMode + String issuer, + String subject, + String audience, + Integer expirySeconds, + Set roles, + Set backendRoles, + boolean roleSecurityMode ) throws Exception { final long nowAsMillis = timeProvider.getAsLong(); final Instant nowAsInstant = Instant.ofEpochMilli(timeProvider.getAsLong()); @@ -162,12 +157,12 @@ public String createJwt( if (logger.isDebugEnabled()) { logger.debug( - "Created JWT: " - + encodedJwt - + "\n" - + jsonMapReaderWriter.toJson(jwt.getJwsHeaders()) - + "\n" - + JwtUtils.claimsToJson(jwt.getClaims()) + "Created JWT: " + + encodedJwt + + "\n" + + jsonMapReaderWriter.toJson(jwt.getJwsHeaders()) + + "\n" + + JwtUtils.claimsToJson(jwt.getClaims()) ); } diff --git a/src/main/java/org/opensearch/security/identity/SecuritySubject.java b/src/main/java/org/opensearch/security/identity/SecuritySubject.java index 8b48ffe360..c7b0a755db 100644 --- a/src/main/java/org/opensearch/security/identity/SecuritySubject.java +++ b/src/main/java/org/opensearch/security/identity/SecuritySubject.java @@ -22,28 +22,28 @@ public class SecuritySubject implements Subject { - private ThreadContext threadContext; - - public SecuritySubject() {} - - public void setThreadContext(ThreadContext threadContext) { - this.threadContext = threadContext; - } - - @Override - public Principal getPrincipal() { - if (threadContext == null) { - return NamedPrincipal.UNAUTHENTICATED; - } - final User user = (User) threadContext.getTransient(ConfigConstants.OPENDISTRO_SECURITY_USER); - if (user == null) { - return NamedPrincipal.UNAUTHENTICATED; - } - return new NamedPrincipal(user.getName()); - } - - @Override - public void authenticate(AuthToken authToken) { - // TODO implement this - replace with logic from SecurityRestFilter - } + private ThreadContext threadContext; + + public SecuritySubject() {} + + public void setThreadContext(ThreadContext threadContext) { + this.threadContext = threadContext; + } + + @Override + public Principal getPrincipal() { + if (threadContext == null) { + return NamedPrincipal.UNAUTHENTICATED; + } + final User user = (User) threadContext.getTransient(ConfigConstants.OPENDISTRO_SECURITY_USER); + if (user == null) { + return NamedPrincipal.UNAUTHENTICATED; + } + return new NamedPrincipal(user.getName()); + } + + @Override + public void authenticate(AuthToken authToken) { + // TODO implement this - replace with logic from SecurityRestFilter + } } diff --git a/src/main/java/org/opensearch/security/identity/SecurityTokenManager.java b/src/main/java/org/opensearch/security/identity/SecurityTokenManager.java index f8a78f0491..81342da25b 100644 --- a/src/main/java/org/opensearch/security/identity/SecurityTokenManager.java +++ b/src/main/java/org/opensearch/security/identity/SecurityTokenManager.java @@ -26,83 +26,83 @@ public class SecurityTokenManager implements TokenManager { - public static Settings DEMO_SETTINGS = Settings.builder() - .put( - "signing_key", - Base64.getEncoder() - .encodeToString( - "This is my super secret that no one in the universe will ever be able to guess in a bajillion years".getBytes( - StandardCharsets.UTF_8 - ) - ) - ) - .put("encryption_key", Base64.getEncoder().encodeToString("encryptionKey".getBytes(StandardCharsets.UTF_8))) - .build(); + public static Settings DEMO_SETTINGS = Settings.builder() + .put( + "signing_key", + Base64.getEncoder() + .encodeToString( + "This is my super secret that no one in the universe will ever be able to guess in a bajillion years".getBytes( + StandardCharsets.UTF_8 + ) + ) + ) + .put("encryption_key", Base64.getEncoder().encodeToString("encryptionKey".getBytes(StandardCharsets.UTF_8))) + .build(); - private ConfigModel configModel; - private ClusterService cs; - private ThreadPool threadPool; - private UserService userService; + private ConfigModel configModel; + private ClusterService cs; + private ThreadPool threadPool; + private UserService userService; - public SecurityTokenManager(ClusterService cs, ThreadPool threadPool, UserService userService) { - this.cs = cs; - this.threadPool = threadPool; - this.userService = userService; - } + public SecurityTokenManager(ClusterService cs, ThreadPool threadPool, UserService userService) { + this.cs = cs; + this.threadPool = threadPool; + this.userService = userService; + } - private JwtVendor jwtVendor = new JwtVendor(DEMO_SETTINGS, Optional.empty()); + private JwtVendor jwtVendor = new JwtVendor(DEMO_SETTINGS, Optional.empty()); - @Override - public AuthToken issueOnBehalfOfToken(Subject subject, OnBehalfOfClaims claims) { - User user = threadPool.getThreadContext().getTransient(ConfigConstants.OPENDISTRO_SECURITY_USER); - if (user == null) { - throw new OpenSearchSecurityException("Cannot issue on behalf of token."); - } - if (Strings.isNullOrEmpty(claims.getAudience())) { - throw new OpenSearchSecurityException("Cannot issue on behalf of token without an audience claim."); - } + @Override + public AuthToken issueOnBehalfOfToken(Subject subject, OnBehalfOfClaims claims) { + User user = threadPool.getThreadContext().getTransient(ConfigConstants.OPENDISTRO_SECURITY_USER); + if (user == null) { + throw new OpenSearchSecurityException("Cannot issue on behalf of token."); + } + if (Strings.isNullOrEmpty(claims.getAudience())) { + throw new OpenSearchSecurityException("Cannot issue on behalf of token without an audience claim."); + } - final TransportAddress caller = threadPool.getThreadContext().getTransient(ConfigConstants.OPENDISTRO_SECURITY_REMOTE_ADDRESS); + final TransportAddress caller = threadPool.getThreadContext().getTransient(ConfigConstants.OPENDISTRO_SECURITY_REMOTE_ADDRESS); - Set mappedRoles = mapRoles(user, caller); - String encodedJwt = null; + Set mappedRoles = mapRoles(user, caller); + String encodedJwt = null; - try { - encodedJwt = jwtVendor.createJwt( - cs.getClusterName().value(), - user.getName(), - claims.getAudience(), - 300, - mappedRoles, - user.getRoles(), - false - ); - } catch (Exception e) { - throw new RuntimeException(e); - } - return new BearerAuthToken(encodedJwt); - } + try { + encodedJwt = jwtVendor.createJwt( + cs.getClusterName().value(), + user.getName(), + claims.getAudience(), + 300, + mappedRoles, + user.getRoles(), + false + ); + } catch (Exception e) { + throw new RuntimeException(e); + } + return new BearerAuthToken(encodedJwt); + } - @Override - public AuthToken issueServiceAccountToken(String extensionUniqueId) throws OpenSearchSecurityException { - try { - return new BasicAuthToken(this.userService.generateAuthToken(extensionUniqueId)); - } catch (Exception e) { - throw new RuntimeException(e); - } - } + @Override + public AuthToken issueServiceAccountToken(String extensionUniqueId) throws OpenSearchSecurityException { + try { + return new BasicAuthToken(this.userService.generateAuthToken(extensionUniqueId)); + } catch (Exception e) { + throw new RuntimeException(e); + } + } - @Override - public Subject authenticateToken(AuthToken authToken) { - return null; - } + @Override + public Subject authenticateToken(AuthToken authToken) { + return null; + } - public Set mapRoles(final User user, final TransportAddress caller) { - return this.configModel.mapSecurityRoles(user, caller); - } + public Set mapRoles(final User user, final TransportAddress caller) { + return this.configModel.mapSecurityRoles(user, caller); + } - @Subscribe - public void onConfigModelChanged(ConfigModel configModel) { - this.configModel = configModel; - } + @Subscribe + public void onConfigModelChanged(ConfigModel configModel) { + this.configModel = configModel; + } } diff --git a/src/main/java/org/opensearch/security/privileges/PrivilegesEvaluator.java b/src/main/java/org/opensearch/security/privileges/PrivilegesEvaluator.java index 7287633613..7c3c6999fc 100644 --- a/src/main/java/org/opensearch/security/privileges/PrivilegesEvaluator.java +++ b/src/main/java/org/opensearch/security/privileges/PrivilegesEvaluator.java @@ -109,7 +109,7 @@ public class PrivilegesEvaluator { private static final WildcardMatcher ACTION_MATCHER = WildcardMatcher.from("indices:data/read/*search*"); private static final Pattern DNFOF_PATTERNS = Pattern.compile( - "indices:(data/read/.*|(admin/(mappings/fields/get.*|shards/search_shards|resolve/index)))" + "indices:(data/read/.*|(admin/(mappings/fields/get.*|shards/search_shards|resolve/index)))" ); private static final IndicesOptions ALLOW_EMPTY = IndicesOptions.fromOptions(true, true, false, false); @@ -140,17 +140,17 @@ public class PrivilegesEvaluator { private final NamedXContentRegistry namedXContentRegistry; public PrivilegesEvaluator( - final ClusterService clusterService, - final ThreadPool threadPool, - final ConfigurationRepository configurationRepository, - final IndexNameExpressionResolver resolver, - AuditLog auditLog, - final Settings settings, - final PrivilegesInterceptor privilegesInterceptor, - final ClusterInfoHolder clusterInfoHolder, - final IndexResolverReplacer irr, - boolean dlsFlsEnabled, - NamedXContentRegistry namedXContentRegistry + final ClusterService clusterService, + final ThreadPool threadPool, + final ConfigurationRepository configurationRepository, + final IndexNameExpressionResolver resolver, + AuditLog auditLog, + final Settings settings, + final PrivilegesInterceptor privilegesInterceptor, + final ClusterInfoHolder clusterInfoHolder, + final IndexResolverReplacer irr, + boolean dlsFlsEnabled, + NamedXContentRegistry namedXContentRegistry ) { super(); @@ -162,8 +162,8 @@ public PrivilegesEvaluator( this.privilegesInterceptor = privilegesInterceptor; this.checkSnapshotRestoreWritePrivileges = settings.getAsBoolean( - ConfigConstants.SECURITY_CHECK_SNAPSHOT_RESTORE_WRITE_PRIVILEGES, - ConfigConstants.SECURITY_DEFAULT_CHECK_SNAPSHOT_RESTORE_WRITE_PRIVILEGES + ConfigConstants.SECURITY_CHECK_SNAPSHOT_RESTORE_WRITE_PRIVILEGES, + ConfigConstants.SECURITY_DEFAULT_CHECK_SNAPSHOT_RESTORE_WRITE_PRIVILEGES ); this.clusterInfoHolder = clusterInfoHolder; @@ -192,7 +192,7 @@ private SecurityRoles getSecurityRoles(Set roles) { SecurityRoles securityRoles = configModel.getSecurityRoles().filter(roles); User authenticatedUser = threadContext.getTransient(ConfigConstants.OPENDISTRO_SECURITY_USER); Optional matchingExtension = OpenSearchSecurityPlugin.GuiceHolder.getExtensionsManager() - .lookupExtensionSettingsById(authenticatedUser.getName()); + .lookupExtensionSettingsById(authenticatedUser.getName()); if (matchingExtension.isPresent()) { Settings permissions = (Settings) matchingExtension.get().getAdditionalSettings().get(PERMISSIONS_SETTING); List indexPerms = permissions.getNestedListOfSettings("index_permissions"); @@ -248,11 +248,11 @@ private void setUserInfoInThreadContext(User user) { } public PrivilegesEvaluatorResponse evaluate( - final User user, - String action0, - final ActionRequest request, - Task task, - final Set injectedRoles + final User user, + String action0, + final ActionRequest request, + Task task, + final Set injectedRoles ) { if (!isInitialized()) { @@ -276,7 +276,7 @@ public PrivilegesEvaluatorResponse evaluate( final TransportAddress caller = threadContext.getTransient(ConfigConstants.OPENDISTRO_SECURITY_REMOTE_ADDRESS); Set mappedRoles = (injectedRoles == null) ? mapRoles(user, caller) : injectedRoles; final String injectedRolesValidationString = threadContext.getTransient( - ConfigConstants.OPENDISTRO_SECURITY_INJECTED_ROLES_VALIDATION + ConfigConstants.OPENDISTRO_SECURITY_INJECTED_ROLES_VALIDATION ); if (injectedRolesValidationString != null) { HashSet injectedRolesValidationSet = new HashSet<>(Arrays.asList(injectedRolesValidationString.split(","))); @@ -314,11 +314,11 @@ public PrivilegesEvaluatorResponse evaluate( presponse.missingPrivileges.add(action0); presponse.allowed = false; log.info( - "No cluster-level perm match for {} [Action [{}]] [RolesChecked {}]. No permissions for {}", - user, - action0, - securityRoles.getRoleNames(), - presponse.missingPrivileges + "No cluster-level perm match for {} [Action [{}]] [RolesChecked {}]. No permissions for {}", + user, + action0, + securityRoles.getRoleNames(), + presponse.missingPrivileges ); } else { presponse.allowed = true; @@ -361,11 +361,11 @@ public PrivilegesEvaluatorResponse evaluate( } presponse.evaluatedDlsFlsConfig = getSecurityRoles(mappedRoles).getDlsFls( - user, - dfmEmptyOverwritesAll, - resolver, - clusterService, - namedXContentRegistry + user, + dfmEmptyOverwritesAll, + resolver, + clusterService, + namedXContentRegistry ); if (isClusterPerm(action0)) { @@ -373,12 +373,12 @@ public PrivilegesEvaluatorResponse evaluate( presponse.missingPrivileges.add(action0); presponse.allowed = false; log.info( - "No cluster-level perm match for {} {} [Action [{}]] [RolesChecked {}]. No permissions for {}", - user, - requestedResolved, - action0, - securityRoles.getRoleNames(), - presponse.missingPrivileges + "No cluster-level perm match for {} {} [Action [{}]] [RolesChecked {}]. No permissions for {}", + user, + requestedResolved, + action0, + securityRoles.getRoleNames(), + presponse.missingPrivileges ); return presponse; } else { @@ -391,12 +391,12 @@ public PrivilegesEvaluatorResponse evaluate( if (privilegesInterceptor.getClass() != PrivilegesInterceptor.class) { final PrivilegesInterceptor.ReplaceResult replaceResult = privilegesInterceptor.replaceDashboardsIndex( - request, - action0, - user, - dcm, - requestedResolved, - mapTenants(user, mappedRoles) + request, + action0, + user, + dcm, + requestedResolved, + mapTenants(user, mappedRoles) ); if (isDebugEnabled) { @@ -423,11 +423,11 @@ public PrivilegesEvaluatorResponse evaluate( } Set reduced = securityRoles.reduce( - requestedResolved, - user, - new String[] { action0 }, - resolver, - clusterService + requestedResolved, + user, + new String[] { action0 }, + resolver, + clusterService ); if (reduced.isEmpty()) { @@ -458,7 +458,7 @@ public PrivilegesEvaluatorResponse evaluate( // term aggregations if (termsAggregationEvaluator.evaluate(requestedResolved, request, clusterService, user, securityRoles, resolver, presponse) - .isComplete()) { + .isComplete()) { return presponse; } @@ -482,12 +482,12 @@ public PrivilegesEvaluatorResponse evaluate( if (privilegesInterceptor.getClass() != PrivilegesInterceptor.class) { final PrivilegesInterceptor.ReplaceResult replaceResult = privilegesInterceptor.replaceDashboardsIndex( - request, - action0, - user, - dcm, - requestedResolved, - mapTenants(user, mappedRoles) + request, + action0, + user, + dcm, + requestedResolved, + mapTenants(user, mappedRoles) ); if (isDebugEnabled) { @@ -559,12 +559,12 @@ public PrivilegesEvaluatorResponse evaluate( if (!permGiven) { log.info( - "No {}-level perm match for {} {} [Action [{}]] [RolesChecked {}]", - "index", - user, - requestedResolved, - action0, - securityRoles.getRoleNames() + "No {}-level perm match for {} {} [Action [{}]] [RolesChecked {}]", + "index", + user, + requestedResolved, + action0, + securityRoles.getRoleNames() ); log.info("No permissions for {}", presponse.missingPrivileges); } else { @@ -694,14 +694,14 @@ private Set evaluateAdditionalIndexPermissions(final ActionRequest reque public static boolean isClusterPerm(String action0) { return (action0.startsWith("cluster:") - || action0.startsWith("indices:admin/template/") - || action0.startsWith("indices:admin/index_template/") - || action0.startsWith(SearchScrollAction.NAME) - || (action0.equals(BulkAction.NAME)) - || (action0.equals(MultiGetAction.NAME)) - || (action0.startsWith(MultiSearchAction.NAME)) - || (action0.equals(MultiTermVectorsAction.NAME)) - || (action0.equals(ReindexAction.NAME)) + || action0.startsWith("indices:admin/template/") + || action0.startsWith("indices:admin/index_template/") + || action0.startsWith(SearchScrollAction.NAME) + || (action0.equals(BulkAction.NAME)) + || (action0.equals(MultiGetAction.NAME)) + || (action0.startsWith(MultiSearchAction.NAME)) + || (action0.equals(MultiTermVectorsAction.NAME)) + || (action0.equals(ReindexAction.NAME)) ); } @@ -777,10 +777,10 @@ public Iterator iterator() { if (filteredAliases.size() > 1 && ACTION_MATCHER.test(action)) { // TODO add queries as dls queries (works only if dls module is installed) log.error( - "More than one ({}) filtered alias found for same index ({}). This is currently not supported. Aliases: {}", - filteredAliases.size(), - indexMetaData.getIndex().getName(), - toString(filteredAliases) + "More than one ({}) filtered alias found for same index ({}). This is currently not supported. Aliases: {}", + filteredAliases.size(), + indexMetaData.getIndex().getName(), + toString(filteredAliases) ); return true; } diff --git a/src/main/java/org/opensearch/security/privileges/SecurityIndexAccessEvaluator.java b/src/main/java/org/opensearch/security/privileges/SecurityIndexAccessEvaluator.java index 3f9b92db02..209e6e3773 100644 --- a/src/main/java/org/opensearch/security/privileges/SecurityIndexAccessEvaluator.java +++ b/src/main/java/org/opensearch/security/privileges/SecurityIndexAccessEvaluator.java @@ -69,30 +69,30 @@ public class SecurityIndexAccessEvaluator { private final boolean systemIndexEnabled; public SecurityIndexAccessEvaluator( - final Settings settings, - AuditLog auditLog, - IndexResolverReplacer irr, - ThreadContext threadContext + final Settings settings, + AuditLog auditLog, + IndexResolverReplacer irr, + ThreadContext threadContext ) { this.securityIndex = settings.get( - ConfigConstants.SECURITY_CONFIG_INDEX_NAME, - ConfigConstants.OPENDISTRO_SECURITY_DEFAULT_CONFIG_INDEX + ConfigConstants.SECURITY_CONFIG_INDEX_NAME, + ConfigConstants.OPENDISTRO_SECURITY_DEFAULT_CONFIG_INDEX ); this.auditLog = auditLog; this.irr = irr; this.threadContext = threadContext; this.filterSecurityIndex = settings.getAsBoolean(ConfigConstants.SECURITY_FILTER_SECURITYINDEX_FROM_ALL_REQUESTS, false); this.systemIndexMatcher = WildcardMatcher.from( - settings.getAsList(ConfigConstants.SECURITY_SYSTEM_INDICES_KEY, ConfigConstants.SECURITY_SYSTEM_INDICES_DEFAULT) + settings.getAsList(ConfigConstants.SECURITY_SYSTEM_INDICES_KEY, ConfigConstants.SECURITY_SYSTEM_INDICES_DEFAULT) ); this.systemIndexEnabled = settings.getAsBoolean( - ConfigConstants.SECURITY_SYSTEM_INDICES_ENABLED_KEY, - ConfigConstants.SECURITY_SYSTEM_INDICES_ENABLED_DEFAULT + ConfigConstants.SECURITY_SYSTEM_INDICES_ENABLED_KEY, + ConfigConstants.SECURITY_SYSTEM_INDICES_ENABLED_DEFAULT ); final boolean restoreSecurityIndexEnabled = settings.getAsBoolean( - ConfigConstants.SECURITY_UNSUPPORTED_RESTORE_SECURITYINDEX_ENABLED, - false + ConfigConstants.SECURITY_UNSUPPORTED_RESTORE_SECURITYINDEX_ENABLED, + false ); final List securityIndexDeniedActionPatternsList = new ArrayList(); @@ -110,16 +110,16 @@ public SecurityIndexAccessEvaluator( securityIndexDeniedActionPatternsListNoSnapshot.add("cluster:admin/snapshot/restore*"); securityDeniedActionMatcher = WildcardMatcher.from( - restoreSecurityIndexEnabled ? securityIndexDeniedActionPatternsList : securityIndexDeniedActionPatternsListNoSnapshot + restoreSecurityIndexEnabled ? securityIndexDeniedActionPatternsList : securityIndexDeniedActionPatternsListNoSnapshot ); } public PrivilegesEvaluatorResponse evaluate( - final ActionRequest request, - final Task task, - final String action, - final Resolved requestedResolved, - final PrivilegesEvaluatorResponse presponse + final ActionRequest request, + final Task task, + final String action, + final Resolved requestedResolved, + final PrivilegesEvaluatorResponse presponse ) { System.out.println("SecurityIndexAccessEvaluator"); final boolean isDebugEnabled = log.isDebugEnabled(); @@ -130,11 +130,11 @@ public PrivilegesEvaluatorResponse evaluate( irr.replace(request, false, "*", "-" + securityIndex); if (isDebugEnabled) { log.debug( - "Filtered '{}'from {}, resulting list with *,-{} is {}", - securityIndex, - requestedResolved, - securityIndex, - irr.resolveRequest(request) + "Filtered '{}'from {}, resulting list with *,-{} is {}", + securityIndex, + requestedResolved, + securityIndex, + irr.resolveRequest(request) ); } return presponse; @@ -164,18 +164,18 @@ public PrivilegesEvaluatorResponse evaluate( } else { User authenticatedUser = threadContext.getTransient(ConfigConstants.OPENDISTRO_SECURITY_USER); Optional matchingExtension = OpenSearchSecurityPlugin.GuiceHolder.getExtensionsManager() - .lookupExtensionSettingsById(authenticatedUser.getName()); + .lookupExtensionSettingsById(authenticatedUser.getName()); auditLog.logSecurityIndexAttempt(request, action, task); final String foundSystemIndexes = getProtectedIndexes(requestedResolved).stream().collect(Collectors.joining(", ")); if (matchingExtension.isPresent()) { List reservedIndices = (List) matchingExtension.get() - .getAdditionalSettings() - .get(RESERVED_INDICES_SETTING); + .getAdditionalSettings() + .get(RESERVED_INDICES_SETTING); if (matchAllReservedIndices(requestedResolved, reservedIndices)) { log.info( - "{} for '{}' index is allowed for service account of extension reserving the indices", - action, - foundSystemIndexes + "{} for '{}' index is allowed for service account of extension reserving the indices", + action, + foundSystemIndexes ); presponse.allowed = true; return presponse.markComplete(); @@ -189,8 +189,8 @@ public PrivilegesEvaluatorResponse evaluate( } if (requestedResolved.isLocalAll() - || requestedResolved.getAllIndices().contains(securityIndex) - || matchAnySystemIndices(requestedResolved)) { + || requestedResolved.getAllIndices().contains(securityIndex) + || matchAnySystemIndices(requestedResolved)) { if (request instanceof SearchRequest) { ((SearchRequest) request).requestCache(Boolean.FALSE); @@ -215,9 +215,9 @@ private boolean matchAnySystemIndices(final Resolved requestedResolved) { private List getProtectedIndexes(final Resolved requestedResolved) { final List protectedIndexes = requestedResolved.getAllIndices() - .stream() - .filter(securityIndex::equals) - .collect(Collectors.toList()); + .stream() + .filter(securityIndex::equals) + .collect(Collectors.toList()); if (systemIndexEnabled) { protectedIndexes.addAll(systemIndexMatcher.getMatchAny(requestedResolved.getAllIndices(), Collectors.toList())); } @@ -226,9 +226,9 @@ private List getProtectedIndexes(final Resolved requestedResolved) { private boolean matchAllReservedIndices(final Resolved requestedResolved, final List reservedIndices) { final List requestedIndexes = requestedResolved.getAllIndices() - .stream() - .filter(securityIndex::equals) - .collect(Collectors.toList()); + .stream() + .filter(securityIndex::equals) + .collect(Collectors.toList()); if (systemIndexEnabled) { return reservedIndices.containsAll(requestedIndexes); } diff --git a/src/main/java/org/opensearch/security/securityconf/DynamicConfigModelV6.java b/src/main/java/org/opensearch/security/securityconf/DynamicConfigModelV6.java index 78344d0451..e5308aa574 100644 --- a/src/main/java/org/opensearch/security/securityconf/DynamicConfigModelV6.java +++ b/src/main/java/org/opensearch/security/securityconf/DynamicConfigModelV6.java @@ -211,7 +211,7 @@ public Multimap> getAuthBackendClientBlockRe public Settings getDynamicOnBehalfOfSettings() { return Settings.EMPTY; } - + private void buildAAA() { final SortedSet restAuthDomains0 = new TreeSet<>(); diff --git a/src/main/java/org/opensearch/security/securityconf/DynamicConfigModelV7.java b/src/main/java/org/opensearch/security/securityconf/DynamicConfigModelV7.java index 62e69e338d..00c4d994b5 100644 --- a/src/main/java/org/opensearch/security/securityconf/DynamicConfigModelV7.java +++ b/src/main/java/org/opensearch/security/securityconf/DynamicConfigModelV7.java @@ -86,7 +86,13 @@ public class DynamicConfigModelV7 extends DynamicConfigModel { private List> ipClientBlockRegistries; private Multimap> authBackendClientBlockRegistries; - public DynamicConfigModelV7(ConfigV7 config, Settings opensearchSettings, Path configPath, InternalAuthenticationBackend iab, ClusterInfoHolder cih) { + public DynamicConfigModelV7( + ConfigV7 config, + Settings opensearchSettings, + Path configPath, + InternalAuthenticationBackend iab, + ClusterInfoHolder cih + ) { super(); this.config = config; this.opensearchSettings = opensearchSettings; @@ -219,8 +225,8 @@ public Multimap> getAuthBackendClientBlockRe @Override public Settings getDynamicOnBehalfOfSettings() { return Settings.builder() - .put(Settings.builder().loadFromSource(config.dynamic.on_behalf_of.configAsJson(), XContentType.JSON).build()) - .build(); + .put(Settings.builder().loadFromSource(config.dynamic.on_behalf_of.configAsJson(), XContentType.JSON).build()) + .build(); } private void buildAAA() { @@ -380,21 +386,21 @@ private void buildAAA() { Settings oboSettings = getDynamicOnBehalfOfSettings(); if (oboSettings.get("signing_key") != null && oboSettings.get("encryption_key") != null) { final AuthDomain _ad = new AuthDomain( - new NoOpAuthenticationBackend(Settings.EMPTY, null), - new OnBehalfOfAuthenticator(getDynamicOnBehalfOfSettings(), this.cih.getClusterName()), - false, - -1 ); + new NoOpAuthenticationBackend(Settings.EMPTY, null), + new OnBehalfOfAuthenticator(getDynamicOnBehalfOfSettings(), this.cih.getClusterName()), + false, + -1 + ); restAuthDomains0.add(_ad); } final AuthDomain _ad = new AuthDomain( - new NoOpAuthenticationBackend(Settings.EMPTY, null), - new OnBehalfOfAuthenticator(DEMO_SETTINGS, this.cih.getClusterName()), - false, - -1 + new NoOpAuthenticationBackend(Settings.EMPTY, null), + new OnBehalfOfAuthenticator(DEMO_SETTINGS, this.cih.getClusterName()), + false, + -1 ); - restAuthDomains0.add(_ad); List originalDestroyableComponents = destroyableComponents; diff --git a/src/main/java/org/opensearch/security/securityconf/impl/v6/ConfigV6.java b/src/main/java/org/opensearch/security/securityconf/impl/v6/ConfigV6.java index 20e58a5bb7..86054be6cc 100644 --- a/src/main/java/org/opensearch/security/securityconf/impl/v6/ConfigV6.java +++ b/src/main/java/org/opensearch/security/securityconf/impl/v6/ConfigV6.java @@ -389,11 +389,11 @@ public String getSigningKey() { public void setSigningKey(String signingKey) { this.signingKey = signingKey; } + public String getEncryptionKey() { return encryptionKey; } - public void setEncryptionKey(String encryptionKey) { this.encryptionKey = encryptionKey; } diff --git a/src/main/java/org/opensearch/security/securityconf/impl/v7/ConfigV7.java b/src/main/java/org/opensearch/security/securityconf/impl/v7/ConfigV7.java index 6f95d81d47..f50723e823 100644 --- a/src/main/java/org/opensearch/security/securityconf/impl/v7/ConfigV7.java +++ b/src/main/java/org/opensearch/security/securityconf/impl/v7/ConfigV7.java @@ -66,7 +66,6 @@ public ConfigV7(ConfigV6 c6) { dynamic.hosts_resolver_mode = c6.dynamic.hosts_resolver_mode; dynamic.transport_userrname_attribute = c6.dynamic.transport_userrname_attribute; - dynamic.kibana = new Kibana(); dynamic.kibana.index = c6.dynamic.kibana.index; diff --git a/src/main/java/org/opensearch/security/ssl/DefaultSecurityKeyStore.java b/src/main/java/org/opensearch/security/ssl/DefaultSecurityKeyStore.java index 283b82d519..fb72ffe119 100644 --- a/src/main/java/org/opensearch/security/ssl/DefaultSecurityKeyStore.java +++ b/src/main/java/org/opensearch/security/ssl/DefaultSecurityKeyStore.java @@ -907,7 +907,7 @@ private void initEnabledSSLCiphers() { List jdkSupportedProtocols = null; try { final SSLContext serverContext = SSLContext.getInstance("TLS"); - TrustManager[] trustManagers = new TrustManager[] { new AllowAnyTrustManager()}; + TrustManager[] trustManagers = new TrustManager[] { new AllowAnyTrustManager() }; serverContext.init(null, trustManagers, null); engine = serverContext.createSSLEngine(); jdkSupportedCiphers = Arrays.asList(engine.getEnabledCipherSuites()); diff --git a/src/main/java/org/opensearch/security/user/AuthCredentials.java b/src/main/java/org/opensearch/security/user/AuthCredentials.java index a92e681f12..b28722292a 100644 --- a/src/main/java/org/opensearch/security/user/AuthCredentials.java +++ b/src/main/java/org/opensearch/security/user/AuthCredentials.java @@ -229,6 +229,7 @@ public String toString() { public Set getSecurityRoles() { return new HashSet(securityRoles); } + /** * * @return Defensive copy of the roles this user is member of. diff --git a/src/main/java/org/opensearch/security/util/KeyUtil.java b/src/main/java/org/opensearch/security/util/KeyUtil.java index e916e1da20..93d42425c6 100644 --- a/src/main/java/org/opensearch/security/util/KeyUtil.java +++ b/src/main/java/org/opensearch/security/util/KeyUtil.java @@ -45,7 +45,7 @@ public JwtParser run() { Key key = null; final String minimalKeyFormat = signingKey.replace("-----BEGIN PUBLIC KEY-----\n", "") - .replace("-----END PUBLIC KEY-----", ""); + .replace("-----END PUBLIC KEY-----", ""); final byte[] decoded = Base64.getDecoder().decode(minimalKeyFormat); @@ -97,7 +97,7 @@ public JwtParserBuilder run() { Key key = null; final String minimalKeyFormat = signingKey.replace("-----BEGIN PUBLIC KEY-----\n", "") - .replace("-----END PUBLIC KEY-----", ""); + .replace("-----END PUBLIC KEY-----", ""); final byte[] decoded = Base64.getDecoder().decode(minimalKeyFormat); @@ -130,12 +130,10 @@ public JwtParserBuilder run() { } private static PublicKey getPublicKey(final byte[] keyBytes, final String algo) throws NoSuchAlgorithmException, - InvalidKeySpecException { + InvalidKeySpecException { X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes); KeyFactory kf = KeyFactory.getInstance(algo); return kf.generatePublic(spec); } - - } diff --git a/src/test/java/org/opensearch/security/privileges/SecurityIndexAccessEvaluatorTest.java b/src/test/java/org/opensearch/security/privileges/SecurityIndexAccessEvaluatorTest.java index eb5f21a888..1d96730fde 100644 --- a/src/test/java/org/opensearch/security/privileges/SecurityIndexAccessEvaluatorTest.java +++ b/src/test/java/org/opensearch/security/privileges/SecurityIndexAccessEvaluatorTest.java @@ -66,13 +66,13 @@ public class SecurityIndexAccessEvaluatorTest { @Before public void before() { evaluator = new SecurityIndexAccessEvaluator( - Settings.EMPTY.builder() - .put("plugins.security.system_indices.indices", ".test") - .put("plugins.security.system_indices.enabled", true) - .build(), - auditLog, - irr, - threadContext + Settings.EMPTY.builder() + .put("plugins.security.system_indices.indices", ".test") + .put("plugins.security.system_indices.enabled", true) + .build(), + auditLog, + irr, + threadContext ); evaluator.log = log; @@ -149,11 +149,11 @@ public void protectedActionSystemIndex() { private Resolved createResolved(final String... indexes) { return new Resolved( - ImmutableSet.of(), - ImmutableSet.copyOf(indexes), - ImmutableSet.copyOf(indexes), - ImmutableSet.of(), - IndicesOptions.STRICT_EXPAND_OPEN + ImmutableSet.of(), + ImmutableSet.copyOf(indexes), + ImmutableSet.copyOf(indexes), + ImmutableSet.of(), + IndicesOptions.STRICT_EXPAND_OPEN ); } }