diff --git a/.github/workflows/iam-namespace-drift.yml b/.github/workflows/iam-namespace-drift.yml new file mode 100644 index 0000000000..1f4c1e2220 --- /dev/null +++ b/.github/workflows/iam-namespace-drift.yml @@ -0,0 +1,59 @@ +name: IAM Namespace Drift + +# Checks that every namespace in the vendored IAM service namespace list is one AWS actually +# publishes. That needs the live service reference index, so unlike every other check here it can +# fail without anything in the repository having changed: an AWS outage, or a namespace AWS has +# retired. It therefore runs on its own, never as part of a job that ordinary changes trigger. +# +# Two triggers, for two different failures: +# +# - On a pull request that touches the vendored file or its generator, which is where a +# hand-typed or mistyped namespace would enter the repository. A pull request that does not +# touch them cannot introduce one, so it does not run and cannot be failed by an outage. +# - Weekly, because the list also goes stale without anyone touching it: AWS ships services and +# occasionally retires them. Tying the only upstream check to pull request activity would mean +# a quiet month is a month with no drift detection at all. +# +# A namespace AWS has *added* since the last `make iam-namespaces-sync` is reported without +# failing, because being behind makes the service-last-accessed report incomplete rather than +# wrong. The fix for a real failure is to run that target and commit the result. +# +# The offline shape check is hermetic and runs per pull request inside the "Vendored AWS data in +# sync" job in partition-literals.yml instead. + +on: + pull_request: + paths: + - 'src/main/resources/aws/iam-service-namespaces.json' + - 'tools/aws/regen_service_namespaces.py' + - 'tools/aws/test_regen_service_namespaces.py' + - '.github/workflows/iam-namespace-drift.yml' + schedule: + # Mondays at 06:00 UTC, before the working week rather than during it. + - cron: '0 6 * * 1' + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + iam-namespaces-drift: + name: Vendored IAM namespaces still exist upstream + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - name: Set up Python + uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + with: + python-version: "3.x" + + # No dependency install: the generator is deliberately stdlib-only, and this job runs no + # tests. The pinned botocore the sibling workflow needs is for the partition generator. + - name: Check every vendored IAM namespace still exists upstream + run: make iam-namespaces-verify diff --git a/.github/workflows/partition-literals.yml b/.github/workflows/partition-literals.yml index 8dc0451070..366d40ee21 100644 --- a/.github/workflows/partition-literals.yml +++ b/.github/workflows/partition-literals.yml @@ -64,7 +64,7 @@ jobs: run: make partition-audit aws-data: - name: Vendored partition data in sync + name: Vendored AWS data in sync runs-on: ubuntu-latest timeout-minutes: 5 steps: @@ -83,3 +83,10 @@ jobs: - name: Check partitions.json against a fresh generation run: make aws-data-check + + # Offline and hermetic, so it is safe on a job this broadly triggered. The online check + # that needs AWS lives in iam-namespace-drift.yml, which only runs when the vendored file + # or its generator changes, so an outage cannot fail an unrelated Java pull request. + - name: Check the vendored IAM namespace list is well-formed + run: make iam-namespaces-check + diff --git a/Makefile b/Makefile index c0f5a687ee..188c3dcaf4 100644 --- a/Makefile +++ b/Makefile @@ -42,7 +42,8 @@ PREFIX ?= $(HOME)/.local .DEFAULT_GOAL := help .PHONY: help dev build test native native-host run-native native-install native-image native-up native-down native-logs clean-sidecars clean-volumes compat docker-tests \ docs-sync docs-check docs-test partition-check partition-baseline partition-audit partition-test \ - aws-data-sync aws-data-check aws-data-test + aws-data-sync aws-data-check aws-data-test \ + iam-namespaces-sync iam-namespaces-check iam-namespaces-verify iam-namespaces-test help: ## List the targets below @grep -hE '^[a-zA-Z_-]+:.*?## ' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf " %-14s %s\n", $$1, $$2}' @@ -184,3 +185,30 @@ aws-data-check: ## CI gate: the vendored partition data must match a fresh gener aws-data-test: ## Run the partition-data generator's unit tests $(PYTHON) -m pytest tools/aws -q + +iam-namespaces-sync: ## Regenerate src/main/resources/aws/iam-service-namespaces.json from AWS (commit the result) + $(PYTHON) tools/aws/regen_service_namespaces.py + +iam-namespaces-check: ## CI gate (offline): the vendored IAM namespace list must be well-formed + @$(PYTHON) tools/aws/regen_service_namespaces.py --check || { \ + echo ""; \ + echo "error: src/main/resources/aws/iam-service-namespaces.json is malformed."; \ + echo " Run 'make iam-namespaces-sync' and commit the result."; \ + exit 1; \ + } + +iam-namespaces-verify: ## CI gate (online): every vendored IAM namespace must still exist upstream + @$(PYTHON) tools/aws/regen_service_namespaces.py --verify; status=$$?; \ + if [ $$status -eq 2 ]; then \ + echo ""; \ + echo "error: could not reach AWS's service reference index, so nothing was verified."; \ + exit 1; \ + elif [ $$status -ne 0 ]; then \ + echo ""; \ + echo "error: the vendored IAM namespace list names a service AWS does not publish."; \ + echo " Run 'make iam-namespaces-sync' and commit the result."; \ + exit 1; \ + fi + +iam-namespaces-test: ## Run the IAM namespace generator's unit tests + $(PYTHON) -m pytest tools/aws/test_regen_service_namespaces.py -q diff --git a/docs/services/iam.md b/docs/services/iam.md index d2ba1633db..758adc8d94 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -355,11 +355,26 @@ reach through its permissions policies, and for a service with no access attempt `GetServiceLastAccessedDetails` returns a real, policy-derived `ServicesLastAccessed` list in which every entry is that "no attempt" shape. The missing piece is the usage timestamps, not the list. -Only the namespaces a policy names literally can be enumerated. An `Action` of `*`, a globbed -prefix such as `s3*`, and any `NotAction` all denote a set no policy document spells out, and Floci -has no catalog of every AWS service namespace to expand them against, so services reachable only -through one of those are absent from the list. `ServiceName` is a required member that AWS fills -with a display name (`Amazon S3`); Floci has no such mapping and repeats the namespace instead. +A grant that names no namespace is expanded against the vendored catalog of IAM service namespaces +in `src/main/resources/aws/iam-service-namespaces.json`: an `Action` of `*` reaches every published +service, a globbed prefix such as `s3*` reaches the ones it matches, and an `Allow` with `NotAction` +reaches everything the list does not carve out entirely. A namespace a policy names outright is +reported whether or not the catalog knows it, so a catalog that has fallen behind an AWS launch +still reports an explicitly named service; only wildcard expansion depends on it being current. + +That catalog is generated by `tools/aws/regen_service_namespaces.py` from AWS's Service Reference +Information index, whose per-service `service` field is the IAM namespace itself. botocore is +deliberately not the source: a namespace is not any botocore field, since CloudWatch's +`endpointPrefix` is `monitoring` and its `serviceId` is `CloudWatch` against an IAM namespace of +`cloudwatch`. Because that index is a live endpoint rather than a pinned dependency, the gate is not +byte-equality: `make iam-namespaces-check` validates the file's shape offline, and +`make iam-namespaces-verify` checks online that every namespace in it still exists upstream, so +nothing invented can survive. Services AWS has added since the last `make iam-namespaces-sync` are +reported by that check without failing it, since being behind makes the list incomplete rather than +wrong. + +`ServiceName` is a required member that AWS fills with a display name (`Amazon S3`); Floci has no +such mapping and repeats the namespace instead. `GetServiceLastAccessedDetailsWithEntities` is policy-derived in the same way. AWS reports the entities that *could have used* the reported permissions to reach a service, so a group report diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsServiceNamespaces.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsServiceNamespaces.java new file mode 100644 index 0000000000..566ebbc47e --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsServiceNamespaces.java @@ -0,0 +1,82 @@ +package io.github.hectorvent.floci.core.common; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; + +/** + * Every IAM service namespace, read once from the vendored {@code aws/iam-service-namespaces.json}. + * + *

