mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
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.
This commit is contained in:
1 parent
f1ad306599
commit
c96dc98065
17 files changed
+1515
-77
No files matched your search
+71
@@ -0,0 +1,71 @@
|
||||
package io.github.hectorvent.floci.services.s3;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
|
||||
import io.github.hectorvent.floci.core.storage.PersistentStorage;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
/**
|
||||
* Account-level Block Public Access is a security control that AWS LZA sets once per governed
|
||||
* account during the LoggingStack deploy; a resumed pipeline does not re-run
|
||||
* {@code Custom::PutPublicAccessBlock}. It must therefore survive a restart rather than living
|
||||
* only in process memory.
|
||||
*/
|
||||
class S3AccountPublicAccessBlockPersistenceTest {
|
||||
|
||||
private static final String DEFAULT_ACCOUNT = "000000000000";
|
||||
private static final String GOVERNED_ACCOUNT = "452743914166";
|
||||
|
||||
private static final String CONFIG_XML =
|
||||
"<PublicAccessBlockConfiguration><BlockPublicAcls>true</BlockPublicAcls>"
|
||||
+ "<RestrictPublicBuckets>true</RestrictPublicBuckets>"
|
||||
+ "</PublicAccessBlockConfiguration>";
|
||||
|
||||
@Test
|
||||
void accountConfigurationSurvivesRestart(@TempDir Path dir) {
|
||||
S3Service first = newService(dir);
|
||||
first.putAccountPublicAccessBlock(GOVERNED_ACCOUNT, CONFIG_XML);
|
||||
first.putAccountPublicAccessBlock(DEFAULT_ACCOUNT, "<PublicAccessBlockConfiguration/>");
|
||||
|
||||
S3Service restarted = newService(dir);
|
||||
|
||||
assertEquals(CONFIG_XML, restarted.getAccountPublicAccessBlock(GOVERNED_ACCOUNT));
|
||||
assertEquals("<PublicAccessBlockConfiguration/>",
|
||||
restarted.getAccountPublicAccessBlock(DEFAULT_ACCOUNT));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletedAccountConfigurationStaysDeletedAcrossRestart(@TempDir Path dir) {
|
||||
S3Service first = newService(dir);
|
||||
first.putAccountPublicAccessBlock(GOVERNED_ACCOUNT, CONFIG_XML);
|
||||
first.deleteAccountPublicAccessBlock(GOVERNED_ACCOUNT);
|
||||
|
||||
S3Service restarted = newService(dir);
|
||||
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> restarted.getAccountPublicAccessBlock(GOVERNED_ACCOUNT));
|
||||
assertEquals("NoSuchPublicAccessBlockConfiguration", ex.getErrorCode());
|
||||
}
|
||||
|
||||
private S3Service newService(Path dir) {
|
||||
PersistentStorage<String, String> backend = new PersistentStorage<>(
|
||||
dir.resolve("s3-account-public-access-block.json"),
|
||||
new TypeReference<Map<String, String>>() {});
|
||||
backend.load();
|
||||
return new S3Service(
|
||||
new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(),
|
||||
new AccountAwareStorageBackend<>(backend, null, DEFAULT_ACCOUNT),
|
||||
dir.resolve("s3"),
|
||||
false);
|
||||
}
|
||||
}
|
||||
+112
@@ -0,0 +1,112 @@
|
||||
package io.github.hectorvent.floci.services.s3;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import java.nio.file.Path;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
/**
|
||||
* Account-level (S3 Control) Block Public Access.
|
||||
*
|
||||
* <p>AWS LZA's {@code Custom::PutPublicAccessBlock} custom resource sets account-wide
|
||||
* S3 Block Public Access via the s3control API ({@code PutPublicAccessBlock} keyed by
|
||||
* {@code AccountId}, distinct from the bucket-level operation). This is what the
|
||||
* LoggingStack deploy exercises for every governed account.
|
||||
*/
|
||||
class S3AccountPublicAccessBlockTest {
|
||||
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
|
||||
private S3Service s3Service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
Path dataRoot = tempDir.resolve("s3");
|
||||
s3Service = new S3Service(new InMemoryStorage<>(), new InMemoryStorage<>(), dataRoot, false);
|
||||
}
|
||||
|
||||
@Test
|
||||
void putThenGetAccountPublicAccessBlockRoundTrips() {
|
||||
String xml = "<PublicAccessBlockConfiguration><BlockPublicAcls>true</BlockPublicAcls>"
|
||||
+ "</PublicAccessBlockConfiguration>";
|
||||
s3Service.putAccountPublicAccessBlock("452743914166", xml);
|
||||
assertEquals(xml, s3Service.getAccountPublicAccessBlock("452743914166"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void accountConfigsAreIsolatedPerAccount() {
|
||||
s3Service.putAccountPublicAccessBlock("452743914166", "<a/>");
|
||||
s3Service.putAccountPublicAccessBlock("000000000000", "<b/>");
|
||||
assertEquals("<a/>", s3Service.getAccountPublicAccessBlock("452743914166"));
|
||||
assertEquals("<b/>", s3Service.getAccountPublicAccessBlock("000000000000"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAccountPublicAccessBlockThrowsNoSuchWhenUnset() {
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> s3Service.getAccountPublicAccessBlock("000000000000"));
|
||||
assertEquals("NoSuchPublicAccessBlockConfiguration", ex.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteAccountPublicAccessBlockRemovesConfig() {
|
||||
s3Service.putAccountPublicAccessBlock("000000000000", "<x/>");
|
||||
s3Service.deleteAccountPublicAccessBlock("000000000000");
|
||||
assertThrows(AwsException.class,
|
||||
() -> s3Service.getAccountPublicAccessBlock("000000000000"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteAccountPublicAccessBlockIsIdempotent() {
|
||||
// Deleting an absent config must not throw (mirrors AWS 204 on repeat delete).
|
||||
s3Service.deleteAccountPublicAccessBlock("000000000000");
|
||||
}
|
||||
|
||||
@Test
|
||||
void accountPublicAccessBlockRequiresAccountId() {
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> s3Service.putAccountPublicAccessBlock(" ", "<x/>"));
|
||||
assertEquals("InvalidRequest", ex.getErrorCode());
|
||||
}
|
||||
|
||||
/**
|
||||
* The s3control {@code AccountId} shape is {@code pattern ^\d{12}$}. The header alone picks
|
||||
* the storage partition every one of these operations reads, overwrites or deletes, so an
|
||||
* unchecked value writes a configuration under a partition no account can ever address again.
|
||||
*/
|
||||
@Test
|
||||
void accountPublicAccessBlockRejectsAMalformedAccountId() {
|
||||
for (String bad : new String[] {"12345678901", "1234567890123", "00000000000a",
|
||||
"arn:aws:iam::000000000000:root", "000000000000 "}) {
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> s3Service.putAccountPublicAccessBlock(bad, "<x/>"),
|
||||
"expected rejection for account id: " + bad);
|
||||
assertEquals("InvalidRequest", ex.getErrorCode());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAndDeleteAccountPublicAccessBlockAlsoRejectAMalformedAccountId() {
|
||||
assertEquals("InvalidRequest", assertThrows(AwsException.class,
|
||||
() -> s3Service.getAccountPublicAccessBlock("not-an-account")).getErrorCode());
|
||||
assertEquals("InvalidRequest", assertThrows(AwsException.class,
|
||||
() -> s3Service.deleteAccountPublicAccessBlock("not-an-account")).getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void clearLeavesAccountPublicAccessBlockToItsStorageBackend() {
|
||||
// clear() resets only the in-process object/multipart maps. The account-level config now
|
||||
// lives in a StorageFactory-backed store, whose lifecycle StorageFactory.clearAll() owns —
|
||||
// same as the bucket and object stores, which clear() also deliberately leaves alone.
|
||||
s3Service.putAccountPublicAccessBlock("000000000000", "<x/>");
|
||||
s3Service.clear();
|
||||
assertEquals("<x/>", s3Service.getAccountPublicAccessBlock("000000000000"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package io.github.hectorvent.floci.services.s3;
|
||||
|
||||
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
|
||||
import io.github.hectorvent.floci.services.s3.model.S3Object;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
|
||||
/**
|
||||
* In {@code hybrid}/filesystem storage mode (the default) an S3 object's bytes live on disk.
|
||||
* LZA's Bootstrap stage fans out ~15 CodeBuild actions that each redundantly re-upload the
|
||||
* same runtime-artifact keys ({@code codepipeline/<execId>/Source.zip}, {@code .../Config.zip})
|
||||
* while other builds concurrently download those same keys to stage their source. A writer that
|
||||
* truncates-then-writes a file is not atomic against a concurrent reader, so the reader can
|
||||
* observe an empty or partial object — which surfaced downstream as an empty {@code src-Config}
|
||||
* secondary source and {@code ENOENT: global-config.yaml}. getObject must therefore never return
|
||||
* a torn view of a key that always holds the same full-size payload.
|
||||
*/
|
||||
class S3ConcurrentWriteReadTest {
|
||||
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
|
||||
@Test
|
||||
void concurrentOverwriteNeverYieldsTornRead() throws Exception {
|
||||
S3Service s3 = new S3Service(new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
tempDir.resolve("s3"), false);
|
||||
String bucket = "codepipeline-artifacts";
|
||||
String key = "codepipeline/exec-1/Config.zip";
|
||||
s3.createBucket(bucket, "us-east-1");
|
||||
|
||||
// A sizable payload widens the truncate-then-write window so a torn read is observable.
|
||||
byte[] payload = new byte[1 << 20];
|
||||
for (int i = 0; i < payload.length; i++) {
|
||||
payload[i] = (byte) (i * 31 + 7);
|
||||
}
|
||||
// Seed the key so readers never race a not-yet-created object (that is a separate concern).
|
||||
s3.putObject(bucket, key, payload, "application/zip", Map.of());
|
||||
|
||||
int writers = 4;
|
||||
int readers = 4;
|
||||
int iterations = 400;
|
||||
AtomicReference<String> firstTear = new AtomicReference<>();
|
||||
AtomicInteger reads = new AtomicInteger();
|
||||
volatileDone done = new volatileDone();
|
||||
|
||||
Thread[] threads = new Thread[writers + readers];
|
||||
for (int w = 0; w < writers; w++) {
|
||||
threads[w] = new Thread(() -> {
|
||||
for (int i = 0; i < iterations && firstTear.get() == null; i++) {
|
||||
s3.putObject(bucket, key, payload, "application/zip", Map.of());
|
||||
}
|
||||
done.count.incrementAndGet();
|
||||
});
|
||||
}
|
||||
for (int r = 0; r < readers; r++) {
|
||||
threads[writers + r] = new Thread(() -> {
|
||||
while (done.count.get() < writers && firstTear.get() == null) {
|
||||
S3Object obj = s3.getObject(bucket, key);
|
||||
byte[] data = obj.getData();
|
||||
reads.incrementAndGet();
|
||||
if (data == null || data.length != payload.length) {
|
||||
firstTear.compareAndSet(null,
|
||||
"torn read: length=" + (data == null ? "null" : data.length)
|
||||
+ " expected=" + payload.length);
|
||||
return;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
for (Thread t : threads) t.start();
|
||||
for (Thread t : threads) {
|
||||
t.join(30_000);
|
||||
assertFalse(t.isAlive(), "thread did not finish within the join timeout");
|
||||
}
|
||||
|
||||
assertNull(firstTear.get(), firstTear.get());
|
||||
// Guard against a vacuous pass: the readers must actually have run.
|
||||
assertEquals(true, reads.get() > 0, "reader threads never observed the object");
|
||||
}
|
||||
|
||||
/** Tiny holder so the reader loop can see writers finishing without a shared executor. */
|
||||
private static final class volatileDone {
|
||||
final AtomicInteger count = new AtomicInteger();
|
||||
}
|
||||
}
|
||||
+152
@@ -0,0 +1,152 @@
|
||||
package io.github.hectorvent.floci.services.s3;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.RequestContext;
|
||||
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
|
||||
import jakarta.enterprise.inject.Instance;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import java.nio.file.Path;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* The account-level Block Public Access operations are keyed by the {@code x-amz-account-id}
|
||||
* header. Block Public Access is a security control, so the header must not be usable to read,
|
||||
* overwrite or delete another account's configuration: AWS s3control requires the header to
|
||||
* name the caller's own account and answers {@code AccessDenied} otherwise.
|
||||
*
|
||||
* <p>Every controller here shares one {@link S3Service}, as the CDI beans do — only the resolved
|
||||
* caller account differs between them.
|
||||
*/
|
||||
class S3ControlAccountIdEnforcementTest {
|
||||
|
||||
private static final String DEFAULT_ACCOUNT = "000000000000";
|
||||
private static final String GOVERNED_ACCOUNT = "452743914166";
|
||||
private static final String OTHER_ACCOUNT = "999988887777";
|
||||
|
||||
private static final String CONFIG_XML =
|
||||
"<PublicAccessBlockConfiguration><BlockPublicAcls>true</BlockPublicAcls>"
|
||||
+ "</PublicAccessBlockConfiguration>";
|
||||
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
|
||||
private S3Service service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
service = new S3Service(new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
tempDir.resolve("s3"), false);
|
||||
}
|
||||
|
||||
@Test
|
||||
void callerMayManageItsOwnAccountConfiguration() {
|
||||
S3ControlController owner = controllerFor(GOVERNED_ACCOUNT);
|
||||
|
||||
assertEquals(200, owner.putPublicAccessBlock(GOVERNED_ACCOUNT, CONFIG_XML).getStatus());
|
||||
|
||||
Response read = owner.getPublicAccessBlock(GOVERNED_ACCOUNT);
|
||||
assertEquals(200, read.getStatus());
|
||||
assertTrue(read.getEntity().toString().contains("<BlockPublicAcls>true</BlockPublicAcls>"));
|
||||
|
||||
assertEquals(204, owner.deletePublicAccessBlock(GOVERNED_ACCOUNT).getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void foreignCallerCannotWriteAnotherAccountConfiguration() {
|
||||
controllerFor(GOVERNED_ACCOUNT).putPublicAccessBlock(GOVERNED_ACCOUNT, CONFIG_XML);
|
||||
|
||||
Response response = controllerFor(OTHER_ACCOUNT)
|
||||
.putPublicAccessBlock(GOVERNED_ACCOUNT, "<PublicAccessBlockConfiguration/>");
|
||||
|
||||
assertEquals(403, response.getStatus());
|
||||
assertTrue(response.getEntity().toString().contains("<Code>AccessDenied</Code>"));
|
||||
|
||||
// The victim's configuration is untouched.
|
||||
Response read = controllerFor(GOVERNED_ACCOUNT).getPublicAccessBlock(GOVERNED_ACCOUNT);
|
||||
assertTrue(read.getEntity().toString().contains("<BlockPublicAcls>true</BlockPublicAcls>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void foreignCallerCannotReadOrDeleteAnotherAccountConfiguration() {
|
||||
controllerFor(GOVERNED_ACCOUNT).putPublicAccessBlock(GOVERNED_ACCOUNT, CONFIG_XML);
|
||||
S3ControlController attacker = controllerFor(OTHER_ACCOUNT);
|
||||
|
||||
Response read = attacker.getPublicAccessBlock(GOVERNED_ACCOUNT);
|
||||
assertEquals(403, read.getStatus());
|
||||
assertTrue(read.getEntity().toString().contains("<Code>AccessDenied</Code>"));
|
||||
|
||||
Response deleted = attacker.deletePublicAccessBlock(GOVERNED_ACCOUNT);
|
||||
assertEquals(403, deleted.getStatus());
|
||||
assertTrue(deleted.getEntity().toString().contains("<Code>AccessDenied</Code>"));
|
||||
|
||||
assertEquals(200, controllerFor(GOVERNED_ACCOUNT)
|
||||
.getPublicAccessBlock(GOVERNED_ACCOUNT).getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void managementAccountCallerMayManageAGovernedAccountConfiguration() {
|
||||
// LZA's Custom::PutPublicAccessBlock Lambda runs under the management account's
|
||||
// placeholder credentials while naming each governed account in the header.
|
||||
S3ControlController management = controllerFor(DEFAULT_ACCOUNT);
|
||||
|
||||
assertEquals(200, management.putPublicAccessBlock(GOVERNED_ACCOUNT, CONFIG_XML).getStatus());
|
||||
assertEquals(200, management.getPublicAccessBlock(GOVERNED_ACCOUNT).getStatus());
|
||||
// The config landed in the governed account's partition, not the management account's.
|
||||
assertEquals(404, management.getPublicAccessBlock(DEFAULT_ACCOUNT).getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingAccountIdStillFailsAsInvalidRequest() {
|
||||
Response response = controllerFor(GOVERNED_ACCOUNT).getPublicAccessBlock(" ");
|
||||
|
||||
assertEquals(400, response.getStatus());
|
||||
assertTrue(response.getEntity().toString().contains("<Code>InvalidRequest</Code>"));
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code PublicAccessBlockConfiguration} is a required member of {@code PutPublicAccessBlockRequest}.
|
||||
* Block Public Access is a security control, so an empty, unparseable, or wrong-root body must
|
||||
* be rejected as {@code MalformedXML} rather than silently normalized into a configuration with
|
||||
* every flag defaulted to false — which would look like the caller deliberately disabled every
|
||||
* protection.
|
||||
*/
|
||||
@Test
|
||||
void putRejectsAMalformedOrWrongRootBody() {
|
||||
S3ControlController owner = controllerFor(GOVERNED_ACCOUNT);
|
||||
owner.putPublicAccessBlock(GOVERNED_ACCOUNT, CONFIG_XML);
|
||||
|
||||
for (String body : new String[] {null, "", "not xml",
|
||||
"<VersioningConfiguration><Status>Enabled</Status></VersioningConfiguration>"}) {
|
||||
Response response = owner.putPublicAccessBlock(GOVERNED_ACCOUNT, body);
|
||||
assertEquals(400, response.getStatus(), "expected rejection for body: " + body);
|
||||
assertTrue(response.getEntity().toString().contains("<Code>MalformedXML</Code>"),
|
||||
"expected MalformedXML for body: " + body);
|
||||
}
|
||||
|
||||
// The existing configuration must survive a rejected write.
|
||||
Response read = owner.getPublicAccessBlock(GOVERNED_ACCOUNT);
|
||||
assertTrue(read.getEntity().toString().contains("<BlockPublicAcls>true</BlockPublicAcls>"));
|
||||
}
|
||||
|
||||
private S3ControlController controllerFor(String callerAccountId) {
|
||||
RequestContext context = new RequestContext();
|
||||
context.setAccountId(callerAccountId);
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
Instance<RequestContext> contextInstance = mock(Instance.class);
|
||||
when(contextInstance.get()).thenReturn(context);
|
||||
|
||||
EmulatorConfig config = mock(EmulatorConfig.class);
|
||||
when(config.defaultAccountId()).thenReturn(DEFAULT_ACCOUNT);
|
||||
|
||||
return new S3ControlController(service, contextInstance, config);
|
||||
}
|
||||
}
|
||||
+207
@@ -0,0 +1,207 @@
|
||||
package io.github.hectorvent.floci.services.s3;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RequestContext;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
|
||||
import io.github.hectorvent.floci.services.s3.model.Bucket;
|
||||
import io.github.hectorvent.floci.services.s3.model.S3Object;
|
||||
import jakarta.enterprise.inject.Instance;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import static java.nio.charset.StandardCharsets.UTF_8;
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* S3 bucket names are globally unique in AWS: a bucket lives in one account but is legitimately
|
||||
* reachable cross-account (subject to policy). The Landing Zone Accelerator relies on this — every
|
||||
* member account publishes CDK assets to one shared {@code cdk-accel-assets-<mgmt>-<region>} bucket
|
||||
* owned by the management account. floci's default per-account bucket isolation breaks that path.
|
||||
*
|
||||
* <p>With {@code globalBucketNamespace} enabled, bucket/object <em>resolution</em> spans accounts
|
||||
* while <em>listing</em> stays owner-scoped. Default-off preserves the existing isolation model
|
||||
* (guarded by {@code PreSignedUrlAccountResolutionIntegrationTest}).
|
||||
*/
|
||||
class S3GlobalBucketNamespaceTest {
|
||||
|
||||
private static final String DEFAULT_ACCT = "000000000000";
|
||||
private static final String ACCOUNT_A = "000000000001";
|
||||
private static final String ACCOUNT_B = "000000000002";
|
||||
|
||||
private final AtomicReference<String> caller = new AtomicReference<>(DEFAULT_ACCT);
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private Instance<RequestContext> mutableContext() {
|
||||
RequestContext rc = mock(RequestContext.class);
|
||||
when(rc.getAccountId()).thenAnswer(inv -> caller.get());
|
||||
Instance<RequestContext> inst = mock(Instance.class);
|
||||
when(inst.get()).thenReturn(rc);
|
||||
return inst;
|
||||
}
|
||||
|
||||
@Test
|
||||
void bucketOwnedByOneAccountIsResolvableCrossAccountButNotListed() {
|
||||
Instance<RequestContext> ctx = mutableContext();
|
||||
AccountAwareStorageBackend<Bucket> buckets =
|
||||
new AccountAwareStorageBackend<>(new InMemoryStorage<>(), ctx, DEFAULT_ACCT);
|
||||
AccountAwareStorageBackend<S3Object> objects =
|
||||
new AccountAwareStorageBackend<>(new InMemoryStorage<>(), ctx, DEFAULT_ACCT);
|
||||
|
||||
S3Service globalNs = new S3Service(buckets, objects, Path.of("s3-gns-test"), true, true);
|
||||
S3Service isolatedNs = new S3Service(buckets, objects, Path.of("s3-gns-test"), true, false);
|
||||
|
||||
// Account A owns the shared bucket and publishes a template into it.
|
||||
caller.set(ACCOUNT_A);
|
||||
globalNs.createBucket("shared-assets-bucket", "us-west-2");
|
||||
byte[] template = "{\"Resources\":{}}".getBytes(UTF_8);
|
||||
globalNs.putObject("shared-assets-bucket", "template.json", template, "application/json", Map.of());
|
||||
|
||||
// Account B is a different account (a member account in LZA terms).
|
||||
caller.set(ACCOUNT_B);
|
||||
|
||||
// (1) HeadBucket resolves cross-account.
|
||||
assertDoesNotThrow(() -> globalNs.headBucket("shared-assets-bucket"));
|
||||
|
||||
// (1) GetBucketLocation returns the owner's region cross-account.
|
||||
assertEquals("us-west-2", globalNs.getBucketRegion("shared-assets-bucket"));
|
||||
|
||||
// (2) GetObject reads the owner's object cross-account.
|
||||
assertArrayEquals(template,
|
||||
globalNs.getObject("shared-assets-bucket", "template.json").getData());
|
||||
|
||||
// (2b) The LZA central-assets path: a member account publishes its own asset into the
|
||||
// management-owned bucket (existence check must resolve cross-account), then reads it back.
|
||||
byte[] memberAsset = "member-payload".getBytes(UTF_8);
|
||||
assertDoesNotThrow(() ->
|
||||
globalNs.putObject("shared-assets-bucket", "member-asset.json", memberAsset,
|
||||
"application/json", Map.of()));
|
||||
assertArrayEquals(memberAsset,
|
||||
globalNs.getObject("shared-assets-bucket", "member-asset.json").getData());
|
||||
|
||||
// (3) Listing stays owner-scoped: account B does not see account A's bucket.
|
||||
assertTrue(globalNs.listBuckets().stream()
|
||||
.noneMatch(b -> "shared-assets-bucket".equals(b.getName())),
|
||||
"ListBuckets must remain owner-scoped even with global namespace enabled");
|
||||
|
||||
// (4) Default-off preserves isolation: the same cross-account HeadBucket is NoSuchBucket.
|
||||
AwsException notFound = assertThrows(AwsException.class,
|
||||
() -> isolatedNs.headBucket("shared-assets-bucket"));
|
||||
assertEquals("NoSuchBucket", notFound.getErrorCode());
|
||||
}
|
||||
|
||||
/**
|
||||
* Cross-account bucket-config <em>mutation</em>. LZA's {@code Custom::S3PutBucketReplication}
|
||||
* custom resource runs a Lambda in the source (member) account that owns the bucket, but that
|
||||
* Lambda calls back into floci under the default/management account context. The mutation must
|
||||
* resolve the bucket cross-account (not 404) AND persist back to the <em>owner's</em> partition —
|
||||
* a naive resolve-then-{@code put} would fork a phantom bucket into the caller's partition and
|
||||
* silently lose the config on the real bucket.
|
||||
*/
|
||||
@Test
|
||||
void putBucketReplicationResolvesAndWritesBackToOwnerCrossAccount() {
|
||||
Instance<RequestContext> ctx = mutableContext();
|
||||
AccountAwareStorageBackend<Bucket> buckets =
|
||||
new AccountAwareStorageBackend<>(new InMemoryStorage<>(), ctx, DEFAULT_ACCT);
|
||||
AccountAwareStorageBackend<S3Object> objects =
|
||||
new AccountAwareStorageBackend<>(new InMemoryStorage<>(), ctx, DEFAULT_ACCT);
|
||||
S3Service globalNs = new S3Service(buckets, objects, Path.of("s3-gns-repl-test"), true, true);
|
||||
|
||||
// The source (member) account owns the ELB access-logs bucket.
|
||||
caller.set(ACCOUNT_A);
|
||||
globalNs.createBucket("elb-access-logs-bucket", "us-east-1");
|
||||
|
||||
// The replication custom-resource Lambda calls back under the default/management context.
|
||||
caller.set(DEFAULT_ACCT);
|
||||
String xml = "<ReplicationConfiguration>"
|
||||
+ "<Role>arn:aws:iam::000000000001:role/replication</Role>"
|
||||
+ "<Rule><Status>Enabled</Status>"
|
||||
+ "<Destination><Bucket>arn:aws:s3:::central-logs</Bucket></Destination></Rule>"
|
||||
+ "</ReplicationConfiguration>";
|
||||
assertDoesNotThrow(() -> globalNs.putBucketReplication("elb-access-logs-bucket", xml));
|
||||
|
||||
// Persisted on the OWNER's bucket (account A), not the caller's partition.
|
||||
Bucket owned = buckets.getForAccount(ACCOUNT_A, "elb-access-logs-bucket")
|
||||
.orElseThrow(() -> new AssertionError("bucket vanished from owner partition"));
|
||||
assertEquals(xml, owned.getReplicationConfiguration());
|
||||
|
||||
// No phantom bucket forked into the caller's default partition.
|
||||
assertTrue(buckets.getForAccount(DEFAULT_ACCT, "elb-access-logs-bucket").isEmpty(),
|
||||
"cross-account replication write must not fork a bucket into the caller's account");
|
||||
}
|
||||
|
||||
/**
|
||||
* The write side of {@code Custom::S3PutBucketReplication} resolves and persists cross-account
|
||||
* (see {@link #putBucketReplicationResolvesAndWritesBackToOwnerCrossAccount}); the read side
|
||||
* must resolve just as far, or the custom resource's own follow-up
|
||||
* {@code GetBucketReplication} — and any other management-account reader — sees
|
||||
* {@code NoSuchBucket} on a bucket that plainly exists in its owning account.
|
||||
*/
|
||||
@Test
|
||||
void getBucketReplicationResolvesCrossAccount() {
|
||||
Instance<RequestContext> ctx = mutableContext();
|
||||
AccountAwareStorageBackend<Bucket> buckets =
|
||||
new AccountAwareStorageBackend<>(new InMemoryStorage<>(), ctx, DEFAULT_ACCT);
|
||||
AccountAwareStorageBackend<S3Object> objects =
|
||||
new AccountAwareStorageBackend<>(new InMemoryStorage<>(), ctx, DEFAULT_ACCT);
|
||||
S3Service globalNs = new S3Service(buckets, objects, Path.of("s3-gns-repl-read-test"), true, true);
|
||||
|
||||
caller.set(ACCOUNT_A);
|
||||
globalNs.createBucket("elb-access-logs-bucket-2", "us-east-1");
|
||||
String xml = "<ReplicationConfiguration>"
|
||||
+ "<Role>arn:aws:iam::000000000001:role/replication</Role>"
|
||||
+ "<Rule><Status>Enabled</Status>"
|
||||
+ "<Destination><Bucket>arn:aws:s3:::central-logs</Bucket></Destination></Rule>"
|
||||
+ "</ReplicationConfiguration>";
|
||||
globalNs.putBucketReplication("elb-access-logs-bucket-2", xml);
|
||||
|
||||
caller.set(DEFAULT_ACCT);
|
||||
assertEquals(xml, globalNs.getBucketReplication("elb-access-logs-bucket-2"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Bucket-policy operations were left on the direct {@code bucketStore.get}/{@code put} path when
|
||||
* global namespace resolution was added — unlike replication and object read/write, they never got
|
||||
* wired through {@code resolveBucket}/{@code mutateBucket}. A management-account caller (as the LZA
|
||||
* Logging stage's policy-application step runs) must be able to put/get/delete a policy on a bucket
|
||||
* owned by a member account.
|
||||
*/
|
||||
@Test
|
||||
void bucketPolicyResolvesAndPersistsCrossAccount() {
|
||||
Instance<RequestContext> ctx = mutableContext();
|
||||
AccountAwareStorageBackend<Bucket> buckets =
|
||||
new AccountAwareStorageBackend<>(new InMemoryStorage<>(), ctx, DEFAULT_ACCT);
|
||||
AccountAwareStorageBackend<S3Object> objects =
|
||||
new AccountAwareStorageBackend<>(new InMemoryStorage<>(), ctx, DEFAULT_ACCT);
|
||||
S3Service globalNs = new S3Service(buckets, objects, Path.of("s3-gns-policy-test"), true, true);
|
||||
|
||||
caller.set(ACCOUNT_A);
|
||||
globalNs.createBucket("central-logs-bucket", "us-east-1");
|
||||
|
||||
caller.set(DEFAULT_ACCT);
|
||||
String policy = "{\"Version\":\"2012-10-17\",\"Statement\":[]}";
|
||||
assertDoesNotThrow(() -> globalNs.putBucketPolicy("central-logs-bucket", policy));
|
||||
assertEquals(policy, globalNs.getBucketPolicy("central-logs-bucket"));
|
||||
|
||||
// Persisted on the OWNER's bucket (account A), not forked into the caller's partition.
|
||||
Bucket owned = buckets.getForAccount(ACCOUNT_A, "central-logs-bucket")
|
||||
.orElseThrow(() -> new AssertionError("bucket vanished from owner partition"));
|
||||
assertEquals(policy, owned.getPolicy());
|
||||
assertTrue(buckets.getForAccount(DEFAULT_ACCT, "central-logs-bucket").isEmpty(),
|
||||
"cross-account putBucketPolicy must not fork a bucket into the caller's account");
|
||||
|
||||
assertDoesNotThrow(() -> globalNs.deleteBucketPolicy("central-logs-bucket"));
|
||||
AwsException notFound = assertThrows(AwsException.class,
|
||||
() -> globalNs.getBucketPolicy("central-logs-bucket"));
|
||||
assertEquals("NoSuchBucketPolicy", notFound.getErrorCode());
|
||||
}
|
||||
}
|
||||
+188
-5
@@ -172,8 +172,109 @@ class S3ReplicationConfigurationIntegrationTest {
|
||||
.body(containsString("<ID>rule2</ID>"));
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code ReplicationRule/Status} is Required: Yes with enum {@code Enabled|Disabled}.
|
||||
* Storing a rule with any other status — or with none — makes the emulator answer a
|
||||
* later GetBucketReplication with a document AWS would never have accepted.
|
||||
*/
|
||||
@Test
|
||||
@Order(8)
|
||||
void putReplicationRejectsARuleStatusOutsideTheEnum() {
|
||||
given()
|
||||
.body("""
|
||||
<ReplicationConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
|
||||
<Role>arn:aws:iam::000000000000:role/replication-role</Role>
|
||||
<Rule>
|
||||
<ID>bad-status</ID>
|
||||
<Status>enabled</Status>
|
||||
<Destination>
|
||||
<Bucket>arn:aws:s3:::replication-config-int-test-target</Bucket>
|
||||
</Destination>
|
||||
</Rule>
|
||||
</ReplicationConfiguration>
|
||||
""")
|
||||
.when()
|
||||
.put("/" + BUCKET + "?replication")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body(containsString("MalformedXML"));
|
||||
given()
|
||||
.when()
|
||||
.get("/" + BUCKET + "?replication")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(not(containsString("bad-status")));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(9)
|
||||
void putReplicationRejectsARuleWithNoStatus() {
|
||||
given()
|
||||
.body("""
|
||||
<ReplicationConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
|
||||
<Role>arn:aws:iam::000000000000:role/replication-role</Role>
|
||||
<Rule>
|
||||
<ID>no-status</ID>
|
||||
<Destination>
|
||||
<Bucket>arn:aws:s3:::replication-config-int-test-target</Bucket>
|
||||
</Destination>
|
||||
</Rule>
|
||||
</ReplicationConfiguration>
|
||||
""")
|
||||
.when()
|
||||
.put("/" + BUCKET + "?replication")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body(containsString("MalformedXML"));
|
||||
given()
|
||||
.when()
|
||||
.get("/" + BUCKET + "?replication")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(not(containsString("no-status")));
|
||||
}
|
||||
|
||||
/**
|
||||
* Each {@code Rule} requires its own {@code Destination/Bucket}; a document-wide check that
|
||||
* only looks for one {@code Bucket} anywhere in the XML is satisfied when just one of several
|
||||
* rules has a destination, so a rule missing one round-trips as a configuration AWS would
|
||||
* have rejected as {@code MalformedXML}.
|
||||
*/
|
||||
@Test
|
||||
@Order(10)
|
||||
void putReplicationRejectsARuleWithoutItsOwnDestinationBucket() {
|
||||
given()
|
||||
.body("""
|
||||
<ReplicationConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
|
||||
<Role>arn:aws:iam::000000000000:role/replication-role</Role>
|
||||
<Rule>
|
||||
<ID>has-destination</ID>
|
||||
<Status>Enabled</Status>
|
||||
<Destination>
|
||||
<Bucket>arn:aws:s3:::replication-config-int-test-target</Bucket>
|
||||
</Destination>
|
||||
</Rule>
|
||||
<Rule>
|
||||
<ID>missing-destination</ID>
|
||||
<Status>Enabled</Status>
|
||||
</Rule>
|
||||
</ReplicationConfiguration>
|
||||
""")
|
||||
.when()
|
||||
.put("/" + BUCKET + "?replication")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body(containsString("MalformedXML"));
|
||||
given()
|
||||
.when()
|
||||
.get("/" + BUCKET + "?replication")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(not(containsString("missing-destination")));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(11)
|
||||
void putReplicationOnMissingBucketReturns404() {
|
||||
given()
|
||||
.body(REPLICATION_XML)
|
||||
@@ -185,7 +286,7 @@ class S3ReplicationConfigurationIntegrationTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(9)
|
||||
@Order(12)
|
||||
void getReplicationOnMissingBucketReturns404() {
|
||||
given()
|
||||
.when()
|
||||
@@ -202,7 +303,7 @@ class S3ReplicationConfigurationIntegrationTest {
|
||||
* /{bucket}?replication} would have fallen through to {@code DeleteBucket}.
|
||||
*/
|
||||
@Test
|
||||
@Order(10)
|
||||
@Order(13)
|
||||
void deleteReplicationClearsTheStoredConfiguration() {
|
||||
given()
|
||||
.when()
|
||||
@@ -224,7 +325,7 @@ class S3ReplicationConfigurationIntegrationTest {
|
||||
|
||||
/** Matching real S3, deleting an already-absent configuration still answers 204. */
|
||||
@Test
|
||||
@Order(11)
|
||||
@Order(14)
|
||||
void deleteReplicationWithoutConfigurationStillReturns204() {
|
||||
given()
|
||||
.when()
|
||||
@@ -234,7 +335,7 @@ class S3ReplicationConfigurationIntegrationTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(12)
|
||||
@Order(15)
|
||||
void deleteReplicationOnMissingBucketReturns404() {
|
||||
given()
|
||||
.when()
|
||||
@@ -252,7 +353,7 @@ class S3ReplicationConfigurationIntegrationTest {
|
||||
* the two.
|
||||
*/
|
||||
@Test
|
||||
@Order(13)
|
||||
@Order(16)
|
||||
void accelerateAndReplicationPrecedenceFollowsEachMethodsDispatchOrder() {
|
||||
String bucket = "replication-precedence-test";
|
||||
given()
|
||||
@@ -315,4 +416,86 @@ class S3ReplicationConfigurationIntegrationTest {
|
||||
.statusCode(404)
|
||||
.body(containsString("ReplicationConfigurationNotFoundError"));
|
||||
}
|
||||
|
||||
/**
|
||||
* A document-wide count of Rule elements against Destination elements can't distinguish a
|
||||
* well-formed document from one where a rule improperly carries two Destinations and another
|
||||
* rule carries none — the totals still balance (2 rules, 2 destinations) even though the
|
||||
* second rule has no destination of its own and the first has one too many.
|
||||
*/
|
||||
@Test
|
||||
@Order(17)
|
||||
void putReplicationRejectsWhenDestinationsAreNotOnePerRule() {
|
||||
given()
|
||||
.body("""
|
||||
<ReplicationConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
|
||||
<Role>arn:aws:iam::000000000000:role/replication-role</Role>
|
||||
<Rule>
|
||||
<ID>two-destinations</ID>
|
||||
<Status>Enabled</Status>
|
||||
<Destination>
|
||||
<Bucket>arn:aws:s3:::replication-config-int-test-target</Bucket>
|
||||
</Destination>
|
||||
<Destination>
|
||||
<Bucket>arn:aws:s3:::replication-config-int-test-target-2</Bucket>
|
||||
</Destination>
|
||||
</Rule>
|
||||
<Rule>
|
||||
<ID>zero-destinations</ID>
|
||||
<Status>Enabled</Status>
|
||||
</Rule>
|
||||
</ReplicationConfiguration>
|
||||
""")
|
||||
.when()
|
||||
.put("/" + BUCKET + "?replication")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body(containsString("MalformedXML"));
|
||||
// BUCKET has no configuration at this point in the ordered sequence (cleared by
|
||||
// deleteReplicationClearsTheStoredConfiguration, @Order(13)), so the rejected PUT above
|
||||
// must not have stored anything either.
|
||||
given()
|
||||
.when()
|
||||
.get("/" + BUCKET + "?replication")
|
||||
.then()
|
||||
.statusCode(404)
|
||||
.body(containsString("ReplicationConfigurationNotFoundError"));
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code Destination.Bucket} is a required <em>scalar</em> member (botocore
|
||||
* s3/2006-03-01/service-2.json: {@code "Bucket":{"shape":"BucketName"}}, not a list) — a
|
||||
* Destination with two Bucket children is not a valid alternative encoding, it is malformed.
|
||||
* Selecting only the first Bucket child would silently accept the second as if it never
|
||||
* existed and store a document AWS would reject.
|
||||
*/
|
||||
@Test
|
||||
@Order(18)
|
||||
void putReplicationRejectsADestinationWithMultipleBucketElements() {
|
||||
given()
|
||||
.body("""
|
||||
<ReplicationConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
|
||||
<Role>arn:aws:iam::000000000000:role/replication-role</Role>
|
||||
<Rule>
|
||||
<ID>two-buckets</ID>
|
||||
<Status>Enabled</Status>
|
||||
<Destination>
|
||||
<Bucket>arn:aws:s3:::replication-config-int-test-target</Bucket>
|
||||
<Bucket>arn:aws:s3:::replication-config-int-test-target-2</Bucket>
|
||||
</Destination>
|
||||
</Rule>
|
||||
</ReplicationConfiguration>
|
||||
""")
|
||||
.when()
|
||||
.put("/" + BUCKET + "?replication")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body(containsString("MalformedXML"));
|
||||
given()
|
||||
.when()
|
||||
.get("/" + BUCKET + "?replication")
|
||||
.then()
|
||||
.statusCode(404)
|
||||
.body(containsString("ReplicationConfigurationNotFoundError"));
|
||||
}
|
||||
}
|
||||
+133
-4
@@ -8,12 +8,26 @@ import org.junit.jupiter.api.TestMethodOrder;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
|
||||
@QuarkusTest
|
||||
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
|
||||
class S3ReplicationIntegrationTest {
|
||||
|
||||
private static final String BUCKET = "replication-int-test";
|
||||
private static final String WEST_BUCKET = "replication-int-test-west";
|
||||
private static final String REPLICATION_XML = """
|
||||
<ReplicationConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
|
||||
<Role>arn:aws:iam::000000000000:role/replication-role</Role>
|
||||
<Rule>
|
||||
<ID>rule-1</ID>
|
||||
<Status>Enabled</Status>
|
||||
<Destination>
|
||||
<Bucket>arn:aws:s3:::replication-dest</Bucket>
|
||||
</Destination>
|
||||
</Rule>
|
||||
</ReplicationConfiguration>
|
||||
""";
|
||||
|
||||
@Test
|
||||
@Order(1)
|
||||
@@ -25,6 +39,17 @@ class S3ReplicationIntegrationTest {
|
||||
.statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(2)
|
||||
void getReplicationBeforePutReturns404() {
|
||||
given()
|
||||
.when()
|
||||
.get("/" + BUCKET + "?replication")
|
||||
.then()
|
||||
.statusCode(404)
|
||||
.body(containsString("ReplicationConfigurationNotFoundError"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Regression test for the bucket-destroying bug where {@code DELETE /{bucket}?replication}
|
||||
* (DeleteBucketReplication) was not handled and fell through to the unqualified
|
||||
@@ -32,7 +57,7 @@ class S3ReplicationIntegrationTest {
|
||||
* replication configuration and returns 204.
|
||||
*/
|
||||
@Test
|
||||
@Order(2)
|
||||
@Order(3)
|
||||
void deleteReplicationDoesNotDeleteBucket() {
|
||||
given()
|
||||
.when()
|
||||
@@ -42,7 +67,7 @@ class S3ReplicationIntegrationTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(3)
|
||||
@Order(4)
|
||||
void bucketStillExistsAfterReplicationDelete() {
|
||||
// A sub-resource-qualified DELETE must never remove the bucket itself.
|
||||
given()
|
||||
@@ -53,7 +78,7 @@ class S3ReplicationIntegrationTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(4)
|
||||
@Order(5)
|
||||
void putVersioningAfterReplicationDeleteSucceeds() {
|
||||
given()
|
||||
.body("""
|
||||
@@ -68,7 +93,111 @@ class S3ReplicationIntegrationTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(5)
|
||||
@Order(6)
|
||||
void putReplicationStoresConfiguration() {
|
||||
given()
|
||||
.body(REPLICATION_XML)
|
||||
.when()
|
||||
.put("/" + BUCKET + "?replication")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(7)
|
||||
void getReplicationRoundTripsStoredConfiguration() {
|
||||
given()
|
||||
.when()
|
||||
.get("/" + BUCKET + "?replication")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString("<Role>arn:aws:iam::000000000000:role/replication-role</Role>"))
|
||||
.body(containsString("<ID>rule-1</ID>"))
|
||||
.body(containsString("<Status>Enabled</Status>"))
|
||||
.body(containsString("<Bucket>arn:aws:s3:::replication-dest</Bucket>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(8)
|
||||
void putReplicationWithoutRoleReturnsMalformedXml() {
|
||||
given()
|
||||
.body("""
|
||||
<ReplicationConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
|
||||
<Rule>
|
||||
<Status>Enabled</Status>
|
||||
<Destination>
|
||||
<Bucket>arn:aws:s3:::replication-dest</Bucket>
|
||||
</Destination>
|
||||
</Rule>
|
||||
</ReplicationConfiguration>
|
||||
""")
|
||||
.when()
|
||||
.put("/" + BUCKET + "?replication")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body(containsString("MalformedXML"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(9)
|
||||
void deleteReplicationRemovesConfiguration() {
|
||||
given()
|
||||
.when()
|
||||
.delete("/" + BUCKET + "?replication")
|
||||
.then()
|
||||
.statusCode(204);
|
||||
|
||||
given()
|
||||
.when()
|
||||
.get("/" + BUCKET + "?replication")
|
||||
.then()
|
||||
.statusCode(404)
|
||||
.body(containsString("ReplicationConfigurationNotFoundError"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Regression test for {@code PUT /{bucket}?replication} falling through to CreateBucket:
|
||||
* outside us-east-1 the fall-through surfaced as {@code 409 BucketAlreadyOwnedByYou}
|
||||
* (and in us-east-1 as a silent false success).
|
||||
*/
|
||||
@Test
|
||||
@Order(10)
|
||||
void putReplicationOnNonUsEast1BucketDoesNot409() {
|
||||
given()
|
||||
.body("""
|
||||
<CreateBucketConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
|
||||
<LocationConstraint>us-west-2</LocationConstraint>
|
||||
</CreateBucketConfiguration>
|
||||
""")
|
||||
.when()
|
||||
.put("/" + WEST_BUCKET)
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
given()
|
||||
.body(REPLICATION_XML)
|
||||
.when()
|
||||
.put("/" + WEST_BUCKET + "?replication")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(not(containsString("BucketAlreadyOwnedByYou")));
|
||||
|
||||
given()
|
||||
.when()
|
||||
.get("/" + WEST_BUCKET + "?replication")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString("<ID>rule-1</ID>"));
|
||||
|
||||
given()
|
||||
.when()
|
||||
.delete("/" + WEST_BUCKET)
|
||||
.then()
|
||||
.statusCode(204);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(11)
|
||||
void unqualifiedDeleteStillRemovesBucket() {
|
||||
given()
|
||||
.when()
|
||||
|
||||
Reference in new issue
Block a user