mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(apigateway): prevent JWT issuer and JWKS SSRF (#3743)
* fix(apigateway): prevent JWT issuer and JWKS SSRF * fix(apigateway): import verifier types
This commit is contained in:
1 parent
0578532851
commit
ef03c59864
9 files changed
+356
-47
No files matched your search
@@ -2,6 +2,19 @@
|
||||
|
||||
Floci supports both API Gateway v1 (REST APIs) and API Gateway v2 (HTTP APIs).
|
||||
|
||||
## JWT issuer network policy
|
||||
|
||||
HTTP API JWT authorizers fetch the configured issuer's OIDC discovery document and JWKS. Floci
|
||||
rejects HTTP issuers and destinations that resolve to local, link-local, private, or other
|
||||
non-public addresses by default. This prevents an authorizer configuration from turning JWT
|
||||
verification into an SSRF path.
|
||||
|
||||
For an isolated development environment with a local fixture issuer, set
|
||||
`FLOCI_SECURITY_ALLOW_PRIVATE_JWT_TARGETS=true`. This shared JWT policy also applies to AppSync
|
||||
OIDC providers. The option permits private HTTPS targets and HTTP URLs that use a literal private
|
||||
or loopback address. It does not permit public HTTP targets. Keep it disabled when Floci can
|
||||
receive untrusted API configuration.
|
||||
|
||||
## Custom API IDs
|
||||
|
||||
API IDs are generated randomly, which means endpoint URLs change every time you recreate an API. To pin
|
||||
|
||||
@@ -5,6 +5,14 @@
|
||||
|
||||
Floci implements the AWS AppSync Management API, providing local emulation of GraphQL API configuration, schema management, data source binding, resolver mapping, API key provisioning, custom domains, and channel namespaces.
|
||||
|
||||
## OIDC issuer network policy
|
||||
|
||||
AppSync OIDC authentication uses the shared JWT issuer policy. By default, issuer discovery and
|
||||
JWKS requests require HTTPS and reject local, private, link-local, and other non-public addresses.
|
||||
For an isolated development environment, set `FLOCI_SECURITY_ALLOW_PRIVATE_JWT_TARGETS=true`.
|
||||
This also applies to API Gateway HTTP API JWT authorizers. The option permits private HTTPS
|
||||
targets and HTTP URLs that use a literal private or loopback address.
|
||||
|
||||
## Supported Operations
|
||||
|
||||
### GraphQL API
|
||||
|
||||
@@ -198,6 +198,9 @@ public interface EmulatorConfig {
|
||||
@WithDefault("false")
|
||||
boolean disableCorsHeaders();
|
||||
|
||||
@WithDefault("false")
|
||||
boolean allowPrivateJwtTargets();
|
||||
|
||||
/**
|
||||
* Whether to grant Private Network Access preflights (respond with
|
||||
* {@code Access-Control-Allow-Private-Network: true}) when the browser asks.
|
||||
|
||||
+140
-35
@@ -2,15 +2,29 @@ package io.github.hectorvent.floci.services.apigatewayv2;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.SsrfProtection;
|
||||
import jakarta.annotation.PreDestroy;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.apache.hc.client5.http.DnsResolver;
|
||||
import org.apache.hc.client5.http.SystemDefaultDnsResolver;
|
||||
import org.apache.hc.client5.http.config.ConnectionConfig;
|
||||
import org.apache.hc.client5.http.config.RequestConfig;
|
||||
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
|
||||
import org.apache.hc.client5.http.impl.classic.HttpClients;
|
||||
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
|
||||
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder;
|
||||
import org.apache.hc.core5.http.io.entity.EntityUtils;
|
||||
import org.apache.hc.core5.http.io.support.ClassicRequestBuilder;
|
||||
import org.apache.hc.core5.util.Timeout;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.math.BigInteger;
|
||||
import java.net.InetAddress;
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.net.UnknownHostException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.GeneralSecurityException;
|
||||
import java.security.KeyFactory;
|
||||
@@ -21,6 +35,7 @@ import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Base64;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/**
|
||||
@@ -40,7 +55,7 @@ import java.util.concurrent.ConcurrentHashMap;
|
||||
* would reopen exactly the unauthenticated-claims gap this class exists to close.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class JwtSignatureVerifier {
|
||||
public class JwtSignatureVerifier implements AutoCloseable {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(JwtSignatureVerifier.class);
|
||||
|
||||
@@ -48,26 +63,47 @@ public class JwtSignatureVerifier {
|
||||
private static final Duration HTTP_TIMEOUT = Duration.ofSeconds(10);
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
private final HttpClient httpClient;
|
||||
private final CloseableHttpClient httpClient;
|
||||
private final boolean allowPrivateNetworkTargets;
|
||||
private final Map<String, CachedJwks> jwksCache = new ConcurrentHashMap<>();
|
||||
|
||||
@Inject
|
||||
public JwtSignatureVerifier(ObjectMapper objectMapper) {
|
||||
this(objectMapper, HttpClient.newBuilder()
|
||||
.version(HttpClient.Version.HTTP_1_1)
|
||||
.connectTimeout(HTTP_TIMEOUT)
|
||||
.followRedirects(HttpClient.Redirect.NORMAL)
|
||||
.build());
|
||||
public JwtSignatureVerifier(ObjectMapper objectMapper, EmulatorConfig config) {
|
||||
this(objectMapper, SystemDefaultDnsResolver.INSTANCE,
|
||||
config.security().allowPrivateJwtTargets());
|
||||
}
|
||||
|
||||
/**
|
||||
* Injects a caller-supplied client, so tests (including {@code OidcAuthValidatorTest} in the
|
||||
* AppSync auth package, which points it at a local fixture server) don't have to reach the
|
||||
* real network to exercise verification.
|
||||
* Injects the DNS boundary so tests can verify address policy without using external DNS.
|
||||
*/
|
||||
public JwtSignatureVerifier(ObjectMapper objectMapper, HttpClient httpClient) {
|
||||
JwtSignatureVerifier(
|
||||
ObjectMapper objectMapper,
|
||||
DnsResolver dnsResolver,
|
||||
boolean allowPrivateNetworkTargets
|
||||
) {
|
||||
this.objectMapper = objectMapper;
|
||||
this.httpClient = httpClient;
|
||||
this.allowPrivateNetworkTargets = allowPrivateNetworkTargets;
|
||||
|
||||
ConnectionConfig connectionConfig = ConnectionConfig.custom()
|
||||
.setConnectTimeout(Timeout.of(HTTP_TIMEOUT))
|
||||
.setSocketTimeout(Timeout.of(HTTP_TIMEOUT))
|
||||
.build();
|
||||
PoolingHttpClientConnectionManager connectionManager = PoolingHttpClientConnectionManagerBuilder.create()
|
||||
.setDnsResolver(new JwtDnsResolver(dnsResolver, allowPrivateNetworkTargets))
|
||||
.setDefaultConnectionConfig(connectionConfig)
|
||||
.build();
|
||||
RequestConfig requestConfig = RequestConfig.custom()
|
||||
.setConnectionRequestTimeout(Timeout.of(HTTP_TIMEOUT))
|
||||
.setResponseTimeout(Timeout.of(HTTP_TIMEOUT))
|
||||
.setRedirectsEnabled(false)
|
||||
.build();
|
||||
this.httpClient = HttpClients.custom()
|
||||
.setConnectionManager(connectionManager)
|
||||
.setDefaultRequestConfig(requestConfig)
|
||||
.disableRedirectHandling()
|
||||
.disableAutomaticRetries()
|
||||
.disableCookieManagement()
|
||||
.build();
|
||||
}
|
||||
|
||||
public static class JwtVerificationException extends Exception {
|
||||
@@ -97,7 +133,6 @@ public class JwtSignatureVerifier {
|
||||
if (issuer == null || issuer.isBlank()) {
|
||||
throw new JwtVerificationException("JWT authorizer has no configured issuer");
|
||||
}
|
||||
|
||||
String[] parts = token == null ? new String[0] : token.split("\\.", -1);
|
||||
if (parts.length != 3) {
|
||||
throw new JwtVerificationException("Token is not a well-formed JWT");
|
||||
@@ -142,7 +177,7 @@ public class JwtSignatureVerifier {
|
||||
return fetched.get(kid);
|
||||
}
|
||||
|
||||
private Map<String, RSAPublicKey> fetchJwks(String issuer) throws JwtVerificationException {
|
||||
Map<String, RSAPublicKey> fetchJwks(String issuer) throws JwtVerificationException {
|
||||
String jwksUri = fetchJwksUri(issuer);
|
||||
JsonNode jwks = httpGetJson(jwksUri, "JWKS document");
|
||||
|
||||
@@ -173,7 +208,7 @@ public class JwtSignatureVerifier {
|
||||
return result;
|
||||
}
|
||||
|
||||
private String fetchJwksUri(String issuer) throws JwtVerificationException {
|
||||
String fetchJwksUri(String issuer) throws JwtVerificationException {
|
||||
String discoveryUrl = issuer.replaceAll("/+$", "") + "/.well-known/openid-configuration";
|
||||
JsonNode discovery = httpGetJson(discoveryUrl, "OIDC discovery document");
|
||||
String jwksUri = discovery.path("jwks_uri").asText(null);
|
||||
@@ -185,19 +220,15 @@ public class JwtSignatureVerifier {
|
||||
}
|
||||
|
||||
private JsonNode httpGetJson(String url, String description) throws JwtVerificationException {
|
||||
HttpRequest request;
|
||||
URI target = validateTarget(url, description);
|
||||
try {
|
||||
request = HttpRequest.newBuilder()
|
||||
.uri(URI.create(url))
|
||||
.timeout(HTTP_TIMEOUT)
|
||||
.GET()
|
||||
.build();
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw new JwtVerificationException("Invalid " + description + " URL: " + url, e);
|
||||
}
|
||||
|
||||
try {
|
||||
HttpResponse<byte[]> response = httpClient.send(request, HttpResponse.BodyHandlers.ofByteArray());
|
||||
FetchedDocument response = httpClient.execute(
|
||||
ClassicRequestBuilder.get(target).build(),
|
||||
apacheResponse -> new FetchedDocument(
|
||||
apacheResponse.getCode(),
|
||||
apacheResponse.getEntity() == null
|
||||
? new byte[0]
|
||||
: EntityUtils.toByteArray(apacheResponse.getEntity())));
|
||||
if (response.statusCode() != 200) {
|
||||
throw new JwtVerificationException(
|
||||
"Fetching " + description + " from " + url + " returned HTTP " + response.statusCode());
|
||||
@@ -210,6 +241,80 @@ public class JwtSignatureVerifier {
|
||||
}
|
||||
}
|
||||
|
||||
private URI validateTarget(String url, String description) throws JwtVerificationException {
|
||||
URI target;
|
||||
try {
|
||||
target = URI.create(url);
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw new JwtVerificationException("Invalid " + description + " URL: " + url, e);
|
||||
}
|
||||
String scheme = target.getScheme();
|
||||
if (target.getHost() == null || target.getHost().isBlank() || target.getUserInfo() != null) {
|
||||
throw new JwtVerificationException("JWT " + description + " has an invalid host: " + url);
|
||||
}
|
||||
InetAddress literalAddress = literalAddress(target.getHost());
|
||||
boolean privateLiteral = literalAddress != null && SsrfProtection.isBlockedAddress(literalAddress);
|
||||
boolean privateHttp = allowPrivateNetworkTargets
|
||||
&& "http".equalsIgnoreCase(scheme)
|
||||
&& privateLiteral;
|
||||
if (!"https".equalsIgnoreCase(scheme) && !privateHttp) {
|
||||
throw new JwtVerificationException("JWT " + description + " must use HTTPS: " + url);
|
||||
}
|
||||
if (!allowPrivateNetworkTargets && privateLiteral) {
|
||||
throw new JwtVerificationException(
|
||||
"JWT " + description + " resolves to a private or local address: " + target.getHost());
|
||||
}
|
||||
return target;
|
||||
}
|
||||
|
||||
private static InetAddress literalAddress(String host) {
|
||||
if (host.indexOf(':') < 0 && !host.matches("[0-9]{1,3}(?:\\.[0-9]{1,3}){3}")) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return InetAddress.ofLiteral(host);
|
||||
} catch (IllegalArgumentException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@PreDestroy
|
||||
@Override
|
||||
public void close() {
|
||||
try {
|
||||
httpClient.close();
|
||||
} catch (Exception e) {
|
||||
LOG.debugv("Could not close JWT document client: {0}", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private record FetchedDocument(int statusCode, byte[] body) {
|
||||
}
|
||||
|
||||
record JwtDnsResolver(DnsResolver delegate, boolean allowPrivateNetworkTargets) implements DnsResolver {
|
||||
@Override
|
||||
public InetAddress[] resolve(String host) throws UnknownHostException {
|
||||
InetAddress[] addresses = delegate.resolve(host);
|
||||
if (addresses == null || addresses.length == 0) {
|
||||
throw new UnknownHostException("JWT target host has no addresses: " + host);
|
||||
}
|
||||
if (!allowPrivateNetworkTargets) {
|
||||
for (InetAddress address : addresses) {
|
||||
if (SsrfProtection.isBlockedAddress(address)) {
|
||||
throw new UnknownHostException(
|
||||
"JWT target host resolves to a private or local address: " + host);
|
||||
}
|
||||
}
|
||||
}
|
||||
return addresses.clone();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String resolveCanonicalHostname(String host) {
|
||||
return host;
|
||||
}
|
||||
}
|
||||
|
||||
private RSAPublicKey toRsaPublicKey(String n, String e) throws GeneralSecurityException {
|
||||
BigInteger modulus = new BigInteger(1, Base64.getUrlDecoder().decode(padBase64(n)));
|
||||
BigInteger exponent = new BigInteger(1, Base64.getUrlDecoder().decode(padBase64(e)));
|
||||
@@ -229,13 +334,13 @@ public class JwtSignatureVerifier {
|
||||
}
|
||||
}
|
||||
|
||||
private java.util.Optional<JsonNode> decodeJson(String base64UrlSegment) {
|
||||
private Optional<JsonNode> decodeJson(String base64UrlSegment) {
|
||||
try {
|
||||
byte[] decoded = Base64.getUrlDecoder().decode(padBase64(base64UrlSegment));
|
||||
JsonNode node = objectMapper.readTree(decoded);
|
||||
return node != null && node.isObject() ? java.util.Optional.of(node) : java.util.Optional.empty();
|
||||
} catch (IllegalArgumentException | java.io.IOException e) {
|
||||
return java.util.Optional.empty();
|
||||
return node != null && node.isObject() ? Optional.of(node) : Optional.empty();
|
||||
} catch (IllegalArgumentException | IOException e) {
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -254,6 +254,7 @@ floci:
|
||||
# The Docker images set it, since they listen on 0.0.0.0 inside the container.
|
||||
# Env var: FLOCI_SECURITY_ALLOW_UNSAFE_NETWORK_EXPOSURE=true
|
||||
allow-unsafe-network-exposure: false
|
||||
allow-private-jwt-targets: false
|
||||
|
||||
tls:
|
||||
enabled: false # FLOCI_TLS_ENABLED (default: false)
|
||||
|
||||
@@ -83,4 +83,21 @@ class ApplicationDefaultsTest {
|
||||
.asBoolean(true),
|
||||
"production application.yml should not create default admin credentials unless enabled");
|
||||
}
|
||||
|
||||
@Test
|
||||
void productionConfigRejectsPrivateJwtTargetsByDefault() throws Exception {
|
||||
JsonNode config = new YAMLMapper().readTree(Path.of("src/main/resources/application.yml").toFile());
|
||||
|
||||
assertFalse(config.path("floci")
|
||||
.path("security")
|
||||
.path("allow-private-jwt-targets")
|
||||
.asBoolean(true),
|
||||
"production application.yml should reject private JWT issuer and JWKS targets");
|
||||
|
||||
WithDefault fallback = EmulatorConfig.SecurityConfig.class
|
||||
.getMethod("allowPrivateJwtTargets")
|
||||
.getAnnotation(WithDefault.class);
|
||||
assertNotNull(fallback, "allowPrivateJwtTargets should declare a fallback default");
|
||||
assertEquals("false", fallback.value());
|
||||
}
|
||||
}
|
||||
+161
-7
@@ -3,14 +3,16 @@ package io.github.hectorvent.floci.services.apigatewayv2;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
import org.apache.hc.client5.http.DnsResolver;
|
||||
import org.apache.hc.client5.http.SystemDefaultDnsResolver;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.math.BigInteger;
|
||||
import java.net.InetAddress;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.UnknownHostException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.GeneralSecurityException;
|
||||
import java.security.KeyPair;
|
||||
@@ -18,9 +20,13 @@ import java.security.KeyPairGenerator;
|
||||
import java.security.Signature;
|
||||
import java.security.interfaces.RSAPrivateKey;
|
||||
import java.security.interfaces.RSAPublicKey;
|
||||
import java.time.Duration;
|
||||
import java.util.Base64;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.function.Function;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
@@ -37,6 +43,7 @@ class JwtSignatureVerifierTest {
|
||||
private RSAPrivateKey privateKey;
|
||||
private RSAPublicKey publicKey;
|
||||
private JwtSignatureVerifier verifier;
|
||||
private JwtSignatureVerifier strictVerifier;
|
||||
private final ObjectMapper objectMapper = new ObjectMapper();
|
||||
|
||||
@BeforeEach
|
||||
@@ -74,14 +81,14 @@ class JwtSignatureVerifierTest {
|
||||
server.start();
|
||||
issuer = "http://127.0.0.1:" + server.getAddress().getPort();
|
||||
|
||||
HttpClient client = HttpClient.newBuilder()
|
||||
.connectTimeout(Duration.ofSeconds(5))
|
||||
.build();
|
||||
verifier = new JwtSignatureVerifier(objectMapper, client);
|
||||
verifier = new JwtSignatureVerifier(objectMapper, SystemDefaultDnsResolver.INSTANCE, true);
|
||||
strictVerifier = new JwtSignatureVerifier(objectMapper, SystemDefaultDnsResolver.INSTANCE, false);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() {
|
||||
verifier.close();
|
||||
strictVerifier.close();
|
||||
server.stop(0);
|
||||
}
|
||||
|
||||
@@ -141,6 +148,153 @@ class JwtSignatureVerifierTest {
|
||||
() -> verifier.verify(token, null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsNonPublicIssuerAddressesWithoutExplicitOptIn() throws Exception {
|
||||
String token = signToken("test-key-1", privateKey);
|
||||
|
||||
assertThrows(JwtSignatureVerifier.JwtVerificationException.class,
|
||||
() -> strictVerifier.verify(token, issuer));
|
||||
assertThrows(JwtSignatureVerifier.JwtVerificationException.class,
|
||||
() -> strictVerifier.verify(token, "https://127.0.0.1:443"));
|
||||
assertThrows(JwtSignatureVerifier.JwtVerificationException.class,
|
||||
() -> strictVerifier.verify(token, "https://10.0.0.1"));
|
||||
assertThrows(JwtSignatureVerifier.JwtVerificationException.class,
|
||||
() -> strictVerifier.verify(token, "https://169.254.169.254"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void privateNetworkOptInDoesNotAllowPublicPlaintextIssuer() throws Exception {
|
||||
String token = signToken("test-key-1", privateKey);
|
||||
|
||||
JwtSignatureVerifier.JwtVerificationException exception = assertThrows(
|
||||
JwtSignatureVerifier.JwtVerificationException.class,
|
||||
() -> verifier.verify(token, "http://example.invalid"));
|
||||
|
||||
assertTrue(exception.getMessage().contains("must use HTTPS"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsMalformedIssuerScheme() throws Exception {
|
||||
String token = signToken("test-key-1", privateKey);
|
||||
|
||||
JwtSignatureVerifier.JwtVerificationException exception = assertThrows(
|
||||
JwtSignatureVerifier.JwtVerificationException.class,
|
||||
() -> strictVerifier.verify(token, "ftp://issuer.example.com"));
|
||||
|
||||
assertTrue(exception.getMessage().contains("must use HTTPS"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsPrivateJwksTargetReturnedByDiscovery() throws Exception {
|
||||
String token = signToken("test-key-1", privateKey);
|
||||
try (JwtSignatureVerifier privateJwksVerifier = new JwtSignatureVerifier(
|
||||
objectMapper, SystemDefaultDnsResolver.INSTANCE, false) {
|
||||
@Override
|
||||
String fetchJwksUri(String ignoredIssuer) {
|
||||
return "https://169.254.169.254/latest/meta-data";
|
||||
}
|
||||
}) {
|
||||
assertThrows(JwtSignatureVerifier.JwtVerificationException.class,
|
||||
() -> privateJwksVerifier.verify(token, "https://issuer.example.com"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsMalformedJwksSchemeReturnedByDiscovery() throws Exception {
|
||||
String token = signToken("test-key-1", privateKey);
|
||||
try (JwtSignatureVerifier malformedJwksVerifier = new JwtSignatureVerifier(
|
||||
objectMapper, SystemDefaultDnsResolver.INSTANCE, false) {
|
||||
@Override
|
||||
String fetchJwksUri(String ignoredIssuer) {
|
||||
return "ftp://issuer.example.com/jwks.json";
|
||||
}
|
||||
}) {
|
||||
assertThrows(JwtSignatureVerifier.JwtVerificationException.class,
|
||||
() -> malformedJwksVerifier.verify(token, "https://issuer.example.com"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void validatesResolvedAddressesAtTheConnectionBoundary() throws Exception {
|
||||
AtomicInteger resolutions = new AtomicInteger();
|
||||
DnsResolver changingResolver = dnsResolver(host -> resolutions.incrementAndGet() == 1
|
||||
? new InetAddress[]{InetAddress.ofLiteral("8.8.8.8")}
|
||||
: new InetAddress[]{InetAddress.ofLiteral("127.0.0.1")});
|
||||
JwtSignatureVerifier.JwtDnsResolver resolver =
|
||||
new JwtSignatureVerifier.JwtDnsResolver(changingResolver, false);
|
||||
|
||||
assertEquals("8.8.8.8", resolver.resolve("issuer.example.com")[0].getHostAddress());
|
||||
assertThrows(UnknownHostException.class, () -> resolver.resolve("issuer.example.com"));
|
||||
assertEquals(2, resolutions.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void cachedKeyVerificationDoesNotResolveDnsAgain() throws Exception {
|
||||
AtomicInteger fetches = new AtomicInteger();
|
||||
AtomicInteger resolutions = new AtomicInteger();
|
||||
DnsResolver countingResolver = dnsResolver(host -> {
|
||||
resolutions.incrementAndGet();
|
||||
return new InetAddress[]{InetAddress.ofLiteral("127.0.0.1")};
|
||||
});
|
||||
try (JwtSignatureVerifier cachingVerifier = new JwtSignatureVerifier(
|
||||
objectMapper, countingResolver, false) {
|
||||
@Override
|
||||
Map<String, RSAPublicKey> fetchJwks(String ignoredIssuer) {
|
||||
fetches.incrementAndGet();
|
||||
return Map.of("test-key-1", publicKey);
|
||||
}
|
||||
}) {
|
||||
String token = signToken("test-key-1", privateKey);
|
||||
|
||||
assertDoesNotThrow(() -> cachingVerifier.verify(token, "https://issuer.example.com"));
|
||||
assertDoesNotThrow(() -> cachingVerifier.verify(token, "https://issuer.example.com"));
|
||||
|
||||
assertEquals(1, fetches.get());
|
||||
assertEquals(0, resolutions.get());
|
||||
}
|
||||
}
|
||||
|
||||
private static DnsResolver dnsResolver(Function<String, InetAddress[]> lookup) {
|
||||
return new DnsResolver() {
|
||||
@Override
|
||||
public InetAddress[] resolve(String host) {
|
||||
return lookup.apply(host);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String resolveCanonicalHostname(String host) {
|
||||
return host;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@Test
|
||||
void doesNotFollowDiscoveryRedirects() throws Exception {
|
||||
AtomicInteger redirectedRequests = new AtomicInteger();
|
||||
HttpServer redirectServer = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
|
||||
redirectServer.createContext("/.well-known/openid-configuration", exchange -> {
|
||||
exchange.getResponseHeaders().add("Location", "/discovery");
|
||||
exchange.sendResponseHeaders(302, -1);
|
||||
exchange.close();
|
||||
});
|
||||
redirectServer.createContext("/discovery", exchange -> {
|
||||
redirectedRequests.incrementAndGet();
|
||||
exchange.sendResponseHeaders(200, 0);
|
||||
exchange.close();
|
||||
});
|
||||
redirectServer.start();
|
||||
try {
|
||||
String redirectIssuer = "http://127.0.0.1:" + redirectServer.getAddress().getPort();
|
||||
String token = signToken("test-key-1", privateKey);
|
||||
|
||||
assertThrows(JwtSignatureVerifier.JwtVerificationException.class,
|
||||
() -> verifier.verify(token, redirectIssuer));
|
||||
assertEquals(0, redirectedRequests.get());
|
||||
} finally {
|
||||
redirectServer.stop(0);
|
||||
}
|
||||
}
|
||||
|
||||
private String signToken(String kid, RSAPrivateKey signingKey) throws GeneralSecurityException {
|
||||
ObjectNode header = objectMapper.createObjectNode();
|
||||
header.put("alg", "RS256");
|
||||
|
||||
+12
-5
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.appsync.graphql.auth;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.services.apigatewayv2.JwtSignatureVerifier;
|
||||
import io.github.hectorvent.floci.services.appsync.graphql.AppSyncTransportException;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
@@ -12,7 +13,6 @@ import org.junit.jupiter.api.Test;
|
||||
import java.io.IOException;
|
||||
import java.math.BigInteger;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.http.HttpClient;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.GeneralSecurityException;
|
||||
import java.security.KeyPair;
|
||||
@@ -21,7 +21,6 @@ import java.security.Signature;
|
||||
import java.security.interfaces.RSAPrivateKey;
|
||||
import java.security.interfaces.RSAPublicKey;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.Arrays;
|
||||
@@ -32,6 +31,8 @@ import java.util.Map;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* Follows {@code JwtSignatureVerifierTest}'s pattern: a real local {@code com.sun.net.httpserver}
|
||||
@@ -48,6 +49,7 @@ class OidcAuthValidatorTest {
|
||||
private String issuer;
|
||||
private RSAPrivateKey privateKey;
|
||||
private RSAPublicKey publicKey;
|
||||
private JwtSignatureVerifier signatureVerifier;
|
||||
private OidcAuthValidator validator;
|
||||
|
||||
@BeforeEach
|
||||
@@ -64,13 +66,18 @@ class OidcAuthValidatorTest {
|
||||
server.start();
|
||||
issuer = "http://127.0.0.1:" + server.getAddress().getPort();
|
||||
|
||||
HttpClient httpClient = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build();
|
||||
validator = new OidcAuthValidator(new JwtClaimsDecoder(mapper),
|
||||
new JwtSignatureVerifier(mapper, httpClient), Clock.fixed(NOW, ZoneOffset.UTC));
|
||||
EmulatorConfig config = mock(EmulatorConfig.class);
|
||||
EmulatorConfig.SecurityConfig securityConfig = mock(EmulatorConfig.SecurityConfig.class);
|
||||
when(config.security()).thenReturn(securityConfig);
|
||||
when(securityConfig.allowPrivateJwtTargets()).thenReturn(true);
|
||||
signatureVerifier = new JwtSignatureVerifier(mapper, config);
|
||||
validator = new OidcAuthValidator(new JwtClaimsDecoder(mapper), signatureVerifier,
|
||||
Clock.fixed(NOW, ZoneOffset.UTC));
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() {
|
||||
signatureVerifier.close();
|
||||
server.stop(0);
|
||||
}
|
||||
|
||||
|
||||
@@ -102,6 +102,7 @@ floci:
|
||||
# The test listener binds all interfaces so Quarkus keeps localhost as its test authority.
|
||||
# This is test-only; production keeps the loopback default.
|
||||
allow-unsafe-network-exposure: true
|
||||
allow-private-jwt-targets: true
|
||||
|
||||
init-hooks:
|
||||
shell-executable: /bin/sh
|
||||
|
||||
Reference in new issue
Block a user