From e3b303e2c855e24474003326ee295fe5972b71a9 Mon Sep 17 00:00:00 2001 From: Chris Eager Date: Fri, 9 Oct 2026 10:28:36 -0400 Subject: [PATCH] Add expiration to TUS JWT --- .../attachments/TusAttachmentGenerator.java | 5 +- .../attachments/TusConfiguration.java | 22 +++++- .../textsecuregcm/auth/JwtGenerator.java | 6 +- .../backup/Cdn3BackupCredentialGenerator.java | 16 +++-- .../textsecuregcm/auth/JwtGeneratorTest.java | 69 ++++++++++++------- .../Cdn3BackupCredentialGeneratorTest.java | 16 ++--- .../AttachmentControllerV4Test.java | 2 +- .../grpc/AttachmentsGrpcServiceTest.java | 2 +- 8 files changed, 88 insertions(+), 50 deletions(-) diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/attachments/TusAttachmentGenerator.java b/service/src/main/java/org/whispersystems/textsecuregcm/attachments/TusAttachmentGenerator.java index b3f52ce35..170597054 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/attachments/TusAttachmentGenerator.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/attachments/TusAttachmentGenerator.java @@ -10,6 +10,7 @@ import org.whispersystems.textsecuregcm.auth.JwtGenerator; import org.whispersystems.textsecuregcm.util.HeaderUtils; import java.nio.charset.StandardCharsets; import java.time.Clock; +import java.time.Duration; import java.util.Base64; import java.util.Map; @@ -19,15 +20,17 @@ public class TusAttachmentGenerator implements AttachmentGenerator { private final JwtGenerator jwtGenerator; private final String tusUri; + private final Duration tokenExpiration; public TusAttachmentGenerator(final TusConfiguration cfg) { this.tusUri = cfg.uploadUri(); + this.tokenExpiration = cfg.tokenExpiration(); this.jwtGenerator = new JwtGenerator(cfg.userAuthenticationTokenSharedSecret().value(), Clock.systemUTC()); } @Override public Descriptor generateAttachment(final String key, final long uploadLength) { - final String token = jwtGenerator.generateJwt(ATTACHMENTS, key, + final String token = jwtGenerator.generateJwt(ATTACHMENTS, key, tokenExpiration, builder -> builder.withClaim(JwtGenerator.MAX_LENGTH_CLAIM_KEY, uploadLength)); final String b64Key = Base64.getEncoder().encodeToString(key.getBytes(StandardCharsets.UTF_8)); diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/attachments/TusConfiguration.java b/service/src/main/java/org/whispersystems/textsecuregcm/attachments/TusConfiguration.java index e7c399209..f002f3c44 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/attachments/TusConfiguration.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/attachments/TusConfiguration.java @@ -5,11 +5,27 @@ package org.whispersystems.textsecuregcm.attachments; +import com.google.common.annotations.VisibleForTesting; import jakarta.validation.constraints.NotEmpty; -import jakarta.validation.constraints.Positive; +import jakarta.validation.constraints.NotNull; +import java.time.Duration; +import org.hibernate.validator.constraints.time.DurationMin; import org.whispersystems.textsecuregcm.configuration.secrets.SecretBytes; import org.whispersystems.textsecuregcm.util.ExactlySize; public record TusConfiguration( - @ExactlySize(32) SecretBytes userAuthenticationTokenSharedSecret, - @NotEmpty String uploadUri){} + @ExactlySize(32) SecretBytes userAuthenticationTokenSharedSecret, + @NotEmpty String uploadUri, + // The TUS server enforces its own `MAX_TOKEN_AGE`, so this must be greater than or equal to it. + // https://github.com/signalapp/tus-server/tree/main/src/index.ts + @NotNull @DurationMin(days = 7) Duration tokenExpiration){ + + @VisibleForTesting + public static final Duration DEFAULT_TOKEN_EXPIRATION = Duration.ofDays(7); + + public TusConfiguration { + if (tokenExpiration == null) { + tokenExpiration = DEFAULT_TOKEN_EXPIRATION; + } + } +} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/auth/JwtGenerator.java b/service/src/main/java/org/whispersystems/textsecuregcm/auth/JwtGenerator.java index a1b8662db..4c409c7fc 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/auth/JwtGenerator.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/auth/JwtGenerator.java @@ -10,6 +10,7 @@ import com.auth0.jwt.JWT; import com.auth0.jwt.JWTCreator; import com.auth0.jwt.algorithms.Algorithm; import java.time.Clock; +import java.time.Duration; import java.time.Instant; import java.util.function.Consumer; @@ -27,12 +28,13 @@ public class JwtGenerator { this.clock = clock; } - public String generateJwt(final String audience, final String subject, Consumer claimCustomizer) { + public String generateJwt(final String audience, final String subject, final Duration expiration, Consumer claimCustomizer) { final Instant now = clock.instant(); JWTCreator.Builder builder = JWT.create() .withAudience(audience) .withSubject(subject) - .withIssuedAt(now); + .withIssuedAt(now) + .withExpiresAt(now.plus(expiration)); claimCustomizer.accept(builder); return builder.sign(algorithm); } diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/backup/Cdn3BackupCredentialGenerator.java b/service/src/main/java/org/whispersystems/textsecuregcm/backup/Cdn3BackupCredentialGenerator.java index c0fb2c921..319ff5e1f 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/backup/Cdn3BackupCredentialGenerator.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/backup/Cdn3BackupCredentialGenerator.java @@ -5,25 +5,27 @@ package org.whispersystems.textsecuregcm.backup; +import java.nio.charset.StandardCharsets; +import java.time.Clock; +import java.time.Duration; +import java.util.Base64; +import java.util.Map; import org.apache.http.HttpHeaders; import org.whispersystems.textsecuregcm.attachments.TusConfiguration; import org.whispersystems.textsecuregcm.auth.JwtGenerator; import org.whispersystems.textsecuregcm.util.HeaderUtils; -import java.nio.charset.StandardCharsets; -import java.time.Clock; -import java.util.Base64; -import java.util.Map; - public class Cdn3BackupCredentialGenerator { public static final String CDN_PATH = "backups"; public static final int BACKUP_CDN = 3; private final String tusUri; + private final Duration tokenExpiration; private final JwtGenerator jwtGenerator; public Cdn3BackupCredentialGenerator(final TusConfiguration cfg) { this.tusUri = cfg.uploadUri(); + this.tokenExpiration = cfg.tokenExpiration(); this.jwtGenerator = new JwtGenerator(cfg.userAuthenticationTokenSharedSecret().value(), Clock.systemUTC()); } @@ -32,7 +34,7 @@ public class Cdn3BackupCredentialGenerator { throw new IllegalArgumentException("Upload descriptors must have non-empty keys"); } - final String token = jwtGenerator.generateJwt(CDN_PATH, key, builder -> builder + final String token = jwtGenerator.generateJwt(CDN_PATH, key, tokenExpiration, builder -> builder .withClaim(JwtGenerator.MAX_LENGTH_CLAIM_KEY, uploadSize) .withClaim(JwtGenerator.SCOPE_CLAIM_KEY, "write")); @@ -53,7 +55,7 @@ public class Cdn3BackupCredentialGenerator { throw new IllegalArgumentException("Backup subdir name must be non-empty"); } - final String token = jwtGenerator.generateJwt(CDN_PATH, hashedBackupId, builder -> builder + final String token = jwtGenerator.generateJwt(CDN_PATH, hashedBackupId, tokenExpiration, builder -> builder .withClaim(JwtGenerator.SCOPE_CLAIM_KEY, "read")); return Map.of(HttpHeaders.AUTHORIZATION, HeaderUtils.bearerAuthHeader(token)); } diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/auth/JwtGeneratorTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/auth/JwtGeneratorTest.java index 4059344fa..c46ec16a6 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/auth/JwtGeneratorTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/auth/JwtGeneratorTest.java @@ -8,9 +8,13 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import com.auth0.jwt.JWT; +import com.auth0.jwt.JWTVerifier; import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.exceptions.IncorrectClaimException; +import com.auth0.jwt.exceptions.TokenExpiredException; import com.auth0.jwt.interfaces.DecodedJWT; +import com.auth0.jwt.interfaces.Verification; +import java.time.Duration; import java.time.Instant; import org.junit.jupiter.api.Test; import org.whispersystems.textsecuregcm.util.TestClock; @@ -20,63 +24,76 @@ class JwtGeneratorTest { private static final byte[] SECRET = TestRandomUtil.nextBytes(32); private static final String AUD = "test-audience"; private static final String SUB = "test-key"; + private static final Duration EXPIRATION = Duration.ofHours(1); + + private static Verification verifier() { + return JWT.require(Algorithm.HMAC256(SECRET)) + .withAudience(AUD) + .withSubject(SUB); + } + + private static DecodedJWT verify(final Verification verification, final TestClock clock, final String token) { + return ((JWTVerifier.BaseVerification) verification).build(clock).verify(token); + } @Test public void validToken() { final TestClock clock = TestClock.pinned(Instant.EPOCH); final JwtGenerator jwtGenerator = new JwtGenerator(SECRET, clock); - final String token = jwtGenerator.generateJwt(AUD, SUB, _ -> {}); + final String token = jwtGenerator.generateJwt(AUD, SUB, EXPIRATION, _ -> {}); - final DecodedJWT decoded = JWT.require(Algorithm.HMAC256(SECRET)) - .withAudience(AUD) - .withSubject(SUB) - .build().verify(token); - assertThat(decoded.getIssuedAt()).isEqualTo(Instant.EPOCH); - assertThat(decoded.getClaims()).containsOnlyKeys("aud", "sub", "iat"); + final DecodedJWT decoded = verify(verifier(), clock, token); + assertThat(decoded.getIssuedAtAsInstant()).isEqualTo(Instant.EPOCH); + assertThat(decoded.getExpiresAtAsInstant()).isEqualTo(Instant.EPOCH.plus(EXPIRATION)); + assertThat(decoded.getClaims()).containsOnlyKeys("aud", "sub", "iat", "exp"); } @Test public void validClaims() { final TestClock clock = TestClock.pinned(Instant.EPOCH); final JwtGenerator jwtGenerator = new JwtGenerator(SECRET, clock); - final String token = jwtGenerator.generateJwt(AUD, SUB, builder -> builder + final String token = jwtGenerator.generateJwt(AUD, SUB, EXPIRATION, builder -> builder .withClaim("number", 17) .withClaim("string", "abc")); - final DecodedJWT decoded = JWT.require(Algorithm.HMAC256(SECRET)) - .withAudience(AUD) - .withSubject(SUB) + final DecodedJWT decoded = verify(verifier() .withClaim("number", 17) - .withClaim("string", "abc") - .build().verify(token); - assertThat(decoded.getIssuedAt()).isEqualTo(Instant.EPOCH); - assertThat(decoded.getClaims()).containsOnlyKeys("aud", "sub", "iat", "number", "string"); + .withClaim("string", "abc"), clock, token); + assertThat(decoded.getIssuedAtAsInstant()).isEqualTo(Instant.EPOCH); + assertThat(decoded.getClaims()).containsOnlyKeys("aud", "sub", "iat", "exp", "number", "string"); } @Test public void badAudience() { final TestClock clock = TestClock.pinned(Instant.EPOCH); final JwtGenerator jwtGenerator = new JwtGenerator(SECRET, clock); - final String token = jwtGenerator.generateJwt("bad-audience", SUB, _ -> {}); + final String token = jwtGenerator.generateJwt("bad-audience", SUB, EXPIRATION, _ -> {}); - assertThatExceptionOfType(IncorrectClaimException.class).isThrownBy(() -> JWT.require(Algorithm.HMAC256(SECRET)) - .withAudience(AUD) - .withSubject(SUB) - .build().verify(token)); + assertThatExceptionOfType(IncorrectClaimException.class).isThrownBy(() -> verify(verifier(), clock, token)); } @Test public void badCustomClaim() { final TestClock clock = TestClock.pinned(Instant.EPOCH); final JwtGenerator jwtGenerator = new JwtGenerator(SECRET, clock); - final String token = jwtGenerator.generateJwt(AUD, SUB, builder -> builder + final String token = jwtGenerator.generateJwt(AUD, SUB, EXPIRATION, builder -> builder .withClaim("number", 18)); - assertThatExceptionOfType(IncorrectClaimException.class).isThrownBy(() -> JWT.require(Algorithm.HMAC256(SECRET)) - .withAudience(AUD) - .withSubject(SUB) - .withClaim("number", 17) - .build().verify(token)); + assertThatExceptionOfType(IncorrectClaimException.class).isThrownBy(() -> verify(verifier() + .withClaim("number", 17), clock, token)); + } + + @Test + public void expiredToken() { + final TestClock clock = TestClock.pinned(Instant.EPOCH); + final JwtGenerator jwtGenerator = new JwtGenerator(SECRET, clock); + final String token = jwtGenerator.generateJwt(AUD, SUB, EXPIRATION, _ -> {}); + + clock.pin(Instant.EPOCH.plus(EXPIRATION).minusSeconds(1)); + assertThat(verify(verifier(), clock, token).getSubject()).isEqualTo(SUB); + + clock.pin(Instant.EPOCH.plus(EXPIRATION).plus(Duration.ofSeconds(1))); + assertThatExceptionOfType(TokenExpiredException.class).isThrownBy(() -> verify(verifier(), clock, token)); } } diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/backup/Cdn3BackupCredentialGeneratorTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/backup/Cdn3BackupCredentialGeneratorTest.java index 7e13c64eb..115e08029 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/backup/Cdn3BackupCredentialGeneratorTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/backup/Cdn3BackupCredentialGeneratorTest.java @@ -6,15 +6,11 @@ package org.whispersystems.textsecuregcm.backup; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatNoException; -import java.nio.charset.StandardCharsets; -import java.util.Base64; -import java.util.Map; import com.auth0.jwt.JWT; -import com.auth0.jwt.JWTVerifier; import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.interfaces.DecodedJWT; +import java.util.Map; import org.junit.jupiter.api.Test; import org.whispersystems.textsecuregcm.attachments.TusConfiguration; import org.whispersystems.textsecuregcm.configuration.secrets.SecretBytes; @@ -28,7 +24,8 @@ public class Cdn3BackupCredentialGeneratorTest { public void uploadGenerator() { final Cdn3BackupCredentialGenerator generator = new Cdn3BackupCredentialGenerator(new TusConfiguration( new SecretBytes(SECRET), - "https://example.org/upload")); + "https://example.org/upload", + TusConfiguration.DEFAULT_TOKEN_EXPIRATION)); final BackupUploadDescriptor messageBackupUploadDescriptor = generator.generateUpload("subdir/key", MAX_UPLOAD_LENGTH); assertThat(messageBackupUploadDescriptor.signedUploadLocation()).isEqualTo("https://example.org/upload/backups"); @@ -42,14 +39,15 @@ public class Cdn3BackupCredentialGeneratorTest { .withClaim("scope", "write") .withClaim("maxLen", MAX_UPLOAD_LENGTH) .build().verify(token); - assertThat(decoded.getClaims()).containsOnlyKeys("aud", "sub", "scope", "iat", "maxLen"); + assertThat(decoded.getClaims()).containsOnlyKeys("aud", "sub", "scope", "iat", "exp", "maxLen"); } @Test public void readCredential() { final Cdn3BackupCredentialGenerator generator = new Cdn3BackupCredentialGenerator(new TusConfiguration( new SecretBytes(SECRET), - "https://example.org/upload")); + "https://example.org/upload", + TusConfiguration.DEFAULT_TOKEN_EXPIRATION)); final Map headers = generator.readHeaders("subdir"); assertThat(headers).containsKey("Authorization"); @@ -58,7 +56,7 @@ public class Cdn3BackupCredentialGeneratorTest { .withSubject("subdir") .withClaim("scope", "read") .build().verify(parseBearerToken(headers.get("Authorization"))); - assertThat(decoded.getClaims()).containsOnlyKeys("aud", "sub", "scope", "iat"); + assertThat(decoded.getClaims()).containsOnlyKeys("aud", "sub", "scope", "iat", "exp"); } private static String parseBearerToken(final String authHeader) { diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/AttachmentControllerV4Test.java b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/AttachmentControllerV4Test.java index e34def924..569076d84 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/AttachmentControllerV4Test.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/AttachmentControllerV4Test.java @@ -108,7 +108,7 @@ class AttachmentControllerV4Test { .addProvider(new RateLimitExceededExceptionMapper()) .addProvider(new AttachmentControllerV4(RATE_LIMITERS, gcsAttachmentGenerator, - new TusAttachmentGenerator(new TusConfiguration(new SecretBytes(TUS_SECRET), TUS_URL)), + new TusAttachmentGenerator(new TusConfiguration(new SecretBytes(TUS_SECRET), TUS_URL, TusConfiguration.DEFAULT_TOKEN_EXPIRATION)), EXPERIMENT_MANAGER, MAX_UPLOAD_LENGTH)) .build(); } catch (IOException | InvalidKeyException | InvalidKeySpecException e) { diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/AttachmentsGrpcServiceTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/AttachmentsGrpcServiceTest.java index cc2cb0b46..2324d49f4 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/AttachmentsGrpcServiceTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/AttachmentsGrpcServiceTest.java @@ -86,7 +86,7 @@ class AttachmentsGrpcServiceTest extends final GcsAttachmentGenerator gcsAttachmentGenerator = new GcsAttachmentGenerator( "some-cdn.signal.org", "signal@example.com", "/attach-here", gcsPrivateKeyPem); final TusAttachmentGenerator tusAttachmentGenerator = - new TusAttachmentGenerator(new TusConfiguration(new SecretBytes(TUS_SECRET), TUS_URL)); + new TusAttachmentGenerator(new TusConfiguration(new SecretBytes(TUS_SECRET), TUS_URL, TusConfiguration.DEFAULT_TOKEN_EXPIRATION)); return new AttachmentsGrpcService( experimentEnrollmentManager,