diff --git a/docs/guide/client-api.md b/docs/guide/client-api.md index a60e5a93..049e3d5f 100644 --- a/docs/guide/client-api.md +++ b/docs/guide/client-api.md @@ -747,6 +747,8 @@ When the connection fails, or stays disconnected for two seconds, the session re The timeout bounds the requests as a whole, not each read, so a server that sends its answer a byte at a time cannot stretch it. A request still out when the session times out or is cancelled is cut off at once; one still waiting for the head of its answer only from Java 16 on, and before that at its timeout. Once the server has named the session, in the head of its answer, it is deleted all the same; a session the server created for an answer that had not come yet is left for the server to time out. +Failures and reports name the URL of an endpoint or session by its scheme, host and port only, since the rest may be a secret: services take stream keys and signatures in the query, and some, such as Cloudflare Stream, in the path. A failure can go to a log as it is, apart from what the endpoint itself says in an error, which it passes on unchanged. + `session.close()` deletes the session on the server, which frees what the server holds for it, and closes the peer. Both start at once, so a slow server does not keep the peer open, and the deletion takes at most the session's timeout. The tracks a WHIP session published stay open. `session.peer()` is a regular peer, for stats and anything else. A deletion the server refuses or that fails goes to the runtime's error handler, and also fails the future of `closeAsync()`, which completes once both are done; a peer that did not close fails it too. `session.extensions()` gives the protocol extensions the endpoint offers for the session (RFC 9725, 4.9): the URL of each by its relation type, such as `urn:ietf:params:whip:ext:example:server-sent-events` (`urn:ietf:params:whep:ext:...` for WHEP), as the endpoint named them in `Link` header fields of its answer, resolved against it. Of a relation type named twice, the first counts. Links of other relation types are ignored, as WHIP and WHEP ask, apart from `ice-server`. The session uses none of the extensions itself; an application uses those it knows, and the map is empty if the endpoint named none. diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/RTCIceServer.java b/webrtc/src/main/java/dev/onvoid/webrtc/RTCIceServer.java index 9be58ed3..e73d63d8 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/RTCIceServer.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/RTCIceServer.java @@ -110,11 +110,15 @@ public boolean equals(Object obj) { Objects.equals(username, other.username); } + /** + * Describes the server for logs and messages, so without the password, + * and without {@link #hashCode()}, which is computed from it. + */ @Override public String toString() { return String.format("%s@%d [urls=%s, username=%s, password=%s, tlsCertPolicy=%s, hostname=%s, tlsAlpnProtocols=%s, tlsEllipticCurves=%s]", - RTCIceServer.class.getSimpleName(), hashCode(), - urls, username, password, tlsCertPolicy, hostname, + RTCIceServer.class.getSimpleName(), System.identityHashCode(this), + urls, username, password != null ? "***" : null, tlsCertPolicy, hostname, tlsAlpnProtocols, tlsEllipticCurves); } } diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/HttpCall.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/HttpCall.java index 0ea64f00..94857124 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/HttpCall.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/HttpCall.java @@ -276,7 +276,7 @@ CompletableFuture send(String contentType, byte[] content, int maxBody void abort() { IOException reason = remainingNanos() <= 0 ? timedOut() - : new IOException("The request to " + uri + " was aborted"); + : new IOException("The request to " + redacted(uri) + " was aborted"); CompletableFuture exchange; Body body; Future retry; @@ -337,8 +337,9 @@ private void exchange(URI target, String contentType, byte[] content, int maxBod request = builder.build(); } catch (IllegalArgumentException e) { - result.completeExceptionally(new IOException("The request to " + target + " is invalid: " - + e.getMessage(), e)); + // Without the message or the exception itself, which quote the URL + // or the value of a header field, such as the Authorization. + result.completeExceptionally(new IOException("The request to " + redacted(target) + " is invalid")); return; } @@ -374,7 +375,7 @@ private void exchange(URI target, String contentType, byte[] content, int maxBod return; } if (redirects == MAX_REDIRECTS) { - result.completeExceptionally(new IOException("The request to " + uri + result.completeExceptionally(new IOException("The request to " + redacted(uri) + " was redirected more than " + MAX_REDIRECTS + " times")); return; } @@ -407,7 +408,7 @@ private HttpResponse.BodySubscriber head(HttpResponse.ResponseInfo info, synchronized (this) { if (aborted) { - body.stop(new IOException("The request to " + uri + " was aborted")); + body.stop(new IOException("The request to " + redacted(uri) + " was aborted")); return body; } @@ -505,19 +506,19 @@ private static URI redirectTarget(URI from, String location) throws IOException target = from.resolve(location.trim()); } catch (IllegalArgumentException e) { - throw new IOException("The server redirected to an invalid URL: " + location); + throw new IOException("The server redirected to an invalid URL"); } String scheme = target.getScheme(); if (!"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) { - throw new IOException("The server redirected to a URL that is not http: " + target); + throw new IOException("The server redirected to a URL that is not http: " + redacted(target)); } if ("https".equalsIgnoreCase(from.getScheme()) && !"https".equalsIgnoreCase(scheme)) { - throw new IOException("The server redirected to a URL without TLS: " + target); + throw new IOException("The server redirected to a URL without TLS: " + redacted(target)); } if (!"https".equalsIgnoreCase(scheme) && !isLoopback(target.getHost())) { - throw new IOException("The server redirected to a URL without TLS: " + target); + throw new IOException("The server redirected to a URL without TLS: " + redacted(target)); } return target; @@ -557,12 +558,36 @@ static boolean isLoopback(String host) { } } + /** + * Names a URL in a message, by its scheme, host and port only, since what + * a message says ends up in logs. The rest of a URL may be a secret, and + * not only its user info and query: Cloudflare Stream, for one, has the + * key to publish with as a segment of the path. + * + * @param uri the URL. + * + * @return the URL without what may be a secret, such as {@code + * https://example.com:8443}. + */ + static String redacted(URI uri) { + String scheme = uri.getScheme() != null ? uri.getScheme() + ":" : ""; + String authority = uri.getRawAuthority(); + + if (authority == null) { + return scheme.isEmpty() ? "a URL without a scheme" : scheme; + } + + // The raw authority, since a host that is not a valid one, as with an + // underscore, leaves getHost() and getUserInfo() null. + return scheme + "//" + authority.substring(authority.lastIndexOf('@') + 1); + } + private long remainingNanos() { return limit - (System.nanoTime() - start); } private HttpTimeoutException timedOut() { - return new HttpTimeoutException("The request to " + uri + " did not complete within " + timeout); + return new HttpTimeoutException("The request to " + redacted(uri) + " did not complete within " + timeout); } private static Throwable unwrap(Throwable error) { diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/HttpIce.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/HttpIce.java index 23c205a2..5899cf3d 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/HttpIce.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/HttpIce.java @@ -16,6 +16,8 @@ package dev.onvoid.webrtc.client; +import static dev.onvoid.webrtc.client.HttpCall.redacted; + import java.net.URI; import java.net.http.HttpClient; import java.nio.charset.StandardCharsets; @@ -273,7 +275,7 @@ private UnaryOperator answered(HttpCall request, HttpCall.Response respo } if (error != null) { - throw new WebRtcException("Restarting ICE of the session " + target + " failed: " + error.getMessage(), + throw new WebRtcException("Restarting ICE of the session " + redacted(target) + " failed: " + error.getMessage(), error); } if (UNSUPPORTED.contains(response.status)) { @@ -281,17 +283,17 @@ private UnaryOperator answered(HttpCall request, HttpCall.Response respo restartsRefused = true; } - throw response.error("The session " + target + " takes no ICE restarts: " + response.describe()); + throw response.error("The session " + redacted(target) + " takes no ICE restarts: " + response.describe()); } if (response.status / 100 != 2) { - throw response.error("The session " + target + " answered the ICE restart with " + response.describe()); + throw response.error("The session " + redacted(target) + " answered the ICE restart with " + response.describe()); } HttpSession.requireContentType(response, FRAGMENT_TYPE); Fragment remote = Fragment.parse(response.body); if (remote.ufrag == null || remote.pwd == null) { - throw new WebRtcException("The session " + target + " answered the ICE restart without " + throw new WebRtcException("The session " + redacted(target) + " answered the ICE restart without " + "its new ICE credentials"); } @@ -391,10 +393,10 @@ private void flush() { // An error status is the cause, for its status. Throwable cause = error != null ? error - : response.error("The session " + target + " answered the candidates with " + : response.error("The session " + redacted(target) + " answered the candidates with " + response.describe()); - rtc.reportError(new WebRtcException("Sending ICE candidates to the session " + target + rtc.reportError(new WebRtcException("Sending ICE candidates to the session " + redacted(target) + " failed, and no more are sent: " + (error != null ? error.getMessage() : response.describe()), cause)); @@ -491,7 +493,7 @@ private void restartByItself() { } if (report) { - rtc.reportError(new WebRtcException("Restarting ICE of the session " + target + rtc.reportError(new WebRtcException("Restarting ICE of the session " + redacted(target) + " after the connection broke failed", PeerImpl.unwrap(error))); } }); diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/HttpSession.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/HttpSession.java index c61d6ca0..9e5096bc 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/HttpSession.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/HttpSession.java @@ -16,6 +16,7 @@ package dev.onvoid.webrtc.client; +import static dev.onvoid.webrtc.client.HttpCall.redacted; import static java.util.Objects.requireNonNull; import java.net.URI; @@ -292,18 +293,18 @@ private static CompletableFuture negotiate(WebRtc rtc, PeerImpl peer, URI e // as the timeout again. peer.close(); result.completeExceptionally(PeerImpl.asWebRtcException(error, - "The session with " + endpoint + " could not be set up")); + "The session with " + redacted(endpoint) + " could not be set up")); discard(rtc, resource.getAndSet(null), authorization, timeout); }; ScheduledFuture deadline = rtc.timer.schedule(() -> fail.accept(new WebRtcException( - "The session with " + endpoint + " was not connected within " + timeout)), + "The session with " + redacted(endpoint) + " was not connected within " + timeout)), Timeouts.toMillis(timeout), TimeUnit.MILLISECONDS); abandoned.thenRun(() -> { deadline.cancel(false); - fail.accept(new CancellationException("The session with " + endpoint + " was abandoned")); + fail.accept(new CancellationException("The session with " + redacted(endpoint) + " was abandoned")); }); CompletableFuture initial = prepared.thenCompose(ready -> gathering == Gathering.COMPLETE @@ -385,12 +386,12 @@ private static CompletableFuture post(HttpCall request, URI endpoint, Str throw (WebRtcException) error; } if (error != null) { - throw new WebRtcException("Sending the offer to " + endpoint + " failed: " + error.getMessage(), + throw new WebRtcException("Sending the offer to " + redacted(endpoint) + " failed: " + error.getMessage(), error); } if (response.status == 201) { if (resource.get() == null) { - throw new WebRtcException("The endpoint " + endpoint + " answered without a session Location"); + throw new WebRtcException("The endpoint " + redacted(endpoint) + " answered without a session Location"); } requireContentType(response, "application/sdp"); return new Reply(response.body, false, null, 0, response, protocol); @@ -399,7 +400,7 @@ private static CompletableFuture post(HttpCall request, URI endpoint, Str URI session = resourceOf(response.uri, response.header("Location")); if (session == null) { - throw new WebRtcException("The endpoint " + endpoint + throw new WebRtcException("The endpoint " + redacted(endpoint) + " countered the offer without naming the session"); } @@ -408,7 +409,7 @@ private static CompletableFuture post(HttpCall request, URI endpoint, Str protocol); } - throw response.error("The endpoint " + endpoint + " answered the offer with " + response.describe()); + throw response.error("The endpoint " + redacted(endpoint) + " answered the offer with " + response.describe()); }); } @@ -426,7 +427,7 @@ private static CompletableFuture answerCounterOffer(WebRtc rtc, HttpClient return peer.manual.answerInstead(new RTCSessionDescription(RTCSdpType.OFFER, reply.sdp), Gathering.COMPLETE) .thenCompose(answer -> { if (System.currentTimeMillis() > reply.validUntil) { - throw new WebRtcException("The counter-offer for " + reply.session + throw new WebRtcException("The counter-offer for " + redacted(reply.session) + " expired before it was answered"); } @@ -446,12 +447,12 @@ private static CompletableFuture answerCounterOffer(WebRtc rtc, HttpClient withRtcpMuxOnly(answer.sdp).getBytes(StandardCharsets.UTF_8), 0, head -> { }).handle((response, error) -> { if (error != null) { - throw new WebRtcException("Sending the answer to " + reply.session + " failed: " + throw new WebRtcException("Sending the answer to " + redacted(reply.session) + " failed: " + error.getMessage(), error); } if (response.status / 100 != 2) { throw response.error("The endpoint answered the answer for " - + reply.session + " with " + response.describe()); + + redacted(reply.session) + " with " + response.describe()); } ice.attach(reply.session, response.header("ETag"), answer.sdp); @@ -610,14 +611,14 @@ private static CompletableFuture discard(WebRtc rtc, URI resour Throwable failure = error; if (failure == null && response.status / 100 != 2) { - failure = response.error("The endpoint answered the deletion of " + resource + failure = response.error("The endpoint answered the deletion of " + redacted(resource) + " with " + response.describe()); } if (failure == null) { return null; } - WebRtcException reported = new WebRtcException("Deleting the session " + resource + " failed", + WebRtcException reported = new WebRtcException("Deleting the session " + redacted(resource) + " failed", failure); rtc.reportError(reported); return reported; @@ -659,7 +660,7 @@ static CompletableFuture head(WebRtc rtc, URI endpoint, Strin CompletableFuture response = request.send(null, null, 0, head -> { }) .handle((value, error) -> { if (error != null) { - throw new WebRtcException("Asking " + endpoint + " with HEAD failed: " + error.getMessage(), + throw new WebRtcException("Asking " + redacted(endpoint) + " with HEAD failed: " + error.getMessage(), error); } @@ -688,7 +689,7 @@ private static WebRtcException leftOnServer(WebRtc rtc, URI resource) { return null; } - WebRtcException error = new WebRtcException("The session " + resource + WebRtcException error = new WebRtcException("The session " + redacted(resource) + " was left on the server, since the runtime is closed"); rtc.reportError(error); return error; @@ -710,19 +711,23 @@ static URI resourceOf(URI endpoint, String location) { resource = endpoint.resolve(location.trim()); } catch (IllegalArgumentException e) { - throw new WebRtcException("The endpoint " + endpoint + " named an invalid resource: " + location, e); + // Without the exception, which quotes the Location. + throw new WebRtcException("The endpoint " + redacted(endpoint) + " named an invalid resource"); } String scheme = resource.getScheme(); if (!"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) { - throw new WebRtcException("The endpoint " + endpoint + " named a resource that is not http: " + resource); + throw new WebRtcException("The endpoint " + redacted(endpoint) + " named a resource that is not http: " + + redacted(resource)); } if ("https".equalsIgnoreCase(endpoint.getScheme()) && !"https".equalsIgnoreCase(scheme)) { - throw new WebRtcException("The endpoint " + endpoint + " named a resource without TLS: " + resource); + throw new WebRtcException("The endpoint " + redacted(endpoint) + " named a resource without TLS: " + + redacted(resource)); } if (!"https".equalsIgnoreCase(scheme) && !HttpCall.isLoopback(resource.getHost())) { - throw new WebRtcException("The endpoint " + endpoint + " named a resource without TLS: " + resource); + throw new WebRtcException("The endpoint " + redacted(endpoint) + " named a resource without TLS: " + + redacted(resource)); } return resource; @@ -782,7 +787,7 @@ static String withRtcpMuxOnly(String sdp) { static void requireContentType(HttpCall.Response response, String expected) { String type = response.header("Content-Type"); if (type == null || !type.split(";", 2)[0].trim().equalsIgnoreCase(expected)) { - throw new WebRtcException("The session " + response.uri + " answered with Content-Type " + throw new WebRtcException("The session " + redacted(response.uri) + " answered with Content-Type " + type + "; expected " + expected); } } @@ -888,7 +893,7 @@ static URI checkEndpoint(URI endpoint) { if (!"https".equalsIgnoreCase(scheme) && !local) { throw new IllegalArgumentException("The endpoint must be an https URL, or an http one on this machine, " - + "such as http://localhost, got " + endpoint); + + "such as http://localhost, got " + redacted(endpoint)); } return endpoint; diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/RTCIceServerTests.java b/webrtc/src/test/java/dev/onvoid/webrtc/RTCIceServerTests.java new file mode 100644 index 00000000..192bcc65 --- /dev/null +++ b/webrtc/src/test/java/dev/onvoid/webrtc/RTCIceServerTests.java @@ -0,0 +1,51 @@ +/* + * Copyright 2026 Alex Andres + * + * Licensed 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 dev.onvoid.webrtc; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.UUID; + +import org.junit.jupiter.api.Test; + +class RTCIceServerTests { + + @Test + void toStringHidesPassword() { + RTCIceServer server = new RTCIceServer(); + server.urls.add("turn:127.0.0.1:3478"); + server.username = "user"; + server.password = UUID.randomUUID().toString(); + + String text = server.toString(); + + assertFalse(text.contains(server.password), text); + // Computed from the password, so a guess could be checked against it. + assertFalse(text.contains(String.valueOf(server.hashCode())), text); + assertTrue(text.contains("password=***"), text); + assertTrue(text.contains("username=user"), text); + assertTrue(text.contains("turn:127.0.0.1:3478"), text); + } + + @Test + void toStringTellsNoPassword() { + String text = new RTCIceServer().toString(); + + assertTrue(text.contains("password=null"), text); + } +} diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/client/HttpCallTests.java b/webrtc/src/test/java/dev/onvoid/webrtc/client/HttpCallTests.java index 66e050c9..a200419b 100644 --- a/webrtc/src/test/java/dev/onvoid/webrtc/client/HttpCallTests.java +++ b/webrtc/src/test/java/dev/onvoid/webrtc/client/HttpCallTests.java @@ -17,12 +17,15 @@ package dev.onvoid.webrtc.client; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertInstanceOf; 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 java.io.IOException; +import java.io.PrintWriter; +import java.io.StringWriter; import java.net.Authenticator; import java.net.PasswordAuthentication; import java.net.Proxy; @@ -68,6 +71,9 @@ class HttpCallTests { private static final String ANSWER = "v=0\r\n" + String.join("", Collections.nCopies(2000, "a=x\r\n")); + /** Stands for the stream key or signature of a URL, which no failure may show. */ + static final String SECRET = "s3cr3t-t0k3n"; + @Test void framedAnswersRead() throws Exception { @@ -225,6 +231,88 @@ void redirectLeavesNoLoopbackInClear() throws Exception { } } + @Test + void urlsRedacted() { + assertEquals("https://example.com", HttpCall.redacted(URI.create("https://example.com"))); + assertEquals("https://example.com:8443", + HttpCall.redacted(URI.create("https://user:pass@example.com:8443/key/whip?token=x#y"))); + assertEquals("http://[::1]:8080", HttpCall.redacted(URI.create("http://[::1]:8080/key"))); + // A host that java.net.URI cannot read, which leaves only the authority. + assertEquals("https://under_score.example:8443", + HttpCall.redacted(URI.create("https://user:pass@under_score.example:8443/key"))); + assertEquals("mailto:", HttpCall.redacted(URI.create("mailto:key@example.com"))); + assertEquals("a URL without a scheme", HttpCall.redacted(URI.create("key/whip?token=x"))); + } + + @Test + void invalidRequestHidesSecrets() { + // The client's own messages quote the URL and the header field. + HttpClient client = HttpCall.newClient(false); + URI unsupported = URI.create("https://under_score.invalid/" + SECRET + "?key=" + SECRET); + URI valid = URI.create("https://example.invalid/"); + + for (HttpCall call : Arrays.asList(post(client, unsupported), + new HttpCall(client, valid, "POST", "Bearer " + SECRET + "\r\nX: y", TIMEOUT))) { + ExecutionException failed = assertThrows(ExecutionException.class, + () -> await(call.send("application/sdp", new byte[1], 1024, head -> { }))); + + assertTrue(failed.getCause().getMessage().contains("is invalid"), failed.getCause().getMessage()); + assertHidesSecret(failed); + } + } + + @Test + void failedRedirectHidesSecrets() throws Exception { + List locations = Arrays.asList("/not valid?key=" + SECRET, "http://media.example/" + SECRET, + "mailto:" + SECRET + "@example.com"); + + for (String location : locations) { + try (TestHttpEndpoint endpoint = new TestHttpEndpoint(offer -> ANSWER, 201)) { + endpoint.redirectAnswers(307, location); + + HttpCall call = post(HttpCall.newClient(false), withSecret(endpoint.uri())).followRedirects(); + + assertHidesSecret(assertThrows(ExecutionException.class, + () -> await(call.send("application/sdp", new byte[1], 1024, head -> { })))); + } + } + } + + @Test + void abortHidesSecrets() throws Exception { + try (TestHttpEndpoint endpoint = new TestHttpEndpoint(offer -> "v=0 and the rest", 201)) { + endpoint.stallBodies(); + + CountDownLatch head = new CountDownLatch(1); + HttpCall call = post(HttpCall.newClient(false), withSecret(endpoint.uri())); + CompletableFuture response = call.send("application/sdp", new byte[] { 'o' }, 1024, + received -> head.countDown()); + + assertTrue(head.await(TIMEOUT_SECONDS, TimeUnit.SECONDS)); + call.abort(); + + ExecutionException failed = assertThrows(ExecutionException.class, () -> await(response)); + + assertTrue(failed.getCause().getMessage().contains("aborted"), failed.getCause().getMessage()); + assertHidesSecret(failed); + } + } + + @Test + void timeoutHidesSecrets() throws Exception { + try (TestHttpEndpoint endpoint = new TestHttpEndpoint(offer -> "v=0 and the rest", 201)) { + endpoint.stallBodies(); + + HttpCall call = new HttpCall(HttpCall.newClient(false), withSecret(endpoint.uri()), "POST", null, + Duration.ofMillis(200)); + ExecutionException failed = assertThrows(ExecutionException.class, + () -> await(call.send("application/sdp", new byte[] { 'o' }, 1024, head -> { }))); + + assertInstanceOf(HttpTimeoutException.class, failed.getCause()); + assertHidesSecret(failed); + } + } + @Test void proxyForwardsRequest() throws Exception { try (TestHttpEndpoint endpoint = new TestHttpEndpoint(offer -> ANSWER, 201); @@ -343,6 +431,26 @@ void retryAfterRead() { assertEquals(-1, HttpCall.retryDelayMillis(null, now)); } + /** + * @return the URL with {@link #SECRET} in each of its parts that may hold one. + */ + static URI withSecret(URI uri) { + return URI.create(uri.getScheme() + "://user:" + SECRET + "@" + uri.getRawAuthority() + uri.getRawPath() + + "/" + SECRET + "?key=" + SECRET + "#" + SECRET); + } + + /** + * Checks all that a log of the failure shows: the messages of its whole + * chain of causes, and what was suppressed along the way. + */ + static void assertHidesSecret(Throwable failure) { + StringWriter log = new StringWriter(); + + failure.printStackTrace(new PrintWriter(log, true)); + + assertFalse(log.toString().contains(SECRET), log::toString); + } + private static HttpCall post(HttpClient client, URI uri) { return new HttpCall(client, uri, "POST", null, TIMEOUT); } diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/client/HttpSessionTests.java b/webrtc/src/test/java/dev/onvoid/webrtc/client/HttpSessionTests.java index b4d52455..8c7f0259 100644 --- a/webrtc/src/test/java/dev/onvoid/webrtc/client/HttpSessionTests.java +++ b/webrtc/src/test/java/dev/onvoid/webrtc/client/HttpSessionTests.java @@ -16,6 +16,9 @@ package dev.onvoid.webrtc.client; +import static dev.onvoid.webrtc.client.HttpCallTests.SECRET; +import static dev.onvoid.webrtc.client.HttpCallTests.assertHidesSecret; +import static dev.onvoid.webrtc.client.HttpCallTests.withSecret; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertInstanceOf; @@ -52,6 +55,7 @@ import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Consumer; import java.util.function.Function; import java.util.function.UnaryOperator; @@ -1548,6 +1552,157 @@ void oversizedAnswerRefused() throws Exception { } } + @Test + void invalidEndpointHidesSecrets() { + URI endpoint = URI.create("http://media.example/" + SECRET + "?key=" + SECRET); + + assertHidesSecret(assertThrows(IllegalArgumentException.class, () -> Whip.to(endpoint))); + assertHidesSecret(assertThrows(IllegalArgumentException.class, () -> Whep.from(endpoint))); + } + + @Test + void refusedSetupHidesSecrets() throws Exception { + // None of these leaves a session to delete. + List> failures = Arrays.asList( + endpoint -> endpoint.answerStatus = 403, + endpoint -> endpoint.location = null, + endpoint -> endpoint.location = "/not valid?key=" + SECRET, + endpoint -> endpoint.location = "http://media.example/" + SECRET, + endpoint -> endpoint.location = "mailto:" + SECRET + "@example.com"); + + for (Consumer failure : failures) { + try (TestHttpEndpoint endpoint = sendingEndpoint()) { + failure.accept(endpoint); + assertHidesSecret(assertThrows(ExecutionException.class, + () -> await(Whep.from(withSecret(endpoint.uri())).play(rtc)))); + } + } + } + + @Test + void unusableAnswerHidesSecrets() throws Exception { + try (TestHttpEndpoint endpoint = sendingEndpoint()) { + endpoint.answerContentType = "text/plain"; + endpoint.location = "/live/session/" + SECRET; + assertHidesSecret(assertThrows(ExecutionException.class, + () -> await(Whep.from(withSecret(endpoint.uri())).play(rtc)))); + endpoint.awaitRequest("DELETE /live/session/" + SECRET, TIMEOUT_SECONDS); + } + } + + @Test + void unreachableEndpointHidesSecrets() { + // The port is not served, and the host is one the client takes no request to. + for (String authority : Arrays.asList("127.0.0.1:1", "under_score.invalid")) { + URI endpoint = withSecret(URI.create("https://" + authority + "/live/endpoint")); + + assertHidesSecret(assertThrows(ExecutionException.class, () -> await(Whep.from(endpoint).play(rtc)))); + assertHidesSecret(assertThrows(ExecutionException.class, () -> await(Whep.from(endpoint).detect(rtc)))); + } + } + + @Test + void setupTimeoutHidesSecrets() throws Exception { + ManualTimer timer = new ManualTimer(); + WebRtc client = clientRuntime(builder -> builder.timer(timer)); + + try (TestHttpEndpoint endpoint = new TestHttpEndpoint(offer -> "", 201)) { + endpoint.stallAnswers(); + + URI secret = withSecret(endpoint.uri()); + CompletableFuture session = Whep.from(secret).timeout(SESSION_TIMEOUT).play(client); + + endpoint.awaitRequest(request -> request.toString().startsWith("POST"), "the offer", TIMEOUT_SECONDS); + assertEquals(1, timer.fire(SESSION_TIMEOUT)); + assertHidesSecret(assertThrows(ExecutionException.class, () -> await(session))); + } + finally { + client.close(); + } + } + + @Test + void failedDeleteHidesSecrets() throws Exception { + CompletableFuture error = new CompletableFuture<>(); + WebRtc client = clientRuntime(builder -> builder.errorHandler(error::complete)); + + try (TestHttpEndpoint endpoint = sendingEndpoint()) { + endpoint.deleteStatus = 500; + endpoint.location = "/live/session/" + SECRET; + + Whep.Session session = await(Whep.from(withSecret(endpoint.uri())).play(client)); + + assertHidesSecret(assertThrows(ExecutionException.class, () -> await(session.closeAsync()))); + assertHidesSecret(await(error)); + } + finally { + client.close(); + } + } + + @Test + void failedCandidatesHideSecrets() throws Exception { + CompletableFuture error = new CompletableFuture<>(); + WebRtc client = clientRuntime(builder -> builder.errorHandler(error::complete)); + + try (TestHttpEndpoint endpoint = sendingEndpoint()) { + endpoint.patchStatus = 412; + endpoint.location = "/live/session/" + SECRET; + + Whep.Session session = await(Whep.from(withSecret(endpoint.uri())).play(client)); + + assertHidesSecret(await(error)); + await(session.closeAsync()); + } + finally { + client.close(); + } + } + + @Test + void failedRestartHidesSecrets() throws Exception { + CompletableFuture error = new CompletableFuture<>(); + WebRtc client = clientRuntime(builder -> builder.errorHandler(error::complete)); + + try (TestHttpEndpoint endpoint = restartingEndpoint(new ArrayList<>())) { + endpoint.iceRestartStatus = 500; + endpoint.location = "/live/session/" + SECRET; + + Whep.Session session = await(Whep.from(withSecret(endpoint.uri())).play(client)); + + assertHidesSecret(assertThrows(ExecutionException.class, () -> await(session.restartIce()))); + + // One the session makes itself is reported. + session.ice().stateChanged(PeerState.FAILED); + assertHidesSecret(await(error)); + await(session.closeAsync()); + } + finally { + client.close(); + } + } + + @Test + void refusedIceServerHidesPassword() throws Exception { + CompletableFuture error = new CompletableFuture<>(); + WebRtc client = clientRuntime(builder -> builder.errorHandler(error::complete)); + + try (TestHttpEndpoint endpoint = sendingEndpoint()) { + endpoint.answerHeaders = "Link: ; rel=\"ice-server\"; username=\"user\"; credential=\"" + + SECRET + "\"\r\n"; + + Whep.Session session = await(Whep.from(endpoint.uri()).play(client)); + ConfigurationException refused = assertInstanceOf(ConfigurationException.class, await(error)); + + assertTrue(refused.getMessage().contains("turn:"), refused.getMessage()); + assertHidesSecret(refused); + await(session.closeAsync()); + } + finally { + client.close(); + } + } + @Test void failedDeleteReported() throws Exception { try (TestHttpEndpoint endpoint = receivingEndpoint()) {