mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(core): mint every regionless ARN in its partition and gate blank-region Arn.of calls (#4787)
* fix(core): mint every regionless ARN in its partition and gate blank-region Arn.of calls Part of #4272 (P10a). Arn.of derives the partition from the region, so a blank region always minted arn:aws:, and the partition literal gate could not see it because it is a call shape, not a literal. Sixteen call sites did this, and three gated literals were left: - RdsSigV4Validator built the rds-db:connect resource as arn:aws:rds-db:, so a China IAM policy naming arn:aws-cn:rds-db: never matched and IAM auth to an RDS proxy was denied there. - CloudFront, Organizations, Cost Explorer anomaly monitors and the SSO portal role ARN now take the request's partition (RegionResolver injected). - S3 bucket ARNs (event notifications, AWS::S3::Bucket Arn, Cost Explorer S3 usage) take the bucket's or the stack region's partition; the Lambda CFN default role, the Kinesis ESM invokeIdentityArn, the EC2 launch template CreatedBy and the SQS AddPermission root principal take their own region's. - FlinkContainerManager's fallback key goes through Arn.of, and the CloudFormation S3 TemplateURL host check accepts every partition's DNS suffix. partition_literals.py gains a gated, code-scoped blank-region-arn category (Arn.of with a "" or null region, comments excluded). The baseline is now empty, so any new literal or blank-region mint fails Partition Literals. * fix(core): scan blank-region Arn.of calls across lines and skip text blocks Greptile on #4787: the blank-region-arn category ran per line, so a call whose region argument sits on the next line escaped it, and text-block contents were kept, so an example inside one would count as a call against the empty baseline. code_text now blanks comments and text blocks over the whole source and the code categories match across lines, reporting the line the call starts on.
This commit is contained in:
1 parent
3a56aad670
commit
27ddf0bb00
28 files changed
+278
-70
No files matched your search
@@ -121,14 +121,19 @@ Floci must implement real AWS wire protocols.
|
||||
Floci serves every AWS partition, not only the commercial one, so a literal that bakes
|
||||
`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
|
||||
and hand-rolled `arn:aws[a-z-]*:` regexes against `tools/partition/baseline.tsv`, per file.
|
||||
`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.
|
||||
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.
|
||||
|
||||
- Mint ARNs through `AwsArnUtils.Arn.of(...)` / `RegionResolver.buildArn(...)`, recognise
|
||||
them with `AwsArnUtils.isArn` / `PARTITION_REGEX`, and derive hosts from the region's
|
||||
DNS suffix (`AwsRegions.dnsSuffixFor`).
|
||||
- A regionless ARN (IAM, STS, CloudFront, Organizations, an S3 bucket) never goes through
|
||||
`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).
|
||||
- A service principal is `ServicePrincipals.of("<service>")`, never a literal: it is
|
||||
`<service>.amazonaws.com` in every partition, and `ServicePrincipals.canonical` folds the
|
||||
legacy per-partition forms a policy may still use before matching.
|
||||
|
||||
@@ -28,11 +28,10 @@ public final class AwsArnUtils {
|
||||
* gets {@code aws-us-gov}, and everything else gets {@code aws}. See
|
||||
* {@link AwsRegions#partitionFor}.
|
||||
*
|
||||
* <p>Global services pass an empty region, and nothing in that argument can say which
|
||||
* partition they belong to, so this keeps {@code aws} for them. A call site that knows the
|
||||
* request's partition mints those through {@link #global} (or
|
||||
* {@link RegionResolver#buildGlobalArn}); the fallback here stays only until every
|
||||
* regionless call site has moved, after which a blank region becomes an error.
|
||||
* <p>A blank region says nothing about the partition, so it falls back to {@code aws}.
|
||||
* A regionless ARN is minted through {@link #global} or
|
||||
* {@link RegionResolver#buildGlobalArn} instead; {@code make partition-check} fails a call
|
||||
* that passes a literal blank region here.
|
||||
*/
|
||||
public static Arn of(String service, String region, String accountId, String resource) {
|
||||
return new Arn(AwsRegions.partitionFor(region), service, region, accountId, resource);
|
||||
|
||||
@@ -9,6 +9,7 @@ import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.PaginatedResult;
|
||||
import io.github.hectorvent.floci.core.common.Pagination;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.common.Resettable;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
@@ -41,19 +42,22 @@ public class CostAnomalyService implements Resettable {
|
||||
private final AccountAwareStorageBackend<ObjectNode> monitors;
|
||||
private final AccountAwareStorageBackend<ObjectNode> subscriptions;
|
||||
private final ObjectMapper mapper;
|
||||
private final RegionResolver regionResolver;
|
||||
|
||||
@Inject
|
||||
public CostAnomalyService(StorageFactory storageFactory, ObjectMapper mapper) {
|
||||
public CostAnomalyService(StorageFactory storageFactory, ObjectMapper mapper, RegionResolver regionResolver) {
|
||||
this(storageFactory.create("ce", "anomaly-monitors.json", new TypeReference<Map<String, ObjectNode>>() {}),
|
||||
storageFactory.create("ce", "anomaly-subscriptions.json", new TypeReference<Map<String, ObjectNode>>() {}),
|
||||
mapper);
|
||||
mapper, regionResolver);
|
||||
}
|
||||
|
||||
CostAnomalyService(AccountAwareStorageBackend<ObjectNode> monitors,
|
||||
AccountAwareStorageBackend<ObjectNode> subscriptions, ObjectMapper mapper) {
|
||||
AccountAwareStorageBackend<ObjectNode> subscriptions, ObjectMapper mapper,
|
||||
RegionResolver regionResolver) {
|
||||
this.monitors = monitors;
|
||||
this.subscriptions = subscriptions;
|
||||
this.mapper = mapper;
|
||||
this.regionResolver = regionResolver;
|
||||
}
|
||||
|
||||
public synchronized ObjectNode createMonitor(JsonNode request) {
|
||||
@@ -466,7 +470,7 @@ public class CostAnomalyService implements Resettable {
|
||||
}
|
||||
|
||||
private String arn(String account, String type) {
|
||||
return AwsArnUtils.Arn.of("ce", "", account, type + "/" + UUID.randomUUID()).toString();
|
||||
return regionResolver.buildGlobalArn("ce", account, type + "/" + UUID.randomUUID());
|
||||
}
|
||||
|
||||
private boolean contains(JsonNode values, String value) {
|
||||
|
||||
+3
-1
@@ -1,6 +1,7 @@
|
||||
package io.github.hectorvent.floci.services.ce.enumerator;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsRegions;
|
||||
import io.github.hectorvent.floci.core.common.ResourceUsageEnumerator;
|
||||
import io.github.hectorvent.floci.core.common.UsageLine;
|
||||
import io.github.hectorvent.floci.services.s3.S3Service;
|
||||
@@ -77,7 +78,8 @@ public class S3UsageEnumerator implements ResourceUsageEnumerator {
|
||||
STANDARD_STORAGE_USAGE_TYPE, "StandardStorage",
|
||||
UsageLine.RECORD_TYPE_USAGE,
|
||||
"000000000000",
|
||||
AwsArnUtils.Arn.of("s3", "", "", bucket.getName()).toString(),
|
||||
AwsArnUtils.Arn.global(AwsRegions.partitionFor(bucketRegion), "s3", "",
|
||||
bucket.getName()).toString(),
|
||||
tags,
|
||||
gbMonths,
|
||||
"GB-Mo"));
|
||||
|
||||
+4
-3
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.cloudformation;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.AwsPartitions;
|
||||
import io.github.hectorvent.floci.core.common.AwsRegions;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.common.RequestContext;
|
||||
@@ -2402,8 +2403,8 @@ public class CloudFormationService implements ResourceProvider {
|
||||
/**
|
||||
* Whether the host is the S3 <em>service</em> endpoint rather than a bucket-qualified one:
|
||||
* {@code s3.<suffix>} and the regional {@code s3.<region>.<suffix>}, for a local hostname as
|
||||
* much as for {@code amazonaws.com}. A URL against the service endpoint is path-style, so its
|
||||
* bucket is the first path segment.
|
||||
* much as for any partition's DNS suffix ({@code amazonaws.com}, {@code amazonaws.com.cn}, ...).
|
||||
* A URL against the service endpoint is path-style, so its bucket is the first path segment.
|
||||
*
|
||||
* <p>The first label alone does not decide it, because a bucket may legally be named
|
||||
* {@code s3}: that makes {@code s3.s3.us-east-1.amazonaws.com} and {@code s3.s3.<suffix>}
|
||||
@@ -2453,7 +2454,7 @@ public class CloudFormationService implements ResourceProvider {
|
||||
}
|
||||
|
||||
private static boolean isEndpointSuffix(String candidate, String hostnameSuffix) {
|
||||
if (candidate.equals("amazonaws.com") || candidate.equals("localhost")) {
|
||||
if (AwsPartitions.isDnsSuffix(candidate) || candidate.equals("localhost")) {
|
||||
return true;
|
||||
}
|
||||
return hostnameSuffix != null && !hostnameSuffix.isBlank()
|
||||
|
||||
+3
-1
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.AwsRegions;
|
||||
import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
|
||||
import io.github.hectorvent.floci.services.cloudformation.InlineZipPackager;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||
@@ -209,7 +210,8 @@ public class LambdaCfnProvisioner implements CfnResourceProvisioner {
|
||||
createRequest.put("PackageType", packageType);
|
||||
|
||||
String role = ctx.resolveOrDefault(props, "Role",
|
||||
AwsArnUtils.Arn.of("iam", "", ctx.accountId(), "role/default").toString());
|
||||
AwsArnUtils.Arn.global(AwsRegions.partitionFor(ctx.region()), "iam", ctx.accountId(),
|
||||
"role/default").toString());
|
||||
createRequest.put("Role", role);
|
||||
configRequest.put("Role", role);
|
||||
|
||||
|
||||
+3
-1
@@ -6,6 +6,7 @@ import io.github.hectorvent.floci.core.common.AwsEndpoints;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.AwsNamespaces;
|
||||
import io.github.hectorvent.floci.core.common.AwsPartitions;
|
||||
import io.github.hectorvent.floci.core.common.AwsRegions;
|
||||
import io.github.hectorvent.floci.core.common.XmlBuilder;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||
import io.github.hectorvent.floci.services.s3.S3Service;
|
||||
@@ -86,7 +87,8 @@ public class S3CfnProvisioner implements CfnResourceProvisioner {
|
||||
applyLifecycleConfiguration(bucketName, props, ctx);
|
||||
applyBucketTags(bucketName, props, ctx);
|
||||
r.setPhysicalId(bucketName);
|
||||
r.getAttributes().put("Arn", AwsArnUtils.Arn.of("s3", "", "", bucketName).toString());
|
||||
r.getAttributes().put("Arn",
|
||||
AwsArnUtils.Arn.global(AwsRegions.partitionFor(ctx.region()), "s3", "", bucketName).toString());
|
||||
r.getAttributes().put("DomainName", AwsEndpoints.s3Host(bucketName, ctx.region()));
|
||||
r.getAttributes().put("RegionalDomainName", AwsEndpoints.s3RegionalHost(bucketName, ctx.region()));
|
||||
if (AwsPartitions.forRegionOrCommercial(ctx.region()).supportsS3DualStack(ctx.region())) {
|
||||
|
||||
+2
-5
@@ -1,6 +1,5 @@
|
||||
package io.github.hectorvent.floci.services.cloudfront;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.AwsNamespaces;
|
||||
import io.github.hectorvent.floci.core.common.XmlBuilder;
|
||||
@@ -960,8 +959,7 @@ public class CloudFrontController {
|
||||
.elem("Runtime", fn.getRuntime() != null ? fn.getRuntime() : "cloudfront-js-2.0")
|
||||
.end("FunctionConfig")
|
||||
.start("FunctionMetadata")
|
||||
.elem("FunctionARN", AwsArnUtils.Arn.of("cloudfront", "", service.getAccountId(),
|
||||
"function/" + fn.getName()).toString())
|
||||
.elem("FunctionARN", service.arn("function/" + fn.getName()))
|
||||
.elem("Stage", fn.getStage())
|
||||
.elem("CreatedTime", fn.getCreatedTime() != null ? fn.getCreatedTime().toString() : "")
|
||||
.elem("LastModifiedTime",
|
||||
@@ -2409,8 +2407,7 @@ public class CloudFrontController {
|
||||
.elem("Runtime", fn.getRuntime() != null ? fn.getRuntime() : "cloudfront-js-2.0")
|
||||
.end("FunctionConfig")
|
||||
.start("FunctionMetadata")
|
||||
.elem("FunctionARN",
|
||||
AwsArnUtils.Arn.of("cloudfront", "", service.getAccountId(), "function/" + fn.getName()).toString())
|
||||
.elem("FunctionARN", service.arn("function/" + fn.getName()))
|
||||
.elem("Stage", fn.getStage())
|
||||
.elem("CreatedTime", fn.getCreatedTime() != null ? fn.getCreatedTime().toString() : "")
|
||||
.elem("LastModifiedTime",
|
||||
|
||||
+11
-8
@@ -2,8 +2,8 @@ package io.github.hectorvent.floci.services.cloudfront;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.common.dns.EmbeddedDnsServer;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
@@ -120,6 +120,7 @@ public class CloudFrontService {
|
||||
private final StorageBackend<String, FieldLevelEncryptionProfile> fleProfileStore;
|
||||
private final StorageBackend<String, MonitoringSubscription> monitoringStore;
|
||||
private final String accountId;
|
||||
private final RegionResolver regionResolver;
|
||||
private final String domainSuffix;
|
||||
/**
|
||||
* Host suffixes under which every distribution is served as {@code <id><suffix>}, whatever
|
||||
@@ -133,7 +134,7 @@ public class CloudFrontService {
|
||||
private final List<String> localDeliverySuffixes;
|
||||
|
||||
@Inject
|
||||
public CloudFrontService(StorageFactory factory, EmulatorConfig config) {
|
||||
public CloudFrontService(StorageFactory factory, EmulatorConfig config, RegionResolver regionResolver) {
|
||||
this.distStore = factory.create("cloudfront", "cloudfront-distributions.json",
|
||||
new TypeReference<Map<String, Distribution>>() {});
|
||||
this.invalidationStore = factory.create("cloudfront", "cloudfront-invalidations.json",
|
||||
@@ -169,6 +170,7 @@ public class CloudFrontService {
|
||||
this.monitoringStore = factory.create("cloudfront", "cloudfront-monitoring-subscriptions.json",
|
||||
new TypeReference<Map<String, MonitoringSubscription>>() {});
|
||||
this.accountId = config.defaultAccountId();
|
||||
this.regionResolver = regionResolver;
|
||||
this.domainSuffix = config.services().cloudfront().domainSuffix();
|
||||
this.localDeliverySuffixes = localDeliverySuffixes(config);
|
||||
}
|
||||
@@ -182,7 +184,7 @@ public class CloudFrontService {
|
||||
validateTrustedKeyGroups(dist.getConfig());
|
||||
String id = generateDistributionId();
|
||||
dist.setId(id);
|
||||
dist.setArn(AwsArnUtils.Arn.of("cloudfront", "", accountId, "distribution/" + id).toString());
|
||||
dist.setArn(arn("distribution/" + id));
|
||||
dist.setDomainName(domainNameFor(id));
|
||||
dist.setStatus("Deployed");
|
||||
dist.setLastModifiedTime(Instant.now());
|
||||
@@ -1757,7 +1759,7 @@ public class CloudFrontService {
|
||||
// ── Realtime Log Configs ──────────────────────────────────────────────────
|
||||
|
||||
public synchronized RealtimeLogConfig createRealtimeLogConfig(RealtimeLogConfig cfg) {
|
||||
String arn = AwsArnUtils.Arn.of("cloudfront", "", accountId, "realtime-log-config/" + cfg.getName()).toString();
|
||||
String arn = arn("realtime-log-config/" + cfg.getName());
|
||||
cfg.setArn(arn);
|
||||
realtimeLogConfigStore.put(cfg.getName(), cfg);
|
||||
return cfg;
|
||||
@@ -1777,7 +1779,7 @@ public class CloudFrontService {
|
||||
|
||||
public synchronized RealtimeLogConfig updateRealtimeLogConfig(RealtimeLogConfig updated) {
|
||||
getRealtimeLogConfig(updated.getName());
|
||||
String arn = AwsArnUtils.Arn.of("cloudfront", "", accountId, "realtime-log-config/" + updated.getName()).toString();
|
||||
String arn = arn("realtime-log-config/" + updated.getName());
|
||||
updated.setArn(arn);
|
||||
realtimeLogConfigStore.put(updated.getName(), updated);
|
||||
return updated;
|
||||
@@ -1800,7 +1802,7 @@ public class CloudFrontService {
|
||||
public synchronized StreamingDistribution createStreamingDistribution(StreamingDistribution sd) {
|
||||
String id = generateDistributionId();
|
||||
sd.setId(id);
|
||||
sd.setArn(AwsArnUtils.Arn.of("cloudfront", "", accountId, "streaming-distribution/" + id).toString());
|
||||
sd.setArn(arn("streaming-distribution/" + id));
|
||||
sd.setDomainName(domainNameFor(id));
|
||||
sd.setStatus("Deployed");
|
||||
sd.setLastModifiedTime(Instant.now());
|
||||
@@ -1960,8 +1962,9 @@ public class CloudFrontService {
|
||||
|
||||
// ── Helpers ───────────────────────────────────────────────────────────────
|
||||
|
||||
public String getAccountId() {
|
||||
return accountId;
|
||||
/** A CloudFront ARN: global, so it carries no region and takes the request's partition. */
|
||||
public String arn(String resource) {
|
||||
return regionResolver.buildGlobalArn("cloudfront", accountId, resource);
|
||||
}
|
||||
|
||||
private static String generateDistributionId() {
|
||||
|
||||
@@ -6415,7 +6415,8 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
|
||||
launchTemplate.setLaunchTemplateId("lt-" + randomHex(17));
|
||||
launchTemplate.setLaunchTemplateName(name);
|
||||
launchTemplate.setCreateTime(Instant.now());
|
||||
launchTemplate.setCreatedBy(AwsArnUtils.Arn.of("iam", "", callerAccountId(), "root").toString());
|
||||
launchTemplate.setCreatedBy(
|
||||
AwsArnUtils.Arn.global(AwsRegions.partitionFor(region), "iam", callerAccountId(), "root").toString());
|
||||
launchTemplate.setRegion(region);
|
||||
launchTemplate.setData(new LaunchTemplateData(data != null ? data : new LaunchTemplateData()));
|
||||
if (launchTemplateTags != null && !launchTemplateTags.isEmpty()) {
|
||||
|
||||
+2
-3
@@ -121,9 +121,8 @@ public class FlinkContainerManager {
|
||||
private String runtimeKey(FlinkApplication app) {
|
||||
String arn = app.getApplicationArn();
|
||||
if (arn == null || arn.isBlank()) {
|
||||
arn = "arn:aws:kinesisanalytics:" + regionResolver.getDefaultRegion() + ":"
|
||||
+ regionResolver.getAccountId() + ":application/"
|
||||
+ app.getApplicationName();
|
||||
arn = AwsArnUtils.Arn.of("kinesisanalytics", regionResolver.getDefaultRegion(),
|
||||
regionResolver.getAccountId(), "application/" + app.getApplicationName()).toString();
|
||||
}
|
||||
return arn.replace(':', '-').replace('/', '-');
|
||||
}
|
||||
|
||||
+3
-1
@@ -7,6 +7,7 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.AwsRegions;
|
||||
import io.github.hectorvent.floci.core.common.Resettable;
|
||||
import io.github.hectorvent.floci.services.kinesis.KinesisService;
|
||||
import io.github.hectorvent.floci.services.kinesis.model.KinesisRecord;
|
||||
@@ -214,7 +215,8 @@ public class KinesisEventSourcePoller implements Resettable {
|
||||
record.put("eventVersion", "1.0");
|
||||
record.put("eventID", shardId + ":" + rec.getSequenceNumber());
|
||||
record.put("eventName", "aws:kinesis:record");
|
||||
record.put("invokeIdentityArn", AwsArnUtils.Arn.of("iam", "", esm.getAccountId(), "role/lambda-role").toString());
|
||||
record.put("invokeIdentityArn", AwsArnUtils.Arn.global(AwsRegions.partitionFor(esm.getRegion()), "iam",
|
||||
esm.getAccountId(), "role/lambda-role").toString());
|
||||
record.put("awsRegion", esm.getRegion());
|
||||
record.put("eventSourceARN", esm.getEventSourceArn());
|
||||
recordsArray.add(record);
|
||||
|
||||
+12
-6
@@ -4,8 +4,8 @@ import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
@@ -150,18 +150,20 @@ public class OrganizationsService implements ScpProvider {
|
||||
private final AccountAwareStorageBackend<OrganizationPolicy> policies;
|
||||
private final AccountAwareStorageBackend<CreateAccountStatus> createAccountStatuses;
|
||||
private final AccountAwareStorageBackend<Handshake> handshakes;
|
||||
private final RegionResolver regionResolver;
|
||||
private final boolean scpEnforcementEnabled;
|
||||
private final String managementAccountEmail;
|
||||
|
||||
@Inject
|
||||
public OrganizationsService(StorageFactory storageFactory, ObjectMapper objectMapper,
|
||||
EmulatorConfig config) {
|
||||
EmulatorConfig config, RegionResolver regionResolver) {
|
||||
EmulatorConfig.OrganizationsServiceConfig organizationsConfig = config.services().organizations();
|
||||
this.scpEnforcementEnabled = organizationsConfig.scpEnforcementEnabled();
|
||||
this.managementAccountEmail = organizationsConfig.managementAccountEmail()
|
||||
.map(OrganizationsService::requireValidConfiguredEmail)
|
||||
.orElse(null);
|
||||
this.objectMapper = objectMapper;
|
||||
this.regionResolver = regionResolver;
|
||||
this.organizations = storageFactory.create("organizations", "organizations-organizations.json",
|
||||
new TypeReference<Map<String, Organization>>() {});
|
||||
this.accounts = storageFactory.create("organizations", "organizations-accounts.json",
|
||||
@@ -177,17 +179,19 @@ public class OrganizationsService implements ScpProvider {
|
||||
}
|
||||
|
||||
OrganizationsService(ObjectMapper objectMapper,
|
||||
RegionResolver regionResolver,
|
||||
AccountAwareStorageBackend<Organization> organizations,
|
||||
AccountAwareStorageBackend<OrganizationAccount> accounts,
|
||||
AccountAwareStorageBackend<OrganizationalUnit> organizationalUnits,
|
||||
AccountAwareStorageBackend<OrganizationPolicy> policies,
|
||||
AccountAwareStorageBackend<CreateAccountStatus> createAccountStatuses,
|
||||
AccountAwareStorageBackend<Handshake> handshakes) {
|
||||
this(objectMapper, organizations, accounts, organizationalUnits, policies,
|
||||
this(objectMapper, regionResolver, organizations, accounts, organizationalUnits, policies,
|
||||
createAccountStatuses, handshakes, true);
|
||||
}
|
||||
|
||||
OrganizationsService(ObjectMapper objectMapper,
|
||||
RegionResolver regionResolver,
|
||||
AccountAwareStorageBackend<Organization> organizations,
|
||||
AccountAwareStorageBackend<OrganizationAccount> accounts,
|
||||
AccountAwareStorageBackend<OrganizationalUnit> organizationalUnits,
|
||||
@@ -195,11 +199,12 @@ public class OrganizationsService implements ScpProvider {
|
||||
AccountAwareStorageBackend<CreateAccountStatus> createAccountStatuses,
|
||||
AccountAwareStorageBackend<Handshake> handshakes,
|
||||
boolean scpEnforcementEnabled) {
|
||||
this(objectMapper, organizations, accounts, organizationalUnits, policies,
|
||||
this(objectMapper, regionResolver, organizations, accounts, organizationalUnits, policies,
|
||||
createAccountStatuses, handshakes, scpEnforcementEnabled, null);
|
||||
}
|
||||
|
||||
OrganizationsService(ObjectMapper objectMapper,
|
||||
RegionResolver regionResolver,
|
||||
AccountAwareStorageBackend<Organization> organizations,
|
||||
AccountAwareStorageBackend<OrganizationAccount> accounts,
|
||||
AccountAwareStorageBackend<OrganizationalUnit> organizationalUnits,
|
||||
@@ -209,6 +214,7 @@ public class OrganizationsService implements ScpProvider {
|
||||
boolean scpEnforcementEnabled,
|
||||
String managementAccountEmail) {
|
||||
this.objectMapper = objectMapper;
|
||||
this.regionResolver = regionResolver;
|
||||
this.organizations = organizations;
|
||||
this.accounts = accounts;
|
||||
this.organizationalUnits = organizationalUnits;
|
||||
@@ -1849,9 +1855,9 @@ public class OrganizationsService implements ScpProvider {
|
||||
"policy/" + organization.getId() + "/" + type.toLowerCase(java.util.Locale.ROOT) + "/" + policyId);
|
||||
}
|
||||
|
||||
/** Organizations ARNs carry no region, so the region segment is deliberately empty. */
|
||||
/** Organizations ARNs carry no region; they take the request's partition. */
|
||||
private String arn(String accountId, String resource) {
|
||||
return AwsArnUtils.Arn.of("organizations", "", accountId, resource).toString();
|
||||
return regionResolver.buildGlobalArn("organizations", accountId, resource);
|
||||
}
|
||||
|
||||
private String randomId(int length) {
|
||||
|
||||
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.rds.proxy;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.auth.SigV4RequestValidator;
|
||||
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator;
|
||||
import io.github.hectorvent.floci.services.iam.IamService;
|
||||
@@ -118,8 +119,8 @@ public class RdsSigV4Validator {
|
||||
if (caller == null) {
|
||||
return true;
|
||||
}
|
||||
String resource = "arn:aws:rds-db:" + binding.region() + ":" + binding.accountId()
|
||||
+ ":dbuser:" + binding.resourceId() + "/" + dbUser;
|
||||
String resource = AwsArnUtils.Arn.of("rds-db", binding.region(), binding.accountId(),
|
||||
"dbuser:" + binding.resourceId() + "/" + dbUser).toString();
|
||||
IamPolicyEvaluator.SimulationDecision decision =
|
||||
POLICY_EVALUATOR.simulatePrincipalPolicy(caller, "rds-db:connect", resource, Map.of());
|
||||
if (decision != IamPolicyEvaluator.SimulationDecision.ALLOWED) {
|
||||
|
||||
@@ -4684,7 +4684,7 @@ public class S3Service implements Resettable, ResourceProvider {
|
||||
|
||||
ObjectNode bucketNode = objectMapper.createObjectNode();
|
||||
bucketNode.put("name", bucketName);
|
||||
bucketNode.put("arn", AwsArnUtils.Arn.of("s3", "", "", bucketName).toString());
|
||||
bucketNode.put("arn", AwsArnUtils.Arn.global(bucketPartition(bucketName), "s3", "", bucketName).toString());
|
||||
|
||||
ObjectNode objectNode = objectMapper.createObjectNode();
|
||||
objectNode.put("key", key);
|
||||
|
||||
@@ -8,6 +8,7 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.AwsRegions;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.common.Resettable;
|
||||
import io.github.hectorvent.floci.core.resource.ExplorerResource;
|
||||
@@ -1742,7 +1743,7 @@ public class SqsService implements Resettable, ResourceProvider {
|
||||
ObjectNode principal = statement.putObject("Principal");
|
||||
ArrayNode awsArns = principal.putArray("AWS");
|
||||
for (String accountId : awsAccountIds) {
|
||||
awsArns.add(AwsArnUtils.Arn.of("iam", "", accountId, "root").toString());
|
||||
awsArns.add(AwsArnUtils.Arn.global(AwsRegions.partitionFor(region), "iam", accountId, "root").toString());
|
||||
}
|
||||
ArrayNode actions = statement.putArray("Action");
|
||||
for (String action : actionNames) {
|
||||
|
||||
@@ -3,7 +3,7 @@ package io.github.hectorvent.floci.services.ssoportal;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.PaginatedResult;
|
||||
import io.github.hectorvent.floci.core.common.Pagination;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.common.ServicePrincipals;
|
||||
import io.github.hectorvent.floci.services.iam.IamService;
|
||||
import io.github.hectorvent.floci.services.organizations.OrganizationsService;
|
||||
@@ -34,16 +34,19 @@ public class SsoPortalService {
|
||||
private final SsoAdminService ssoAdminService;
|
||||
private final OrganizationsService organizationsService;
|
||||
private final IamService iamService;
|
||||
private final RegionResolver regionResolver;
|
||||
|
||||
@Inject
|
||||
public SsoPortalService(SsoOidcService oidcService,
|
||||
SsoAdminService ssoAdminService,
|
||||
OrganizationsService organizationsService,
|
||||
IamService iamService) {
|
||||
IamService iamService,
|
||||
RegionResolver regionResolver) {
|
||||
this.oidcService = oidcService;
|
||||
this.ssoAdminService = ssoAdminService;
|
||||
this.organizationsService = organizationsService;
|
||||
this.iamService = iamService;
|
||||
this.regionResolver = regionResolver;
|
||||
}
|
||||
|
||||
public PaginatedResult<PortalAccountInfo> listAccounts(
|
||||
@@ -105,9 +108,8 @@ public class SsoPortalService {
|
||||
String accessKeyId = "ASIA" + random(UPPER_ALPHANUMERIC, 16);
|
||||
String secretAccessKey = random(SECRET_CHARACTERS, 40);
|
||||
String sessionToken = random(SECRET_CHARACTERS, 200);
|
||||
String roleArn = AwsArnUtils.Arn.of("iam", "", accountId,
|
||||
"role/aws-reserved/" + ServicePrincipals.of("sso") + "/AWSReservedSSO_" + roleName + "_floci")
|
||||
.toString();
|
||||
String roleArn = regionResolver.buildGlobalArn("iam", accountId,
|
||||
"role/aws-reserved/" + ServicePrincipals.of("sso") + "/AWSReservedSSO_" + roleName + "_floci");
|
||||
iamService.registerSessionForAccount(accountId, accessKeyId, secretAccessKey, sessionToken,
|
||||
roleArn, expiration, null);
|
||||
return new PortalRoleCredentials(accessKeyId, expiration.toEpochMilli(), secretAccessKey, sessionToken);
|
||||
|
||||
@@ -6,6 +6,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.PersistentStorage;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
@@ -32,7 +33,17 @@ class CostAnomalyServiceTest {
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
service = new CostAnomalyService(AccountAwareStorageBackend.inMemory(ACCOUNT),
|
||||
AccountAwareStorageBackend.inMemory(ACCOUNT), mapper);
|
||||
AccountAwareStorageBackend.inMemory(ACCOUNT), mapper, new RegionResolver("us-east-1", ACCOUNT));
|
||||
}
|
||||
|
||||
@Test
|
||||
void monitorArnsTakeTheRequestsPartition() {
|
||||
CostAnomalyService china = new CostAnomalyService(AccountAwareStorageBackend.inMemory(ACCOUNT),
|
||||
AccountAwareStorageBackend.inMemory(ACCOUNT), mapper, new RegionResolver("cn-north-1", ACCOUNT));
|
||||
|
||||
String arn = china.createMonitor(customMonitor("china")).path("MonitorArn").asText();
|
||||
|
||||
assertTrue(arn.startsWith("arn:aws-cn:ce::" + ACCOUNT + ":anomalymonitor/"), arn);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -212,7 +223,8 @@ class CostAnomalyServiceTest {
|
||||
monitors.load();
|
||||
subscriptions.load();
|
||||
return new CostAnomalyService(new AccountAwareStorageBackend<>(monitors, null, ACCOUNT),
|
||||
new AccountAwareStorageBackend<>(subscriptions, null, ACCOUNT), mapper);
|
||||
new AccountAwareStorageBackend<>(subscriptions, null, ACCOUNT), mapper,
|
||||
new RegionResolver("us-east-1", ACCOUNT));
|
||||
}
|
||||
|
||||
private ObjectNode customMonitor(String name) {
|
||||
|
||||
+9
@@ -79,6 +79,15 @@ class CloudFormationTemplateUrlTest {
|
||||
assertThat(ref.key(), equalTo("key"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void pathStyleAgainstChina_readsBucketFromThePath() {
|
||||
S3TemplateRef ref = CloudFormationService.parseTemplateUrl(
|
||||
"https://s3.cn-north-1.amazonaws.com.cn/bucket/key", SUFFIX);
|
||||
|
||||
assertThat(ref.bucket(), equalTo("bucket"));
|
||||
assertThat(ref.key(), equalTo("key"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void virtualHostedAgainstAws_readsBucketFromTheHost() {
|
||||
S3TemplateRef ref = CloudFormationService.parseTemplateUrl(
|
||||
|
||||
+1
@@ -134,6 +134,7 @@ class S3CfnProvisionerTest {
|
||||
|
||||
assertEquals("my-bucket.s3.eu-isoe-west-1.cloud.adc-e.uk", r.getAttributes().get("RegionalDomainName"));
|
||||
assertFalse(r.getAttributes().containsKey("DualStackDomainName"));
|
||||
assertEquals("arn:aws-iso-e:s3:::my-bucket", r.getAttributes().get("Arn"));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+2
-1
@@ -15,6 +15,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@@ -61,7 +62,7 @@ class CloudFrontControllerTest {
|
||||
CloudFrontFunction second = function("beta");
|
||||
CloudFrontFunction third = function("gamma");
|
||||
CloudFrontFunction fourth = function("omega");
|
||||
when(service.getAccountId()).thenReturn("000000000000");
|
||||
when(service.arn(anyString())).thenAnswer(call -> "arn:aws:cloudfront::000000000000:" + call.getArgument(0));
|
||||
when(service.listFunctions(null, null, 3))
|
||||
.thenReturn(List.of(first, second, third));
|
||||
when(service.listFunctions(null, "beta", 3))
|
||||
|
||||
+15
-1
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.cloudfront;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.common.XmlParser;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
@@ -123,6 +124,10 @@ class CloudFrontServiceTest {
|
||||
+ "</GeoRestriction></Restrictions>";
|
||||
|
||||
private CloudFrontService serviceWithDomainSuffix(String domainSuffix) {
|
||||
return serviceWithDomainSuffix(domainSuffix, "us-east-1");
|
||||
}
|
||||
|
||||
private CloudFrontService serviceWithDomainSuffix(String domainSuffix, String region) {
|
||||
StorageFactory storageFactory = Mockito.mock(StorageFactory.class);
|
||||
when(storageFactory.create(Mockito.anyString(), Mockito.anyString(), Mockito.any()))
|
||||
.thenAnswer(invocation -> AccountAwareStorageBackend.inMemory("000000000000"));
|
||||
@@ -140,7 +145,7 @@ class CloudFrontServiceTest {
|
||||
when(servicesConfig.cloudfront()).thenReturn(cloudFrontConfig);
|
||||
when(cloudFrontConfig.domainSuffix()).thenReturn(domainSuffix);
|
||||
|
||||
return new CloudFrontService(storageFactory, config);
|
||||
return new CloudFrontService(storageFactory, config, new RegionResolver(region, ACCOUNT));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -227,6 +232,15 @@ class CloudFrontServiceTest {
|
||||
assertEquals("NoSuchFunctionExists", error.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void distributionArnTakesTheRequestsPartition() {
|
||||
CloudFrontService china = serviceWithDomainSuffix("cloudfront.net", "cn-north-1");
|
||||
|
||||
Distribution dist = china.createDistribution(new Distribution(), Map.of());
|
||||
|
||||
assertEquals("arn:aws-cn:cloudfront::" + ACCOUNT + ":distribution/" + dist.getId(), dist.getArn());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createDistributionUsesDefaultDomainSuffix() {
|
||||
CloudFrontService service = serviceWithDomainSuffix("cloudfront.net");
|
||||
|
||||
+23
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.organizations;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.services.organizations.model.CreateAccountStatus;
|
||||
import io.github.hectorvent.floci.services.organizations.model.Handshake;
|
||||
@@ -33,6 +34,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
class OrganizationsServiceTest {
|
||||
|
||||
private static final String MANAGEMENT_ACCOUNT = "100000000001";
|
||||
private static final RegionResolver REGION_RESOLVER = new RegionResolver("us-east-1", MANAGEMENT_ACCOUNT);
|
||||
private static final String OUTSIDER_ACCOUNT = "100000000009";
|
||||
|
||||
private OrganizationsService service;
|
||||
@@ -43,6 +45,7 @@ class OrganizationsServiceTest {
|
||||
handshakes = AccountAwareStorageBackend.inMemory(MANAGEMENT_ACCOUNT);
|
||||
service = new OrganizationsService(
|
||||
new ObjectMapper(),
|
||||
REGION_RESOLVER,
|
||||
AccountAwareStorageBackend.inMemory(MANAGEMENT_ACCOUNT),
|
||||
AccountAwareStorageBackend.inMemory(MANAGEMENT_ACCOUNT),
|
||||
AccountAwareStorageBackend.inMemory(MANAGEMENT_ACCOUNT),
|
||||
@@ -74,6 +77,23 @@ class OrganizationsServiceTest {
|
||||
assertTrue(status.getAccountId().matches("\\d{12}"), status.getAccountId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void organizationsArnsTakeTheRequestsPartition() {
|
||||
OrganizationsService china = new OrganizationsService(
|
||||
new ObjectMapper(),
|
||||
new RegionResolver("cn-north-1", MANAGEMENT_ACCOUNT),
|
||||
AccountAwareStorageBackend.inMemory(MANAGEMENT_ACCOUNT),
|
||||
AccountAwareStorageBackend.inMemory(MANAGEMENT_ACCOUNT),
|
||||
AccountAwareStorageBackend.inMemory(MANAGEMENT_ACCOUNT),
|
||||
AccountAwareStorageBackend.inMemory(MANAGEMENT_ACCOUNT),
|
||||
AccountAwareStorageBackend.inMemory(MANAGEMENT_ACCOUNT),
|
||||
AccountAwareStorageBackend.inMemory(MANAGEMENT_ACCOUNT));
|
||||
Organization organization = china.createOrganization(MANAGEMENT_ACCOUNT, "ALL");
|
||||
|
||||
assertEquals("arn:aws-cn:organizations::" + MANAGEMENT_ACCOUNT + ":organization/" + organization.getId(),
|
||||
organization.getArn());
|
||||
}
|
||||
|
||||
@Test
|
||||
void organizationsArnsCarryNoRegion() {
|
||||
Organization organization = service.createOrganization(MANAGEMENT_ACCOUNT, "ALL");
|
||||
@@ -348,6 +368,7 @@ class OrganizationsServiceTest {
|
||||
void effectiveScpLevelsAreNullWhenEnforcementDisabled() {
|
||||
OrganizationsService disabled = new OrganizationsService(
|
||||
new ObjectMapper(),
|
||||
REGION_RESOLVER,
|
||||
AccountAwareStorageBackend.inMemory(MANAGEMENT_ACCOUNT),
|
||||
AccountAwareStorageBackend.inMemory(MANAGEMENT_ACCOUNT),
|
||||
AccountAwareStorageBackend.inMemory(MANAGEMENT_ACCOUNT),
|
||||
@@ -372,6 +393,7 @@ class OrganizationsServiceTest {
|
||||
void managementAccountEmailOverrideIsUsedForOrganizationAndAccount() {
|
||||
OrganizationsService configured = new OrganizationsService(
|
||||
new ObjectMapper(),
|
||||
REGION_RESOLVER,
|
||||
AccountAwareStorageBackend.inMemory(MANAGEMENT_ACCOUNT),
|
||||
AccountAwareStorageBackend.inMemory(MANAGEMENT_ACCOUNT),
|
||||
AccountAwareStorageBackend.inMemory(MANAGEMENT_ACCOUNT),
|
||||
@@ -393,6 +415,7 @@ class OrganizationsServiceTest {
|
||||
void malformedManagementAccountEmailOverrideIsRejected() {
|
||||
assertThrows(IllegalArgumentException.class, () -> new OrganizationsService(
|
||||
new ObjectMapper(),
|
||||
REGION_RESOLVER,
|
||||
AccountAwareStorageBackend.inMemory(MANAGEMENT_ACCOUNT),
|
||||
AccountAwareStorageBackend.inMemory(MANAGEMENT_ACCOUNT),
|
||||
AccountAwareStorageBackend.inMemory(MANAGEMENT_ACCOUNT),
|
||||
|
||||
+16
@@ -78,6 +78,22 @@ class RdsSigV4ValidatorTest {
|
||||
assertTrue(validator.validate(token, "jane_doe", exampleBinding()));
|
||||
}
|
||||
|
||||
/** A China database's rds-db:connect resource is an arn:aws-cn: ARN, as a China IAM policy names it. */
|
||||
@Test
|
||||
void validateAcceptsAChinaConnectGrantForADatabaseInChina() throws Exception {
|
||||
IamService iamService = IamServiceTestHelper.iamServiceWithUserPolicy(
|
||||
"AKIDRDS", "secret-rds", "jane", connectPolicyFor(
|
||||
"arn:aws-cn:rds-db:cn-north-1:123456789012:dbuser:db-ABCDEFGHIJKL01234/jane_doe"));
|
||||
RdsSigV4Validator validator = new RdsSigV4Validator(iamService, () -> true);
|
||||
String token = SigV4TokenTestHelper.createRdsTokenWithScope(
|
||||
"db.example.local", 3307, "jane_doe", "AKIDRDS", "secret-rds", "cn-north-1", "rds-db",
|
||||
Instant.now().minusSeconds(60), 900);
|
||||
RdsProxyBinding chinaBinding = new RdsProxyBinding(
|
||||
"db.example.local", 3307, "cn-north-1", "123456789012", "db-ABCDEFGHIJKL01234", true);
|
||||
|
||||
assertTrue(validator.validate(token, "jane_doe", chinaBinding));
|
||||
}
|
||||
|
||||
@Test
|
||||
void validateRejectsCallerWhoseConnectGrantIsForAnotherDbUser() throws Exception {
|
||||
IamService iamService = IamServiceTestHelper.iamServiceWithUserPolicy(
|
||||
|
||||
+5
-2
@@ -1,5 +1,6 @@
|
||||
package io.github.hectorvent.floci.services.ssoportal;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.services.iam.IamService;
|
||||
import io.github.hectorvent.floci.services.organizations.OrganizationsService;
|
||||
import io.github.hectorvent.floci.services.ssoadmin.SsoAdminService;
|
||||
@@ -39,7 +40,8 @@ class SsoPortalServiceTest {
|
||||
ssoAdminService = mock(SsoAdminService.class);
|
||||
organizationsService = mock(OrganizationsService.class);
|
||||
iamService = mock(IamService.class);
|
||||
service = new SsoPortalService(oidcService, ssoAdminService, organizationsService, iamService);
|
||||
service = new SsoPortalService(oidcService, ssoAdminService, organizationsService, iamService,
|
||||
new RegionResolver("cn-north-1", "000000000000"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -69,7 +71,8 @@ class SsoPortalServiceTest {
|
||||
|
||||
ArgumentCaptor<String> roleArn = ArgumentCaptor.forClass(String.class);
|
||||
verify(iamService).registerSessionForAccount(eq(accountId), any(), any(), any(), roleArn.capture(), any(), eq(null));
|
||||
assertTrue(roleArn.getValue().contains(":iam::" + accountId + ":role/aws-reserved/sso.amazonaws.com/AWSReservedSSO_PlatformAdmins_floci"));
|
||||
assertEquals("arn:aws-cn:iam::" + accountId
|
||||
+ ":role/aws-reserved/sso.amazonaws.com/AWSReservedSSO_PlatformAdmins_floci", roleArn.getValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -1,5 +1,2 @@
|
||||
# category path count
|
||||
# Generated by tools/partition/partition_literals.py --write-baseline; do not hand-edit.
|
||||
arn-literal src/main/java/io/github/hectorvent/floci/services/kinesisanalytics/container/FlinkContainerManager.java 1
|
||||
arn-literal src/main/java/io/github/hectorvent/floci/services/rds/proxy/RdsSigV4Validator.java 1
|
||||
dns-suffix src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java 1
|
||||
|
@@ -58,6 +58,10 @@ class Category:
|
||||
regex: re.Pattern
|
||||
gated: bool
|
||||
description: str
|
||||
# "literal" runs the regex over each string literal's content; "code" over the whole source
|
||||
# with comments and text blocks blanked, for a partition bug that is a call shape rather than a
|
||||
# literal, even one split across lines.
|
||||
scope: str = "literal"
|
||||
|
||||
|
||||
# Regexes run against the content of one string literal (one line of a text block), never
|
||||
@@ -95,6 +99,14 @@ CATEGORIES: tuple[Category, ...] = (
|
||||
True,
|
||||
"a region or availability-zone id; take it from the request or the resource, or the configured default",
|
||||
),
|
||||
Category(
|
||||
"blank-region-arn",
|
||||
re.compile(r'Arn\.of\(\s*"[^"]*"\s*,\s*(?:""|null)\s*,'),
|
||||
True,
|
||||
"an ARN minted by Arn.of with a blank region, which silently means the commercial partition; "
|
||||
"use Arn.global with the resource's or the request's partition",
|
||||
"code",
|
||||
),
|
||||
)
|
||||
|
||||
CATEGORY_BY_NAME = {category.name: category for category in CATEGORIES}
|
||||
@@ -181,6 +193,44 @@ def scan_java(text: str) -> tuple[list[Literal], dict[int, str]]:
|
||||
return literals, escapes
|
||||
|
||||
|
||||
def code_text(text: str) -> str:
|
||||
"""The source with every comment and text block blanked, string literals kept as written.
|
||||
|
||||
Newlines survive, so an offset maps back to its line. Uses the same lexing rules as
|
||||
scan_java: a `//` inside a string is not a comment, a call shape inside a comment, javadoc or
|
||||
text block never counts, and a call split across lines is still one match.
|
||||
"""
|
||||
out: list[str] = []
|
||||
i = 0
|
||||
n = len(text)
|
||||
while i < n:
|
||||
if text.startswith("//", i):
|
||||
end = text.find("\n", i)
|
||||
end = n if end < 0 else end
|
||||
out.append(" " * (end - i))
|
||||
i = end
|
||||
elif text.startswith("/*", i) or text.startswith('"""', i):
|
||||
closer = "*/" if text[i + 1] == "*" else '"""'
|
||||
j = i + len(closer)
|
||||
while j < n and not text.startswith(closer, j):
|
||||
j += 2 if closer == '"""' and text[j] == "\\" else 1
|
||||
end = min(j + len(closer), n)
|
||||
out.append("".join(c if c == "\n" else " " for c in text[i:end]))
|
||||
i = end
|
||||
elif text[i] in "\"'":
|
||||
quote = text[i]
|
||||
j = i + 1
|
||||
while j < n and text[j] not in quote + "\n":
|
||||
j += 2 if text[j] == "\\" else 1
|
||||
end = j + 1 if j < n and text[j] == quote else j
|
||||
out.append(text[i:end])
|
||||
i = end
|
||||
else:
|
||||
out.append(text[i])
|
||||
i += 1
|
||||
return "".join(out)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AllowRule:
|
||||
kind: str
|
||||
@@ -220,19 +270,22 @@ def collect_findings(source_root: Path, rules: list[AllowRule]) -> list[Finding]
|
||||
text = java.read_text(encoding="utf-8")
|
||||
lines = text.split("\n")
|
||||
literals, escapes = scan_java(text)
|
||||
hits: list[tuple[str, int]] = []
|
||||
for literal in literals:
|
||||
source_line = lines[literal.line - 1] if literal.line - 1 < len(lines) else ""
|
||||
for category in CATEGORIES:
|
||||
hits = len(category.regex.findall(literal.text))
|
||||
if hits == 0:
|
||||
continue
|
||||
excuse = excuse_for(rel_path, source_line, rules)
|
||||
if excuse is None and literal.line in escapes:
|
||||
excuse = f"escape: {escapes[literal.line]}"
|
||||
findings.extend(
|
||||
Finding(category.name, rel_path, literal.line, source_line.strip(), excuse)
|
||||
for _ in range(hits)
|
||||
)
|
||||
if category.scope == "literal":
|
||||
hits += [(category.name, literal.line)] * len(category.regex.findall(literal.text))
|
||||
code = code_text(text)
|
||||
for category in CATEGORIES:
|
||||
if category.scope == "code":
|
||||
hits += [(category.name, code.count("\n", 0, match.start()) + 1)
|
||||
for match in category.regex.finditer(code)]
|
||||
for name, line_number in hits:
|
||||
source_line = lines[line_number - 1] if line_number - 1 < len(lines) else ""
|
||||
excuse = excuse_for(rel_path, source_line, rules)
|
||||
if excuse is None and line_number in escapes:
|
||||
excuse = f"escape: {escapes[line_number]}"
|
||||
findings.append(Finding(name, rel_path, line_number, source_line.strip(), excuse))
|
||||
return findings
|
||||
|
||||
|
||||
|
||||
@@ -146,6 +146,58 @@ def test_region_literal_matches_region_and_zone_ids(text, expected):
|
||||
assert ("region-literal" in categories_of(text)) is expected
|
||||
|
||||
|
||||
def test_code_text_blanks_comments_and_text_blocks_and_keeps_strings():
|
||||
text = (
|
||||
'a = Arn.of("iam", "", x, "r"); // Arn.of("s3", "", y\n'
|
||||
'/* Arn.of("x", "", z */ s = "// not a comment";\n'
|
||||
'String doc = """\n Arn.of("iam", "", account, "root")\n """;\n'
|
||||
)
|
||||
code = p.code_text(text)
|
||||
lines = code.split("\n")
|
||||
assert len(lines) == len(text.split("\n"))
|
||||
assert lines[0].startswith('a = Arn.of("iam", "", x, "r");')
|
||||
assert "s3" not in lines[0]
|
||||
assert "Arn.of" not in lines[1]
|
||||
assert '"// not a comment"' in lines[1]
|
||||
assert "Arn.of" not in "\n".join(lines[2:])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("code, expected", [
|
||||
('Arn.of("iam", "", account, "root")', True),
|
||||
('AwsArnUtils.Arn.of( "s3" , null, "", bucket)', True),
|
||||
('Arn.of("sqs", region, account, name)', False),
|
||||
('Arn.global(partition, "iam", account, "root")', False),
|
||||
('Arn.of("lambda", "us-east-1", account, name)', False),
|
||||
])
|
||||
def test_blank_region_arn_matches_a_blank_or_null_region_only(code, expected):
|
||||
category = p.CATEGORY_BY_NAME["blank-region-arn"]
|
||||
assert (category.regex.search(code) is not None) is expected
|
||||
|
||||
|
||||
def test_blank_region_arn_matches_a_call_split_across_lines(tmp_path):
|
||||
write_java(tmp_path, "a/A.java", (
|
||||
'class A {\n'
|
||||
' String arn = AwsArnUtils.Arn.of(\n'
|
||||
' "iam", "", account, "root").toString();\n'
|
||||
'}\n'
|
||||
))
|
||||
findings = p.collect_findings(tmp_path, [])
|
||||
assert p.count(findings) == Counter({("blank-region-arn", "a/A.java"): 1})
|
||||
assert [f.line for f in findings] == [2]
|
||||
|
||||
|
||||
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'
|
||||
' String arn = AwsArnUtils.Arn.of("iam", "", account, "root").toString();\n'
|
||||
' // AwsArnUtils.Arn.of("iam", "", account, "root")\n'
|
||||
' String doc = "Arn.of(\\"iam\\", \\"\\", a, b)";\n'
|
||||
'}\n'
|
||||
))
|
||||
counted = p.count(p.collect_findings(tmp_path, []))
|
||||
assert counted == Counter({("blank-region-arn", "a/A.java"): 1})
|
||||
|
||||
|
||||
def test_every_category_is_gated():
|
||||
assert {c.name for c in p.CATEGORIES if c.gated} == {c.name for c in p.CATEGORIES}
|
||||
|
||||
|
||||
Reference in new issue
Block a user