fix(eks): validate IAM authentication tokens (#2912)

Reject forged, expired, and cross-cluster EKS authentication tokens before granting cluster-admin access.
This commit is contained in:
Simone Primarosa authored and GitHub committed 2026-09-02 19:37:26 -04:00
1 parent 3d2b8828ad
commit 309043baf6
18 files changed
+739 -66

No files matched your search

@@ -138,9 +138,10 @@ public class EksClusterManager {
// Wire a token-authentication webhook so `aws eks get-token` bearer tokens are validated by
// Floci and mapped to cluster-admin. The k3s API server POSTs a TokenReview to Floci's
// _floci/eks/token-webhook endpoint. The kubeconfig is copied into the container via the
// Docker API after create and before start (below) — not bind-mounted — so it works the same
// natively and in Docker-in-Docker, with no host-path / host-persistent-path requirement.
// _floci/eks/clusters/<cluster-name>/token-webhook endpoint. The kubeconfig is copied into
// the container via the Docker API after create and before start (below), not bind-mounted,
// so it works the same natively and in Docker-in-Docker, with no host-path /
// host-persistent-path requirement.
String webhookLocalFile = null;
if (config.services().eks().iamAuthWebhook()) {
webhookLocalFile = writeWebhookKubeconfig(cluster.getName());
@@ -495,7 +496,7 @@ public class EksClusterManager {
.toAbsolutePath().normalize();
try {
Files.createDirectories(localFile.getParent());
Files.writeString(localFile, buildWebhookKubeconfig(webhookUrl()));
Files.writeString(localFile, buildWebhookKubeconfig(webhookUrl(clusterName)));
} catch (IOException e) {
LOG.warnv("EKS token-webhook disabled for cluster {0}: could not write kubeconfig: {1}",
clusterName, e.getMessage());
@@ -617,8 +618,12 @@ public class EksClusterManager {
}
/** The Floci token-webhook URL as reachable from inside the k3s container. */
String webhookUrl() {
return "http://" + dockerHostResolver.resolve() + ":" + config.port() + "/_floci/eks/token-webhook";
String webhookUrl(String clusterName) {
return "http://" + dockerHostResolver.resolve() + ":" + config.port() + webhookPath(clusterName);
}
static String webhookPath(String clusterName) {
return "/_floci/eks/clusters/" + clusterName + "/token-webhook";
}
/**
@@ -0,0 +1,241 @@
package io.github.hectorvent.floci.services.eks;
import io.github.hectorvent.floci.services.iam.IamService;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URI;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Base64;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
/**
* Validates the SigV4-presigned STS request embedded in an EKS IAM bearer token.
*/
@ApplicationScoped
class EksTokenValidator {
private static final Logger LOG = Logger.getLogger(EksTokenValidator.class);
private static final String TOKEN_PREFIX = "k8s-aws-v1.";
private static final String ALGORITHM = "AWS4-HMAC-SHA256";
private static final String EMPTY_PAYLOAD_SHA256 =
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
private static final String REQUIRED_SIGNED_HEADERS = "host;x-k8s-aws-id";
private static final int MAX_PRESIGN_EXPIRY_SECONDS = 60;
private static final int MAX_TOKEN_LENGTH = 4096;
private static final Duration MAX_FUTURE_SKEW = Duration.ofMinutes(5);
private static final DateTimeFormatter DATETIME_FORMAT =
DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'").withZone(ZoneOffset.UTC);
private final IamService iamService;
private final Clock clock;
@Inject
EksTokenValidator(IamService iamService) {
this(iamService, Clock.systemUTC());
}
EksTokenValidator(IamService iamService, Clock clock) {
this.iamService = iamService;
this.clock = clock;
}
boolean validate(String token, String clusterName) {
if (token == null || clusterName == null || clusterName.isBlank() || token.length() > MAX_TOKEN_LENGTH) {
return false;
}
try {
URI request = parseToken(token);
if (request == null) {
return false;
}
Map<String, String> parameters = parseQuery(request.getRawQuery());
if (!hasExpectedRequestShape(request, parameters)) {
return false;
}
CredentialScope scope = parseCredentialScope(parameters.get("X-Amz-Credential"));
Instant signedAt = Instant.from(DATETIME_FORMAT.parse(parameters.get("X-Amz-Date")));
if (!isCurrent(signedAt, parameters.get("X-Amz-Expires"))
|| !scope.date().equals(parameters.get("X-Amz-Date").substring(0, 8))) {
return false;
}
String secretKey = secretKey(scope.accessKeyId(), parameters.get("X-Amz-Security-Token"));
if (secretKey == null) {
return false;
}
String canonicalRequest = canonicalRequest(request, parameters, clusterName);
String stringToSign = ALGORITHM + "\n"
+ parameters.get("X-Amz-Date") + "\n"
+ scope.value() + "\n"
+ sha256Hex(canonicalRequest);
String expectedSignature = hexEncode(hmacSha256(
deriveSigningKey(secretKey, scope.date(), scope.region(), scope.service()), stringToSign));
return MessageDigest.isEqual(
expectedSignature.getBytes(StandardCharsets.UTF_8),
parameters.get("X-Amz-Signature").getBytes(StandardCharsets.UTF_8));
} catch (Exception exception) {
LOG.debugv("EKS IAM token validation rejected a malformed token: {0}", exception.getMessage());
return false;
}
}
private URI parseToken(String token) {
if (!token.startsWith(TOKEN_PREFIX)) {
return null;
}
String encodedRequest = token.substring(TOKEN_PREFIX.length());
if (encodedRequest.isBlank()) {
return null;
}
String decodedRequest = new String(Base64.getUrlDecoder().decode(encodedRequest), StandardCharsets.UTF_8);
URI request = URI.create(decodedRequest);
if (!"http".equals(request.getScheme()) && !"https".equals(request.getScheme())) {
return null;
}
if (request.getHost() == null || request.getRawAuthority() == null || request.getUserInfo() != null
|| request.getRawFragment() != null || !"/".equals(request.getRawPath())) {
return null;
}
return request;
}
private static boolean hasExpectedRequestShape(URI request, Map<String, String> parameters) {
return request.getRawQuery() != null
&& "GetCallerIdentity".equals(parameters.get("Action"))
&& "2011-06-15".equals(parameters.get("Version"))
&& ALGORITHM.equals(parameters.get("X-Amz-Algorithm"))
&& REQUIRED_SIGNED_HEADERS.equals(parameters.get("X-Amz-SignedHeaders"))
&& parameters.containsKey("X-Amz-Credential")
&& parameters.containsKey("X-Amz-Date")
&& parameters.containsKey("X-Amz-Expires")
&& parameters.containsKey("X-Amz-Signature");
}
private static Map<String, String> parseQuery(String rawQuery) {
Map<String, String> parameters = new HashMap<>();
for (String pair : rawQuery.split("&", -1)) {
int delimiter = pair.indexOf('=');
if (delimiter <= 0) {
throw new IllegalArgumentException("query parameter has no value");
}
String name = decode(pair.substring(0, delimiter));
String value = decode(pair.substring(delimiter + 1));
if (parameters.putIfAbsent(name, value) != null) {
throw new IllegalArgumentException("query parameter appears more than once");
}
}
return parameters;
}
private boolean isCurrent(Instant signedAt, String expiryText) {
int expirySeconds = Integer.parseInt(expiryText);
if (expirySeconds <= 0 || expirySeconds > MAX_PRESIGN_EXPIRY_SECONDS) {
return false;
}
Instant now = clock.instant();
return !signedAt.isAfter(now.plus(MAX_FUTURE_SKEW)) && !now.isAfter(signedAt.plusSeconds(expirySeconds));
}
private String secretKey(String accessKeyId, String sessionToken) {
if (iamService.isSeededDeployerAccessKey(accessKeyId)) {
return null;
}
Optional<String> secretKey = iamService.findSecretKey(accessKeyId, sessionToken);
return secretKey.orElse(null);
}
private static CredentialScope parseCredentialScope(String encodedCredential) {
String[] parts = encodedCredential.split("/", -1);
if (parts.length != 5 || parts[0].isBlank() || !parts[1].matches("[0-9]{8}")
|| parts[2].isBlank() || !"sts".equals(parts[3]) || !"aws4_request".equals(parts[4])) {
throw new IllegalArgumentException("invalid credential scope");
}
return new CredentialScope(parts[0], parts[1], parts[2], parts[3]);
}
private static String canonicalRequest(URI request, Map<String, String> parameters, String clusterName) {
String canonicalQuery = parameters.entrySet().stream()
.filter(parameter -> !"X-Amz-Signature".equals(parameter.getKey()))
.map(parameter -> awsEncode(parameter.getKey()) + "=" + awsEncode(parameter.getValue()))
.sorted(Comparator.naturalOrder())
.reduce((left, right) -> left + "&" + right)
.orElse("");
String authority = request.getRawAuthority().toLowerCase(Locale.ROOT);
return "GET\n/\n"
+ canonicalQuery + "\n"
+ "host:" + authority + "\n"
+ "x-k8s-aws-id:" + clusterName + "\n\n"
+ REQUIRED_SIGNED_HEADERS + "\n"
+ EMPTY_PAYLOAD_SHA256;
}
private static String decode(String value) {
return URLDecoder.decode(value.replace("+", "%2B"), StandardCharsets.UTF_8);
}
private static String awsEncode(String value) {
StringBuilder encoded = new StringBuilder();
for (byte valueByte : value.getBytes(StandardCharsets.UTF_8)) {
int unsigned = Byte.toUnsignedInt(valueByte);
if ((unsigned >= 'A' && unsigned <= 'Z') || (unsigned >= 'a' && unsigned <= 'z')
|| (unsigned >= '0' && unsigned <= '9') || unsigned == '-' || unsigned == '_'
|| unsigned == '.' || unsigned == '~') {
encoded.append((char) unsigned);
} else {
encoded.append('%').append(String.format("%02X", unsigned));
}
}
return encoded.toString();
}
private static byte[] deriveSigningKey(String secretKey, String date, String region, String service)
throws Exception {
byte[] dateKey = hmacSha256(("AWS4" + secretKey).getBytes(StandardCharsets.UTF_8), date);
byte[] regionKey = hmacSha256(dateKey, region);
byte[] serviceKey = hmacSha256(regionKey, service);
return hmacSha256(serviceKey, "aws4_request");
}
private static byte[] hmacSha256(byte[] key, String data) throws Exception {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(key, "HmacSHA256"));
return mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
}
private static String sha256Hex(String input) throws Exception {
return hexEncode(MessageDigest.getInstance("SHA-256").digest(input.getBytes(StandardCharsets.UTF_8)));
}
private static String hexEncode(byte[] bytes) {
StringBuilder encoded = new StringBuilder(bytes.length * 2);
for (byte value : bytes) {
encoded.append(String.format("%02x", value));
}
return encoded.toString();
}
private record CredentialScope(String accessKeyId, String date, String region, String service) {
private String value() {
return date + "/" + region + "/" + service + "/aws4_request";
}
}
}
@@ -1,9 +1,11 @@
package io.github.hectorvent.floci.services.eks;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
@@ -16,35 +18,40 @@ import java.util.Map;
* Kubernetes token-authentication webhook for k3s-backed EKS clusters.
*
* <p>The k3s API server is configured (see {@code EksClusterManager}) to POST a
* {@code TokenReview} here whenever it receives a bearer token it does not recognise — notably the
* {@code k8s-aws-v1.<presigned-sts-url>} token produced by {@code aws eks get-token}. Floci accepts
* the token and maps it to the {@code system:masters} group, which is bound to {@code cluster-admin}
* by default. This is what makes the native {@code aws eks update-kubeconfig} + {@code kubectl}
* workflow authenticate against a Floci EKS cluster.
* {@code TokenReview} here whenever it receives a bearer token it does not recognise, notably the
* {@code k8s-aws-v1.<presigned-sts-url>} token produced by {@code aws eks get-token}. Floci validates
* the request signature, expiration, and signed cluster ID before mapping the token to the
* {@code system:masters} group, which is bound to {@code cluster-admin} by default.
*
* <p>This is Floci plumbing under the {@code _floci/...} namespace, not an AWS API.
*/
@ApplicationScoped
@Path("_floci/eks/token-webhook")
@Path("_floci/eks/clusters/{clusterName}/token-webhook")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class EksTokenWebhookController {
private static final Logger LOG = Logger.getLogger(EksTokenWebhookController.class);
private static final String EKS_TOKEN_PREFIX = "k8s-aws-v1.";
private final EksTokenValidator tokenValidator;
@Inject
public EksTokenWebhookController(EksTokenValidator tokenValidator) {
this.tokenValidator = tokenValidator;
}
@POST
public Response review(Map<String, Object> tokenReview) {
public Response review(@PathParam("clusterName") String clusterName, Map<String, Object> tokenReview) {
// The response apiVersion MUST match the request's (the kube-apiserver sends v1beta1 by
// default and cannot convert a v1 response back). Echo whatever the apiserver sent.
String apiVersion = tokenReview != null && tokenReview.get("apiVersion") instanceof String v
? v : "authentication.k8s.io/v1";
String token = extractToken(tokenReview);
boolean authenticated = token != null && token.startsWith(EKS_TOKEN_PREFIX);
boolean authenticated = tokenValidator.validate(token, clusterName);
if (authenticated) {
LOG.debug("EKS token-webhook: authenticated aws-iam token as cluster-admin");
LOG.debugv("EKS token-webhook: authenticated aws-iam token for cluster {0} as cluster-admin",
clusterName);
return Response.ok(Map.of(
"apiVersion", apiVersion,
"kind", "TokenReview",
@@ -56,7 +63,7 @@ public class EksTokenWebhookController {
"groups", List.of("system:masters"))))).build();
}
LOG.debug("EKS token-webhook: rejecting unrecognised token");
LOG.debugv("EKS token-webhook: rejected aws-iam token for cluster {0}", clusterName);
return Response.ok(Map.of(
"apiVersion", apiVersion,
"kind", "TokenReview",
@@ -31,6 +31,8 @@ import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.time.Instant;
import java.util.Optional;
import java.util.Set;
@@ -1810,12 +1812,42 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
// Internal helpers
// =========================================================================
/** Returns the secret for an active access key or an unexpired temporary session. */
public Optional<String> findSecretKey(String accessKeyId) {
Optional<String> fromAccessKey = accessKeys.get(accessKeyId).map(AccessKey::getSecretAccessKey);
if (fromAccessKey.isPresent()) {
return fromAccessKey;
return activeAccessKeySecret(accessKeyId)
.or(() -> currentSession(accessKeyId).map(SessionCredential::getSecretAccessKey));
}
/** Returns a temporary session secret only when the issued session token also matches. */
public Optional<String> findSecretKey(String accessKeyId, String sessionToken) {
return activeAccessKeySecret(accessKeyId).or(() -> currentSession(accessKeyId)
.filter(session -> hasMatchingSessionToken(session, sessionToken))
.map(SessionCredential::getSecretAccessKey));
}
/** 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);
}
private Optional<String> activeAccessKeySecret(String accessKeyId) {
return accessKeys.get(accessKeyId)
.filter(accessKey -> "Active".equals(accessKey.getStatus()))
.map(AccessKey::getSecretAccessKey);
}
private Optional<SessionCredential> currentSession(String accessKeyId) {
return findSessionAnyAccount(accessKeyId)
.filter(session -> session.getExpiration() == null || Instant.now().isBefore(session.getExpiration()));
}
private static boolean hasMatchingSessionToken(SessionCredential session, String sessionToken) {
if (sessionToken == null || session.getSessionToken() == null) {
return false;
}
return findSessionAnyAccount(accessKeyId).map(SessionCredential::getSecretAccessKey);
return MessageDigest.isEqual(
session.getSessionToken().getBytes(StandardCharsets.UTF_8),
sessionToken.getBytes(StandardCharsets.UTF_8));
}
public Optional<AccessKey> findAccessKey(String accessKeyId) {
@@ -1864,8 +1896,15 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
*/
public void registerSession(String sessionAccessKeyId, String secretAccessKey, String roleArn,
java.time.Instant expiration, String sessionPolicyDocument) {
registerSession(sessionAccessKeyId, secretAccessKey, null, roleArn, expiration, sessionPolicyDocument);
}
/** Stores a temporary credential including the session token required for authentication. */
public void registerSession(String sessionAccessKeyId, String secretAccessKey, String sessionToken,
String roleArn, java.time.Instant expiration, String sessionPolicyDocument) {
sessions.put(sessionAccessKeyId,
new SessionCredential(sessionAccessKeyId, secretAccessKey, roleArn, expiration, sessionPolicyDocument));
new SessionCredential(sessionAccessKeyId, secretAccessKey, sessionToken, roleArn,
expiration, sessionPolicyDocument));
}
/**
@@ -1876,8 +1915,16 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
public void registerSession(String sessionAccessKeyId, String secretAccessKey, String roleArn,
java.time.Instant expiration, String sessionPolicyDocument,
String originAccountId) {
registerSession(sessionAccessKeyId, secretAccessKey, null, roleArn, expiration, sessionPolicyDocument,
originAccountId);
}
/** Stores a temporary credential and its origin account. */
public void registerSession(String sessionAccessKeyId, String secretAccessKey, String sessionToken,
String roleArn, java.time.Instant expiration, String sessionPolicyDocument,
String originAccountId) {
sessions.put(sessionAccessKeyId,
new SessionCredential(sessionAccessKeyId, secretAccessKey, roleArn, expiration,
new SessionCredential(sessionAccessKeyId, secretAccessKey, sessionToken, roleArn, expiration,
sessionPolicyDocument, originAccountId));
}
@@ -1885,11 +1932,20 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
public void registerSessionForAccount(String accountId, String sessionAccessKeyId, String secretAccessKey,
String roleArn, java.time.Instant expiration,
String sessionPolicyDocument) {
registerSessionForAccount(accountId, sessionAccessKeyId, secretAccessKey, null, roleArn, expiration,
sessionPolicyDocument);
}
/** Stores a temporary credential in an explicit account namespace. */
public void registerSessionForAccount(String accountId, String sessionAccessKeyId, String secretAccessKey,
String sessionToken, String roleArn, java.time.Instant expiration,
String sessionPolicyDocument) {
if (accountId == null || accountId.isBlank()) {
throw new IllegalArgumentException("Session account ID must not be blank");
}
SessionCredential session = new SessionCredential(
sessionAccessKeyId, secretAccessKey, roleArn, expiration, sessionPolicyDocument, accountId);
sessionAccessKeyId, secretAccessKey, sessionToken, roleArn, expiration, sessionPolicyDocument,
accountId);
if (sessions instanceof AccountAwareStorageBackend<SessionCredential> aware) {
aware.putForAccount(accountId, sessionAccessKeyId, session);
} else {
@@ -1903,11 +1959,17 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
*/
public void registerLambdaExecutionRoleSession(String accountId, String sessionAccessKeyId,
String secretAccessKey, String roleArn) {
registerLambdaExecutionRoleSession(accountId, sessionAccessKeyId, secretAccessKey, null, roleArn);
}
/** Stores a non-expiring Lambda execution-role session with its session token. */
public void registerLambdaExecutionRoleSession(String accountId, String sessionAccessKeyId,
String secretAccessKey, String sessionToken, String roleArn) {
if (accountId == null || accountId.isBlank()) {
throw new IllegalArgumentException("Lambda function account ID must not be blank");
}
SessionCredential session = new SessionCredential(
sessionAccessKeyId, secretAccessKey, roleArn, null, null, accountId);
sessionAccessKeyId, secretAccessKey, sessionToken, roleArn, null, null, accountId);
session.setLambdaExecutionRole(true);
if (sessions instanceof AccountAwareStorageBackend<SessionCredential> aware) {
aware.putForAccount(accountId, sessionAccessKeyId, session);
@@ -116,7 +116,8 @@ public class StsQueryHandler {
// IAM token validation can find the temporary secret key, and account routing can map
// these temporary credentials to the assumed role's account.
String sessionPolicy = getParam(params, "Policy");
iamService.registerSession(accessKeyId, secretKey, roleArn, expiration, sessionPolicy, callerAccountId);
iamService.registerSession(
accessKeyId, secretKey, sessionToken, roleArn, expiration, sessionPolicy, callerAccountId);
String result = new XmlBuilder()
.raw(credentialsXml(accessKeyId, secretKey, sessionToken, expiration))
@@ -178,7 +179,8 @@ public class StsQueryHandler {
String result = credentialsXml(accessKeyId, secretKey, sessionToken, expiration);
// No role ARN — route these credentials back to the caller's account.
iamService.registerSession(accessKeyId, secretKey, null, expiration, null, regionResolver.getAccountId());
iamService.registerSession(
accessKeyId, secretKey, sessionToken, null, expiration, null, regionResolver.getAccountId());
return Response.ok(AwsQueryResponse.envelope("GetSessionToken", AwsNamespaces.STS, result)).build();
}
@@ -220,7 +222,8 @@ public class StsQueryHandler {
String subject = verified != null ? verified.subject() : "web-identity-subject";
String sessionPolicy = getParam(params, "Policy");
iamService.registerSession(accessKeyId, secretKey, roleArn, expiration, sessionPolicy, callerAccountId);
iamService.registerSession(
accessKeyId, secretKey, sessionToken, roleArn, expiration, sessionPolicy, callerAccountId);
String result = new XmlBuilder()
.raw(credentialsXml(accessKeyId, secretKey, sessionToken, expiration))
@@ -342,7 +345,7 @@ public class StsQueryHandler {
String assumedRoleArn = AwsArnUtils.Arn.of("sts", "", accountId, "assumed-role/" + roleName + "/" + sessionName).toString();
String assumedRoleId = "AROA" + randomId(16) + ":" + sessionName;
iamService.registerSession(accessKeyId, secretKey, roleArn, expiration, null, callerAccountId);
iamService.registerSession(accessKeyId, secretKey, sessionToken, roleArn, expiration, null, callerAccountId);
String result = new XmlBuilder()
.raw(credentialsXml(accessKeyId, secretKey, sessionToken, expiration))
@@ -379,7 +382,8 @@ public class StsQueryHandler {
String sessionPolicy = getParam(params, "Policy");
// Register federation token so enforcement can scope its policies via session policy.
// The federated-user ARN already carries the caller's account, so reuse it as the origin.
iamService.registerSession(accessKeyId, secretKey, federatedUserArn, expiration, sessionPolicy, accountId);
iamService.registerSession(
accessKeyId, secretKey, sessionToken, federatedUserArn, expiration, sessionPolicy, accountId);
String result = new XmlBuilder()
.raw(credentialsXml(accessKeyId, secretKey, sessionToken, expiration))
@@ -11,6 +11,7 @@ public class SessionCredential {
private String accessKeyId;
private String secretAccessKey;
private String sessionToken;
private String roleArn;
private Instant expiration;
/** Inline session policy passed to AssumeRole/GetFederationToken — further restricts role policies. */
@@ -40,8 +41,14 @@ public class SessionCredential {
public SessionCredential(String accessKeyId, String secretAccessKey, String roleArn, Instant expiration,
String sessionPolicyDocument) {
this(accessKeyId, secretAccessKey, null, roleArn, expiration, sessionPolicyDocument);
}
public SessionCredential(String accessKeyId, String secretAccessKey, String sessionToken, String roleArn,
Instant expiration, String sessionPolicyDocument) {
this.accessKeyId = accessKeyId;
this.secretAccessKey = secretAccessKey;
this.sessionToken = sessionToken;
this.roleArn = roleArn;
this.expiration = expiration;
this.sessionPolicyDocument = sessionPolicyDocument;
@@ -49,8 +56,14 @@ public class SessionCredential {
public SessionCredential(String accessKeyId, String secretAccessKey, String roleArn, Instant expiration,
String sessionPolicyDocument, String originAccountId) {
this(accessKeyId, secretAccessKey, null, roleArn, expiration, sessionPolicyDocument, originAccountId);
}
public SessionCredential(String accessKeyId, String secretAccessKey, String sessionToken, String roleArn,
Instant expiration, String sessionPolicyDocument, String originAccountId) {
this.accessKeyId = accessKeyId;
this.secretAccessKey = secretAccessKey;
this.sessionToken = sessionToken;
this.roleArn = roleArn;
this.expiration = expiration;
this.sessionPolicyDocument = sessionPolicyDocument;
@@ -63,6 +76,9 @@ public class SessionCredential {
public String getSecretAccessKey() { return secretAccessKey; }
public void setSecretAccessKey(String secretAccessKey) { this.secretAccessKey = secretAccessKey; }
public String getSessionToken() { return sessionToken; }
public void setSessionToken(String sessionToken) { this.sessionToken = sessionToken; }
public String getRoleArn() { return roleArn; }
public void setRoleArn(String roleArn) { this.roleArn = roleArn; }
@@ -83,7 +83,8 @@ public class LambdaExecutionRoleCredentials {
random(SECRET_CHARACTERS, 40),
random(SECRET_CHARACTERS, 200));
iamService.registerLambdaExecutionRoleSession(
functionAccountId, credentials.accessKeyId(), credentials.secretAccessKey(), roleArn);
functionAccountId, credentials.accessKeyId(), credentials.secretAccessKey(),
credentials.sessionToken(), roleArn);
return Optional.of(credentials);
}
@@ -253,7 +253,7 @@ public class SigninService {
Instant expiration = issuedAt.plusSeconds(ACCESS_TOKEN_TTL_SECONDS);
String principalArn = "arn:aws:iam::" + accountId + ":root";
iamService.registerSessionForAccount(
accountId, accessKeyId, secretAccessKey, principalArn, expiration, null);
accountId, accessKeyId, secretAccessKey, sessionToken, principalArn, expiration, null);
SessionCreds accessToken = new SessionCreds(accessKeyId, secretAccessKey, sessionToken);
String idToken = includeIdToken ? idToken(principalArn, accountId, clientId, issuedAt) : null;