yadavay-amzn commented on code in PR #57262: URL: https://github.com/apache/spark/pull/57262#discussion_r3583874029
########## core/src/main/java/org/apache/spark/security/credentials/FileTokenIngestor.java: ########## @@ -0,0 +1,139 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.spark.security.credentials; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Instant; +import java.util.Date; +import java.util.Optional; + +import io.jsonwebtoken.Claims; +import io.jsonwebtoken.Jwts; + +import org.apache.spark.annotation.DeveloperApi; +import org.apache.spark.internal.SparkLogger; +import org.apache.spark.internal.SparkLoggerFactory; +import org.apache.spark.security.UserContext; + +/** + * :: DeveloperApi :: + * A {@link TokenIngestor} that reads an OIDC identity token from a file. + * <p> + * The file path is typically a Kubernetes projected service account token + * (e.g., {@code /var/run/secrets/tokens/spark-identity}) or a path configured via + * {@code spark.security.credentials.identityToken.file}. + * <p> + * This implementation: + * <ul> + * <li>Detects file rotation via mtime change (only re-parses when the file changes)</li> + * <li>Parses JWT claims without signature verification (unsigned claims parsing) + * since the token is trusted from the local filesystem</li> + * <li>Handles errors gracefully: malformed JWT, missing file, or empty content + * returns empty rather than throwing</li> + * </ul> + * + * @since 4.3.0 + */ +@DeveloperApi +public class FileTokenIngestor implements TokenIngestor { + + private static final SparkLogger LOG = SparkLoggerFactory.getLogger(FileTokenIngestor.class); + + private final Path tokenPath; + private volatile long lastMtime = -1L; + private volatile UserContext cachedContext = null; + + /** + * Construct a new FileTokenIngestor. + * + * @param tokenPath path to the identity token file (must not be null) + */ + public FileTokenIngestor(Path tokenPath) { + this.tokenPath = tokenPath; + } + + @Override + public Optional<UserContext> load() { + try { + if (!Files.exists(tokenPath)) { + LOG.debug("Token file does not exist: {}", tokenPath); + return Optional.empty(); + } + + // File did not change since last successful parse + long currentMtime = Files.getLastModifiedTime(tokenPath).toMillis(); + if (currentMtime == lastMtime && cachedContext != null) { + return Optional.of(cachedContext); + } + + // Read the token contents and check for emptiness + String content = new String(Files.readAllBytes(tokenPath), "UTF-8").trim(); + if (content.isEmpty()) { + LOG.warn("Token file is empty: " + tokenPath); + return Optional.empty(); + } + + Optional<UserContext> userContext = parseJwt(content); + if (userContext.isPresent()) { + lastMtime = currentMtime; + cachedContext = userContext.get(); + } + return userContext; + } catch (Exception e) { + LOG.warn("Failed to load token from " + tokenPath, e); + return Optional.empty(); + } + } + + /** + * Parse a JWT token string into a UserContext using unsigned claims parsing. + * The token is trusted from the local filesystem. No need to verify the signature. + */ + private Optional<UserContext> parseJwt(String token) { + try { + Claims claims = Jwts.parser() + .unsecured() + .build() + .parseUnsecuredClaims(token) Review Comment: I think there might be an issue here: this only accepts unsigned JWTs (`alg: none`), but a Kubernetes projected service account token is a signed JWT (RS256), as is any real OIDC IdP token. I tried it against jjwt 0.13.0 and a signed token throws `UnsupportedJwtException: Cannot verify JWS signature: unable to locate signature verification key`, so it looks like `load()` would return empty for the production input this ingestor targets. Stripping the signature and passing `header.payload.` didn't work for me either, since jjwt sees the `alg` header and still requires the signature. Since the token is trusted (local FS, kubelet-delivered) and the signature is re-verified downstream at exchange, I think a possible fix is to read the claims without going through the JWS parser, by decoding the payload segment directly rather than routing a signed token through `parseUnsecuredClaims`. Happy to pair on the exact jjwt call if useful; I confirmed `Base64.getUrlDecoder().decode(parts[1])` gives back the claims JSON for a signed token. ########## core/src/main/java/org/apache/spark/security/credentials/FileTokenIngestor.java: ########## @@ -0,0 +1,139 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.spark.security.credentials; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Instant; +import java.util.Date; +import java.util.Optional; + +import io.jsonwebtoken.Claims; +import io.jsonwebtoken.Jwts; + +import org.apache.spark.annotation.DeveloperApi; +import org.apache.spark.internal.SparkLogger; +import org.apache.spark.internal.SparkLoggerFactory; +import org.apache.spark.security.UserContext; + +/** + * :: DeveloperApi :: + * A {@link TokenIngestor} that reads an OIDC identity token from a file. + * <p> + * The file path is typically a Kubernetes projected service account token + * (e.g., {@code /var/run/secrets/tokens/spark-identity}) or a path configured via + * {@code spark.security.credentials.identityToken.file}. + * <p> + * This implementation: + * <ul> + * <li>Detects file rotation via mtime change (only re-parses when the file changes)</li> + * <li>Parses JWT claims without signature verification (unsigned claims parsing) + * since the token is trusted from the local filesystem</li> + * <li>Handles errors gracefully: malformed JWT, missing file, or empty content + * returns empty rather than throwing</li> + * </ul> + * + * @since 4.3.0 + */ +@DeveloperApi +public class FileTokenIngestor implements TokenIngestor { + + private static final SparkLogger LOG = SparkLoggerFactory.getLogger(FileTokenIngestor.class); + + private final Path tokenPath; + private volatile long lastMtime = -1L; + private volatile UserContext cachedContext = null; + + /** + * Construct a new FileTokenIngestor. + * + * @param tokenPath path to the identity token file (must not be null) + */ + public FileTokenIngestor(Path tokenPath) { + this.tokenPath = tokenPath; + } + + @Override + public Optional<UserContext> load() { + try { + if (!Files.exists(tokenPath)) { + LOG.debug("Token file does not exist: {}", tokenPath); + return Optional.empty(); + } + + // File did not change since last successful parse + long currentMtime = Files.getLastModifiedTime(tokenPath).toMillis(); + if (currentMtime == lastMtime && cachedContext != null) { + return Optional.of(cachedContext); + } + + // Read the token contents and check for emptiness + String content = new String(Files.readAllBytes(tokenPath), "UTF-8").trim(); + if (content.isEmpty()) { + LOG.warn("Token file is empty: " + tokenPath); + return Optional.empty(); + } + + Optional<UserContext> userContext = parseJwt(content); + if (userContext.isPresent()) { + lastMtime = currentMtime; + cachedContext = userContext.get(); Review Comment: Both fields are volatile, but I think publishing `lastMtime` before `cachedContext` could let a concurrent `load()` see the new mtime with the old context and return a stale token. Swapping the two lines (context first, mtime last) would avoid that. It only matters if `load()` is called concurrently, so it might be worth deciding whether it's meant to be thread-safe and noting it, since the task-2 SPI documents thread-safety. ########## core/src/test/java/org/apache/spark/security/credentials/FileTokenIngestorSuite.java: ########## @@ -0,0 +1,228 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.spark.security.credentials; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Comparator; +import java.util.Date; +import java.util.Optional; + +import io.jsonwebtoken.Jwts; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import org.apache.spark.security.UserContext; + +import static org.junit.jupiter.api.Assertions.*; + +public class FileTokenIngestorSuite { + + private Path tempDir; + + @BeforeEach + public void setUp() throws Exception { + tempDir = Files.createTempDirectory("token-ingestor-test"); + } + + @AfterEach + public void tearDown() throws Exception { + if (tempDir != null) { + Files.walk(tempDir).sorted(Comparator.reverseOrder()).forEach(path -> { try { Files.deleteIfExists(path); } catch (Exception ignored) {} }); + } + } + + private String createUnsignedJwt(String subject, String issuer, Date issuedAt, Date expiresAt) { Review Comment: One thing I noticed: every token here is built with `Jwts.builder()...compact()` and never `.signWith(...)`, so the suite only exercises unsigned tokens, which happens to be the case that works today. A signed-token case (build with `.signWith(...)`, assert a valid `UserContext` comes back) would probably catch the parsing issue above and guard against a regression. ########## core/src/main/java/org/apache/spark/security/credentials/FileTokenIngestor.java: ########## @@ -0,0 +1,139 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.spark.security.credentials; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Instant; +import java.util.Date; +import java.util.Optional; + +import io.jsonwebtoken.Claims; +import io.jsonwebtoken.Jwts; + +import org.apache.spark.annotation.DeveloperApi; +import org.apache.spark.internal.SparkLogger; +import org.apache.spark.internal.SparkLoggerFactory; +import org.apache.spark.security.UserContext; + +/** + * :: DeveloperApi :: + * A {@link TokenIngestor} that reads an OIDC identity token from a file. + * <p> + * The file path is typically a Kubernetes projected service account token + * (e.g., {@code /var/run/secrets/tokens/spark-identity}) or a path configured via + * {@code spark.security.credentials.identityToken.file}. + * <p> + * This implementation: + * <ul> + * <li>Detects file rotation via mtime change (only re-parses when the file changes)</li> + * <li>Parses JWT claims without signature verification (unsigned claims parsing) + * since the token is trusted from the local filesystem</li> + * <li>Handles errors gracefully: malformed JWT, missing file, or empty content + * returns empty rather than throwing</li> + * </ul> + * + * @since 4.3.0 + */ +@DeveloperApi +public class FileTokenIngestor implements TokenIngestor { + + private static final SparkLogger LOG = SparkLoggerFactory.getLogger(FileTokenIngestor.class); + + private final Path tokenPath; + private volatile long lastMtime = -1L; + private volatile UserContext cachedContext = null; + + /** + * Construct a new FileTokenIngestor. + * + * @param tokenPath path to the identity token file (must not be null) + */ + public FileTokenIngestor(Path tokenPath) { + this.tokenPath = tokenPath; + } + + @Override + public Optional<UserContext> load() { + try { + if (!Files.exists(tokenPath)) { + LOG.debug("Token file does not exist: {}", tokenPath); + return Optional.empty(); + } + + // File did not change since last successful parse + long currentMtime = Files.getLastModifiedTime(tokenPath).toMillis(); + if (currentMtime == lastMtime && cachedContext != null) { + return Optional.of(cachedContext); + } + + // Read the token contents and check for emptiness + String content = new String(Files.readAllBytes(tokenPath), "UTF-8").trim(); Review Comment: Nit: `StandardCharsets.UTF_8` would drop the checked `UnsupportedEncodingException` and the magic string. ########## core/src/main/java/org/apache/spark/security/credentials/TokenIngestor.java: ########## @@ -0,0 +1,44 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.spark.security.credentials; Review Comment: One consistency question: `UserContext`/`CredentialProvider` (tasks 1 and 2) are in `org.apache.spark.security` on master, so this splits the SPIP's `@DeveloperApi` surface across two packages. Might be worth aligning on one, though that's probably a call for Kousuke as the SPIP owner. ########## core/src/main/java/org/apache/spark/security/credentials/FileTokenIngestor.java: ########## @@ -0,0 +1,139 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.spark.security.credentials; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Instant; +import java.util.Date; +import java.util.Optional; + +import io.jsonwebtoken.Claims; +import io.jsonwebtoken.Jwts; + +import org.apache.spark.annotation.DeveloperApi; +import org.apache.spark.internal.SparkLogger; +import org.apache.spark.internal.SparkLoggerFactory; +import org.apache.spark.security.UserContext; + +/** + * :: DeveloperApi :: + * A {@link TokenIngestor} that reads an OIDC identity token from a file. + * <p> + * The file path is typically a Kubernetes projected service account token + * (e.g., {@code /var/run/secrets/tokens/spark-identity}) or a path configured via + * {@code spark.security.credentials.identityToken.file}. + * <p> + * This implementation: + * <ul> + * <li>Detects file rotation via mtime change (only re-parses when the file changes)</li> + * <li>Parses JWT claims without signature verification (unsigned claims parsing) + * since the token is trusted from the local filesystem</li> + * <li>Handles errors gracefully: malformed JWT, missing file, or empty content + * returns empty rather than throwing</li> + * </ul> + * + * @since 4.3.0 + */ +@DeveloperApi +public class FileTokenIngestor implements TokenIngestor { + + private static final SparkLogger LOG = SparkLoggerFactory.getLogger(FileTokenIngestor.class); + + private final Path tokenPath; + private volatile long lastMtime = -1L; + private volatile UserContext cachedContext = null; + + /** + * Construct a new FileTokenIngestor. + * + * @param tokenPath path to the identity token file (must not be null) + */ + public FileTokenIngestor(Path tokenPath) { + this.tokenPath = tokenPath; + } + + @Override + public Optional<UserContext> load() { + try { + if (!Files.exists(tokenPath)) { + LOG.debug("Token file does not exist: {}", tokenPath); + return Optional.empty(); + } + + // File did not change since last successful parse + long currentMtime = Files.getLastModifiedTime(tokenPath).toMillis(); + if (currentMtime == lastMtime && cachedContext != null) { + return Optional.of(cachedContext); + } + + // Read the token contents and check for emptiness + String content = new String(Files.readAllBytes(tokenPath), "UTF-8").trim(); + if (content.isEmpty()) { + LOG.warn("Token file is empty: " + tokenPath); + return Optional.empty(); + } + + Optional<UserContext> userContext = parseJwt(content); + if (userContext.isPresent()) { + lastMtime = currentMtime; + cachedContext = userContext.get(); + } + return userContext; + } catch (Exception e) { + LOG.warn("Failed to load token from " + tokenPath, e); + return Optional.empty(); + } + } + + /** + * Parse a JWT token string into a UserContext using unsigned claims parsing. + * The token is trusted from the local filesystem. No need to verify the signature. + */ + private Optional<UserContext> parseJwt(String token) { + try { + Claims claims = Jwts.parser() + .unsecured() + .build() + .parseUnsecuredClaims(token) + .getPayload(); + + String subject = claims.getSubject(); + String issuer = claims.getIssuer(); + + if (subject == null || subject.isEmpty()) { + LOG.warn("JWT token missing required 'sub' claim"); + return Optional.empty(); + } + if (issuer == null || issuer.isEmpty()) { + LOG.warn("JWT token missing required 'iss' claim"); + return Optional.empty(); + } + + Date issuedAtDate = claims.getIssuedAt(); + Date expirationDate = claims.getExpiration(); + Instant issuedAt = issuedAtDate != null ? issuedAtDate.toInstant() : null; + Instant expiresAt = expirationDate != null ? expirationDate.toInstant() : null; + + return Optional.of(new UserContext(subject, issuer, token, issuedAt, expiresAt)); + } catch (Exception e) { + LOG.warn("Failed to parse JWT token", e); Review Comment: Small thing, but for some malformed inputs jjwt's exception message can include the token text, which might put credential material in the logs. Might be safer to log `e.getClass().getName()` or a sanitized message rather than the full exception. Same thought on the `catch` in `load()`. ########## core/src/test/java/org/apache/spark/security/credentials/FileTokenIngestorSuite.java: ########## @@ -0,0 +1,228 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.spark.security.credentials; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Comparator; +import java.util.Date; +import java.util.Optional; + +import io.jsonwebtoken.Jwts; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import org.apache.spark.security.UserContext; + +import static org.junit.jupiter.api.Assertions.*; + +public class FileTokenIngestorSuite { + + private Path tempDir; + + @BeforeEach + public void setUp() throws Exception { + tempDir = Files.createTempDirectory("token-ingestor-test"); + } + + @AfterEach + public void tearDown() throws Exception { + if (tempDir != null) { + Files.walk(tempDir).sorted(Comparator.reverseOrder()).forEach(path -> { try { Files.deleteIfExists(path); } catch (Exception ignored) {} }); + } + } + + private String createUnsignedJwt(String subject, String issuer, Date issuedAt, Date expiresAt) { + var builder = Jwts.builder() + .subject(subject) + .issuer(issuer); + + if (issuedAt != null) builder.issuedAt(issuedAt); + if (expiresAt != null) builder.expiration(expiresAt); + + return builder.compact(); + } + + private String createUnsignedJwt(String subject, String issuer) { + return createUnsignedJwt(subject, issuer, new Date(), new Date(System.currentTimeMillis() + 3600000)); + } + + private String createUnsignedJwt() { + return createUnsignedJwt("system:serviceaccount:ns:sa", "https://kubernetes.default.svc"); + } + + private void writeToken(Path path, String content) throws Exception { + Files.write(path, content.getBytes("UTF-8")); + } + + @Test + public void loadReturnsValidUserContextFromTokenFile() throws Exception { + Path tokenFile = tempDir.resolve("token"); + String token = createUnsignedJwt(); + writeToken(tokenFile, token); + + FileTokenIngestor ingestor = new FileTokenIngestor(tokenFile); + Optional<UserContext> result = ingestor.load(); + + assertTrue(result.isPresent()); + UserContext ctx = result.get(); + assertEquals("system:serviceaccount:ns:sa", ctx.getPrincipal()); + assertEquals("https://kubernetes.default.svc", ctx.getIssuer()); + assertEquals(token, ctx.getRawToken()); + assertNotNull(ctx.getIssuedAt()); + assertNotNull(ctx.getExpiresAt()); + } + + @Test + public void loadDetectsFileRotation() throws Exception { + Path tokenFile = tempDir.resolve("token"); + String token1 = createUnsignedJwt("user1", "https://issuer.example.com"); + writeToken(tokenFile, token1); + + FileTokenIngestor ingestor = new FileTokenIngestor(tokenFile); + Optional<UserContext> result1 = ingestor.load(); + assertEquals("user1", result1.get().getPrincipal()); + + // Simulate token rotation: sleep to ensure mtime differs + Thread.sleep(100); + String token2 = createUnsignedJwt("user2", "https://issuer.example.com"); + writeToken(tokenFile, token2); + + Optional<UserContext> result2 = ingestor.load(); + assertEquals("user2", result2.get().getPrincipal()); + assertEquals(token2, result2.get().getRawToken()); + } + + @Test + public void loadReturnsEmptyForMissingFile() { + Path tokenFile = tempDir.resolve("nonexistent"); + FileTokenIngestor ingestor = new FileTokenIngestor(tokenFile); + assertTrue(ingestor.load().isEmpty()); + } + + @Test + public void loadReturnsEmptyForEmptyFile() throws Exception { + Path tokenFile = tempDir.resolve("token"); + writeToken(tokenFile, ""); + + FileTokenIngestor ingestor = new FileTokenIngestor(tokenFile); + assertTrue(ingestor.load().isEmpty()); + } + + @Test + public void loadReturnsEmptyForWhitespaceOnlyFile() throws Exception { + Path tokenFile = tempDir.resolve("token"); + writeToken(tokenFile, " \n\t "); + + FileTokenIngestor ingestor = new FileTokenIngestor(tokenFile); + assertTrue(ingestor.load().isEmpty()); + } + + @Test + public void loadReturnsEmptyForMalformedJwt() throws Exception { + Path tokenFile = tempDir.resolve("token"); + writeToken(tokenFile, "not-a-valid-jwt-token"); + + FileTokenIngestor ingestor = new FileTokenIngestor(tokenFile); + assertTrue(ingestor.load().isEmpty()); + } + + @Test + public void loadReturnsEmptyForJwtMissingSubClaim() throws Exception { + Path tokenFile = tempDir.resolve("token"); + String token = Jwts.builder() + .issuer("https://issuer.example.com") + .compact(); + writeToken(tokenFile, token); + + FileTokenIngestor ingestor = new FileTokenIngestor(tokenFile); + assertTrue(ingestor.load().isEmpty()); + } + + @Test + public void loadReturnsEmptyForJwtMissingIssClaim() throws Exception { + Path tokenFile = tempDir.resolve("token"); + String token = Jwts.builder() + .subject("user1") + .compact(); + writeToken(tokenFile, token); + + FileTokenIngestor ingestor = new FileTokenIngestor(tokenFile); + assertTrue(ingestor.load().isEmpty()); + } + + @Test + public void loadHandlesJwtWithoutIatAndExpClaims() throws Exception { + Path tokenFile = tempDir.resolve("token"); + String token = Jwts.builder() + .subject("user1") + .issuer("https://issuer.example.com") + .compact(); + writeToken(tokenFile, token); + + FileTokenIngestor ingestor = new FileTokenIngestor(tokenFile); + Optional<UserContext> result = ingestor.load(); + assertTrue(result.isPresent()); + assertEquals("user1", result.get().getPrincipal()); + assertNull(result.get().getIssuedAt()); + assertNull(result.get().getExpiresAt()); + } + + @Test + public void loadUsesCachedResultWhenFileUnchanged() throws Exception { + Path tokenFile = tempDir.resolve("token"); + String token = createUnsignedJwt("cached-user", "https://issuer.example.com"); + writeToken(tokenFile, token); + + FileTokenIngestor ingestor = new FileTokenIngestor(tokenFile); + Optional<UserContext> result1 = ingestor.load(); + Optional<UserContext> result2 = ingestor.load(); + + assertEquals(result1, result2); Review Comment: I think this asserts `result1.equals(result2)`, which would pass whether or not the cache was hit. Asserting reference identity (`result1.get() == result2.get()`) might prove the cached path more directly. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
