diff --git a/AGENTS.md b/AGENTS.md index ab4f5e2a55..84a161d42e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -122,8 +122,8 @@ Floci serves every AWS partition, not only the commercial one, so a literal that `aws` into a code path is a bug in a GovCloud, China, ISO or EUSC deployment even when it prints correctly in `us-east-1`. `make partition-check` (CI: Partition Literals) inventories `src/main/java` for `arn:aws:` prefixes, `amazonaws.com` hosts, Route 53 hosted-zone ids, -hand-rolled `arn:aws[a-z-]*:` regexes and `Arn.of(...)` calls with a blank region against -`tools/partition/baseline.tsv`, per file. The baseline is empty, so any new one fails. +hand-rolled `arn:aws[a-z-]*:` regexes, `Arn.of(...)` calls with a blank region and comparisons +with the literal `"aws"` against `tools/partition/baseline.tsv`, per file. The baseline is empty, so any new one fails. A literal in a new file fails, growth in an existing file fails, and a drop fails until you run `make partition-baseline` and commit the smaller baseline. @@ -134,6 +134,12 @@ run `make partition-baseline` and commit the smaller baseline. `Arn.of(service, "", ...)`, which silently means `aws`: use `RegionResolver.buildGlobalArn` for the request's partition, or `Arn.global(partition, ...)` with the resource's own (`AwsRegions.partitionFor(region)` for a bucket or a stack's region). +- Never compare a partition with a literal: `"aws".equals(arn.partition())` is commercial-only + logic that fails silently in every other partition. Compare with the partition the resource + belongs to, `AwsRegions.partitionFor(region)` for a regional resource or the stored ARN's own + partition for a global one, and accept any published partition with `AwsPartitions.find(...)` + when only the shape matters. `"aws"` as an account (managed policies) or a command name is not + a partition: end that line with `// partition-literal: `. - A service principal is `ServicePrincipals.of("")`, never a literal: it is `.amazonaws.com` in every partition, and `ServicePrincipals.canonical` folds the legacy per-partition forms a policy may still use before matching. 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 844577d714..75b0885f19 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 @@ -2023,7 +2023,7 @@ public class IamQueryHandler { // An AWS-managed policy carries the literal "aws" in the account field // (arn:aws:iam::aws:policy/...) and is served from the global catalog, so it is not a // foreign account and must not be rejected as one. - boolean awsManaged = "aws".equals(parsed.accountId()); + boolean awsManaged = "aws".equals(parsed.accountId()); // partition-literal: managed-policy account if (!awsManaged && parsed.accountId() != null && !parsed.accountId().isEmpty() && !parsed.accountId().equals(accountId)) { throw new AwsException("NoSuchEntity", "The ARN " + arn + " cannot be found.", 404); diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/kubernetes/EksTokenMinter.java b/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/kubernetes/EksTokenMinter.java index 31b6f5678f..3870b2e224 100644 --- a/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/kubernetes/EksTokenMinter.java +++ b/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/kubernetes/EksTokenMinter.java @@ -131,7 +131,7 @@ final class EksTokenMinter { } var fileName = Path.of(command).getFileName(); var commandName = fileName == null ? command : fileName.toString(); - if (!"aws".equals(commandName)) { + if (!"aws".equals(commandName)) { // partition-literal: kubeconfig exec command return false; } return findSubcommandIndex(exec.path("args")) >= 0; diff --git a/src/main/java/io/github/hectorvent/floci/services/ssm/SsmService.java b/src/main/java/io/github/hectorvent/floci/services/ssm/SsmService.java index 6d8d06a5b5..57dc82d4ea 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ssm/SsmService.java +++ b/src/main/java/io/github/hectorvent/floci/services/ssm/SsmService.java @@ -366,7 +366,7 @@ public class SsmService implements ResourceProvider { private static void rejectReservedName(String name) { String bare = name == null ? "" : name.startsWith("/") ? name.substring(1) : name; String lower = bare.toLowerCase(Locale.ROOT); - if (lower.equals("aws") || lower.equals("ssm") + if (lower.equals("aws") || lower.equals("ssm") // partition-literal: reserved name prefix || lower.startsWith("aws/") || lower.startsWith("ssm/")) { throw new AwsException("ValidationException", "Parameter name: can't be prefixed with \"aws\" or \"ssm\" (case-insensitive). " diff --git a/tools/partition/partition_literals.py b/tools/partition/partition_literals.py index 86435d82a2..c10121b677 100644 --- a/tools/partition/partition_literals.py +++ b/tools/partition/partition_literals.py @@ -107,6 +107,24 @@ CATEGORIES: tuple[Category, ...] = ( "use Arn.global with the resource's or the request's partition", "code", ), + Category( + "aws-partition-compare", + re.compile( + r'"aws"\s*\.\s*equals(?:IgnoreCase)?\s*\(' + r'|\.\s*equals(?:IgnoreCase)?\s*\(\s*"aws"\s*\)' + # Objects.equals with "aws" as either argument; the other argument may hold one level of + # nested calls, and the match ends at this call's own closing parenthesis. + r'|Objects\.equals\(\s*"aws"\s*,' + r'|Objects\.equals\(\s*(?:[^(),;"]|"[^"]*"|\([^()]*\))*,\s*"aws"\s*\)' + # A switch label naming "aws", alone or in a list (case "aws" ->, case "x", "aws":). + r'|\bcase\s+(?:"[^"]*"\s*,\s*)*"aws"\s*(?:->|:|,)' + ), + True, + "a value compared with, or switched on, the literal \"aws\", which as a partition check holds only " + "in the commercial partition; compare with AwsRegions.partitionFor(region) or the stored ARN's own " + "partition, or escape a non-partition use (an account, a command name)", + "code", + ), ) CATEGORY_BY_NAME = {category.name: category for category in CATEGORIES} @@ -378,22 +396,23 @@ def format_audit(findings: list[Finding], baseline: Counter) -> str: per_package[package_of(finding.path)][finding.category] += 1 totals[finding.category] += 1 width = max([len("package"), len("total")] + [len(p) for p in per_package]) + 2 - header = f"{'package':<{width}}" + "".join(f"{name:>19}" for name in names) + f"{'total':>8}" + column = max(19, max(len(name) for name in names) + 2) + header = f"{'package':<{width}}" + "".join(f"{name:>{column}}" for name in names) + f"{'total':>8}" out = [header, "-" * len(header)] for package, counter in sorted(per_package.items(), key=lambda item: (-sum(item[1].values()), item[0])): out.append( f"{package:<{width}}" - + "".join(f"{counter.get(name, 0):>19}" for name in names) + + "".join(f"{counter.get(name, 0):>{column}}" for name in names) + f"{sum(counter.values()):>8}" ) out.append("-" * len(header)) out.append( f"{'total':<{width}}" - + "".join(f"{totals.get(name, 0):>19}" for name in names) + + "".join(f"{totals.get(name, 0):>{column}}" for name in names) + f"{sum(totals.values()):>8}" ) gate = "".join( - f"{'gated' if category.gated else 'report-only':>19}" for category in CATEGORIES + f"{'gated' if category.gated else 'report-only':>{column}}" for category in CATEGORIES ) out.append(f"{'':<{width}}{gate}") if baseline: diff --git a/tools/partition/test_partition_literals.py b/tools/partition/test_partition_literals.py index d122b08221..a3e5a52285 100644 --- a/tools/partition/test_partition_literals.py +++ b/tools/partition/test_partition_literals.py @@ -186,6 +186,42 @@ def test_blank_region_arn_matches_a_call_split_across_lines(tmp_path): assert [f.line for f in findings] == [2] +@pytest.mark.parametrize("code, expected", [ + ('"aws".equals(arn.partition())', True), + ('!"aws".equalsIgnoreCase(partition)', True), + ('partition.equals("aws")', True), + ('Objects.equals(parsed.partition(), "aws")', True), + ('Objects.equals("aws", partition)', True), + ('Objects.equals(arn.partition(), "aws")', True), + ('foo(Objects.equals(a, b), "aws")', False), + ('Objects.equals(a, b) || log("aws")', False), + ('switch (arn.partition()) { case "aws" -> 1; default -> 2; }', True), + ('case "aws":', True), + ('case "aws-cn", "aws" ->', True), + ('case "aws", "aws-cn" ->', True), + ('case "aws-cn" ->', False), + ('AwsRegions.partitionFor(region).equals(arn.partition())', False), + ('"aws-cn".equals(partition)', False), + ('name.equals("awsome")', False), +]) +def test_aws_partition_compare_matches_comparisons_with_the_literal_aws(code, expected): + category = p.CATEGORY_BY_NAME["aws-partition-compare"] + assert (category.regex.search(code) is not None) is expected + + +def test_aws_partition_compare_is_counted_and_an_escape_excuses_its_line(tmp_path): + write_java(tmp_path, "a/A.java", ( + 'class A {\n' + ' boolean commercial = "aws".equals(arn.partition());\n' + ' boolean managed = "aws".equals(arn.accountId()); // partition-literal: the managed-policy account\n' + ' // "aws".equals(partition) in a comment never counts\n' + '}\n' + )) + findings = p.collect_findings(tmp_path, []) + assert p.count(findings) == Counter({("aws-partition-compare", "a/A.java"): 1}) + assert [(f.line, f.counted) for f in findings] == [(2, True), (3, False)] + + def test_blank_region_arn_is_a_code_category_and_never_matches_literals(tmp_path): write_java(tmp_path, "a/A.java", ( 'class A {\n'