From e4ab1f1ed48a643b0332812e31a8f92d5d469470 Mon Sep 17 00:00:00 2001 From: Oliver Lazoroski Date: Wed, 25 Nov 2026 12:07:45 +0100 Subject: [PATCH 1/2] fix(security): scope and expire SRT ingest tokens [SEC-2523] The SRT credentials helper embedded a permanent user token with full account access in the encoder URL. It now mints a token that carries scoped_call_cid (the backend lets it only join that call) and expires after 24 hours by default. Callers can set another lifetime, the result reports when the token expires, the helper rejects a stream id over the 512-byte SRT limit, and printing the credentials redacts the address. The ingest re-presents the token on every SFU rejoin (at least every 6h), so the lifetime must cover the whole stream. An SRT URL left in an always-on encoder now stops working after 24 hours unless a longer lifetime is requested. --- .../models/framework/SRTCredentials.java | 13 ++ src/main/java/io/getstream/services/Call.java | 87 ++++++++++++-- .../services/framework/TokenBuilder.java | 28 +++++ .../services/SRTCredentialsTest.java | 112 ++++++++++++++++++ .../services/framework/TokenBuilderTest.java | 29 +++++ 5 files changed, 258 insertions(+), 11 deletions(-) create mode 100644 src/test/java/io/getstream/services/SRTCredentialsTest.java diff --git a/src/main/java/io/getstream/models/framework/SRTCredentials.java b/src/main/java/io/getstream/models/framework/SRTCredentials.java index db5e4cf5..9f4020b3 100644 --- a/src/main/java/io/getstream/models/framework/SRTCredentials.java +++ b/src/main/java/io/getstream/models/framework/SRTCredentials.java @@ -1,10 +1,23 @@ package io.getstream.models.framework; +import java.time.Instant; import lombok.Builder; import lombok.Getter; +/** + * SRT address an encoder (OBS, ffmpeg, ...) publishes to. The address contains a user token, so + * {@link #toString()} leaves it out; call {@code getAddress()} when you need it. + */ @Builder @Getter public class SRTCredentials { String address; + + /** When the token in the address expires. */ + Instant expiresAt; + + @Override + public String toString() { + return "SRTCredentials(address=[redacted], expiresAt=" + expiresAt + ")"; + } } diff --git a/src/main/java/io/getstream/services/Call.java b/src/main/java/io/getstream/services/Call.java index b748b25f..0f4efb9b 100644 --- a/src/main/java/io/getstream/services/Call.java +++ b/src/main/java/io/getstream/services/Call.java @@ -4,6 +4,13 @@ import io.getstream.models.*; import io.getstream.models.framework.SRTCredentials; import io.getstream.models.framework.StreamResponse; +import io.getstream.services.framework.TokenBuilder; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.regex.Matcher; +import java.util.regex.Pattern; import org.jetbrains.annotations.NotNull; public class Call extends BaseCall { @@ -42,23 +49,81 @@ public StreamResponse getOrCreate() throws StreamExcept return this.getOrCreate(new GetOrCreateCallRequest()); } + /** + * Creates the SRT address an encoder (OBS, ffmpeg, ...) uses to publish into this call. The token + * in it expires after {@link #DEFAULT_SRT_TOKEN_VALIDITY}. + * + * @see #createSRTCredentials(String, Duration) + */ public SRTCredentials createSRTCredentials(@NotNull String userID) throws StreamException { + return createSRTCredentials(userID, DEFAULT_SRT_TOKEN_VALIDITY); + } + + /** + * Creates the SRT address an encoder (OBS, ffmpeg, ...) uses to publish into this call. + * + *

The address embeds a user token that can only join this call and expires after {@code + * validity}. The token is checked again whenever the stream reconnects, and at least every 6 + * hours during a stream, so it must stay valid until the stream ends. Treat the address as a + * secret. + * + * @param userID the user the encoder publishes as + * @param validity how long the address works, at least one second + */ + public SRTCredentials createSRTCredentials(@NotNull String userID, @NotNull Duration validity) + throws StreamException { if (this.data == null) { throw StreamException.build( "Call object is not initialized, please call get() or getOrCreate() first"); } + return buildSRTCredentials( + data.getIngress().getSrt().getAddress(), + this.service.getSDKClient().tokenBuilder(), + userID, + callType + ":" + callID, + validity); + } + + /** Default lifetime of the token in an SRT address. */ + public static final Duration DEFAULT_SRT_TOKEN_VALIDITY = Duration.ofHours(24); + + /** SRT caps the stream id at 512 bytes; encoders refuse a longer one. */ + static final int MAX_SRT_STREAM_ID_BYTES = 512; + + private static final Pattern SRT_STREAM_ID = Pattern.compile("[?&]streamid=([^&]*)"); + + static SRTCredentials buildSRTCredentials( + @NotNull String addressTemplate, + @NotNull TokenBuilder tokenBuilder, + @NotNull String userID, + @NotNull String callCID, + @NotNull Duration validity) + throws StreamException { + if (validity == null || validity.compareTo(Duration.ofSeconds(1)) < 0) { + throw new IllegalArgumentException("validity must be at least one second"); + } - String token = this.service.getSDKClient().tokenBuilder().createToken(userID); + Instant expiresAt = Instant.now().plus(validity).truncatedTo(ChronoUnit.SECONDS); + String token = tokenBuilder.createScopedCallToken(userID, callCID, expiresAt); String[] segments = token.split("\\."); - String passphrase = segments[2]; - - return SRTCredentials.builder() - .address( - data.getIngress() - .getSrt() - .getAddress() - .replace("{passphrase}", passphrase) - .replace("{token}", token)) - .build(); + if (segments.length != 3) { + throw StreamException.build("Invalid token format"); + } + + String address = addressTemplate.replace("{passphrase}", segments[2]).replace("{token}", token); + Matcher streamID = SRT_STREAM_ID.matcher(address); + if (streamID.find()) { + int size = streamID.group(1).getBytes(StandardCharsets.UTF_8).length; + if (size > MAX_SRT_STREAM_ID_BYTES) { + throw StreamException.build( + "The SRT stream id is " + + size + + " bytes, over the " + + MAX_SRT_STREAM_ID_BYTES + + "-byte SRT limit. Use a shorter user ID or call ID."); + } + } + + return SRTCredentials.builder().address(address).expiresAt(expiresAt).build(); } } diff --git a/src/main/java/io/getstream/services/framework/TokenBuilder.java b/src/main/java/io/getstream/services/framework/TokenBuilder.java index aa5a85a7..42f10e9a 100644 --- a/src/main/java/io/getstream/services/framework/TokenBuilder.java +++ b/src/main/java/io/getstream/services/framework/TokenBuilder.java @@ -51,6 +51,34 @@ public static String createToken( return builder.compact(); } + /** + * Creates a token that can only join the call {@code callCID} (and read the app settings). The + * backend refuses it on every other endpoint and on the websocket. Unlike {@code call_cids}, + * which grants the user a role in calls, this takes access away. + * + * @param userId the user the token authenticates + * @param callCID the call the token is limited to, as {@code type:id} + * @param expiresAt when the token expires + */ + @NotNull + public String createScopedCallToken( + @NotNull String userId, @NotNull String callCID, @NotNull Instant expiresAt) { + if (userId == null || userId.isBlank()) { + throw new IllegalArgumentException("userId is required"); + } + if (callCID == null || callCID.isBlank()) { + throw new IllegalArgumentException("callCID is required"); + } + var key = Keys.hmacShaKeyFor(secret.getBytes(StandardCharsets.UTF_8)); + return Jwts.builder() + .claim("user_id", userId) + .claim("scoped_call_cid", callCID) + .issuedAt(Date.from(Instant.now().minusSeconds(5))) + .expiration(Date.from(expiresAt)) + .signWith(key, Jwts.SIG.HS256) + .compact(); + } + public String createCallToken(@NotNull CallTokenClaims claims) { return createCallToken(secret, claims); } diff --git a/src/test/java/io/getstream/services/SRTCredentialsTest.java b/src/test/java/io/getstream/services/SRTCredentialsTest.java new file mode 100644 index 00000000..b33e6070 --- /dev/null +++ b/src/test/java/io/getstream/services/SRTCredentialsTest.java @@ -0,0 +1,112 @@ +package io.getstream.services; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import io.getstream.exceptions.StreamException; +import io.getstream.models.framework.SRTCredentials; +import io.getstream.services.framework.TokenBuilder; +import io.jsonwebtoken.Claims; +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.security.Keys; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.regex.Pattern; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +public class SRTCredentialsTest { + private static final String API_KEY = "srt-test-key"; + private static final String SECRET = "a-test-secret-that-is-long-enough-for-hs256"; + private static final Pattern TOKEN = Pattern.compile("streamid=[^/]+/(.+)$"); + + private static String template(String callType, String callID) { + return "srt://ingress.stream-io-video.com:10080?mode=caller&passphrase={passphrase}&streamid=" + + API_KEY + + "." + + callType + + "." + + callID + + "/{token}"; + } + + private static SRTCredentials build(String callID, String userID, Duration validity) + throws StreamException { + return Call.buildSRTCredentials( + template("livestream", callID), + new TokenBuilder(SECRET), + userID, + "livestream:" + callID, + validity); + } + + private static String tokenOf(SRTCredentials credentials) { + var matcher = TOKEN.matcher(credentials.getAddress()); + assertTrue(matcher.find()); + return matcher.group(1); + } + + private static Claims claimsOf(String token) { + return Jwts.parser() + .verifyWith(Keys.hmacShaKeyFor(SECRET.getBytes(StandardCharsets.UTF_8))) + .build() + .parseSignedClaims(token) + .getPayload(); + } + + @Test + void embedsCallScopedTokenThatExpiresAfterTheDefaultValidity() throws StreamException { + var credentials = build("my-call", "john", Call.DEFAULT_SRT_TOKEN_VALIDITY); + var token = tokenOf(credentials); + var claims = claimsOf(token); + + assertEquals(Duration.ofHours(24), Call.DEFAULT_SRT_TOKEN_VALIDITY); + assertEquals("john", claims.get("user_id")); + assertEquals("livestream:my-call", claims.get("scoped_call_cid")); + assertNull(claims.get("call_cids")); + assertEquals(credentials.getExpiresAt(), claims.getExpiration().toInstant()); + var lifetime = + Duration.between(claims.getIssuedAt().toInstant(), claims.getExpiration().toInstant()); + assertTrue(lifetime.compareTo(Duration.ofHours(24)) >= 0, lifetime.toString()); + assertTrue(lifetime.compareTo(Duration.ofHours(24).plusSeconds(10)) <= 0, lifetime.toString()); + assertTrue(credentials.getAddress().contains("passphrase=" + token.split("\\.")[2] + "&")); + } + + @Test + void acceptsCustomValidity() throws StreamException { + var claims = claimsOf(tokenOf(build("my-call", "john", Duration.ofHours(3)))); + var lifetime = + Duration.between(claims.getIssuedAt().toInstant(), claims.getExpiration().toInstant()); + + assertTrue(lifetime.compareTo(Duration.ofHours(3)) >= 0, lifetime.toString()); + assertTrue(lifetime.compareTo(Duration.ofHours(3).plusSeconds(10)) <= 0, lifetime.toString()); + } + + @ParameterizedTest + @ValueSource(longs = {0, -1, 999}) + void rejectsValidityUnderOneSecond(long millis) { + assertThrows( + IllegalArgumentException.class, () -> build("my-call", "john", Duration.ofMillis(millis))); + } + + @Test + void rejectsStreamIdOverTheSrtLimit() { + var error = + assertThrows( + StreamException.class, + () -> build("c".repeat(200), "u".repeat(100), Call.DEFAULT_SRT_TOKEN_VALIDITY)); + assertTrue(error.getMessage().contains("512-byte SRT limit"), error.getMessage()); + } + + @Test + void toStringHidesTheAddress() throws StreamException { + var credentials = build("my-call", "john", Call.DEFAULT_SRT_TOKEN_VALIDITY); + + assertFalse(credentials.toString().contains(tokenOf(credentials))); + assertTrue(credentials.toString().contains("[redacted]")); + } +} diff --git a/src/test/java/io/getstream/services/framework/TokenBuilderTest.java b/src/test/java/io/getstream/services/framework/TokenBuilderTest.java index 31688700..60b5589c 100644 --- a/src/test/java/io/getstream/services/framework/TokenBuilderTest.java +++ b/src/test/java/io/getstream/services/framework/TokenBuilderTest.java @@ -1,11 +1,14 @@ package io.getstream.services.framework; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.security.Keys; import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.time.temporal.ChronoUnit; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.NullSource; @@ -34,4 +37,30 @@ void createTokenCarriesUserId() { .getPayload(); assertEquals("john", claims.get("user_id")); } + + @Test + void createScopedCallTokenCarriesScopeAndExpiration() { + var expiresAt = Instant.now().plusSeconds(3600).truncatedTo(ChronoUnit.SECONDS); + var token = new TokenBuilder(SECRET).createScopedCallToken("john", "livestream:abc", expiresAt); + var claims = + Jwts.parser() + .verifyWith(Keys.hmacShaKeyFor(SECRET.getBytes(StandardCharsets.UTF_8))) + .build() + .parseSignedClaims(token) + .getPayload(); + assertEquals("john", claims.get("user_id")); + assertEquals("livestream:abc", claims.get("scoped_call_cid")); + assertNull(claims.get("call_cids")); + assertEquals(expiresAt, claims.getExpiration().toInstant()); + } + + @ParameterizedTest + @NullSource + @ValueSource(strings = {"", " "}) + void createScopedCallTokenRejectsMissingCallCID(String callCID) { + var builder = new TokenBuilder(SECRET); + assertThrows( + IllegalArgumentException.class, + () -> builder.createScopedCallToken("john", callCID, Instant.now().plusSeconds(60))); + } } From 473a86fad21c08fe2cbfe05a7e22ded9a429f41a Mon Sep 17 00:00:00 2001 From: Oliver Lazoroski Date: Wed, 25 Nov 2026 14:44:25 +0100 Subject: [PATCH 2/2] fix(security): drop SRT stream id length check and credential redaction [SEC-2523] Per review on stream-node#417, the SDK no longer checks the SRT stream id length and no longer redacts the address when the credentials are printed. --- .../models/framework/SRTCredentials.java | 7 +------ src/main/java/io/getstream/services/Call.java | 21 ------------------- .../services/SRTCredentialsTest.java | 18 ---------------- 3 files changed, 1 insertion(+), 45 deletions(-) diff --git a/src/main/java/io/getstream/models/framework/SRTCredentials.java b/src/main/java/io/getstream/models/framework/SRTCredentials.java index 9f4020b3..f644fdf8 100644 --- a/src/main/java/io/getstream/models/framework/SRTCredentials.java +++ b/src/main/java/io/getstream/models/framework/SRTCredentials.java @@ -6,7 +6,7 @@ /** * SRT address an encoder (OBS, ffmpeg, ...) publishes to. The address contains a user token, so - * {@link #toString()} leaves it out; call {@code getAddress()} when you need it. + * keep it secret. */ @Builder @Getter @@ -15,9 +15,4 @@ public class SRTCredentials { /** When the token in the address expires. */ Instant expiresAt; - - @Override - public String toString() { - return "SRTCredentials(address=[redacted], expiresAt=" + expiresAt + ")"; - } } diff --git a/src/main/java/io/getstream/services/Call.java b/src/main/java/io/getstream/services/Call.java index 0f4efb9b..17847731 100644 --- a/src/main/java/io/getstream/services/Call.java +++ b/src/main/java/io/getstream/services/Call.java @@ -5,12 +5,9 @@ import io.getstream.models.framework.SRTCredentials; import io.getstream.models.framework.StreamResponse; import io.getstream.services.framework.TokenBuilder; -import java.nio.charset.StandardCharsets; import java.time.Duration; import java.time.Instant; import java.time.temporal.ChronoUnit; -import java.util.regex.Matcher; -import java.util.regex.Pattern; import org.jetbrains.annotations.NotNull; public class Call extends BaseCall { @@ -87,11 +84,6 @@ public SRTCredentials createSRTCredentials(@NotNull String userID, @NotNull Dura /** Default lifetime of the token in an SRT address. */ public static final Duration DEFAULT_SRT_TOKEN_VALIDITY = Duration.ofHours(24); - /** SRT caps the stream id at 512 bytes; encoders refuse a longer one. */ - static final int MAX_SRT_STREAM_ID_BYTES = 512; - - private static final Pattern SRT_STREAM_ID = Pattern.compile("[?&]streamid=([^&]*)"); - static SRTCredentials buildSRTCredentials( @NotNull String addressTemplate, @NotNull TokenBuilder tokenBuilder, @@ -111,19 +103,6 @@ static SRTCredentials buildSRTCredentials( } String address = addressTemplate.replace("{passphrase}", segments[2]).replace("{token}", token); - Matcher streamID = SRT_STREAM_ID.matcher(address); - if (streamID.find()) { - int size = streamID.group(1).getBytes(StandardCharsets.UTF_8).length; - if (size > MAX_SRT_STREAM_ID_BYTES) { - throw StreamException.build( - "The SRT stream id is " - + size - + " bytes, over the " - + MAX_SRT_STREAM_ID_BYTES - + "-byte SRT limit. Use a shorter user ID or call ID."); - } - } - return SRTCredentials.builder().address(address).expiresAt(expiresAt).build(); } } diff --git a/src/test/java/io/getstream/services/SRTCredentialsTest.java b/src/test/java/io/getstream/services/SRTCredentialsTest.java index b33e6070..0325dc91 100644 --- a/src/test/java/io/getstream/services/SRTCredentialsTest.java +++ b/src/test/java/io/getstream/services/SRTCredentialsTest.java @@ -1,7 +1,6 @@ package io.getstream.services; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -92,21 +91,4 @@ void rejectsValidityUnderOneSecond(long millis) { assertThrows( IllegalArgumentException.class, () -> build("my-call", "john", Duration.ofMillis(millis))); } - - @Test - void rejectsStreamIdOverTheSrtLimit() { - var error = - assertThrows( - StreamException.class, - () -> build("c".repeat(200), "u".repeat(100), Call.DEFAULT_SRT_TOKEN_VALIDITY)); - assertTrue(error.getMessage().contains("512-byte SRT limit"), error.getMessage()); - } - - @Test - void toStringHidesTheAddress() throws StreamException { - var credentials = build("my-call", "john", Call.DEFAULT_SRT_TOKEN_VALIDITY); - - assertFalse(credentials.toString().contains(tokenOf(credentials))); - assertTrue(credentials.toString().contains("[redacted]")); - } }