diff --git a/service/config/sample.yml b/service/config/sample.yml index ae2710595..98c7aa4bc 100644 --- a/service/config/sample.yml +++ b/service/config/sample.yml @@ -241,6 +241,7 @@ gcpAttachments: # GCP Storage configuration tus: uploadUri: https://example.org/upload userAuthenticationTokenSharedSecret: secret://tus.userAuthenticationTokenSharedSecret + maxSizeInBytes: 1024 apn: # Apple Push Notifications configuration sandbox: true diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/attachments/AttachmentGenerator.java b/service/src/main/java/org/whispersystems/textsecuregcm/attachments/AttachmentGenerator.java index e0525aa75..87457277d 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/attachments/AttachmentGenerator.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/attachments/AttachmentGenerator.java @@ -12,4 +12,6 @@ public interface AttachmentGenerator { Descriptor generateAttachment(final String key); + long maxUploadSizeInBytes(); + } diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/attachments/GcsAttachmentGenerator.java b/service/src/main/java/org/whispersystems/textsecuregcm/attachments/GcsAttachmentGenerator.java index 177a5e03b..1260f8221 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/attachments/GcsAttachmentGenerator.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/attachments/GcsAttachmentGenerator.java @@ -22,10 +22,12 @@ public class GcsAttachmentGenerator implements AttachmentGenerator { @Nonnull private final CanonicalRequestSigner canonicalRequestSigner; + private final int maxSizeInBytes; public GcsAttachmentGenerator(@Nonnull String domain, @Nonnull String email, int maxSizeInBytes, @Nonnull String pathPrefix, @Nonnull String rsaSigningKey) throws IOException, InvalidKeyException, InvalidKeySpecException { + this.maxSizeInBytes = maxSizeInBytes; this.canonicalRequestGenerator = new CanonicalRequestGenerator(domain, email, maxSizeInBytes, pathPrefix); this.canonicalRequestSigner = new CanonicalRequestSigner(rsaSigningKey); } @@ -37,6 +39,11 @@ public class GcsAttachmentGenerator implements AttachmentGenerator { return new Descriptor(getHeaderMap(canonicalRequest), getSignedUploadLocation(canonicalRequest)); } + @Override + public long maxUploadSizeInBytes() { + return this.maxSizeInBytes; + } + private String getSignedUploadLocation(@Nonnull CanonicalRequest canonicalRequest) { return "https://" + canonicalRequest.getDomain() + canonicalRequest.getResourcePath() + '?' + canonicalRequest.getCanonicalQuery() @@ -50,5 +57,4 @@ public class GcsAttachmentGenerator implements AttachmentGenerator { "x-goog-resumable", "start"); } - } 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 9fc7a71c2..94e6789a5 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/attachments/TusAttachmentGenerator.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/attachments/TusAttachmentGenerator.java @@ -6,8 +6,7 @@ package org.whispersystems.textsecuregcm.attachments; import org.apache.http.HttpHeaders; -import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials; -import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator; +import org.whispersystems.textsecuregcm.auth.JwtGenerator; import org.whispersystems.textsecuregcm.util.HeaderUtils; import java.nio.charset.StandardCharsets; import java.time.Clock; @@ -18,30 +17,31 @@ public class TusAttachmentGenerator implements AttachmentGenerator { private static final String ATTACHMENTS = "attachments"; - final ExternalServiceCredentialsGenerator credentialsGenerator; - final String tusUri; + private final JwtGenerator jwtGenerator; + private final String tusUri; + private final long maxUploadSize; public TusAttachmentGenerator(final TusConfiguration cfg) { this.tusUri = cfg.uploadUri(); - this.credentialsGenerator = credentialsGenerator(Clock.systemUTC(), cfg); - } - - private static ExternalServiceCredentialsGenerator credentialsGenerator(final Clock clock, final TusConfiguration cfg) { - return ExternalServiceCredentialsGenerator - .builder(cfg.userAuthenticationTokenSharedSecret()) - .prependUsername(false) - .withClock(clock) - .build(); + this.jwtGenerator = new JwtGenerator(cfg.userAuthenticationTokenSharedSecret().value(), Clock.systemUTC()); + this.maxUploadSize = cfg.maxSizeInBytes(); } @Override public Descriptor generateAttachment(final String key) { - final ExternalServiceCredentials credentials = credentialsGenerator.generateFor(ATTACHMENTS + "/" + key); + final String token = jwtGenerator.generateJwt(ATTACHMENTS, key, + builder -> builder.withClaim(JwtGenerator.MAX_LENGTH_CLAIM_KEY, maxUploadSize)); final String b64Key = Base64.getEncoder().encodeToString(key.getBytes(StandardCharsets.UTF_8)); + final Map headers = Map.of( - HttpHeaders.AUTHORIZATION, HeaderUtils.basicAuthHeader(credentials), + HttpHeaders.AUTHORIZATION, HeaderUtils.bearerAuthHeader(token), "Upload-Metadata", String.format("filename %s", b64Key) ); return new Descriptor(headers, tusUri + "/" + ATTACHMENTS); } + + @Override + public long maxUploadSizeInBytes() { + return maxUploadSize; + } } 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 c6f6889db..a65ded517 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/attachments/TusConfiguration.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/attachments/TusConfiguration.java @@ -6,10 +6,12 @@ package org.whispersystems.textsecuregcm.attachments; import jakarta.validation.constraints.NotEmpty; +import jakarta.validation.constraints.Positive; import org.whispersystems.textsecuregcm.configuration.secrets.SecretBytes; import org.whispersystems.textsecuregcm.util.ExactlySize; public record TusConfiguration( @ExactlySize(32) SecretBytes userAuthenticationTokenSharedSecret, - @NotEmpty String uploadUri + @NotEmpty String uploadUri, + @Positive long maxSizeInBytes ){} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/auth/JwtGenerator.java b/service/src/main/java/org/whispersystems/textsecuregcm/auth/JwtGenerator.java new file mode 100644 index 000000000..a1b8662db --- /dev/null +++ b/service/src/main/java/org/whispersystems/textsecuregcm/auth/JwtGenerator.java @@ -0,0 +1,39 @@ + +/* + * Copyright 2026 Signal Messenger, LLC + * + * SPDX-License-Identifier: AGPL-3.0-only + */ +package org.whispersystems.textsecuregcm.auth; + +import com.auth0.jwt.JWT; +import com.auth0.jwt.JWTCreator; +import com.auth0.jwt.algorithms.Algorithm; +import java.time.Clock; +import java.time.Instant; +import java.util.function.Consumer; + +/// Generates JWT tokens for external services to validate. This class always uses symmetric HMAC-SHA256 with a shared secret +public class JwtGenerator { + + public static final String MAX_LENGTH_CLAIM_KEY = "maxLen"; + public static final String SCOPE_CLAIM_KEY = "scope"; + + private final Algorithm algorithm; + private final Clock clock; + + public JwtGenerator(final byte[] sharedSecret, final Clock clock) { + this.algorithm = Algorithm.HMAC256(sharedSecret); + this.clock = clock; + } + + public String generateJwt(final String audience, final String subject, Consumer claimCustomizer) { + final Instant now = clock.instant(); + JWTCreator.Builder builder = JWT.create() + .withAudience(audience) + .withSubject(subject) + .withIssuedAt(now); + claimCustomizer.accept(builder); + return builder.sign(algorithm); + } +} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/backup/BackupManager.java b/service/src/main/java/org/whispersystems/textsecuregcm/backup/BackupManager.java index c02ae5837..5650ca5c5 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/backup/BackupManager.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/backup/BackupManager.java @@ -6,7 +6,6 @@ package org.whispersystems.textsecuregcm.backup; import com.google.common.annotations.VisibleForTesting; -import io.dropwizard.util.DataSize; import io.micrometer.core.instrument.DistributionSummary; import io.micrometer.core.instrument.Metrics; import io.micrometer.core.instrument.Tag; @@ -61,8 +60,6 @@ import javax.annotation.Nullable; public class BackupManager { static final String MESSAGE_BACKUP_NAME = "messageBackup"; - public static final long MAX_MESSAGE_BACKUP_OBJECT_SIZE = DataSize.mebibytes(101).toBytes(); - public static final long MAX_MEDIA_OBJECT_SIZE = DataSize.mebibytes(101).toBytes(); private static final String ZK_AUTHN_COUNTER_NAME = MetricsUtil.name(BackupManager.class, "authentication"); private static final String ZK_AUTHZ_FAILURE_COUNTER_NAME = MetricsUtil.name(BackupManager.class, @@ -199,7 +196,7 @@ public class BackupManager { // Report that the backup is out of quota if it cannot store a max size media object final boolean quotaExhausted = storedBackupAttributes.bytesUsed() >= - (maxTotalMediaSize - BackupManager.MAX_MEDIA_OBJECT_SIZE); + (maxTotalMediaSize - tusAttachmentGenerator.maxUploadSizeInBytes()); final Tags tags = Tags.of( UserAgentTagUtil.getPlatformTag(backupUser.userAgent()), @@ -338,7 +335,7 @@ public class BackupManager { checkBackupCredentialType(backupUser, BackupCredentialType.MEDIA); for (CopyParameters copyParameters : toCopy) { - if (copyParameters.sourceLength() > MAX_MEDIA_OBJECT_SIZE || copyParameters.sourceLength() < 0) { + if (copyParameters.sourceLength() > tusAttachmentGenerator.maxUploadSizeInBytes() || copyParameters.sourceLength() < 0) { throw new BackupInvalidArgumentException("Invalid sourceObject size"); } } @@ -732,6 +729,10 @@ public class BackupManager { .toFuture(); } + public long maxMessageBackupUploadSize() { + return tusAttachmentGenerator.maxUploadSizeInBytes(); + } + interface PresentationSignatureVerifier { Pair verifySignature(byte[] signature, ECPublicKey publicKey) throws BackupFailedZkAuthenticationException; 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 075b1708f..10c3df254 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/backup/Cdn3BackupCredentialGenerator.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/backup/Cdn3BackupCredentialGenerator.java @@ -7,8 +7,7 @@ package org.whispersystems.textsecuregcm.backup; import org.apache.http.HttpHeaders; import org.whispersystems.textsecuregcm.attachments.TusConfiguration; -import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials; -import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentialsGenerator; +import org.whispersystems.textsecuregcm.auth.JwtGenerator; import org.whispersystems.textsecuregcm.util.HeaderUtils; import java.nio.charset.StandardCharsets; @@ -17,47 +16,31 @@ 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 static String READ_PERMISSION = "read"; - private static String WRITE_PERMISSION = "write"; - private static String PERMISSION_SEPARATOR = "$"; - - // Write entities will be of the form 'write$backups/ - private static final String WRITE_ENTITY_PREFIX = String.format("%s%s%s/", WRITE_PERMISSION, PERMISSION_SEPARATOR, - CDN_PATH); - // Read entities will be of the form 'read$backups/ - private static final String READ_ENTITY_PREFIX = String.format("%s%s%s/", READ_PERMISSION, PERMISSION_SEPARATOR, - CDN_PATH); - - private final ExternalServiceCredentialsGenerator credentialsGenerator; private final String tusUri; + private final JwtGenerator jwtGenerator; + private final long maxUploadSize; public Cdn3BackupCredentialGenerator(final TusConfiguration cfg) { this.tusUri = cfg.uploadUri(); - this.credentialsGenerator = credentialsGenerator(Clock.systemUTC(), cfg); - } - - private static ExternalServiceCredentialsGenerator credentialsGenerator(final Clock clock, - final TusConfiguration cfg) { - return ExternalServiceCredentialsGenerator - .builder(cfg.userAuthenticationTokenSharedSecret()) - .prependUsername(false) - .withClock(clock) - .build(); + this.jwtGenerator = new JwtGenerator(cfg.userAuthenticationTokenSharedSecret().value(), Clock.systemUTC()); + this.maxUploadSize = cfg.maxSizeInBytes(); } public BackupUploadDescriptor generateUpload(final String key) { if (key.isBlank()) { throw new IllegalArgumentException("Upload descriptors must have non-empty keys"); } - final String entity = WRITE_ENTITY_PREFIX + key; - final ExternalServiceCredentials credentials = credentialsGenerator.generateFor(entity); + + final String token = jwtGenerator.generateJwt(CDN_PATH, key, builder -> builder + .withClaim(JwtGenerator.MAX_LENGTH_CLAIM_KEY, maxUploadSize) + .withClaim(JwtGenerator.SCOPE_CLAIM_KEY, "write")); + final String b64Key = Base64.getEncoder().encodeToString(key.getBytes(StandardCharsets.UTF_8)); final Map headers = Map.of( - HttpHeaders.AUTHORIZATION, HeaderUtils.basicAuthHeader(credentials), + HttpHeaders.AUTHORIZATION, HeaderUtils.bearerAuthHeader(token), "Upload-Metadata", String.format("filename %s", b64Key)); return new BackupUploadDescriptor( @@ -71,8 +54,9 @@ public class Cdn3BackupCredentialGenerator { if (hashedBackupId.isBlank()) { throw new IllegalArgumentException("Backup subdir name must be non-empty"); } - final ExternalServiceCredentials credentials = credentialsGenerator.generateFor( - READ_ENTITY_PREFIX + hashedBackupId); - return Map.of(HttpHeaders.AUTHORIZATION, HeaderUtils.basicAuthHeader(credentials)); + + final String token = jwtGenerator.generateJwt(CDN_PATH, hashedBackupId, builder -> builder + .withClaim(JwtGenerator.SCOPE_CLAIM_KEY, "read")); + return Map.of(HttpHeaders.AUTHORIZATION, HeaderUtils.bearerAuthHeader(token)); } } diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/controllers/ArchiveController.java b/service/src/main/java/org/whispersystems/textsecuregcm/controllers/ArchiveController.java index 19f89fbd6..959edd671 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/controllers/ArchiveController.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/controllers/ArchiveController.java @@ -596,7 +596,7 @@ public class ArchiveController { backupManager.authenticateBackupUser(presentation.presentation, signature.signature, userAgent); final boolean oversize = uploadLength - .map(length -> length > BackupManager.MAX_MESSAGE_BACKUP_OBJECT_SIZE) + .map(length -> length > backupManager.maxMessageBackupUploadSize()) .orElse(false); backupMetrics.updateMessageBackupSizeDistribution(backupUser, oversize, uploadLength); diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/BackupsAnonymousGrpcService.java b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/BackupsAnonymousGrpcService.java index 7e13c34b4..98e91e852 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/BackupsAnonymousGrpcService.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/BackupsAnonymousGrpcService.java @@ -182,7 +182,7 @@ public class BackupsAnonymousGrpcService extends SimpleBackupsAnonymousGrpc.Back switch (request.getUploadTypeCase()) { case MESSAGES -> { final long uploadLength = request.getMessages().getUploadLength(); - final boolean oversize = uploadLength > BackupManager.MAX_MESSAGE_BACKUP_OBJECT_SIZE; + final boolean oversize = uploadLength > backupManager.maxMessageBackupUploadSize(); backupMetrics.updateMessageBackupSizeDistribution(backupUser, oversize, Optional.of(uploadLength)); if (oversize) { builder.setExceedsMaxUploadLength(FailedPrecondition.getDefaultInstance()); diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/util/HeaderUtils.java b/service/src/main/java/org/whispersystems/textsecuregcm/util/HeaderUtils.java index b4ce310d6..87f5bac1a 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/util/HeaderUtils.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/util/HeaderUtils.java @@ -55,6 +55,10 @@ public final class HeaderUtils { return "Basic " + Base64.getEncoder().encodeToString((username + ":" + password).getBytes(StandardCharsets.UTF_8)); } + public static String bearerAuthHeader(final String token) { + return "Bearer " + token; + } + @Nonnull public static String getTimestampHeader() { return TIMESTAMP_HEADER + ":" + System.currentTimeMillis(); diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/auth/JwtGeneratorTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/auth/JwtGeneratorTest.java new file mode 100644 index 000000000..4059344fa --- /dev/null +++ b/service/src/test/java/org/whispersystems/textsecuregcm/auth/JwtGeneratorTest.java @@ -0,0 +1,82 @@ +/* + * Copyright 2026 Signal Messenger, LLC + * SPDX-License-Identifier: AGPL-3.0-only + */ +package org.whispersystems.textsecuregcm.auth; + +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.algorithms.Algorithm; +import com.auth0.jwt.exceptions.IncorrectClaimException; +import com.auth0.jwt.interfaces.DecodedJWT; +import java.time.Instant; +import org.junit.jupiter.api.Test; +import org.whispersystems.textsecuregcm.util.TestClock; +import org.whispersystems.textsecuregcm.util.TestRandomUtil; + +class JwtGeneratorTest { + private static final byte[] SECRET = TestRandomUtil.nextBytes(32); + private static final String AUD = "test-audience"; + private static final String SUB = "test-key"; + + @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 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"); + } + + @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 + .withClaim("number", 17) + .withClaim("string", "abc")); + + final DecodedJWT decoded = JWT.require(Algorithm.HMAC256(SECRET)) + .withAudience(AUD) + .withSubject(SUB) + .withClaim("number", 17) + .withClaim("string", "abc") + .build().verify(token); + assertThat(decoded.getIssuedAt()).isEqualTo(Instant.EPOCH); + assertThat(decoded.getClaims()).containsOnlyKeys("aud", "sub", "iat", "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, _ -> {}); + + assertThatExceptionOfType(IncorrectClaimException.class).isThrownBy(() -> JWT.require(Algorithm.HMAC256(SECRET)) + .withAudience(AUD) + .withSubject(SUB) + .build().verify(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 + .withClaim("number", 18)); + + assertThatExceptionOfType(IncorrectClaimException.class).isThrownBy(() -> JWT.require(Algorithm.HMAC256(SECRET)) + .withAudience(AUD) + .withSubject(SUB) + .withClaim("number", 17) + .build().verify(token)); + } + +} diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/backup/BackupManagerTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/backup/BackupManagerTest.java index 1d8304e88..c92599bcc 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/backup/BackupManagerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/backup/BackupManagerTest.java @@ -104,6 +104,7 @@ public class BackupManagerTest { 3, "abc", 100, COPY_ENCRYPTION_PARAM, TestRandomUtil.nextBytes(15)); private static final long MAX_TOTAL_MEDIA_BYTES = DataSize.mebibytes(1).toBytes(); + private static final long MAX_UPLOAD_SIZE = 1000; private final TestClock testClock = TestClock.now(); private final BackupAuthTestUtil backupAuthTestUtil = new BackupAuthTestUtil(testClock); @@ -151,6 +152,8 @@ public class BackupManagerTest { when(dynamicConfiguration.getBackupConfiguration()).thenReturn(backupConfiguration); when(dynamicConfigurationManager.getConfiguration()).thenReturn(dynamicConfiguration); + when(tusAttachmentGenerator.maxUploadSizeInBytes()).thenReturn(MAX_UPLOAD_SIZE); + this.backupManager = new BackupManager( backupsDb, backupAuthTestUtil.params, 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 8f38a9ecb..adf673f23 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/backup/Cdn3BackupCredentialGeneratorTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/backup/Cdn3BackupCredentialGeneratorTest.java @@ -6,46 +6,65 @@ 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 org.junit.jupiter.api.Test; import org.whispersystems.textsecuregcm.attachments.TusConfiguration; import org.whispersystems.textsecuregcm.configuration.secrets.SecretBytes; import org.whispersystems.textsecuregcm.util.TestRandomUtil; public class Cdn3BackupCredentialGeneratorTest { + private static final long MAX_UPLOAD_LENGTH = 100; + private static final byte[] SECRET = TestRandomUtil.nextBytes(32); + @Test public void uploadGenerator() { - Cdn3BackupCredentialGenerator generator = new Cdn3BackupCredentialGenerator(new TusConfiguration( - new SecretBytes(TestRandomUtil.nextBytes(32)), - "https://example.org/upload")); + final Cdn3BackupCredentialGenerator generator = new Cdn3BackupCredentialGenerator(new TusConfiguration( + new SecretBytes(SECRET), + "https://example.org/upload", + MAX_UPLOAD_LENGTH)); final BackupUploadDescriptor messageBackupUploadDescriptor = generator.generateUpload("subdir/key"); assertThat(messageBackupUploadDescriptor.signedUploadLocation()).isEqualTo("https://example.org/upload/backups"); assertThat(messageBackupUploadDescriptor.key()).isEqualTo("subdir/key"); assertThat(messageBackupUploadDescriptor.headers()).containsKey("Authorization"); - final String username = parseUsername(messageBackupUploadDescriptor.headers().get("Authorization")); - assertThat(username).isEqualTo("write$backups/subdir/key"); + final String token = parseBearerToken(messageBackupUploadDescriptor.headers().get("Authorization")); + + final DecodedJWT decoded = JWT.require(Algorithm.HMAC256(SECRET)) + .withAudience(Cdn3BackupCredentialGenerator.CDN_PATH) + .withSubject("subdir/key") + .withClaim("scope", "write") + .withClaim("maxLen", MAX_UPLOAD_LENGTH) + .build().verify(token); + assertThat(decoded.getClaims()).containsOnlyKeys("aud", "sub", "scope", "iat", "maxLen"); } @Test public void readCredential() { - Cdn3BackupCredentialGenerator generator = new Cdn3BackupCredentialGenerator(new TusConfiguration( - new SecretBytes(TestRandomUtil.nextBytes(32)), - "https://example.org/upload")); + final Cdn3BackupCredentialGenerator generator = new Cdn3BackupCredentialGenerator(new TusConfiguration( + new SecretBytes(SECRET), + "https://example.org/upload", + MAX_UPLOAD_LENGTH)); final Map headers = generator.readHeaders("subdir"); assertThat(headers).containsKey("Authorization"); - final String username = parseUsername(headers.get("Authorization")); - assertThat(username).isEqualTo("read$backups/subdir"); + final DecodedJWT decoded = JWT.require(Algorithm.HMAC256(SECRET)) + .withAudience(Cdn3BackupCredentialGenerator.CDN_PATH) + .withSubject("subdir") + .withClaim("scope", "read") + .build().verify(parseBearerToken(headers.get("Authorization"))); + assertThat(decoded.getClaims()).containsOnlyKeys("aud", "sub", "scope", "iat"); } - private static String parseUsername(final String authHeader) { - assertThat(authHeader).startsWith("Basic"); - final String encoded = authHeader.substring("Basic".length() + 1); - final String cred = new String(Base64.getDecoder().decode(encoded), StandardCharsets.UTF_8); - return cred.split(":")[0]; + private static String parseBearerToken(final String authHeader) { + assertThat(authHeader).startsWith("Bearer"); + return authHeader.substring("Bearer".length() + 1); } } diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/ArchiveControllerTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/ArchiveControllerTest.java index 9e713c9b1..2a0754d00 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/ArchiveControllerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/ArchiveControllerTest.java @@ -90,6 +90,7 @@ import reactor.core.publisher.Flux; @ExtendWith(DropwizardExtensionsSupport.class) public class ArchiveControllerTest { + private static final long MAX_MESSAGE_BACKUP_OBJECT_SIZE = 1000L; private static final AccountsManager accountsManager = mock(AccountsManager.class); private static final BackupAuthManager backupAuthManager = mock(BackupAuthManager.class); private static final BackupManager backupManager = mock(BackupManager.class); @@ -117,6 +118,8 @@ public class ArchiveControllerTest { reset(backupAuthManager); reset(backupManager); + when(backupManager.maxMessageBackupUploadSize()).thenReturn(MAX_MESSAGE_BACKUP_OBJECT_SIZE); + when(accountsManager.getByAccountIdentifier(AuthHelper.VALID_UUID)) .thenReturn(Optional.of(AuthHelper.VALID_ACCOUNT)); } @@ -612,8 +615,8 @@ public class ArchiveControllerTest { static Stream messagesUploadForm() { return Stream.of( Arguments.of(Optional.empty(), true), - Arguments.of(Optional.of(BackupManager.MAX_MESSAGE_BACKUP_OBJECT_SIZE), true), - Arguments.of(Optional.of(BackupManager.MAX_MESSAGE_BACKUP_OBJECT_SIZE + 1), false) + Arguments.of(Optional.of(MAX_MESSAGE_BACKUP_OBJECT_SIZE), true), + Arguments.of(Optional.of(MAX_MESSAGE_BACKUP_OBJECT_SIZE + 1), false) ); } 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 08ec51228..00477bce0 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/AttachmentControllerV4Test.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/AttachmentControllerV4Test.java @@ -96,7 +96,7 @@ class AttachmentControllerV4Test { .setTestContainerFactory(new GrizzlyWebTestContainerFactory()) .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, 1000)), EXPERIMENT_MANAGER)) .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 7622efee5..f3a54ab70 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/AttachmentsGrpcServiceTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/AttachmentsGrpcServiceTest.java @@ -72,7 +72,7 @@ class AttachmentsGrpcServiceTest extends final GcsAttachmentGenerator gcsAttachmentGenerator = new GcsAttachmentGenerator( "some-cdn.signal.org", "signal@example.com", 1000, "/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, 1000)); return new AttachmentsGrpcService( experimentEnrollmentManager, diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/BackupsAnonymousGrpcServiceTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/BackupsAnonymousGrpcServiceTest.java index fd8554feb..fbe9a9d11 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/BackupsAnonymousGrpcServiceTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/BackupsAnonymousGrpcServiceTest.java @@ -77,6 +77,8 @@ import reactor.core.publisher.Flux; class BackupsAnonymousGrpcServiceTest extends SimpleBaseGrpcTest { + private static final long MAX_MESSAGE_BACKUP_OBJECT_SIZE = 100; + private final UUID aci = UUID.randomUUID(); private final byte[] messagesBackupKey = TestRandomUtil.nextBytes(32); private final BackupAuthTestUtil backupAuthTestUtil = new BackupAuthTestUtil(Clock.systemUTC()); @@ -96,6 +98,7 @@ class BackupsAnonymousGrpcServiceTest extends try { when(backupManager.authenticateBackupUser(any(), any(), any())) .thenReturn(backupUser(presentation.getBackupId(), BackupCredentialType.MESSAGES, BackupLevel.PAID)); + when(backupManager.maxMessageBackupUploadSize()).thenReturn(MAX_MESSAGE_BACKUP_OBJECT_SIZE); } catch (BackupFailedZkAuthenticationException e) { Assertions.fail(e); } @@ -344,8 +347,8 @@ class BackupsAnonymousGrpcServiceTest extends static Stream messagesUploadForm() { return Stream.of( Arguments.of(Optional.empty(), true), - Arguments.of(Optional.of(BackupManager.MAX_MESSAGE_BACKUP_OBJECT_SIZE), true), - Arguments.of(Optional.of(BackupManager.MAX_MESSAGE_BACKUP_OBJECT_SIZE + 1), false) + Arguments.of(Optional.of(MAX_MESSAGE_BACKUP_OBJECT_SIZE), true), + Arguments.of(Optional.of(MAX_MESSAGE_BACKUP_OBJECT_SIZE + 1), false) ); } diff --git a/service/src/test/resources/config/test.yml b/service/src/test/resources/config/test.yml index ede6c3e34..2fd3b02b7 100644 --- a/service/src/test/resources/config/test.yml +++ b/service/src/test/resources/config/test.yml @@ -249,6 +249,7 @@ gcpAttachments: # GCP Storage configuration tus: uploadUri: https://example.org/upload userAuthenticationTokenSharedSecret: secret://tus.userAuthenticationTokenSharedSecret + maxSizeInBytes: 1024 apn: # Apple Push Notifications configuration sandbox: true