Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Move secret validation logic and authN-loadPrincipal into PolarisSecretsManager #511

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -2355,7 +2355,10 @@ public void testTokenInvalidSignature() {
@Test
public void testTokenInvalidPrincipalId() {
String newToken =
defaultJwt().withClaim(CLAIM_KEY_PRINCIPAL_ID, 0).sign(Algorithm.HMAC256("polaris"));
defaultJwt()
.withClaim(CLAIM_KEY_PRINCIPAL_ID, 0)
.withClaim(CLAIM_KEY_CLIENT_ID, "foo")
.sign(Algorithm.HMAC256("polaris"));
try (Response response =
newRequest("http://localhost:%d/api/management/v1/principals", newToken).get()) {
assertThat(response)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,13 +36,12 @@
import java.util.HashMap;
import java.util.Map;
import org.apache.polaris.core.PolarisCallContext;
import org.apache.polaris.core.auth.PolarisSecretsManager.PrincipalSecretsResult;
import org.apache.polaris.core.auth.PolarisSecretsManager;
import org.apache.polaris.core.context.CallContext;
import org.apache.polaris.core.context.RealmContext;
import org.apache.polaris.core.entity.PolarisBaseEntity;
import org.apache.polaris.core.entity.PolarisEntitySubType;
import org.apache.polaris.core.entity.PolarisEntityType;
import org.apache.polaris.core.entity.PolarisPrincipalSecrets;
import org.apache.polaris.core.persistence.PolarisMetaStoreManager;
import org.apache.polaris.service.config.DefaultConfigurationStore;
import org.junit.jupiter.api.Test;
Expand Down Expand Up @@ -116,10 +115,6 @@ public void testSuccessfulTokenGeneration() throws Exception {
CallContext.setCurrentContext(getTestCallContext(polarisCallContext));
PolarisMetaStoreManager metastoreManager = Mockito.mock(PolarisMetaStoreManager.class);
String mainSecret = "client-secret";
PolarisPrincipalSecrets principalSecrets =
new PolarisPrincipalSecrets(1L, clientId, mainSecret, "otherSecret");
Mockito.when(metastoreManager.loadPrincipalSecrets(polarisCallContext, clientId))
.thenReturn(new PrincipalSecretsResult(principalSecrets));
PolarisBaseEntity principal =
new PolarisBaseEntity(
0L,
Expand All @@ -128,8 +123,8 @@ public void testSuccessfulTokenGeneration() throws Exception {
PolarisEntitySubType.NULL_SUBTYPE,
0L,
"principal");
Mockito.when(metastoreManager.loadEntity(polarisCallContext, 0L, 1L))
.thenReturn(new PolarisMetaStoreManager.EntityResult(principal));
Mockito.when(metastoreManager.validateSecret(polarisCallContext, clientId, mainSecret))
.thenReturn(new PolarisSecretsManager.SecretValidationResult(principal));
TokenBroker tokenBroker = new JWTRSAKeyPair(metastoreManager, 420);
TokenResponse token =
tokenBroker.generateFromClientSecrets(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,12 @@
import com.auth0.jwt.interfaces.DecodedJWT;
import java.util.Map;
import org.apache.polaris.core.PolarisCallContext;
import org.apache.polaris.core.auth.PolarisSecretsManager.PrincipalSecretsResult;
import org.apache.polaris.core.auth.PolarisSecretsManager;
import org.apache.polaris.core.context.CallContext;
import org.apache.polaris.core.context.RealmContext;
import org.apache.polaris.core.entity.PolarisBaseEntity;
import org.apache.polaris.core.entity.PolarisEntitySubType;
import org.apache.polaris.core.entity.PolarisEntityType;
import org.apache.polaris.core.entity.PolarisPrincipalSecrets;
import org.apache.polaris.core.persistence.PolarisMetaStoreManager;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
Expand Down Expand Up @@ -63,10 +62,6 @@ public Map<String, Object> contextVariables() {
PolarisMetaStoreManager metastoreManager = Mockito.mock(PolarisMetaStoreManager.class);
String mainSecret = "test_secret";
String clientId = "test_client_id";
PolarisPrincipalSecrets principalSecrets =
new PolarisPrincipalSecrets(1L, clientId, mainSecret, "otherSecret");
Mockito.when(metastoreManager.loadPrincipalSecrets(polarisCallContext, clientId))
.thenReturn(new PrincipalSecretsResult(principalSecrets));
PolarisBaseEntity principal =
new PolarisBaseEntity(
0L,
Expand All @@ -75,8 +70,8 @@ public Map<String, Object> contextVariables() {
PolarisEntitySubType.NULL_SUBTYPE,
0L,
"principal");
Mockito.when(metastoreManager.loadEntity(polarisCallContext, 0L, 1L))
.thenReturn(new PolarisMetaStoreManager.EntityResult(principal));
Mockito.when(metastoreManager.validateSecret(polarisCallContext, clientId, mainSecret))
.thenReturn(new PolarisSecretsManager.SecretValidationResult(principal));
TokenBroker generator = new JWTSymmetricKeyBroker(metastoreManager, 666, () -> "polaris");
TokenResponse token =
generator.generateFromClientSecrets(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,10 @@
import jakarta.annotation.Nonnull;
import jakarta.annotation.Nullable;
import org.apache.polaris.core.PolarisCallContext;
import org.apache.polaris.core.entity.PolarisBaseEntity;
import org.apache.polaris.core.entity.PolarisPrincipalSecrets;
import org.apache.polaris.core.persistence.BaseResult;
import org.apache.polaris.core.persistence.PolarisMetaStoreManager.EntityResult;

/** Manages secrets for Polaris principals. */
public interface PolarisSecretsManager {
Expand All @@ -39,6 +41,17 @@ public interface PolarisSecretsManager {
PrincipalSecretsResult loadPrincipalSecrets(
@Nonnull PolarisCallContext callCtx, @Nonnull String clientId);

@Nonnull
SecretValidationResult validateSecret(
@Nonnull PolarisCallContext callCtx, @Nonnull String clientId, @Nonnull String clientSecret);

@Nonnull
EntityResult loadPrincipal(
@Nonnull PolarisCallContext callCtx,
@Nullable String roleName,
@Nullable String clientId,
@Nullable Long principalId);
Comment on lines +48 to +53
Copy link
Contributor

Choose a reason for hiding this comment

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

Loading the principal entity should be the purview of the persistence layer, not the secrets manager. IMO, the secrets manager should be something like Vault or AWS Secrets manager that knows nothing about Polaris entities, but does know how to store client id / secret

Copy link
Member Author

Choose a reason for hiding this comment

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

The problem is: effectively only the secrets manager knows which attributes it has at hand, correct?
Currently, it's the principal-ID, which is another unique ID in the JWT - but it should rather be just the client-ID. But that's currently hard to refactor, because the data model details leak all the way up. That's why #512 is there as an immediate follow-up.
TL;DR this PR is one of a series of upcoming PRs to untangle the hard dependency of all the services on the data model details/internals.

Copy link
Contributor

Choose a reason for hiding this comment

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

Vault, Secrets Manager, and K8s all allow storing secret values as structured types, like JSON. I think it's pretty easy to imagine a layout like using the clientId as the secret key and storing the secret value as something like {"secret": "abcd", "principalId": 1}. This allows full decoupling of the PolarisSecretsManager from the PolarisMetaStoreManager, whereas returning the PrincipalEntity from the PolarisSecretsManager means it has to maintain a reference to the MetaStore and the MetaStore has to deal with lookup keys beside name and id. No other entity has a lookup key beside name or id, so I think keeping it consistent for Principal makes sense.

Copy link
Member Author

Choose a reason for hiding this comment

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

The issue here is: there are currently two lookup keys: client-ID and principal-ID. Client-ID is the natural key, so I think that we should only use that one.

Copy link
Member Author

Choose a reason for hiding this comment

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

I think, the assumption that Polaris is the source-of-truth for principals is not correct. Principals/identities are usually managed elsewhere. It would be difficult to force people to add a principal-ID as a new attribute to new or existing identities. On top, principal-ID is an internal concern.

Copy link
Contributor

Choose a reason for hiding this comment

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

The secrets manager is only used for Polaris-managed Principals. There's no need to manage secrets for externally managed Principals. I think the assumption that Polaris is authoritative here is a safe one


/**
* Rotate secrets
*
Expand Down Expand Up @@ -100,4 +113,34 @@ public PolarisPrincipalSecrets getPrincipalSecrets() {
return principalSecrets;
}
}

/** the result of load/rotate principal secrets */
class SecretValidationResult extends BaseResult {

private final PolarisBaseEntity principal;

public SecretValidationResult(
@Nonnull BaseResult.ReturnStatus errorCode, @Nullable String extraInformation) {
super(errorCode, extraInformation);
this.principal = null;
}

public SecretValidationResult(@Nonnull PolarisBaseEntity principal) {
super(BaseResult.ReturnStatus.SUCCESS);
this.principal = principal;
}

@JsonCreator
private SecretValidationResult(
@JsonProperty("returnStatus") @Nonnull BaseResult.ReturnStatus returnStatus,
@JsonProperty("extraInformation") @Nullable String extraInformation,
@JsonProperty("principalSecrets") @Nonnull PolarisBaseEntity principal) {
super(returnStatus, extraInformation);
this.principal = principal;
}

public PolarisBaseEntity getPrincipal() {
return principal;
}
Comment on lines +142 to +144
Copy link
Contributor

Choose a reason for hiding this comment

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

Same comment on returning the principal from the secret validation command. I can imagine storing extra metadata, such as the principal id with the client id / secret, but the entity itself should be returned from the persistence layer.

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,8 @@ public enum ReturnStatus {

// error caught while sub-scoping credentials. Error message will be returned
SUBSCOPE_CREDS_ERROR(13),

SECRET_VALIDATION_FAILED(14),
;

// code for the enum
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ public Resolver prepareResolver(
callContext.getPolarisCallContext(),
metaStoreManager,
authenticatedPrincipal.getPrincipalEntity().getId(),
null, /* callerPrincipalName */
authenticatedPrincipal.getPrincipalEntity().getName(),
authenticatedPrincipal.getActivatedPrincipalRoleNames().isEmpty()
? null
: authenticatedPrincipal.getActivatedPrincipalRoleNames(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@
*/
package org.apache.polaris.core.persistence;

import static com.google.common.base.Preconditions.checkArgument;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
Expand Down Expand Up @@ -55,6 +57,7 @@
import org.apache.polaris.core.storage.PolarisStorageActions;
import org.apache.polaris.core.storage.PolarisStorageConfigurationInfo;
import org.apache.polaris.core.storage.PolarisStorageIntegration;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

Expand Down Expand Up @@ -1006,6 +1009,61 @@ public Map<String, String> deserializeProperties(PolarisCallContext callCtx, Str
: new PrincipalSecretsResult(secrets);
}

@Override
public @NotNull SecretValidationResult validateSecret(
@NotNull PolarisCallContext callCtx, @NotNull String clientId, @NotNull String clientSecret) {
PrincipalSecretsResult principalSecrets = loadPrincipalSecrets(callCtx, clientId);
if (!principalSecrets.isSuccess()
|| !principalSecrets.getPrincipalSecrets().matchesSecret(clientSecret)) {
return new SecretValidationResult(BaseResult.ReturnStatus.SECRET_VALIDATION_FAILED, "");
}
PolarisMetaStoreManager.EntityResult result =
loadEntity(callCtx, 0L, principalSecrets.getPrincipalSecrets().getPrincipalId());
if (!result.isSuccess() || result.getEntity().getType() != PolarisEntityType.PRINCIPAL) {
return new SecretValidationResult(BaseResult.ReturnStatus.SECRET_VALIDATION_FAILED, "");
}
return new SecretValidationResult(result.getEntity());
}

@Override
public @NotNull EntityResult loadPrincipal(
@NotNull PolarisCallContext callCtx,
@Nullable String roleName,
@Nullable String clientId,
@Nullable Long principalId) {
checkArgument(principalId != null || clientId != null || roleName != null);
if (principalId != null && principalId > 0) {
EntityResult result = loadEntity(callCtx, 0L, principalId);
if (result.isSuccess() && result.getEntity().getType() == PolarisEntityType.PRINCIPAL) {
return result;
}
}
if (roleName != null) {
EntityResult result =
readEntityByName(
callCtx,
null,
PolarisEntityType.PRINCIPAL,
PolarisEntitySubType.NULL_SUBTYPE,
roleName);
if (result.isSuccess()) {
return result;
}
}
if (clientId != null) {
PrincipalSecretsResult principalSecrets = loadPrincipalSecrets(callCtx, clientId);
if (principalSecrets.isSuccess()
&& principalSecrets.getPrincipalSecrets().getPrincipalId() > 0) {
EntityResult result =
loadEntity(callCtx, 0L, principalSecrets.getPrincipalSecrets().getPrincipalId());
if (result.isSuccess() && result.getEntity().getType() == PolarisEntityType.PRINCIPAL) {
return result;
}
}
}
return new EntityResult(BaseResult.ReturnStatus.ENTITY_NOT_FOUND, "");
}

/** See {@link #} */
private @Nullable PolarisPrincipalSecrets rotatePrincipalSecrets(
@Nonnull PolarisCallContext callCtx,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
import org.apache.polaris.core.entity.PolarisEntityType;
import org.apache.polaris.core.entity.PolarisPrivilege;
import org.apache.polaris.core.storage.PolarisStorageActions;
import org.jetbrains.annotations.NotNull;

/**
* Wraps an existing impl of PolarisMetaStoreManager and delegates expected "read" operations
Expand Down Expand Up @@ -129,6 +130,23 @@ public PrincipalSecretsResult loadPrincipalSecrets(
return null;
}

@Override
public @NotNull SecretValidationResult validateSecret(
@NotNull PolarisCallContext callCtx, @NotNull String clientId, @NotNull String clientSecret) {
callCtx.getDiagServices().fail("illegal_method_in_transaction_workspace", "validateSecret");
return null;
}

@Override
public @NotNull EntityResult loadPrincipal(
@NotNull PolarisCallContext callCtx,
@Nullable String roleName,
@Nullable String clientId,
@Nullable Long principalId) {
callCtx.getDiagServices().fail("illegal_method_in_transaction_workspace", "validateSecret");
return null;
}

@Override
public PrincipalSecretsResult rotatePrincipalSecrets(
@Nonnull PolarisCallContext callCtx,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,6 @@
import org.apache.polaris.core.context.CallContext;
import org.apache.polaris.core.context.RealmContext;
import org.apache.polaris.core.entity.PolarisEntity;
import org.apache.polaris.core.entity.PolarisEntitySubType;
import org.apache.polaris.core.entity.PolarisEntityType;
import org.apache.polaris.core.entity.PrincipalEntity;
import org.apache.polaris.core.persistence.MetaStoreManagerFactory;
import org.apache.polaris.core.persistence.PolarisMetaStoreManager;
Expand Down Expand Up @@ -65,17 +63,12 @@ protected Optional<AuthenticatedPolarisPrincipal> getPrincipal(DecodedToken toke
PolarisEntity principal;
try {
principal =
tokenInfo.getPrincipalId() > 0
? PolarisEntity.of(
metaStoreManager.loadEntity(
getCurrentPolarisContext(), 0L, tokenInfo.getPrincipalId()))
: PolarisEntity.of(
metaStoreManager.readEntityByName(
getCurrentPolarisContext(),
null,
PolarisEntityType.PRINCIPAL,
PolarisEntitySubType.NULL_SUBTYPE,
tokenInfo.getSub()));
PolarisEntity.of(
metaStoreManager.loadPrincipal(
getCurrentPolarisContext(),
tokenInfo.getSub(),
tokenInfo.getClientId(),
tokenInfo.getPrincipalId()));
} catch (Exception e) {
LOGGER
.atError()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,8 @@
import jakarta.annotation.Nonnull;
import java.util.Optional;
import org.apache.polaris.core.PolarisCallContext;
import org.apache.polaris.core.auth.PolarisSecretsManager.PrincipalSecretsResult;
import org.apache.polaris.core.auth.PolarisSecretsManager;
import org.apache.polaris.core.context.CallContext;
import org.apache.polaris.core.entity.PolarisEntityType;
import org.apache.polaris.core.entity.PrincipalEntity;
import org.apache.polaris.core.persistence.PolarisMetaStoreManager;
import org.apache.polaris.service.types.TokenType;
Expand All @@ -47,20 +46,11 @@ TokenResponse generateFromToken(
PolarisMetaStoreManager metaStoreManager, String clientId, String clientSecret) {
// Validate the principal is present and secrets match
PolarisCallContext polarisCallContext = CallContext.getCurrentContext().getPolarisCallContext();
PrincipalSecretsResult principalSecrets =
metaStoreManager.loadPrincipalSecrets(polarisCallContext, clientId);
if (!principalSecrets.isSuccess()) {
PolarisSecretsManager.SecretValidationResult result =
metaStoreManager.validateSecret(polarisCallContext, clientId, clientSecret);
if (!result.isSuccess()) {
return Optional.empty();
}
if (!principalSecrets.getPrincipalSecrets().matchesSecret(clientSecret)) {
return Optional.empty();
}
PolarisMetaStoreManager.EntityResult result =
metaStoreManager.loadEntity(
polarisCallContext, 0L, principalSecrets.getPrincipalSecrets().getPrincipalId());
if (!result.isSuccess() || result.getEntity().getType() != PolarisEntityType.PRINCIPAL) {
return Optional.empty();
}
return Optional.of(PrincipalEntity.of(result.getEntity()));
return Optional.of(PrincipalEntity.of(result.getPrincipal()));
}
}
Loading