feat(sts): serve the OIDC discovery document and JWKS for the web identity token issuer (#8567)

This commit is contained in:
David authored and GitHub committed 2026-11-16 08:19:05 -04:00
1 parent 2cbdef4b23
commit 08479ffffe
12 files changed
+646 -48

No files matched your search

+7 -6
View File
@@ -1301,12 +1301,13 @@ partition's. It is minted once per account and kept across a disable, so re-enab
same URL. AWS does not document which way that goes; the reasoning is that a relying party
verifying tokens will have pinned the URL, so regenerating it would break verification silently.
Two things the feature references are not modeled. The issuer URL is documented as hosting OIDC
discovery endpoints at `/.well-known/openid-configuration` and `/.well-known/jwks.json`, and the
operation's description points at a `GetWebIdentityToken` API for obtaining JWTs. Neither is served
here: these six are the management operations only. `JwtVendingEnabled` is therefore reported as
true whenever the feature is enabled, which is the only reading available, since nothing in the API
toggles it separately.
The issuer URL is documented as hosting OIDC discovery endpoints at
`/.well-known/openid-configuration` and `/.well-known/jwks.json`, and the operation's description
points at STS's `GetWebIdentityToken` for obtaining JWTs. STS serves both: the token operation, and
the two discovery documents under a Floci route keyed by the issuer's UUID, since the issuer's own
host does not reach Floci (see [STS, Verifying a token](sts.md#verifying-a-token)).
`JwtVendingEnabled` is reported as true whenever the feature is enabled, which is the only reading
available, since nothing in the API toggles it separately.
`SetSecurityTokenServicePreferences` stores the version, and `GetAccountSummary` reports it as
`GlobalEndpointTokenVersion`, which the operation's own description requires. What does not follow
+38 -4
View File
@@ -235,10 +235,44 @@ says what the maximum payload is, so no size is invented here to refuse a reques
The signing key is the account's, minted on first use per algorithm and stored, so a restart does
not invalidate a token already handed out. `RS256` signs with a 2048-bit RSA key and `ES384` with
P-384, whose signature is the raw `R || S` pair JWS defines rather than the DER sequence a default
ECDSA signer returns. What is not here yet is the other half of the feature: nothing publishes the
verification key, so the `/.well-known/openid-configuration` and `/.well-known/jwks.json` documents
the issuer URL would host are not served, and a relying party cannot verify one of these tokens
against this emulator.
ECDSA signer returns.
### Verifying a token
AWS publishes the verification keys at the issuer itself, under
`/.well-known/openid-configuration` and `/.well-known/jwks.json`. The issuer's host
(`https://<uuid>.tokens.sts.global.api.aws`) does not reach Floci, so the two documents are served
under a Floci route keyed by the issuer's UUID, its first host label:
| Route | Serves |
|---|---|
| `GET /_floci/sts/web-identity/<uuid>/.well-known/openid-configuration` | The OIDC discovery document |
| `GET /_floci/sts/web-identity/<uuid>/.well-known/jwks.json` | The account's verification keys |
A relying party fetches them without AWS credentials, as it would from AWS, and the UUID tells Floci
which account's keys to answer with. The token's `iss` keeps AWS's form, and the discovery document
names it as `issuer`, which is what a verifier compares, while `jwks_uri` points at the key route
above. Point the relying party's JWKS URL (or its discovery URL) at Floci:
```bash
ISSUER=$(aws iam get-outbound-web-identity-federation-info --endpoint-url $AWS_ENDPOINT_URL \
--query IssuerIdentifier --output text)
ID=$(echo "$ISSUER" | sed -E 's#https://([^.]+)\..*#\1#')
curl -s "$AWS_ENDPOINT_URL/_floci/sts/web-identity/$ID/.well-known/jwks.json"
```
The key set holds one key per algorithm, in the shape of the sample the IAM User Guide gives: the
`ES384` key with `kty` `EC`, `alg` and `crv` `P-384`, and the `RS256` key with `kty` `RSA`, its
modulus and exponent. Both are minted on the first read if no token has used them yet, so a key set
cached before the first token already holds that token's key. AWS does not publish its discovery
document, so Floci's carries the members OpenID Connect Discovery requires and no more: `issuer`,
`jwks_uri`, `response_types_supported`, `subject_types_supported` and
`id_token_signing_alg_values_supported` (`RS256` and `ES384`).
The documents stay served while the feature is disabled. The issuer outlives a disable, and so do
the tokens already minted under it, which a relying party still has to verify until they expire.
AWS does not document this either way, so it is Floci's reading. An issuer no account was given
answers 404.
## Configuration
@@ -1,6 +1,8 @@
package io.floci.aws.core.common;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Base64;
/** Base64url without padding, the encoding of JWT segments and WebAuthn fields. */
@@ -18,6 +20,45 @@ public final class Base64Url {
return encode(text.getBytes(StandardCharsets.UTF_8));
}
/**
* Encodes a non-negative integer as its unsigned big-endian bytes, the form a JWK carries an RSA
* modulus and exponent in (RFC 7518, section 6.3.1): the shortest one, without the leading zero
* byte {@link BigInteger#toByteArray()} adds when the top bit is set.
*/
public static String encodeUnsigned(BigInteger value) {
return encode(unsignedBytes(value));
}
/**
* Encodes a non-negative integer as exactly {@code length} unsigned big-endian bytes, the form a
* JWK carries an EC coordinate in (RFC 7518, section 6.2.1.2): "the full coordinate size, even if
* that octet string is zero-padded on the left", which the shortest form misses for about one
* value in 256.
*
* @throws IllegalArgumentException if {@code value} needs more than {@code length} bytes
*/
public static String encodeUnsigned(BigInteger value, int length) {
byte[] bytes = unsignedBytes(value);
if (bytes.length > length) {
throw new IllegalArgumentException(
"Value needs " + bytes.length + " bytes, more than the " + length + " allowed");
}
byte[] padded = new byte[length];
System.arraycopy(bytes, 0, padded, length - bytes.length, bytes.length);
return encode(padded);
}
private static byte[] unsignedBytes(BigInteger value) {
if (value.signum() < 0) {
throw new IllegalArgumentException("Value is negative");
}
byte[] bytes = value.toByteArray();
if (bytes.length > 1 && bytes[0] == 0) {
return Arrays.copyOfRange(bytes, 1, bytes.length);
}
return bytes;
}
/**
* Decodes {@code text}, padded or not, as UTF-8.
*
@@ -10,9 +10,7 @@ import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import java.math.BigInteger;
import java.security.interfaces.RSAPublicKey;
import java.util.Arrays;
/**
* Exposes Cognito well-known endpoints.
@@ -46,8 +44,8 @@ public class CognitoWellKnownController {
UserPool pool = cognitoService.describeUserPool(poolId);
String kid = cognitoService.getSigningKeyId(pool);
RSAPublicKey publicKey = cognitoService.getSigningPublicKey(pool);
String modulus = base64UrlEncodeUnsigned(publicKey.getModulus());
String exponent = base64UrlEncodeUnsigned(publicKey.getPublicExponent());
String modulus = Base64Url.encodeUnsigned(publicKey.getModulus());
String exponent = Base64Url.encodeUnsigned(publicKey.getPublicExponent());
String body = """
{"keys":[{"kty":"RSA","kid":"%s","alg":"RS256","n":"%s","e":"%s","use":"sig"}]}
@@ -70,12 +68,4 @@ public class CognitoWellKnownController {
""".formatted(issuer, jwksUri, authorizationEndpoint, tokenEndpoint, userInfoEndpoint).strip();
return Response.ok(body).build();
}
private String base64UrlEncodeUnsigned(BigInteger value) {
byte[] bytes = value.toByteArray();
if (bytes.length > 1 && bytes[0] == 0) {
bytes = Arrays.copyOfRange(bytes, 1, bytes.length);
}
return Base64Url.encode(bytes);
}
}
@@ -15,9 +15,7 @@ import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import java.math.BigInteger;
import java.security.interfaces.RSAPublicKey;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@@ -85,8 +83,8 @@ public class EksOidcWellKnownController {
jwk.put("alg", "RS256");
jwk.put("use", "sig");
jwk.put("kid", key.getKeyId());
jwk.put("n", base64UrlEncodeUnsigned(publicKey.getModulus()));
jwk.put("e", base64UrlEncodeUnsigned(publicKey.getPublicExponent()));
jwk.put("n", Base64Url.encodeUnsigned(publicKey.getModulus()));
jwk.put("e", Base64Url.encodeUnsigned(publicKey.getPublicExponent()));
return Response.ok(Map.of("keys", List.of(jwk))).build();
}
@@ -110,16 +108,4 @@ public class EksOidcWellKnownController {
private String jwksUri(String clusterName, String region) {
return config.effectiveBaseUrl() + "/_floci/eks/clusters/" + clusterName + "/oidc/keys?region=" + region;
}
/**
* Encodes an RSA parameter as an unsigned big-endian base64url value, dropping the leading zero
* byte {@link BigInteger#toByteArray()} adds for sign — JWK requires the unsigned form.
*/
private String base64UrlEncodeUnsigned(BigInteger value) {
byte[] bytes = value.toByteArray();
if (bytes.length > 1 && bytes[0] == 0) {
bytes = Arrays.copyOfRange(bytes, 1, bytes.length);
}
return Base64Url.encode(bytes);
}
}
@@ -199,6 +199,9 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
private static final String ACCOUNT_PASSWORD_POLICY_KEY = "account-password-policy";
private static final String STS_PREFERENCES_KEY = "sts-preferences";
private static final String OUTBOUND_FEDERATION_KEY = "outbound-web-identity-federation";
/** The issuer URL's first host label: the lowercase UUID {@code UUID.randomUUID()} prints. */
private static final Pattern ISSUER_ID =
Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}");
/** globalEndpointTokenVersion's only two values. */
private static final Set<String> GLOBAL_ENDPOINT_TOKEN_VERSIONS = Set.of("v1Token", "v2Token");
/** AWS-documented bounds for the account password policy's numeric fields. */
@@ -3420,6 +3423,44 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
return state;
}
/**
* The account whose issuer URL has {@code issuerId} as its first host label, and that URL, for
* a request that names an issuer rather than carrying an account: the discovery routes are
* fetched by relying parties, which hold no AWS credential. The id is the UUID minted for the
* account, so it names one account across all of them, as AWS's discovery endpoint "serves
* discovery requests for any issuer UUID in the partition".
*
* <p>The issuer is found whether the feature is on or off. It outlives a disable (see
* {@link OutboundWebIdentityFederation}), and so do the tokens already minted under it, which
* a relying party still has to verify until they expire.
*
* <p>The routes asking are public, so an id that is not a UUID, the only form
* {@link #mintIssuerIdentifier} produces, is answered without reading the store, and the read
* itself takes no lock: it only reads, the store is safe to read concurrently, and an issuer
* URL never changes once minted. The lock serializes enabling and disabling, which a public
* request has no reason to wait behind.
*/
public Optional<AccountAwareStorageBackend.AccountEntry<String>> findOutboundWebIdentityIssuer(
String issuerId) {
if (issuerId == null || !ISSUER_ID.matcher(issuerId).matches()) {
return Optional.empty();
}
String hostPrefix = "https://" + issuerId + ".";
if (outboundFederation instanceof AccountAwareStorageBackend<OutboundWebIdentityFederation> aware) {
return aware.scanAllAccountEntries(OUTBOUND_FEDERATION_KEY::equals).stream()
.filter(entry -> entry.value().getIssuerIdentifier() != null
&& entry.value().getIssuerIdentifier().startsWith(hostPrefix))
.findFirst()
.map(entry -> new AccountAwareStorageBackend.AccountEntry<>(
entry.accountId(), entry.key(), entry.value().getIssuerIdentifier()));
}
return outboundFederation.get(OUTBOUND_FEDERATION_KEY)
.map(OutboundWebIdentityFederation::getIssuerIdentifier)
.filter(issuer -> issuer != null && issuer.startsWith(hostPrefix))
.map(issuer -> new AccountAwareStorageBackend.AccountEntry<>(
regionResolver.getDefaultAccountId(), OUTBOUND_FEDERATION_KEY, issuer));
}
/**
* The issuer URL AWS mints for an account: a per-account host under
* {@code tokens.sts.global.<dual-stack suffix>}, which the API Reference shows as
@@ -0,0 +1,128 @@
package io.floci.aws.services.iam;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.Base64Url;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.services.iam.WebIdentityTokenIssuer.Algorithm;
import io.floci.aws.services.iam.WebIdentityTokenIssuer.PublishedKey;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import java.security.interfaces.ECPublicKey;
import java.security.interfaces.RSAPublicKey;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* Serves the OIDC discovery document and the key set for the issuer {@code GetWebIdentityToken}
* names in its tokens, so a relying party under test can verify a token Floci signed.
*
* <p>AWS hosts both at the issuer itself, {@code https://<uuid>.tokens.sts.global.api.aws}, under
* {@code /.well-known/openid-configuration} and {@code /.well-known/jwks.json}. That host does not
* reach Floci, and serving {@code /.well-known/...} at the root would answer for no issuer in
* particular and collide with S3's path-style catch-all, so the routes live under
* {@code _floci/sts/web-identity/<uuid>}, as {@code EksOidcWellKnownController} does for a
* cluster's issuer. The token's {@code iss} stays AWS's form; the document names it as
* {@code issuer}, which is what a verifier compares, and points {@code jwks_uri} at Floci.
*
* <p>The UUID is the route's key because it is what AWS keys on too: its one discovery endpoint
* "serves discovery requests for any issuer UUID in the partition", and a relying party fetching
* it carries no AWS credential, so the account comes from the issuer rather than the request.
*/
@ApplicationScoped
@Path("_floci/sts/web-identity/{issuerId}/.well-known")
@Produces(MediaType.APPLICATION_JSON)
public class StsWebIdentityWellKnownController {
/** The byte length of a P-384 coordinate, which a JWK carries at full length. */
private static final int P384_COORDINATE_BYTES = 48;
private final IamService iamService;
private final WebIdentityTokenIssuer tokenIssuer;
private final EmulatorConfig config;
@Inject
public StsWebIdentityWellKnownController(IamService iamService,
WebIdentityTokenIssuer tokenIssuer,
EmulatorConfig config) {
this.iamService = iamService;
this.tokenIssuer = tokenIssuer;
this.config = config;
}
/**
* The discovery document. AWS does not publish the one its issuer serves, so this carries the
* members OpenID Connect Discovery requires of a provider that issues signed tokens and no
* more: the issuer, where its keys are, and the two algorithms {@code GetWebIdentityToken}
* signs with.
*/
@GET
@Path("openid-configuration")
public Response openIdConfiguration(@PathParam("issuerId") String issuerId) {
String issuer = requireIssuer(issuerId).value();
Map<String, Object> body = new LinkedHashMap<>();
body.put("issuer", issuer);
body.put("jwks_uri", config.effectiveBaseUrl() + "/_floci/sts/web-identity/" + issuerId
+ "/.well-known/jwks.json");
body.put("response_types_supported", List.of("id_token"));
body.put("subject_types_supported", List.of("public"));
body.put("id_token_signing_alg_values_supported", Algorithm.names());
return Response.ok(body).build();
}
/**
* The account's verification keys, one per algorithm, in the shape of the sample key set the
* IAM User Guide gives: the EC key names its {@code alg} and curve, and the RSA key carries
* neither {@code alg} nor anything beyond its modulus and exponent.
*/
@GET
@Path("jwks.json")
public Response keys(@PathParam("issuerId") String issuerId) {
String accountId = requireIssuer(issuerId).accountId();
List<Map<String, Object>> keys = new ArrayList<>();
for (PublishedKey key : tokenIssuer.publishedKeys(accountId)) {
keys.add(jwk(key));
}
return Response.ok(Map.of("keys", keys)).build();
}
private AccountAwareStorageBackend.AccountEntry<String> requireIssuer(String issuerId) {
return iamService.findOutboundWebIdentityIssuer(issuerId)
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
"No web identity token issuer: " + issuerId, 404));
}
private static Map<String, Object> jwk(PublishedKey key) {
Map<String, Object> jwk = new LinkedHashMap<>();
switch (key.algorithm()) {
case ES384 -> {
ECPublicKey ec = (ECPublicKey) key.publicKey();
jwk.put("kty", "EC");
jwk.put("use", "sig");
jwk.put("kid", key.keyId());
jwk.put("alg", key.algorithm().name());
jwk.put("crv", "P-384");
jwk.put("x", Base64Url.encodeUnsigned(ec.getW().getAffineX(), P384_COORDINATE_BYTES));
jwk.put("y", Base64Url.encodeUnsigned(ec.getW().getAffineY(), P384_COORDINATE_BYTES));
}
case RS256 -> {
RSAPublicKey rsa = (RSAPublicKey) key.publicKey();
jwk.put("kty", "RSA");
jwk.put("use", "sig");
jwk.put("kid", key.keyId());
jwk.put("n", Base64Url.encodeUnsigned(rsa.getModulus()));
jwk.put("e", Base64Url.encodeUnsigned(rsa.getPublicExponent()));
}
}
return jwk;
}
}
@@ -6,6 +6,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.floci.aws.core.common.CompactJws;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.core.storage.StorageBackend;
import io.floci.aws.core.storage.StorageFactory;
import io.floci.aws.services.iam.model.WebIdentityTokenKey;
@@ -18,9 +19,12 @@ import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.ECGenParameterSpec;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Map;
@@ -141,11 +145,43 @@ public class WebIdentityTokenIssuer {
return claims;
}
private synchronized WebIdentityTokenKey ensureKey(Algorithm algorithm) {
return keyStore.get(algorithm.name()).orElseGet(() -> generateKey(algorithm));
/** One verification key the account publishes: its {@code kid}, algorithm and public half. */
public record PublishedKey(String keyId, Algorithm algorithm, PublicKey publicKey) {
}
private WebIdentityTokenKey generateKey(Algorithm algorithm) {
/**
* The public half of {@code accountId}'s key for each algorithm, for the key set a relying party
* verifies against. A key that has not signed anything yet is minted here, so the set names
* both algorithms from the first read, as the sample key set in the IAM User Guide does, and a
* verifier that cached it before the first token was asked for already holds that token's key.
*
* <p>The account is named rather than read off the request, because the request asking for it
* carries no AWS credential: a relying party fetching the key set is not an AWS caller.
*/
public List<PublishedKey> publishedKeys(String accountId) {
List<PublishedKey> keys = new ArrayList<>();
for (Algorithm algorithm : Algorithm.values()) {
WebIdentityTokenKey key = ensureKey(accountId, algorithm);
keys.add(new PublishedKey(key.getKeyId(), algorithm, publicKey(key, algorithm)));
}
return keys;
}
private WebIdentityTokenKey ensureKey(Algorithm algorithm) {
return ensureKey(null, algorithm);
}
/**
* The key for {@code algorithm} in {@code accountId}, or in the request's account when it is
* null, minted on first use. One lock covers both callers, so a token and a key set read at the
* same moment cannot each mint a key and leave the token signed by the one that lost.
*/
private synchronized WebIdentityTokenKey ensureKey(String accountId, Algorithm algorithm) {
return AccountAwareStorageBackend.getInAccount(keyStore, accountId, algorithm.name())
.orElseGet(() -> generateKey(accountId, algorithm));
}
private WebIdentityTokenKey generateKey(String accountId, Algorithm algorithm) {
try {
KeyPairGenerator generator = KeyPairGenerator.getInstance(algorithm.keyAlgorithm);
switch (algorithm) {
@@ -157,7 +193,7 @@ public class WebIdentityTokenIssuer {
key.setKeyId(UUID.randomUUID().toString().replace("-", ""));
key.setPublicKey(Base64.getEncoder().encodeToString(pair.getPublic().getEncoded()));
key.setPrivateKey(Base64.getEncoder().encodeToString(pair.getPrivate().getEncoded()));
keyStore.put(algorithm.name(), key);
AccountAwareStorageBackend.putInAccount(keyStore, accountId, algorithm.name(), key);
LOG.debugv("Generated the account's {0} web identity token signing key", algorithm);
return key;
} catch (GeneralSecurityException e) {
@@ -177,6 +213,17 @@ public class WebIdentityTokenIssuer {
}
}
private static PublicKey publicKey(WebIdentityTokenKey key, Algorithm algorithm) {
try {
X509EncodedKeySpec spec =
new X509EncodedKeySpec(Base64.getDecoder().decode(key.getPublicKey()));
return KeyFactory.getInstance(algorithm.keyAlgorithm).generatePublic(spec);
} catch (GeneralSecurityException | IllegalArgumentException e) {
throw new IllegalStateException(
"Failed to load the " + algorithm + " web identity token verification key", e);
}
}
private byte[] writeJson(ObjectNode node) {
try {
return objectMapper.writeValueAsBytes(node);
@@ -2,6 +2,8 @@ package io.floci.aws.core.common;
import org.junit.jupiter.api.Test;
import java.math.BigInteger;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
@@ -31,4 +33,42 @@ class Base64UrlTest {
void refusesTextThatIsNotBase64Url() {
assertThrows(IllegalArgumentException.class, () -> Base64Url.decode("!!!"));
}
/** 65537, the usual RSA exponent, is the three bytes {@code 01 00 01}: "AQAB" in every JWK. */
@Test
void encodesAnUnsignedIntegerInItsShortestForm() {
assertEquals("AQAB", Base64Url.encodeUnsigned(BigInteger.valueOf(65537)));
}
/**
* A value with its top bit set gets a leading zero from {@link BigInteger#toByteArray()} to
* keep it positive, and the unsigned form drops it: 0xff is one byte, not two.
*/
@Test
void dropsTheSignByteBigIntegerAddsWhenTheTopBitIsSet() {
assertEquals("_w", Base64Url.encodeUnsigned(BigInteger.valueOf(0xff)));
}
@Test
void encodesZeroAsOneZeroByte() {
assertEquals("AA", Base64Url.encodeUnsigned(BigInteger.ZERO));
}
/** An EC coordinate keeps the curve's full length, zero padded on the left. */
@Test
void padsAFixedLengthValueOnTheLeft() {
assertEquals("AAAB", Base64Url.encodeUnsigned(BigInteger.ONE, 3));
assertEquals("AP8", Base64Url.encodeUnsigned(BigInteger.valueOf(0xff), 2));
}
@Test
void refusesAFixedLengthValueThatDoesNotFit() {
assertThrows(IllegalArgumentException.class,
() -> Base64Url.encodeUnsigned(BigInteger.valueOf(0x10000), 2));
}
@Test
void refusesANegativeValue() {
assertThrows(IllegalArgumentException.class, () -> Base64Url.encodeUnsigned(BigInteger.valueOf(-1)));
}
}
@@ -0,0 +1,243 @@
package io.floci.aws.services.iam;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.Test;
import java.math.BigInteger;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.security.AlgorithmParameters;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.ECGenParameterSpec;
import java.security.spec.ECParameterSpec;
import java.security.spec.ECPoint;
import java.security.spec.ECPublicKeySpec;
import java.security.spec.RSAPublicKeySpec;
import java.util.Base64;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* The discovery document and key set for the issuer {@code GetWebIdentityToken} names, fetched as
* a relying party fetches them: with no AWS credential, by the issuer's UUID.
*
* <p>The point of the routes is that a token Floci signs can be verified by someone who only holds
* the token, so the signature checks here rebuild each key from its published JWK alone and never
* reach into the store, unlike {@link WebIdentityTokenIssuerTest}.
*
* <p>Each test works in an account of its own, since the feature switch is account-level and
* {@link WebIdentityTokenIntegrationTest} turns the default account's off and on.
*/
@QuarkusTest
class StsWebIdentityWellKnownIntegrationTest {
private static final String ISSUER = "GetOutboundWebIdentityFederationInfoResponse"
+ ".GetOutboundWebIdentityFederationInfoResult.IssuerIdentifier";
private static final String TOKEN =
"GetWebIdentityTokenResponse.GetWebIdentityTokenResult.WebIdentityToken";
private static final ObjectMapper MAPPER = new ObjectMapper();
/** A request signed as {@code account} for {@code service}. */
private static RequestSpecification signed(String account, String service) {
return given().header("Authorization", "AWS4-HMAC-SHA256 Credential=" + account
+ "/20261116/us-east-1/" + service + "/aws4_request");
}
private static RequestSpecification iam(String account, String action) {
return signed(account, "iam").formParam("Action", action);
}
/** Enables the feature in {@code account} if it is off, and answers with its issuer. */
private static String enabledIssuer(String account) {
iam(account, "EnableOutboundWebIdentityFederation").when().post("/");
return iam(account, "GetOutboundWebIdentityFederationInfo")
.when().post("/").then().statusCode(200).extract().path(ISSUER);
}
private static String token(String account, String algorithm) {
return signed(account, "sts")
.formParam("Action", "GetWebIdentityToken")
.formParam("Audience.member.1", "https://relying-party.example")
.formParam("SigningAlgorithm", algorithm)
.when().post("/").then().statusCode(200).extract().path(TOKEN);
}
/** The UUID AWS's issuer URL carries as its first host label. */
private static String issuerId(String issuer) {
String host = URI.create(issuer).getHost();
return host.substring(0, host.indexOf('.'));
}
private static String base(String issuer) {
return "/_floci/sts/web-identity/" + issuerId(issuer) + "/.well-known/";
}
private static JsonNode keySet(String issuer) throws Exception {
String body = given().when().get(base(issuer) + "jwks.json")
.then().statusCode(200).extract().asString();
return MAPPER.readTree(body);
}
private static JsonNode jwt(String token, int index) throws Exception {
return MAPPER.readTree(Base64.getUrlDecoder().decode(token.split("\\.", -1)[index]));
}
private static JsonNode keyById(JsonNode keySet, String kid) {
for (JsonNode key : keySet.path("keys")) {
if (kid.equals(key.path("kid").asText())) {
return key;
}
}
throw new AssertionError("no published key has kid " + kid + ": " + keySet);
}
private static BigInteger unsigned(String base64Url) {
return new BigInteger(1, Base64.getUrlDecoder().decode(base64Url));
}
/** The verification key rebuilt from nothing but its JWK. */
private static PublicKey fromJwk(JsonNode jwk) throws Exception {
if ("RSA".equals(jwk.path("kty").asText())) {
return KeyFactory.getInstance("RSA").generatePublic(new RSAPublicKeySpec(
unsigned(jwk.path("n").asText()), unsigned(jwk.path("e").asText())));
}
assertEquals("P-384", jwk.path("crv").asText());
AlgorithmParameters parameters = AlgorithmParameters.getInstance("EC");
parameters.init(new ECGenParameterSpec("secp384r1"));
ECPoint point = new ECPoint(unsigned(jwk.path("x").asText()), unsigned(jwk.path("y").asText()));
return KeyFactory.getInstance("EC").generatePublic(
new ECPublicKeySpec(point, parameters.getParameterSpec(ECParameterSpec.class)));
}
/** Verifies {@code token} the way a relying party does: by its {@code kid}, from the key set. */
private static void assertVerifies(String token, JsonNode keySet) throws Exception {
JsonNode header = jwt(token, 0);
JsonNode jwk = keyById(keySet, header.path("kid").asText());
String signatureAlgorithm = switch (header.path("alg").asText()) {
case "RS256" -> "SHA256withRSA";
case "ES384" -> "SHA384withECDSAinP1363Format";
default -> throw new AssertionError("unexpected alg " + header);
};
String[] parts = token.split("\\.", -1);
Signature verifier = Signature.getInstance(signatureAlgorithm);
verifier.initVerify(fromJwk(jwk));
verifier.update((parts[0] + "." + parts[1]).getBytes(StandardCharsets.US_ASCII));
assertTrue(verifier.verify(Base64.getUrlDecoder().decode(parts[2])),
header.path("alg").asText() + " token does not verify against its published key");
}
/**
* The document names the token's {@code iss} as its issuer, which is what a verifier compares,
* and its {@code jwks_uri} is a Floci route that serves the key set.
*/
@Test
void theDiscoveryDocumentNamesTheTokensIssuerAndAKeySetFlociServes() throws Exception {
String issuer = enabledIssuer("555555555551");
String token = token("555555555551", "RS256");
assertEquals(issuer, jwt(token, 1).path("iss").asText());
String jwksUri = given().when().get(base(issuer) + "openid-configuration")
.then().statusCode(200)
.body("issuer", equalTo(issuer))
.body("response_types_supported", contains("id_token"))
.body("subject_types_supported", contains("public"))
.body("id_token_signing_alg_values_supported", contains("RS256", "ES384"))
.extract().path("jwks_uri");
String jwksPath = URI.create(jwksUri).getPath();
assertEquals(base(issuer) + "jwks.json", jwksPath);
given().when().get(jwksPath).then().statusCode(200);
}
/** Both algorithms' tokens verify against the published key their {@code kid} names. */
@Test
void aTokenOfEitherAlgorithmVerifiesAgainstThePublishedKeyItNames() throws Exception {
String issuer = enabledIssuer("555555555552");
String rs256 = token("555555555552", "RS256");
String es384 = token("555555555552", "ES384");
JsonNode keySet = keySet(issuer);
assertVerifies(rs256, keySet);
assertVerifies(es384, keySet);
JsonNode ec = keyById(keySet, jwt(es384, 0).path("kid").asText());
assertEquals("EC", ec.path("kty").asText());
assertEquals("ES384", ec.path("alg").asText());
assertEquals("sig", ec.path("use").asText());
assertEquals(48, Base64.getUrlDecoder().decode(ec.path("x").asText()).length);
assertEquals(48, Base64.getUrlDecoder().decode(ec.path("y").asText()).length);
JsonNode rsa = keyById(keySet, jwt(rs256, 0).path("kid").asText());
assertEquals("RSA", rsa.path("kty").asText());
assertEquals("sig", rsa.path("use").asText());
}
/**
* A verifier that caches the key set before the first token is asked for already holds that
* token's key: the set names both algorithms from the first read, and minting reuses them.
*/
@Test
void theKeySetReadBeforeAnyTokenAlreadyHoldsTheKeyTheTokenIsSignedWith() throws Exception {
String issuer = enabledIssuer("555555555553");
JsonNode cached = keySet(issuer);
assertEquals(2, cached.path("keys").size(), cached.toString());
assertVerifies(token("555555555553", "RS256"), cached);
assertVerifies(token("555555555553", "ES384"), cached);
assertEquals(cached, keySet(issuer), "a later read publishes the same keys");
}
/** Each account's issuer publishes that account's keys, and no other account's token verifies. */
@Test
void anIssuerPublishesOnlyItsOwnAccountsKeys() throws Exception {
String first = enabledIssuer("555555555554");
String second = enabledIssuer("555555555555");
assertNotEquals(first, second);
String token = token("555555555554", "RS256");
String kid = jwt(token, 0).path("kid").asText();
assertVerifies(token, keySet(first));
for (JsonNode key : keySet(second).path("keys")) {
assertNotEquals(kid, key.path("kid").asText(), "the other account publishes this key");
}
}
/**
* Turning the feature off stops new tokens, but the issuer outlives it and so do the tokens
* already minted, which a relying party still verifies until they expire.
*/
@Test
void theIssuerStaysPublishedWhileTheFeatureIsOff() throws Exception {
String issuer = enabledIssuer("555555555556");
String token = token("555555555556", "ES384");
iam("555555555556", "DisableOutboundWebIdentityFederation").when().post("/")
.then().statusCode(200);
given().when().get(base(issuer) + "openid-configuration")
.then().statusCode(200).body("issuer", equalTo(issuer));
assertVerifies(token, keySet(issuer));
}
/**
* An issuer no account was given is not found, on either route, whether the id has the
* issuer's UUID form or not.
*/
@Test
void anUnknownIssuerIsNotFound() {
for (String id : new String[] {"00000000-0000-0000-0000-000000000000", "not-an-issuer"}) {
String unknown = "/_floci/sts/web-identity/" + id + "/.well-known/";
given().when().get(unknown + "openid-configuration").then().statusCode(404);
given().when().get(unknown + "jwks.json").then().statusCode(404);
}
}
}
@@ -24,9 +24,9 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
* {@code GetWebIdentityToken} over the wire: the signed JWT it answers with, the switch it reads,
* and the constraints it is held to.
*
* <p>The token is checked here by decoding it rather than by verifying its signature, no endpoint
* publishing the verification key yet, that being the other half of the feature. What is checked
* instead is the shape a verifier depends on, including the one detail an ECDSA JWS is easy to get
* <p>The token is checked here by decoding it rather than by verifying its signature, which
* {@link StsWebIdentityWellKnownIntegrationTest} does against the published key set. What is
* checked here is the shape a verifier depends on, including the one detail an ECDSA JWS is easy to get
* wrong: the signature is the raw {@code R || S} pair, 96 bytes for P-384, rather than the
* variable-length DER sequence the JDK's default ECDSA signer returns. That the signature verifies
* at all, against the key the issuer stored and over the claims it was made for, is
@@ -1,6 +1,7 @@
package io.floci.aws.services.iam;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.core.storage.InMemoryStorage;
import io.floci.aws.core.storage.StorageBackend;
import io.floci.aws.services.iam.model.WebIdentityTokenKey;
@@ -25,9 +26,8 @@ import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* What the wire test cannot check: that a token verifies against the key the issuer stored. Nothing
* publishes that key yet, that being the other half of the feature, so this reaches it through the
* store the issuer is built with.
* What the wire test cannot check: that a token verifies against the key the issuer stored,
* reached through the store the issuer is built with, and that the keys it publishes are those.
*
* <p>The JCA names are spelled out here rather than read off
* {@link WebIdentityTokenIssuer.Algorithm}, which is the point of the exercise: a signature that
@@ -142,4 +142,51 @@ class WebIdentityTokenIssuerTest {
assertEquals(keyId(first), keyStore.get("RS256").orElseThrow().getKeyId());
assertEquals(keyId(other), keyStore.get("ES384").orElseThrow().getKeyId());
}
/**
* The keys a relying party is handed are the ones tokens are signed with: one per algorithm,
* under the {@code kid} the token names, and a token verifies against the published half.
*/
@Test
void thePublishedKeysAreTheOnesTokensAreSignedWith() throws Exception {
String rs256 = mint(WebIdentityTokenIssuer.Algorithm.RS256, 300);
List<WebIdentityTokenIssuer.PublishedKey> published = issuer.publishedKeys(null);
assertEquals(List.of(WebIdentityTokenIssuer.Algorithm.RS256, WebIdentityTokenIssuer.Algorithm.ES384),
published.stream().map(WebIdentityTokenIssuer.PublishedKey::algorithm).toList());
WebIdentityTokenIssuer.PublishedKey key = published.get(0);
assertEquals(keyId(rs256), key.keyId(), "the key minted for the token is the one published");
Signature verifier = Signature.getInstance("SHA256withRSA");
verifier.initVerify(key.publicKey());
verifier.update(signingInput(rs256).getBytes(StandardCharsets.US_ASCII));
assertTrue(verifier.verify(signature(rs256)));
String es384 = mint(WebIdentityTokenIssuer.Algorithm.ES384, 300);
assertEquals(keyId(es384), published.get(1).keyId(),
"a key published before any token signed with it is the one the token then uses");
}
/**
* The key set is read for a named account, since the request asking for it carries none, and
* reading or minting one account's keys never touches another's.
*/
@Test
void publishedKeysAreTheNamedAccountsOwn() {
AccountAwareStorageBackend<WebIdentityTokenKey> scoped =
AccountAwareStorageBackend.inMemory("000000000000");
WebIdentityTokenIssuer accounts = new WebIdentityTokenIssuer(scoped, MAPPER);
List<WebIdentityTokenIssuer.PublishedKey> first = accounts.publishedKeys("111111111111");
List<WebIdentityTokenIssuer.PublishedKey> second = accounts.publishedKeys("222222222222");
assertNotEquals(first.get(0).keyId(), second.get(0).keyId());
assertNotEquals(first.get(1).keyId(), second.get(1).keyId());
assertEquals(first.get(0).keyId(), accounts.publishedKeys("111111111111").get(0).keyId(),
"a second read publishes the keys the first one minted");
assertEquals(first.get(0).keyId(),
scoped.getForAccount("111111111111", "RS256").orElseThrow().getKeyId());
assertTrue(scoped.getForAccount("000000000000", "RS256").isEmpty(),
"naming an account does not fall through to the default one");
}
}