mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(eks): support IRSA with a real OIDC issuer and JWT validation (#2108)
* feat(eks): support IRSA with a real OIDC issuer and JWT validation
Every EKS cluster now gets an OIDC identity provider, so the full IRSA flow
works end to end without mocked or hardcoded tokens.
CreateCluster generates an RSA-2048 keypair and an AWS-shaped issuer URL,
returned by DescribeCluster as identity.oidc.issuer. The issuer is a faithful
string for building trust policies but is never dereferenced: STS resolves the
signing key in-process via a new OidcIssuerKeyLookup port, declared in
core.common so services.iam does not depend on services.eks.
Key material lives in storage separate from the Cluster model. Cluster is
serialized straight onto the DescribeCluster wire response, so a private key
carried there would leak; @JsonIgnore would instead lose it across restarts and
break tokens minted earlier.
sts:AssumeRoleWithWebIdentity previously accepted any non-blank token and
returned a hardcoded subject. It now verifies, but only for issuers Floci hosts:
- RS256 signature against the cluster's public key
- iss matches the issuer exactly
- aud contains sts.amazonaws.com
- exp / nbf, with 60s of clock-skew tolerance
- the role's trust policy, via a new WebIdentityTrustPolicyEvaluator matching
Principal.Federated and the Condition block
The response now carries the token's real claims in
SubjectFromWebIdentityToken, Provider, and Audience. Bad tokens return
InvalidIdentityToken (400); a trust policy that does not permit the subject
returns AccessDenied (403) — a check the web-identity path was missing entirely.
Tokens from an issuer Floci does not host stay permissive, since Floci cannot
verify a third-party signature. Existing behaviour is therefore unchanged and no
configuration flag is required.
WebIdentityTrustPolicyEvaluator is a sibling of AssumeRolePolicyEvaluator rather
than an extension of it: that evaluator serves sts:AssumeRole, hardcodes that
action, reads only Principal.AWS, and ignores conditions. Condition values are
compared with exact, case-sensitive equality instead of the existing
globMatches, which lowercases both operands — case-folding an OIDC subject would
silently admit a different service account.
Because Floci has no kubelet to project a token into a pod, a local-dev harness
can mint one via POST _floci/eks/clusters/{name}/oidc-token and write it to the
file named by AWS_WEB_IDENTITY_TOKEN_FILE. Signing stays server-side so the
private key never leaves Floci. OIDC discovery and JWKS routes are served under
the same _floci namespace, for fidelity rather than because anything fetches
them; the AWS-shaped issuer path is not resolvable by Floci's embedded DNS and
would collide with S3's path-style catch-all.
Adds 51 tests: unit coverage for the verifier, the trust-policy evaluator, and
the OIDC service, plus an end-to-end integration test covering the mint ->
assume -> credentials path and its negative cases (wrong service account,
tampered signature, wrong audience, expired, alg:none).
* fix(iam): close two web-identity validation gaps and backfill cluster OIDC state
Three defects found in review of the IRSA change.
An unsigned "header.payload." token bypassed validation entirely. verify()
split with a -1 limit so a trailing empty segment was preserved, but
parseClaims() — which backs peekIssuer() — did not. Java drops trailing empty
strings by default, so such a token split into two parts, its issuer went unseen,
and STS classified it as an opaque third-party token: signature, claim, and
trust-policy checks were all skipped and credentials were issued for a JWT that
was never signed. Both split sites now pass -1.
StringLike and StringNotLike on an OIDC condition key folded case. They
delegated to IamPolicyEvaluator.globMatches, which lowercases both operands, so
a trust policy scoped to one service account or namespace would admit another
differing only in case — the exact hazard the StringEquals branch was written to
avoid. Adds a case-sensitive glob and uses it for both operators. Action matching
still uses globMatches, which is correctly case-insensitive.
Clusters persisted before this feature never gained an issuer or key, so after an
upgrade DescribeCluster reported no identity.oidc.issuer, minting returned 400,
and the JWKS routes 404'd until the cluster was recreated. EksService now
backfills on startup, and re-runs ensureKey for clusters that already have an
issuer so a restart cannot leave a known issuer without its signing key.
Each fix has a regression test confirmed to fail without it.
* fix(eks): keep IRSA OIDC state scoped to the cluster's owning account
The startup backfill read clusters across every account via scanAllAccounts() but
wrote them back with the request-scoped put(), which resolves to the default
account outside a request context. A cluster owned by any other account kept its
issuer-less record while a duplicate appeared under the default account, leaving
DescribeCluster and the IRSA endpoints broken for the owner. The backfill now
takes the account from the cluster record and writes with putForAccount, per the
pattern StorageFactory documents for work running outside a request.
The same root cause affected key lookup more seriously. findVerificationKey used
the account-scoped scan(), so an issuer owned by a non-default account went
unresolved — and an unresolved issuer is treated as a third-party provider, so
STS accepted the token with no signature, claim, or trust-policy check at all.
It now scans every account, which is correct regardless: an issuer URL is
globally unique, and the account calling AssumeRoleWithWebIdentity need not be
the one that owns the cluster.
deleteKey and findKeyByCluster stay account-scoped; both are only reached from
request-scoped paths (DeleteCluster and the JWKS route), where the caller's
account is the right scope.
Both fixes have a regression test confirmed to fail without them.
This commit is contained in:
1 parent
4a5fae4dcd
commit
7e5afae61b
21 files changed
+2527
-17
No files matched your search
+226
@@ -0,0 +1,226 @@
|
||||
package io.github.hectorvent.floci.core.common;
|
||||
|
||||
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.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.eks.EksOidcService;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.GeneralSecurityException;
|
||||
import java.security.KeyPair;
|
||||
import java.security.KeyPairGenerator;
|
||||
import java.security.PrivateKey;
|
||||
import java.security.Signature;
|
||||
import java.security.interfaces.RSAPublicKey;
|
||||
import java.util.Base64;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class WebIdentityTokenVerifierTest {
|
||||
|
||||
private static final String ISSUER =
|
||||
"https://oidc.eks.us-east-1.amazonaws.com/id/ABCDEF0123456789ABCDEF0123456789";
|
||||
private static final String CLUSTER = "irsa-test-cluster";
|
||||
|
||||
private WebIdentityTokenVerifier verifier;
|
||||
private EksOidcService oidcService;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
verifier = new WebIdentityTokenVerifier(objectMapper);
|
||||
oidcService = new EksOidcService(new StorageFactory(null, null) {
|
||||
@Override
|
||||
public <V> StorageBackend<String, V> create(String serviceName, String fileName,
|
||||
TypeReference<Map<String, V>> typeReference) {
|
||||
return new InMemoryStorage<>();
|
||||
}
|
||||
}, objectMapper);
|
||||
oidcService.ensureKey(CLUSTER, ISSUER);
|
||||
}
|
||||
|
||||
private RSAPublicKey publicKey() {
|
||||
return oidcService.findVerificationKey(ISSUER).orElseThrow();
|
||||
}
|
||||
|
||||
private String mint(String namespace, String serviceAccount, String audience, Integer lifetime) {
|
||||
return oidcService.mintServiceAccountToken(CLUSTER, ISSUER, namespace, serviceAccount,
|
||||
audience, lifetime);
|
||||
}
|
||||
|
||||
private static KeyPair newKeyPair() throws GeneralSecurityException {
|
||||
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
|
||||
generator.initialize(2048);
|
||||
return generator.generateKeyPair();
|
||||
}
|
||||
|
||||
private static String base64Url(String value) {
|
||||
return Base64.getUrlEncoder().withoutPadding()
|
||||
.encodeToString(value.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
/** Signs an arbitrary claim set, so tests can build tokens the production mint path never would. */
|
||||
private static String signRs256(PrivateKey privateKey, String claimsJson)
|
||||
throws GeneralSecurityException {
|
||||
String header = base64Url("{\"alg\":\"RS256\",\"typ\":\"JWT\"}");
|
||||
String payload = base64Url(claimsJson);
|
||||
Signature signature = Signature.getInstance("SHA256withRSA");
|
||||
signature.initSign(privateKey);
|
||||
signature.update((header + "." + payload).getBytes(StandardCharsets.UTF_8));
|
||||
return header + "." + payload + "."
|
||||
+ Base64.getUrlEncoder().withoutPadding().encodeToString(signature.sign());
|
||||
}
|
||||
|
||||
@Test
|
||||
void verifiesFlociMintedToken() throws Exception {
|
||||
String token = mint("my-namespace", "my-service-account", null, null);
|
||||
|
||||
WebIdentityToken verified = verifier.verify(token, publicKey(), ISSUER,
|
||||
EksOidcService.STS_AUDIENCE);
|
||||
|
||||
assertEquals(ISSUER, verified.issuer());
|
||||
assertEquals("system:serviceaccount:my-namespace:my-service-account", verified.subject());
|
||||
assertTrue(verified.audiences().contains(EksOidcService.STS_AUDIENCE));
|
||||
}
|
||||
|
||||
@Test
|
||||
void peeksIssuerWithoutVerifying() {
|
||||
String token = mint("my-namespace", "my-service-account", null, null);
|
||||
assertEquals(ISSUER, verifier.peekIssuer(token).orElseThrow());
|
||||
}
|
||||
|
||||
@Test
|
||||
void peekIssuerReturnsEmptyForOpaqueToken() {
|
||||
assertTrue(verifier.peekIssuer("dummy-token").isEmpty());
|
||||
assertTrue(verifier.peekIssuer(null).isEmpty());
|
||||
assertTrue(verifier.peekIssuer("").isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void peekIssuerSeesTheIssuerOfAnUnsignedToken() {
|
||||
// Regression guard: an unsigned "header.payload." token must not read as opaque. If its
|
||||
// issuer went unseen, the caller would skip validation for a token naming a Floci issuer
|
||||
// and hand out credentials for an unsigned JWT.
|
||||
String header = base64Url("{\"alg\":\"none\",\"typ\":\"JWT\"}");
|
||||
String payload = base64Url("{\"iss\":\"" + ISSUER + "\","
|
||||
+ "\"aud\":[\"" + EksOidcService.STS_AUDIENCE + "\"],"
|
||||
+ "\"sub\":\"system:serviceaccount:my-namespace:my-service-account\","
|
||||
+ "\"exp\":" + (System.currentTimeMillis() / 1000 + 3600) + "}");
|
||||
|
||||
assertEquals(ISSUER, verifier.peekIssuer(header + "." + payload + ".").orElseThrow());
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsTamperedPayload() {
|
||||
String token = mint("my-namespace", "my-service-account", null, null);
|
||||
String[] parts = token.split("\\.", -1);
|
||||
// The forged payload is otherwise valid — same issuer, audience, and a future expiry — so
|
||||
// only the signature check can reject it.
|
||||
String forgedPayload = base64Url("{\"iss\":\"" + ISSUER + "\","
|
||||
+ "\"aud\":[\"" + EksOidcService.STS_AUDIENCE + "\"],"
|
||||
+ "\"sub\":\"system:serviceaccount:my-namespace:attacker\","
|
||||
+ "\"nbf\":" + (System.currentTimeMillis() / 1000 - 60) + ","
|
||||
+ "\"exp\":" + (System.currentTimeMillis() / 1000 + 3600) + "}");
|
||||
String tampered = parts[0] + "." + forgedPayload + "." + parts[2];
|
||||
|
||||
WebIdentityTokenVerifier.InvalidTokenException thrown = assertThrows(
|
||||
WebIdentityTokenVerifier.InvalidTokenException.class,
|
||||
() -> verifier.verify(tampered, publicKey(), ISSUER, EksOidcService.STS_AUDIENCE));
|
||||
assertTrue(thrown.getMessage().contains("signature"),
|
||||
"expected a signature failure, got: " + thrown.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsWrongIssuer() {
|
||||
String token = mint("my-namespace", "my-service-account", null, null);
|
||||
|
||||
assertThrows(WebIdentityTokenVerifier.InvalidTokenException.class,
|
||||
() -> verifier.verify(token, publicKey(),
|
||||
"https://oidc.eks.us-east-1.amazonaws.com/id/OTHER",
|
||||
EksOidcService.STS_AUDIENCE));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsWrongAudience() {
|
||||
String token = mint("my-namespace", "my-service-account", "some.other.audience", null);
|
||||
|
||||
assertThrows(WebIdentityTokenVerifier.InvalidTokenException.class,
|
||||
() -> verifier.verify(token, publicKey(), ISSUER, EksOidcService.STS_AUDIENCE));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsExpiredToken() throws Exception {
|
||||
// Signed with a locally generated key so the payload can carry an arbitrary past expiry;
|
||||
// the production mint path always issues a future-dated token.
|
||||
KeyPair keyPair = newKeyPair();
|
||||
long expired = System.currentTimeMillis() / 1000 - 7200;
|
||||
String token = signRs256(keyPair.getPrivate(),
|
||||
"{\"iss\":\"" + ISSUER + "\",\"aud\":[\"" + EksOidcService.STS_AUDIENCE + "\"],"
|
||||
+ "\"sub\":\"system:serviceaccount:my-namespace:my-service-account\","
|
||||
+ "\"exp\":" + expired + "}");
|
||||
|
||||
WebIdentityTokenVerifier.InvalidTokenException thrown = assertThrows(
|
||||
WebIdentityTokenVerifier.InvalidTokenException.class,
|
||||
() -> verifier.verify(token, (RSAPublicKey) keyPair.getPublic(), ISSUER,
|
||||
EksOidcService.STS_AUDIENCE));
|
||||
assertTrue(thrown.getMessage().contains("expired"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsTokenNotYetValid() throws Exception {
|
||||
KeyPair keyPair = newKeyPair();
|
||||
long now = System.currentTimeMillis() / 1000;
|
||||
String token = signRs256(keyPair.getPrivate(),
|
||||
"{\"iss\":\"" + ISSUER + "\",\"aud\":[\"" + EksOidcService.STS_AUDIENCE + "\"],"
|
||||
+ "\"sub\":\"system:serviceaccount:my-namespace:my-service-account\","
|
||||
+ "\"nbf\":" + (now + 7200) + ",\"exp\":" + (now + 10800) + "}");
|
||||
|
||||
WebIdentityTokenVerifier.InvalidTokenException thrown = assertThrows(
|
||||
WebIdentityTokenVerifier.InvalidTokenException.class,
|
||||
() -> verifier.verify(token, (RSAPublicKey) keyPair.getPublic(), ISSUER,
|
||||
EksOidcService.STS_AUDIENCE));
|
||||
assertTrue(thrown.getMessage().contains("not yet valid"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsKeyFromAnotherCluster() {
|
||||
String otherIssuer = "https://oidc.eks.us-east-1.amazonaws.com/id/OTHERCLUSTER0000000000000000";
|
||||
oidcService.ensureKey("other-cluster", otherIssuer);
|
||||
String token = mint("my-namespace", "my-service-account", null, null);
|
||||
RSAPublicKey otherKey = oidcService.findVerificationKey(otherIssuer).orElseThrow();
|
||||
|
||||
assertThrows(WebIdentityTokenVerifier.InvalidTokenException.class,
|
||||
() -> verifier.verify(token, otherKey, ISSUER, EksOidcService.STS_AUDIENCE));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsMalformedToken() {
|
||||
assertThrows(WebIdentityTokenVerifier.InvalidTokenException.class,
|
||||
() -> verifier.verify("not-a-jwt", publicKey(), ISSUER, EksOidcService.STS_AUDIENCE));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsUnsignedAlgNoneToken() {
|
||||
String header = base64Url("{\"alg\":\"none\",\"typ\":\"JWT\"}");
|
||||
String payload = base64Url("{\"iss\":\"" + ISSUER + "\","
|
||||
+ "\"aud\":[\"" + EksOidcService.STS_AUDIENCE + "\"],"
|
||||
+ "\"sub\":\"system:serviceaccount:my-namespace:my-service-account\","
|
||||
+ "\"exp\":" + (System.currentTimeMillis() / 1000 + 3600) + "}");
|
||||
|
||||
// The empty third segment must be preserved when splitting, so this is rejected by the
|
||||
// algorithm check rather than being mistaken for a two-segment malformed token.
|
||||
WebIdentityTokenVerifier.InvalidTokenException thrown = assertThrows(
|
||||
WebIdentityTokenVerifier.InvalidTokenException.class,
|
||||
() -> verifier.verify(header + "." + payload + ".", publicKey(), ISSUER,
|
||||
EksOidcService.STS_AUDIENCE));
|
||||
assertTrue(thrown.getMessage().contains("algorithm"),
|
||||
"expected an algorithm rejection, got: " + thrown.getMessage());
|
||||
}
|
||||
}
|
||||
+266
@@ -0,0 +1,266 @@
|
||||
package io.github.hectorvent.floci.services.eks;
|
||||
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.response.Response;
|
||||
import org.junit.jupiter.api.MethodOrderer;
|
||||
import org.junit.jupiter.api.Order;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestMethodOrder;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.notNullValue;
|
||||
|
||||
/**
|
||||
* Full IRSA path: create a cluster, read its OIDC issuer, create a role whose trust policy pins the
|
||||
* federated OIDC provider to a service account, mint a token for that service account, and exchange
|
||||
* it via {@code sts:AssumeRoleWithWebIdentity}.
|
||||
*
|
||||
* <p>Also covers the negative cases that matter — wrong service account, tampered signature, wrong
|
||||
* audience — and the compatibility guarantee that an opaque third-party token is still accepted.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
|
||||
class EksIrsaEndToEndIntegrationTest {
|
||||
|
||||
private static final String JSON = "application/json";
|
||||
private static final String FORM = "application/x-www-form-urlencoded";
|
||||
private static final String CLUSTER = "irsa-e2e-cluster";
|
||||
private static final String ROLE = "irsa-e2e-role";
|
||||
private static final String NAMESPACE = "my-namespace";
|
||||
private static final String SERVICE_ACCOUNT = "cell-e2e";
|
||||
private static final String ACCOUNT = "000000000000";
|
||||
|
||||
private static String issuer;
|
||||
private static String roleArn;
|
||||
|
||||
private static String issuerKeyPrefix() {
|
||||
return issuer.replaceFirst("^https://", "");
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(1)
|
||||
void createClusterAndCaptureIssuer() {
|
||||
issuer = given()
|
||||
.contentType(JSON)
|
||||
.body("{\"name\":\"" + CLUSTER + "\",\"roleArn\":\"arn:aws:iam::" + ACCOUNT + ":role/eks\"}")
|
||||
.when()
|
||||
.post("/clusters")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("cluster.identity.oidc.issuer", notNullValue())
|
||||
.extract().path("cluster.identity.oidc.issuer");
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(2)
|
||||
void createRoleWithFederatedTrustPolicy() {
|
||||
String prefix = issuerKeyPrefix();
|
||||
String trustPolicy = """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{\
|
||||
"Federated":"arn:aws:iam::%s:oidc-provider/%s"},\
|
||||
"Action":"sts:AssumeRoleWithWebIdentity","Condition":{"StringEquals":{\
|
||||
"%s:sub":"system:serviceaccount:%s:%s","%s:aud":"sts.amazonaws.com"}}}]}"""
|
||||
.formatted(ACCOUNT, prefix, prefix, NAMESPACE, SERVICE_ACCOUNT, prefix);
|
||||
|
||||
roleArn = given()
|
||||
.contentType(FORM)
|
||||
.formParam("Action", "CreateRole")
|
||||
.formParam("Version", "2010-05-08")
|
||||
.formParam("RoleName", ROLE)
|
||||
.formParam("AssumeRolePolicyDocument", trustPolicy)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract().path("CreateRoleResponse.CreateRoleResult.Role.Arn");
|
||||
}
|
||||
|
||||
private String mintToken(String namespace, String serviceAccount, String audience) {
|
||||
StringBuilder body = new StringBuilder("{\"namespace\":\"" + namespace
|
||||
+ "\",\"serviceAccount\":\"" + serviceAccount + "\"");
|
||||
if (audience != null) {
|
||||
body.append(",\"audience\":\"").append(audience).append("\"");
|
||||
}
|
||||
body.append("}");
|
||||
|
||||
return given()
|
||||
.contentType(JSON)
|
||||
.body(body.toString())
|
||||
.when()
|
||||
.post("/_floci/eks/clusters/" + CLUSTER + "/oidc-token")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("token", notNullValue())
|
||||
.extract().path("token");
|
||||
}
|
||||
|
||||
private Response assumeRole(String token) {
|
||||
return given()
|
||||
.contentType(FORM)
|
||||
.formParam("Action", "AssumeRoleWithWebIdentity")
|
||||
.formParam("Version", "2011-06-15")
|
||||
.formParam("RoleArn", roleArn)
|
||||
.formParam("RoleSessionName", "irsa-e2e-session")
|
||||
.formParam("WebIdentityToken", token)
|
||||
.when()
|
||||
.post("/");
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(3)
|
||||
void mintedTokenAssumesRoleAndReturnsRealClaims() {
|
||||
String token = mintToken(NAMESPACE, SERVICE_ACCOUNT, null);
|
||||
|
||||
assumeRole(token)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString("<AccessKeyId>ASIA"))
|
||||
.body(containsString("<SecretAccessKey>"))
|
||||
.body(containsString("<SessionToken>"))
|
||||
// Real claims from the token, not the old hardcoded placeholders.
|
||||
.body(containsString("<SubjectFromWebIdentityToken>system:serviceaccount:"
|
||||
+ NAMESPACE + ":" + SERVICE_ACCOUNT + "</SubjectFromWebIdentityToken>"))
|
||||
.body(containsString("<Provider>" + issuer + "</Provider>"))
|
||||
.body(containsString("<Audience>sts.amazonaws.com</Audience>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(4)
|
||||
void deniesTokenForDifferentServiceAccount() {
|
||||
String token = mintToken(NAMESPACE, "not-the-trusted-sa", null);
|
||||
|
||||
assumeRole(token)
|
||||
.then()
|
||||
.statusCode(403)
|
||||
.body(containsString("AccessDenied"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(5)
|
||||
void rejectsTamperedSignature() {
|
||||
String token = mintToken(NAMESPACE, SERVICE_ACCOUNT, null);
|
||||
String[] parts = token.split("\\.", -1);
|
||||
// Flip a character mid-signature. The final base64 character of a 256-byte RSA signature
|
||||
// carries only a few significant bits, so mutating it can decode to identical bytes and
|
||||
// still verify; a middle character always changes the signature.
|
||||
int middle = parts[2].length() / 2;
|
||||
char original = parts[2].charAt(middle);
|
||||
String flipped = parts[2].substring(0, middle)
|
||||
+ (original == 'A' ? 'B' : 'A')
|
||||
+ parts[2].substring(middle + 1);
|
||||
|
||||
assumeRole(parts[0] + "." + parts[1] + "." + flipped)
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body(containsString("InvalidIdentityToken"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(6)
|
||||
void rejectsWrongAudience() {
|
||||
String token = mintToken(NAMESPACE, SERVICE_ACCOUNT, "some.other.audience");
|
||||
|
||||
assumeRole(token)
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body(containsString("InvalidIdentityToken"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(7)
|
||||
void rejectsUnsignedTokenNamingAFlociIssuer() {
|
||||
// An unsigned "header.payload." token must not slip through the opaque-token path: its
|
||||
// issuer is one Floci hosts, so it has to be validated and rejected, not accepted.
|
||||
String token = mintToken(NAMESPACE, SERVICE_ACCOUNT, null);
|
||||
String[] parts = token.split("\\.", -1);
|
||||
|
||||
assumeRole(parts[0] + "." + parts[1] + ".")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body(containsString("InvalidIdentityToken"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(8)
|
||||
void opaqueThirdPartyTokenRemainsAccepted() {
|
||||
// Compatibility guarantee: Floci cannot adjudicate an issuer it does not host, so the
|
||||
// historical permissive behaviour is preserved rather than failing the call.
|
||||
assumeRole("dummy-token")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString("<AccessKeyId>ASIA"))
|
||||
.body(containsString("<SubjectFromWebIdentityToken>web-identity-subject"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(9)
|
||||
void jwksAndDiscoveryEndpointsServeTheSigningKey() {
|
||||
given()
|
||||
.when()
|
||||
.get("/_floci/eks/clusters/" + CLUSTER + "/oidc/.well-known/openid-configuration")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("issuer", equalTo(issuer))
|
||||
.body("id_token_signing_alg_values_supported[0]", equalTo("RS256"));
|
||||
|
||||
given()
|
||||
.when()
|
||||
.get("/_floci/eks/clusters/" + CLUSTER + "/oidc/keys")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("keys[0].kty", equalTo("RSA"))
|
||||
.body("keys[0].alg", equalTo("RS256"))
|
||||
.body("keys[0].n", notNullValue())
|
||||
.body("keys[0].e", equalTo("AQAB"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(10)
|
||||
void mintRejectsMissingServiceAccount() {
|
||||
given()
|
||||
.contentType(JSON)
|
||||
.body("{\"namespace\":\"" + NAMESPACE + "\"}")
|
||||
.when()
|
||||
.post("/_floci/eks/clusters/" + CLUSTER + "/oidc-token")
|
||||
.then()
|
||||
.statusCode(400);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(11)
|
||||
void mintRejectsUnknownCluster() {
|
||||
given()
|
||||
.contentType(JSON)
|
||||
.body("{\"namespace\":\"" + NAMESPACE + "\",\"serviceAccount\":\"" + SERVICE_ACCOUNT + "\"}")
|
||||
.when()
|
||||
.post("/_floci/eks/clusters/no-such-cluster/oidc-token")
|
||||
.then()
|
||||
.statusCode(404);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(12)
|
||||
void deletingClusterDropsSigningKey() {
|
||||
given().when().delete("/clusters/" + CLUSTER).then().statusCode(200);
|
||||
|
||||
given()
|
||||
.when()
|
||||
.get("/_floci/eks/clusters/" + CLUSTER + "/oidc/keys")
|
||||
.then()
|
||||
.statusCode(404);
|
||||
|
||||
// Cleanup runs as the last ordered step rather than in @AfterAll: Quarkus has already shut
|
||||
// the test HTTP server down by then, so an @AfterAll request fails with a connection reset.
|
||||
given()
|
||||
.contentType(FORM)
|
||||
.formParam("Action", "DeleteRole")
|
||||
.formParam("Version", "2010-05-08")
|
||||
.formParam("RoleName", ROLE)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
}
|
||||
}
|
||||
+121
@@ -0,0 +1,121 @@
|
||||
package io.github.hectorvent.floci.services.eks;
|
||||
|
||||
import io.github.hectorvent.floci.services.eks.model.ClusterOidcKey;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.MethodOrderer;
|
||||
import org.junit.jupiter.api.Order;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestMethodOrder;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.matchesPattern;
|
||||
import static org.hamcrest.Matchers.notNullValue;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
|
||||
/**
|
||||
* DescribeCluster must expose {@code identity.oidc.issuer} so IRSA callers can build a trust policy
|
||||
* referencing the cluster's OIDC provider, and must never expose the signing material behind it.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
|
||||
class EksOidcIdentityIntegrationTest {
|
||||
|
||||
private static final String JSON = "application/json";
|
||||
private static final String CLUSTER = "oidc-it-cluster";
|
||||
|
||||
@Inject
|
||||
EksOidcService oidcService;
|
||||
|
||||
@Test
|
||||
@Order(1)
|
||||
void createClusterReturnsAwsShapedOidcIssuer() {
|
||||
given()
|
||||
.contentType(JSON)
|
||||
.body("{\"name\":\"" + CLUSTER + "\",\"roleArn\":\"arn:aws:iam::000000000000:role/eks\"}")
|
||||
.when()
|
||||
.post("/clusters")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("cluster.identity.oidc.issuer", matchesPattern(
|
||||
"https://oidc\\.eks\\.us-east-1\\.amazonaws\\.com/id/[A-F0-9]{32}"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(2)
|
||||
void describeClusterReturnsStableIssuer() {
|
||||
String issuer = given()
|
||||
.when()
|
||||
.get("/clusters/" + CLUSTER)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("cluster.identity.oidc.issuer", notNullValue())
|
||||
.extract().path("cluster.identity.oidc.issuer");
|
||||
|
||||
// The issuer is persisted, not regenerated per describe — a trust policy written once
|
||||
// must keep matching.
|
||||
given()
|
||||
.when()
|
||||
.get("/clusters/" + CLUSTER)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("cluster.identity.oidc.issuer", equalTo(issuer));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(3)
|
||||
void describeClusterNeverExposesSigningMaterial() {
|
||||
// Asserted against the actual stored key rather than a list of guessed field names, so this
|
||||
// fails if key material is ever surfaced under any property.
|
||||
ClusterOidcKey stored = oidcService.findKeyByCluster(CLUSTER).orElseThrow();
|
||||
|
||||
String body = given()
|
||||
.when()
|
||||
.get("/clusters/" + CLUSTER)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract().asString();
|
||||
|
||||
assertFalse(body.contains(stored.getPrivateKey()),
|
||||
"DescribeCluster response leaked the OIDC private key");
|
||||
assertFalse(body.contains(stored.getPublicKey()),
|
||||
"DescribeCluster response leaked the OIDC public key");
|
||||
// A PKCS#8 RSA private key in base64 always begins with this prefix.
|
||||
assertFalse(body.contains("MII"), "DescribeCluster response contains encoded key material");
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(4)
|
||||
void distinctClustersGetDistinctIssuers() {
|
||||
String second = CLUSTER + "-2";
|
||||
String firstIssuer = given()
|
||||
.when().get("/clusters/" + CLUSTER)
|
||||
.then().statusCode(200)
|
||||
.extract().path("cluster.identity.oidc.issuer");
|
||||
|
||||
String secondIssuer = given()
|
||||
.contentType(JSON)
|
||||
.body("{\"name\":\"" + second + "\",\"roleArn\":\"arn:aws:iam::000000000000:role/eks\"}")
|
||||
.when()
|
||||
.post("/clusters")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract().path("cluster.identity.oidc.issuer");
|
||||
|
||||
assertNotEquals(firstIssuer, secondIssuer);
|
||||
|
||||
given().when().delete("/clusters/" + second).then().statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(5)
|
||||
void deleteClusterSucceeds() {
|
||||
given()
|
||||
.when()
|
||||
.delete("/clusters/" + CLUSTER)
|
||||
.then()
|
||||
.statusCode(200);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
package io.github.hectorvent.floci.services.eks;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.eks.model.ClusterOidcKey;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Base64;
|
||||
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.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class EksOidcServiceTest {
|
||||
|
||||
private static final String ISSUER =
|
||||
"https://oidc.eks.us-east-1.amazonaws.com/id/ABCDEF0123456789ABCDEF0123456789";
|
||||
private static final String CLUSTER = "irsa-test-cluster";
|
||||
|
||||
private EksOidcService oidcService;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
oidcService = new EksOidcService(new StorageFactory(null, null) {
|
||||
@Override
|
||||
public <V> StorageBackend<String, V> create(String serviceName, String fileName,
|
||||
TypeReference<Map<String, V>> typeReference) {
|
||||
return new InMemoryStorage<>();
|
||||
}
|
||||
}, new ObjectMapper());
|
||||
}
|
||||
|
||||
private String decodePayload(String token) {
|
||||
return new String(Base64.getUrlDecoder().decode(token.split("\\.", -1)[1]));
|
||||
}
|
||||
|
||||
@Test
|
||||
void newIssuerUrlIsAwsShapedAndUnique() {
|
||||
String first = oidcService.newIssuerUrl("us-east-1");
|
||||
String second = oidcService.newIssuerUrl("us-east-1");
|
||||
|
||||
assertTrue(first.matches("https://oidc\\.eks\\.us-east-1\\.amazonaws\\.com/id/[A-F0-9]{32}"),
|
||||
"unexpected issuer shape: " + first);
|
||||
assertNotEquals(first, second);
|
||||
assertTrue(oidcService.newIssuerUrl("eu-west-2").contains("oidc.eks.eu-west-2."));
|
||||
}
|
||||
|
||||
@Test
|
||||
void ensureKeyIsIdempotentForTheSameIssuer() {
|
||||
ClusterOidcKey first = oidcService.ensureKey(CLUSTER, ISSUER);
|
||||
ClusterOidcKey second = oidcService.ensureKey(CLUSTER, ISSUER);
|
||||
|
||||
assertEquals(first.getKeyId(), second.getKeyId());
|
||||
assertEquals(first.getPrivateKey(), second.getPrivateKey());
|
||||
}
|
||||
|
||||
@Test
|
||||
void ensureKeyRotatesWhenTheIssuerChanges() {
|
||||
ClusterOidcKey original = oidcService.ensureKey(CLUSTER, ISSUER);
|
||||
ClusterOidcKey rotated = oidcService.ensureKey(CLUSTER,
|
||||
"https://oidc.eks.us-east-1.amazonaws.com/id/0000000000000000000000000000BEEF");
|
||||
|
||||
assertNotEquals(original.getPrivateKey(), rotated.getPrivateKey());
|
||||
assertTrue(oidcService.findVerificationKey(ISSUER).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void findVerificationKeyResolvesAcrossAccounts() {
|
||||
// STS must resolve an issuer regardless of which account owns the cluster: the caller need
|
||||
// not be the owner, and an unresolved issuer is treated as a third-party provider — so the
|
||||
// token would be accepted with no validation at all.
|
||||
StorageBackend<String, ClusterOidcKey> raw = new InMemoryStorage<>();
|
||||
var accountAware = new AccountAwareStorageBackend<>(raw, null, "000000000000");
|
||||
EksOidcService service = new EksOidcService(new StorageFactory(null, null) {
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public <V> StorageBackend<String, V> create(String serviceName, String fileName,
|
||||
TypeReference<Map<String, V>> typeReference) {
|
||||
return (StorageBackend<String, V>) accountAware;
|
||||
}
|
||||
}, new ObjectMapper());
|
||||
|
||||
service.ensureKeyForAccount("999999999999", CLUSTER, ISSUER);
|
||||
|
||||
// The lookup runs outside any request context, so it resolves to the default account.
|
||||
assertTrue(service.findVerificationKey(ISSUER).isPresent());
|
||||
}
|
||||
|
||||
@Test
|
||||
void findVerificationKeyResolvesOnlyKnownIssuers() {
|
||||
oidcService.ensureKey(CLUSTER, ISSUER);
|
||||
|
||||
assertTrue(oidcService.findVerificationKey(ISSUER).isPresent());
|
||||
assertTrue(oidcService.findVerificationKey("https://accounts.google.com").isEmpty());
|
||||
assertTrue(oidcService.findVerificationKey(null).isEmpty());
|
||||
assertTrue(oidcService.findVerificationKey("").isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteKeyRemovesSigningMaterial() {
|
||||
oidcService.ensureKey(CLUSTER, ISSUER);
|
||||
oidcService.deleteKey(CLUSTER);
|
||||
|
||||
assertTrue(oidcService.findKeyByCluster(CLUSTER).isEmpty());
|
||||
assertTrue(oidcService.findVerificationKey(ISSUER).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void mintedTokenCarriesKubernetesServiceAccountClaims() {
|
||||
oidcService.ensureKey(CLUSTER, ISSUER);
|
||||
String payload = decodePayload(oidcService.mintServiceAccountToken(
|
||||
CLUSTER, ISSUER, "my-namespace", "my-service-account", null, null));
|
||||
|
||||
assertTrue(payload.contains("\"sub\":\"system:serviceaccount:my-namespace:my-service-account\""));
|
||||
assertTrue(payload.contains("\"kubernetes.io\""));
|
||||
assertTrue(payload.contains("\"namespace\":\"my-namespace\""));
|
||||
assertTrue(payload.contains("\"name\":\"my-service-account\""));
|
||||
}
|
||||
|
||||
@Test
|
||||
void mintRejectsMissingNamespaceOrServiceAccount() {
|
||||
oidcService.ensureKey(CLUSTER, ISSUER);
|
||||
|
||||
assertThrows(AwsException.class, () -> oidcService.mintServiceAccountToken(
|
||||
CLUSTER, ISSUER, null, "my-service-account", null, null));
|
||||
assertThrows(AwsException.class, () -> oidcService.mintServiceAccountToken(
|
||||
CLUSTER, ISSUER, " ", "my-service-account", null, null));
|
||||
assertThrows(AwsException.class, () -> oidcService.mintServiceAccountToken(
|
||||
CLUSTER, ISSUER, "my-namespace", null, null, null));
|
||||
assertThrows(AwsException.class, () -> oidcService.mintServiceAccountToken(
|
||||
CLUSTER, ISSUER, "my-namespace", " ", null, null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void mintClampsLifetimeToTheMaximum() {
|
||||
oidcService.ensureKey(CLUSTER, ISSUER);
|
||||
long now = System.currentTimeMillis() / 1000;
|
||||
|
||||
String payload = decodePayload(oidcService.mintServiceAccountToken(
|
||||
CLUSTER, ISSUER, "my-namespace", "my-service-account", null, Integer.MAX_VALUE));
|
||||
|
||||
long exp = Long.parseLong(payload.replaceAll(".*\"exp\":(\\d+).*", "$1"));
|
||||
assertTrue(exp <= now + 604800, "expiry was not clamped to 7 days: " + exp);
|
||||
}
|
||||
|
||||
@Test
|
||||
void namespaceWithControlCharactersStillProducesAParseableToken() {
|
||||
// Claims are serialized with Jackson, so a newline is escaped rather than breaking the JSON.
|
||||
oidcService.ensureKey(CLUSTER, ISSUER);
|
||||
String payload = decodePayload(oidcService.mintServiceAccountToken(
|
||||
CLUSTER, ISSUER, "bad\nnamespace\"quote", "my-service-account", null, null));
|
||||
|
||||
assertFalse(payload.contains("\n"), "raw newline leaked into the JWT payload");
|
||||
assertTrue(payload.contains("\\n"));
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.eks;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
@@ -12,7 +13,10 @@ import io.github.hectorvent.floci.services.ec2.Ec2ImageCatalog;
|
||||
import io.github.hectorvent.floci.services.ec2.Ec2InstanceTypeCatalog;
|
||||
import io.github.hectorvent.floci.services.ec2.Ec2Service;
|
||||
import io.github.hectorvent.floci.services.ec2.portforward.Ec2PortForwardManager;
|
||||
import io.github.hectorvent.floci.services.eks.model.ClusterIdentity;
|
||||
import io.github.hectorvent.floci.services.eks.model.ClusterOidcKey;
|
||||
import io.github.hectorvent.floci.services.eks.model.ClusterStatus;
|
||||
import io.github.hectorvent.floci.services.eks.model.OidcIdentity;
|
||||
import io.github.hectorvent.floci.services.eks.model.CreateClusterRequest;
|
||||
import io.github.hectorvent.floci.services.eks.model.CreateFargateProfileRequest;
|
||||
import io.github.hectorvent.floci.services.eks.model.CreateNodeGroupRequest;
|
||||
@@ -24,6 +28,7 @@ import io.github.hectorvent.floci.services.eks.model.NodegroupScalingConfig;
|
||||
import io.github.hectorvent.floci.services.eks.model.NodegroupStatus;
|
||||
import io.github.hectorvent.floci.services.eks.model.ResourcesVpcConfig;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
@@ -56,7 +61,8 @@ class EksServiceTest {
|
||||
EksClusterManager clusterManager = null;
|
||||
Ec2Service ec2Service = null;
|
||||
RegionResolver regionResolver = new RegionResolver("us-east-1", "000000000000");
|
||||
eksService = new EksService(storageFactory, config, regionResolver, clusterManager, ec2Service);
|
||||
eksService = new EksService(storageFactory, config, regionResolver, clusterManager, ec2Service,
|
||||
new EksOidcService(storageFactory, new ObjectMapper()));
|
||||
}
|
||||
|
||||
private EmulatorConfig testConfig() {
|
||||
@@ -181,6 +187,113 @@ class EksServiceTest {
|
||||
assertNotNull(cluster.getCreatedAt());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createClusterAssignsOidcIssuerAndKey() {
|
||||
CreateClusterRequest req = new CreateClusterRequest();
|
||||
req.setName("oidc-cluster");
|
||||
req.setRoleArn("arn:aws:iam::000000000000:role/eks-role");
|
||||
|
||||
Cluster cluster = eksService.createCluster(req);
|
||||
|
||||
assertNotNull(cluster.getIdentity());
|
||||
assertNotNull(cluster.getIdentity().getOidc());
|
||||
assertTrue(cluster.getIdentity().getOidc().getIssuer()
|
||||
.matches("https://oidc\\.eks\\.us-east-1\\.amazonaws\\.com/id/[A-F0-9]{32}"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void initBackfillsOidcIdentityForClustersPersistedBeforeIrsaSupport() {
|
||||
// A cluster restored from storage without an identity — what an upgrade looks like — must
|
||||
// gain an issuer and key on startup, or minting and the JWKS routes stay broken for it.
|
||||
StorageBackend<String, Cluster> clusterStore = new InMemoryStorage<>();
|
||||
StorageBackend<String, ClusterOidcKey> keyStore = new InMemoryStorage<>();
|
||||
|
||||
Cluster legacy = new Cluster();
|
||||
legacy.setName("legacy-cluster");
|
||||
legacy.setStatus(ClusterStatus.ACTIVE);
|
||||
clusterStore.put("legacy-cluster", legacy);
|
||||
assertNull(legacy.getIdentity());
|
||||
|
||||
EksOidcService oidcService = new EksOidcService(
|
||||
fixedStorageFactory(keyStore), new ObjectMapper());
|
||||
EksService restarted = new EksService(fixedStorageFactory(clusterStore), testConfig(),
|
||||
new RegionResolver("us-east-1", "000000000000"), null, null, oidcService);
|
||||
restarted.init();
|
||||
|
||||
Cluster migrated = restarted.describeCluster("legacy-cluster");
|
||||
assertNotNull(migrated.getIdentity());
|
||||
String issuer = migrated.getIdentity().getOidc().getIssuer();
|
||||
assertTrue(issuer.matches("https://oidc\\.eks\\.us-east-1\\.amazonaws\\.com/id/[A-F0-9]{32}"));
|
||||
assertTrue(oidcService.findVerificationKey(issuer).isPresent());
|
||||
}
|
||||
|
||||
@Test
|
||||
void initLeavesAnExistingOidcIssuerUnchanged() {
|
||||
StorageBackend<String, Cluster> clusterStore = new InMemoryStorage<>();
|
||||
StorageBackend<String, ClusterOidcKey> keyStore = new InMemoryStorage<>();
|
||||
|
||||
String issuer = "https://oidc.eks.us-east-1.amazonaws.com/id/ABCDEF0123456789ABCDEF0123456789";
|
||||
Cluster existing = new Cluster();
|
||||
existing.setName("existing-cluster");
|
||||
existing.setIdentity(new ClusterIdentity(new OidcIdentity(issuer)));
|
||||
clusterStore.put("existing-cluster", existing);
|
||||
|
||||
EksOidcService oidcService = new EksOidcService(
|
||||
fixedStorageFactory(keyStore), new ObjectMapper());
|
||||
EksService restarted = new EksService(fixedStorageFactory(clusterStore), testConfig(),
|
||||
new RegionResolver("us-east-1", "000000000000"), null, null, oidcService);
|
||||
restarted.init();
|
||||
|
||||
// The issuer a trust policy was written against must survive a restart, and its key must
|
||||
// be present so previously minted tokens still verify.
|
||||
assertEquals(issuer,
|
||||
restarted.describeCluster("existing-cluster").getIdentity().getOidc().getIssuer());
|
||||
assertTrue(oidcService.findVerificationKey(issuer).isPresent());
|
||||
}
|
||||
|
||||
@Test
|
||||
void initBackfillsUnderTheOwningAccountNotTheDefault() {
|
||||
// Startup has no request context, so the account-scoped put() resolves to the default
|
||||
// account. A cluster owned by another account must still be migrated in place, or the owner
|
||||
// keeps an issuer-less record while a duplicate appears under the default account.
|
||||
String otherAccount = "999999999999";
|
||||
StorageBackend<String, Cluster> rawClusters = new InMemoryStorage<>();
|
||||
StorageBackend<String, ClusterOidcKey> rawKeys = new InMemoryStorage<>();
|
||||
var clusterStore = new AccountAwareStorageBackend<>(rawClusters, null, "000000000000");
|
||||
var keyStore = new AccountAwareStorageBackend<>(rawKeys, null, "000000000000");
|
||||
|
||||
Cluster legacy = new Cluster();
|
||||
legacy.setName("legacy-cluster");
|
||||
legacy.setAccountId(otherAccount);
|
||||
legacy.setStatus(ClusterStatus.ACTIVE);
|
||||
clusterStore.putForAccount(otherAccount, "legacy-cluster", legacy);
|
||||
|
||||
EksOidcService oidcService = new EksOidcService(
|
||||
fixedStorageFactory(keyStore), new ObjectMapper());
|
||||
new EksService(fixedStorageFactory(clusterStore), testConfig(),
|
||||
new RegionResolver("us-east-1", "000000000000"), null, null, oidcService).init();
|
||||
|
||||
Cluster migrated = clusterStore.getForAccount(otherAccount, "legacy-cluster").orElseThrow();
|
||||
String issuer = migrated.getIdentity().getOidc().getIssuer();
|
||||
assertNotNull(issuer);
|
||||
// No duplicate stranded under the default account.
|
||||
assertTrue(clusterStore.getForAccount("000000000000", "legacy-cluster").isEmpty());
|
||||
// The signing key is stored under the owner too, and is still resolvable by issuer.
|
||||
assertTrue(keyStore.getForAccount(otherAccount, "legacy-cluster").isPresent());
|
||||
assertTrue(oidcService.findVerificationKey(issuer).isPresent());
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private StorageFactory fixedStorageFactory(StorageBackend<String, ?> backend) {
|
||||
return new StorageFactory(null, null) {
|
||||
@Override
|
||||
public <V> StorageBackend<String, V> create(String serviceName, String fileName,
|
||||
TypeReference<Map<String, V>> typeReference) {
|
||||
return (StorageBackend<String, V>) backend;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@Test
|
||||
void createClusterDuplicateFails() {
|
||||
CreateClusterRequest req = new CreateClusterRequest();
|
||||
@@ -202,7 +315,8 @@ class EksServiceTest {
|
||||
}
|
||||
};
|
||||
RegionResolver regionResolver = new RegionResolver("us-east-1", "000000000000");
|
||||
EksService service = new EksService(storageFactory, testConfig(), regionResolver, null, realEc2Service());
|
||||
EksService service = new EksService(storageFactory, testConfig(), regionResolver, null, realEc2Service(),
|
||||
new EksOidcService(storageFactory, new ObjectMapper()));
|
||||
|
||||
ResourcesVpcConfig vpcConfig = new ResourcesVpcConfig();
|
||||
vpcConfig.setSubnetIds(List.of("subnet-1", "subnet-2"));
|
||||
@@ -228,7 +342,8 @@ class EksServiceTest {
|
||||
}
|
||||
};
|
||||
RegionResolver regionResolver = new RegionResolver("us-east-1", "000000000000");
|
||||
EksService service = new EksService(storageFactory, testConfig(), regionResolver, null, realEc2Service());
|
||||
EksService service = new EksService(storageFactory, testConfig(), regionResolver, null, realEc2Service(),
|
||||
new EksOidcService(storageFactory, new ObjectMapper()));
|
||||
|
||||
ResourcesVpcConfig vpcConfig = new ResourcesVpcConfig();
|
||||
vpcConfig.setSubnetIds(List.of("subnet-default-a", "subnet-default-b"));
|
||||
@@ -261,7 +376,7 @@ class EksServiceTest {
|
||||
};
|
||||
RegionResolver regionResolver = new RegionResolver("us-east-1", "000000000000");
|
||||
EksService service = new EksService(storageFactory, testConfig(), regionResolver, null,
|
||||
realEc2Service());
|
||||
realEc2Service(), new EksOidcService(storageFactory, new ObjectMapper()));
|
||||
|
||||
ResourcesVpcConfig vpcConfig = new ResourcesVpcConfig();
|
||||
vpcConfig.setSubnetIds(List.of("subnet-default-a", "subnet-default-b"));
|
||||
@@ -290,7 +405,7 @@ class EksServiceTest {
|
||||
};
|
||||
RegionResolver regionResolver = new RegionResolver("eu-west-2", "000000000000");
|
||||
EksService service = new EksService(storageFactory, testConfig(), regionResolver, null,
|
||||
realEc2Service());
|
||||
realEc2Service(), new EksOidcService(storageFactory, new ObjectMapper()));
|
||||
|
||||
ResourcesVpcConfig vpcConfig = new ResourcesVpcConfig();
|
||||
vpcConfig.setSubnetIds(List.of("subnet-default-a"));
|
||||
@@ -336,7 +451,7 @@ class EksServiceTest {
|
||||
// The request is for eu-west-2, where that subnet does not exist.
|
||||
RegionResolver regionResolver = new RegionResolver("eu-west-2", "000000000000");
|
||||
EksService service = new EksService(storageFactory, testConfig(), regionResolver, null,
|
||||
ec2Service);
|
||||
ec2Service, new EksOidcService(storageFactory, new ObjectMapper()));
|
||||
|
||||
ResourcesVpcConfig vpcConfig = new ResourcesVpcConfig();
|
||||
vpcConfig.setSubnetIds(List.of(usEastOnlySubnet));
|
||||
|
||||
+244
@@ -0,0 +1,244 @@
|
||||
package io.github.hectorvent.floci.services.iam;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class WebIdentityTrustPolicyEvaluatorTest {
|
||||
|
||||
private static final String PREFIX =
|
||||
"oidc.eks.us-east-1.amazonaws.com/id/ABCDEF0123456789ABCDEF0123456789";
|
||||
private static final String PROVIDER_ARN = "arn:aws:iam::000000000000:oidc-provider/" + PREFIX;
|
||||
private static final String NAMESPACE = "my-namespace";
|
||||
private static final String SERVICE_ACCOUNT = "my-service-account";
|
||||
private static final String SUBJECT = "system:serviceaccount:" + NAMESPACE + ":" + SERVICE_ACCOUNT;
|
||||
|
||||
private final WebIdentityTrustPolicyEvaluator evaluator =
|
||||
new WebIdentityTrustPolicyEvaluator(new ObjectMapper());
|
||||
|
||||
/** The canonical IRSA trust policy shape. */
|
||||
private String irsaTrustPolicy(String subject) {
|
||||
return """
|
||||
{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [{
|
||||
"Effect": "Allow",
|
||||
"Principal": { "Federated": "%s" },
|
||||
"Action": "sts:AssumeRoleWithWebIdentity",
|
||||
"Condition": {
|
||||
"StringEquals": {
|
||||
"%s:sub": "%s",
|
||||
"%s:aud": "sts.amazonaws.com"
|
||||
}
|
||||
}
|
||||
}]
|
||||
}""".formatted(PROVIDER_ARN, PREFIX, subject, PREFIX);
|
||||
}
|
||||
|
||||
private Map<String, List<String>> claims(String subject) {
|
||||
return Map.of("sub", List.of(subject), "aud", List.of("sts.amazonaws.com"));
|
||||
}
|
||||
|
||||
private boolean allows(String policy, Map<String, List<String>> claims) {
|
||||
return evaluator.allows(policy, PROVIDER_ARN, PREFIX, claims);
|
||||
}
|
||||
|
||||
@Test
|
||||
void allowsMatchingSubjectAndAudience() {
|
||||
assertTrue(allows(irsaTrustPolicy(SUBJECT), claims(SUBJECT)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deniesDifferentServiceAccount() {
|
||||
assertFalse(allows(irsaTrustPolicy(SUBJECT),
|
||||
claims("system:serviceaccount:my-namespace:other-service-account")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deniesDifferentNamespace() {
|
||||
assertFalse(allows(irsaTrustPolicy(SUBJECT),
|
||||
claims("system:serviceaccount:other-ns:" + SERVICE_ACCOUNT)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void subjectComparisonIsCaseSensitive() {
|
||||
// globMatches lowercases both operands; OIDC subjects must not case-fold or a policy for
|
||||
// "my-service-account" would admit the distinct service account "My-Service-Account".
|
||||
assertFalse(allows(irsaTrustPolicy("system:serviceaccount:my-namespace:My-Service-Account"),
|
||||
claims(SUBJECT)));
|
||||
assertFalse(allows(irsaTrustPolicy(SUBJECT),
|
||||
claims("system:serviceaccount:my-namespace:My-Service-Account")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deniesWrongAudience() {
|
||||
Map<String, List<String>> claims = Map.of(
|
||||
"sub", List.of(SUBJECT), "aud", List.of("some.other.audience"));
|
||||
assertFalse(allows(irsaTrustPolicy(SUBJECT), claims));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deniesUnrelatedOidcProvider() {
|
||||
String policy = irsaTrustPolicy(SUBJECT);
|
||||
assertFalse(evaluator.allows(policy,
|
||||
"arn:aws:iam::000000000000:oidc-provider/oidc.eks.us-east-1.amazonaws.com/id/OTHER",
|
||||
PREFIX, claims(SUBJECT)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deniesConditionKeyedToAnotherProvider() {
|
||||
String policy = """
|
||||
{"Statement":[{"Effect":"Allow","Principal":{"Federated":"%s"},
|
||||
"Action":"sts:AssumeRoleWithWebIdentity","Condition":{"StringEquals":{
|
||||
"oidc.eks.us-east-1.amazonaws.com/id/SOMEONEELSE:sub":"%s"}}}]}"""
|
||||
.formatted(PROVIDER_ARN, SUBJECT);
|
||||
assertFalse(allows(policy, claims(SUBJECT)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deniesAwsPrincipalOnlyPolicy() {
|
||||
String policy = """
|
||||
{"Statement":[{"Effect":"Allow",
|
||||
"Principal":{"AWS":"arn:aws:iam::000000000000:root"},
|
||||
"Action":"sts:AssumeRoleWithWebIdentity"}]}""";
|
||||
assertFalse(allows(policy, claims(SUBJECT)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deniesWrongAction() {
|
||||
String policy = """
|
||||
{"Statement":[{"Effect":"Allow","Principal":{"Federated":"%s"},
|
||||
"Action":"sts:AssumeRole","Condition":{"StringEquals":{"%s:sub":"%s"}}}]}"""
|
||||
.formatted(PROVIDER_ARN, PREFIX, SUBJECT);
|
||||
assertFalse(allows(policy, claims(SUBJECT)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void allowsWildcardAction() {
|
||||
String policy = """
|
||||
{"Statement":[{"Effect":"Allow","Principal":{"Federated":"%s"},
|
||||
"Action":"sts:*","Condition":{"StringEquals":{"%s:sub":"%s"}}}]}"""
|
||||
.formatted(PROVIDER_ARN, PREFIX, SUBJECT);
|
||||
assertTrue(allows(policy, claims(SUBJECT)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void explicitDenyOverridesAllow() {
|
||||
String policy = """
|
||||
{"Statement":[
|
||||
{"Effect":"Allow","Principal":{"Federated":"%s"},
|
||||
"Action":"sts:AssumeRoleWithWebIdentity",
|
||||
"Condition":{"StringEquals":{"%s:sub":"%s"}}},
|
||||
{"Effect":"Deny","Principal":{"Federated":"%s"},
|
||||
"Action":"sts:AssumeRoleWithWebIdentity"}
|
||||
]}""".formatted(PROVIDER_ARN, PREFIX, SUBJECT, PROVIDER_ARN);
|
||||
assertFalse(allows(policy, claims(SUBJECT)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void allowsSubjectListContainingClaim() {
|
||||
String policy = """
|
||||
{"Statement":[{"Effect":"Allow","Principal":{"Federated":"%s"},
|
||||
"Action":"sts:AssumeRoleWithWebIdentity","Condition":{"StringEquals":{
|
||||
"%s:sub":["system:serviceaccount:my-namespace:other","%s"]}}}]}"""
|
||||
.formatted(PROVIDER_ARN, PREFIX, SUBJECT);
|
||||
assertTrue(allows(policy, claims(SUBJECT)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void allowsStringLikeWildcardSubject() {
|
||||
String policy = """
|
||||
{"Statement":[{"Effect":"Allow","Principal":{"Federated":"%s"},
|
||||
"Action":"sts:AssumeRoleWithWebIdentity","Condition":{"StringLike":{
|
||||
"%s:sub":"system:serviceaccount:my-namespace:*"}}}]}"""
|
||||
.formatted(PROVIDER_ARN, PREFIX);
|
||||
assertTrue(allows(policy, claims(SUBJECT)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void stringLikeComparisonIsCaseSensitive() {
|
||||
// StringLike must not fold case either, or a pattern scoped to one namespace would admit a
|
||||
// differently-cased one. The literal part of the pattern is what matters here.
|
||||
String policy = """
|
||||
{"Statement":[{"Effect":"Allow","Principal":{"Federated":"%s"},
|
||||
"Action":"sts:AssumeRoleWithWebIdentity","Condition":{"StringLike":{
|
||||
"%s:sub":"system:serviceaccount:My-Namespace:*"}}}]}"""
|
||||
.formatted(PROVIDER_ARN, PREFIX);
|
||||
assertFalse(allows(policy, claims(SUBJECT)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void stringNotLikeComparisonIsCaseSensitive() {
|
||||
// The claim differs from the pattern only by case, so it does NOT match, so StringNotLike
|
||||
// is satisfied and the statement allows.
|
||||
String policy = """
|
||||
{"Statement":[{"Effect":"Allow","Principal":{"Federated":"%s"},
|
||||
"Action":"sts:AssumeRoleWithWebIdentity","Condition":{"StringNotLike":{
|
||||
"%s:sub":"system:serviceaccount:MY-NAMESPACE:*"}}}]}"""
|
||||
.formatted(PROVIDER_ARN, PREFIX);
|
||||
assertTrue(allows(policy, claims(SUBJECT)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void caseSensitiveGlobHandlesWildcardsAndQuestionMarks() {
|
||||
assertTrue(WebIdentityTrustPolicyEvaluator.globMatchesCaseSensitive("abc", "abc"));
|
||||
assertFalse(WebIdentityTrustPolicyEvaluator.globMatchesCaseSensitive("abc", "ABC"));
|
||||
assertTrue(WebIdentityTrustPolicyEvaluator.globMatchesCaseSensitive("a*", "abcdef"));
|
||||
assertTrue(WebIdentityTrustPolicyEvaluator.globMatchesCaseSensitive("*f", "abcdef"));
|
||||
assertTrue(WebIdentityTrustPolicyEvaluator.globMatchesCaseSensitive("a*e?", "abcdef"));
|
||||
assertTrue(WebIdentityTrustPolicyEvaluator.globMatchesCaseSensitive("**abc**", "xxabcyy"));
|
||||
assertTrue(WebIdentityTrustPolicyEvaluator.globMatchesCaseSensitive("*", ""));
|
||||
assertFalse(WebIdentityTrustPolicyEvaluator.globMatchesCaseSensitive("a?c", "ac"));
|
||||
assertFalse(WebIdentityTrustPolicyEvaluator.globMatchesCaseSensitive("abc", "abcd"));
|
||||
assertFalse(WebIdentityTrustPolicyEvaluator.globMatchesCaseSensitive(null, "abc"));
|
||||
assertFalse(WebIdentityTrustPolicyEvaluator.globMatchesCaseSensitive("abc", null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void allowsFederatedPrincipalWithoutConditions() {
|
||||
String policy = """
|
||||
{"Statement":[{"Effect":"Allow","Principal":{"Federated":"%s"},
|
||||
"Action":"sts:AssumeRoleWithWebIdentity"}]}""".formatted(PROVIDER_ARN);
|
||||
assertTrue(allows(policy, claims(SUBJECT)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deniesUnsupportedConditionOperator() {
|
||||
String policy = """
|
||||
{"Statement":[{"Effect":"Allow","Principal":{"Federated":"%s"},
|
||||
"Action":"sts:AssumeRoleWithWebIdentity","Condition":{"DateGreaterThan":{
|
||||
"aws:CurrentTime":"2020-01-01T00:00:00Z"}}}]}""".formatted(PROVIDER_ARN);
|
||||
assertFalse(allows(policy, claims(SUBJECT)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deniesNullBlankOrMalformedPolicy() {
|
||||
assertFalse(allows(null, claims(SUBJECT)));
|
||||
assertFalse(allows("", claims(SUBJECT)));
|
||||
assertFalse(allows("{not json", claims(SUBJECT)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void handlesSingleStatementObject() {
|
||||
String policy = """
|
||||
{"Statement":{"Effect":"Allow","Principal":{"Federated":"%s"},
|
||||
"Action":"sts:AssumeRoleWithWebIdentity","Condition":{"StringEquals":{
|
||||
"%s:sub":"%s"}}}}""".formatted(PROVIDER_ARN, PREFIX, SUBJECT);
|
||||
assertTrue(allows(policy, claims(SUBJECT)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void conditionKeyPrefixIsCaseInsensitive() {
|
||||
// Condition *keys* are case-insensitive in AWS even though values are not.
|
||||
String policy = """
|
||||
{"Statement":[{"Effect":"Allow","Principal":{"Federated":"%s"},
|
||||
"Action":"STS:AssumeRoleWithWebIdentity","Condition":{"StringEquals":{
|
||||
"%s:SUB":"%s"}}}]}""".formatted(PROVIDER_ARN, PREFIX.toUpperCase(), SUBJECT);
|
||||
assertTrue(allows(policy, claims(SUBJECT)));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user