From 09a2cc01905d66b850eafea495cc94967fefeee5 Mon Sep 17 00:00:00 2001 From: Hector Ventura Date: Sat, 28 Nov 2026 20:34:31 -0600 Subject: [PATCH] fix(iam): accept the regional EUSC sign-in endpoint as a SAML recipient (#9698) Signed-off-by: Hector Ventura --- docs/configuration/partitions.md | 25 ++- .../floci/aws/core/common/AwsRegionFacts.java | 28 ++- .../CodePipelineEventPublisher.java | 4 +- .../iam/DelegationRequestService.java | 4 +- .../services/iam/SAMLAssertionVerifier.java | 66 +++++-- .../aws/services/iam/StsQueryHandler.java | 2 +- src/main/resources/aws/region-facts.json | 9 +- .../aws/core/common/AwsRegionFactsTest.java | 21 ++- .../CodePipelineEventPublisherTest.java | 6 +- ...RoleWithSamlValidationIntegrationTest.java | 168 +++++++++++++++++- .../iam/DelegationRequestServiceTest.java | 8 +- .../SAMLAssertionVerifierRecipientTest.java | 38 ++-- tools/aws/regen_region_facts.py | 71 +++++++- tools/aws/test_regen_region_facts.py | 83 ++++++++- 14 files changed, 472 insertions(+), 61 deletions(-) diff --git a/docs/configuration/partitions.md b/docs/configuration/partitions.md index 86c453c9ec..aa320f2366 100644 --- a/docs/configuration/partitions.md +++ b/docs/configuration/partitions.md @@ -124,13 +124,24 @@ a colon in that setting. Existing stored namespaces are not migrated or deleted ids are the same literal in every partition, as the Sign-In model spells them. - **Hosted zones and console URLs**: load balancer and S3 website hosted zone ids come from a per-region table (`aws/region-facts.json`, generated from the Terraform provider and the CDK, - which transcribe the AWS General Reference, and from the General Reference itself and the China - and GovCloud user guides); Network + which transcribe the AWS General Reference, and from the General Reference itself and the China, + GovCloud and EUSC user guides); Network load balancers have their own zone, distinct from the Application/Classic one. The CloudFront - hosted zone is published for `aws` and `aws-cn`; the SAML sign-on URL for five partitions. The console link in a CodePipeline + hosted zone is published for `aws` and `aws-cn`; the SAML sign-on URL for five partitions. An + assertion may also be addressed to a Region's sign-in endpoint, as the + [commercial](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_enable-console-saml.html) + and [EUSC](https://docs.aws.eu/IAM/latest/UserGuide/id_roles_providers_enable-console-saml.html) + IAM guides give it, with or without the provider id: `https://us-east-1.signin.aws.amazon.com/saml` + and `https://us-east-1.signin.aws.amazon.com/saml/acs/` beside the sign-on URL in + `aws`, and `https://eusc-de-east-1.signin.amazonaws-eusc.eu/saml` and + `https://eusc-de-east-1.signin.amazonaws-eusc.eu/saml/acs/`, the only forms, in + `aws-eusc`. Floci assigns a SAML provider no id, so any id of the + `SAMLProviderUUID` shape is accepted. A trust policy's `saml:aud` is tested against the endpoint + the assertion was accepted for. The console link in a CodePipeline approval notification uses the console host of the pipeline's partition (`console.amazonaws.cn` - in China, `console.amazonaws-us-gov.com` in GovCloud), as the China and GovCloud user guides - state it; the path after the host is the commercial console's. A generated CloudFront + in China, `console.amazonaws-us-gov.com` in GovCloud, `eusc-de-east-1.console.amazonaws-eusc.eu` + in EUSC), as the China, GovCloud and EUSC user guides state it; the path after the host is the + commercial console's. A generated CloudFront distribution domain name ends in `cloudfront.cn` in China, as the China guide names the default CloudFront domain, unless `floci.services.cloudfront.domain-suffix` is set. A regional API Gateway custom domain reports the regional hosted zone the AWS General Reference publishes for its region. @@ -278,9 +289,9 @@ the commercial value or Floci's own base host until sourced: (`us-iso-east-1-az1`), where the other partitions get AWS's short prefix (`use1-az1`, `usgw1-az1`, `cnn1-az1`); - S3 `LocationConstraint` enum values and Route 53 hosted zones for the ISO and EUSC regions; -- the management console host in the ISO and EUSC partitions, where a CodePipeline approval +- the management console host in the ISO partitions, where a CodePipeline approval notification keeps linking to the commercial `console.aws.amazon.com`; -- the SAML sign-on URL in `aws-iso-e`, `aws-iso-f` and `aws-eusc`, where assertions keep being +- the SAML sign-on URL in `aws-iso-e` and `aws-iso-f`, where assertions keep being checked against the commercial `https://signin.aws.amazon.com/saml`; - the exact error AWS WAF returns for the `CLOUDFRONT` scope in a partition without CloudFront (GovCloud, the ISO partitions): Floci refuses it with `WAFInvalidParameterException` and its own diff --git a/src/main/java/io/floci/aws/core/common/AwsRegionFacts.java b/src/main/java/io/floci/aws/core/common/AwsRegionFacts.java index 67ffdfc3ac..193f1872db 100644 --- a/src/main/java/io/floci/aws/core/common/AwsRegionFacts.java +++ b/src/main/java/io/floci/aws/core/common/AwsRegionFacts.java @@ -13,9 +13,9 @@ import java.util.Set; /** * The per-region and per-partition constants AWS publishes only as prose tables, vendored in * {@code aws/region-facts.json} by {@code tools/aws/regen_region_facts.py} from the Terraform - * provider, the CDK, the botocore models, the API Gateway General Reference page and the China and - * GovCloud user guides: load balancer, S3 website and API Gateway regional hosted zone ids, the CloudFront hosted zone and distribution - * domain suffix per partition, the SAML sign-on URL and the management console host per partition + * provider, the CDK, the botocore models, the API Gateway General Reference page and the China, GovCloud + * and EUSC user guides: load balancer, S3 website and API Gateway regional hosted zone ids, the CloudFront hosted zone and distribution + * domain suffix per partition, the SAML sign-on URL or regional SAML endpoint and the management console host per partition * and the VPC endpoint service-name prefixes. Every accessor is {@link Optional}: the ISO and EUSC partitions have no published * hosted zones, and a service that needs one there has nothing faithful to answer. */ @@ -81,9 +81,29 @@ public final class AwsRegionFacts { return partitionText(partition, "samlSignOnUrl"); } + /** + * The regional sign-in endpoint with the SAML provider's id a SAML assertion may be addressed to, + * with {@code {region}} and {@code {id}} placeholders, as the IAM guide of {@code aws} and + * {@code aws-eusc} gives it ({@code https://{region}.signin.amazonaws-eusc.eu/saml/acs/{id}}); + * absent everywhere else. + */ + public static Optional samlRegionalAcsUrl(String partition) { + return partitionText(partition, "samlRegionalAcsUrl"); + } + + /** + * The regional sign-in endpoint without the provider's id, with a {@code {region}} placeholder, as the + * SAML assertions page of the {@code aws} and {@code aws-eusc} IAM guides gives it + * ({@code https://{region}.signin.amazonaws-eusc.eu/saml}); absent everywhere else. + */ + public static Optional samlRegionalSignInUrl(String partition) { + return partitionText(partition, "samlRegionalSignInUrl"); + } + /** * The management console host, without a scheme. Stated by the user guides for {@code aws}, - * {@code aws-cn} and {@code aws-us-gov}; absent for the ISO partitions and {@code aws-eusc}. + * {@code aws-cn}, {@code aws-us-gov} and {@code aws-eusc} (whose guide names the regional + * {@code eusc-de-east-1.console.amazonaws-eusc.eu}); absent for the ISO partitions. */ public static Optional consoleHost(String partition) { return partitionText(partition, "consoleHost"); diff --git a/src/main/java/io/floci/aws/services/codepipeline/CodePipelineEventPublisher.java b/src/main/java/io/floci/aws/services/codepipeline/CodePipelineEventPublisher.java index a0bbbd38cf..c58aa996c1 100644 --- a/src/main/java/io/floci/aws/services/codepipeline/CodePipelineEventPublisher.java +++ b/src/main/java/io/floci/aws/services/codepipeline/CodePipelineEventPublisher.java @@ -141,8 +141,8 @@ public class CodePipelineEventPublisher { /** * The CodePipeline console page on the console host of the pipeline's partition, derived * from the execution's region because this runs with no request context. The user guides - * state the host for the commercial, China and GovCloud partitions; the ISO and EUSC - * partitions have no published one and keep the commercial host. The path is the commercial + * state the host for the commercial, China, GovCloud and EUSC partitions; the ISO partitions + * have no published one and keep the commercial host. The path is the commercial * console's in every partition: no source gives the per-service path per partition. */ private static String consoleUrl(String region) { diff --git a/src/main/java/io/floci/aws/services/iam/DelegationRequestService.java b/src/main/java/io/floci/aws/services/iam/DelegationRequestService.java index ad1145abfa..17a05ca9ee 100644 --- a/src/main/java/io/floci/aws/services/iam/DelegationRequestService.java +++ b/src/main/java/io/floci/aws/services/iam/DelegationRequestService.java @@ -924,8 +924,8 @@ public class DelegationRequestService implements DelegationRequestOwnership, Res } /** - * The deep link on the console host of the region's partition. The China and GovCloud user - * guides state a host; the EUSC and ISO partitions publish none and keep the commercial one. + * The deep link on the console host of the region's partition. The China, GovCloud and EUSC + * user guides state a host; the ISO partitions publish none and keep the commercial one. */ private static String consoleDeepLink(String region, String id) { String host = AwsRegionFacts.consoleHost(AwsRegions.partitionFor(region)) diff --git a/src/main/java/io/floci/aws/services/iam/SAMLAssertionVerifier.java b/src/main/java/io/floci/aws/services/iam/SAMLAssertionVerifier.java index 645b4fdaf1..60235a2c8a 100644 --- a/src/main/java/io/floci/aws/services/iam/SAMLAssertionVerifier.java +++ b/src/main/java/io/floci/aws/services/iam/SAMLAssertionVerifier.java @@ -1,6 +1,8 @@ package io.floci.aws.services.iam; import io.floci.aws.core.common.AwsArnUtils; +import io.floci.aws.core.common.AwsPartition; +import io.floci.aws.core.common.AwsPartitions; import io.floci.aws.core.common.AwsRegionFacts; import io.floci.aws.core.common.Digests; import io.floci.aws.services.iam.model.SAMLProvider; @@ -26,14 +28,21 @@ import java.util.Base64; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.Set; +import java.util.regex.Matcher; import java.util.regex.Pattern; +import java.util.stream.Collectors; +import java.util.stream.Stream; /** Verifies the specific SAML assertion contract consumed by STS. */ final class SAMLAssertionVerifier { private static final String SAML = "urn:oasis:names:tc:SAML:2.0:assertion"; private static final String DS = "http://www.w3.org/2000/09/xmldsig#"; private static final String AUDIENCE = "urn:amazon:webservices"; + private static final Pattern TEMPLATE_PLACEHOLDER = Pattern.compile("\\{(region|id)}"); + /** The shape of IAM's {@code SAMLProviderUUID} ({@code privateKeyIdType} in the IAM model). */ + private static final String SAML_PROVIDER_ID = "[A-Z0-9]{22,64}"; static final String ASSERTION_INVALID = "The SAML assertion is invalid."; static final String SIGNATURE_INVALID = "Response signature invalid"; private static final String ROLE_SESSION_NAME = "https://aws.amazon.com/SAML/Attributes/RoleSessionName"; @@ -63,11 +72,12 @@ final class SAMLAssertionVerifier { * {@code roleSessionName} is null when the assertion carries no RoleSessionName attribute, * {@code principalTags} is empty when it carries no session tags, and * {@code transitiveTagKeys} is empty when it asks for none to be transitive, which is AWS's - * default for a session. + * default for a session. {@code recipient} is the sign-in endpoint the bearer confirmation was + * accepted for, the endpoint a trust policy tests as {@code saml:aud}. */ record Verified(String issuer, String subject, String subjectType, String nameQualifier, Instant expiration, List roles, String roleSessionName, - Map principalTags, List transitiveTagKeys) {} + Map principalTags, List transitiveTagKeys, String recipient) {} record RolePair(String roleArn, String principalArn) {} static Verified verify(String encoded, SAMLProvider provider, Instant now) throws InvalidAssertionException { @@ -149,7 +159,7 @@ final class SAMLAssertionVerifier { if (confirmations == null || confirmations.getLength() == 0) { throw invalid("subject confirmation missing"); } - boolean validBearer = false; + String acceptedRecipient = null; for (int i = 0; i < confirmations.getLength(); i++) { Element confirmation = (Element) confirmations.item(i); if (!"urn:oasis:names:tc:SAML:2.0:cm:bearer".equals(confirmation.getAttribute("Method"))) { @@ -161,13 +171,13 @@ final class SAMLAssertionVerifier { } String recipient = confirmationData.getAttribute("Recipient"); Instant confirmationExpiry = instant(confirmationData.getAttribute("NotOnOrAfter")); - if (expectedRecipient(provider).equals(recipient) + if (acceptsRecipient(provider, recipient) && confirmationExpiry != null && now.isBefore(confirmationExpiry)) { - validBearer = true; + acceptedRecipient = recipient; break; } } - if (!validBearer) { + if (acceptedRecipient == null) { throw invalid("valid bearer subject confirmation missing"); } @@ -200,7 +210,7 @@ final class SAMLAssertionVerifier { String nameQualifier = Base64.getEncoder().encodeToString( Digests.sha1((issuer + provider.getArn()).getBytes(StandardCharsets.UTF_8))); return new Verified(issuer, name, subjectType, nameQualifier, notOnOrAfter, roles, - roleSessionName, principalTags(attributes), transitiveTagKeys(attributes)); + roleSessionName, principalTags(attributes), transitiveTagKeys(attributes), acceptedRecipient); } catch (InvalidAssertionException e) { throw e; } catch (Exception e) { @@ -359,16 +369,46 @@ final class SAMLAssertionVerifier { } /** - * The console sign-on URL a bearer assertion must name, in the provider's partition. The CDK - * publishes none for {@code aws-iso-e}, {@code aws-iso-f} and {@code aws-eusc}; there the + * Whether {@code recipient} is a sign-in endpoint a bearer assertion may name, in the provider's + * partition: the console sign-on URL where the partition has one, and the regional forms where its + * IAM guide gives them. The commercial and EUSC guides address the assertion to a Region's sign-in + * endpoint, {@code https://region-code.signin.amazonaws-eusc.eu/saml}, or with the provider's id in + * the path, {@code https://region-code.signin.amazonaws-eusc.eu/saml/acs/SAMLSP4SHN3UIS2D558H46}; EUSC + * has only these. Any published Region of the partition and an id of the {@code SAMLProviderUUID} + * shape IAM's model gives ({@code [A-Z0-9]{22,64}}) is accepted there. Floci assigns a provider no such id, + * so the id is not compared. Where neither is published ({@code aws-iso-e}, {@code aws-iso-f}) the * commercial URL is kept, as every partition used before the per-partition table, rather than * refusing every assertion. */ // Package-private for unit testing. - static String expectedRecipient(SAMLProvider provider) { + static boolean acceptsRecipient(SAMLProvider provider, String recipient) { + if (recipient == null) { + return false; + } String partition = AwsArnUtils.parse(provider.getArn()).partition(); - return AwsRegionFacts.samlSignOnUrl(partition) - .or(() -> AwsRegionFacts.samlSignOnUrl("aws")) - .orElseThrow(); + Optional signOnUrl = AwsRegionFacts.samlSignOnUrl(partition); + List regional = Stream.of(AwsRegionFacts.samlRegionalAcsUrl(partition), + AwsRegionFacts.samlRegionalSignInUrl(partition)).flatMap(Optional::stream).toList(); + if (signOnUrl.isEmpty() && regional.isEmpty()) { + return AwsRegionFacts.samlSignOnUrl("aws").orElseThrow().equals(recipient); + } + return signOnUrl.map(recipient::equals).orElse(false) + || regional.stream().anyMatch(template -> regionalRecipient(template, partition).matcher(recipient).matches()); + } + + /** {@code template}'s {@code {region}} as any published Region of {@code partition} and {@code {id}} as a provider id. */ + private static Pattern regionalRecipient(String template, String partition) { + List regions = AwsPartitions.find(partition).map(AwsPartition::regionIds).orElse(List.of()); + String regionAlternatives = regions.stream().map(Pattern::quote).collect(Collectors.joining("|", "(?:", ")")); + StringBuilder regex = new StringBuilder(); + Matcher placeholders = TEMPLATE_PLACEHOLDER.matcher(template); + int literalStart = 0; + while (placeholders.find()) { + regex.append(Pattern.quote(template.substring(literalStart, placeholders.start()))); + regex.append("region".equals(placeholders.group(1)) ? regionAlternatives : SAML_PROVIDER_ID); + literalStart = placeholders.end(); + } + regex.append(Pattern.quote(template.substring(literalStart))); + return Pattern.compile(regex.toString()); } } diff --git a/src/main/java/io/floci/aws/services/iam/StsQueryHandler.java b/src/main/java/io/floci/aws/services/iam/StsQueryHandler.java index bbce7ca701..8402542cef 100644 --- a/src/main/java/io/floci/aws/services/iam/StsQueryHandler.java +++ b/src/main/java/io/floci/aws/services/iam/StsQueryHandler.java @@ -1100,7 +1100,7 @@ public class StsQueryHandler { IamRole role = iamService.findRole(accountId, roleName).orElseThrow(() -> new AwsException("AccessDenied", "Not authorized to perform sts:AssumeRoleWithSAML on resource: " + roleArn, 403)); Map> assertionClaims = Map.of( - "aud", List.of(STS_AUDIENCE), + "aud", List.of(verified.recipient()), "iss", List.of(verified.issuer()), "sub", List.of(verified.subject()), "namequalifier", List.of(verified.nameQualifier())); diff --git a/src/main/resources/aws/region-facts.json b/src/main/resources/aws/region-facts.json index 0ab52962cb..3147da09b1 100644 --- a/src/main/resources/aws/region-facts.json +++ b/src/main/resources/aws/region-facts.json @@ -4,7 +4,7 @@ "rds": "https://docs.aws.amazon.com/cli/v1/reference/rds/describe-db-instances.html", "terraform": "terraform-provider-aws internal/service/elb/hosted_zone_id_data_source.go, internal/service/elbv2/hosted_zone_id_data_source.go, internal/service/s3/hosted_zones.go, internal/conns/awsclient.go", "cdk": "aws-cdk packages/aws-cdk-lib/region-info/build-tools/fact-tables.ts, packages/aws-cdk-lib/aws-route53-targets/lib/cloudfront-target.ts, packages/aws-cdk-lib/aws-ec2/lib/vpc-endpoint.ts", - "docs": "aws-docs/partition-guides (snapshots of AWS guides and CLI examples) cn/cloudfront.md, cn/console.md, gov/configure-account.md, gov/govcloud-abp.md, gov/govcloud-organizations.md, rds/describe-db-instances.txt", + "docs": "aws-docs/partition-guides (snapshots of AWS guides and CLI examples) aws/id_roles_providers_create_saml_assertions.md, aws/id_roles_providers_enable-console-saml.md, cn/cloudfront.md, cn/console.md, eusc/id_roles_providers_create_saml_assertions.md, eusc/id_roles_providers_enable-console-saml.md, eusc/id_users_sign-in.md, gov/configure-account.md, gov/govcloud-abp.md, gov/govcloud-organizations.md, rds/describe-db-instances.txt", "apiGatewayRegionalHostedZones": "https://docs.aws.amazon.com/general/latest/gr/apigateway.html (data plane table, snapshot aws-docs/gr-apigateway.md)", "botocore": "botocore cloudfront/2020-05-31/service-2.json (Distribution$DomainName, DistributionSummary$DomainName)", "s3WebsiteConflicts": "terraform wins over the CDK where they disagree (it cites the S3 website-endpoint table)" @@ -14,6 +14,8 @@ "vpcEndpointServiceNamePrefix": "com.amazonaws.vpce", "cloudfrontHostedZoneId": "Z2FDTNDATAQYW2", "samlSignOnUrl": "https://signin.aws.amazon.com/saml", + "samlRegionalAcsUrl": "https://{region}.signin.aws.amazon.com/saml/acs/{id}", + "samlRegionalSignInUrl": "https://{region}.signin.aws.amazon.com/saml", "consoleHost": "console.aws.amazon.com", "cloudfrontDomainSuffix": "cloudfront.net" }, @@ -25,7 +27,10 @@ "cloudfrontDomainSuffix": "cloudfront.cn" }, "aws-eusc": { - "vpcEndpointServiceNamePrefix": "eu.amazonaws.vpce" + "vpcEndpointServiceNamePrefix": "eu.amazonaws.vpce", + "samlRegionalAcsUrl": "https://{region}.signin.amazonaws-eusc.eu/saml/acs/{id}", + "samlRegionalSignInUrl": "https://{region}.signin.amazonaws-eusc.eu/saml", + "consoleHost": "eusc-de-east-1.console.amazonaws-eusc.eu" }, "aws-iso": { "vpcEndpointServiceNamePrefix": "gov.ic.c2s.vpce", diff --git a/src/test/java/io/floci/aws/core/common/AwsRegionFactsTest.java b/src/test/java/io/floci/aws/core/common/AwsRegionFactsTest.java index 02229a9c54..53261311a3 100644 --- a/src/test/java/io/floci/aws/core/common/AwsRegionFactsTest.java +++ b/src/test/java/io/floci/aws/core/common/AwsRegionFactsTest.java @@ -57,14 +57,31 @@ class AwsRegionFactsTest { assertTrue(AwsRegionFacts.samlSignOnUrl(null).isEmpty()); } - /** The hosts the China and GovCloud user guides state; no guide covers the ISO or EUSC partitions. */ + /** The commercial and EUSC IAM guides address an assertion to a Region's sign-in endpoint; no other guide does. */ + @Test + void theRegionalSamlEndpointIsTheCommercialAndEuscGuidesForm() { + assertEquals(Optional.of("https://{region}.signin.amazonaws-eusc.eu/saml/acs/{id}"), + AwsRegionFacts.samlRegionalAcsUrl("aws-eusc")); + assertEquals(Optional.of("https://{region}.signin.aws.amazon.com/saml/acs/{id}"), + AwsRegionFacts.samlRegionalAcsUrl("aws")); + assertTrue(AwsRegionFacts.samlRegionalAcsUrl("aws-cn").isEmpty()); + assertEquals(Optional.of("https://{region}.signin.aws.amazon.com/saml"), + AwsRegionFacts.samlRegionalSignInUrl("aws")); + assertEquals(Optional.of("https://{region}.signin.amazonaws-eusc.eu/saml"), + AwsRegionFacts.samlRegionalSignInUrl("aws-eusc")); + assertTrue(AwsRegionFacts.samlRegionalSignInUrl("aws-cn").isEmpty()); + assertTrue(AwsRegionFacts.samlRegionalAcsUrl("aws-iso-e").isEmpty()); + assertTrue(AwsRegionFacts.samlRegionalAcsUrl(null).isEmpty()); + } + + /** The hosts the China, GovCloud and EUSC user guides state; no guide covers the ISO partitions. */ @Test void consoleHostIsPerPartitionWhereAGuideStatesIt() { assertEquals(Optional.of("console.aws.amazon.com"), AwsRegionFacts.consoleHost("aws")); assertEquals(Optional.of("console.amazonaws.cn"), AwsRegionFacts.consoleHost("aws-cn")); assertEquals(Optional.of("console.amazonaws-us-gov.com"), AwsRegionFacts.consoleHost("aws-us-gov")); assertTrue(AwsRegionFacts.consoleHost("aws-iso").isEmpty()); - assertTrue(AwsRegionFacts.consoleHost("aws-eusc").isEmpty()); + assertEquals(Optional.of("eusc-de-east-1.console.amazonaws-eusc.eu"), AwsRegionFacts.consoleHost("aws-eusc")); assertTrue(AwsRegionFacts.consoleHost(null).isEmpty()); } diff --git a/src/test/java/io/floci/aws/services/codepipeline/CodePipelineEventPublisherTest.java b/src/test/java/io/floci/aws/services/codepipeline/CodePipelineEventPublisherTest.java index 28da84a679..7f76f6d3a5 100644 --- a/src/test/java/io/floci/aws/services/codepipeline/CodePipelineEventPublisherTest.java +++ b/src/test/java/io/floci/aws/services/codepipeline/CodePipelineEventPublisherTest.java @@ -90,15 +90,15 @@ class CodePipelineEventPublisherTest { } /** - * The console host follows the pipeline's partition where a user guide states one; EUSC and - * ISO have no published host and keep the commercial one. + * The console host follows the pipeline's partition where a user guide states one; ISO has no + * published host and keeps the commercial one. */ @ParameterizedTest @CsvSource({ "us-east-1, console.aws.amazon.com", "cn-north-1, console.amazonaws.cn", "us-gov-west-1, console.amazonaws-us-gov.com", - "eusc-de-east-1, console.aws.amazon.com", + "eusc-de-east-1, eusc-de-east-1.console.amazonaws-eusc.eu", "us-iso-east-1, console.aws.amazon.com"}) void approvalLinksUseTheConsoleHostOfThePipelinesPartition(String region, String host) throws Exception { CodePipelineEventPublisher publisher = diff --git a/src/test/java/io/floci/aws/services/iam/AssumeRoleWithSamlValidationIntegrationTest.java b/src/test/java/io/floci/aws/services/iam/AssumeRoleWithSamlValidationIntegrationTest.java index fafb94f44c..9d60e70b0b 100644 --- a/src/test/java/io/floci/aws/services/iam/AssumeRoleWithSamlValidationIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/iam/AssumeRoleWithSamlValidationIntegrationTest.java @@ -84,6 +84,8 @@ class AssumeRoleWithSamlValidationIntegrationTest { private static final String PROVIDER = "arn:aws:iam::" + ACCOUNT + ":saml-provider/" + PROVIDER_NAME; private static final String AUDIENCE = "urn:amazon:webservices"; private static final String SAML_NS = "urn:oasis:names:tc:SAML:2.0:assertion"; + private static final String COMMERCIAL_RECIPIENT = "https://signin.aws.amazon.com/saml"; + private static final String EUSC_REGION = "eusc-de-east-1"; @TestHTTPResource URI endpoint; @@ -141,6 +143,149 @@ class AssumeRoleWithSamlValidationIntegrationTest { .statusCode(400).body(containsString("InvalidIdentityToken")); } + /** + * The EUSC IAM guide addresses the assertion to the Region's sign-in endpoint, a trust policy + * there testing {@code "saml:aud": "https://region-code.signin.amazonaws-eusc.eu/saml/acs/SAMLSP4SHN3UIS2D558H46"} + * (docs.aws.eu/IAM/latest/UserGuide/id_roles_providers_enable-console-saml.html); the commercial + * sign-in URL appears nowhere in it. + */ + @Test + void anEuscAssertionAddressedToTheRegionalEuscSignInEndpointIsAccepted() { + EuscFixture eusc = new EuscFixture(); + try { + eusc.assume(assertionAddressedTo(eusc.role, eusc.provider, + "https://" + EUSC_REGION + ".signin.amazonaws-eusc.eu/saml/acs/SAMLSP4SHN3UIS2D558H46")) + .statusCode(200) + .body("AssumeRoleWithSAMLResponse.AssumeRoleWithSAMLResult.AssumedRoleUser.Arn", + startsWith("arn:aws-eusc:sts::" + ACCOUNT + ":assumed-role/")); + } finally { + eusc.delete(); + } + } + + /** + * {@code saml:aud} "Filters access by the endpoint URL to which SAML assertions are presented" + * (Service Authorization Reference, {@code sts:AssumeRoleWithSAML}): the recipient the assertion + * was accepted for, which the console trust policy tests as {@code https://signin.aws.amazon.com/saml}. + */ + @Test + void trustPolicyTestingSamlAudAgainstTheSignInEndpointAllowsTheAssertionAddressedToIt() { + String role = createRoleWithCondition("{\"StringEquals\":{\"saml:aud\":\"" + COMMERCIAL_RECIPIENT + "\"}}"); + assume(role, assertion(role, PROVIDER, Instant.now().plusSeconds(300), AUDIENCE, ISSUER, true), PROVIDER) + .statusCode(200); + } + + @Test + void trustPolicyTestingSamlAudAgainstAnotherEndpointRefusesTheAssertion() { + String role = createRoleWithCondition("{\"StringEquals\":{\"saml:aud\":\"https://signin.example.test/saml\"}}"); + assume(role, assertion(role, PROVIDER, Instant.now().plusSeconds(300), AUDIENCE, ISSUER, true), PROVIDER) + .statusCode(403).body(containsString("AccessDenied")); + } + + /** + * The commercial guide's trust policy tests the regional form too, + * {@code "saml:aud": "https://region-code.signin.aws.amazon.com/saml/acs/SAMLSP4SHN3UIS2D558H46"}, and recommends + * regional endpoints for {@code saml:aud}. + */ + @Test + void aCommercialAssertionAddressedToARegionalSignInEndpointMeetsTheGuidesTrustPolicy() { + String recipient = "https://us-east-1.signin.aws.amazon.com/saml/acs/SAMLSP4SHN3UIS2D558H46"; + String role = createRoleWithCondition("{\"StringEquals\":{\"saml:aud\":\"" + recipient + "\"}}"); + assume(role, assertionAddressedTo(role, PROVIDER, recipient), PROVIDER).statusCode(200); + } + + /** + * The EUSC guide's SAML assertions page gives the regional sign-in URL without the provider id too, + * {@code https://region-code.signin.amazonaws-eusc.eu/saml}, with the region code required. + */ + @Test + void anEuscAssertionAddressedToTheRegionalSignInUrlWithoutAnIdIsAccepted() { + String recipient = "https://" + EUSC_REGION + ".signin.amazonaws-eusc.eu/saml"; + EuscFixture eusc = new EuscFixture("{\"StringEquals\":{\"saml:aud\":\"" + recipient + "\"}}"); + try { + eusc.assume(assertionAddressedTo(eusc.role, eusc.provider, recipient)).statusCode(200); + } finally { + eusc.delete(); + } + } + + /** The EUSC guide's own trust policy: {@code saml:aud} is the regional endpoint the assertion names. */ + @Test + void anEuscTrustPolicyTestingTheRegionalSamlAudAllowsTheAssertionAddressedToIt() { + String recipient = "https://" + EUSC_REGION + ".signin.amazonaws-eusc.eu/saml/acs/SAMLSP4SHN3UIS2D558H46"; + EuscFixture eusc = new EuscFixture("{\"StringEquals\":{\"saml:aud\":\"" + recipient + "\"}}"); + try { + eusc.assume(assertionAddressedTo(eusc.role, eusc.provider, recipient)).statusCode(200); + } finally { + eusc.delete(); + } + } + + @Test + void anEuscAssertionAddressedToTheCommercialSignInOrAnotherHostIsRejected() { + EuscFixture eusc = new EuscFixture(); + try { + for (String recipient : List.of(COMMERCIAL_RECIPIENT, + "https://signin.amazonaws-eusc.eu/saml", + "https://us-east-1.signin.amazonaws-eusc.eu/saml/acs/SAMLSP4SHN3UIS2D558H46", + "https://" + EUSC_REGION + ".signin.example.test/saml/acs/SAMLSP4SHN3UIS2D558H46")) { + eusc.assume(assertionAddressedTo(eusc.role, eusc.provider, recipient)) + .statusCode(400).body("ErrorResponse.Error.Code", equalTo("InvalidIdentityToken")); + } + } finally { + eusc.delete(); + } + } + + /** A SAML provider and a role trusting it, both created by requests signed for the EUSC Region. */ + private static final class EuscFixture { + private final String providerName = "eusc-saml-" + UUID.randomUUID().toString().substring(0, 8); + private final String roleName = "eusc-saml-role-" + UUID.randomUUID().toString().substring(0, 8); + final String provider; + final String role; + + private EuscFixture() { + this(null); + } + + private EuscFixture(String condition) { + provider = given().contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateSAMLProvider").formParam("Name", providerName) + .formParam("SAMLMetadataDocument", SamlMetadata.forEntity(ISSUER, certificateBase64)) + .header("Authorization", auth("iam", EUSC_REGION)).when().post("/") + .then().statusCode(200) + .extract().xmlPath().getString("CreateSAMLProviderResponse.CreateSAMLProviderResult.SAMLProviderArn"); + role = given().contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateRole").formParam("RoleName", roleName) + .formParam("AssumeRolePolicyDocument", "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":" + + "\"Allow\",\"Principal\":{\"Federated\":\"" + provider + "\"}," + + "\"Action\":\"sts:AssumeRoleWithSAML\"" + + (condition == null ? "" : ",\"Condition\":" + condition) + "}]}") + .header("Authorization", auth("iam", EUSC_REGION)).when().post("/") + .then().statusCode(200) + .extract().xmlPath().getString("CreateRoleResponse.CreateRoleResult.Role.Arn"); + } + + ValidatableResponse assume(String assertion) { + return given().contentType("application/x-www-form-urlencoded") + .formParam("Action", "AssumeRoleWithSAML") + .formParam("RoleArn", role) + .formParam("PrincipalArn", provider) + .formParam("SAMLAssertion", assertion) + .header("Authorization", auth("sts", EUSC_REGION)) + .when().post("/").then(); + } + + void delete() { + given().contentType("application/x-www-form-urlencoded").formParam("Action", "DeleteRole") + .formParam("RoleName", roleName).header("Authorization", auth("iam", EUSC_REGION)) + .when().post("/").then().statusCode(200); + given().contentType("application/x-www-form-urlencoded").formParam("Action", "DeleteSAMLProvider") + .formParam("SAMLProviderArn", provider).header("Authorization", auth("iam", EUSC_REGION)) + .when().post("/").then().statusCode(200); + } + } + @Test void wrongIssuerIsRejected() { String role = createRole(true); @@ -788,7 +933,11 @@ class AssumeRoleWithSamlValidationIntegrationTest { } private static String auth(String service) { - return "AWS4-HMAC-SHA256 Credential=" + ACCOUNT + "/20260907/us-east-1/" + service + return auth(service, "us-east-1"); + } + + private static String auth(String service, String region) { + return "AWS4-HMAC-SHA256 Credential=" + ACCOUNT + "/20260907/" + region + "/" + service + "/aws4_request, SignedHeaders=host, Signature=test"; } @@ -849,6 +998,21 @@ class AssumeRoleWithSamlValidationIntegrationTest { Function> transforms, String roleSessionName, Map> principalTags, List transitiveTagKeys) { + return assertion(role, provider, expiry, audience, issuer, sign, unrelatedConfirmation, transforms, + roleSessionName, principalTags, transitiveTagKeys, COMMERCIAL_RECIPIENT); + } + + /** A valid signed assertion for {@code role} whose bearer confirmation names {@code recipient}. */ + private static String assertionAddressedTo(String role, String provider, String recipient) { + return assertion(role, provider, Instant.now().plusSeconds(300), AUDIENCE, ISSUER, true, false, + factory -> List.of(enveloped(factory)), null, Map.of(), List.of(), recipient); + } + + private static String assertion(String role, String provider, Instant expiry, String audience, + String issuer, boolean sign, boolean unrelatedConfirmation, + Function> transforms, + String roleSessionName, Map> principalTags, + List transitiveTagKeys, String recipient) { String sessionNameAttribute = roleSessionName == null ? "" : "" + roleSessionName + ""; @@ -876,7 +1040,7 @@ class AssumeRoleWithSamlValidationIntegrationTest { : ""; String xml = "" + issuer + "saml-subject" - + extraConfirmation + "" + + extraConfirmation + "" + "" + audience + "" + "" + role + "," + provider + "" + sessionNameAttribute + tagAttributes + ""; diff --git a/src/test/java/io/floci/aws/services/iam/DelegationRequestServiceTest.java b/src/test/java/io/floci/aws/services/iam/DelegationRequestServiceTest.java index c80fd88c07..1c84cb12a0 100644 --- a/src/test/java/io/floci/aws/services/iam/DelegationRequestServiceTest.java +++ b/src/test/java/io/floci/aws/services/iam/DelegationRequestServiceTest.java @@ -152,16 +152,16 @@ class DelegationRequestServiceTest { /** * The deep link lands on the console host of the request's own partition, so a partner in - * China or GovCloud redirects the customer to a console that exists there. The China and - * GovCloud user guides state a host; the EUSC and ISO partitions publish none and keep the - * commercial one. + * China or GovCloud redirects the customer to a console that exists there. The China, GovCloud + * and EUSC user guides state a host; the ISO partitions publish none and keep the commercial + * one. */ @ParameterizedTest @CsvSource({ "us-east-1, console.aws.amazon.com", "cn-north-1, console.amazonaws.cn", "us-gov-west-1, console.amazonaws-us-gov.com", - "eusc-de-east-1, console.aws.amazon.com", + "eusc-de-east-1, eusc-de-east-1.console.amazonaws-eusc.eu", "us-iso-east-1, console.aws.amazon.com"}) void theDeepLinkPointsAtTheConsoleHostOfTheRequestsPartition(String region, String host) { DelegationRequestService.Created created = createdIn(region, "workflow-1", null); diff --git a/src/test/java/io/floci/aws/services/iam/SAMLAssertionVerifierRecipientTest.java b/src/test/java/io/floci/aws/services/iam/SAMLAssertionVerifierRecipientTest.java index b78a603fda..8e86318042 100644 --- a/src/test/java/io/floci/aws/services/iam/SAMLAssertionVerifierRecipientTest.java +++ b/src/test/java/io/floci/aws/services/iam/SAMLAssertionVerifierRecipientTest.java @@ -7,25 +7,41 @@ import org.junit.jupiter.params.provider.CsvSource; import static org.junit.jupiter.api.Assertions.assertEquals; /** - * A bearer assertion names the console sign-on URL of the provider's partition. Where the CDK - * publishes none (ISO-E, ISO-F, EUSC) the commercial URL is kept, as before the per-partition - * table, instead of refusing every assertion. + * A bearer assertion names the console sign-on URL of the provider's partition. EUSC publishes + * none and addresses the assertion to a Region's sign-in endpoint with the provider's id in the + * path instead. Where neither is published (ISO-E, ISO-F) the commercial URL is kept, as before + * the per-partition table, instead of refusing every assertion. */ class SAMLAssertionVerifierRecipientTest { @ParameterizedTest @CsvSource({ - "aws, https://signin.aws.amazon.com/saml", - "aws-cn, https://signin.amazonaws.cn/saml", - "aws-iso, https://signin.c2shome.ic.gov/saml", - "aws-iso-e, https://signin.aws.amazon.com/saml", - "aws-iso-f, https://signin.aws.amazon.com/saml", - "aws-eusc, https://signin.aws.amazon.com/saml" + "aws, https://signin.aws.amazon.com/saml, true", + "aws, https://us-east-1.signin.aws.amazon.com/saml/acs/SAMLSP4SHN3UIS2D558H46, true", + "aws, https://eu-central-1.signin.aws.amazon.com/saml/acs/SAMLSP4SHN3UIS2D558H46, true", + "aws, https://eusc-de-east-1.signin.aws.amazon.com/saml/acs/SAMLSP4SHN3UIS2D558H46, false", + "aws, https://us-east-1.signin.aws.amazon.com/saml, true", + "aws, https://eusc-de-east-1.signin.aws.amazon.com/saml, false", + "aws-cn, https://cn-north-1.signin.amazonaws.cn/saml, false", + "aws-cn, https://cn-north-1.signin.amazonaws.cn/saml/acs/SAMLSP4SHN3UIS2D558H46, false", + "aws-cn, https://signin.amazonaws.cn/saml, true", + "aws-cn, https://signin.aws.amazon.com/saml, false", + "aws-iso, https://signin.c2shome.ic.gov/saml, true", + "aws-iso-e, https://signin.aws.amazon.com/saml, true", + "aws-iso-f, https://signin.aws.amazon.com/saml, true", + "aws-eusc, https://eusc-de-east-1.signin.amazonaws-eusc.eu/saml/acs/SAMLSP4SHN3UIS2D558H46, true", + "aws-eusc, https://eusc-de-east-1.signin.amazonaws-eusc.eu/saml/acs/SAMLSP4SHN3UIS2D558H46/x, false", + "aws-eusc, https://eusc-de-east-1.signin.amazonaws-eusc.eu/saml/acs/short, false", + "aws-eusc, https://eusc-de-east-1.signin.amazonaws-eusc.eu/saml, true", + "aws-eusc, https://us-east-1.signin.amazonaws-eusc.eu/saml, false", + "aws-eusc, https://signin.amazonaws-eusc.eu/saml, false", + "aws-eusc, https://us-east-1.signin.amazonaws-eusc.eu/saml/acs/SAMLSP4SHN3UIS2D558H46, false", + "aws-eusc, https://signin.aws.amazon.com/saml, false" }) - void theRecipientIsThePartitionsSignOnUrlOrTheCommercialOne(String partition, String expected) { + void theRecipientIsThePartitionsSignInEndpoint(String partition, String recipient, boolean accepted) { SAMLProvider provider = new SAMLProvider(); provider.setArn("arn:" + partition + ":iam::000000000000:saml-provider/idp"); - assertEquals(expected, SAMLAssertionVerifier.expectedRecipient(provider)); + assertEquals(accepted, SAMLAssertionVerifier.acceptsRecipient(provider, recipient)); } } diff --git a/tools/aws/regen_region_facts.py b/tools/aws/regen_region_facts.py index 6c95e4f67c..823b7921f3 100644 --- a/tools/aws/regen_region_facts.py +++ b/tools/aws/regen_region_facts.py @@ -16,18 +16,29 @@ China and GovCloud user guides for what neither transcribes, are the sources her - The CloudFront distribution hosted zone per partition: `internal/conns/awsclient.go` (`CloudFrontDistributionHostedZoneID`), cross-checked against the CDK's `aws-route53-targets/lib/cloudfront-target.ts` mapping. -- The SAML sign-on URL per partition: the CDK's `PARTITION_SAML_SIGN_ON_URL`. +- The SAML sign-on URL per partition: the CDK's `PARTITION_SAML_SIGN_ON_URL`. The commercial and EUSC + IAM guides also address an assertion to a Region's sign-in endpoint, with the SAML provider's id in the + path (`SAML_REGIONAL_ACS_SENTENCES`), the only form EUSC gives, for which the CDK has no sign-on URL; + that form is vendored as `samlRegionalAcsUrl`, with `{region}` and `{id}` placeholders, from + https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_enable-console-saml.html -> aws/id_roles_providers_enable-console-saml.md + https://docs.aws.eu/IAM/latest/UserGuide/id_roles_providers_enable-console-saml.html -> eusc/id_roles_providers_enable-console-saml.md + The same guides' SAML assertions pages give the regional sign-in URL without the provider id, + `https://region-code.signin./saml` (`SAML_REGIONAL_SIGN_IN_SENTENCES`), vendored as + `samlRegionalSignInUrl` with a `{region}` placeholder, from + https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_saml_assertions.html -> aws/id_roles_providers_create_saml_assertions.md + https://docs.aws.eu/IAM/latest/UserGuide/id_roles_providers_create_saml_assertions.html -> eusc/id_roles_providers_create_saml_assertions.md - VPC endpoint service-name prefixes: the CDK's `aws-ec2/lib/vpc-endpoint.ts` exception table (China and the ISO/EUSC partitions reverse their DNS suffix, but only for the listed services) plus the `.cn` suffix exceptions; the per-partition `.vpce` prefix from `region-info/build-tools/generate-static-data.ts`. -- The management console host per partition, for `aws`, `aws-cn` and `aws-us-gov`: one sentence - each from the user-guide snapshots under `aws-docs/partition-guides` (`CONSOLE_HOST_SENTENCES`). - No source states it for the ISO or EUSC partitions, which get no field. The snapshots are these - three pages, saved under the path after the arrow: +- The management console host per partition, for `aws`, `aws-cn`, `aws-us-gov` and `aws-eusc`: one + sentence each from the user-guide snapshots under `aws-docs/partition-guides` (`CONSOLE_HOST_SENTENCES`). + No source states it for the ISO partitions, which get no field. The snapshots are these four + pages, saved under the path after the arrow: https://docs.aws.amazon.com/govcloud-us/latest/UserGuide/govcloud-organizations.html -> gov/govcloud-organizations.md https://docs.amazonaws.cn/en_us/aws/latest/userguide/console.html -> cn/console.md https://docs.aws.amazon.com/govcloud-us/latest/UserGuide/configure-account.html -> gov/configure-account.md + https://docs.aws.eu/IAM/latest/UserGuide/id_users_sign-in.html -> eusc/id_users_sign-in.md Either rendering parses: the page's text (what the `aws-refs` skill's docs driver extracts from the `.html`), or the Markdown AWS serves at the same URL with `.md` in place of `.html`, which writes the China host as a link. @@ -106,6 +117,27 @@ CONSOLE_HOST_SENTENCES = { r"Management Console is available in both Chinese and English and can be accessed at \[?https://([a-z0-9.-]+)[\] ]")), "aws-us-gov": ("gov/configure-account.md", re.compile( r"Sign in to the AWS GovCloud \(US\) console and open the IAM console at https://([a-z0-9.-]+)/iam")), + "aws-eusc": ("eusc/id_users_sign-in.md", re.compile( + r"general sign-in endpoint and type your\s+account ID or account alias manually:\s*https://([a-z0-9.-]+)/")), +} +# partition -> (guide page, the trust policy line that names the regional sign-in endpoint an assertion +# is addressed to). The page's text sets the region placeholder and the example provider id apart with +# spaces, `https:// region-code .signin. amazonaws-eusc.eu /saml/acs/ SAMLSP4SHN3UIS2D558H46 `; the +# pattern takes the host's domain and drops the example id for an `{id}` placeholder. +SAML_REGIONAL_ACS = re.compile( + r'"saml:aud":\s*"https://\s*region-code\s*\.signin\.\s*([a-z0-9.-]+?)\s*/saml/acs/\s*[A-Z0-9]{22,64}\s*"') +SAML_REGIONAL_ACS_SENTENCES = { + "aws": ("aws/id_roles_providers_enable-console-saml.md", SAML_REGIONAL_ACS), + "aws-eusc": ("eusc/id_roles_providers_enable-console-saml.md", SAML_REGIONAL_ACS), +} +# partition -> (SAML assertions page, the sign-in URL example without the provider id). The commercial +# page calls the region code optional, the EUSC one required; the example after that sentence is the URL. +SAML_REGIONAL_SIGN_IN = re.compile( + r"sign-in URL format with the (?:optional|required) region-code\s*\.\s*" + r"https://\s*region-code\s*\.signin\.([a-z0-9.-]+?)/saml\s") +SAML_REGIONAL_SIGN_IN_SENTENCES = { + "aws": ("aws/id_roles_providers_create_saml_assertions.md", SAML_REGIONAL_SIGN_IN), + "aws-eusc": ("eusc/id_roles_providers_create_saml_assertions.md", SAML_REGIONAL_SIGN_IN), } # The commercial suffix is the one in the example distribution name of these two model members. BOTOCORE_CLOUDFRONT_DOMAIN_SHAPES = ("Distribution", "DistributionSummary") @@ -135,6 +167,8 @@ RDS_ZONE_SENTENCES = { r'"Port":\s*[0-9]+,\s*"HostedZoneId":\s*"(Z[A-Z0-9]+)"')), } GUIDE_PAGES = sorted({page for page, _ in CONSOLE_HOST_SENTENCES.values()} + | {page for page, _ in SAML_REGIONAL_ACS_SENTENCES.values()} + | {page for page, _ in SAML_REGIONAL_SIGN_IN_SENTENCES.values()} | {page for page, _ in CLOUDFRONT_SUFFIX_SENTENCES.values()} | {APIGATEWAY_REGIONAL_ZONE_PAGE} | {page for page, _ in RDS_ZONE_SENTENCES.values()}) @@ -246,6 +280,18 @@ def parse_console_hosts(guides: Path) -> dict[str, str]: return parse_guide_sentences(guides, CONSOLE_HOST_SENTENCES) +def parse_saml_regional_acs_urls(guides: Path) -> dict[str, str]: + """partition -> `https://{region}.signin./saml/acs/{id}`, from the trust policy example.""" + return {partition: "https://{region}.signin." + domain + "/saml/acs/{id}" + for partition, domain in parse_guide_sentences(guides, SAML_REGIONAL_ACS_SENTENCES).items()} + + +def parse_saml_regional_sign_in_urls(guides: Path) -> dict[str, str]: + """partition -> `https://{region}.signin./saml`, from the SAML assertions page.""" + return {partition: "https://{region}.signin." + domain + "/saml" + for partition, domain in parse_guide_sentences(guides, SAML_REGIONAL_SIGN_IN_SENTENCES).items()} + + def parse_botocore_cloudfront_suffix(text: str) -> str: """The suffix of the example distribution name in the model's `DomainName` documentation.""" shapes = json.loads(text)["shapes"] @@ -343,6 +389,8 @@ def build(terraform: Path, cdk: Path, guides: Path, botocore_data: Path, partiti if elb != alb: raise ValueError("the Classic and ALB hosted-zone maps differ; the generator assumed they are one table") console_hosts = parse_console_hosts(guides) + saml_regional_acs = parse_saml_regional_acs_urls(guides) + saml_regional_sign_in = parse_saml_regional_sign_in_urls(guides) cloudfront_suffixes = parse_cloudfront_suffixes(botocore_data, guides) apigateway_zones = parse_apigateway_endpoint_zones( (guides.parent / APIGATEWAY_ENDPOINTS_PAGE).read_text(encoding="utf-8")) @@ -388,6 +436,10 @@ def build(terraform: Path, cdk: Path, guides: Path, botocore_data: Path, partiti entry["cloudfrontHostedZoneId"] = cloudfront_tf[partition_id] if partition_id in saml: entry["samlSignOnUrl"] = saml[partition_id] + if partition_id in saml_regional_acs: + entry["samlRegionalAcsUrl"] = saml_regional_acs[partition_id] + if partition_id in saml_regional_sign_in: + entry["samlRegionalSignInUrl"] = saml_regional_sign_in[partition_id] if partition_id in console_hosts: entry["consoleHost"] = console_hosts[partition_id] if partition_id in cloudfront_suffixes: @@ -424,9 +476,11 @@ def strip_source(text: str) -> str: HOSTED_ZONE_ID_RE = re.compile(r"Z[0-9A-Z]{9,31}") SAML_URL_RE = re.compile(r"https://[a-z0-9.-]+/saml") +SAML_REGIONAL_ACS_RE = re.compile(r"https://\{region\}\.signin(\.[a-z0-9-]+)+/saml/acs/\{id\}") +SAML_REGIONAL_SIGN_IN_RE = re.compile(r"https://\{region\}\.signin(\.[a-z0-9-]+)+/saml") VPCE_PREFIX_RE = re.compile(r"[a-z0-9-]+(\.[a-z0-9-]+)*\.vpce") REVERSED_DNS_RE = re.compile(r"[a-z0-9-]+(\.[a-z0-9-]+)+") -CONSOLE_HOST_RE = re.compile(r"console(\.[a-z0-9-]+){2,}") +CONSOLE_HOST_RE = re.compile(r"([a-z0-9-]+\.)?console(\.[a-z0-9-]+){2,}") CLOUDFRONT_SUFFIX_RE = re.compile(r"cloudfront\.[a-z]+") @@ -465,6 +519,10 @@ def self_check(path: Path, partitions_path: Path = PARTITIONS) -> list[str]: problems.append(f"{path}: {partition['id']}.vpcEndpointServiceNamePrefix should be {expected!r}") if partition["id"] in CONSOLE_HOST_SENTENCES and "consoleHost" not in entry: problems.append(f"{path}: {partition['id']}.consoleHost is missing") + if partition["id"] in SAML_REGIONAL_ACS_SENTENCES and "samlRegionalAcsUrl" not in entry: + problems.append(f"{path}: {partition['id']}.samlRegionalAcsUrl is missing") + if partition["id"] in SAML_REGIONAL_SIGN_IN_SENTENCES and "samlRegionalSignInUrl" not in entry: + problems.append(f"{path}: {partition['id']}.samlRegionalSignInUrl is missing") if partition["id"] in {"aws"} | CLOUDFRONT_SUFFIX_SENTENCES.keys() and "cloudfrontDomainSuffix" not in entry: problems.append(f"{path}: {partition['id']}.cloudfrontDomainSuffix is missing") for region in sorted(apigateway_zone_regions({"partitions": partitions_doc})): @@ -478,6 +536,7 @@ def self_check(path: Path, partitions_path: Path = PARTITIONS) -> list[str]: for partition, entry in document["partitions"].items(): for key, value in entry.items(): pattern = {"cloudfrontHostedZoneId": HOSTED_ZONE_ID_RE, "samlSignOnUrl": SAML_URL_RE, + "samlRegionalAcsUrl": SAML_REGIONAL_ACS_RE, "samlRegionalSignInUrl": SAML_REGIONAL_SIGN_IN_RE, "vpcEndpointServiceNamePrefix": VPCE_PREFIX_RE, "consoleHost": CONSOLE_HOST_RE, "cloudfrontDomainSuffix": CLOUDFRONT_SUFFIX_RE}.get(key) if pattern is None: diff --git a/tools/aws/test_regen_region_facts.py b/tools/aws/test_regen_region_facts.py index 05a479a084..5595125781 100644 --- a/tools/aws/test_regen_region_facts.py +++ b/tools/aws/test_regen_region_facts.py @@ -119,7 +119,48 @@ Sign in to the AWS GovCloud (US) console and open the IAM console at https://con GUIDE_CHINA_MARKDOWN = """ The Amazon Web Services Management Console is available in both Chinese and English and can be accessed at [https://console.amazonaws.cn](https://console.amazonaws.cn). The Amazon Web Services Management Console is dedicated to the China Regions. """ -GUIDES = {"aws": GUIDE_COMMERCIAL, "aws-cn": GUIDE_CHINA, "aws-us-gov": GUIDE_GOVCLOUD} +# the EUSC IAM guide's sign-in page, as the aws-refs docs TextExtractor renders it +GUIDE_EUSC = """ +You can also sign in at the following general sign-in endpoint and type your +account ID or account alias manually: + +https://eusc-de-east-1.console.amazonaws-eusc.eu/ +""" +GUIDES = {"aws": GUIDE_COMMERCIAL, "aws-cn": GUIDE_CHINA, "aws-us-gov": GUIDE_GOVCLOUD, "aws-eusc": GUIDE_EUSC} +# the EUSC IAM guide's SAML console page: the extractor sets each inline code span apart with spaces +GUIDE_EUSC_SAML = """ +"Condition": { +"StringEquals": { +"saml:edupersonorgdn": "ExampleOrg", +"saml:aud": "https:// region-code .signin. amazonaws-eusc.eu /saml/acs/ SAMLSP4SHN3UIS2D558H46 " +} +} +""" +# the commercial IAM guide's SAML console page, which gives the same regional form +GUIDE_COMMERCIAL_SAML = """ +"Condition": { +"StringEquals": { +"saml:edupersonorgdn": "ExampleOrg", +"saml:aud": "https:// region-code .signin. aws.amazon.com /saml/acs/ SAMLSP4SHN3UIS2D558H46 " +} +} +""" +# the commercial and EUSC IAM guides' SAML assertions pages: the sign-in URL without the provider id +GUIDE_COMMERCIAL_SAML_ASSERTIONS = """ +assigns to your SAML provider, which you can find on the Identity provider detail page. The +following example shows the sign-in URL format with the optional region-code . + +https:// region-code .signin.aws.amazon.com/saml + +https:// region-code .signin.aws.amazon.com/saml/acs/ IdP-ID +""" +GUIDE_EUSC_SAML_ASSERTIONS = """ +following example shows the sign-in URL format with the required region-code . + +https:// region-code .signin.amazonaws-eusc.eu/saml + +https:// region-code .signin.amazonaws-eusc.eu/saml/acs/ IdP-ID +""" GUIDE_CHINA_CLOUDFRONT = """ You can\u2019t use the default CloudFront domain, *.cloudfront.cn, to serve content. You must add an alternate domain name. """ @@ -178,6 +219,7 @@ PARTITIONS = {"partitions": [ {"id": "us-gov-east-1", "description": "AWS GovCloud (US-East)"}, {"id": "us-gov-west-1", "description": "AWS GovCloud (US-West)"}]}, {"id": "aws-iso-f", "dnsSuffix": "csp.hci.ic.gov", "regions": [{"id": "us-isof-south-1"}]}, + {"id": "aws-eusc", "dnsSuffix": "amazonaws.eu", "regions": [{"id": "eusc-de-east-1"}]}, ]} @@ -192,6 +234,10 @@ def write_sources(tmp_path: Path) -> tuple[Path, Path, Path, Path]: (guides, r.CLOUDFRONT_SUFFIX_SENTENCES["aws-cn"][0], GUIDE_CHINA_CLOUDFRONT), (guides, r.APIGATEWAY_REGIONAL_ZONE_PAGE, GUIDE_GOVCLOUD_APIGATEWAY), (guides, r.RDS_ZONE_SENTENCES["us-east-1"][0], RDS_CLI_EXAMPLE), + (guides, r.SAML_REGIONAL_ACS_SENTENCES["aws-eusc"][0], GUIDE_EUSC_SAML), + (guides, r.SAML_REGIONAL_ACS_SENTENCES["aws"][0], GUIDE_COMMERCIAL_SAML), + (guides, r.SAML_REGIONAL_SIGN_IN_SENTENCES["aws"][0], GUIDE_COMMERCIAL_SAML_ASSERTIONS), + (guides, r.SAML_REGIONAL_SIGN_IN_SENTENCES["aws-eusc"][0], GUIDE_EUSC_SAML_ASSERTIONS), (botocore, r.BOTOCORE_CLOUDFRONT, BOTOCORE_CLOUDFRONT), (tmp_path, r.APIGATEWAY_ENDPOINTS_PAGE, GENERAL_REFERENCE_APIGATEWAY), ] + [(guides, r.CONSOLE_HOST_SENTENCES[partition][0], body) for partition, body in GUIDES.items()]: @@ -240,11 +286,33 @@ def test_vpc_endpoint_exceptions_are_per_region_and_service(): def test_console_hosts_come_from_the_guide_sentences(tmp_path): _, _, guides, _ = write_sources(tmp_path) assert r.parse_console_hosts(guides) == {"aws": "console.aws.amazon.com", "aws-cn": "console.amazonaws.cn", - "aws-us-gov": "console.amazonaws-us-gov.com"} + "aws-us-gov": "console.amazonaws-us-gov.com", + "aws-eusc": "eusc-de-east-1.console.amazonaws-eusc.eu"} assert r.guides_present(guides) assert not r.guides_present(tmp_path / "nowhere") +def test_the_regional_saml_endpoints_are_the_acs_form_with_placeholders(tmp_path): + _, _, guides, _ = write_sources(tmp_path) + assert r.parse_saml_regional_acs_urls(guides) == { + "aws": "https://{region}.signin.aws.amazon.com/saml/acs/{id}", + "aws-eusc": "https://{region}.signin.amazonaws-eusc.eu/saml/acs/{id}"} + page, sentence = r.SAML_REGIONAL_ACS_SENTENCES["aws-eusc"] + with pytest.raises(ValueError): + r.parse_guide_sentence('"saml:aud": "https://signin.aws.amazon.com/saml"', sentence, page) + + +def test_the_regional_saml_sign_in_urls_are_the_form_without_the_provider_id(tmp_path): + _, _, guides, _ = write_sources(tmp_path) + assert r.parse_saml_regional_sign_in_urls(guides) == { + "aws": "https://{region}.signin.aws.amazon.com/saml", + "aws-eusc": "https://{region}.signin.amazonaws-eusc.eu/saml"} + page, sentence = r.SAML_REGIONAL_SIGN_IN_SENTENCES["aws"] + with pytest.raises(ValueError): + r.parse_guide_sentence("the sign-in URL format with the optional region-code .\n\n" + "https:// region-code .signin.aws.amazon.com/saml/acs/ IdP-ID", sentence, page) + + def test_the_china_cloudfront_suffix_parses_from_the_markdown_escaped_form(): page, sentence = r.CLOUDFRONT_SUFFIX_SENTENCES["aws-cn"] markdown = GUIDE_CHINA_CLOUDFRONT.replace("*.cloudfront.cn", "\\*.cloudfront.cn") @@ -366,6 +434,9 @@ def test_build_merges_sources_with_terraform_winning_the_s3_conflicts(tmp_path): "consoleHost": "console.amazonaws.cn", "cloudfrontDomainSuffix": "cloudfront.cn"} assert partitions["aws"]["cloudfrontDomainSuffix"] == "cloudfront.net" + assert partitions["aws"]["samlSignOnUrl"] == "https://signin.aws.amazon.com/saml" + assert partitions["aws"]["samlRegionalAcsUrl"] == "https://{region}.signin.aws.amazon.com/saml/acs/{id}" + assert partitions["aws"]["samlRegionalSignInUrl"] == "https://{region}.signin.aws.amazon.com/saml" assert partitions["aws-us-gov"] == {"vpcEndpointServiceNamePrefix": "com.amazonaws.vpce", "consoleHost": "console.amazonaws-us-gov.com"} assert regions["us-gov-west-1"] == {"apiGatewayRegionalHostedZoneId": "Z1K6XKP9SAGWDV"} @@ -374,6 +445,10 @@ def test_build_merges_sources_with_terraform_winning_the_s3_conflicts(tmp_path): assert "apiGatewayRegionalHostedZoneId" not in regions["af-south-1"], "a region with no row stays absent" assert document["_source"]["apiGatewayRegionalHostedZones"].startswith(r.APIGATEWAY_ENDPOINTS_URL) assert partitions["aws-iso-f"] == {"vpcEndpointServiceNamePrefix": "gov.ic.hci.csp.vpce"} + assert partitions["aws-eusc"] == {"vpcEndpointServiceNamePrefix": "eu.amazonaws.vpce", + "samlRegionalAcsUrl": "https://{region}.signin.amazonaws-eusc.eu/saml/acs/{id}", + "samlRegionalSignInUrl": "https://{region}.signin.amazonaws-eusc.eu/saml", + "consoleHost": "eusc-de-east-1.console.amazonaws-eusc.eu"} def test_build_refuses_a_region_the_partition_data_does_not_publish(tmp_path): @@ -451,6 +526,10 @@ def test_self_check_holds_the_values_to_what_partitions_json_publishes(tmp_path) "missing China console host": lambda d: d["partitions"]["aws-cn"].pop("consoleHost"), "missing GovCloud console host": lambda d: d["partitions"]["aws-us-gov"].pop("consoleHost"), "missing commercial console host": lambda d: d["partitions"]["aws"].pop("consoleHost"), + "missing EUSC console host": lambda d: d["partitions"]["aws-eusc"].pop("consoleHost"), + "missing EUSC SAML endpoint": lambda d: d["partitions"]["aws-eusc"].pop("samlRegionalAcsUrl"), + "EUSC SAML endpoint without its placeholders": lambda d: d["partitions"]["aws-eusc"].update( + samlRegionalAcsUrl="https://eusc-de-east-1.signin.amazonaws-eusc.eu/saml/acs/SAMLSP4SHN3UIS2D558H46"), "missing commercial CloudFront suffix": lambda d: d["partitions"]["aws"].pop("cloudfrontDomainSuffix"), "missing China CloudFront suffix": lambda d: d["partitions"]["aws-cn"].pop("cloudfrontDomainSuffix"), "missing us-gov-west-1 API Gateway zone": lambda d: d["regions"]["us-gov-west-1"].pop(