Files
floci/docs/configuration/multi-account.md
T
Sam Fakhreddine c96dc98065 feat(s3): opt-in global bucket namespace and replication config (#2640)
* feat(s3): bucket replication configuration round-trip

PUT/GET/DELETE ?replication store the replication configuration verbatim
(validated for a Role and at least one Rule with a Destination/Bucket)
instead of falling through to CreateBucket. Storage-only fidelity — floci
performs no actual replication. Split from a cross-service commit; the IAM
password-policy and CloudFormation SSM-parameter changes ship separately.

* fix(s3): resolve buckets cross-account under a global bucket namespace

S3 bucket names are globally unique in AWS: a bucket lives in one account but is
legitimately reachable cross-account. floci's per-account isolation broke LZA,
which has member accounts read/write a management-owned shared assets bucket and
runs cross-account custom resources (e.g. Custom::S3PutBucketReplication) whose
Lambda calls back under a different account context than the bucket's owner.

Add an opt-in globalBucketNamespace mode (default off, preserving isolation):
bucket/object existence RESOLUTION spans every account's partition while LISTING
stays owner-scoped. Reads route through resolveBucket/resolveObject; bucket-config
MUTATIONS route through a new owner-aware mutateBucket helper that resolves the
owning account via AccountAwareStorageBackend.findAnyAccountEntry and writes back
to the owner's partition (putForAccount) rather than forking a phantom bucket into
the caller's partition. Applied to put/deleteBucketReplication — the path LZA's
Logging stage exercises cross-account.

* test(s3): guard getObject against torn reads under concurrent overwrite

LZA's Bootstrap stage fans out ~15 CodeBuild actions that redundantly re-upload
the same artifact keys (Source.zip/Config.zip) while other builds concurrently
download them. A non-atomic truncate-then-write would let a reader observe an
empty/partial object — which surfaced as an empty src-Config secondary source and
ENOENT: global-config.yaml. Add a stress test (4 writers / 4 readers) asserting
getObject never returns a torn view of a constant-size key.

* docs(s3): document the global bucket namespace flag

Describe FLOCI_SERVICES_S3_GLOBAL_BUCKET_NAMESPACE in s3.md, the
multi-account isolation exception, and the environment-variable reference.

* feat(s3): account-level Block Public Access (s3control PublicAccessBlock)

Add account-scoped PUT/GET/DELETE PublicAccessBlock to the s3control
controller, keyed by the x-amz-account-id header and stored separately
from the bucket-level configuration. LZA's Custom::PutPublicAccessBlock
custom resource calls this account-level op while building the
LoggingStack; without a route the resource reported FAILED and the
stack rolled back (NoStack on CDK readback).

(cherry picked from commit a1cdf186ac7909647350ced455c4e0ba5d2d26a0)

* fix(s3): persist account-level Block Public Access

The account-level (s3control) PublicAccessBlock configuration was held in a
plain ConcurrentHashMap, bypassing StorageFactory while every other piece of
S3 state goes through it. Block Public Access is a security control, and LZA's
Custom::PutPublicAccessBlock runs once per governed account during the
LoggingStack deploy — it does not re-run on a resumed pipeline. A restart
therefore dropped the control silently and every governed account started
reporting NoSuchPublicAccessBlockConfiguration.

Move it to a StorageFactory-backed store (s3-account-public-access-block.json)
addressed through the explicit *ForAccount overloads, so the account comes from
the validated x-amz-account-id header and globalBucketNamespace never widens it.
The s3 descriptor already declares storageKey/storageMode, so no catalog change
is needed and PersistentPathValidator now covers this state.

clear() no longer wipes the config: like the bucket and object stores, its
lifecycle belongs to StorageFactory.clearAll().

* fix(s3): check x-amz-account-id against the caller on Block Public Access

The account-level PublicAccessBlock operations took the account solely from the
x-amz-account-id header, which was only checked for being non-blank. Any caller
could read, overwrite or delete any account's Block Public Access configuration
by setting one header — and Block Public Access is a security control.

AWS s3control answers AccessDenied when the header does not name the caller's
own account: there a cross-account call carries credentials assumed into the
target account, so header and caller always agree. Compare the header against
the caller's resolved account and return the same AWS-shaped AccessDenied (403)
on a mismatch, resolving the caller exactly as AccountAwareStorageBackend does
so the check and the storage partition can never disagree.

One exception is kept deliberately: the configured default (management) account
may act on any account, because Floci's launched Lambdas run on placeholder
credentials that resolve to the management account instead of assuming a role in
the target account. Without it LZA's Custom::PutPublicAccessBlock — the reason
these operations exist — would be denied for every governed account. This is the
same allowance S3Service.mutateBucket already makes for
Custom::S3PutBucketReplication.

Enforcement is scoped to the three PublicAccessBlock routes; the tag routes on
this controller accept and ignore the header as before.

* docs(s3): state the global bucket namespace trade-off explicitly

No behaviour change. The flag widens bucket resolution across accounts, which
reads as an account-isolation violation to a reviewer working from a checklist.
Say the intent in place, on the config option and in the S3 guide: S3 bucket
names are globally unique in AWS, a bucket lives in one owning account, and
cross-account access is a policy decision — so a hard per-account partition
models a state AWS cannot reach and fails legitimate cross-account calls with
NoSuchBucket. Record what it costs too: with the flag on, only IAM and bucket
policy stand between a caller and another account's object. Mutations still
write back to the owning account and listing stays owner-scoped, and the flag
is off by default.

* fix(s3): keep the account-aware bucket replication over the upstream #2519 duplicate

Upstream landed its own Put/Get/DeleteBucketReplication (ce4f6d1c4), which
duplicated the branch implementation. The branch copy stays because it goes
through mutateBucket (the caller-scoped mutation the LZA
Custom::S3PutBucketReplication path requires) and validates Role, Rule and
Destination/Bucket; upstream's root-element MalformedXML check is folded
into it so nothing upstream tested is lost. Duplicate Bucket field and
accessors removed.

* fix(s3): enforce the modeled AccountId pattern and ReplicationRule status enum

Account-level Block Public Access took x-amz-account-id as its storage
partition key after only a blank check, so a value outside the s3control
AccountId shape (^\d{12}$) filed a security configuration under a partition
no account could address again.

PutBucketReplication stored the document after checking only that a Role, a
Rule and a Destination/Bucket were present, so a rule with a missing or
out-of-enum Status round-tripped through GetBucketReplication as a document
AWS would have rejected. Both now answer the error the operation already
uses for its other input guards.

* fix(s3): resolve GetBucketReplication cross-account under the global bucket namespace

putBucketReplication and every other bucket-config mutation resolve cross-account
through mutateBucket/resolveBucket when globalBucketNamespace is enabled, but
getBucketReplication still called bucketStore.get(bucketName) directly. A
management-account caller could write a bucket's replication configuration
cross-account (mirroring LZA's Custom::S3PutBucketReplication path) but a
follow-up GetBucketReplication under the same caller saw NoSuchBucket instead of
the configuration it just stored.

RED test: getBucketReplicationResolvesCrossAccount in
S3GlobalBucketNamespaceTest failed with NoSuchBucket before this change.

* fix(s3): validate each replication rule's own destination bucket

PutBucketReplication checked that at least one Bucket appeared anywhere in the
document, then validated only Status per rule. A multi-rule document where only
one rule carried a Destination/Bucket satisfied that document-wide check and
round-tripped through GetBucketReplication as a configuration AWS would have
rejected as MalformedXML.

Destination elements appear in the same document order as their owning Rule
(extractGroupsMulti can't see nested Destination/Bucket as a Rule leaf), so
pairing the Destination list position-for-position with the Rule list and
requiring an equal count plus a non-blank Bucket in each enforces that every
rule carries its own destination.

RED test: putReplicationRejectsARuleWithoutItsOwnDestinationBucket in
S3ReplicationConfigurationIntegrationTest got 200 instead of 400 before this
change.

* fix(s3): remove unreachable duplicate ?replication dispatch

The PUT and GET handlers each had two identical `if (hasQueryParam(uriInfo,
"replication"))` branches — a rebase artifact. The earlier branch in each
method always returns first, so the second was dead code that risked a future
routing change updating only one copy.

* docs(s3): expose global-bucket-namespace in the canonical application.yml

globalBucketNamespace() was documented in EmulatorConfig and in
docs/services/s3.md but absent from the s3 block in both application.yml
files, leaving the runtime configuration surface out of sync with what the
code and docs describe.

* test(s3): assert torn-read stress threads actually finish

The writer/reader threads were joined with a 30s timeout but never checked for
liveness afterward. A thread still running past the timeout could leak past
the test (hanging the suite) or let the assertions pass vacuously without that
thread's reads or writes having completed.

* fix(s3): reject malformed PutPublicAccessBlock bodies

s3control's PutPublicAccessBlockRequest requires PublicAccessBlockConfiguration,
but the controller normalized any body — null, empty, unparseable, or a
different root element entirely — into a valid configuration with every flag
defaulted to false via canonicalPublicAccessBlockXml. For an account-level
Block Public Access control, that silently disabled every protection on a bad
request instead of failing it.

Reject a body whose root element is not PublicAccessBlockConfiguration with
the same MalformedXML the bucket-level replication path already uses for this
class of error, before normalization runs.

RED test: putRejectsAMalformedOrWrongRootBody in
S3ControlAccountIdEnforcementTest got 200 instead of 400 before this change.

* fix(s3): validate replication destinations against their own rule, not the document total

Counting Rule and Destination elements document-wide and requiring the totals to match let a
rule with two Destinations balance a rule with none, satisfying the check while storing a
configuration AWS would reject as MalformedXML. Destination is Required: Yes directly on Rule, so
PutBucketReplication now walks the parsed element tree and requires each Rule to have exactly one
Destination of its own with a non-blank Bucket, instead of comparing counts across the whole
document.

* fix(s3): reject a replication destination with multiple Bucket elements

Destination.Bucket is a required scalar member (botocore
s3/2006-03-01/service-2.json: "Bucket":{"shape":"BucketName"}), not a list.
child("Bucket") returns only the first match, so a Destination with two Bucket
children silently accepted the first and stored a document AWS would reject
as MalformedXML.

Count the Bucket children explicitly and require exactly one, instead of
taking child("Bucket")'s single match unconditionally.

RED test: putReplicationRejectsADestinationWithMultipleBucketElements in
S3ReplicationConfigurationIntegrationTest got 200 instead of 400 before this
change.

* fix(s3): wire bucket-policy operations through cross-account resolution

getBucketPolicy/putBucketPolicy/deleteBucketPolicy still resolved via
bucketStore directly, unlike object read/write and replication, so a
management-account caller got NoSuchBucket on a member-owned bucket's
policy even with the global bucket namespace enabled. Route them
through resolveBucket/mutateBucket like the rest of the cross-account
paths, and document the IAM-enforcement dependency and the same-name
non-determinism case in the trade-off writeup.

* docs(s3): name the flag that actually gates bucket-policy evaluation

The trade-off write-up said global-bucket-namespace's IAM/bucket-policy
protection depends on FLOCI_SERVICES_IAM_ENFORCEMENT_ENABLED, but that flag
only gates identity-policy checks in IamEnforcementFilter before a request
reaches S3 — bucket-policy evaluation itself (S3Service.authorizeS3Read/
authorizeS3Write, which reads the stored bucket policy) is gated separately
by FLOCI_SERVICES_S3_ENFORCE_AUTH, which also defaults false. Name both
flags and make explicit that the S3-specific one is what actually turns
bucket-policy evaluation on or off.
2026-08-28 11:24:47 -04:00

8.8 KiB

Multi-Account Isolation

Floci supports full per-account resource isolation out of the box. Resources created by one account are invisible to all others — no configuration flag required.

How It Works

Every incoming request carries an AWS SigV4 Authorization header. Floci reads the Access Key ID (AKID) from that header and resolves the account in this order:

  1. An exactly 12-digit AKID is used directly as the account ID.
  2. An active long-term IAM access key resolves to the account that owns it.
  3. A live STS temporary credential resolves to its recorded account.
  4. Any other key falls back to FLOCI_DEFAULT_ACCOUNT_ID.
Authorization: AWS4-HMAC-SHA256 Credential=111111111111/20260510/us-east-1/sqs/aws4_request, ...
                                            ^^^^^^^^^^^^
                                            12-digit AKID → account ID 111111111111

Once the account ID is determined, every storage read and write is transparently namespaced under it. An SQS queue named orders created by account 111111111111 is stored and retrieved as 111111111111/orders — completely separate from the same queue name under account 222222222222.

!!! note "Same convention as LocalStack" This 12-digit AKID → account ID rule matches LocalStack's multi-account behavior, so existing multi-account test setups work without changes.

Long-Term IAM Credentials

Active access keys created through IAM route requests back to the account that owns the key. This lets a client keep using its generated AKIA… credentials instead of replacing the access key ID with a synthetic 12-digit account ID.

Account selection is AKID-based and is not proof that the caller possesses the corresponding secret. This extends Floci's existing local-emulator trust model for 12-digit AKIDs; do not treat account namespaces as a security boundary between mutually untrusted clients.

Temporary Credentials (AssumeRole)

STS temporary credentials are also routed to the correct account. When you call AssumeRole (or AssumeRoleWithWebIdentity, AssumeRoleWithSAML, GetFederationToken), Floci issues a temporary ASIA… access key and remembers which account it belongs to:

  • AssumeRole / web-identity / SAML / federation → the account in the role (or federated-user) ARN. Assuming arn:aws:iam::222222222222:role/Deployer from account 111111111111 yields credentials that resolve to 222222222222, so resources created with them land in account B's namespace.
  • GetSessionToken → the caller's account (these credentials carry no role), so they stay in the same account.
Account 111111111111 ──AssumeRole arn:aws:iam::222222222222:role/Deployer──▶ ASIA… temp key
                                                                              │
ASIA… temp key ──CreateTable orders──▶ stored as 222222222222/...::orders  ◀──┘

This makes the cross-account AssumeRole-then-provision pattern (e.g. CloudFormation deploying into a target account) work locally exactly as it does in AWS.

Default Behavior (Single Account)

If a credential is not a 12-digit account ID, an active IAM access key, or a live STS session (for example, test), requests resolve to the default account ID:

FLOCI_DEFAULT_ACCOUNT_ID=000000000000   # default

All ARNs and URLs use this value:

arn:aws:sqs:us-east-1:000000000000:my-queue
http://localhost:4566/000000000000/my-queue

You can change the default account ID without enabling per-request isolation:

FLOCI_DEFAULT_ACCOUNT_ID=123456789012

Enabling Multi-Account Isolation

Use 12-digit numeric access key IDs. The secret access key can be any non-empty string — Floci does not validate signatures by default.

AWS CLI

# Configure two named profiles
aws configure --profile account-a
# AWS Access Key ID: 111111111111
# AWS Secret Access Key: test

aws configure --profile account-b
# AWS Access Key ID: 222222222222
# AWS Secret Access Key: test

export AWS_ENDPOINT_URL=http://localhost:4566

# Create the same queue name under both accounts
aws sqs create-queue --queue-name orders --profile account-a
aws sqs create-queue --queue-name orders --profile account-b

# Each account sees only its own queue
aws sqs list-queues --profile account-a   # → .../111111111111/orders
aws sqs list-queues --profile account-b   # → .../222222222222/orders

AWS SDK (Java)

StaticCredentialsProvider accountA = StaticCredentialsProvider.create(
    AwsBasicCredentials.create("111111111111", "test"));

StaticCredentialsProvider accountB = StaticCredentialsProvider.create(
    AwsBasicCredentials.create("222222222222", "test"));

SqsClient clientA = SqsClient.builder()
    .endpointOverride(URI.create("http://localhost:4566"))
    .region(Region.US_EAST_1)
    .credentialsProvider(accountA)
    .build();

SqsClient clientB = SqsClient.builder()
    .endpointOverride(URI.create("http://localhost:4566"))
    .region(Region.US_EAST_1)
    .credentialsProvider(accountB)
    .build();

// Both calls succeed, resources are fully isolated
clientA.createQueue(r -> r.queueName("orders"));
clientB.createQueue(r -> r.queueName("orders"));

AWS SDK (Python)

import boto3

def client(service, account_id):
    return boto3.client(
        service,
        endpoint_url="http://localhost:4566",
        region_name="us-east-1",
        aws_access_key_id=account_id,      # 12-digit → account ID
        aws_secret_access_key="test",
    )

sqs_a = client("sqs", "111111111111")
sqs_b = client("sqs", "222222222222")

sqs_a.create_queue(QueueName="orders")
sqs_b.create_queue(QueueName="orders")

print(sqs_a.list_queues()["QueueUrls"])  # [".../111111111111/orders"]
print(sqs_b.list_queues()["QueueUrls"])  # [".../222222222222/orders"]

ARNs Include the Correct Account ID

Floci embeds the resolved account ID in every ARN it generates:

arn:aws:sqs:us-east-1:111111111111:orders
arn:aws:lambda:us-east-1:222222222222:function:my-fn
arn:aws:s3:::my-bucket                         # S3 ARNs are account-agnostic

Isolation Scope

All services that use StorageFactory participate in account isolation automatically. This covers every service in Floci — SQS, SNS, S3, DynamoDB, Lambda, SSM, Secrets Manager, KMS, Kinesis, EventBridge, Cognito, RDS, ElastiCache, OpenSearch, MSK, and more.

AWS Organizations sits on top of this model: the organization's state lives in the management account's namespace, member accounts created with CreateAccount are immediately usable as 12-digit access key IDs, and — with IAM enforcement plus FLOCI_SERVICES_ORGANIZATIONS_SCP_ENFORCEMENT_ENABLED — service control policies attached in the organization constrain what member-account identities may do.

Background workers (Lambda event-source pollers, DynamoDB TTL sweeper, MSK readiness poller, OpenSearch readiness poller) iterate across all accounts internally and route writes back to the originating account. No cross-account data leaks through these async paths.

S3 exception — global bucket namespace. S3 buckets are isolated per account by default like every other service, but real S3 bucket names are globally unique. Set FLOCI_SERVICES_S3_GLOBAL_BUCKET_NAMESPACE=true to make bucket/object resolution span every account's partition, so a bucket created in one account is visible cross-account — needed when a workload writes a bucket in one account and reads it from another (see S3).

Signature Validation

Floci does not currently perform general SigV4 validation for Authorization headers. Only the access key ID matters for account resolution, so the secret access key can be any non-empty string.

FLOCI_AUTH_VALIDATE_SIGNATURES currently applies only to S3 presigned URL validation. It does not authenticate general service requests or protect IAM and STS account routing. To validate S3 presigned URLs:

FLOCI_AUTH_VALIDATE_SIGNATURES=true
FLOCI_AUTH_PRESIGN_SECRET=your-secret   # for pre-signed URL verification

When validate-signatures is false (the default), S3 presigned URL signatures are not verified. Account routing remains AKID-based regardless of this setting.

Persistence and Account Isolation

Storage keys are namespaced per account at the persistence layer. When using persistent, hybrid, or wal storage modes, each account's data is stored under its own key prefix. Restarting Floci restores each account's resources independently.

Configuration Reference

Variable Default Description
FLOCI_DEFAULT_ACCOUNT_ID 000000000000 Account ID used when the AKID does not resolve directly or through a stored credential
FLOCI_DEFAULT_REGION us-east-1 Region used when not derivable from the Authorization header
FLOCI_AUTH_VALIDATE_SIGNATURES false Verify S3 presigned URL signatures