The file is generated by {@code tools/aws/regen_service_namespaces.py} from AWS's Service + * Reference Information index (https://servicereference.us-east-1.amazonaws.com/), whose per-service + * {@code service} field is the IAM namespace itself. botocore is deliberately not the source: a + * namespace is not any botocore field, since CloudWatch's {@code endpointPrefix} is {@code + * monitoring} and its {@code serviceId} is {@code CloudWatch} against an IAM namespace of {@code + * cloudwatch}. {@code make iam-namespaces-verify} checks that nothing here is invented. + * + *

This exists so a policy that grants a service without naming it can still be reported on: + * {@code "Action": "*"} and a globbed prefix such as {@code s3*} name no namespace, so + * {@code GetServiceLastAccessedDetails} needs a list to expand them against. + * + *

A missing or malformed resource is a build defect, not a runtime condition, so loading fails + * with {@link IllegalStateException} rather than degrading to an empty catalog, which would + * silently turn every wildcard grant back into an unreported one. + */ +public final class AwsServiceNamespaces { + + static final String RESOURCE_NAME = "aws/iam-service-namespaces.json"; + + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private static final class Holder { + static final List NAMESPACES = load(); + } + + private AwsServiceNamespaces() { + } + + /** + * Every published namespace, sorted, as the vendored file lists them. + * + *

Matching a globbed pattern against these is the caller's job, so that the one glob + * implementation Floci already has for policy patterns stays in the IAM evaluator rather than + * being duplicated here. + */ + public static List all() { + return Holder.NAMESPACES; + } + + private static List load() { + try (InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(RESOURCE_NAME)) { + if (in == null) { + throw new IllegalStateException("IAM service namespace catalog resource not found: " + + RESOURCE_NAME); + } + return parse(in); + } catch (IOException e) { + throw new IllegalStateException("Failed to read the IAM service namespace catalog " + + RESOURCE_NAME, e); + } + } + + static List parse(InputStream in) throws IOException { + JsonNode root = MAPPER.readTree(in); + JsonNode namespaces = root.path("serviceNamespaces"); + if (!namespaces.isArray() || namespaces.isEmpty()) { + throw new IllegalStateException(RESOURCE_NAME + " carries no serviceNamespaces"); + } + List parsed = new ArrayList<>(namespaces.size()); + for (JsonNode namespace : namespaces) { + String value = namespace.asText(""); + if (value.isBlank()) { + throw new IllegalStateException(RESOURCE_NAME + " carries a blank service namespace"); + } + parsed.add(value); + } + return List.copyOf(parsed); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamPolicyEvaluator.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamPolicyEvaluator.java index 4c8d10ab70..e54d948204 100644 --- a/src/main/java/io/github/hectorvent/floci/services/iam/IamPolicyEvaluator.java +++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamPolicyEvaluator.java @@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.iam; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.core.common.AwsArnUtils; +import io.github.hectorvent.floci.core.common.AwsServiceNamespaces; import io.github.hectorvent.floci.services.iam.model.CallerContext; import io.github.hectorvent.floci.services.iam.model.PolicyStatement; import jakarta.enterprise.context.ApplicationScoped; @@ -14,6 +15,8 @@ import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Set; +import java.util.TreeSet; import java.util.concurrent.ConcurrentHashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -381,53 +384,67 @@ public class IamPolicyEvaluator { } /** - * The service namespaces {@code policyDocuments} name explicitly in an {@code Allow}, backing - * the service list in {@code GetServiceLastAccessedDetails}. + * The service namespaces {@code policyDocuments} grant, backing the service list in + * {@code GetServiceLastAccessedDetails}. * - *

AWS lists a service the entity could reach even when it was never used, so the list is - * derived from the same permissions-policy logic as {@link #grantsServiceAccess}. Only - * namespaces written out literally can be enumerated: {@code Action: "*"}, a globbed prefix - * like {@code s3*}, and {@code NotAction} all denote a set no policy document enumerates, so - * they are reported through {@code grantsAllServices} for the caller to expand against - * whatever universe of services it knows. + *

AWS lists a service the entity could reach even when it was never used, so the list comes + * from the same permissions-policy logic as {@link #grantsServiceAccess}. A grant that names no + * namespace is expanded against {@link AwsServiceNamespaces}: {@code Action: "*"} yields every + * published namespace, a globbed prefix such as {@code s3*} yields the ones it matches, and an + * {@code Allow} with {@code NotAction} yields everything the list does not carve out entirely. + * + *

A namespace written out literally is kept whether or not the vendored catalog knows it, so + * a catalog that has fallen behind an AWS launch still reports a service the policy names + * outright; only wildcard expansion depends on the catalog being current. + * + *

A document that fails to parse grants nothing, matching {@link #parseAll} elsewhere here. */ - public GrantedServices servicesGrantedBy(List policyDocuments) { - List namespaces = new ArrayList<>(); - boolean all = false; + public List servicesGrantedBy(List policyDocuments) { + Set granted = new TreeSet<>(); for (PolicyStatement stmt : parseAll(policyDocuments)) { if (!"Allow".equalsIgnoreCase(stmt.getEffect())) { continue; } if (stmt.getNotActions() != null) { - all = true; + for (String namespace : AwsServiceNamespaces.all()) { + if (!excludesEntirely(stmt.getNotActions(), namespace)) { + granted.add(namespace); + } + } continue; } if (stmt.getActions() == null) { continue; } for (String pattern : stmt.getActions()) { - int colon = pattern == null ? -1 : pattern.indexOf(':'); - if (colon < 0) { - // "*" grants every service; anything else without a colon is malformed. - all = all || "*".equals(pattern); - continue; - } - String namespace = pattern.substring(0, colon); - if (namespace.indexOf('*') >= 0 || namespace.indexOf('?') >= 0) { - all = true; - } else if (!namespaces.contains(namespace)) { - namespaces.add(namespace); - } + collectGrantedNamespaces(pattern, granted); } } - return new GrantedServices(namespaces, all); + return List.copyOf(granted); } - /** - * Service namespaces an identity's policies grant: those named literally, plus whether some - * statement grants every service without naming any. - */ - public record GrantedServices(List namespaces, boolean grantsAllServices) {} + /** Adds whatever one action pattern's service part denotes: a name, a glob, or everything. */ + private static void collectGrantedNamespaces(String pattern, Set granted) { + if ("*".equals(pattern)) { + granted.addAll(AwsServiceNamespaces.all()); + return; + } + int colon = pattern == null ? -1 : pattern.indexOf(':'); + if (colon < 0) { + // Not "service:Action" and not "*"; IAM would reject it, so it grants nothing. + return; + } + String namespace = pattern.substring(0, colon); + if (namespace.indexOf('*') < 0 && namespace.indexOf('?') < 0) { + granted.add(namespace); + return; + } + for (String candidate : AwsServiceNamespaces.all()) { + if (globMatches(namespace, candidate)) { + granted.add(candidate); + } + } + } /** An action pattern reaches a namespace when its service part matches, whatever the verb is. */ private static boolean actionPatternReaches(String pattern, String serviceNamespace) { diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.java index c88b52185b..4f46d3b64c 100644 --- a/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.java @@ -32,7 +32,6 @@ import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; -import java.util.TreeSet; import java.util.regex.Pattern; import java.util.stream.Stream; @@ -1570,11 +1569,11 @@ public class IamQueryHandler { String accountId = accountResolver.resolve(authorization); String arn = requireParam(params, "Arn"); AccessAdvisorTarget target = resolveAccessAdvisorTarget(accountId, arn); - IamPolicyEvaluator.GrantedServices granted = - policyEvaluator.servicesGrantedBy(target.policyDocuments()); + // Already sorted and expanded, including the wildcard and NotAction grants that name no + // namespace of their own. + List granted = policyEvaluator.servicesGrantedBy(target.policyDocuments()); ServiceLastAccessedJob job = serviceLastAccessedService.generate(accountId, arn, - params.getFirst("Granularity"), new TreeSet<>(granted.namespaces()).stream().toList(), - target.entities()); + params.getFirst("Granularity"), granted, target.entities()); return Response.ok(AwsQueryResponse.envelope("GenerateServiceLastAccessedDetails", AwsNamespaces.IAM, new XmlBuilder().elem("JobId", job.getJobId()).build())).build(); } diff --git a/src/main/resources/aws/iam-service-namespaces.json b/src/main/resources/aws/iam-service-namespaces.json new file mode 100644 index 0000000000..022404448b --- /dev/null +++ b/src/main/resources/aws/iam-service-namespaces.json @@ -0,0 +1,466 @@ +{ + "_source": { + "generator": "tools/aws/regen_service_namespaces.py", + "index": "https://servicereference.us-east-1.amazonaws.com/", + "retrieved": "2026-09-27", + "note": "make iam-namespaces-verify checks every entry still exists upstream." + }, + "serviceNamespaces": [ + "a2c", + "a4b", + "access-analyzer", + "account", + "account-access", + "acm", + "acm-pca", + "aco-automation", + "action-recommendations", + "activate", + "agent-registry", + "agentaccess-mcp", + "aidevops", + "aiops", + "airflow", + "airflow-serverless", + "amplify", + "amplifybackend", + "amplifyuibuilder", + "aoss", + "apigateway", + "app-integrations", + "appconfig", + "appfabric", + "appflow", + "application-autoscaling", + "application-signals", + "application-signals-mcp", + "application-transformation", + "applicationinsights", + "appmesh", + "appmesh-preview", + "apprunner", + "appstream", + "appstudio", + "appsync", + "apptest", + "aps", + "arc-region-switch", + "arc-zonal-shift", + "arsenal", + "artifact", + "athena", + "auditmanager", + "autoscaling", + "autoscaling-plans", + "aws-external-anthropic", + "aws-marketplace", + "aws-marketplace-management", + "aws-portal", + "awsconnector", + "b2bi", + "backup", + "backup-gateway", + "backup-search", + "backup-storage", + "batch", + "bcm-dashboards", + "bcm-data-exports", + "bcm-pricing-calculator", + "bcm-recommended-actions", + "bedrock", + "bedrock-agentcore", + "bedrock-mantle", + "bedrock-websearch", + "billing", + "billingconductor", + "braket", + "budgets", + "bugbust", + "cases", + "cassandra", + "ce", + "chatbot", + "chime", + "cleanrooms", + "cleanrooms-ml", + "cloud9", + "clouddirectory", + "cloudformation", + "cloudfront", + "cloudfront-keyvaluestore", + "cloudhsm", + "cloudsearch", + "cloudshell", + "cloudtrail", + "cloudtrail-data", + "cloudwatch", + "codeartifact", + "codebuild", + "codecatalyst", + "codecommit", + "codeconnections", + "codedeploy", + "codedeploy-commands-secure", + "codeguru", + "codeguru-profiler", + "codeguru-reviewer", + "codeguru-security", + "codepipeline", + "codestar", + "codestar-connections", + "codestar-notifications", + "codewhisperer", + "cognito-identity", + "cognito-idp", + "cognito-sync", + "comprehend", + "comprehendmedical", + "compute-optimizer", + "config", + "connect", + "connect-campaigns", + "consoleapp", + "consolidatedbilling", + "controlcatalog", + "controltower", + "cost-optimization-hub", + "cur", + "customer-verification", + "databrew", + "dataexchange", + "datapipeline", + "datasync", + "datazone", + "dax", + "dbqms", + "deadline", + "detective", + "devicefarm", + "devops-guru", + "directconnect", + "discovery", + "dlm", + "dms", + "docdb-elastic", + "drs", + "ds", + "ds-data", + "dsql", + "dynamodb", + "ebs", + "ec2", + "ec2-instance-connect", + "ec2messages", + "ecr", + "ecr-public", + "ecs", + "ecs-mcp", + "eks", + "eks-auth", + "eks-mcp", + "elasticache", + "elasticbeanstalk", + "elasticfilesystem", + "elasticloadbalancing", + "elasticmapreduce", + "elastictranscoder", + "elemental-activations", + "elemental-appliances-software", + "elemental-inference", + "elemental-support-cases", + "elemental-support-content", + "emr-containers", + "emr-serverless", + "entityresolution", + "es", + "events", + "eventsbilltoaws", + "evidently", + "evs", + "execute-api", + "finops-agent", + "finspace", + "finspace-api", + "firehose", + "fis", + "fms", + "forecast", + "frauddetector", + "freertos", + "freetier", + "fsx", + "gamelift", + "gameliftstreams", + "geo", + "geo-maps", + "geo-places", + "geo-routes", + "glacier", + "globalaccelerator", + "glue", + "grafana", + "greengrass", + "groundstation", + "groundtruthlabeling", + "guardduty", + "health", + "health-agent", + "healthlake", + "honeycode", + "iam", + "identity-sync", + "identitystore", + "identitystore-auth", + "imagebuilder", + "importexport", + "inspector", + "inspector-scan", + "inspector2", + "inspector2-telemetry", + "interconnect", + "internetmonitor", + "invoicing", + "iot", + "iot-device-tester", + "iotanalytics", + "iotdeviceadvisor", + "iotevents", + "iotfleethub", + "iotfleetwise", + "iotjobsdata", + "iotmanagedintegrations", + "iotsitewise", + "iottwinmaker", + "iotwireless", + "iq", + "iq-permission", + "ivs", + "ivschat", + "kafka", + "kafka-cluster", + "kafkaconnect", + "kendra", + "kendra-ranking", + "kinesis", + "kinesisanalytics", + "kinesisvideo", + "kms", + "lakeformation", + "lambda", + "launchwizard", + "lex", + "license-manager", + "license-manager-linux-subscriptions", + "license-manager-user-subscriptions", + "lightsail", + "logs", + "lookoutequipment", + "lookoutmetrics", + "lookoutvision", + "m2", + "machinelearning", + "macie2", + "managedblockchain", + "managedblockchain-query", + "mapcredits", + "marketplacecommerceanalytics", + "mechanicalturk", + "mediaconnect", + "mediaconvert", + "mediaimport", + "medialive", + "mediapackage", + "mediapackage-vod", + "mediapackagev2", + "mediastore", + "mediatailor", + "medical-imaging", + "memorydb", + "mgh", + "mgn", + "migrationhub-orchestrator", + "migrationhub-strategy", + "mobileanalytics", + "mobiletargeting", + "monitron", + "mpa", + "mq", + "neptune-db", + "neptune-graph", + "network-firewall", + "network-security-director", + "network-security-manager", + "networkflowmonitor", + "networkmanager", + "networkmanager-chat", + "networkmonitor", + "nimble", + "notifications", + "notifications-contacts", + "nova-act", + "oam", + "observabilityadmin", + "odb", + "omics", + "one", + "opensearch", + "opsworks", + "opsworks-cm", + "organizations", + "osis", + "outposts", + "panorama", + "partnercentral", + "partnercentral-account-management", + "payment-cryptography", + "payments", + "pca-connector-ad", + "pca-connector-scep", + "pcs", + "personalize", + "pi", + "pipes", + "polly", + "pricing", + "pricingplanmanager", + "private-networks", + "profile", + "proton", + "purchase-orders", + "q", + "qapps", + "qbusiness", + "qdeveloper", + "qldb", + "quicksight", + "ram", + "rbin", + "rds", + "rds-data", + "rds-db", + "redshift", + "redshift-data", + "redshift-serverless", + "refactor-spaces", + "rekognition", + "repostspace", + "researchstudio", + "resiliencehub", + "resource-explorer", + "resource-explorer-2", + "resource-groups", + "rhelkb", + "robomaker", + "rolesanywhere", + "route53", + "route53-recovery-cluster", + "route53-recovery-control-config", + "route53-recovery-readiness", + "route53domains", + "route53globalresolver", + "route53profiles", + "route53resolver", + "rtbfabric", + "rum", + "s3", + "s3-object-lambda", + "s3-outposts", + "s3express", + "s3files", + "s3tables", + "s3vectors", + "sagemaker", + "sagemaker-data-science-assistant", + "sagemaker-geospatial", + "sagemaker-mlflow", + "sagemaker-unified-studio-mcp", + "savingsplans", + "scheduler", + "schemas", + "scn", + "sdb", + "secretsmanager", + "security-ir", + "securityagent", + "securityhub", + "securitylake", + "serverlessrepo", + "servicecatalog", + "servicediscovery", + "serviceextract", + "servicequotas", + "ses", + "shield", + "signer", + "signin", + "simspaceweaver", + "sms", + "sms-voice", + "snow-device-management", + "snowball", + "sns", + "social-messaging", + "sqlworkbench", + "sqs", + "ssm", + "ssm-contacts", + "ssm-guiconnect", + "ssm-incidents", + "ssm-quicksetup", + "ssm-sap", + "ssmmessages", + "sso", + "sso-directory", + "sso-oauth", + "states", + "storagegateway", + "sts", + "support", + "support-console", + "supportapp", + "supportauthz", + "supportplans", + "sustainability", + "swf", + "synthetics", + "tag", + "tax", + "textract", + "thinclient", + "timestream", + "timestream-influxdb", + "tiros", + "tnb", + "transcribe", + "transfer", + "transform", + "transform-custom", + "translate", + "trustedadvisor", + "ts", + "user-subscriptions", + "uxc", + "vendor-insights", + "verified-access", + "verifiedpermissions", + "voiceid", + "vpc-lattice", + "vpc-lattice-svcs", + "vpce", + "waf", + "waf-regional", + "wafv2", + "wam", + "wellarchitected", + "wickr", + "wisdom", + "workdocs", + "worklink", + "workmail", + "workmailmessageflow", + "workspaces", + "workspaces-instances", + "workspaces-web", + "xray" + ] +} diff --git a/src/test/java/io/github/hectorvent/floci/core/common/AwsServiceNamespacesTest.java b/src/test/java/io/github/hectorvent/floci/core/common/AwsServiceNamespacesTest.java new file mode 100644 index 0000000000..4fe3b6c4bc --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/core/common/AwsServiceNamespacesTest.java @@ -0,0 +1,98 @@ +package io.github.hectorvent.floci.core.common; + +import org.junit.jupiter.api.Test; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** Verifies the vendored IAM service namespace catalog and how it fails when malformed. */ +class AwsServiceNamespacesTest { + + @Test + void theVendoredCatalogCarriesEveryServiceAwsPublishes() { + List namespaces = AwsServiceNamespaces.all(); + + // AWS publishes several hundred; a catalog an order of magnitude smaller means the + // vendored file was truncated rather than regenerated. + assertTrue(namespaces.size() > 300, + "expected several hundred namespaces, got " + namespaces.size()); + } + + /** + * The whole reason this catalog is generated from AWS's service reference rather than botocore: + * CloudWatch's credential scope and endpoint prefix are both {@code monitoring}, while its IAM + * namespace is {@code cloudwatch}. Deriving it from botocore metadata produces the former. + */ + @Test + void cloudWatchIsCarriedByItsIamNamespaceNotItsCredentialScope() { + assertTrue(AwsServiceNamespaces.all().contains("cloudwatch"), + "cloudwatch is CloudWatch's IAM namespace and must be present"); + assertFalse(AwsServiceNamespaces.all().contains("monitoring"), + "monitoring is a credential scope, not an IAM namespace"); + } + + @Test + void theCatalogIsSortedAndFreeOfDuplicates() { + List namespaces = AwsServiceNamespaces.all(); + + assertEquals(namespaces.stream().sorted().toList(), namespaces, "expected a sorted catalog"); + assertEquals(namespaces.size(), namespaces.stream().distinct().count(), + "expected no duplicate namespaces"); + } + + @Test + void everyNamespaceIsUsableInAPolicyActionPrefix() { + for (String namespace : AwsServiceNamespaces.all()) { + assertTrue(namespace.matches("[a-z0-9][a-z0-9-]{0,63}"), + namespace + " is not usable as an IAM action prefix"); + } + } + + @Test + void servicesFlociEmulatesArePresent() { + for (String namespace : List.of("iam", "s3", "sts", "dynamodb", "lambda", "sqs", "sns", + "logs", "events", "kms", "secretsmanager", "states", "ecs", "eks")) { + assertTrue(AwsServiceNamespaces.all().contains(namespace), + namespace + " should be in the catalog"); + } + } + + @Test + void aCatalogWithNoNamespacesIsABuildDefect() { + String json = "{\"serviceNamespaces\": []}"; + + assertThrows(IllegalStateException.class, () -> AwsServiceNamespaces.parse( + new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8)))); + } + + @Test + void aCatalogWithABlankNamespaceIsABuildDefect() { + String json = "{\"serviceNamespaces\": [\"s3\", \"\"]}"; + + assertThrows(IllegalStateException.class, () -> AwsServiceNamespaces.parse( + new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8)))); + } + + @Test + void aCatalogMissingTheFieldEntirelyIsABuildDefect() { + String json = "{\"somethingElse\": [\"s3\"]}"; + + assertThrows(IllegalStateException.class, () -> AwsServiceNamespaces.parse( + new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8)))); + } + + @Test + void aWellFormedCatalogParsesInOrder() throws IOException { + String json = "{\"serviceNamespaces\": [\"cloudwatch\", \"iam\", \"s3\"]}"; + + assertEquals(List.of("cloudwatch", "iam", "s3"), AwsServiceNamespaces.parse( + new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8)))); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/ServiceLastAccessedIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/ServiceLastAccessedIntegrationTest.java index 07703f74f3..0aa666d95d 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iam/ServiceLastAccessedIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iam/ServiceLastAccessedIntegrationTest.java @@ -172,6 +172,103 @@ class ServiceLastAccessedIntegrationTest { .body(not(containsString("dynamodb"))); } + /** + * A policy granting {@code "Action": "*"} reaches every service, and AWS lists them all. The + * grant names no namespace, so this only works with a catalog to expand it against (#4487). + */ + @Test + void getServiceLastAccessedDetailsExpandsAWildcardActionToEveryService() { + String tag = suffix(); + String userName = "laa-star-" + tag; + String arn = createUser(userName); + iam("PutUserPolicy").formParam("UserName", userName) + .formParam("PolicyName", "laa-star-policy-" + tag) + .formParam("PolicyDocument", "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\"," + + "\"Action\":\"*\",\"Resource\":\"*\"}]}") + .when().post("/").then().statusCode(200); + + // MaxItems is raised so one page can show the whole expansion. + String body = iam("GetServiceLastAccessedDetails").formParam("JobId", generateJobFor(arn)) + .formParam("MaxItems", "1000") + .when().post("/").then() + .statusCode(200) + // Services the policy never names, reachable only through the wildcard. + .body(containsString("s3")) + .body(containsString("dynamodb")) + .body(containsString("cloudwatch")) + .extract().asString(); + + int reported = body.split("", -1).length - 1; + assertTrue(reported > 300, "expected a wildcard grant to reach every service, got " + reported); + // CloudWatch's credential scope must not leak in as though it were an IAM namespace. + assertTrue(!body.contains("monitoring"), + "monitoring is a credential scope, not an IAM namespace, in: " + body); + } + + /** A globbed prefix names a set of namespaces, so it expands to the ones it matches. */ + @Test + void getServiceLastAccessedDetailsExpandsAGlobbedServicePrefix() { + String tag = suffix(); + String userName = "laa-glob-" + tag; + String arn = createUser(userName); + iam("PutUserPolicy").formParam("UserName", userName) + .formParam("PolicyName", "laa-glob-policy-" + tag) + .formParam("PolicyDocument", "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\"," + + "\"Action\":\"dynamodb*:*\",\"Resource\":\"*\"}]}") + .when().post("/").then().statusCode(200); + + iam("GetServiceLastAccessedDetails").formParam("JobId", generateJobFor(arn)) + .formParam("MaxItems", "1000") + .when().post("/").then() + .statusCode(200) + .body(containsString("dynamodb")) + // The glob covers the dynamodb family only, not every service. + .body(not(containsString("s3"))); + } + + /** {@code Allow} with {@code NotAction} reaches every service the list does not carve out. */ + @Test + void getServiceLastAccessedDetailsExpandsNotActionToEverythingNotCarvedOut() { + String tag = suffix(); + String userName = "laa-notaction-expand-" + tag; + String arn = createUser(userName); + iam("PutUserPolicy").formParam("UserName", userName) + .formParam("PolicyName", "laa-notaction-expand-policy-" + tag) + .formParam("PolicyDocument", "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\"," + + "\"NotAction\":\"iam:*\",\"Resource\":\"*\"}]}") + .when().post("/").then().statusCode(200); + + // The whole expansion has to be in view for the carve-out to be the reason iam is absent. + iam("GetServiceLastAccessedDetails").formParam("JobId", generateJobFor(arn)) + .formParam("MaxItems", "1000") + .when().post("/").then() + .statusCode(200) + .body(containsString("s3")) + // iam is carved out entirely, so it is the one service not reachable. + .body(not(containsString("iam"))); + } + + /** + * A namespace the policy names outright is reported whether or not the vendored catalog knows + * it, so a catalog behind an AWS launch still reports an explicitly named service. + */ + @Test + void getServiceLastAccessedDetailsKeepsALiterallyNamedNamespaceUnknownToTheCatalog() { + String tag = suffix(); + String userName = "laa-unknown-ns-" + tag; + String arn = createUser(userName); + iam("PutUserPolicy").formParam("UserName", userName) + .formParam("PolicyName", "laa-unknown-ns-policy-" + tag) + .formParam("PolicyDocument", "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\"," + + "\"Action\":\"somefutureservice:DoThing\",\"Resource\":\"*\"}]}") + .when().post("/").then().statusCode(200); + + iam("GetServiceLastAccessedDetails").formParam("JobId", generateJobFor(arn)) + .when().post("/").then() + .statusCode(200) + .body(containsString("somefutureservice")); + } + /** A managed-policy ARN reports on that policy's own document, not on any identity. */ @Test void getServiceLastAccessedDetailsForAPolicyArnUsesThatPolicysDocument() { diff --git a/tools/aws/regen_service_namespaces.py b/tools/aws/regen_service_namespaces.py new file mode 100644 index 0000000000..e564303a9d --- /dev/null +++ b/tools/aws/regen_service_namespaces.py @@ -0,0 +1,209 @@ +#!/usr/bin/env python3 +"""Regenerate src/main/resources/aws/iam-service-namespaces.json from AWS's own service list. + +IAM reports which services a principal can reach (`GetServiceLastAccessedDetails`), and a policy +that grants a service without naming it -- `"Action": "*"`, a globbed prefix such as `s3*`, or any +`NotAction` -- can only be expanded against a list of every IAM service namespace. Floci had no +such list, so those grants were left out of the report (#4487). + +botocore is deliberately not the source here, even though every other vendored file in this repo +comes from it. A service's IAM namespace is not any botocore field: CloudWatch's `endpointPrefix` +is `monitoring` and its `serviceId` is `CloudWatch`, while its IAM namespace is `cloudwatch`; CloudWatch +Logs has `serviceId` `CloudWatch Logs` against an IAM namespace of `logs`. Any rule over botocore +metadata is wrong for some service, and a wrong namespace is worse than a missing one, because it +names something that does not exist in IAM. + +The source is AWS's Service Reference Information index, which publishes one entry per service +whose `service` field is exactly the IAM namespace: + + https://servicereference.us-east-1.amazonaws.com/ + +That index is a live endpoint rather than a pinned dependency, so unlike `regen_partitions.py` a +fresh generation is not byte-identical: AWS adds services whenever it ships them. Byte-equality is +therefore the wrong gate, but it is not the guarantee that matters. What must be guaranteed is that +nothing in the vendored file is invented, and that is checkable directly: + +- `--check` is offline and structural. The file must be sorted, free of duplicates, every entry + usable as a namespace, and it must carry the cases that justify not deriving this from botocore + (`cloudwatch` present, `monitoring` absent). This catches corruption and hand-editing of shape. +- `--verify` is the real gate and needs the network. Every namespace in the vendored file must + still exist in the live index. A hand-typed or mistyped namespace fails, because AWS does not + publish it; a namespace AWS has retired fails, because the file now claims something untrue. + Services AWS has *added* since the last regeneration are reported but do not fail, since the file + being behind makes the report incomplete rather than wrong, and failing on that would break this + repo's build for someone else's launch. + +Run from anywhere in the repo: + python3 tools/aws/regen_service_namespaces.py # rewrite the vendored file in place + python3 tools/aws/regen_service_namespaces.py --check # offline: shape of the vendored file + python3 tools/aws/regen_service_namespaces.py --verify # online: nothing in it is invented + python3 tools/aws/regen_service_namespaces.py --source # read a saved index instead +""" +from __future__ import annotations + +import argparse +import json +import re +import sys +import urllib.request +from datetime import datetime, timezone +from pathlib import Path + +REPO_ROOT = Path(__file__).resolve().parents[2] +OUTPUT = REPO_ROOT / "src/main/resources/aws/iam-service-namespaces.json" +INDEX_URL = "https://servicereference.us-east-1.amazonaws.com/" +FETCH_TIMEOUT_SECONDS = 30 + +# serviceNamespaceType in botocore's IAM model is `[\w-]*`, max 64. Every namespace AWS publishes +# is a subset of this; anything outside it would not be usable in a policy, so it is an error +# rather than something to sanitise silently. +NAMESPACE_RE = re.compile(r"^[a-z0-9][a-z0-9-]{0,63}$") + + +def fetch_index(source: Path | None) -> tuple[list[dict], str]: + """The Service Reference index and a provenance label for where it came from.""" + if source is not None: + return json.loads(source.read_text(encoding="utf-8")), f"--source {source}" + request = urllib.request.Request(INDEX_URL, headers={"Accept": "application/json"}) + with urllib.request.urlopen(request, timeout=FETCH_TIMEOUT_SECONDS) as response: + payload = response.read().decode("utf-8") + return json.loads(payload), INDEX_URL + + +def namespaces_from(index: list[dict]) -> list[str]: + """The sorted, de-duplicated IAM namespaces named by the index.""" + if not isinstance(index, list) or not index: + raise ValueError("the service reference index must be a non-empty list") + found: set[str] = set() + for entry in index: + if not isinstance(entry, dict) or "service" not in entry: + raise ValueError(f"index entry without a 'service' field: {entry!r}") + namespace = entry["service"] + if not NAMESPACE_RE.match(namespace): + raise ValueError(f"{namespace!r} is not usable as an IAM service namespace") + found.add(namespace) + return sorted(found) + + +def build(index: list[dict], provenance: str) -> dict: + return { + "_source": { + "generator": "tools/aws/regen_service_namespaces.py", + "index": provenance, + "retrieved": datetime.now(timezone.utc).strftime("%Y-%m-%d"), + "note": "make iam-namespaces-verify checks every entry still exists upstream.", + }, + "serviceNamespaces": namespaces_from(index), + } + + +def render(document: dict) -> str: + return json.dumps(document, indent=2) + "\n" + + +def validate(document: dict) -> list[str]: + """Problems that make the vendored file unusable, rather than merely out of date.""" + problems: list[str] = [] + namespaces = document.get("serviceNamespaces") + if not isinstance(namespaces, list) or not namespaces: + return ["serviceNamespaces is missing or empty"] + if namespaces != sorted(namespaces): + problems.append("serviceNamespaces is not sorted") + if len(namespaces) != len(set(namespaces)): + problems.append("serviceNamespaces contains duplicates") + for namespace in namespaces: + if not isinstance(namespace, str) or not NAMESPACE_RE.match(namespace): + problems.append(f"{namespace!r} is not usable as an IAM service namespace") + # A handful of namespaces whose value is the whole point of not deriving this from botocore. + for required in ("cloudwatch", "logs", "iam", "s3", "sts"): + if required not in namespaces: + problems.append(f"expected {required!r} to be present") + if "monitoring" in namespaces: + problems.append("'monitoring' is a credential scope, not an IAM namespace") + return problems + + +def verify_against(vendored: list[str], upstream: list[str]) -> tuple[list[str], list[str]]: + """Namespaces the vendored file claims but AWS does not publish, and ones AWS has added.""" + upstream_set = set(upstream) + invented = [namespace for namespace in vendored if namespace not in upstream_set] + added = sorted(upstream_set.difference(vendored)) + return invented, added + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("--check", action="store_true", + help="offline: validate the shape of the vendored file") + parser.add_argument("--verify", action="store_true", + help="online: every vendored namespace must still exist in the live index") + parser.add_argument("--source", type=Path, default=None, + help="read a saved copy of the index instead of fetching it") + parser.add_argument("--output", type=Path, default=OUTPUT, help=argparse.SUPPRESS) + args = parser.parse_args(argv) + + if args.check: + if not args.output.exists(): + print(f"error: {args.output} does not exist", file=sys.stderr) + return 1 + problems = validate(json.loads(args.output.read_text(encoding="utf-8"))) + for problem in problems: + print(f"error: {problem}", file=sys.stderr) + if problems: + return 1 + count = len(json.loads(args.output.read_text(encoding="utf-8"))["serviceNamespaces"]) + print(f"{args.output.relative_to(REPO_ROOT)} is well-formed ({count} namespaces)") + return 0 + + if args.verify: + if not args.output.exists(): + print(f"error: {args.output} does not exist", file=sys.stderr) + return 1 + vendored = json.loads(args.output.read_text(encoding="utf-8"))["serviceNamespaces"] + try: + index, provenance = fetch_index(args.source) + upstream = namespaces_from(index) + except (OSError, ValueError) as e: + # Distinct from a data problem: the gate could not run, rather than having found + # something invented. Separate exit code so CI can tell the two apart. ValueError + # covers a malformed index, including the JSONDecodeError a truncated or non-JSON + # response raises, which is just as much "could not verify" as an unreachable host. + print(f"error: could not read the service reference index ({e})", file=sys.stderr) + return 2 + invented, added = verify_against(vendored, upstream) + for namespace in invented: + print(f"error: {namespace!r} is not published by {provenance}", file=sys.stderr) + if invented: + print(f"error: {len(invented)} vendored namespace(s) do not exist upstream; " + f"the file claims something untrue.", file=sys.stderr) + return 1 + if added: + print(f"{args.output.relative_to(REPO_ROOT)}: all {len(vendored)} namespaces verified. " + f"AWS has since added {len(added)}, so the report is incomplete but not wrong " + f"(run without --verify to refresh): {', '.join(added[:10])}" + f"{'...' if len(added) > 10 else ''}") + else: + print(f"{args.output.relative_to(REPO_ROOT)}: all {len(vendored)} namespaces verified " + f"against {provenance}, none added upstream.") + return 0 + + try: + index, provenance = fetch_index(args.source) + document = build(index, provenance) + except (OSError, ValueError) as e: + print(f"error: could not read the service reference index ({e})", file=sys.stderr) + return 2 + problems = validate(document) + for problem in problems: + print(f"error: {problem}", file=sys.stderr) + if problems: + return 1 + args.output.write_text(render(document), encoding="utf-8") + print(f"wrote {args.output.relative_to(REPO_ROOT)} " + f"({len(document['serviceNamespaces'])} namespaces from {provenance})") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/aws/test_regen_service_namespaces.py b/tools/aws/test_regen_service_namespaces.py new file mode 100644 index 0000000000..2033bf7d7c --- /dev/null +++ b/tools/aws/test_regen_service_namespaces.py @@ -0,0 +1,139 @@ +"""Tests for regen_service_namespaces. + +Run with: pytest tools/aws -q (or: make iam-namespaces-test) +""" +from __future__ import annotations + +import json + +import pytest + +import regen_service_namespaces as r + + +def index(*services: str) -> list[dict]: + return [{"service": name, "url": f"https://example.test/{name}.json"} for name in services] + + +# --------------------------------------------------------------------------- # +# namespaces_from: what the index is allowed to contain +# --------------------------------------------------------------------------- # +def test_namespaces_are_sorted_and_deduplicated(): + assert r.namespaces_from(index("s3", "cloudwatch", "s3", "iam")) == ["cloudwatch", "iam", "s3"] + + +def test_hyphens_and_digits_are_accepted(): + assert r.namespaces_from(index("execute-api", "s3", "route53domains", "a4b")) == [ + "a4b", "execute-api", "route53domains", "s3"] + + +@pytest.mark.parametrize("payload, reason", [ + ([], "empty"), + ({"service": "s3"}, "not a list"), + ([{"url": "x"}], "no service field"), +]) +def test_malformed_index_is_rejected(payload, reason): + with pytest.raises(ValueError): + r.namespaces_from(payload) + + +@pytest.mark.parametrize("namespace", [ + "S3", # serviceNamespaceType is lowercase in practice + "cloud watch", # a space is not usable in an action prefix + "cloud_watch", # underscores do not appear in AWS namespaces + "-leading", # must start with a letter or digit + "a" * 65, # serviceNamespaceType is max 64 + "", +]) +def test_unusable_namespace_is_rejected(namespace): + with pytest.raises(ValueError): + r.namespaces_from([{"service": namespace}]) + + +# --------------------------------------------------------------------------- # +# validate: the offline gate over the vendored file +# --------------------------------------------------------------------------- # +def sound() -> list[str]: + return sorted(["cloudwatch", "logs", "iam", "s3", "sts"]) + + +def test_a_sound_document_has_no_problems(): + assert r.validate({"serviceNamespaces": sound()}) == [] + + +def test_unsorted_is_reported(): + assert "serviceNamespaces is not sorted" in r.validate( + {"serviceNamespaces": ["s3", "cloudwatch", "iam", "logs", "sts"]}) + + +def test_duplicates_are_reported(): + assert "serviceNamespaces contains duplicates" in r.validate( + {"serviceNamespaces": sorted(sound() + ["s3"])}) + + +def test_missing_or_empty_is_reported(): + assert r.validate({}) == ["serviceNamespaces is missing or empty"] + assert r.validate({"serviceNamespaces": []}) == ["serviceNamespaces is missing or empty"] + + +def test_a_namespace_botocore_would_have_produced_is_rejected(): + """'monitoring' is CloudWatch's credential scope; using it as an IAM namespace is the bug + this whole file exists to prevent, so the gate names it explicitly.""" + problems = r.validate({"serviceNamespaces": sorted(sound() + ["monitoring"])}) + assert any("credential scope" in p for p in problems) + + +def test_losing_a_sentinel_namespace_is_reported(): + problems = r.validate({"serviceNamespaces": ["iam", "logs", "s3", "sts"]}) + assert any("cloudwatch" in p for p in problems) + + +# --------------------------------------------------------------------------- # +# verify_against: the online gate, which is what stops invented data +# --------------------------------------------------------------------------- # +def test_nothing_invented_and_nothing_added(): + invented, added = r.verify_against(["iam", "s3"], ["iam", "s3"]) + assert invented == [] and added == [] + + +def test_an_invented_namespace_is_caught(): + invented, added = r.verify_against(["iam", "s3", "s3-typo"], ["iam", "s3"]) + assert invented == ["s3-typo"] + assert added == [] + + +def test_a_namespace_aws_retired_is_caught(): + invented, _ = r.verify_against(["iam", "retired-service"], ["iam"]) + assert invented == ["retired-service"] + + +def test_services_aws_added_are_reported_but_not_invented(): + """A vendored file that is merely behind makes the report incomplete, not wrong, so this must + not fail the build: AWS shipping a service is not a defect here.""" + invented, added = r.verify_against(["iam", "s3"], ["brand-new", "iam", "s3"]) + assert invented == [] + assert added == ["brand-new"] + + +# --------------------------------------------------------------------------- # +# build / render: the vendored file itself +# --------------------------------------------------------------------------- # +def test_build_records_provenance_and_namespaces(): + document = r.build(index("s3", "cloudwatch", "logs", "iam", "sts"), "https://example.test/") + assert document["_source"]["index"] == "https://example.test/" + assert document["_source"]["generator"] == "tools/aws/regen_service_namespaces.py" + assert document["serviceNamespaces"] == ["cloudwatch", "iam", "logs", "s3", "sts"] + + +def test_render_is_stable_json_with_a_trailing_newline(): + document = r.build(index("s3", "iam"), "x") + text = r.render(document) + assert text.endswith("\n") + assert json.loads(text) == document + + +def test_check_accepts_the_vendored_file_in_this_repo(): + """The file actually committed here must pass the offline gate.""" + vendored = json.loads(r.OUTPUT.read_text(encoding="utf-8")) + assert r.validate(vendored) == [] + assert len(vendored["serviceNamespaces"]) > 300, "AWS publishes several hundred namespaces"