diff --git a/docs/services/index.md b/docs/services/index.md
index f980be76f0..38b6f3d92c 100644
--- a/docs/services/index.md
+++ b/docs/services/index.md
@@ -24,7 +24,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac
| [API Gateway v1](api-gateway.md) | `/restapis/...` | REST JSON | 80 |
| [API Gateway v2](api-gateway.md#v2) | `/v2/apis/...` | REST JSON | 53 + data-plane |
| [IAM](iam.md) | `POST /` with `Action=` param | Query | 180 |
-| [STS](sts.md) | `POST /` with `Action=` param | Query | 10 |
+| [STS](sts.md) | `POST /` with `Action=` param | Query | 11 |
| [AWS Sign-In](iam.md#aws-sign-in-login-credentials) | `/v1/authorize`, `/v1/token` | REST JSON | 2 |
| [Organizations](organizations.md) | `POST /` + `X-Amz-Target: AWSOrganizationsV20161128.*` | JSON 1.1 | 56 |
| [Cognito](cognito.md) | `POST /` + `X-Amz-Target: AWSCognitoIdentityProviderService.*` | JSON 1.1 | 90 |
diff --git a/docs/services/sts.md b/docs/services/sts.md
index 8e54ed1502..1f1f2757b5 100644
--- a/docs/services/sts.md
+++ b/docs/services/sts.md
@@ -16,6 +16,7 @@
| `GetDelegatedAccessToken` | Exchange a delegation request's trade-in token for temporary credentials |
| `GetAccessKeyInfo` | Returns the account an access key ID belongs to |
| `AssumeRoot` | Opens a privileged session on a member account of the organization |
+| `GetWebIdentityToken` | Returns a signed JWT representing the calling identity |
## Privileged Root Sessions
@@ -99,6 +100,60 @@ Only the account that filed the delegation request may exchange its token; any o
stating it is not populated for this operation. See the delegation request section of the
[IAM service doc](iam.md) for the lifecycle that issues the token.
+## Web Identity Tokens
+
+`GetWebIdentityToken` answers "a signed JSON Web Token (JWT) that represents the calling AWS
+identity", for authenticating to an external service that supports OIDC discovery. The issuer is
+IAM's: outbound web identity federation mints one issuer URL per account, and the token names it as
+`iss`, so the operation reads the switch behind that URL and answers
+`OutboundWebIdentityFederationDisabledException` while the feature is off rather than IAM's own
+`FeatureDisabled`. The declared constraints are read ahead of the switch, as everywhere else in
+this package: `Audience` is required and holds 1 to 10 audiences of 1 to 1000 characters,
+`SigningAlgorithm` is required at a fixed length of 5, `DurationSeconds` is 60 to 3600 and defaults
+to 300, and `Tags` is at most 50 tags whose keys and values carry their own lengths and pattern. An
+audience sent empty is an audience that is present, so it breaks the minimum length rather than
+reading as absent.
+
+A session cannot outlive itself. `SessionDurationEscalationException` is what a caller holding
+temporary credentials gets when the requested duration would run past the moment its own session
+ends, which is the sentence the reference gives that error: "You cannot use this operation to
+extend the lifetime of a session beyond what was granted when the session was originally created."
+A long-term key names no session and is bounded only by the 3600-second maximum.
+
+A temporary credential with no live session behind it is refused with `ExpiredTokenException`, the
+wording the enforcement filter answers for an expired session, rather than read as a caller Floci
+cannot identify. An unresolvable caller is the account root stand-in elsewhere in this package,
+which is what `GetCallerIdentity` answers for an unknown key, and a token is not a request: its
+subject is signed and outlives the call, so a session that has already gone does not get one
+naming the account root. An unknown long-term key keeps the stand-in.
+
+The claim layout is the one the IAM User Guide publishes. 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: `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`. The guide notes that "all these claims may not be present in
+a token at the same time", so the organization, principal tag and session context claims it also
+lists are left out rather than invented, and `request_tags` is absent from a token whose request
+named no tags. The nesting is 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 here are Floci's readings. `jwtAlgorithmType` publishes a fixed length of 5 and no enum, so a
+five-character value that is neither `RS256` nor `ES384` is answered with the enum violation this
+package renders for a value outside a documented set, the two values coming from the reference
+rather than from the model. 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 `AssumeRoot`; a request to a local host names no such
+endpoint and is not refused. `JWTPayloadSizeExceededException` is modelled and nothing published
+says what the maximum payload is, so no size is invented here to refuse a request with.
+
+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.
+
## Configuration
| Variable | Default | Description |
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/CompactJws.java b/src/main/java/io/github/hectorvent/floci/core/common/CompactJws.java
new file mode 100644
index 0000000000..2a0c9b4d20
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/core/common/CompactJws.java
@@ -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.
+ *
+ *
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);
+ }
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java b/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java
index 15bb5fa718..1ca56e1f30 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java
@@ -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.";
diff --git a/src/main/java/io/github/hectorvent/floci/services/eks/EksOidcService.java b/src/main/java/io/github/hectorvent/floci/services/eks/EksOidcService.java
index 30477c3919..c24bf4eb63 100644
--- a/src/main/java/io/github/hectorvent/floci/services/eks/EksOidcService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/eks/EksOidcService.java
@@ -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));
diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java
index f3197b2c27..1b87fd7112 100644
--- a/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java
@@ -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 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 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);
diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/StsQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/iam/StsQueryHandler.java
index 10f4459dec..63e1e122a0 100644
--- a/src/main/java/io/github/hectorvent/floci/services/iam/StsQueryHandler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/iam/StsQueryHandler.java
@@ -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}.
+ *
+ * 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.
+ *
+ *
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.
+ *
+ *
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 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 audiences = listMembers(params, AUDIENCE_MEMBER);
+ Map tagClaims = new LinkedHashMap<>();
+ List 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 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 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 listMembers(MultivaluedMap 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 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 audienceViolations(MultivaluedMap params,
+ List audiences) {
+ if (audiences.isEmpty()) {
+ return List.of(SmithyValidationErrors.notNull("audience"));
+ }
+ List 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 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 tagViolations(MultivaluedMap params,
+ Map claims) {
+ List tags = listMembers(params, TAG_MEMBER);
+ if (tags.isEmpty()) {
+ return List.of();
+ }
+ List 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 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")
diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/WebIdentityTokenIssuer.java b/src/main/java/io/github/hectorvent/floci/services/iam/WebIdentityTokenIssuer.java
new file mode 100644
index 0000000000..5a9833f2d9
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/iam/WebIdentityTokenIssuer.java
@@ -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.
+ *
+ * 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.
+ *
+ *
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 keyStore;
+ private final ObjectMapper objectMapper;
+
+ @Inject
+ public WebIdentityTokenIssuer(StorageFactory storageFactory, ObjectMapper objectMapper) {
+ this(storageFactory.create("iam", "sts-web-identity-token-keys.json",
+ new TypeReference