diff --git a/src/main/java/io/getstream/models/framework/SRTCredentials.java b/src/main/java/io/getstream/models/framework/SRTCredentials.java index db5e4cf5..f644fdf8 100644 --- a/src/main/java/io/getstream/models/framework/SRTCredentials.java +++ b/src/main/java/io/getstream/models/framework/SRTCredentials.java @@ -1,10 +1,18 @@ 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 + * keep it secret. + */ @Builder @Getter public class SRTCredentials { String address; + + /** When the token in the address expires. */ + Instant expiresAt; } diff --git a/src/main/java/io/getstream/services/Call.java b/src/main/java/io/getstream/services/Call.java index b748b25f..17847731 100644 --- a/src/main/java/io/getstream/services/Call.java +++ b/src/main/java/io/getstream/services/Call.java @@ -4,6 +4,10 @@ import io.getstream.models.*; import io.getstream.models.framework.SRTCredentials; import io.getstream.models.framework.StreamResponse; +import io.getstream.services.framework.TokenBuilder; +import java.time.Duration; +import java.time.Instant; +import java.time.temporal.ChronoUnit; import org.jetbrains.annotations.NotNull; public class Call extends BaseCall { @@ -42,23 +46,63 @@ 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); - String token = this.service.getSDKClient().tokenBuilder().createToken(userID); + 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"); + } + + Instant expiresAt = Instant.now().plus(validity).truncatedTo(ChronoUnit.SECONDS); + String token = tokenBuilder.createScopedCallToken(userID, callCID, expiresAt); String[] segments = token.split("\\."); - String passphrase = segments[2]; + if (segments.length != 3) { + throw StreamException.build("Invalid token format"); + } - return SRTCredentials.builder() - .address( - data.getIngress() - .getSrt() - .getAddress() - .replace("{passphrase}", passphrase) - .replace("{token}", token)) - .build(); + String address = addressTemplate.replace("{passphrase}", segments[2]).replace("{token}", token); + 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..0325dc91 --- /dev/null +++ b/src/test/java/io/getstream/services/SRTCredentialsTest.java @@ -0,0 +1,94 @@ +package io.getstream.services; + +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 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))); + } +} 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))); + } }