mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 06:00:46 -05:00
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:
1 parent
56196fec1c
commit
4c55ec6b77
12 files changed
+1214
-26
No files matched your search
@@ -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 |
|
||||
|
||||
@@ -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 |
|
||||
|
||||
@@ -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; }
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import io.github.hectorvent.floci.core.common.WebIdentityToken;
|
||||
import io.github.hectorvent.floci.core.common.WebIdentityTokenVerifier;
|
||||
import io.github.hectorvent.floci.services.iam.model.DelegationRequest;
|
||||
import io.github.hectorvent.floci.services.iam.model.IamRole;
|
||||
import io.github.hectorvent.floci.services.iam.model.OutboundWebIdentityFederation;
|
||||
import io.github.hectorvent.floci.testing.PartitionMatrix;
|
||||
import io.github.hectorvent.floci.testing.PartitionMatrix.PartitionCase;
|
||||
import jakarta.ws.rs.core.HttpHeaders;
|
||||
@@ -36,6 +37,7 @@ import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyList;
|
||||
import static org.mockito.ArgumentMatchers.anyMap;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
@@ -88,6 +90,13 @@ class StsQueryHandlerTest {
|
||||
|
||||
private static StsQueryHandler newHandler(IamService iamService, RegionResolver regionResolver,
|
||||
Clock clock, DelegationRequestService delegation) {
|
||||
return newHandler(iamService, regionResolver, clock, delegation,
|
||||
mock(WebIdentityTokenIssuer.class));
|
||||
}
|
||||
|
||||
private static StsQueryHandler newHandler(IamService iamService, RegionResolver regionResolver,
|
||||
Clock clock, DelegationRequestService delegation,
|
||||
WebIdentityTokenIssuer tokenIssuer) {
|
||||
EmulatorConfig config = mock(EmulatorConfig.class);
|
||||
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
|
||||
EmulatorConfig.IamServiceConfig iam = mock(EmulatorConfig.IamServiceConfig.class);
|
||||
@@ -108,6 +117,7 @@ class StsQueryHandlerTest {
|
||||
mock(SAMLTrustPolicyEvaluator.class),
|
||||
delegation,
|
||||
mock(CentralRootAccess.class),
|
||||
tokenIssuer,
|
||||
clock);
|
||||
}
|
||||
|
||||
@@ -143,6 +153,91 @@ class StsQueryHandlerTest {
|
||||
}
|
||||
}
|
||||
|
||||
/** The account's federation state with the feature on, which the operation reads the issuer from. */
|
||||
private static OutboundWebIdentityFederation enabledFederation() {
|
||||
OutboundWebIdentityFederation federation = new OutboundWebIdentityFederation();
|
||||
federation.setEnabled(true);
|
||||
federation.setIssuerIdentifier("https://sts.us-east-1.amazonaws.com/000000000000");
|
||||
return federation;
|
||||
}
|
||||
|
||||
/**
|
||||
* A caller on temporary credentials "cannot use this operation to extend the lifetime of a
|
||||
* session beyond what was granted when the session was originally created", so the ceiling on
|
||||
* a web identity token is the session's own expiration. The boundary is that instant itself: a
|
||||
* token ending exactly with the session is issued, and one ending a second later is not, which
|
||||
* is why the clock is fixed here rather than read. A long-term caller has no session to
|
||||
* escalate, so only the duration's own 3600 holds it.
|
||||
*/
|
||||
@ParameterizedTest
|
||||
@CsvSource({"ASIASESSION, 299, 200", "ASIASESSION, 300, 200", "ASIASESSION, 301, 403",
|
||||
"ASIASESSION, 3600, 403", "AKIALONGTERM, 3600, 200"})
|
||||
void aWebIdentityTokenCannotOutliveTheCallersSession(String accessKeyId, String duration,
|
||||
int expectedStatus) {
|
||||
Instant now = Instant.parse("2026-01-01T00:00:00Z");
|
||||
IamService iamService = mock(IamService.class);
|
||||
when(iamService.findEnabledOutboundWebIdentityFederation())
|
||||
.thenReturn(Optional.of(enabledFederation()));
|
||||
when(iamService.findSessionExpiration("ASIASESSION"))
|
||||
.thenReturn(Optional.of(now.plusSeconds(300)));
|
||||
WebIdentityTokenIssuer tokenIssuer = mock(WebIdentityTokenIssuer.class);
|
||||
when(tokenIssuer.mint(any(), anyString(), anyString(), anyList(), any(), any(), any()))
|
||||
.thenReturn("header.claims.signature");
|
||||
StsQueryHandler handler = newHandler(iamService, new RegionResolver(REGION, "000000000000"),
|
||||
Clock.fixed(now, ZoneOffset.UTC), mock(DelegationRequestService.class),
|
||||
tokenIssuer);
|
||||
setCaller(handler, accessKeyId, "-");
|
||||
|
||||
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
|
||||
params.putSingle("Audience.member.1", "app");
|
||||
params.putSingle("SigningAlgorithm", "RS256");
|
||||
params.putSingle("DurationSeconds", duration);
|
||||
Response response = handler.handle("GetWebIdentityToken", params);
|
||||
|
||||
String body = (String) response.getEntity();
|
||||
assertEquals(expectedStatus, response.getStatus(), body);
|
||||
if (expectedStatus == 403) {
|
||||
assertTrue(body.contains("<Code>SessionDurationEscalationException</Code>"), body);
|
||||
assertTrue(body.contains("You cannot use this operation to extend the lifetime of a"
|
||||
+ " session beyond what was granted when the session was originally created."),
|
||||
body);
|
||||
verifyNoInteractions(tokenIssuer);
|
||||
} else {
|
||||
verify(tokenIssuer).mint(any(), anyString(), anyString(), anyList(), any(), any(),
|
||||
any());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A temporary credential the session store no longer knows is refused as expired rather than
|
||||
* minted for. The lookup comes back empty for a session that has gone, which would otherwise
|
||||
* fall through to the account root ARN this file hands a caller it cannot resolve, and a
|
||||
* token's subject is signed and outlives the request that asked for it.
|
||||
*/
|
||||
@Test
|
||||
void aTemporaryCredentialWithNoLiveSessionIsRefusedRatherThanSignedAsRoot() {
|
||||
IamService iamService = mock(IamService.class);
|
||||
when(iamService.findEnabledOutboundWebIdentityFederation())
|
||||
.thenReturn(Optional.of(enabledFederation()));
|
||||
WebIdentityTokenIssuer tokenIssuer = mock(WebIdentityTokenIssuer.class);
|
||||
StsQueryHandler handler = newHandler(iamService, new RegionResolver(REGION, "000000000000"),
|
||||
Clock.fixed(Instant.parse("2026-01-01T00:00:00Z"), ZoneOffset.UTC),
|
||||
mock(DelegationRequestService.class), tokenIssuer);
|
||||
setCaller(handler, "ASIAGONE", "-");
|
||||
|
||||
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
|
||||
params.putSingle("Audience.member.1", "app");
|
||||
params.putSingle("SigningAlgorithm", "RS256");
|
||||
Response response = handler.handle("GetWebIdentityToken", params);
|
||||
|
||||
String body = (String) response.getEntity();
|
||||
assertEquals(403, response.getStatus(), body);
|
||||
assertTrue(body.contains("<Code>ExpiredTokenException</Code>"), body);
|
||||
assertTrue(body.contains("The security token included in the request has expired."), body);
|
||||
assertFalse(body.contains(":root"), body);
|
||||
verifyNoInteractions(tokenIssuer);
|
||||
}
|
||||
|
||||
private static void setCaller(StsQueryHandler handler, String headerKey, String queryKey) {
|
||||
handler.headers = mock(HttpHeaders.class);
|
||||
if (!"-".equals(headerKey)) {
|
||||
@@ -662,7 +757,8 @@ class StsQueryHandlerTest {
|
||||
StsQueryHandler handler = new StsQueryHandler(iamService, mock(AccountResolver.class),
|
||||
new RegionResolver(REGION, "000000000000"), config, mock(AssumeRolePolicyEvaluator.class),
|
||||
trust, verifier, keys, mock(SAMLProviderService.class), mock(SAMLTrustPolicyEvaluator.class),
|
||||
mock(DelegationRequestService.class), mock(CentralRootAccess.class));
|
||||
mock(DelegationRequestService.class), mock(CentralRootAccess.class),
|
||||
mock(WebIdentityTokenIssuer.class));
|
||||
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
|
||||
params.putSingle("RoleArn", requestedRoleArn);
|
||||
params.putSingle("RoleSessionName", "app");
|
||||
|
||||
+353
@@ -0,0 +1,353 @@
|
||||
package io.github.hectorvent.floci.services.iam;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.response.ExtractableResponse;
|
||||
import io.restassured.response.Response;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Base64;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.matchesPattern;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
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
|
||||
* 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
|
||||
* {@link WebIdentityTokenIssuerTest}, which reaches the key through the store.
|
||||
*
|
||||
* <p>The feature switch is account-level and shared, so each test sets the state it needs first.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class WebIdentityTokenIntegrationTest {
|
||||
|
||||
private static final String IAM_AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20261025/us-east-1/iam/aws4_request";
|
||||
private static final String STS_AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20261025/us-east-1/sts/aws4_request";
|
||||
|
||||
private static final String TOKEN =
|
||||
"GetWebIdentityTokenResponse.GetWebIdentityTokenResult.WebIdentityToken";
|
||||
private static final String EXPIRATION =
|
||||
"GetWebIdentityTokenResponse.GetWebIdentityTokenResult.Expiration";
|
||||
/** A violation is read off the message rather than the body, which escapes its quotes. */
|
||||
private static final String CODE = "ErrorResponse.Error.Code";
|
||||
private static final String MESSAGE = "ErrorResponse.Error.Message";
|
||||
private static final String ISSUER = "GetOutboundWebIdentityFederationInfoResponse"
|
||||
+ ".GetOutboundWebIdentityFederationInfoResult.IssuerIdentifier";
|
||||
/** The namespace the IAM User Guide nests the identity claims and the request's tags under. */
|
||||
private static final String CLAIM_NAMESPACE = "https://sts.amazonaws.com/";
|
||||
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
private static RequestSpecification iam(String action) {
|
||||
return given().header("Authorization", IAM_AUTH).formParam("Action", action);
|
||||
}
|
||||
|
||||
private static RequestSpecification sts(String action) {
|
||||
return given().header("Authorization", STS_AUTH).formParam("Action", action);
|
||||
}
|
||||
|
||||
/** One audience and RS256, which is the shape the Reference's own sample request sends. */
|
||||
private static RequestSpecification token(String algorithm) {
|
||||
return sts("GetWebIdentityToken")
|
||||
.formParam("Audience.member.1", "app")
|
||||
.formParam("SigningAlgorithm", algorithm);
|
||||
}
|
||||
|
||||
/** The same request, signed as the session {@code GetSessionToken} handed out. */
|
||||
private static RequestSpecification session(String accessKeyId) {
|
||||
return given()
|
||||
.header("Authorization", "AWS4-HMAC-SHA256 Credential=" + accessKeyId
|
||||
+ "/20261025/us-east-1/sts/aws4_request")
|
||||
.formParam("Action", "GetWebIdentityToken")
|
||||
.formParam("Audience.member.1", "app")
|
||||
.formParam("SigningAlgorithm", "RS256");
|
||||
}
|
||||
|
||||
/** Enables the feature if it is off, and answers with the account's issuer either way. */
|
||||
private static String enabledIssuer() {
|
||||
iam("EnableOutboundWebIdentityFederation").when().post("/");
|
||||
return iam("GetOutboundWebIdentityFederationInfo")
|
||||
.when().post("/").then().statusCode(200).extract().path(ISSUER);
|
||||
}
|
||||
|
||||
private static void disableFederation() {
|
||||
iam("DisableOutboundWebIdentityFederation").when().post("/");
|
||||
}
|
||||
|
||||
private static JsonNode part(String jwt, int index) throws Exception {
|
||||
return MAPPER.readTree(Base64.getUrlDecoder().decode(jwt.split("\\.", -1)[index]));
|
||||
}
|
||||
|
||||
private static byte[] signature(String jwt) {
|
||||
return Base64.getUrlDecoder().decode(jwt.split("\\.", -1)[2]);
|
||||
}
|
||||
|
||||
/**
|
||||
* "The token contains standard JWT claims such as subject, audience, expiration time", the
|
||||
* audience being the one the request named, and the issuer the one IAM minted for the account.
|
||||
* The default duration is 300 seconds, and {@code Expiration} names the same instant as
|
||||
* {@code exp}. Beside them sit the identity claims the guide nests under its own namespace,
|
||||
* the account the token was asked for and the region it was asked from, and no
|
||||
* {@code request_tags} where the request named no tags.
|
||||
*/
|
||||
@Test
|
||||
void aTokenCarriesTheStandardClaimsAndTheAccountsIssuer() throws Exception {
|
||||
String issuer = enabledIssuer();
|
||||
|
||||
String jwt = token("RS256").when().post("/").then().statusCode(200)
|
||||
.body(EXPIRATION, matchesPattern("\\d{4}-\\d{2}-\\d{2}T.*Z"))
|
||||
.extract().path(TOKEN);
|
||||
|
||||
JsonNode header = part(jwt, 0);
|
||||
assertEquals("RS256", header.path("alg").asText());
|
||||
assertEquals("JWT", header.path("typ").asText());
|
||||
assertTrue(header.path("kid").asText().matches("[0-9a-f]{32}"), header.toString());
|
||||
|
||||
JsonNode claims = part(jwt, 1);
|
||||
assertEquals(issuer, claims.path("iss").asText());
|
||||
assertEquals(1, claims.path("aud").size(), claims.toString());
|
||||
assertEquals("app", claims.path("aud").get(0).asText());
|
||||
assertTrue(claims.path("sub").asText().matches("arn:aws[a-z-]*:iam::\\d{12}:.+"),
|
||||
claims.toString());
|
||||
assertEquals(300, claims.path("exp").asLong() - claims.path("iat").asLong());
|
||||
assertNotNull(claims.path("jti").asText());
|
||||
assertEquals(256, signature(jwt).length, "RS256 signs with the 2048-bit account key");
|
||||
|
||||
JsonNode identity = claims.path(CLAIM_NAMESPACE);
|
||||
assertTrue(identity.path("aws_account").asText().matches("\\d{12}"), claims.toString());
|
||||
assertEquals("us-east-1", identity.path("source_region").asText(), claims.toString());
|
||||
assertTrue(identity.path("request_tags").isMissingNode(),
|
||||
"a request that named no tags carries no request_tags claim");
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code ES384} is "ECDSA using P-384 curve with SHA-384", and JWS defines that signature as
|
||||
* the raw {@code R || S} pair: two 48-byte halves for P-384. A DER sequence would be close to
|
||||
* this length and would verify nowhere.
|
||||
*/
|
||||
@Test
|
||||
void anEs384TokenSignsWithTheRawPairJwsDefines() throws Exception {
|
||||
enabledIssuer();
|
||||
|
||||
String jwt = token("ES384").when().post("/").then().statusCode(200).extract().path(TOKEN);
|
||||
|
||||
assertEquals("ES384", part(jwt, 0).path("alg").asText());
|
||||
assertEquals(96, signature(jwt).length, "ES384 is R || S over P-384, not DER");
|
||||
}
|
||||
|
||||
/**
|
||||
* Request tags "appear under the request_tags field in the token", which the guide nests under
|
||||
* the same namespace as the identity claims. That nesting is also what keeps a tag named after
|
||||
* a claim STS sets out of it: such a tag is a key under {@code request_tags}, so it cannot
|
||||
* lengthen the token's own life.
|
||||
*/
|
||||
@Test
|
||||
void tagsBecomeRequestTagsUnderTheNamespaceRatherThanClaimsOfTheirOwn() throws Exception {
|
||||
enabledIssuer();
|
||||
|
||||
String jwt = token("RS256")
|
||||
.formParam("Tags.member.1.Key", "Team")
|
||||
.formParam("Tags.member.1.Value", "platform")
|
||||
.formParam("Tags.member.2.Key", "exp")
|
||||
.formParam("Tags.member.2.Value", "99999999999")
|
||||
.when().post("/").then().statusCode(200).extract().path(TOKEN);
|
||||
|
||||
JsonNode claims = part(jwt, 1);
|
||||
JsonNode requestTags = claims.path(CLAIM_NAMESPACE).path("request_tags");
|
||||
assertEquals("platform", requestTags.path("Team").asText(), claims.toString());
|
||||
assertEquals("99999999999", requestTags.path("exp").asText(),
|
||||
"a tag named after a claim is a request tag, not that claim");
|
||||
assertTrue(claims.path("Team").isMissingNode(), "a tag is not a claim of its own");
|
||||
assertEquals(300, claims.path("exp").asLong() - claims.path("iat").asLong(),
|
||||
"the request's own exp tag does not become the expiry");
|
||||
}
|
||||
|
||||
/**
|
||||
* The duration is 60 to 3600, and {@code Expiration} is "determined by adding the
|
||||
* DurationSeconds value to the time the token was issued".
|
||||
*/
|
||||
@Test
|
||||
void theDurationIsHeldToItsRangeAndSetsTheExpiry() throws Exception {
|
||||
enabledIssuer();
|
||||
|
||||
ExtractableResponse<Response> issued = token("RS256").formParam("DurationSeconds", "3600")
|
||||
.when().post("/").then().statusCode(200).extract();
|
||||
JsonNode claims = part(issued.path(TOKEN), 1);
|
||||
assertEquals(3600, claims.path("exp").asLong() - claims.path("iat").asLong());
|
||||
assertEquals(claims.path("exp").asLong(),
|
||||
Instant.parse(issued.path(EXPIRATION)).getEpochSecond(),
|
||||
"Expiration names the instant the exp claim does");
|
||||
|
||||
token("RS256").formParam("DurationSeconds", "59").when().post("/").then().statusCode(400)
|
||||
.body(containsString("ValidationError"))
|
||||
.body(containsString("Member must have value greater than or equal to 60"));
|
||||
token("RS256").formParam("DurationSeconds", "3601").when().post("/").then().statusCode(400)
|
||||
.body(containsString("Member must have value less than or equal to 3600"));
|
||||
}
|
||||
|
||||
/** The feature's own refusal, which is not IAM's {@code FeatureDisabled} 404. */
|
||||
@Test
|
||||
void theSwitchBeingOffIsTheOperationsOwnRefusal() {
|
||||
disableFederation();
|
||||
|
||||
token("RS256").when().post("/").then().statusCode(403)
|
||||
.body(CODE, equalTo("OutboundWebIdentityFederationDisabledException"))
|
||||
.body(MESSAGE, containsString("The outbound web identity federation feature is not"
|
||||
+ " enabled for this account."))
|
||||
.body(not(containsString("FeatureDisabled")));
|
||||
|
||||
enabledIssuer();
|
||||
}
|
||||
|
||||
/**
|
||||
* The validation layer runs ahead of the operation, so a request that breaks a declared
|
||||
* constraint is the 400 even where the feature the operation reads is off.
|
||||
*/
|
||||
@Test
|
||||
void theDeclaredConstraintsAreReadAheadOfTheSwitch() {
|
||||
disableFederation();
|
||||
|
||||
sts("GetWebIdentityToken").formParam("SigningAlgorithm", "RS256")
|
||||
.when().post("/").then().statusCode(400)
|
||||
.body(CODE, equalTo("ValidationError"))
|
||||
.body(MESSAGE, equalTo("1 validation error detected: Value null at 'audience' failed"
|
||||
+ " to satisfy constraint: Member must not be null"))
|
||||
.body(not(containsString("OutboundWebIdentityFederationDisabled")));
|
||||
|
||||
enabledIssuer();
|
||||
}
|
||||
|
||||
/**
|
||||
* Both required members are reported together when both are absent, and a member sent empty is
|
||||
* a member that is present, so it breaks the minimum length of 1 rather than reading as absent.
|
||||
*/
|
||||
@Test
|
||||
void theRequiredMembersAndTheirBoundsAreReportedTogether() {
|
||||
enabledIssuer();
|
||||
|
||||
sts("GetWebIdentityToken").when().post("/").then().statusCode(400)
|
||||
.body(MESSAGE, equalTo("2 validation errors detected: Value null at 'audience' failed"
|
||||
+ " to satisfy constraint: Member must not be null; Value null at"
|
||||
+ " 'signingAlgorithm' failed to satisfy constraint: Member must not be"
|
||||
+ " null"));
|
||||
|
||||
sts("GetWebIdentityToken")
|
||||
.formParam("Audience.member.1", "")
|
||||
.formParam("SigningAlgorithm", "RS256")
|
||||
.when().post("/").then().statusCode(400)
|
||||
.body(MESSAGE, containsString("Value '' at 'audience.1.member' failed to satisfy"
|
||||
+ " constraint: Member must have length greater than or equal to 1"));
|
||||
|
||||
RequestSpecification eleven = sts("GetWebIdentityToken")
|
||||
.formParam("SigningAlgorithm", "RS256");
|
||||
for (int audience = 1; audience <= 11; audience++) {
|
||||
eleven.formParam("Audience.member." + audience, "app" + audience);
|
||||
}
|
||||
eleven.when().post("/").then().statusCode(400)
|
||||
.body(MESSAGE, containsString("Value at 'audience' failed to satisfy constraint:"
|
||||
+ " Member must have length less than or equal to 10"));
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code jwtAlgorithmType} publishes a fixed length of 5 and no enum, so the length is the
|
||||
* declared constraint and the two values the Reference names are read from it.
|
||||
*/
|
||||
@Test
|
||||
void aSigningAlgorithmIsHeldToItsLengthAndThenToTheTwoValues() {
|
||||
enabledIssuer();
|
||||
|
||||
token("RS25").when().post("/").then().statusCode(400)
|
||||
.body(MESSAGE, containsString("Value 'RS25' at 'signingAlgorithm' failed to satisfy"
|
||||
+ " constraint: Member must have length greater than or equal to 5"));
|
||||
|
||||
token("HS256").when().post("/").then().statusCode(400)
|
||||
.body(MESSAGE, containsString("Value 'HS256' at 'signingAlgorithm' failed to satisfy"
|
||||
+ " constraint: Member must satisfy enum value set: [RS256, ES384]"));
|
||||
}
|
||||
|
||||
/**
|
||||
* The session ceiling against a real session rather than a stubbed one: {@code GetSessionToken}
|
||||
* hands out credentials that expire, and a token asked for past that instant is refused.
|
||||
* {@code StsQueryHandlerTest} holds the boundary itself on a fixed clock; what this adds is
|
||||
* that the expiration is found through the session the caller is actually on.
|
||||
*/
|
||||
@Test
|
||||
void aTokenIsRefusedWhereItWouldOutliveTheCallersOwnSession() throws Exception {
|
||||
enabledIssuer();
|
||||
String sessionKey = sts("GetSessionToken").formParam("DurationSeconds", "900")
|
||||
.when().post("/").then().statusCode(200)
|
||||
.extract().path("GetSessionTokenResponse.GetSessionTokenResult.Credentials.AccessKeyId");
|
||||
|
||||
session(sessionKey).formParam("DurationSeconds", "3600")
|
||||
.when().post("/").then().statusCode(403)
|
||||
.body(CODE, equalTo("SessionDurationEscalationException"))
|
||||
.body(MESSAGE, containsString("You cannot use this operation to extend the lifetime"
|
||||
+ " of a session beyond what was granted when the session was originally"
|
||||
+ " created."));
|
||||
|
||||
String jwt = session(sessionKey).formParam("DurationSeconds", "60")
|
||||
.when().post("/").then().statusCode(200).extract().path(TOKEN);
|
||||
JsonNode claims = part(jwt, 1);
|
||||
assertEquals(60, claims.path("exp").asLong() - claims.path("iat").asLong(),
|
||||
"a token inside the session is issued for what it asked for");
|
||||
}
|
||||
|
||||
/**
|
||||
* The same refusal over the wire for a session key nothing issued, which reaches the operation
|
||||
* because enforcement is off here: no token is minted, and none names the account root.
|
||||
*/
|
||||
@Test
|
||||
void aSessionKeyWithNoSessionBehindItIsRefusedAsExpired() {
|
||||
enabledIssuer();
|
||||
|
||||
session("ASIANOSUCHSESSION001").when().post("/").then().statusCode(403)
|
||||
.body(CODE, equalTo("ExpiredTokenException"))
|
||||
.body(MESSAGE, equalTo("The security token included in the request has expired."))
|
||||
.body(not(containsString(":root")));
|
||||
}
|
||||
|
||||
/** A {@code Tag} declares its key and its value required, and each carries its own shape. */
|
||||
@Test
|
||||
void aTagIsHeldToItsOwnMembers() {
|
||||
enabledIssuer();
|
||||
|
||||
token("RS256").formParam("Tags.member.1.Key", "Team")
|
||||
.when().post("/").then().statusCode(400)
|
||||
.body(MESSAGE, containsString("Value null at 'tags.1.member.value' failed to satisfy"
|
||||
+ " constraint: Member must not be null"));
|
||||
|
||||
token("RS256")
|
||||
.formParam("Tags.member.1.Key", "Team?")
|
||||
.formParam("Tags.member.1.Value", "platform")
|
||||
.when().post("/").then().statusCode(400)
|
||||
.body(MESSAGE, containsString("at 'tags.1.member.key' failed to satisfy constraint:"
|
||||
+ " Member must satisfy regular expression pattern"));
|
||||
|
||||
RequestSpecification fiftyOne = token("RS256");
|
||||
for (int tag = 1; tag <= 51; tag++) {
|
||||
fiftyOne.formParam("Tags.member." + tag + ".Key", "Key" + tag)
|
||||
.formParam("Tags.member." + tag + ".Value", "value" + tag);
|
||||
}
|
||||
fiftyOne.when().post("/").then().statusCode(400)
|
||||
.body(MESSAGE, containsString("Value at 'tags' failed to satisfy constraint: Member"
|
||||
+ " must have length less than or equal to 50"));
|
||||
}
|
||||
}
|
||||
+145
@@ -0,0 +1,145 @@
|
||||
package io.github.hectorvent.floci.services.iam;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.services.iam.model.WebIdentityTokenKey;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.EnumSource;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.KeyFactory;
|
||||
import java.security.PublicKey;
|
||||
import java.security.Signature;
|
||||
import java.security.spec.X509EncodedKeySpec;
|
||||
import java.time.Instant;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
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.
|
||||
*
|
||||
* <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
|
||||
* stopped being the raw {@code R || S} pair JWS defines would fail this verifier rather than
|
||||
* follow the change into it.
|
||||
*/
|
||||
class WebIdentityTokenIssuerTest {
|
||||
|
||||
private static final String ISSUER = "https://sts.us-east-1.amazonaws.com/000000000000";
|
||||
private static final String SUBJECT = "arn:aws:iam::000000000000:user/token-holder";
|
||||
private static final Instant ISSUED_AT = Instant.parse("2026-01-01T00:00:00Z");
|
||||
private static final WebIdentityTokenIssuer.CustomClaims CUSTOM_CLAIMS =
|
||||
new WebIdentityTokenIssuer.CustomClaims("000000000000", "us-east-1", Map.of());
|
||||
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
private StorageBackend<String, WebIdentityTokenKey> keyStore;
|
||||
private WebIdentityTokenIssuer issuer;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
keyStore = new InMemoryStorage<>();
|
||||
issuer = new WebIdentityTokenIssuer(keyStore, MAPPER);
|
||||
}
|
||||
|
||||
private String mint(WebIdentityTokenIssuer.Algorithm algorithm, long seconds) {
|
||||
return issuer.mint(algorithm, ISSUER, SUBJECT, List.of("app"), CUSTOM_CLAIMS,
|
||||
ISSUED_AT, ISSUED_AT.plusSeconds(seconds));
|
||||
}
|
||||
|
||||
private static String segment(String jwt, int index) {
|
||||
return jwt.split("\\.", -1)[index];
|
||||
}
|
||||
|
||||
private static String signingInput(String jwt) {
|
||||
return jwt.substring(0, jwt.lastIndexOf('.'));
|
||||
}
|
||||
|
||||
private static byte[] signature(String jwt) {
|
||||
return Base64.getUrlDecoder().decode(segment(jwt, 2));
|
||||
}
|
||||
|
||||
private static String keyId(String jwt) throws Exception {
|
||||
return MAPPER.readTree(Base64.getUrlDecoder().decode(segment(jwt, 0)))
|
||||
.path("kid").asText();
|
||||
}
|
||||
|
||||
private static String keyAlgorithm(WebIdentityTokenIssuer.Algorithm algorithm) {
|
||||
return algorithm == WebIdentityTokenIssuer.Algorithm.RS256 ? "RSA" : "EC";
|
||||
}
|
||||
|
||||
private static String signatureAlgorithm(WebIdentityTokenIssuer.Algorithm algorithm) {
|
||||
return algorithm == WebIdentityTokenIssuer.Algorithm.RS256
|
||||
? "SHA256withRSA"
|
||||
: "SHA384withECDSAinP1363Format";
|
||||
}
|
||||
|
||||
/** Verifies a signature over the bytes given, against the stored public half of the key. */
|
||||
private boolean verifies(WebIdentityTokenIssuer.Algorithm algorithm, String signingInput,
|
||||
byte[] signature) throws Exception {
|
||||
WebIdentityTokenKey key = keyStore.get(algorithm.name()).orElseThrow();
|
||||
PublicKey publicKey = KeyFactory.getInstance(keyAlgorithm(algorithm)).generatePublic(
|
||||
new X509EncodedKeySpec(Base64.getDecoder().decode(key.getPublicKey())));
|
||||
Signature verifier = Signature.getInstance(signatureAlgorithm(algorithm));
|
||||
verifier.initVerify(publicKey);
|
||||
verifier.update(signingInput.getBytes(StandardCharsets.US_ASCII));
|
||||
return verifier.verify(signature);
|
||||
}
|
||||
|
||||
/** The token is signed over its own header and claims by the key stored for its algorithm. */
|
||||
@ParameterizedTest
|
||||
@EnumSource(WebIdentityTokenIssuer.Algorithm.class)
|
||||
void aTokenVerifiesAgainstTheKeyTheIssuerStored(WebIdentityTokenIssuer.Algorithm algorithm)
|
||||
throws Exception {
|
||||
String jwt = mint(algorithm, 300);
|
||||
|
||||
assertTrue(verifies(algorithm, signingInput(jwt), signature(jwt)),
|
||||
algorithm + " must verify against the key the issuer stored");
|
||||
}
|
||||
|
||||
/**
|
||||
* The signature covers the claims it was made over, so one token's signature does not carry
|
||||
* another's claim set. A signature of the right length but over the wrong bytes passes a
|
||||
* length check and fails here.
|
||||
*/
|
||||
@ParameterizedTest
|
||||
@EnumSource(WebIdentityTokenIssuer.Algorithm.class)
|
||||
void aSignatureDoesNotCoverAnotherTokensClaims(WebIdentityTokenIssuer.Algorithm algorithm)
|
||||
throws Exception {
|
||||
String jwt = mint(algorithm, 300);
|
||||
String longer = mint(algorithm, 3600);
|
||||
assertNotEquals(segment(jwt, 1), segment(longer, 1));
|
||||
|
||||
String swapped = segment(jwt, 0) + "." + segment(longer, 1);
|
||||
|
||||
assertFalse(verifies(algorithm, swapped, signature(jwt)),
|
||||
algorithm + " must not verify a claim set it did not sign");
|
||||
}
|
||||
|
||||
/**
|
||||
* One key per algorithm, minted on first use and stored rather than held in memory, so a
|
||||
* restart does not invalidate a token already handed out.
|
||||
*/
|
||||
@Test
|
||||
void theKeyIsMintedOncePerAlgorithmAndStored() throws Exception {
|
||||
String first = mint(WebIdentityTokenIssuer.Algorithm.RS256, 300);
|
||||
String second = mint(WebIdentityTokenIssuer.Algorithm.RS256, 300);
|
||||
String other = mint(WebIdentityTokenIssuer.Algorithm.ES384, 300);
|
||||
|
||||
assertEquals(keyId(first), keyId(second));
|
||||
assertNotEquals(keyId(first), keyId(other));
|
||||
assertEquals(keyId(first), keyStore.get("RS256").orElseThrow().getKeyId());
|
||||
assertEquals(keyId(other), keyStore.get("ES384").orElseThrow().getKeyId());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user