Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 37 additions & 7 deletions keycard-a2a/src/main/java/ai/keycard/a2a/DelegationClient.java
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,8 @@ public static Builder builder(URI issuer) {
* @param params the {@code message/send} params in the 1.0 shape, such as {@link
* A2aProtocol#textMessage(String)}
* @return the JSON-RPC result (a {@code message} or a {@code task}) and the card
* @throws A2aDiscoveryException when the card can't be fetched or is invalid
* @throws A2aDiscoveryException when the card can't be fetched or is invalid, or when an
* invocation endpoint or redirect has an untrusted origin
* @throws ai.keycard.oauth.OAuthErrorException when the zone refuses the exchange; the target
* isn't called
* @throws A2aInvocationException when the call fails or the target answers with a JSON-RPC
Expand All @@ -109,7 +110,7 @@ public DelegationResult invoke(URI target, String subjectToken, Map<String, Obje
// Resolve and vet the endpoint before exchanging, so a bad card never costs a token.
URI url = endpoint(target, card, base);
String token = exchange.exchangeToken(subjectToken, URI.create(base)).accessToken();
return new DelegationResult(wire.decodeResult(call(url, token, params)), card);
return new DelegationResult(wire.decodeResult(call(url, target, token, params)), card);
}

/**
Expand Down Expand Up @@ -160,7 +161,30 @@ static String origin(URI url) {
return scheme + "://" + host + ":" + port;
}

private Map<String, Object> call(URI url, String token, Map<String, Object> params) {
private void checkRedirect(TransportResponse response, URI url, URI target) {
switch (response.status()) {
case 301, 302, 303, 307, 308 -> {
String location = response.header("Location");
if (location == null || location.isEmpty()) {
return;
}
URI redirect;
try {
redirect = url.resolve(location);
} catch (IllegalArgumentException e) {
return;
}
String redirectOrigin = origin(redirect);
if (!redirectOrigin.equals(origin(target)) && !trustedOrigins.contains(redirectOrigin)) {
throw new A2aDiscoveryException(
"redirect origin " + redirectOrigin + " is not trusted for target " + target, null, false);
}
}
default -> {}
}
}

private Map<String, Object> call(URI url, URI target, String token, Map<String, Object> params) {
Map<String, Object> payload = new LinkedHashMap<>();
payload.put("jsonrpc", "2.0");
payload.put("id", UUID.randomUUID().toString());
Expand All @@ -173,7 +197,9 @@ private Map<String, Object> call(URI url, String token, Map<String, Object> para
.withHeader(wire.header(), wire.version());
TransportResponse response;
try {
response = transport.sendWithLimit(request, maxPeerResponseBytes);
response = transport.sendWithLimit(request, maxPeerResponseBytes, head -> checkRedirect(head, url, target));
} catch (A2aDiscoveryException e) {
throw e;
} catch (ResponseBodyTooLargeException e) {
throw e.status() >= 200 && e.status() < 300 ? e.nonRetryable() : e;
} catch (KeycardException e) {
Expand Down Expand Up @@ -261,21 +287,25 @@ public Builder credential(Credential credential) {
}

/**
* The transport for discovery, the exchange and the call.
* The transport for discovery, the exchange and the call. A custom transport must not
* follow redirects.
*
* @param transport the transport
* @return this builder
* @throws ai.keycard.oauth.ConfigurationException if a visible client policy follows redirects
*/
public Builder transport(KeycardHttpTransport transport) {
this.transport = Objects.requireNonNull(transport, "transport");
Objects.requireNonNull(transport, "transport").requireRedirectsDisabled();
this.transport = transport;
return this;
}
Comment thread
claude[bot] marked this conversation as resolved.
Resolved

/**
* Sends requests through this JDK client.
* Sends requests through this JDK client with redirects disabled.
*
* @param client the client
* @return this builder
* @throws ai.keycard.oauth.ConfigurationException if the client follows redirects
*/
public Builder httpClient(HttpClient client) {
return transport(KeycardHttpTransport.of(client));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,10 @@
import ai.keycard.oauth.OAuthErrorException;
import ai.keycard.oauth.ResponseBodyTooLargeException;
import ai.keycard.oauth.TokenTypes;
import ai.keycard.oauth.TransportResponse;
import ai.keycard.oauth.testing.StubZone;
import ai.keycard.oauth.testing.StubZone.RecordedRequest;
import ai.keycard.oauth.testing.StubZone.StubResponse;
import ai.keycard.oauth.testing.TestClock;
import com.nimbusds.jose.util.JSONObjectUtils;
import com.sun.net.httpserver.HttpServer;
Expand All @@ -21,6 +23,7 @@
import java.net.http.HttpClient;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.zip.GZIPOutputStream;
Expand Down Expand Up @@ -452,6 +455,136 @@ private static byte[] gzip(String json, int padding) throws IOException {
return bytes.toByteArray();
}

@Test
@DisplayName("row 16: 307 and 302 redirects to untrusted origins receive no request")
void row16() {
for (int status : List.of(307, 302)) {
try (StubZone zone = zone();
StubZone agent = agent(CARD);
StubZone other = StubZone.start()) {
redirect(agent, status, other.url("/next").toString());
DelegationClient delegation = status == 307
? client(zone)
: clientBuilder(zone)
.httpClient(HttpClient.newHttpClient())
.build();
assertRedirectRefused(() -> invoke(delegation, agent.issuer()), other.issuer(), agent.issuer());
assertThat(other.requests()).isEmpty();
assertInitialInvocation(zone, agent);
}
}
}

@Test
@DisplayName("row 16: refuses an untrusted redirect before reading its oversized body")
void row16OversizedRedirect() {
try (StubZone zone = zone();
StubZone agent = agent(CARD);
StubZone other = StubZone.start()) {
agent.respond(
"POST",
A2aProtocol.JSONRPC_PATH,
new StubResponse(307, Map.of("Location", other.url("/next").toString()), "x".repeat(2048)));
DelegationClient delegation =
clientBuilder(zone).maxPeerResponseBytes(1024).build();
assertRedirectRefused(() -> invoke(delegation, agent.issuer()), other.issuer(), agent.issuer());
assertThat(other.requests()).isEmpty();
}
}

@Test
@DisplayName("row 16: a redirect-following JDK client is rejected before use")
void row16RejectsRedirectFollowingJdkClient() {
for (HttpClient.Redirect policy : List.of(HttpClient.Redirect.ALWAYS, HttpClient.Redirect.NORMAL)) {
HttpClient httpClient =
HttpClient.newBuilder().followRedirects(policy).build();
DelegationClient.Builder builder = DelegationClient.builder(URI.create("https://zone.example"));
assertThatThrownBy(() -> builder.httpClient(httpClient))
.isInstanceOf(ConfigurationException.class)
.hasMessageContaining("requires HTTP redirects to be disabled");
assertThatThrownBy(() -> builder.transport(KeycardHttpTransport.of(httpClient)))
.isInstanceOf(ConfigurationException.class)
.hasMessageContaining("requires HTTP redirects to be disabled");
}
}

@Test
@DisplayName("row 17: a relative same-origin redirect returns an invocation error")
void row17() {
try (StubZone zone = zone();
StubZone agent = agent(CARD)) {
redirect(agent, 307, "/next");
assertThatThrownBy(() -> invoke(client(zone), agent.issuer())).isInstanceOf(A2aInvocationException.class);
assertThat(agent.requests("/next")).isEmpty();
assertInitialInvocation(zone, agent);
}
}

@Test
@DisplayName("row 18: an allowlisted cross-origin redirect returns an invocation error")
void row18() {
try (StubZone zone = zone();
StubZone agent = agent(CARD);
StubZone other = StubZone.start()) {
redirect(agent, 307, other.url("/next").toString());
DelegationClient delegation =
clientBuilder(zone).trustedEndpointOrigins(other.issuer()).build();
assertThatThrownBy(() -> invoke(delegation, agent.issuer())).isInstanceOf(A2aInvocationException.class);
assertThat(other.requests()).isEmpty();
assertInitialInvocation(zone, agent);
}
}

@Test
@DisplayName("row 19: an HTTPS to HTTP redirect is a disallowed origin change")
void row19() {
try (StubZone zone = zone()) {
URI target = URI.create("https://agent.example");
URI redirect = URI.create("http://agent.example/a2a/jsonrpc");
List<URI> peerRequests = new ArrayList<>();
KeycardHttpTransport network = KeycardHttpTransport.create();
DelegationClient delegation = clientBuilder(zone)
.transport(request -> {
URI uri = request.uri();
if (uri.getHost().equals(zone.issuer().getHost())) {
return network.send(request);
}
peerRequests.add(uri);
if (uri.getPath().equals(A2aProtocol.AGENT_CARD_PATH)) {
return new TransportResponse(200, Map.of(), CARD);
}
return new TransportResponse(307, Map.of("Location", List.of(redirect.toString())), "");
})
.build();
assertRedirectRefused(() -> invoke(delegation, target), redirect, target);
assertThat(peerRequests)
.containsExactly(
target.resolve(A2aProtocol.AGENT_CARD_PATH), target.resolve(A2aProtocol.JSONRPC_PATH));
assertThat(zone.requests(StubZone.TOKEN_PATH)).hasSize(1);
}
}

private static void redirect(StubZone agent, int status, String location) {
agent.respond("POST", A2aProtocol.JSONRPC_PATH, new StubResponse(status, Map.of("Location", location), ""));
}

private static void assertRedirectRefused(ThrowingCallable invocation, URI redirect, URI target) {
assertThatThrownBy(invocation).isInstanceOfSatisfying(A2aDiscoveryException.class, error -> {
assertThat(error.retryable()).isFalse();
assertThat(error)
.hasMessageContaining("redirect origin " + DelegationClient.origin(redirect))
.hasMessageContaining(target.toString());
});
}

private static void assertInitialInvocation(StubZone zone, StubZone agent) {
assertThat(zone.requests(StubZone.TOKEN_PATH)).hasSize(1);
assertThat(agent.requests(A2aProtocol.JSONRPC_PATH))
.singleElement()
.satisfies(
request -> assertThat(request.header("Authorization")).isEqualTo("Bearer token-for-b"));
}

private static DelegationResult invoke(DelegationClient client, URI target) {
return client.invoke(target, "user-token", A2aProtocol.textMessage("hi"));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import java.util.zip.GZIPInputStream;
import java.util.zip.InflaterInputStream;
import org.jspecify.annotations.Nullable;
Expand All @@ -38,25 +39,39 @@ final class JdkHttpTransport implements KeycardHttpTransport {
this.client = Objects.requireNonNull(client, "client");
}

@Override
public void requireRedirectsDisabled() {
if (client.followRedirects() != HttpClient.Redirect.NEVER) {
throw new ConfigurationException("A2A delegation requires HTTP redirects to be disabled");
}
}

@Override
public TransportResponse send(TransportRequest request) {
return sendWithLimit(request, KeycardHttpTransport.MAX_RESPONSE_BODY_BYTES);
}

@Override
public TransportResponse sendUnbounded(TransportRequest request) {
return exchange(request, -1);
return exchange(request, -1, null);
}

@Override
public TransportResponse sendWithLimit(TransportRequest request, int maxResponseBodyBytes) {
return sendWithLimit(request, maxResponseBodyBytes, null);
}

@Override
public TransportResponse sendWithLimit(
TransportRequest request, int maxResponseBodyBytes, @Nullable Consumer<TransportResponse> inspectResponse) {
if (maxResponseBodyBytes <= 0) {
throw new IllegalArgumentException("response limit must be positive");
}
return exchange(request, maxResponseBodyBytes);
return exchange(request, maxResponseBodyBytes, inspectResponse);
}

private TransportResponse exchange(TransportRequest request, int limit) {
private TransportResponse exchange(
TransportRequest request, int limit, @Nullable Consumer<TransportResponse> inspectResponse) {
HttpRequest httpRequest = toHttpRequest(request);
String host = request.uri().getHost();
AtomicReference<InputStream> bodyStream = new AtomicReference<>();
Expand All @@ -65,7 +80,7 @@ private TransportResponse exchange(TransportRequest request, int limit) {
CompletableFuture<HttpResponse<InputStream>> sent =
client.sendAsync(httpRequest, HttpResponse.BodyHandlers.ofInputStream());
CompletableFuture<TransportResponse> exchange =
sent.thenApplyAsync(response -> readResponse(response, bodyStream, limit));
sent.thenApplyAsync(response -> readResponse(response, bodyStream, limit, inspectResponse));
try {
return exchange.get(request.timeout().toNanos(), TimeUnit.NANOSECONDS);
} catch (TimeoutException e) {
Expand Down Expand Up @@ -103,21 +118,31 @@ private TransportResponse exchange(TransportRequest request, int limit) {
}

private static TransportResponse readResponse(
HttpResponse<InputStream> response, AtomicReference<InputStream> bodyStream, int limit) {
HttpResponse<InputStream> response,
AtomicReference<InputStream> bodyStream,
int limit,
@Nullable Consumer<TransportResponse> inspectResponse) {
int status = response.statusCode();
String encoding = response.headers()
.firstValue("content-encoding")
.map(v -> v.trim().toLowerCase(Locale.ROOT))
.orElse("");
InputStream raw = response.body();
bodyStream.set(raw);
try (InputStream decoded = wrapEncoding(raw, encoding)) {
byte[] bytes = readBytes(
decoded,
status,
response.headers().firstValue("retry-after").orElse(null),
limit);
return new TransportResponse(status, response.headers().map(), new String(bytes, StandardCharsets.UTF_8));
try {
if (inspectResponse != null) {
inspectResponse.accept(
new TransportResponse(status, response.headers().map(), ""));
}
try (InputStream decoded = wrapEncoding(raw, encoding)) {
byte[] bytes = readBytes(
decoded,
status,
response.headers().firstValue("retry-after").orElse(null),
limit);
return new TransportResponse(
status, response.headers().map(), new String(bytes, StandardCharsets.UTF_8));
}
} catch (IOException e) {
throw new UncheckedIOException(e);
} finally {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import java.net.http.HttpClient;
import java.time.Duration;
import java.util.function.Consumer;

/**
* The HTTP transport every Keycard operation sends its requests through. Inject one to route
Expand Down Expand Up @@ -58,6 +59,30 @@ default TransportResponse sendWithLimit(TransportRequest request, int maxRespons
return sendUnbounded(request);
}

/**
* Sends one request, inspecting response status and headers before reading the body on the
* SDK's JDK transport. Other transports may provide an already buffered response.
*
* @param request the request
* @param maxResponseBodyBytes the positive decoded byte limit
* @param inspectResponse the response inspector, which may throw to reject the response
* @return the response, whatever its status
*/
default TransportResponse sendWithLimit(
TransportRequest request, int maxResponseBodyBytes, Consumer<TransportResponse> inspectResponse) {
TransportResponse response = sendWithLimit(request, maxResponseBodyBytes);
inspectResponse.accept(response);
return response;
}

/**
* Checks that redirects are disabled when the client's policy is visible to the SDK.
* Custom transports are responsible for disabling redirects.
*
* @throws ConfigurationException if the client follows redirects
*/
default void requireRedirectsDisabled() {}

/**
* The default transport: a JDK {@link HttpClient} that follows no redirects and connects
* within {@link #DEFAULT_TIMEOUT}.
Expand Down
Loading