diff --git a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/async/DeleteAsyncResultsService.java b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/async/DeleteAsyncResultsService.java index 2aa26d323dbfa..d306f9d078d40 100644 --- a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/async/DeleteAsyncResultsService.java +++ b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/async/DeleteAsyncResultsService.java @@ -55,7 +55,7 @@ private void hasCancelTaskPrivilegeAsync(Consumer consumer) { final Authentication current = store.getSecurityContext().getAuthentication(); if (current != null) { HasPrivilegesRequest req = new HasPrivilegesRequest(); - req.username(current.getUser().principal()); + req.username(current.getEffectiveSubject().getUser().principal()); req.clusterPrivileges(ClusterPrivilegeResolver.CANCEL_TASK.name()); req.indexPrivileges(new RoleDescriptor.IndicesPrivileges[] {}); req.applicationPrivileges(new RoleDescriptor.ApplicationResourcePrivileges[] {}); diff --git a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/SecurityContext.java b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/SecurityContext.java index 54ea6acd7d3e2..744c079845095 100644 --- a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/SecurityContext.java +++ b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/SecurityContext.java @@ -68,7 +68,7 @@ public User requireUser() { @Nullable public User getUser() { Authentication authentication = getAuthentication(); - return authentication == null ? null : authentication.getUser(); + return authentication == null ? null : authentication.getEffectiveSubject().getUser(); } /** Returns the authentication information, or null if the current request has no authentication info. */ diff --git a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/action/oidc/OpenIdConnectAuthenticateResponse.java b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/action/oidc/OpenIdConnectAuthenticateResponse.java index c8e63556e5f51..e51a0beb20630 100644 --- a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/action/oidc/OpenIdConnectAuthenticateResponse.java +++ b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/action/oidc/OpenIdConnectAuthenticateResponse.java @@ -28,7 +28,7 @@ public OpenIdConnectAuthenticateResponse( String refreshTokenString, TimeValue expiresIn ) { - this.principal = authentication.getUser().principal(); + this.principal = authentication.getEffectiveSubject().getUser().principal(); ; this.accessTokenString = accessTokenString; this.refreshTokenString = refreshTokenString; diff --git a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/action/saml/SamlAuthenticateResponse.java b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/action/saml/SamlAuthenticateResponse.java index a3963d6e7b3c9..8877cf2667294 100644 --- a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/action/saml/SamlAuthenticateResponse.java +++ b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/action/saml/SamlAuthenticateResponse.java @@ -43,7 +43,7 @@ public SamlAuthenticateResponse(StreamInput in) throws IOException { } public SamlAuthenticateResponse(Authentication authentication, String tokenString, String refreshToken, TimeValue expiresIn) { - this.principal = authentication.getUser().principal(); + this.principal = authentication.getEffectiveSubject().getUser().principal(); this.realm = authentication.getAuthenticatedBy().getName(); this.tokenString = tokenString; this.refreshToken = refreshToken; diff --git a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/authc/Authentication.java b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/authc/Authentication.java index 3cb92eebec14a..af8f8021380a9 100644 --- a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/authc/Authentication.java +++ b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/authc/Authentication.java @@ -167,14 +167,6 @@ public boolean isRunAs() { return authenticatingSubject != effectiveSubject; } - /** - * Use {@code getEffectiveSubject().getUser()} instead. - */ - @Deprecated - public User getUser() { - return effectiveSubject.getUser(); - } - /** * Use {@code getAuthenticatingSubject().getRealm()} instead. */ @@ -321,8 +313,8 @@ public Authentication token() { public Authentication maybeAddAnonymousRoles(@Nullable AnonymousUser anonymousUser) { final boolean shouldAddAnonymousRoleNames = anonymousUser != null && anonymousUser.enabled() - && false == anonymousUser.equals(getUser()) - && false == User.isInternal(getUser()) + && false == anonymousUser.equals(getEffectiveSubject().getUser()) + && false == User.isInternal(getEffectiveSubject().getUser()) && false == isApiKey() && false == isServiceAccount(); @@ -334,7 +326,7 @@ public Authentication maybeAddAnonymousRoles(@Nullable AnonymousUser anonymousUs if (anonymousUser.roles().length == 0) { throw new IllegalStateException("anonymous is only enabled when the anonymous user has roles"); } - final String[] allRoleNames = ArrayUtils.concat(getUser().roles(), anonymousUser.roles()); + final String[] allRoleNames = ArrayUtils.concat(getEffectiveSubject().getUser().roles(), anonymousUser.roles()); if (isRunAs()) { final User user = effectiveSubject.getUser(); @@ -433,7 +425,7 @@ public boolean supportsRunAs(@Nullable AnonymousUser anonymousUser) { // There is no reason for internal users to run-as. This check prevents either internal user itself // or a token created for it (though no such thing in current code) to run-as. - if (User.isInternal(getUser())) { + if (User.isInternal(getEffectiveSubject().getUser())) { return false; } @@ -449,7 +441,7 @@ public boolean supportsRunAs(@Nullable AnonymousUser anonymousUser) { // Also, if anonymous access is disabled or anonymous username, roles are changed after the token is created. // Should we still consider the token being created by an anonymous user which is now different from the new // anonymous user? - if (getUser().equals(anonymousUser)) { + if (getEffectiveSubject().getUser().equals(anonymousUser)) { assert ANONYMOUS_REALM_TYPE.equals(getAuthenticatingSubject().getRealm().getType()) && ANONYMOUS_REALM_NAME.equals(getAuthenticatingSubject().getRealm().getName()); return false; diff --git a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/authc/support/SecondaryAuthentication.java b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/authc/support/SecondaryAuthentication.java index 0fccacb23d049..d83f8e08a87f1 100644 --- a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/authc/support/SecondaryAuthentication.java +++ b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/authc/support/SecondaryAuthentication.java @@ -58,7 +58,7 @@ public Authentication getAuthentication() { } public User getUser() { - return authentication.getUser(); + return authentication.getEffectiveSubject().getUser(); } public T execute(Function body) { diff --git a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/authz/privilege/ManageOwnApiKeyClusterPrivilege.java b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/authz/privilege/ManageOwnApiKeyClusterPrivilege.java index 42975182c4106..c644db8937802 100644 --- a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/authz/privilege/ManageOwnApiKeyClusterPrivilege.java +++ b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/authz/privilege/ManageOwnApiKeyClusterPrivilege.java @@ -142,7 +142,7 @@ private static boolean checkIfUserIsOwnerOfApiKeys( } else if (ownedByAuthenticatedUser) { return true; } else if (Strings.hasText(username) && Strings.hasText(realmName)) { - if (false == username.equals(authentication.getUser().principal())) { + if (false == username.equals(authentication.getEffectiveSubject().getUser().principal())) { return false; } RealmDomain domain = authentication.getSourceRealm().getDomain(); diff --git a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/execution/WatchExecutionContext.java b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/execution/WatchExecutionContext.java index fa98a6ffa6e67..f400b3c818ef1 100644 --- a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/execution/WatchExecutionContext.java +++ b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/execution/WatchExecutionContext.java @@ -270,7 +270,7 @@ public static String getUsernameFromWatch(Watch watch) throws IOException { String header = watch.status().getHeaders().get(AuthenticationField.AUTHENTICATION_KEY); if (header != null) { Authentication auth = AuthenticationContextSerializer.decode(header); - return auth.getUser().principal(); + return auth.getEffectiveSubject().getUser().principal(); } } return null; diff --git a/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ClientHelperTests.java b/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ClientHelperTests.java index 06fc5842f11ef..3d1c119070891 100644 --- a/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ClientHelperTests.java +++ b/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ClientHelperTests.java @@ -455,14 +455,14 @@ public void testGetPersistableSafeSecurityHeaders() throws IOException { headers2.get(AuthenticationField.AUTHENTICATION_KEY) ); assertThat(rewrittenAuth.getEffectiveSubject().getVersion(), equalTo(previousVersion)); - assertThat(rewrittenAuth.getUser(), equalTo(authentication.getUser())); + assertThat(rewrittenAuth.getEffectiveSubject().getUser(), equalTo(authentication.getEffectiveSubject().getUser())); } if (hasSecondaryAuthHeader) { final Authentication rewrittenSecondaryAuth = AuthenticationContextSerializer.decode( headers2.get(SecondaryAuthentication.THREAD_CTX_KEY) ); assertThat(rewrittenSecondaryAuth.getEffectiveSubject().getVersion(), equalTo(previousVersion)); - assertThat(rewrittenSecondaryAuth.getUser(), equalTo(authentication.getUser())); + assertThat(rewrittenSecondaryAuth.getEffectiveSubject().getUser(), equalTo(authentication.getEffectiveSubject().getUser())); } } } diff --git a/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/security/authc/AuthenticationTestHelper.java b/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/security/authc/AuthenticationTestHelper.java index 4a4932ebf4baf..3b86b6b32f46e 100644 --- a/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/security/authc/AuthenticationTestHelper.java +++ b/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/security/authc/AuthenticationTestHelper.java @@ -209,7 +209,7 @@ private static User stripRoles(User user) { } public static String randomInternalUsername() { - return builder().internal().build(false).getUser().principal(); + return builder().internal().build(false).getEffectiveSubject().getUser().principal(); } /** diff --git a/x-pack/plugin/security/src/internalClusterTest/java/org/elasticsearch/xpack/security/authc/SecurityRealmSettingsTests.java b/x-pack/plugin/security/src/internalClusterTest/java/org/elasticsearch/xpack/security/authc/SecurityRealmSettingsTests.java index 5dca9b2efdd1f..ce8c9b1aba46c 100644 --- a/x-pack/plugin/security/src/internalClusterTest/java/org/elasticsearch/xpack/security/authc/SecurityRealmSettingsTests.java +++ b/x-pack/plugin/security/src/internalClusterTest/java/org/elasticsearch/xpack/security/authc/SecurityRealmSettingsTests.java @@ -146,8 +146,8 @@ public void testClusterStarted() { final AuthenticateResponse authenticate = client().execute(AuthenticateAction.INSTANCE, AuthenticateRequest.INSTANCE) .actionGet(10, TimeUnit.SECONDS); assertThat(authenticate.authentication(), notNullValue()); - assertThat(authenticate.authentication().getUser(), notNullValue()); - assertThat(authenticate.authentication().getUser().enabled(), is(true)); + assertThat(authenticate.authentication().getEffectiveSubject().getUser(), notNullValue()); + assertThat(authenticate.authentication().getEffectiveSubject().getUser().enabled(), is(true)); } } diff --git a/x-pack/plugin/security/src/internalClusterTest/java/org/elasticsearch/xpack/security/authc/esnative/NativeRealmIntegTests.java b/x-pack/plugin/security/src/internalClusterTest/java/org/elasticsearch/xpack/security/authc/esnative/NativeRealmIntegTests.java index 328b70b2b8282..6d8859ae684aa 100644 --- a/x-pack/plugin/security/src/internalClusterTest/java/org/elasticsearch/xpack/security/authc/esnative/NativeRealmIntegTests.java +++ b/x-pack/plugin/security/src/internalClusterTest/java/org/elasticsearch/xpack/security/authc/esnative/NativeRealmIntegTests.java @@ -744,7 +744,7 @@ public void testOperationsOnReservedUsers() throws Exception { AuthenticateResponse authenticateResponse = client().filterWithHeader( Collections.singletonMap("Authorization", basicAuthHeaderValue(username, getReservedPassword())) ).execute(AuthenticateAction.INSTANCE, AuthenticateRequest.INSTANCE).get(); - assertThat(authenticateResponse.authentication().getUser().principal(), is(username)); + assertThat(authenticateResponse.authentication().getEffectiveSubject().getUser().principal(), is(username)); assertThat(authenticateResponse.authentication().getAuthenticatedBy().getName(), equalTo("reserved")); assertThat(authenticateResponse.authentication().getAuthenticatedBy().getType(), equalTo("reserved")); assertNull(authenticateResponse.authentication().getLookedUpBy()); diff --git a/x-pack/plugin/security/src/internalClusterTest/java/org/elasticsearch/xpack/security/authz/SecuritySearchOperationListenerTests.java b/x-pack/plugin/security/src/internalClusterTest/java/org/elasticsearch/xpack/security/authz/SecuritySearchOperationListenerTests.java index c977848330c3a..185db79039997 100644 --- a/x-pack/plugin/security/src/internalClusterTest/java/org/elasticsearch/xpack/security/authz/SecuritySearchOperationListenerTests.java +++ b/x-pack/plugin/security/src/internalClusterTest/java/org/elasticsearch/xpack/security/authz/SecuritySearchOperationListenerTests.java @@ -165,7 +165,10 @@ public void testValidateSearchContext() throws Exception { threadContext.putTransient(ORIGINATING_ACTION_KEY, "action"); threadContext.putTransient( AUTHORIZATION_INFO_KEY, - (AuthorizationInfo) () -> Collections.singletonMap(PRINCIPAL_ROLES_FIELD_NAME, authentication.getUser().roles()) + (AuthorizationInfo) () -> Collections.singletonMap( + PRINCIPAL_ROLES_FIELD_NAME, + authentication.getEffectiveSubject().getUser().roles() + ) ); final InternalScrollSearchRequest request = new InternalScrollSearchRequest(); SearchContextMissingException expected = expectThrows( @@ -179,7 +182,7 @@ public void testValidateSearchContext() throws Exception { eq(authentication), eq("action"), eq(request), - authzInfoRoles(authentication.getUser().roles()) + authzInfoRoles(authentication.getEffectiveSubject().getUser().roles()) ); } @@ -216,7 +219,10 @@ public void testValidateSearchContext() throws Exception { threadContext.putTransient(ORIGINATING_ACTION_KEY, "action"); threadContext.putTransient( AUTHORIZATION_INFO_KEY, - (AuthorizationInfo) () -> Collections.singletonMap(PRINCIPAL_ROLES_FIELD_NAME, authentication.getUser().roles()) + (AuthorizationInfo) () -> Collections.singletonMap( + PRINCIPAL_ROLES_FIELD_NAME, + authentication.getEffectiveSubject().getUser().roles() + ) ); final InternalScrollSearchRequest request = new InternalScrollSearchRequest(); SearchContextMissingException expected = expectThrows( @@ -230,7 +236,7 @@ public void testValidateSearchContext() throws Exception { eq(authentication), eq("action"), eq(request), - authzInfoRoles(authentication.getUser().roles()) + authzInfoRoles(authentication.getEffectiveSubject().getUser().roles()) ); } } diff --git a/x-pack/plugin/security/src/internalClusterTest/java/org/elasticsearch/xpack/security/enrollment/EnrollmentSingleNodeTests.java b/x-pack/plugin/security/src/internalClusterTest/java/org/elasticsearch/xpack/security/enrollment/EnrollmentSingleNodeTests.java index b4df44b6877f6..07a2bd2147ddf 100644 --- a/x-pack/plugin/security/src/internalClusterTest/java/org/elasticsearch/xpack/security/enrollment/EnrollmentSingleNodeTests.java +++ b/x-pack/plugin/security/src/internalClusterTest/java/org/elasticsearch/xpack/security/enrollment/EnrollmentSingleNodeTests.java @@ -101,7 +101,7 @@ public void testKibanaEnrollmentTokenCreation() throws Exception { ); final AuthenticateResponse authenticateResponse1 = apiKeyClient.execute(AuthenticateAction.INSTANCE, AuthenticateRequest.INSTANCE) .actionGet(); - assertThat(authenticateResponse1.authentication().getUser().principal(), equalTo("_xpack_security")); + assertThat(authenticateResponse1.authentication().getEffectiveSubject().getUser().principal(), equalTo("_xpack_security")); final KibanaEnrollmentResponse kibanaEnrollmentResponse = apiKeyClient.execute( KibanaEnrollmentAction.INSTANCE, @@ -115,6 +115,6 @@ public void testKibanaEnrollmentTokenCreation() throws Exception { final AuthenticateResponse authenticateResponse2 = kibanaClient.execute(AuthenticateAction.INSTANCE, AuthenticateRequest.INSTANCE) .actionGet(); - assertThat(authenticateResponse2.authentication().getUser().principal(), equalTo("elastic/kibana")); + assertThat(authenticateResponse2.authentication().getEffectiveSubject().getUser().principal(), equalTo("elastic/kibana")); } } diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/action/apikey/TransportGetApiKeyAction.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/action/apikey/TransportGetApiKeyAction.java index 92d28ba601fb5..1bd0562593cc1 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/action/apikey/TransportGetApiKeyAction.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/action/apikey/TransportGetApiKeyAction.java @@ -53,7 +53,7 @@ protected void doExecute(Task task, GetApiKeyRequest request, ActionListener indices = Optional.ofNullable(indices(msg)); @@ -788,7 +788,7 @@ public void explicitIndexAccessEvent( ) { assert eventType == ACCESS_DENIED || eventType == AuditLevel.ACCESS_GRANTED || eventType == SYSTEM_ACCESS_GRANTED; final String[] indices = index == null ? null : new String[] { index }; - final User user = authentication.getUser(); + final User user = authentication.getEffectiveSubject().getUser(); if (User.isInternal(user) && eventType == ACCESS_GRANTED) { eventType = SYSTEM_ACCESS_GRANTED; } @@ -839,7 +839,7 @@ public void accessDenied( if (eventFilterPolicyRegistry.ignorePredicate() .test( new AuditEventMetaInfo( - Optional.of(authentication.getUser()), + Optional.of(authentication.getEffectiveSubject().getUser()), // can be null for API keys created before version 7.7 Optional.ofNullable(ApiKeyService.getCreatorRealmName(authentication)), Optional.of(authorizationInfo), @@ -902,7 +902,7 @@ public void tamperedRequest(String requestId, Authentication authentication, Str if (eventFilterPolicyRegistry.ignorePredicate() .test( new AuditEventMetaInfo( - Optional.of(authentication.getUser()), + Optional.of(authentication.getEffectiveSubject().getUser()), // can be null for API keys created before version 7.7 Optional.ofNullable(ApiKeyService.getCreatorRealmName(authentication)), Optional.empty(), @@ -971,7 +971,7 @@ public void runAsGranted( if (eventFilterPolicyRegistry.ignorePredicate() .test( new AuditEventMetaInfo( - Optional.of(authentication.getUser()), + Optional.of(authentication.getEffectiveSubject().getUser()), // can be null for API keys created before version 7.7 Optional.ofNullable(ApiKeyService.getCreatorRealmName(authentication)), Optional.of(authorizationInfo), @@ -1007,7 +1007,7 @@ public void runAsDenied( if (eventFilterPolicyRegistry.ignorePredicate() .test( new AuditEventMetaInfo( - Optional.of(authentication.getUser()), + Optional.of(authentication.getEffectiveSubject().getUser()), // can be null for API keys created before version 7.7 Optional.ofNullable(ApiKeyService.getCreatorRealmName(authentication)), Optional.of(authorizationInfo), @@ -1036,7 +1036,7 @@ public void runAsDenied(String requestId, Authentication authentication, RestReq && eventFilterPolicyRegistry.ignorePredicate() .test( new AuditEventMetaInfo( - Optional.of(authentication.getUser()), + Optional.of(authentication.getEffectiveSubject().getUser()), // can be null for API keys created before version 7.7 Optional.ofNullable(ApiKeyService.getCreatorRealmName(authentication)), Optional.of(authorizationInfo), @@ -1532,7 +1532,7 @@ LogEntryBuilder withRestUriAndMethod(RestRequest request) { LogEntryBuilder withRunAsSubject(Authentication authentication) { logEntry.with(PRINCIPAL_FIELD_NAME, authentication.getAuthenticatingSubject().getUser().principal()) .with(PRINCIPAL_REALM_FIELD_NAME, authentication.getAuthenticatedBy().getName()) - .with(PRINCIPAL_RUN_AS_FIELD_NAME, authentication.getUser().principal()); + .with(PRINCIPAL_RUN_AS_FIELD_NAME, authentication.getEffectiveSubject().getUser().principal()); if (authentication.getAuthenticatedBy().getDomain() != null) { logEntry.with(PRINCIPAL_DOMAIN_FIELD_NAME, authentication.getAuthenticatedBy().getDomain().name()); } @@ -1605,7 +1605,7 @@ private void setThreadContextField(ThreadContext threadContext, String threadCon } LogEntryBuilder withAuthentication(Authentication authentication) { - logEntry.with(PRINCIPAL_FIELD_NAME, authentication.getUser().principal()); + logEntry.with(PRINCIPAL_FIELD_NAME, authentication.getEffectiveSubject().getUser().principal()); logEntry.with(AUTHENTICATION_TYPE_FIELD_NAME, authentication.getAuthenticationType().toString()); if (authentication.isApiKey()) { logEntry.with(API_KEY_ID_FIELD_NAME, (String) authentication.getMetadata().get(AuthenticationField.API_KEY_ID_KEY)); diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/AuthenticatorChain.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/AuthenticatorChain.java index a60b6ad2c73f9..d4938cbd1a984 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/AuthenticatorChain.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/AuthenticatorChain.java @@ -216,7 +216,7 @@ void maybeLookupRunAsUser(Authenticator.Context context, Authentication authenti logger.debug( "Cannot find run-as user [{}] for authenticated user [{}]", runAsUsername, - authentication.getUser().principal() + authentication.getAuthenticatingSubject().getUser().principal() ); // the user does not exist, but we still create a User object, which will later be rejected by authz finalAuth = authentication.runAs(new User(runAsUsername, null, null, null, Map.of(), true), null); @@ -316,9 +316,10 @@ void handleNullToken(Authenticator.Context context, ActionListener listener) { - if (authentication.getUser().enabled() == false || authentication.getAuthenticatingSubject().getUser().enabled() == false) { + if (authentication.getEffectiveSubject().getUser().enabled() == false + || authentication.getAuthenticatingSubject().getUser().enabled() == false) { // TODO: these should be different log messages if the runas vs auth user is disabled? - logger.debug("user [{}] is disabled. failing authentication", authentication.getUser()); + logger.debug("user [{}] is disabled. failing authentication", authentication.getEffectiveSubject().getUser()); listener.onFailure(context.getRequest().authenticationFailed(context.getMostRecentAuthenticationToken())); } else { writeAuthToContext(context, authentication, listener); diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/RealmsAuthenticator.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/RealmsAuthenticator.java index 259dee6ff1ff1..b0a434df05c89 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/RealmsAuthenticator.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/RealmsAuthenticator.java @@ -279,7 +279,11 @@ public void lookupRunAsUser(Context context, Authentication authentication, Acti assert authentication.getLookedUpBy() == null : "authentication already has a lookup realm"; final String runAsUsername = context.getThreadContext().getHeader(AuthenticationServiceField.RUN_AS_USER_HEADER); if (runAsUsername != null && runAsUsername.isEmpty() == false) { - logger.trace("Looking up run-as user [{}] for authenticated user [{}]", runAsUsername, authentication.getUser().principal()); + logger.trace( + "Looking up run-as user [{}] for authenticated user [{}]", + runAsUsername, + authentication.getAuthenticatingSubject().getUser().principal() + ); final RealmUserLookup lookup = new RealmUserLookup(getRealmList(context, runAsUsername), context.getThreadContext()); final long startInvalidationNum = numInvalidation.get(); lookup.lookup(runAsUsername, ActionListener.wrap(tuple -> { @@ -287,7 +291,7 @@ public void lookupRunAsUser(Context context, Authentication authentication, Acti logger.debug( "Cannot find run-as user [{}] for authenticated user [{}]", runAsUsername, - authentication.getUser().principal() + authentication.getAuthenticatingSubject().getUser().principal() ); listener.onResponse(null); } else { @@ -298,14 +302,21 @@ public void lookupRunAsUser(Context context, Authentication authentication, Acti // this might provide a valid hint lastSuccessfulAuthCache.computeIfAbsent(runAsUsername, s -> realm); } - logger.trace("Using run-as user [{}] with authenticated user [{}]", foundUser, authentication.getUser().principal()); + logger.trace( + "Using run-as user [{}] with authenticated user [{}]", + foundUser, + authentication.getAuthenticatingSubject().getUser().principal() + ); listener.onResponse(tuple); } }, e -> listener.onFailure(context.getRequest().exceptionProcessingRequest(e, context.getMostRecentAuthenticationToken())))); } else if (runAsUsername == null) { listener.onResponse(null); } else { - logger.debug("user [{}] attempted to runAs with an empty username", authentication.getUser().principal()); + logger.debug( + "user [{}] attempted to runAs with an empty username", + authentication.getAuthenticatingSubject().getUser().principal() + ); listener.onFailure( context.getRequest() .runAsDenied(authentication.runAs(new User(runAsUsername), null), context.getMostRecentAuthenticationToken()) diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/TokenService.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/TokenService.java index 5180587a979a2..82410201de380 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/TokenService.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/TokenService.java @@ -1506,11 +1506,11 @@ private static Optional checkClientCanRefresh( } } else { // falback to the previous method - if (clientAuthentication.getUser().principal().equals(refreshToken.getAssociatedUser()) == false) { + if (clientAuthentication.getEffectiveSubject().getUser().principal().equals(refreshToken.getAssociatedUser()) == false) { logger.warn( "Token was originally created by [{}] but [{}] attempted to refresh it", refreshToken.getAssociatedUser(), - clientAuthentication.getUser().principal() + clientAuthentication.getEffectiveSubject().getUser().principal() ); return Optional.of(invalidGrantException("tokens must be refreshed by the creating client")); } else if (clientAuthentication.getAuthenticatedBy().getName().equals(refreshToken.getAssociatedRealm()) == false) { @@ -1794,7 +1794,7 @@ static BytesReference createTokenDocument( if (userToken.getVersion().onOrAfter(VERSION_CLIENT_AUTH_FOR_REFRESH)) { builder.field("authentication", originatingClientAuth.maybeRewriteForOlderVersion(userToken.getVersion()).encode()); } else { - builder.field("user", originatingClientAuth.getUser().principal()) + builder.field("user", originatingClientAuth.getEffectiveSubject().getUser().principal()) .field("realm", originatingClientAuth.getAuthenticatedBy().getName()); if (originatingClientAuth.getAuthenticatedBy().getDomain() != null) { builder.field("realm_domain", originatingClientAuth.getAuthenticatedBy().getDomain()); @@ -1824,7 +1824,7 @@ private static Predicate> isOfUser(String username) { try (StreamInput in = StreamInput.wrap(Base64.getDecoder().decode(auth))) { in.setVersion(authVersion); Authentication authentication = new Authentication(in); - return authentication.getUser().principal().equals(username); + return authentication.getEffectiveSubject().getUser().principal().equals(username); } catch (IOException e) { throw new UncheckedIOException(e); } @@ -1959,7 +1959,7 @@ private void checkIfTokenIsValid(UserToken userToken, ActionListener response.getIndex(), response.getId(), userToken.getId(), - userToken.getAuthentication().getUser().principal() + userToken.getAuthentication().getEffectiveSubject().getUser().principal() ); onFailure.accept( traceLog( @@ -2545,7 +2545,7 @@ static final class RefreshTokenStatus { assert associatedAuthentication.getEffectiveSubject().getVersion().onOrAfter(VERSION_CLIENT_AUTH_FOR_REFRESH); this.invalidated = invalidated; // not used, filled-in for consistency's sake - this.associatedUser = associatedAuthentication.getUser().principal(); + this.associatedUser = associatedAuthentication.getEffectiveSubject().getUser().principal(); this.associatedRealm = associatedAuthentication.getAuthenticatedBy().getName(); this.associatedAuthentication = associatedAuthentication; this.refreshed = refreshed; diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/pki/PkiRealm.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/pki/PkiRealm.java index 92b2666dc51c4..bf0ef418e811f 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/pki/PkiRealm.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/pki/PkiRealm.java @@ -212,7 +212,7 @@ private void buildUser(X509AuthenticationToken token, String principal, ActionLi "pki_dn", token.dn(), "pki_delegated_by_user", - token.getDelegateeAuthentication().getUser().principal(), + token.getDelegateeAuthentication().getEffectiveSubject().getUser().principal(), "pki_delegated_by_realm", token.getDelegateeAuthentication().getAuthenticatedBy().getName() ); diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/service/IndexServiceAccountTokenStore.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/service/IndexServiceAccountTokenStore.java index 434d368cbb7c3..134931160c2f8 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/service/IndexServiceAccountTokenStore.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/service/IndexServiceAccountTokenStore.java @@ -270,10 +270,10 @@ private XContentBuilder newDocument(Authentication authentication, ServiceAccoun .field("enabled", true); { builder.startObject("creator") - .field("principal", authentication.getUser().principal()) - .field("full_name", authentication.getUser().fullName()) - .field("email", authentication.getUser().email()) - .field("metadata", authentication.getUser().metadata()) + .field("principal", authentication.getEffectiveSubject().getUser().principal()) + .field("full_name", authentication.getEffectiveSubject().getUser().fullName()) + .field("email", authentication.getEffectiveSubject().getUser().email()) + .field("metadata", authentication.getEffectiveSubject().getUser().metadata()) .field("realm", authentication.getSourceRealm().getName()) .field("realm_type", authentication.getSourceRealm().getType()); if (authentication.getSourceRealm().getDomain() != null) { diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/service/ServiceAccountService.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/service/ServiceAccountService.java index d232720004fe8..c80a8e5b5aa2b 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/service/ServiceAccountService.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/service/ServiceAccountService.java @@ -164,7 +164,7 @@ public void findTokensFor(GetServiceAccountCredentialsRequest request, ActionLis // TODO: No production code usage public void getRoleDescriptor(Authentication authentication, ActionListener listener) { assert authentication.isAuthenticatedWithServiceAccount() : "authentication is not for service account: " + authentication; - final String principal = authentication.getUser().principal(); + final String principal = authentication.getEffectiveSubject().getUser().principal(); getRoleDescriptorForPrincipal(principal, listener); } diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authz/AuthorizationDenialMessages.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authz/AuthorizationDenialMessages.java index e602e1ef4a77d..6e76432612c70 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authz/AuthorizationDenialMessages.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authz/AuthorizationDenialMessages.java @@ -42,7 +42,7 @@ static String runAsDenied(Authentication authentication, @Nullable Authorization String unauthorizedToRunAsMessage = "because " + userText + " is unauthorized to run as [" - + authentication.getUser().principal() + + authentication.getEffectiveSubject().getUser().principal() + "]"; return actionIsUnauthorizedMessage @@ -61,7 +61,7 @@ static String actionDenied( String userText = authenticatedUserDescription(authentication); if (authentication.isRunAs()) { - userText = userText + " run as [" + authentication.getUser().principal() + "]"; + userText = userText + " run as [" + authentication.getEffectiveSubject().getUser().principal() + "]"; } userText += rolesDescription(authentication.getEffectiveSubject(), authorizationInfo); diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authz/AuthorizationService.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authz/AuthorizationService.java index 8a898310da375..a61d7f0d77a61 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authz/AuthorizationService.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authz/AuthorizationService.java @@ -255,7 +255,7 @@ public void authorize( return; } - if (SystemUser.is(authentication.getUser())) { + if (SystemUser.is(authentication.getEffectiveSubject().getUser())) { // this never goes async so no need to wrap the listener authorizeSystemUser(authentication, action, auditId, unwrappedRequest, listener); } else { @@ -297,7 +297,7 @@ private String requireAuditId(Authentication authentication, String action, Tran if (auditId == null) { // We would like to assert that there is an existing request-id, but if this is a system action, then that might not be // true because the request-id is generated during authentication - if (isInternal(authentication.getUser())) { + if (isInternal(authentication.getEffectiveSubject().getUser())) { auditId = AuditUtil.getOrGenerateRequestId(threadContext); } else { auditTrailService.get().tamperedRequest(null, authentication, action, originalRequest); @@ -305,7 +305,7 @@ private String requireAuditId(Authentication authentication, String action, Tran "Attempt to authorize action [" + action + "] for [" - + authentication.getUser().principal() + + authentication.getEffectiveSubject().getUser().principal() + "] without an existing request-id" ); } diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authz/LoadAuthorizedIndicesTimeChecker.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authz/LoadAuthorizedIndicesTimeChecker.java index 7001bcdfa7b8b..92693cd19ee5c 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authz/LoadAuthorizedIndicesTimeChecker.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authz/LoadAuthorizedIndicesTimeChecker.java @@ -50,7 +50,7 @@ public void accept(Collection indices) { + " The index privileges for this user may be too complex for this cluster.", indices.size(), requestInfo.getAction(), - requestInfo.getAuthentication().getUser().principal(), + requestInfo.getAuthentication().getEffectiveSubject().getUser().principal(), millis, thresholds.warnThresholdMs ); @@ -61,7 +61,7 @@ public void accept(Collection indices) { millis, indices.size(), requestInfo.getAction(), - requestInfo.getAuthentication().getUser().principal() + requestInfo.getAuthentication().getEffectiveSubject().getUser().principal() ); } } diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authz/RBACEngine.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authz/RBACEngine.java index af6f9961316a4..697fe8cc53398 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authz/RBACEngine.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authz/RBACEngine.java @@ -155,7 +155,9 @@ public void resolveAuthorizationInfo(Subject subject, ActionListener listener) { if (authorizationInfo instanceof RBACAuthorizationInfo) { final Role role = ((RBACAuthorizationInfo) authorizationInfo).getAuthenticatedUserAuthorizationInfo().getRole(); - listener.onResponse(new AuthorizationResult(role.checkRunAs(requestInfo.getAuthentication().getUser().principal()))); + listener.onResponse( + new AuthorizationResult(role.checkRunAs(requestInfo.getAuthentication().getEffectiveSubject().getUser().principal())) + ); } else { listener.onFailure( new IllegalArgumentException("unsupported authorization info:" + authorizationInfo.getClass().getSimpleName()) @@ -198,7 +200,7 @@ static boolean checkSameUserPermissions(String action, TransportRequest request, return false; } final String username = usernames[0]; - final boolean sameUsername = authentication.getUser().principal().equals(username); + final boolean sameUsername = authentication.getEffectiveSubject().getUser().principal().equals(username); if (sameUsername && ChangePasswordAction.NAME.equals(action)) { return checkChangePasswordAction(authentication); } diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/ingest/SetSecurityUserProcessor.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/ingest/SetSecurityUserProcessor.java index d2195791db086..2233682c6e3c1 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/ingest/SetSecurityUserProcessor.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/ingest/SetSecurityUserProcessor.java @@ -80,7 +80,7 @@ public IngestDocument execute(IngestDocument ingestDocument) throws Exception { if (this.securityContext != null) { authentication = securityContext.getAuthentication(); if (authentication != null) { - user = authentication.getUser(); + user = authentication.getEffectiveSubject().getUser(); } } diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/operator/FileOperatorUsersStore.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/operator/FileOperatorUsersStore.java index aa83c4249144d..c65f75b1deb80 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/operator/FileOperatorUsersStore.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/operator/FileOperatorUsersStore.java @@ -70,11 +70,16 @@ public boolean isOperatorUser(Authentication authentication) { // not matter what the name is. return operatorUsersDescriptor.groups.stream().anyMatch(group -> { final Authentication.RealmRef realm = authentication.getSourceRealm(); - final boolean match = group.usernames.contains(authentication.getUser().principal()) + final boolean match = group.usernames.contains(authentication.getEffectiveSubject().getUser().principal()) && group.authenticationType == authentication.getAuthenticationType() && realm.getType().equals(group.realmType) && (group.realmName == null || group.realmName.equals(realm.getName())); - logger.trace("Matching user [{}] against operator rule [{}] is [{}]", authentication.getUser(), group, match); + logger.trace( + "Matching user [{}] against operator rule [{}] is [{}]", + authentication.getEffectiveSubject().getUser(), + group, + match + ); return match; }); } diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/operator/OperatorPrivileges.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/operator/OperatorPrivileges.java index b031b962e2c3e..0a41b7e36bd9d 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/operator/OperatorPrivileges.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/operator/OperatorPrivileges.java @@ -75,7 +75,7 @@ public DefaultOperatorPrivilegesService( public void maybeMarkOperatorUser(Authentication authentication, ThreadContext threadContext) { // Always mark the thread context for operator users regardless of license state which is enforced at check time - final User user = authentication.getUser(); + final User user = authentication.getEffectiveSubject().getUser(); // Let internal users pass, they are exempt from marking and checking // Also check run_as, it is impossible to run_as internal users, but just to be extra safe if (User.isInternal(user) && false == authentication.isRunAs()) { @@ -103,7 +103,7 @@ public ElasticsearchSecurityException check( if (false == shouldProcess()) { return null; } - final User user = authentication.getUser(); + final User user = authentication.getEffectiveSubject().getUser(); // Let internal users pass (also check run_as, it is impossible to run_as internal users, but just to be extra safe) if (User.isInternal(user) && false == authentication.isRunAs()) { return null; diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/support/ApiKeyBoolQueryBuilder.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/support/ApiKeyBoolQueryBuilder.java index fe450f523e908..de22802640517 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/support/ApiKeyBoolQueryBuilder.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/support/ApiKeyBoolQueryBuilder.java @@ -73,7 +73,7 @@ public static ApiKeyBoolQueryBuilder build(QueryBuilder queryBuilder, @Nullable assert apiKeyId != null : "api key id must be present in the metadata"; finalQuery.filter(QueryBuilders.idsQuery().addIds(apiKeyId)); } else { - finalQuery.filter(QueryBuilders.termQuery("creator.principal", authentication.getUser().principal())); + finalQuery.filter(QueryBuilders.termQuery("creator.principal", authentication.getEffectiveSubject().getUser().principal())); final String[] realms = ApiKeyService.getOwnersRealmNames(authentication); final QueryBuilder realmsQuery = ApiKeyService.filterForRealmNames(realms); assert realmsQuery != null; diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/transport/ServerTransportFilter.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/transport/ServerTransportFilter.java index 27bc02a722197..68b68a876dc23 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/transport/ServerTransportFilter.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/transport/ServerTransportFilter.java @@ -103,7 +103,8 @@ requests from all the nodes are attached with a user (either a serialize final Version version = transportChannel.getVersion(); authcService.authenticate(securityAction, request, true, ActionListener.wrap((authentication) -> { if (authentication != null) { - if (securityAction.equals(TransportService.HANDSHAKE_ACTION_NAME) && SystemUser.is(authentication.getUser()) == false) { + if (securityAction.equals(TransportService.HANDSHAKE_ACTION_NAME) + && SystemUser.is(authentication.getEffectiveSubject().getUser()) == false) { securityContext.executeAsSystemUser(version, original -> { final Authentication replaced = securityContext.getAuthentication(); authzService.authorize(replaced, securityAction, request, listener); diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/SecurityContextTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/SecurityContextTests.java index 0c16c8106c30e..8883aa1eddec3 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/SecurityContextTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/SecurityContextTests.java @@ -158,7 +158,7 @@ public void testExecuteAfterRewritingAuthentication() throws IOException { final AtomicReference contextAtomicReference = new AtomicReference<>(); securityContext.executeAfterRewritingAuthentication(originalCtx -> { Authentication authentication = securityContext.getAuthentication(); - assertEquals(original.getUser(), authentication.getUser()); + assertEquals(original.getEffectiveSubject().getUser(), authentication.getEffectiveSubject().getUser()); assertEquals(original.getAuthenticatedBy(), authentication.getAuthenticatedBy()); assertEquals(original.getLookedUpBy(), authentication.getLookedUpBy()); assertEquals(VersionUtils.getPreviousVersion(), authentication.getEffectiveSubject().getVersion()); diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/filter/SecurityActionFilterTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/filter/SecurityActionFilterTests.java index bbd1e447990b6..14e90678929fc 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/filter/SecurityActionFilterTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/filter/SecurityActionFilterTests.java @@ -213,7 +213,7 @@ public void testApplyAsSystemUser() throws Exception { } assertNotNull(authenticationSetOnce.get()); assertNotEquals(authentication, authenticationSetOnce.get()); - assertEquals(SystemUser.INSTANCE, authenticationSetOnce.get().getUser()); + assertEquals(SystemUser.INSTANCE, authenticationSetOnce.get().getEffectiveSubject().getUser()); assertThat(accessControlSetOnce.get(), sameInstance(authzAccessControl)); assertThat(requestIdOnActionHandler.get(), is(requestIdFromAuthn.get())); } diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/user/TransportAuthenticateActionTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/user/TransportAuthenticateActionTests.java index 96a95fa8c303d..ea2365e6ab0d1 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/user/TransportAuthenticateActionTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/user/TransportAuthenticateActionTests.java @@ -122,7 +122,7 @@ public void testValidAuthentication() { final AnonymousUser anonymousUser = prepareAnonymousUser(); final User user = randomFrom(new ElasticUser(true), new KibanaUser(true), new User("joe")); final Authentication authentication = AuthenticationTestHelper.builder().user(user).build(); - final User effectiveUser = authentication.getUser(); + final User effectiveUser = authentication.getEffectiveSubject().getUser(); TransportAuthenticateAction action = prepareAction(anonymousUser, effectiveUser, authentication); @@ -143,10 +143,10 @@ public void onFailure(Exception e) { assertThat(responseRef.get(), notNullValue()); if (anonymousUser.enabled() && false == authentication.isApiKey()) { final Authentication auth = responseRef.get().authentication(); - final User userInResponse = auth.getUser(); + final User userInResponse = auth.getEffectiveSubject().getUser(); assertThat( userInResponse.roles(), - arrayContainingInAnyOrder(ArrayUtils.concat(authentication.getUser().roles(), anonymousUser.roles())) + arrayContainingInAnyOrder(ArrayUtils.concat(authentication.getEffectiveSubject().getUser().roles(), anonymousUser.roles())) ); assertThat(auth.isRunAs(), is(authentication.isRunAs())); if (auth.isRunAs()) { @@ -173,7 +173,7 @@ public void testShouldNotAddAnonymousRolesForApiKeyOrServiceAccount() { } else { authentication = AuthenticationTestHelper.builder().serviceAccount().build(); } - final User user = authentication.getUser(); + final User user = authentication.getEffectiveSubject().getUser(); TransportAuthenticateAction action = prepareAction(anonymousUser, user, authentication); @@ -194,7 +194,7 @@ public void onFailure(Exception e) { assertThat(responseRef.get(), notNullValue()); if (anonymousUser.enabled()) { final Authentication auth = responseRef.get().authentication(); - final User authUser = auth.getUser(); + final User authUser = auth.getEffectiveSubject().getUser(); assertThat(authUser.roles(), emptyArray()); assertThat(auth.getAuthenticatedBy(), sameInstance(auth.getAuthenticatedBy())); assertThat(auth.getLookedUpBy(), sameInstance(auth.getLookedUpBy())); diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/audit/logfile/LoggingAuditTrailFilterTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/audit/logfile/LoggingAuditTrailFilterTests.java index 2362e29d0aa11..a31b9ab6a356d 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/audit/logfile/LoggingAuditTrailFilterTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/audit/logfile/LoggingAuditTrailFilterTests.java @@ -2777,7 +2777,7 @@ public void testRemoveIgnoreFilter() throws IllegalAccessException, IOException threadContext, indexName != null ? indexName : randomAlphaOfLengthBetween(3, 10) ); - final AuthorizationInfo authorizationInfo = authzInfo(authentication.getUser().roles()); + final AuthorizationInfo authorizationInfo = authzInfo(authentication.getEffectiveSubject().getUser().roles()); final String action = actionName != null ? actionName : randomAlphaOfLengthBetween(3, 10); // Filter not created yet, message should be logged diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/audit/logfile/LoggingAuditTrailTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/audit/logfile/LoggingAuditTrailTests.java index 774c5defb4329..870df1a7c679f 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/audit/logfile/LoggingAuditTrailTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/audit/logfile/LoggingAuditTrailTests.java @@ -2869,7 +2869,7 @@ private static void restOrTransportOrigin( } private static void authentication(Authentication authentication, MapBuilder checkedFields) { - checkedFields.put(LoggingAuditTrail.PRINCIPAL_FIELD_NAME, authentication.getUser().principal()); + checkedFields.put(LoggingAuditTrail.PRINCIPAL_FIELD_NAME, authentication.getEffectiveSubject().getUser().principal()); checkedFields.put(LoggingAuditTrail.AUTHENTICATION_TYPE_FIELD_NAME, authentication.getAuthenticationType().toString()); if (authentication.isApiKey()) { assert false == authentication.isRunAs(); diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/AuthenticationServiceTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/AuthenticationServiceTests.java index 22c3031adcccf..6cd3509b1cbdf 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/AuthenticationServiceTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/AuthenticationServiceTests.java @@ -479,7 +479,7 @@ public void testAuthenticateBothSupportSecondSucceeds() throws Exception { reqId.set(expectAuditRequestId(threadContext)); } assertThat(result, notNullValue()); - assertThat(result.getUser(), is(user)); + assertThat(result.getEffectiveSubject().getUser(), is(user)); assertThat(result.getLookedUpBy(), is(nullValue())); assertThat(result.getAuthenticatedBy(), is(notNullValue())); // TODO implement equals assertThat(result.getAuthenticationType(), is(AuthenticationType.REALM)); @@ -519,7 +519,7 @@ public void testAuthenticateSmartRealmOrdering() { reqId.set(expectAuditRequestId(threadContext)); } assertThat(result, notNullValue()); - assertThat(result.getUser(), is(user)); + assertThat(result.getEffectiveSubject().getUser(), is(user)); assertThat(result.getLookedUpBy(), is(nullValue())); assertThat(result.getAuthenticatedBy(), is(notNullValue())); // TODO implement equals assertThat(result.getAuthenticatedBy().getName(), is(SECOND_REALM_NAME)); @@ -540,7 +540,7 @@ public void testAuthenticateSmartRealmOrdering() { service.authenticate("_action", transportRequest, true, ActionListener.wrap(result -> { assertThat(expectAuditRequestId(threadContext), is(reqId.get())); assertThat(result, notNullValue()); - assertThat(result.getUser(), is(user)); + assertThat(result.getEffectiveSubject().getUser(), is(user)); assertThat(result.getLookedUpBy(), is(nullValue())); assertThat(result.getAuthenticatedBy(), is(notNullValue())); // TODO implement equals assertThat(result.getAuthenticatedBy().getName(), is(SECOND_REALM_NAME)); @@ -574,7 +574,7 @@ public void testAuthenticateSmartRealmOrdering() { service.authenticate("_action", transportRequest, true, ActionListener.wrap(result -> { assertThat(expectAuditRequestId(threadContext), is(reqId.get())); assertThat(result, notNullValue()); - assertThat(result.getUser(), is(user)); + assertThat(result.getEffectiveSubject().getUser(), is(user)); assertThat(result.getLookedUpBy(), is(nullValue())); assertThat(result.getAuthenticatedBy(), is(notNullValue())); assertThat(result.getAuthenticatedBy().getName(), is(FIRST_REALM_NAME)); @@ -662,7 +662,7 @@ public void testAuthenticateSmartRealmOrderingDisabled() { reqId.set(expectAuditRequestId(threadContext)); } assertThat(result, notNullValue()); - assertThat(result.getUser(), is(user)); + assertThat(result.getEffectiveSubject().getUser(), is(user)); assertThat(result.getLookedUpBy(), is(nullValue())); assertThat(result.getAuthenticatedBy().getName(), is(SECOND_REALM_NAME)); // TODO implement equals assertThat(result.getAuthenticatedBy().getDomain(), is(secondDomain)); @@ -678,7 +678,7 @@ public void testAuthenticateSmartRealmOrderingDisabled() { service.authenticate("_action", transportRequest, true, ActionListener.wrap(result -> { assertThat(expectAuditRequestId(threadContext), is(reqId.get())); assertThat(result, notNullValue()); - assertThat(result.getUser(), is(user)); + assertThat(result.getEffectiveSubject().getUser(), is(user)); assertThat(result.getLookedUpBy(), is(nullValue())); assertThat(result.getAuthenticatedBy().getName(), is(SECOND_REALM_NAME)); // TODO implement equals assertThat(result.getAuthenticatedBy().getDomain(), is(secondDomain)); @@ -719,7 +719,7 @@ public void testAuthenticateFirstNotSupportingSecondSucceeds() throws Exception reqId.set(expectAuditRequestId(threadContext)); } assertThat(result, notNullValue()); - assertThat(result.getUser(), is(user)); + assertThat(result.getEffectiveSubject().getUser(), is(user)); assertThat(result.getAuthenticationType(), is(AuthenticationType.REALM)); assertThat(result.getAuthenticatedBy().getName(), is(secondRealm.name())); // TODO implement equals assertThat(result.getAuthenticatedBy().getDomain(), is(secondDomain)); @@ -791,7 +791,7 @@ public void testAuthenticationInContextAndHeader() throws Exception { assertThat(expectAuditRequestId(threadContext), is(reqId.get())); } assertThat(result, notNullValue()); - assertThat(result.getUser(), is(user)); + assertThat(result.getEffectiveSubject().getUser(), is(user)); assertThat(result.getAuthenticationType(), is(AuthenticationType.REALM)); String userStr = threadContext.getHeader(AuthenticationField.AUTHENTICATION_KEY); @@ -856,7 +856,7 @@ public void testAuthenticateTransportFallback() throws Exception { } assertThat(expectAuditRequestId(threadContext), is(result.v2())); assertThat(result, notNullValue()); - assertThat(result.v1().getUser(), sameInstance(user1)); + assertThat(result.v1().getEffectiveSubject().getUser(), sameInstance(user1)); assertThat(result.v1().getAuthenticationType(), is(AuthenticationType.INTERNAL)); assertThreadContextContainsAuthentication(result.v1()); verify(operatorPrivilegesService).maybeMarkOperatorUser(eq(result.v1()), eq(threadContext)); @@ -932,7 +932,7 @@ public void testAuthenticateTransportSuccess() throws Exception { reqId.set(expectAuditRequestId(threadContext)); } assertThat(result, notNullValue()); - assertThat(result.getUser(), sameInstance(user)); + assertThat(result.getEffectiveSubject().getUser(), sameInstance(user)); assertThat(result.getAuthenticationType(), is(AuthenticationType.REALM)); assertThat(result.getAuthenticatedBy().getDomain(), is(firstDomain)); assertThat(result.getAuthenticatedBy().getName(), is(firstRealm.name())); // TODO implement equals @@ -955,7 +955,7 @@ public void testAuthenticateRestSuccess() throws Exception { final AtomicBoolean completed = new AtomicBoolean(false); service.authenticate(restRequest, ActionListener.wrap(authentication -> { assertThat(authentication, notNullValue()); - assertThat(authentication.getUser(), sameInstance(user1)); + assertThat(authentication.getEffectiveSubject().getUser(), sameInstance(user1)); assertThat(authentication.getAuthenticationType(), is(AuthenticationType.REALM)); assertThat(authentication.getAuthenticatedBy().getName(), is(firstRealm.name())); // TODO implement equals assertThat(authentication.getAuthenticatedBy().getDomain(), is(firstDomain)); // TODO implement equals @@ -990,7 +990,7 @@ public void testAuthenticateTransportContextAndHeader() throws Exception { reqId.set(expectAuditRequestId(threadContext)); } assertThat(authentication, notNullValue()); - assertThat(authentication.getUser(), sameInstance(user1)); + assertThat(authentication.getEffectiveSubject().getUser(), sameInstance(user1)); assertThat(authentication.getAuthenticationType(), is(AuthenticationType.REALM)); assertThat(authentication.getDomain(), is(firstDomain)); assertThreadContextContainsAuthentication(authentication); @@ -1101,7 +1101,7 @@ public void testAuthenticateTransportContextAndHeader() throws Exception { reqId.set(expectAuditRequestId(threadPool2.getThreadContext())); } assertThat(result, notNullValue()); - assertThat(result.getUser(), equalTo(user1)); + assertThat(result.getEffectiveSubject().getUser(), equalTo(user1)); assertThat(result.getAuthenticationType(), is(AuthenticationType.REALM)); setCompletedToTrue(completed); verify(operatorPrivilegesService, times(1)).maybeMarkOperatorUser(result, threadPool2.getThreadContext()); @@ -1268,7 +1268,7 @@ public void testAnonymousUserRest() throws Exception { authenticateBlocking(request, result -> { assertThat(result, notNullValue()); - assertThat(result.v1().getUser(), sameInstance((Object) anonymousUser)); + assertThat(result.v1().getEffectiveSubject().getUser(), sameInstance((Object) anonymousUser)); assertThat(result.v1().getAuthenticationType(), is(AuthenticationType.ANONYMOUS)); assertThat(result.v1().getDomain(), nullValue()); assertThreadContextContainsAuthentication(result.v1()); @@ -1343,7 +1343,7 @@ public void testAnonymousUserTransportNoDefaultUser() throws Exception { assertThat(expectAuditRequestId(threadContext), is(reqId.get())); } assertThat(expectAuditRequestId(threadContext), is(result.v2())); - assertThat(result.v1().getUser(), sameInstance(anonymousUser)); + assertThat(result.v1().getEffectiveSubject().getUser(), sameInstance(anonymousUser)); assertThat(result.v1().getAuthenticationType(), is(AuthenticationType.ANONYMOUS)); assertThat(result.v1().getDomain(), nullValue()); assertThreadContextContainsAuthentication(result.v1()); @@ -1380,7 +1380,7 @@ public void testAnonymousUserTransportWithDefaultUser() throws Exception { } assertThat(result, notNullValue()); assertThat(expectAuditRequestId(threadContext), is(result.v2())); - assertThat(result.v1().getUser(), sameInstance(SystemUser.INSTANCE)); + assertThat(result.v1().getEffectiveSubject().getUser(), sameInstance(SystemUser.INSTANCE)); assertThat(result.v1().getAuthenticationType(), is(AuthenticationType.INTERNAL)); assertThat(result.v1().getDomain(), nullValue()); assertThreadContextContainsAuthentication(result.v1()); @@ -1654,7 +1654,7 @@ public void testRunAsLookupSameRealm() throws Exception { ActionListener listener = ActionListener.wrap(authentication -> { assertThat(authentication, notNullValue()); assertThat(authentication.getAuthenticationType(), is(AuthenticationType.REALM)); - User effectiveUser = authentication.getUser(); + User effectiveUser = authentication.getEffectiveSubject().getUser(); assertThat(effectiveUser.principal(), is("looked up user")); assertThat(effectiveUser.roles(), arrayContaining("some role")); @@ -1711,7 +1711,7 @@ public void testRunAsLookupDifferentRealm() throws Exception { ActionListener listener = ActionListener.wrap(authentication -> { assertThat(authentication, notNullValue()); assertThat(authentication.getAuthenticationType(), is(AuthenticationType.REALM)); - final User effectiveUser = authentication.getUser(); + final User effectiveUser = authentication.getEffectiveSubject().getUser(); final User authenticatingUser = authentication.getAuthenticatingSubject().getUser(); assertThat(SystemUser.is(effectiveUser), is(false)); @@ -1887,7 +1887,7 @@ public void testAuthenticateWithToken() throws Exception { } service.authenticate("_action", transportRequest, true, ActionListener.wrap(result -> { assertThat(result, notNullValue()); - assertThat(result.getUser(), is(user)); + assertThat(result.getEffectiveSubject().getUser(), is(user)); assertThat(result.getLookedUpBy(), is(nullValue())); assertThat(result.getAuthenticatedBy(), is(notNullValue())); assertThat(result.getAuthenticatedBy().getName(), is("realm")); // TODO implement equals @@ -1930,7 +1930,7 @@ public void testInvalidToken() throws Exception { } service.authenticate("_action", transportRequest, true, ActionListener.wrap(result -> { assertThat(result, notNullValue()); - assertThat(result.getUser(), is(user)); + assertThat(result.getEffectiveSubject().getUser(), is(user)); assertThat(result.getLookedUpBy(), is(nullValue())); assertThat(result.getAuthenticatedBy(), is(notNullValue())); assertThreadContextContainsAuthentication(result); @@ -2129,9 +2129,9 @@ public void testApiKeyAuth() { assertThat(expectAuditRequestId(threadContext), is(reqId.get())); } assertThat(expectAuditRequestId(threadContext), is(result.v2())); - assertThat(result.v1().getUser().principal(), is("johndoe")); - assertThat(result.v1().getUser().fullName(), is("john doe")); - assertThat(result.v1().getUser().email(), is("john@doe.com")); + assertThat(result.v1().getEffectiveSubject().getUser().principal(), is("johndoe")); + assertThat(result.v1().getEffectiveSubject().getUser().fullName(), is("john doe")); + assertThat(result.v1().getEffectiveSubject().getUser().email(), is("john@doe.com")); assertThat(result.v1().getAuthenticationType(), is(AuthenticationType.API_KEY)); assertThat(result.v1().getDomain(), nullValue()); verify(operatorPrivilegesService).maybeMarkOperatorUser(eq(result.v1()), eq(threadContext)); diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/AuthenticatorChainTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/AuthenticatorChainTests.java index b9cbc709e2e19..7cca79b5632e4 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/AuthenticatorChainTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/AuthenticatorChainTests.java @@ -240,7 +240,7 @@ public void testAuthenticateFallbackAndAnonymous() throws IOException { authenticatorChain.authenticateAsync(context, future); final Authentication authentication = future.actionGet(); - assertThat(authentication.getUser(), is(hasFallbackUser ? fallbackUser : anonymousUser)); + assertThat(authentication.getEffectiveSubject().getUser(), is(hasFallbackUser ? fallbackUser : anonymousUser)); verify(serviceAccountAuthenticator).extractCredentials(eq(context)); verify(serviceAccountAuthenticator, never()).authenticate(eq(context), any()); verify(oAuth2TokenAuthenticator).extractCredentials(eq(context)); @@ -303,7 +303,7 @@ public void testMaybeLookupRunAsUser() { ); final String runAsUsername = "your-run-as-username"; threadContext.putHeader(AuthenticationServiceField.RUN_AS_USER_HEADER, runAsUsername); - assertThat(authentication.getUser().principal(), not(equalTo(runAsUsername))); + assertThat(authentication.getEffectiveSubject().getUser().principal(), not(equalTo(runAsUsername))); final AuthenticationService.AuditableRequest auditableRequest = mock(AuthenticationService.AuditableRequest.class); final Authenticator.Context context = new Authenticator.Context(threadContext, auditableRequest, null, true, realms); @@ -334,7 +334,7 @@ public void testRunAsIsIgnoredForUnsupportedAuthenticationTypes() throws Illegal ); threadContext.putHeader(AuthenticationServiceField.RUN_AS_USER_HEADER, "you-shall-not-pass"); assertThat( - authentication.getUser().principal(), + authentication.getEffectiveSubject().getUser().principal(), not(equalTo(threadContext.getHeader(AuthenticationServiceField.RUN_AS_USER_HEADER))) ); diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/RealmsAuthenticatorTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/RealmsAuthenticatorTests.java index 748c3b55d1eea..b1101928d6a73 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/RealmsAuthenticatorTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/RealmsAuthenticatorTests.java @@ -161,7 +161,7 @@ public void testAuthenticate() { final AuthenticationResult result = future.actionGet(); assertThat(result.getStatus(), is(AuthenticationResult.Status.SUCCESS)); final Authentication authentication = result.getValue(); - assertThat(authentication.getUser(), is(user)); + assertThat(authentication.getEffectiveSubject().getUser(), is(user)); assertThat( authentication.getAuthenticatedBy(), is( diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/TokenServiceTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/TokenServiceTests.java index bf4e0146eb37c..6bd2d0fca0b66 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/TokenServiceTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/TokenServiceTests.java @@ -464,7 +464,7 @@ private RefreshTokenStatus newRefreshTokenStatus( } else { return new RefreshTokenStatus( invalidated, - authentication.getUser().principal(), + authentication.getEffectiveSubject().getUser().principal(), authentication.getAuthenticatedBy().getName(), refreshed, refreshInstant, @@ -1047,7 +1047,7 @@ private void mockGetTokenAsyncForDecryptedToken(String accessToken) { } public static void assertAuthentication(Authentication result, Authentication expected) { - assertEquals(expected.getUser(), result.getUser()); + assertEquals(expected.getEffectiveSubject().getUser(), result.getEffectiveSubject().getUser()); assertEquals(expected.getAuthenticatedBy(), result.getAuthenticatedBy()); assertEquals(expected.getLookedUpBy(), result.getLookedUpBy()); assertEquals(expected.getMetadata(), result.getMetadata()); diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/service/IndexServiceAccountTokenStoreTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/service/IndexServiceAccountTokenStoreTests.java index f0afdd2fe095c..96099e2fb1582 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/service/IndexServiceAccountTokenStoreTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/service/IndexServiceAccountTokenStoreTests.java @@ -214,10 +214,10 @@ public void testCreateToken() throws ExecutionException, InterruptedException { @SuppressWarnings("unchecked") final Map creatorMap = (Map) sourceMap.get("creator"); assertThat(creatorMap, notNullValue()); - assertThat(creatorMap.get("principal"), equalTo(authentication.getUser().principal())); - assertThat(creatorMap.get("full_name"), equalTo(authentication.getUser().fullName())); - assertThat(creatorMap.get("email"), equalTo(authentication.getUser().email())); - assertThat(creatorMap.get("metadata"), equalTo(authentication.getUser().metadata())); + assertThat(creatorMap.get("principal"), equalTo(authentication.getEffectiveSubject().getUser().principal())); + assertThat(creatorMap.get("full_name"), equalTo(authentication.getEffectiveSubject().getUser().fullName())); + assertThat(creatorMap.get("email"), equalTo(authentication.getEffectiveSubject().getUser().email())); + assertThat(creatorMap.get("metadata"), equalTo(authentication.getEffectiveSubject().getUser().metadata())); assertThat(creatorMap.get("realm"), equalTo(authentication.getSourceRealm().getName())); assertThat(creatorMap.get("realm_type"), equalTo(authentication.getSourceRealm().getType())); diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/support/SecondaryAuthenticatorTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/support/SecondaryAuthenticatorTests.java index a4ca5336e643a..5dbc287571d5b 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/support/SecondaryAuthenticatorTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/support/SecondaryAuthenticatorTests.java @@ -246,7 +246,7 @@ private SecondaryAuthentication assertAuthenticateWithBasicAuthentication(Consum final SecondaryAuthentication secondaryAuthentication = future.get(0, TimeUnit.MILLISECONDS); assertThat(secondaryAuthentication, Matchers.notNullValue()); assertThat(secondaryAuthentication.getAuthentication(), Matchers.notNullValue()); - assertThat(secondaryAuthentication.getAuthentication().getUser().principal(), equalTo(user)); + assertThat(secondaryAuthentication.getAuthentication().getEffectiveSubject().getUser().principal(), equalTo(user)); assertThat(secondaryAuthentication.getAuthentication().getAuthenticatedBy().getName(), equalTo(realm.name())); listenerContext.get().restore(); @@ -326,7 +326,7 @@ public void testAuthenticateUsingBearerToken() throws Exception { final SecondaryAuthentication secondaryAuthentication = future.actionGet(0, TimeUnit.MILLISECONDS); assertThat(secondaryAuthentication, Matchers.notNullValue()); assertThat(secondaryAuthentication.getAuthentication(), Matchers.notNullValue()); - assertThat(secondaryAuthentication.getAuthentication().getUser(), equalTo(user)); + assertThat(secondaryAuthentication.getAuthentication().getEffectiveSubject().getUser(), equalTo(user)); assertThat(secondaryAuthentication.getAuthentication().getAuthenticationType(), equalTo(AuthenticationType.TOKEN)); } diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authz/AuthorizationServiceTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authz/AuthorizationServiceTests.java index 8d0ec5710cbc2..d69b2df3a67a8 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authz/AuthorizationServiceTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authz/AuthorizationServiceTests.java @@ -1764,7 +1764,7 @@ public void testRunAsRequestWithoutLookedUpBy() throws IOException { .build(false) .runAs(new User("run as me", Strings.EMPTY_ARRAY), null); authentication.writeToContext(threadContext); - assertNotEquals(authUser, authentication.getUser()); + assertNotEquals(authUser, authentication.getEffectiveSubject().getUser()); assertThrowsAuthorizationExceptionRunAsDenied( () -> authorize(authentication, AuthenticateAction.NAME, AuthenticateRequest.INSTANCE), AuthenticateAction.NAME, diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authz/AuthorizationUtilsTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authz/AuthorizationUtilsTests.java index 8b58592ccf5a0..e08f8663ae27c 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authz/AuthorizationUtilsTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authz/AuthorizationUtilsTests.java @@ -150,7 +150,7 @@ private void assertSwitchBasedOnOriginAndExecute(String origin, User user, Versi assertNull(threadContext.getTransient(ThreadContext.ACTION_ORIGIN_TRANSIENT_NAME)); assertNull(threadContext.getHeader(headerName)); final Authentication authentication = securityContext.getAuthentication(); - assertEquals(user, authentication.getUser()); + assertEquals(user, authentication.getEffectiveSubject().getUser()); assertEquals(version, authentication.getEffectiveSubject().getVersion()); latch.countDown(); }, e -> fail(e.getMessage())); @@ -159,7 +159,7 @@ private void assertSwitchBasedOnOriginAndExecute(String origin, User user, Versi assertNull(threadContext.getTransient(ThreadContext.ACTION_ORIGIN_TRANSIENT_NAME)); assertNull(threadContext.getHeader(headerName)); final Authentication authentication = securityContext.getAuthentication(); - assertEquals(user, authentication.getUser()); + assertEquals(user, authentication.getEffectiveSubject().getUser()); assertEquals(version, authentication.getEffectiveSubject().getVersion()); latch.countDown(); listener.onResponse(null); diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/ingest/SetSecurityUserProcessorTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/ingest/SetSecurityUserProcessorTests.java index b45996caeef08..2e7378d12a710 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/ingest/SetSecurityUserProcessorTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/ingest/SetSecurityUserProcessorTests.java @@ -70,24 +70,24 @@ public void testProcessorWithData() throws Exception { processor.execute(ingestDocument); Map result = ingestDocument.getFieldValue("_field", Map.class); - if (authentication.getUser().fullName().startsWith("Service account - ")) { + if (authentication.getEffectiveSubject().getUser().fullName().startsWith("Service account - ")) { assertThat(result, not(hasKey("roles"))); assertThat(result, not(hasKey("email"))); } else { - assertThat(result.get("email"), equalTo(authentication.getUser().email())); - if (authentication.getUser().roles().length == 0) { + assertThat(result.get("email"), equalTo(authentication.getEffectiveSubject().getUser().email())); + if (authentication.getEffectiveSubject().getUser().roles().length == 0) { assertThat(result, not(hasKey("roles"))); } else { - assertThat(result.get("roles"), equalTo(Arrays.asList(authentication.getUser().roles()))); + assertThat(result.get("roles"), equalTo(Arrays.asList(authentication.getEffectiveSubject().getUser().roles()))); } } - if (authentication.getUser().metadata().isEmpty()) { + if (authentication.getEffectiveSubject().getUser().metadata().isEmpty()) { assertThat(result, not(hasKey("metadata"))); } else { - assertThat(result.get("metadata"), equalTo(authentication.getUser().metadata())); + assertThat(result.get("metadata"), equalTo(authentication.getEffectiveSubject().getUser().metadata())); } - assertThat(result.get("username"), equalTo(authentication.getUser().principal())); - assertThat(result.get("full_name"), equalTo(authentication.getUser().fullName())); + assertThat(result.get("username"), equalTo(authentication.getEffectiveSubject().getUser().principal())); + assertThat(result.get("full_name"), equalTo(authentication.getEffectiveSubject().getUser().fullName())); assertThat(((Map) result.get("realm")).get("name"), equalTo(ApiKeyService.getCreatorRealmName(authentication))); assertThat(((Map) result.get("realm")).get("type"), equalTo(ApiKeyService.getCreatorRealmType(authentication))); assertThat(result.get("authentication_type"), equalTo(authentication.getAuthenticationType().toString())); @@ -176,7 +176,7 @@ public void testUsernameProperties() throws Exception { @SuppressWarnings("unchecked") Map result = ingestDocument.getFieldValue("_field", Map.class); assertThat(result, aMapWithSize(1)); - assertThat(result.get("username"), equalTo(authentication.getUser().principal())); + assertThat(result.get("username"), equalTo(authentication.getEffectiveSubject().getUser().principal())); } public void testRolesProperties() throws Exception { @@ -196,11 +196,11 @@ public void testRolesProperties() throws Exception { @SuppressWarnings("unchecked") Map result = ingestDocument.getFieldValue("_field", Map.class); - if (authentication.getUser().roles().length == 0) { + if (authentication.getEffectiveSubject().getUser().roles().length == 0) { assertThat(result, not(hasKey("roles"))); } else { assertThat(result, aMapWithSize(1)); - assertThat(result.get("roles"), equalTo(Arrays.asList(authentication.getUser().roles()))); + assertThat(result.get("roles"), equalTo(Arrays.asList(authentication.getEffectiveSubject().getUser().roles()))); } } @@ -222,7 +222,7 @@ public void testFullNameProperties() throws Exception { @SuppressWarnings("unchecked") Map result = ingestDocument.getFieldValue("_field", Map.class); assertThat(result, aMapWithSize(1)); - assertThat(result.get("full_name"), equalTo(authentication.getUser().fullName())); + assertThat(result.get("full_name"), equalTo(authentication.getEffectiveSubject().getUser().fullName())); } public void testEmailProperties() throws Exception { @@ -242,9 +242,9 @@ public void testEmailProperties() throws Exception { @SuppressWarnings("unchecked") Map result = ingestDocument.getFieldValue("_field", Map.class); - if (authentication.getUser().email() != null) { + if (authentication.getEffectiveSubject().getUser().email() != null) { assertThat(result, aMapWithSize(1)); - assertThat(result.get("email"), equalTo(authentication.getUser().email())); + assertThat(result.get("email"), equalTo(authentication.getEffectiveSubject().getUser().email())); } else { assertThat(result, not(hasKey("email"))); } @@ -267,11 +267,11 @@ public void testMetadataProperties() throws Exception { @SuppressWarnings("unchecked") Map result = ingestDocument.getFieldValue("_field", Map.class); - if (authentication.getUser().metadata().isEmpty()) { + if (authentication.getEffectiveSubject().getUser().metadata().isEmpty()) { assertThat(result, not(hasKey("metadata"))); } else { assertThat(result, aMapWithSize(1)); - assertThat(result.get("metadata"), equalTo(authentication.getUser().metadata())); + assertThat(result.get("metadata"), equalTo(authentication.getEffectiveSubject().getUser().metadata())); } } @@ -295,7 +295,7 @@ public void testOverwriteExistingField() throws Exception { @SuppressWarnings("unchecked") Map result = ingestDocument.getFieldValue("_field", Map.class); assertThat(result, aMapWithSize(1)); - assertThat(result.get("username"), equalTo(authentication.getUser().principal())); + assertThat(result.get("username"), equalTo(authentication.getEffectiveSubject().getUser().principal())); ingestDocument = TestIngestDocument.emptyIngestDocument(); ingestDocument.setFieldValue("_field.other", "test"); @@ -305,7 +305,7 @@ public void testOverwriteExistingField() throws Exception { @SuppressWarnings("unchecked") Map result2 = ingestDocument.getFieldValue("_field", Map.class); assertThat(result2, aMapWithSize(2)); - assertThat(result2.get("username"), equalTo(authentication.getUser().principal())); + assertThat(result2.get("username"), equalTo(authentication.getEffectiveSubject().getUser().principal())); assertThat(result2.get("other"), equalTo("test")); } diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/rest/action/oauth2/RestGetTokenActionTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/rest/action/oauth2/RestGetTokenActionTests.java index 24f77d0609a64..17ab028eb5354 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/rest/action/oauth2/RestGetTokenActionTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/rest/action/oauth2/RestGetTokenActionTests.java @@ -103,7 +103,10 @@ public void sendResponse(RestResponse restResponse) { assertThat(map, hasKey("authentication")); @SuppressWarnings("unchecked") final Map authentication = (Map) (map.get("authentication")); - assertThat(authentication, hasEntry("username", createTokenResponse.getAuthentication().getUser().principal())); + assertThat( + authentication, + hasEntry("username", createTokenResponse.getAuthentication().getEffectiveSubject().getUser().principal()) + ); assertEquals(6, map.size()); } diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/support/ApiKeyBoolQueryBuilderTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/support/ApiKeyBoolQueryBuilderTests.java index c9a5e7457f6ac..73393beaae50b 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/support/ApiKeyBoolQueryBuilderTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/support/ApiKeyBoolQueryBuilderTests.java @@ -69,7 +69,10 @@ public void testQueryForDomainAuthentication() { final QueryBuilder query = randomSimpleQuery("name"); final ApiKeyBoolQueryBuilder apiKeysQuery = ApiKeyBoolQueryBuilder.build(query, authentication); assertThat(apiKeysQuery.filter().get(0), is(QueryBuilders.termQuery("doc_type", "api_key"))); - assertThat(apiKeysQuery.filter().get(1), is(QueryBuilders.termQuery("creator.principal", authentication.getUser().principal()))); + assertThat( + apiKeysQuery.filter().get(1), + is(QueryBuilders.termQuery("creator.principal", authentication.getEffectiveSubject().getUser().principal())) + ); if (authentication.getDomain().realms().size() == 1) { assertThat( apiKeysQuery.filter().get(2), @@ -327,7 +330,10 @@ private void assertCommonFilterQueries(ApiKeyBoolQueryBuilder qb, Authentication return; } assertTrue( - tqb.stream().anyMatch(q -> q.equals(QueryBuilders.termQuery("creator.principal", authentication.getUser().principal()))) + tqb.stream() + .anyMatch( + q -> q.equals(QueryBuilders.termQuery("creator.principal", authentication.getEffectiveSubject().getUser().principal())) + ) ); assertTrue( tqb.stream() diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/transport/SecurityServerTransportInterceptorTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/transport/SecurityServerTransportInterceptorTests.java index 283529a4496c7..1d0f3e6ef4cc6 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/transport/SecurityServerTransportInterceptorTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/transport/SecurityServerTransportInterceptorTests.java @@ -293,8 +293,8 @@ public void sendRequest( when(connection.getVersion()).thenReturn(connectionVersion); sender.sendRequest(connection, "indices:foo[s]", null, null, null); assertTrue(calledWrappedSender.get()); - assertEquals(authentication.getUser(), sendingUser.get()); - assertEquals(authentication.getUser(), securityContext.getUser()); + assertEquals(authentication.getEffectiveSubject().getUser(), sendingUser.get()); + assertEquals(authentication.getEffectiveSubject().getUser(), securityContext.getUser()); assertEquals(Version.CURRENT, authRef.get().getEffectiveSubject().getVersion()); assertEquals(Version.CURRENT, authentication.getEffectiveSubject().getVersion()); } @@ -359,8 +359,8 @@ public void sendRequest( when(connection.getVersion()).thenReturn(connectionVersion); sender.sendRequest(connection, "indices:foo[s]", null, null, null); assertTrue(calledWrappedSender.get()); - assertEquals(authentication.getUser(), sendingUser.get()); - assertEquals(authentication.getUser(), securityContext.getUser()); + assertEquals(authentication.getEffectiveSubject().getUser(), sendingUser.get()); + assertEquals(authentication.getEffectiveSubject().getUser(), securityContext.getUser()); assertEquals(connectionVersion, authRef.get().getEffectiveSubject().getVersion()); assertEquals(Version.CURRENT, authentication.getEffectiveSubject().getVersion()); } @@ -420,7 +420,7 @@ public void sendRequest( assertThat(calledWrappedSender.get(), is(true)); final Authentication authentication = authenticationRef.get(); assertThat(authentication, notNullValue()); - assertThat(authentication.getUser(), equalTo(originToUserMap.get(origin))); + assertThat(authentication.getEffectiveSubject().getUser(), equalTo(originToUserMap.get(origin))); assertThat(authentication.getEffectiveSubject().getVersion(), equalTo(connectionVersion)); } diff --git a/x-pack/qa/third-party/active-directory/src/test/java/org/elasticsearch/xpack/security/authc/ldap/AbstractAdLdapRealmTestCase.java b/x-pack/qa/third-party/active-directory/src/test/java/org/elasticsearch/xpack/security/authc/ldap/AbstractAdLdapRealmTestCase.java index cfdd55eee52d7..72ccea479277f 100644 --- a/x-pack/qa/third-party/active-directory/src/test/java/org/elasticsearch/xpack/security/authc/ldap/AbstractAdLdapRealmTestCase.java +++ b/x-pack/qa/third-party/active-directory/src/test/java/org/elasticsearch/xpack/security/authc/ldap/AbstractAdLdapRealmTestCase.java @@ -299,7 +299,7 @@ private void authenticateUser(Client client, String username, int retryCount) { try { final AuthenticateResponse response = client.execute(AuthenticateAction.INSTANCE, AuthenticateRequest.INSTANCE) .actionGet(10, TimeUnit.SECONDS); - assertThat(response.authentication().getUser().principal(), is(username)); + assertThat(response.authentication().getEffectiveSubject().getUser().principal(), is(username)); return; } catch (ElasticsearchException e) { if (i == retryCount) { diff --git a/x-pack/qa/third-party/active-directory/src/test/java/org/elasticsearch/xpack/security/authc/ldap/ActiveDirectoryRunAsIT.java b/x-pack/qa/third-party/active-directory/src/test/java/org/elasticsearch/xpack/security/authc/ldap/ActiveDirectoryRunAsIT.java index 40f4854c6d5ba..1acc3bd168f00 100644 --- a/x-pack/qa/third-party/active-directory/src/test/java/org/elasticsearch/xpack/security/authc/ldap/ActiveDirectoryRunAsIT.java +++ b/x-pack/qa/third-party/active-directory/src/test/java/org/elasticsearch/xpack/security/authc/ldap/ActiveDirectoryRunAsIT.java @@ -69,7 +69,7 @@ public void testRunAs() throws Exception { AuthenticateRequest.INSTANCE ); final AuthenticateResponse response = future.get(30, TimeUnit.SECONDS); - assertThat(response.authentication().getUser().principal(), Matchers.equalTo(avenger)); + assertThat(response.authentication().getEffectiveSubject().getUser().principal(), Matchers.equalTo(avenger)); } protected Client runAsClient(String user) {