Skip to content

Commit d91dbd0

Browse files
authored
Include principal name in Polaris tokens (#2389)
* Include principal name in Polaris tokens Summary of changes: - Instead of including the principal id twice in the token, the principal name is now used as the subject claim. While the default authenticator doesn't need the principal name and works with just the principal id, not having the "real" principal name available could be a problem for other authenticator implementations. - `DecodedToken` has been refactored and renamed to `InternalPolarisCredential`. It is also now a package-private component. - `TokenBroker.verify()` now returns PolarisCredential. * rename to InternalPolarisToken
1 parent f334d1a commit d91dbd0

File tree

8 files changed

+105
-95
lines changed

8 files changed

+105
-95
lines changed

runtime/service/src/main/java/org/apache/polaris/service/auth/DecodedToken.java

Lines changed: 0 additions & 50 deletions
This file was deleted.
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
/*
2+
* Licensed to the Apache Software Foundation (ASF) under one
3+
* or more contributor license agreements. See the NOTICE file
4+
* distributed with this work for additional information
5+
* regarding copyright ownership. The ASF licenses this file
6+
* to you under the Apache License, Version 2.0 (the
7+
* "License"); you may not use this file except in compliance
8+
* with the License. You may obtain a copy of the License at
9+
*
10+
* http://www.apache.org/licenses/LICENSE-2.0
11+
*
12+
* Unless required by applicable law or agreed to in writing,
13+
* software distributed under the License is distributed on an
14+
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15+
* KIND, either express or implied. See the License for the
16+
* specific language governing permissions and limitations
17+
* under the License.
18+
*/
19+
package org.apache.polaris.service.auth;
20+
21+
import com.google.common.base.Splitter;
22+
import jakarta.annotation.Nonnull;
23+
import java.util.Set;
24+
import java.util.stream.Collectors;
25+
import org.apache.polaris.immutables.PolarisImmutable;
26+
import org.immutables.value.Value;
27+
28+
/**
29+
* A specialized {@link PolarisCredential} used for internal authentication, when Polaris is the
30+
* identity provider.
31+
*
32+
* <p>Such credentials are created by the Polaris service itself, from a JWT token previously issued
33+
* by Polaris itself.
34+
*
35+
* @see JWTBroker
36+
*/
37+
@PolarisImmutable
38+
abstract class InternalPolarisToken implements PolarisCredential {
39+
40+
private static final Splitter SCOPE_SPLITTER = Splitter.on(' ').omitEmptyStrings().trimResults();
41+
42+
static InternalPolarisToken of(
43+
String principalName, Long principalId, String clientId, String scope) {
44+
return ImmutableInternalPolarisToken.builder()
45+
.principalName(principalName)
46+
.principalId(principalId)
47+
.clientId(clientId)
48+
.scope(scope)
49+
.build();
50+
}
51+
52+
@Nonnull // switch from nullable to non-nullable
53+
@Override
54+
@SuppressWarnings("NullableProblems")
55+
public abstract String getPrincipalName();
56+
57+
@Nonnull // switch from nullable to non-nullable
58+
@Override
59+
@SuppressWarnings("NullableProblems")
60+
public abstract Long getPrincipalId();
61+
62+
@Value.Lazy
63+
@Override
64+
public Set<String> getPrincipalRoles() {
65+
// Polaris stores roles in the scope claim
66+
return SCOPE_SPLITTER.splitToStream(getScope()).collect(Collectors.toSet());
67+
}
68+
69+
abstract String getClientId();
70+
71+
abstract String getScope();
72+
}

runtime/service/src/main/java/org/apache/polaris/service/auth/JWTBroker.java

Lines changed: 24 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -20,12 +20,10 @@
2020

2121
import com.auth0.jwt.JWT;
2222
import com.auth0.jwt.algorithms.Algorithm;
23-
import com.auth0.jwt.exceptions.JWTVerificationException;
2423
import com.auth0.jwt.interfaces.DecodedJWT;
2524
import com.auth0.jwt.interfaces.JWTVerifier;
2625
import java.time.Instant;
2726
import java.time.temporal.ChronoUnit;
28-
import java.util.Objects;
2927
import java.util.Optional;
3028
import java.util.UUID;
3129
import org.apache.iceberg.exceptions.NotAuthorizedException;
@@ -60,34 +58,22 @@ public abstract class JWTBroker implements TokenBroker {
6058
public abstract Algorithm getAlgorithm();
6159

6260
@Override
63-
public DecodedToken verify(String token) {
61+
public PolarisCredential verify(String token) {
62+
return verifyInternal(token);
63+
}
64+
65+
private InternalPolarisToken verifyInternal(String token) {
6466
JWTVerifier verifier = JWT.require(getAlgorithm()).withClaim(CLAIM_KEY_ACTIVE, true).build();
6567

6668
try {
6769
DecodedJWT decodedJWT = verifier.verify(token);
68-
return new DecodedToken() {
69-
@Override
70-
public Long getPrincipalId() {
71-
return decodedJWT.getClaim("principalId").asLong();
72-
}
73-
74-
@Override
75-
public String getClientId() {
76-
return decodedJWT.getClaim("client_id").asString();
77-
}
78-
79-
@Override
80-
public String getSub() {
81-
return decodedJWT.getSubject();
82-
}
83-
84-
@Override
85-
public String getScope() {
86-
return decodedJWT.getClaim("scope").asString();
87-
}
88-
};
89-
90-
} catch (JWTVerificationException e) {
70+
return InternalPolarisToken.of(
71+
decodedJWT.getSubject(),
72+
decodedJWT.getClaim(CLAIM_KEY_PRINCIPAL_ID).asLong(),
73+
decodedJWT.getClaim(CLAIM_KEY_CLIENT_ID).asString(),
74+
decodedJWT.getClaim(CLAIM_KEY_SCOPE).asString());
75+
76+
} catch (Exception e) {
9177
throw (NotAuthorizedException)
9278
new NotAuthorizedException("Failed to verify the token").initCause(e);
9379
}
@@ -110,26 +96,26 @@ public TokenResponse generateFromToken(
11096
if (subjectToken == null || subjectToken.isBlank()) {
11197
return new TokenResponse(OAuthTokenErrorResponse.Error.invalid_request);
11298
}
113-
DecodedToken decodedToken;
99+
InternalPolarisToken decodedToken;
114100
try {
115-
decodedToken = verify(subjectToken);
101+
decodedToken = verifyInternal(subjectToken);
116102
} catch (NotAuthorizedException e) {
117103
LOGGER.error("Failed to verify the token", e.getCause());
118104
return new TokenResponse(Error.invalid_client);
119105
}
120106
EntityResult principalLookup =
121107
metaStoreManager.loadEntity(
122-
polarisCallContext,
123-
0L,
124-
Objects.requireNonNull(decodedToken.getPrincipalId()),
125-
PolarisEntityType.PRINCIPAL);
108+
polarisCallContext, 0L, decodedToken.getPrincipalId(), PolarisEntityType.PRINCIPAL);
126109
if (!principalLookup.isSuccess()
127110
|| principalLookup.getEntity().getType() != PolarisEntityType.PRINCIPAL) {
128111
return new TokenResponse(OAuthTokenErrorResponse.Error.unauthorized_client);
129112
}
130113
String tokenString =
131114
generateTokenString(
132-
decodedToken.getClientId(), decodedToken.getScope(), decodedToken.getPrincipalId());
115+
decodedToken.getPrincipalName(),
116+
decodedToken.getPrincipalId(),
117+
decodedToken.getClientId(),
118+
decodedToken.getScope());
133119
return new TokenResponse(
134120
tokenString, TokenType.ACCESS_TOKEN.getValue(), maxTokenGenerationInSeconds);
135121
}
@@ -156,16 +142,18 @@ public TokenResponse generateFromClientSecrets(
156142
if (principal.isEmpty()) {
157143
return new TokenResponse(OAuthTokenErrorResponse.Error.unauthorized_client);
158144
}
159-
String tokenString = generateTokenString(clientId, scope, principal.get().getId());
145+
String tokenString =
146+
generateTokenString(principal.get().getName(), principal.get().getId(), clientId, scope);
160147
return new TokenResponse(
161148
tokenString, TokenType.ACCESS_TOKEN.getValue(), maxTokenGenerationInSeconds);
162149
}
163150

164-
private String generateTokenString(String clientId, String scope, Long principalId) {
151+
private String generateTokenString(
152+
String principalName, long principalId, String clientId, String scope) {
165153
Instant now = Instant.now();
166154
return JWT.create()
167155
.withIssuer(ISSUER_KEY)
168-
.withSubject(String.valueOf(principalId))
156+
.withSubject(principalName)
169157
.withIssuedAt(now)
170158
.withExpiresAt(now.plus(maxTokenGenerationInSeconds, ChronoUnit.SECONDS))
171159
.withJWTId(UUID.randomUUID().toString())

runtime/service/src/main/java/org/apache/polaris/service/auth/NoneTokenBrokerFactory.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ public TokenResponse generateFromToken(
6464
}
6565

6666
@Override
67-
public DecodedToken verify(String token) {
67+
public PolarisCredential verify(String token) {
6868
return null;
6969
}
7070
};

runtime/service/src/main/java/org/apache/polaris/service/auth/TokenBroker.java

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,8 @@ TokenResponse generateFromToken(
6161
PolarisCallContext polarisCallContext,
6262
TokenType requestedTokenType);
6363

64-
DecodedToken verify(String token);
64+
/** Decodes and verifies the token, then returns the associated {@link PolarisCredential}. */
65+
PolarisCredential verify(String token);
6566

6667
static @Nonnull Optional<PrincipalEntity> findPrincipalEntity(
6768
PolarisMetaStoreManager metaStoreManager,

runtime/service/src/main/java/org/apache/polaris/service/auth/internal/InternalAuthenticationMechanism.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@
3838
import java.util.Set;
3939
import org.apache.polaris.service.auth.AuthenticationRealmConfiguration;
4040
import org.apache.polaris.service.auth.AuthenticationType;
41-
import org.apache.polaris.service.auth.DecodedToken;
41+
import org.apache.polaris.service.auth.PolarisCredential;
4242
import org.apache.polaris.service.auth.TokenBroker;
4343

4444
/**
@@ -90,7 +90,7 @@ public Uni<SecurityIdentity> authenticate(
9090

9191
String credential = authHeader.substring(spaceIdx + 1);
9292

93-
DecodedToken token;
93+
PolarisCredential token;
9494
try {
9595
token = tokenBroker.verify(credential);
9696
} catch (Exception e) {

runtime/service/src/test/java/org/apache/polaris/service/auth/DefaultAuthenticatorTest.java

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ public void setUp() {
5252

5353
@Test
5454
public void testFetchPrincipalThrowsServiceExceptionOnMetastoreException() {
55-
DecodedToken token = Mockito.mock(DecodedToken.class);
55+
PolarisCredential token = Mockito.mock(PolarisCredential.class);
5656
long principalId = 100L;
5757
when(token.getPrincipalId()).thenReturn(principalId);
5858
when(metaStoreManager.loadEntity(
@@ -69,10 +69,9 @@ public void testFetchPrincipalThrowsServiceExceptionOnMetastoreException() {
6969

7070
@Test
7171
public void testFetchPrincipalThrowsNotAuthorizedWhenNotFound() {
72-
DecodedToken token = Mockito.mock(DecodedToken.class);
72+
PolarisCredential token = Mockito.mock(PolarisCredential.class);
7373
long principalId = 100L;
7474
when(token.getPrincipalId()).thenReturn(principalId);
75-
when(token.getClientId()).thenReturn("abc");
7675
when(metaStoreManager.loadEntity(
7776
authenticator.callContext.getPolarisCallContext(),
7877
0L,

runtime/service/src/test/java/org/apache/polaris/service/auth/internal/InternalAuthenticationMechanismTest.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@
3434
import org.apache.iceberg.exceptions.NotAuthorizedException;
3535
import org.apache.polaris.service.auth.AuthenticationRealmConfiguration;
3636
import org.apache.polaris.service.auth.AuthenticationType;
37-
import org.apache.polaris.service.auth.DecodedToken;
37+
import org.apache.polaris.service.auth.PolarisCredential;
3838
import org.apache.polaris.service.auth.TokenBroker;
3939
import org.junit.jupiter.api.BeforeEach;
4040
import org.junit.jupiter.api.Test;
@@ -156,7 +156,7 @@ public void testAuthenticateWithValidToken() {
156156
when(routingContext.request()).thenReturn(mock(io.vertx.core.http.HttpServerRequest.class));
157157
when(routingContext.request().getHeader("Authorization")).thenReturn("Bearer validToken");
158158

159-
DecodedToken decodedToken = mock(DecodedToken.class);
159+
PolarisCredential decodedToken = mock(PolarisCredential.class);
160160
when(tokenBroker.verify("validToken")).thenReturn(decodedToken);
161161

162162
SecurityIdentity securityIdentity = mock(SecurityIdentity.class);

0 commit comments

Comments
 (0)