feat(sts): vend a signed web identity token for the calling identity (#6517)

GetWebIdentityToken is the last operation the pinned STS model publishes and
Floci did not dispatch, which takes STS to 11 of 11. It answers "a signed JSON
Web Token (JWT) that represents the calling Amazon Web Services identity",
signed by STS and verifiable against the keys the issuer publishes.

The issuer is IAM's. Outbound web identity federation mints one issuer URL per
account, so the token names it as iss and the operation reads the switch behind
it: while the feature is off the answer is
OutboundWebIdentityFederationDisabledException, not the FeatureDisabled the IAM
getter answers. SessionDurationEscalationException is the other refusal with a
published trigger, for a caller on temporary credentials asking for a token
that would outlive its own session, "beyond what was granted when the session
was originally created". JWTPayloadSizeExceededException is modelled and
nothing published says what the maximum payload is, so no size is invented here
to refuse a request with.

A temporary credential with no live session behind it is refused as expired
rather than read as a caller that cannot be identified. IamEnforcementFilter
answers ExpiredTokenException for one and it never reaches the operation, but
with enforcement off, or in the window between that check and this one, the
session lookup comes back empty and the caller would fall to the account root
ARN this file hands an unresolvable caller, as GetCallerIdentity does. A token
is not a request: its subject is signed and outlives the call, so a session
already gone does not get one that speaks for the account, while an unknown
long-term key keeps the stand-in. The filter's wording is shared rather than
copied a second time.

The declared constraints are read ahead of all of it, as #6402 put them
elsewhere in this package: Audience required and 1 to 10 members of 1 to 1000
characters, SigningAlgorithm required at a fixed length of 5, DurationSeconds
60 to 3600 defaulting to 300, and Tags at most 50 with its keys and values held
to their own lengths and pattern. A member sent empty is a member that is
present, breaking its length rather than reading as absent, and a list member's
violation names the index the request sent rather than the number it reads as,
which is what #6478 settled.

The claim layout is the IAM User Guide's. The standard OIDC claims sit at the
top level, iss, aud, sub, iat, exp and jti, with the caller's ARN as the
subject, and the custom claims are nested under the https://sts.amazonaws.com/
namespace the guide names: aws_account for the account the token was asked for,
source_region for the region it was asked from, and the request's tags under
request_tags. "All these claims may not be present in a token at the same
time", so the organization, principal tag and session context claims the guide
also lists are left out rather than invented, and request_tags is absent from a
token whose request named none. The nesting is also what keeps a tag off a
claim STS sets, a tag named exp being a key under request_tags rather than the
claim that chooses the token's lifetime.

Two answers are readings and docs/services/sts.md says so. The model publishes
no enum for SigningAlgorithm, only the fixed length, so a five-character value
that is neither RS256 nor ES384 is answered with this package's enum violation
over the two values the reference names. The global endpoint refusal borrows
the wording AWS publishes for AssumeRoot, the note for this operation giving
none of its own.

Signing goes through a new core.common helper rather than a third copy of the
assembly: Cognito and EKS each already sign a JWT, and EksOidcService moves
onto it here. ES384 signs through the JDK's P1363 variant, so the signature is
the raw R || S pair JWS defines rather than the DER sequence a default ECDSA
signer returns. Each account's key is minted on first use per algorithm and
stored, so a restart does not invalidate a token already handed out.

Eleven tests over the wire, including the claim set with the namespaced
account and region, both signature shapes by their exact lengths, the tags
arriving under request_tags rather than as claims of their own, the ceiling the
caller's own session puts on a token, the refusal for a session already gone,
and the constraints read while the feature is off.
Beside them, a unit test verifies a minted token against the public half of the
stored key for both algorithms, a length being no evidence of what was signed,
and holds that one token's signature does not verify over another's claims; and
the handler test takes the session ceiling to its own boundary on a fixed clock,
where a token ending exactly with the session is issued, one ending a second
later is refused, and nothing is minted on the refusal.

What is not here is the other half: nothing publishes the verification key yet,
so the discovery documents the issuer URL would host are not served, and the
docs say that plainly.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-10-25 21:15:35 -05:00
1 parent 56196fec1c
commit 4c55ec6b77
12 files changed
+1214 -26

No files matched your search

@@ -0,0 +1,43 @@
package io.github.hectorvent.floci.core.common;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.PrivateKey;
import java.security.Signature;
/**
* Signs a compact JWS, the {@code header.payload.signature} form a JWT travels in. The header and
* the claim set arrive already serialized, so what belongs to one service's token stays with that
* service and only the assembly is shared.
*
* <p>Each part is base64url without padding, which is what JWS requires and what {@link Base64Url}
* produces. An ECDSA signature has to be the raw {@code R || S} pair rather than the DER sequence
* {@code SHA384withECDSA} returns, so an ECDSA caller names the JDK's {@code ...inP1363Format}
* variant, which produces that pair directly and leaves nothing to re-encode here.
*/
public final class CompactJws {
private CompactJws() {
}
/**
* The signed token for a serialized {@code header} and {@code claims}, where {@code algorithm}
* is the JCA signature name for the {@code alg} the header declares.
*/
public static String sign(byte[] header, byte[] claims, PrivateKey key, String algorithm) {
String signingInput = Base64Url.encode(header) + "." + Base64Url.encode(claims);
return signingInput + "." + Base64Url.encode(signature(signingInput, key, algorithm));
}
private static byte[] signature(String signingInput, PrivateKey key, String algorithm) {
try {
Signature signature = Signature.getInstance(algorithm);
signature.initSign(key);
signature.update(signingInput.getBytes(StandardCharsets.UTF_8));
return signature.sign();
} catch (GeneralSecurityException e) {
throw new IllegalStateException(
"Signing a compact JWS with " + algorithm + " failed", e);
}
}
}
@@ -97,8 +97,11 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
private static final String S3_INVALID_ACCESS_KEY_ID =
"The AWS Access Key Id you provided does not exist in our records.";
/** AWS's wording for temporary credentials past their expiration. */
private static final String EXPIRED_TOKEN = "The security token included in the request has expired.";
/**
* AWS's wording for temporary credentials past their expiration, shared with an operation that
* finds the session gone after this filter has let the request through.
*/
public static final String EXPIRED_TOKEN = "The security token included in the request has expired.";
/** S3's wording for the same. */
private static final String S3_EXPIRED_TOKEN = "The provided token has expired.";
@@ -6,7 +6,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsEndpoints;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.Base64Url;
import io.github.hectorvent.floci.core.common.CompactJws;
import io.github.hectorvent.floci.core.common.OidcIssuerKeyLookup;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageBackend;
@@ -16,14 +16,12 @@ import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
@@ -180,12 +178,9 @@ public class EksOidcService implements OidcIssuerKeyLookup {
long exp = now + lifetime;
String subject = "system:serviceaccount:" + namespace + ":" + serviceAccount;
String header = Base64Url.encode(writeJson(buildHeader(key.getKeyId())));
String payload = Base64Url.encode(writeJson(
buildClaims(issuer, aud, subject, namespace, serviceAccount, now, exp)));
String signingInput = header + "." + payload;
return signingInput + "." + sign(signingInput, toPrivateKey(key.getPrivateKey()));
return CompactJws.sign(writeJson(buildHeader(key.getKeyId())),
writeJson(buildClaims(issuer, aud, subject, namespace, serviceAccount, now, exp)),
toPrivateKey(key.getPrivateKey()), "SHA256withRSA");
}
private int resolveLifetime(Integer requested) {
@@ -232,17 +227,6 @@ public class EksOidcService implements OidcIssuerKeyLookup {
}
}
private String sign(String signingInput, PrivateKey privateKey) {
try {
Signature signature = Signature.getInstance("SHA256withRSA");
signature.initSign(privateKey);
signature.update(signingInput.getBytes(StandardCharsets.UTF_8));
return Base64Url.encode(signature.sign());
} catch (GeneralSecurityException e) {
throw new IllegalStateException("EKS OIDC token signing failed", e);
}
}
RSAPublicKey toPublicKey(String encoded) {
try {
X509EncodedKeySpec spec = new X509EncodedKeySpec(Base64.getDecoder().decode(encoded));
@@ -3092,6 +3092,18 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
}
}
/**
* The account's federation state while the feature is on, for a caller that answers its own
* refusal rather than IAM's: STS turns a token request down with
* {@code OutboundWebIdentityFederationDisabledException}, not with {@code FeatureDisabled}.
*/
public Optional<OutboundWebIdentityFederation> findEnabledOutboundWebIdentityFederation() {
synchronized (outboundFederationLock) {
return outboundFederation.get(OUTBOUND_FEDERATION_KEY)
.filter(OutboundWebIdentityFederation::isEnabled);
}
}
/** The issuer URL and whether JWT vending is on, which it is while the feature is enabled. */
public OutboundWebIdentityFederation getOutboundWebIdentityFederationInfo() {
synchronized (outboundFederationLock) {
@@ -4533,6 +4545,15 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
.filter(token -> !token.isBlank());
}
/**
* When the session a temporary access key belongs to expires, for callers that must not hand
* out something outliving it. Empty for a long-term key, which names no session, and for a
* session already expired, which no longer resolves.
*/
public Optional<Instant> findSessionExpiration(String accessKeyId) {
return currentSession(accessKeyId).map(SessionCredential::getExpiration);
}
/** Whether an access key ID identifies Floci's documented public deployer credential. */
public boolean isSeededDeployerAccessKey(String accessKeyId) {
return DEFAULT_DEPLOYER_ACCESS_KEY_ID.equals(accessKeyId);
@@ -6,6 +6,7 @@ import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.AwsNamespaces;
import io.github.hectorvent.floci.core.common.AwsQueryController;
import io.github.hectorvent.floci.core.common.AwsQueryLists;
import io.github.hectorvent.floci.core.common.AwsQueryResponse;
import io.github.hectorvent.floci.core.common.AwsRegions;
import io.github.hectorvent.floci.core.common.IamConditionContextResolver;
@@ -19,6 +20,7 @@ import io.github.hectorvent.floci.core.common.XmlBuilder;
import io.github.hectorvent.floci.services.iam.model.DelegationRequest;
import io.github.hectorvent.floci.services.iam.model.IamPolicy;
import io.github.hectorvent.floci.services.iam.model.IamRole;
import io.github.hectorvent.floci.services.iam.model.OutboundWebIdentityFederation;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.core.Context;
@@ -34,10 +36,14 @@ import java.time.Clock;
import java.time.Instant;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ThreadLocalRandom;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
@@ -60,6 +66,27 @@ public class StsQueryHandler {
/** "the maximum session duration of 900 seconds (15 minutes)", which is also the default here. */
private static final int MAX_ROOT_SESSION_SECONDS = 900;
private static final int MAX_SESSION_TOKEN_SIZE = 4096;
/** {@code webIdentityTokenAudienceListType}: 1 to 10 audiences, each 1 to 1000 characters. */
private static final int MAX_TOKEN_AUDIENCES = 10;
private static final int MAX_TOKEN_AUDIENCE_LENGTH = 1000;
/** {@code jwtAlgorithmType} is a fixed length of 5, which both valid values are. */
private static final int SIGNING_ALGORITHM_LENGTH = 5;
/** {@code tagListType} on this operation: at most 50 tags, each a key and a value. */
private static final int MAX_TOKEN_TAGS = 50;
private static final int MAX_TAG_KEY_LENGTH = 128;
private static final int MAX_TAG_VALUE_LENGTH = 256;
/** {@code tagKeyType} and {@code tagValueType} share this pattern, the value allowing empty. */
private static final Pattern TAG_PATTERN = Pattern.compile("[\\p{L}\\p{Z}\\p{N}_.:/=+\\-@]+");
/** A member of {@code Audience}, capturing the prefix it is named under and its index. */
private static final Pattern AUDIENCE_MEMBER =
Pattern.compile("(Audience(?:\\.member)?\\.([^.]+))");
/** A member of {@code Tags}, which carries its key and its value under that prefix. */
private static final Pattern TAG_MEMBER =
Pattern.compile("(Tags(?:\\.member)?\\.([^.]+))\\.(?:Key|Value)");
/** "If not specified, the default duration is 300 seconds (5 minutes)." */
private static final int DEFAULT_TOKEN_SECONDS = 300;
private static final int MIN_TOKEN_SECONDS = 60;
private static final int MAX_TOKEN_SECONDS = 3600;
private static final String STS_AUDIENCE = "sts.amazonaws.com"; // partition-literal: web-identity audience; no source outside the commercial partition (P9)
private final IamService iamService;
@@ -74,6 +101,7 @@ public class StsQueryHandler {
private final SAMLTrustPolicyEvaluator samlTrustEvaluator;
private final DelegationRequestService delegationRequestService;
private final CentralRootAccess centralRootAccess;
private final WebIdentityTokenIssuer tokenIssuer;
private final Clock clock;
/** CSPRNG for session secret keys and session tokens; ordinary IDs keep using {@link ThreadLocalRandom}. */
@@ -94,10 +122,11 @@ public class StsQueryHandler {
SAMLProviderService samlProviderService,
SAMLTrustPolicyEvaluator samlTrustEvaluator,
DelegationRequestService delegationRequestService,
CentralRootAccess centralRootAccess) {
CentralRootAccess centralRootAccess,
WebIdentityTokenIssuer tokenIssuer) {
this(iamService, accountResolver, regionResolver, config, trustPolicyEvaluator, webIdentityTrustEvaluator,
tokenVerifier, oidcIssuerKeys, samlProviderService, samlTrustEvaluator, delegationRequestService,
centralRootAccess, Clock.systemUTC());
centralRootAccess, tokenIssuer, Clock.systemUTC());
}
StsQueryHandler(IamService iamService, AccountResolver accountResolver, RegionResolver regionResolver,
@@ -109,6 +138,7 @@ public class StsQueryHandler {
SAMLTrustPolicyEvaluator samlTrustEvaluator,
DelegationRequestService delegationRequestService,
CentralRootAccess centralRootAccess,
WebIdentityTokenIssuer tokenIssuer,
Clock clock) {
this.iamService = iamService;
this.accountResolver = accountResolver;
@@ -122,6 +152,7 @@ public class StsQueryHandler {
this.samlTrustEvaluator = samlTrustEvaluator;
this.delegationRequestService = delegationRequestService;
this.centralRootAccess = centralRootAccess;
this.tokenIssuer = tokenIssuer;
this.clock = clock;
}
@@ -139,6 +170,7 @@ public class StsQueryHandler {
case "DecodeAuthorizationMessage" -> handleDecodeAuthorizationMessage(params);
case "GetDelegatedAccessToken" -> handleGetDelegatedAccessToken(params);
case "AssumeRoot" -> handleAssumeRoot(params);
case "GetWebIdentityToken" -> handleGetWebIdentityToken(params);
default -> AwsQueryResponse.error("UnsupportedOperation",
"Operation " + action + " is not supported by STS.", AwsNamespaces.STS, 400);
};
@@ -958,6 +990,243 @@ public class StsQueryHandler {
return null;
}
/**
* {@code GetWebIdentityToken} answers "a signed JSON Web Token (JWT) that represents the
* calling Amazon Web Services identity", signed by STS and verifiable "using the verification
* keys published at the issuer's JWKS endpoint". The issuer is the one IAM mints for the
* account when outbound web identity federation is enabled, so this reads the state that
* switch keeps and refuses while it is off, with
* {@code OutboundWebIdentityFederationDisabledException} rather than IAM's own
* {@code FeatureDisabled}.
*
* <p>The declared constraints are read ahead of all of it: {@code Audience} is 1 to 10 members
* of 1 to 1000 characters each and required, {@code SigningAlgorithm} is a fixed length of 5
* and required, {@code DurationSeconds} is 60 to 3600 and defaults to 300, and {@code Tags} is
* at most 50 tags whose keys and values carry their own lengths and pattern. A member sent
* empty is a member that is present, so it breaks its length rather than reading as absent.
* The duration keeps this file's own check, which answers the first thing it finds and reports
* a value that is no integer as {@code InvalidParameterValue}; everything else is reported
* together, in the order the model lists the members.
*
* <p>Three things here are readings rather than published behaviour, and the docs say so. The
* model publishes no enum for {@code SigningAlgorithm}, only the fixed length, so a five
* character value that is neither {@code RS256} nor {@code ES384} is answered with the enum
* violation this package renders for a value outside a documented set. The global endpoint is
* refused because the Reference says "The GetWebIdentityToken API is not available on the STS
* Global endpoint" without giving the refusal, so it borrows the wording AWS publishes for
* {@code AssumeRoot}, and a request to a local host names no such endpoint and is not
* refused. {@code JWTPayloadSizeExceededException} is modelled and nothing published says what
* the maximum payload is, so no size is invented here to refuse.
*
* <p>A temporary credential with no live session behind it is refused as expired rather than
* read as a caller that cannot be identified. {@link IamEnforcementFilter} answers
* {@code ExpiredTokenException} for one and it never reaches here, but with enforcement off,
* or in the window between that check and this one, the session lookup comes back empty and
* the caller would fall to the account root ARN this file hands an unresolvable caller. A
* token is not a request: its subject is signed and outlives the call, so a session already
* gone does not get one that speaks for the account. An unknown long-term key keeps the
* stand-in, which is what {@code GetCallerIdentity} answers it.
*/
private Response handleGetWebIdentityToken(MultivaluedMap<String, String> params) {
if (arrivedOnTheGlobalEndpoint()) {
return AwsQueryResponse.error("ValidationError", "The global endpoint is not supported"
+ " for GetWebIdentityToken. You must send this request to a Regional AWS STS"
+ " endpoint.", AwsNamespaces.STS, 400);
}
Response durationValidation =
validateDurationSeconds(params, MIN_TOKEN_SECONDS, MAX_TOKEN_SECONDS);
if (durationValidation != null) {
return durationValidation;
}
List<ListMember> audiences = listMembers(params, AUDIENCE_MEMBER);
Map<String, String> tagClaims = new LinkedHashMap<>();
List<String> violations = new ArrayList<>(audienceViolations(params, audiences));
violations.addAll(signingAlgorithmViolations(params.getFirst("SigningAlgorithm")));
violations.addAll(tagViolations(params, tagClaims));
if (!violations.isEmpty()) {
return AwsQueryResponse.error("ValidationError",
SmithyValidationErrors.message(violations), AwsNamespaces.STS, 400);
}
String accessKeyId = callerAccessKeyId();
Optional<Instant> sessionEnds = accessKeyId == null
? Optional.empty()
: iamService.findSessionExpiration(accessKeyId);
if (sessionEnds.isEmpty() && IamService.isTemporaryAccessKey(accessKeyId)) {
return AwsQueryResponse.error("ExpiredTokenException",
IamEnforcementFilter.EXPIRED_TOKEN, AwsNamespaces.STS, 403);
}
Optional<OutboundWebIdentityFederation> federation =
iamService.findEnabledOutboundWebIdentityFederation();
if (federation.isEmpty()) {
return AwsQueryResponse.error("OutboundWebIdentityFederationDisabledException",
"The outbound web identity federation feature is not enabled for this account."
+ " To use this feature, you must first enable it through the AWS"
+ " Management Console or API.", AwsNamespaces.STS, 403);
}
Instant issuedAt = clock.instant();
Instant expiration = issuedAt.plusSeconds(
getIntParam(params, "DurationSeconds", DEFAULT_TOKEN_SECONDS));
if (sessionEnds.filter(expiration::isAfter).isPresent()) {
return AwsQueryResponse.error("SessionDurationEscalationException",
"The requested token duration would extend the session beyond its original"
+ " expiration time. You cannot use this operation to extend the"
+ " lifetime of a session beyond what was granted when the session was"
+ " originally created.", AwsNamespaces.STS, 403);
}
String subject = iamService.resolveCallerArn(accessKeyId).orElseGet(() ->
regionResolver.buildGlobalArn("iam", regionResolver.getAccountId(), "root"));
String token = tokenIssuer.mint(
WebIdentityTokenIssuer.Algorithm.valueOf(params.getFirst("SigningAlgorithm")),
federation.get().getIssuerIdentifier(), subject,
audiences.stream().map(member -> value(params, member)).toList(),
new WebIdentityTokenIssuer.CustomClaims(regionResolver.getAccountId(),
regionResolver.getRegion(), tagClaims),
issuedAt, expiration);
LOG.debugv("Issued a web identity token for {0} expiring at {1}", subject, expiration);
String result = new XmlBuilder()
.elem("WebIdentityToken", token)
.elem("Expiration", isoDate(expiration))
.build();
return Response.ok(
AwsQueryResponse.envelope("GetWebIdentityToken", AwsNamespaces.STS, result)).build();
}
/**
* One member of a Query list: the prefix its parameters are named under, and the index the
* request numbered it with, read back as it was spelled rather than as the number it reads as.
*/
private record ListMember(String prefix, String index) {
}
/**
* The members of a list, in the order their indexes read. The patterns capture the prefix
* because a member of a list of structures carries its fields under it, which
* {@link AwsQueryLists#memberKeys} does not match, and because the index a path names is the
* one the request sent. A member present with an empty value is still a member.
*/
private static List<ListMember> listMembers(MultivaluedMap<String, String> params,
Pattern names) {
return params.keySet().stream()
.map(names::matcher)
.filter(Matcher::matches)
.map(matcher -> new ListMember(matcher.group(1), matcher.group(2)))
.distinct()
.sorted(Comparator.comparingInt(
member -> AwsQueryLists.memberIndex(member.prefix())))
.toList();
}
private static String value(MultivaluedMap<String, String> params, ListMember member) {
String value = params.getFirst(member.prefix());
return value == null ? "" : value;
}
/**
* {@code Audience} is required, so a list of no members is the required member reading as null:
* a Query list of none is how an absent one arrives, which is what makes its minimum of 1
* unreachable on its own.
*/
private static List<String> audienceViolations(MultivaluedMap<String, String> params,
List<ListMember> audiences) {
if (audiences.isEmpty()) {
return List.of(SmithyValidationErrors.notNull("audience"));
}
List<String> violations = new ArrayList<>();
if (audiences.size() > MAX_TOKEN_AUDIENCES) {
violations.add("Value at 'audience' failed to satisfy constraint: Member must have"
+ " length less than or equal to " + MAX_TOKEN_AUDIENCES);
}
for (ListMember audience : audiences) {
addIfPresent(violations, SmithyValidationErrors.lengthOutOfRange(
"audience." + audience.index() + ".member", value(params, audience), 1,
MAX_TOKEN_AUDIENCE_LENGTH));
}
return violations;
}
/**
* The model gives {@code jwtAlgorithmType} a fixed length of 5 and no enum, and the Reference
* names the two values that length is for, so the length is the declared constraint and the
* value set is read from the documentation.
*/
private static List<String> signingAlgorithmViolations(String algorithm) {
if (algorithm == null) {
return List.of(SmithyValidationErrors.notNull("signingAlgorithm"));
}
String length = SmithyValidationErrors.lengthOutOfRange("signingAlgorithm", algorithm,
SIGNING_ALGORITHM_LENGTH, SIGNING_ALGORITHM_LENGTH);
if (length != null) {
return List.of(length);
}
if (!WebIdentityTokenIssuer.Algorithm.names().contains(algorithm)) {
return List.of(SmithyValidationErrors.notInEnum(algorithm, "signingAlgorithm",
WebIdentityTokenIssuer.Algorithm.names()));
}
return List.of();
}
/**
* Each tag is a {@code Tag}, which declares both its key and its value required, so a member
* sent with only one of them breaks the other. The claims a valid tag set contributes are
* collected here rather than read a second time, the last value winning for a key sent twice,
* which is how a Query map's duplicate key resolves elsewhere in this package.
*/
private static List<String> tagViolations(MultivaluedMap<String, String> params,
Map<String, String> claims) {
List<ListMember> tags = listMembers(params, TAG_MEMBER);
if (tags.isEmpty()) {
return List.of();
}
List<String> violations = new ArrayList<>();
if (tags.size() > MAX_TOKEN_TAGS) {
violations.add("Value at 'tags' failed to satisfy constraint: Member must have length"
+ " less than or equal to " + MAX_TOKEN_TAGS);
}
for (ListMember tag : tags) {
String path = "tags." + tag.index() + ".member.";
String key = params.getFirst(tag.prefix() + ".Key");
String value = params.getFirst(tag.prefix() + ".Value");
if (key == null) {
violations.add(SmithyValidationErrors.notNull(path + "key"));
} else {
addIfPresent(violations, SmithyValidationErrors.lengthOutOfRange(path + "key", key,
1, MAX_TAG_KEY_LENGTH));
addIfPresent(violations, patternViolation(path + "key", key, false));
}
if (value == null) {
violations.add(SmithyValidationErrors.notNull(path + "value"));
} else {
addIfPresent(violations, SmithyValidationErrors.lengthOutOfRange(path + "value",
value, 0, MAX_TAG_VALUE_LENGTH));
addIfPresent(violations, patternViolation(path + "value", value, true));
}
if (key != null && value != null) {
claims.put(key, value);
}
}
return violations;
}
/** {@code tagValueType}'s pattern allows an empty value where {@code tagKeyType}'s does not. */
private static String patternViolation(String path, String value, boolean emptyAllowed) {
if (emptyAllowed && value.isEmpty()) {
return null;
}
if (TAG_PATTERN.matcher(value).matches()) {
return null;
}
return "Value '" + value + "' at '" + path + "' failed to satisfy constraint: Member must"
+ " satisfy regular expression pattern: " + TAG_PATTERN.pattern();
}
private static void addIfPresent(List<String> violations, String violation) {
if (violation != null) {
violations.add(violation);
}
}
private String credentialsXml(String accessKeyId, String secretKey, String sessionToken, Instant expiration) {
return new XmlBuilder()
.start("Credentials")
@@ -0,0 +1,187 @@
package io.github.hectorvent.floci.services.iam;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.CompactJws;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.iam.model.WebIdentityTokenKey;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.spec.ECGenParameterSpec;
import java.security.spec.PKCS8EncodedKeySpec;
import java.time.Instant;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.UUID;
/**
* Mints the signed JWT {@code GetWebIdentityToken} answers with, and owns the signing material
* behind it. The issuer URL is IAM's: outbound web identity federation mints one per account, and
* the token names it as {@code iss} so a relying party that pinned that issuer can verify against
* the keys it publishes.
*
* <p>The claim layout is the one the IAM User Guide publishes: the standard OIDC claims at the
* top level, and the AWS identity claims and the request's tags nested under the
* {@code https://sts.amazonaws.com/} namespace, where the guide's sample token carries
* {@code aws_account}, {@code source_region} and the tags under {@code request_tags}. "Please note
* that all these claims may not be present in a token at the same time", so the organization,
* principal tag and session context claims the guide also lists are left out rather than
* invented, and {@code request_tags} is absent from a token whose request named none.
*
* <p>The nesting is also what keeps a tag off a claim STS sets: a tag named {@code exp} or
* {@code sub} is a key under {@code request_tags}, so no request can lengthen its own token's life
* or speak for another identity by naming a tag after the claim that says so.
*/
@ApplicationScoped
public class WebIdentityTokenIssuer {
private static final Logger LOG = Logger.getLogger(WebIdentityTokenIssuer.class);
private static final int RSA_KEY_SIZE = 2048;
/** P-384, the curve {@code ES384} names, as the JDK spells it. */
private static final String P384_CURVE = "secp384r1";
/** The namespace the guide nests the identity claims and the request's tags under. */
private static final String CLAIM_NAMESPACE = "https://sts.amazonaws.com/"; // partition-literal: the claim namespace the IAM User Guide publishes, with no source for another partition's spelling (P9)
private final StorageBackend<String, WebIdentityTokenKey> keyStore;
private final ObjectMapper objectMapper;
@Inject
public WebIdentityTokenIssuer(StorageFactory storageFactory, ObjectMapper objectMapper) {
this(storageFactory.create("iam", "sts-web-identity-token-keys.json",
new TypeReference<Map<String, WebIdentityTokenKey>>() {
}), objectMapper);
}
WebIdentityTokenIssuer(StorageBackend<String, WebIdentityTokenKey> keyStore,
ObjectMapper objectMapper) {
this.keyStore = keyStore;
this.objectMapper = objectMapper;
}
/**
* The two algorithms the operation publishes, in the order the API Reference names them:
* "Valid values are RS256 (RSA with SHA-256) and ES384 (ECDSA using P-384 curve with
* SHA-384)". Each carries the JCA names behind it, the signature one in the {@code P1363}
* variant for ECDSA, since JWS defines that signature as the raw {@code R || S} pair.
*/
public enum Algorithm {
RS256("RSA", "SHA256withRSA"),
ES384("EC", "SHA384withECDSAinP1363Format");
private final String keyAlgorithm;
private final String signatureAlgorithm;
Algorithm(String keyAlgorithm, String signatureAlgorithm) {
this.keyAlgorithm = keyAlgorithm;
this.signatureAlgorithm = signatureAlgorithm;
}
/** The names the Reference lists, in the order a violation reports them in. */
public static List<String> names() {
return List.of(RS256.name(), ES384.name());
}
}
/**
* The claims the guide nests under the namespace: the account the token was asked for, the
* region it was asked from, and the request's tags, which the guide carries under
* {@code request_tags}.
*/
public record CustomClaims(String account, String sourceRegion,
Map<String, String> requestTags) {
}
/**
* The token for one request: the standard claims, the custom claims under AWS's own namespace,
* and the {@code kid} of the account's key for {@code algorithm}, minted on first use.
*/
public String mint(Algorithm algorithm, String issuer, String subject, List<String> audiences,
CustomClaims custom, Instant issuedAt, Instant expiresAt) {
WebIdentityTokenKey key = ensureKey(algorithm);
ObjectNode header = objectMapper.createObjectNode();
header.put("alg", algorithm.name());
header.put("typ", "JWT");
header.put("kid", key.getKeyId());
ObjectNode claims = claims(issuer, subject, audiences, custom, issuedAt, expiresAt);
return CompactJws.sign(writeJson(header), writeJson(claims),
privateKey(key, algorithm), algorithm.signatureAlgorithm);
}
private ObjectNode claims(String issuer, String subject, List<String> audiences,
CustomClaims custom, Instant issuedAt, Instant expiresAt) {
ObjectNode claims = objectMapper.createObjectNode();
claims.put("iss", issuer);
ArrayNode audience = claims.putArray("aud");
audiences.forEach(audience::add);
claims.put("sub", subject);
claims.put("iat", issuedAt.getEpochSecond());
claims.put("exp", expiresAt.getEpochSecond());
claims.put("jti", UUID.randomUUID().toString());
ObjectNode identity = claims.putObject(CLAIM_NAMESPACE);
identity.put("aws_account", custom.account());
identity.put("source_region", custom.sourceRegion());
if (!custom.requestTags().isEmpty()) {
ObjectNode requestTags = identity.putObject("request_tags");
custom.requestTags().forEach(requestTags::put);
}
return claims;
}
private synchronized WebIdentityTokenKey ensureKey(Algorithm algorithm) {
return keyStore.get(algorithm.name()).orElseGet(() -> generateKey(algorithm));
}
private WebIdentityTokenKey generateKey(Algorithm algorithm) {
try {
KeyPairGenerator generator = KeyPairGenerator.getInstance(algorithm.keyAlgorithm);
switch (algorithm) {
case RS256 -> generator.initialize(RSA_KEY_SIZE);
case ES384 -> generator.initialize(new ECGenParameterSpec(P384_CURVE));
}
KeyPair pair = generator.generateKeyPair();
WebIdentityTokenKey key = new WebIdentityTokenKey();
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);
LOG.debugv("Generated the account's {0} web identity token signing key", algorithm);
return key;
} catch (GeneralSecurityException e) {
throw new IllegalStateException(
"Failed to generate a " + algorithm + " web identity token signing key", e);
}
}
private static PrivateKey privateKey(WebIdentityTokenKey key, Algorithm algorithm) {
try {
PKCS8EncodedKeySpec spec =
new PKCS8EncodedKeySpec(Base64.getDecoder().decode(key.getPrivateKey()));
return KeyFactory.getInstance(algorithm.keyAlgorithm).generatePrivate(spec);
} catch (GeneralSecurityException | IllegalArgumentException e) {
throw new IllegalStateException(
"Failed to load the " + algorithm + " web identity token signing key", e);
}
}
private byte[] writeJson(ObjectNode node) {
try {
return objectMapper.writeValueAsBytes(node);
} catch (JsonProcessingException e) {
throw new IllegalStateException("Failed to serialize web identity token claims", e);
}
}
}
@@ -0,0 +1,32 @@
package io.github.hectorvent.floci.services.iam.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.quarkus.runtime.annotations.RegisterForReflection;
/**
* The signing material behind one of the account's web identity token algorithms: the key id the
* token's {@code kid} header names, and the keypair itself, the public half X.509 encoded and the
* private half PKCS#8, both base64.
*
* <p>One of these exists per account and per signing algorithm, minted the first time a token asks
* for that algorithm. It is stored rather than held in memory because a relying party verifies a
* token against the published key, so a restart that minted a new one would invalidate every token
* already handed out.
*/
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public class WebIdentityTokenKey {
private String keyId;
private String publicKey;
private String privateKey;
public WebIdentityTokenKey() {}
public String getKeyId() { return keyId; }
public void setKeyId(String keyId) { this.keyId = keyId; }
public String getPublicKey() { return publicKey; }
public void setPublicKey(String publicKey) { this.publicKey = publicKey; }
public String getPrivateKey() { return privateKey; }
public void setPrivateKey(String privateKey) { this.privateKey = privateKey; }
}