mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(iam): distinguish cross-account resource grants (#3590)
* fix(iam): distinguish cross-account resource grants * fix(iam): honor exact principal ARN resource grants * fix(s3): persist cross-account object metadata to owner --------- Co-authored-by: xujiantop-crypto <265865031+xujiantop-crypto@users.noreply.github.com>
This commit is contained in:
1 parent
494bab4b30
commit
2f76640aa8
9 files changed
+790
-138
No files matched your search
@@ -5,6 +5,7 @@ import io.github.hectorvent.floci.services.cloudtrail.CloudTrailService;
|
||||
import io.github.hectorvent.floci.services.iam.IamActionRegistry;
|
||||
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator;
|
||||
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.Decision;
|
||||
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.ResourceAccountRelationship;
|
||||
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.ResourcePolicyDecision;
|
||||
import io.github.hectorvent.floci.services.iam.IamService;
|
||||
import io.github.hectorvent.floci.services.iam.ResourceArnBuilder;
|
||||
@@ -254,7 +255,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
|
||||
*/
|
||||
public void authorizeAdditionalResource(String authorizationHeader, String action, String resource) {
|
||||
authorizeAdditionalResource(
|
||||
authorizationHeader, action, resource, ResourcePolicyDecision.NEUTRAL);
|
||||
authorizationHeader, action, resource, ResourcePolicyDecision.NEUTRAL, null);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -267,6 +268,20 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
|
||||
String action,
|
||||
String resource,
|
||||
ResourcePolicyDecision resourcePolicyDecision) {
|
||||
authorizeAdditionalResource(
|
||||
authorizationHeader, action, resource, resourcePolicyDecision, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Authorizes a secondary resource whose owning account is known. Resource-policy grants
|
||||
* crossing an account boundary require a matching identity-policy grant as well.
|
||||
*/
|
||||
public void authorizeAdditionalResource(
|
||||
String authorizationHeader,
|
||||
String action,
|
||||
String resource,
|
||||
ResourcePolicyDecision resourcePolicyDecision,
|
||||
String resourceOwnerAccountId) {
|
||||
if (!config.services().iam().enforcementEnabled()) {
|
||||
return;
|
||||
}
|
||||
@@ -310,8 +325,13 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
|
||||
conditionContext.put("aws:PrincipalArn", List.of(principalArn.get()));
|
||||
}
|
||||
|
||||
ResourceAccountRelationship accountRelationship = resourceOwnerAccountId == null
|
||||
|| accountId.equals(resourceOwnerAccountId)
|
||||
? ResourceAccountRelationship.SAME_ACCOUNT
|
||||
: ResourceAccountRelationship.CROSS_ACCOUNT;
|
||||
Decision decision = evaluator.evaluateResolvedResourcePolicy(
|
||||
caller, resourcePolicyDecision, action, resource, conditionContext);
|
||||
caller, resourcePolicyDecision, accountRelationship,
|
||||
action, resource, conditionContext);
|
||||
if (decision != Decision.DENY) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -42,10 +42,16 @@ public class IamPolicyEvaluator {
|
||||
|
||||
public enum ResourcePolicyDecision {
|
||||
ALLOW,
|
||||
ALLOW_DIRECT_IAM_USER,
|
||||
EXPLICIT_DENY,
|
||||
NEUTRAL
|
||||
}
|
||||
|
||||
public enum ResourceAccountRelationship {
|
||||
SAME_ACCOUNT,
|
||||
CROSS_ACCOUNT
|
||||
}
|
||||
|
||||
public enum SimulationDecision {
|
||||
ALLOWED("allowed"),
|
||||
EXPLICIT_DENY("explicitDeny"),
|
||||
@@ -99,7 +105,8 @@ public class IamPolicyEvaluator {
|
||||
boolean resourceAllow = anyExplicitAllow(resourceStmts, action, resource, ctx);
|
||||
return evaluateParsed(
|
||||
caller, identityStmts, sessionStmts, boundaryStmts,
|
||||
resourceExplicitDeny, resourceAllow, action, resource, ctx);
|
||||
resourceExplicitDeny, resourceAllow, false,
|
||||
ResourceAccountRelationship.SAME_ACCOUNT, action, resource, ctx);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -112,6 +119,28 @@ public class IamPolicyEvaluator {
|
||||
String action,
|
||||
String resource,
|
||||
Map<String, List<String>> conditionCtx) {
|
||||
return evaluateResolvedResourcePolicy(
|
||||
caller,
|
||||
resourcePolicyDecision,
|
||||
ResourceAccountRelationship.SAME_ACCOUNT,
|
||||
action,
|
||||
resource,
|
||||
conditionCtx);
|
||||
}
|
||||
|
||||
/**
|
||||
* Evaluates a principal-filtered resource policy with the caller/resource account relationship.
|
||||
* Cross-account access requires both identity and resource policy allows. A same-account resource
|
||||
* policy that directly names an IAM user ARN is not limited by an implicit permissions-boundary
|
||||
* deny, although every explicit deny still wins.
|
||||
*/
|
||||
public Decision evaluateResolvedResourcePolicy(
|
||||
CallerContext caller,
|
||||
ResourcePolicyDecision resourcePolicyDecision,
|
||||
ResourceAccountRelationship accountRelationship,
|
||||
String action,
|
||||
String resource,
|
||||
Map<String, List<String>> conditionCtx) {
|
||||
Map<String, List<String>> ctx = normalizeConditionContext(conditionCtx);
|
||||
List<PolicyStatement> identityStmts = parseAll(caller.identityPolicies());
|
||||
List<PolicyStatement> sessionStmts = caller.sessionPolicyDocument() == null
|
||||
@@ -123,7 +152,11 @@ public class IamPolicyEvaluator {
|
||||
return evaluateParsed(
|
||||
caller, identityStmts, sessionStmts, boundaryStmts,
|
||||
resolvedDecision == ResourcePolicyDecision.EXPLICIT_DENY,
|
||||
resolvedDecision == ResourcePolicyDecision.ALLOW,
|
||||
resolvedDecision == ResourcePolicyDecision.ALLOW
|
||||
|| resolvedDecision == ResourcePolicyDecision.ALLOW_DIRECT_IAM_USER,
|
||||
resolvedDecision == ResourcePolicyDecision.ALLOW_DIRECT_IAM_USER,
|
||||
accountRelationship == null
|
||||
? ResourceAccountRelationship.CROSS_ACCOUNT : accountRelationship,
|
||||
action, resource, ctx);
|
||||
}
|
||||
|
||||
@@ -134,6 +167,8 @@ public class IamPolicyEvaluator {
|
||||
List<PolicyStatement> boundaryStmts,
|
||||
boolean resourceExplicitDeny,
|
||||
boolean resourceAllow,
|
||||
boolean directIamUserResourceAllow,
|
||||
ResourceAccountRelationship accountRelationship,
|
||||
String action,
|
||||
String resource,
|
||||
Map<String, List<String>> ctx) {
|
||||
@@ -154,9 +189,14 @@ public class IamPolicyEvaluator {
|
||||
return Decision.DENY;
|
||||
}
|
||||
|
||||
// 2. Base grant: identity OR resource-based policy must allow
|
||||
// 2. Base grant: same-account access needs either policy family; cross-account access
|
||||
// needs both the caller's identity policy and the resource owner's policy.
|
||||
boolean identityAllow = anyExplicitAllow(identityStmts, action, resource, ctx);
|
||||
if (!identityAllow && !resourceAllow) {
|
||||
if (accountRelationship == ResourceAccountRelationship.CROSS_ACCOUNT) {
|
||||
if (!identityAllow || !resourceAllow) {
|
||||
return Decision.DENY;
|
||||
}
|
||||
} else if (!identityAllow && !resourceAllow) {
|
||||
return Decision.DENY;
|
||||
}
|
||||
|
||||
@@ -165,8 +205,13 @@ public class IamPolicyEvaluator {
|
||||
return Decision.DENY;
|
||||
}
|
||||
|
||||
// 4. Permission boundary (if present) must also allow (caps maximum permissions)
|
||||
if (boundaryStmts != null && !anyExplicitAllow(boundaryStmts, action, resource, ctx)) {
|
||||
// 4. A same-account resource policy that names an IAM user ARN grants directly to that
|
||||
// user. Its boundary's implicit deny does not cap the grant; explicit denies were
|
||||
// already handled above. Other grants remain limited by the boundary intersection.
|
||||
boolean directSameAccountUserGrant = directIamUserResourceAllow
|
||||
&& accountRelationship == ResourceAccountRelationship.SAME_ACCOUNT;
|
||||
if (!directSameAccountUserGrant && boundaryStmts != null
|
||||
&& !anyExplicitAllow(boundaryStmts, action, resource, ctx)) {
|
||||
return Decision.DENY;
|
||||
}
|
||||
|
||||
|
||||
@@ -12,7 +12,6 @@ import io.github.hectorvent.floci.core.common.XmlParser;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.common.RequestContext;
|
||||
import io.github.hectorvent.floci.services.cloudtrail.CloudTrailService;
|
||||
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.ResourcePolicyDecision;
|
||||
import io.github.hectorvent.floci.services.iam.IamService;
|
||||
import io.github.hectorvent.floci.services.sns.SnsQueryHandler;
|
||||
import io.github.hectorvent.floci.services.s3.model.Bucket;
|
||||
@@ -3801,12 +3800,12 @@ public class S3Controller {
|
||||
S3Service.RequestAuthorization authorization) {
|
||||
String action = source.versionId() == null ? "s3:GetObject" : "s3:GetObjectVersion";
|
||||
String resource = S3PublicAccessEvaluator.objectArn(source.bucket(), source.objectKey());
|
||||
ResourcePolicyDecision resourcePolicyDecision =
|
||||
S3Service.SignedPrincipalResourcePolicyEvaluation resourcePolicyEvaluation =
|
||||
s3Service.signedPrincipalResourcePolicyDecision(
|
||||
source.bucket(), action, resource, authorization);
|
||||
iamEnforcementFilter.authorizeAdditionalResource(
|
||||
httpHeaders.getHeaderString("Authorization"), action, resource,
|
||||
resourcePolicyDecision);
|
||||
resourcePolicyEvaluation.decision(), resourcePolicyEvaluation.resourceOwnerAccountId());
|
||||
s3Service.authorizeGetObject(
|
||||
source.bucket(), source.objectKey(), source.versionId(), authorization);
|
||||
}
|
||||
|
||||
@@ -20,6 +20,12 @@ final class S3PublicAccessEvaluator {
|
||||
NEUTRAL
|
||||
}
|
||||
|
||||
record PrincipalPolicyEvaluation(
|
||||
PublicAccessDecision decision,
|
||||
boolean directPrincipalAllow
|
||||
) {
|
||||
}
|
||||
|
||||
private S3PublicAccessEvaluator() {
|
||||
}
|
||||
|
||||
@@ -66,12 +72,25 @@ final class S3PublicAccessEvaluator {
|
||||
String action,
|
||||
String resourceArn,
|
||||
Map<String, String> context) {
|
||||
return principalPolicyEvaluation(
|
||||
objectMapper, policy, principalType, principalValue, action, resourceArn, context).decision();
|
||||
}
|
||||
|
||||
static PrincipalPolicyEvaluation principalPolicyEvaluation(
|
||||
ObjectMapper objectMapper,
|
||||
String policy,
|
||||
String principalType,
|
||||
String principalValue,
|
||||
String action,
|
||||
String resourceArn,
|
||||
Map<String, String> context) {
|
||||
if (policy == null || policy.isBlank()) {
|
||||
return PublicAccessDecision.NEUTRAL;
|
||||
return new PrincipalPolicyEvaluation(PublicAccessDecision.NEUTRAL, false);
|
||||
}
|
||||
try {
|
||||
JsonNode statements = objectMapper.readTree(policy).path("Statement");
|
||||
boolean allowed = false;
|
||||
boolean directPrincipalAllow = false;
|
||||
Iterable<JsonNode> iterable = statements.isArray() ? statements : List.of(statements);
|
||||
for (JsonNode statement : iterable) {
|
||||
String effect = statement.path("Effect").asText("");
|
||||
@@ -87,14 +106,18 @@ final class S3PublicAccessEvaluator {
|
||||
continue;
|
||||
}
|
||||
if ("Deny".equalsIgnoreCase(effect)) {
|
||||
return PublicAccessDecision.DENY;
|
||||
return new PrincipalPolicyEvaluation(PublicAccessDecision.DENY, false);
|
||||
}
|
||||
allowed = true;
|
||||
directPrincipalAllow |= principalDirectlyMatches(
|
||||
statement, principalType, principalValue);
|
||||
}
|
||||
return allowed ? PublicAccessDecision.ALLOW : PublicAccessDecision.NEUTRAL;
|
||||
PublicAccessDecision decision = allowed
|
||||
? PublicAccessDecision.ALLOW : PublicAccessDecision.NEUTRAL;
|
||||
return new PrincipalPolicyEvaluation(decision, directPrincipalAllow);
|
||||
} catch (JsonProcessingException e) {
|
||||
LOG.debugv("Failed to evaluate S3 bucket policy for principal access: {0}", e.getMessage());
|
||||
return PublicAccessDecision.NEUTRAL;
|
||||
return new PrincipalPolicyEvaluation(PublicAccessDecision.NEUTRAL, false);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -134,6 +157,83 @@ final class S3PublicAccessEvaluator {
|
||||
return false;
|
||||
}
|
||||
|
||||
private static boolean principalDirectlyMatches(
|
||||
JsonNode statement, String principalType, String principalValue) {
|
||||
if (!statement.hasNonNull("Principal")) {
|
||||
return false;
|
||||
}
|
||||
JsonNode principal = statement.path("Principal");
|
||||
return principalNodeDirectlyMatches(principal, principalType, principalValue)
|
||||
|| ("AWS".equalsIgnoreCase(principalType)
|
||||
&& hasPublicPrincipal(principal)
|
||||
&& conditionDirectlyMatchesPrincipalArn(
|
||||
statement.path("Condition"), principalValue));
|
||||
}
|
||||
|
||||
private static boolean conditionDirectlyMatchesPrincipalArn(
|
||||
JsonNode conditions, String principalValue) {
|
||||
if (conditions == null || !conditions.isObject()) {
|
||||
return false;
|
||||
}
|
||||
Iterator<Map.Entry<String, JsonNode>> operators = conditions.fields();
|
||||
while (operators.hasNext()) {
|
||||
Map.Entry<String, JsonNode> operator = operators.next();
|
||||
if (!("StringEquals".equalsIgnoreCase(operator.getKey())
|
||||
|| "ArnEquals".equalsIgnoreCase(operator.getKey()))
|
||||
|| !operator.getValue().isObject()) {
|
||||
continue;
|
||||
}
|
||||
Iterator<Map.Entry<String, JsonNode>> entries = operator.getValue().fields();
|
||||
while (entries.hasNext()) {
|
||||
Map.Entry<String, JsonNode> entry = entries.next();
|
||||
if ("aws:PrincipalArn".equalsIgnoreCase(entry.getKey())
|
||||
&& conditionValueMatches(entry.getValue(), principalValue, false)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static boolean principalNodeDirectlyMatches(
|
||||
JsonNode principal, String principalType, String principalValue) {
|
||||
if (principal == null || principal.isMissingNode() || principal.isNull()) {
|
||||
return false;
|
||||
}
|
||||
if (principal.isTextual() || principal.isArray()) {
|
||||
return principalValueDirectlyMatches(principal, principalValue);
|
||||
}
|
||||
if (!principal.isObject()) {
|
||||
return false;
|
||||
}
|
||||
Iterator<Map.Entry<String, JsonNode>> fields = principal.fields();
|
||||
while (fields.hasNext()) {
|
||||
Map.Entry<String, JsonNode> field = fields.next();
|
||||
if (field.getKey().equalsIgnoreCase(principalType)
|
||||
&& principalValueDirectlyMatches(field.getValue(), principalValue)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static boolean principalValueDirectlyMatches(JsonNode candidate, String principalValue) {
|
||||
if (candidate == null || candidate.isNull()) {
|
||||
return false;
|
||||
}
|
||||
if (candidate.isTextual()) {
|
||||
return candidate.asText().equals(principalValue);
|
||||
}
|
||||
if (candidate.isArray()) {
|
||||
for (JsonNode item : candidate) {
|
||||
if (principalValueDirectlyMatches(item, principalValue)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static boolean principalNodeMatches(
|
||||
JsonNode principal, String principalType, String principalValue) {
|
||||
if (principal == null || principal.isMissingNode() || principal.isNull()) {
|
||||
|
||||
@@ -56,7 +56,15 @@ import io.github.hectorvent.floci.core.resource.SupportedResourceType;
|
||||
|
||||
@ApplicationScoped
|
||||
public class S3Service implements Resettable, ResourceProvider {
|
||||
private String ownerId() { return regionResolver != null ? regionResolver.getAccountId() : "000000000000"; }
|
||||
private String ownerId() {
|
||||
if (regionResolver != null) {
|
||||
return regionResolver.getAccountId();
|
||||
}
|
||||
if (bucketStore instanceof AccountAwareStorageBackend<?> aware) {
|
||||
return aware.accountId();
|
||||
}
|
||||
return "000000000000";
|
||||
}
|
||||
private static final String DEFAULT_OWNER_DISPLAY_NAME = "floci";
|
||||
private static final String AUTHENTICATED_USERS_GROUP_URI = "http://acs.amazonaws.com/groups/global/AuthenticatedUsers";
|
||||
private static final String LOG_DELIVERY_GROUP_URI = "http://acs.amazonaws.com/groups/s3/LogDelivery";
|
||||
@@ -78,6 +86,12 @@ public class S3Service implements Resettable, ResourceProvider {
|
||||
}
|
||||
}
|
||||
|
||||
record SignedPrincipalResourcePolicyEvaluation(
|
||||
ResourcePolicyDecision decision,
|
||||
String resourceOwnerAccountId
|
||||
) {
|
||||
}
|
||||
|
||||
private final StorageBackend<String, Bucket> bucketStore;
|
||||
private final StorageBackend<String, S3Object> objectStore;
|
||||
private final StorageBackend<String, ObjectAnnotation> annotationStore;
|
||||
@@ -490,16 +504,18 @@ public class S3Service implements Resettable, ResourceProvider {
|
||||
private S3Object storeObject(String bucketName, String key, byte[] data,
|
||||
String contentType, Map<String, String> metadata,
|
||||
S3Checksum checksum, List<Part> parts, PutObjectOptions options, String eTag) {
|
||||
Bucket bucket = resolveBucket(bucketName)
|
||||
AccountAwareStorageBackend.OwnedEntry<Bucket> ownedBucket = resolveBucketEntry(bucketName)
|
||||
.orElseThrow(() -> new AwsException("NoSuchBucket",
|
||||
"The specified bucket does not exist.", 404));
|
||||
Bucket bucket = ownedBucket.value();
|
||||
synchronized (bucket) {
|
||||
return storeObjectInternal(bucket, bucketName, key, data, contentType, metadata, checksum, parts, options,
|
||||
eTag);
|
||||
return storeObjectInternal(ownedBucket.account(), bucket, bucketName, key, data,
|
||||
contentType, metadata, checksum, parts, options, eTag);
|
||||
}
|
||||
}
|
||||
|
||||
private S3Object storeObjectInternal(Bucket bucket, String bucketName, String key, byte[] data,
|
||||
private S3Object storeObjectInternal(String bucketOwnerAccount, Bucket bucket,
|
||||
String bucketName, String key, byte[] data,
|
||||
String contentType, Map<String, String> metadata,
|
||||
S3Checksum checksum, List<Part> parts, PutObjectOptions options,
|
||||
String eTag) {
|
||||
@@ -532,7 +548,8 @@ public class S3Service implements Resettable, ResourceProvider {
|
||||
object.setSseCustomerAlgorithm(sseCustomerKey.algorithm());
|
||||
object.setSseCustomerKeyMd5(sseCustomerKey.keyMd5());
|
||||
}
|
||||
object.setAcl(resolveObjectAclXml(effectiveOptions.getAcl(), effectiveOptions.getGrantRead(),
|
||||
object.setAcl(resolveObjectAclXml(bucketOwnerAccount,
|
||||
effectiveOptions.getAcl(), effectiveOptions.getGrantRead(),
|
||||
effectiveOptions.getGrantWrite(), effectiveOptions.getGrantFullControl(),
|
||||
effectiveOptions.getGrantReadAcp(), effectiveOptions.getGrantWriteAcp()));
|
||||
if (effectiveOptions.getTagging() != null && !effectiveOptions.getTagging().isEmpty()) {
|
||||
@@ -553,13 +570,14 @@ public class S3Service implements Resettable, ResourceProvider {
|
||||
// object key and would be left unreachable by the new version. Cleanup is deferred
|
||||
// until the replacement body is on disk, so a failed write does not drop them.
|
||||
boolean[] dropPreVersioningAnnotations = {false};
|
||||
objectStore.get(latestKey).ifPresent(prev -> {
|
||||
resolveObjectForAccount(bucketOwnerAccount, latestKey).ifPresent(prev -> {
|
||||
if (prev.isLatest() && !prev.isDeleteMarker() && bucket.isObjectLockEnabled()) {
|
||||
checkLockProtection(prev, false);
|
||||
}
|
||||
if (prev.getVersionId() != null) {
|
||||
prev.setLatest(false);
|
||||
objectStore.put(versionedKey(bucketName, key, prev.getVersionId()), prev);
|
||||
putObjectForAccount(bucketOwnerAccount,
|
||||
versionedKey(bucketName, key, prev.getVersionId()), prev);
|
||||
} else {
|
||||
dropPreVersioningAnnotations[0] = true;
|
||||
}
|
||||
@@ -579,8 +597,8 @@ public class S3Service implements Resettable, ResourceProvider {
|
||||
// versioned write fails, the canonical file - which unlocked GETs already associate
|
||||
// with the still-unpublished previous generation - is never touched, so a concurrent
|
||||
// GET can't observe corrupted "latest" bytes paired with the old metadata.
|
||||
writeVersionedFile(bucketName, key, versionId, data);
|
||||
writeFile(bucketName, key, data);
|
||||
writeVersionedFile(bucketOwnerAccount, bucketName, key, versionId, data);
|
||||
writeFile(bucketOwnerAccount, bucketName, key, data);
|
||||
// Deferred pre-versioning annotation cleanup: only after the replacement body is on
|
||||
// disk, so a failed write keeps the old body and its annotations together.
|
||||
if (dropPreVersioningAnnotations[0]) {
|
||||
@@ -591,11 +609,12 @@ public class S3Service implements Resettable, ResourceProvider {
|
||||
// it (copyObject reads getData() without any lock) and race this null-out otherwise.
|
||||
object.setData(null);
|
||||
// Store versioned copy and update latest pointer
|
||||
objectStore.put(versionedKey(bucketName, key, versionId), object);
|
||||
objectStore.put(latestKey, object);
|
||||
putObjectForAccount(bucketOwnerAccount, versionedKey(bucketName, key, versionId), object);
|
||||
putObjectForAccount(bucketOwnerAccount, latestKey, object);
|
||||
LOG.debugv("Put versioned object: {0}/{1} v={2} ({3} bytes)", bucketName, key, versionId, data.length);
|
||||
} else {
|
||||
S3Object prev = objectStore.get(objectKey(bucketName, key)).orElse(null);
|
||||
S3Object prev = resolveObjectForAccount(
|
||||
bucketOwnerAccount, objectKey(bucketName, key)).orElse(null);
|
||||
// Check lock protection on the existing object before overwriting
|
||||
if (bucket.isObjectLockEnabled() && prev != null && !prev.isDeleteMarker()) {
|
||||
checkLockProtection(prev, false);
|
||||
@@ -614,7 +633,7 @@ public class S3Service implements Resettable, ResourceProvider {
|
||||
|
||||
// Write the body before publishing metadata - see the comment in the versioned
|
||||
// branch above; the same ordering requirement applies here.
|
||||
writeFile(bucketName, key, data);
|
||||
writeFile(bucketOwnerAccount, bucketName, key, data);
|
||||
// An overwrite replaces the object's annotations (AWS drops them on overwrite).
|
||||
// The cleanup runs only after the body write succeeds, so a failed PUT keeps the
|
||||
// old body together with its annotations; and before the new metadata is published,
|
||||
@@ -623,7 +642,7 @@ public class S3Service implements Resettable, ResourceProvider {
|
||||
// Release the cached payload before publishing - see the comment in the versioned
|
||||
// branch above; the same race applies here.
|
||||
object.setData(null);
|
||||
objectStore.put(objectKey(bucketName, key), object);
|
||||
putObjectForAccount(bucketOwnerAccount, objectKey(bucketName, key), object);
|
||||
LOG.debugv("Put object: {0}/{1} ({2} bytes)", bucketName, key, data.length);
|
||||
}
|
||||
return object;
|
||||
@@ -945,43 +964,46 @@ public class S3Service implements Resettable, ResourceProvider {
|
||||
RequestAuthorization authorization) {
|
||||
if (signedPrincipalResourcePolicyDecision(
|
||||
bucketName, action, resourceArn, authorization)
|
||||
== ResourcePolicyDecision.EXPLICIT_DENY) {
|
||||
.decision() == ResourcePolicyDecision.EXPLICIT_DENY) {
|
||||
throw new AwsException("AccessDenied", "Access Denied", 403);
|
||||
}
|
||||
}
|
||||
|
||||
ResourcePolicyDecision signedPrincipalResourcePolicyDecision(
|
||||
SignedPrincipalResourcePolicyEvaluation signedPrincipalResourcePolicyDecision(
|
||||
String bucketName,
|
||||
String action,
|
||||
String resourceArn,
|
||||
RequestAuthorization authorization) {
|
||||
if (authorization == null || !authorization.signed()
|
||||
|| LEGACY_ACCESS_KEY_ID.equals(authorization.accessKeyId()) || iamService == null) {
|
||||
return ResourcePolicyDecision.NEUTRAL;
|
||||
return new SignedPrincipalResourcePolicyEvaluation(ResourcePolicyDecision.NEUTRAL, null);
|
||||
}
|
||||
|
||||
Optional<String> principalArn = iamService.resolveCallerArn(authorization.accessKeyId());
|
||||
if (principalArn.isEmpty()) {
|
||||
return ResourcePolicyDecision.NEUTRAL;
|
||||
return new SignedPrincipalResourcePolicyEvaluation(ResourcePolicyDecision.NEUTRAL, null);
|
||||
}
|
||||
|
||||
Bucket bucket = bucketStore.get(bucketName)
|
||||
AccountAwareStorageBackend.OwnedEntry<Bucket> ownedBucket = resolveBucketEntry(bucketName)
|
||||
.orElseThrow(() -> new AwsException(
|
||||
"NoSuchBucket", "The specified bucket does not exist.", 404));
|
||||
S3PublicAccessEvaluator.PublicAccessDecision policyDecision =
|
||||
S3PublicAccessEvaluator.principalPolicyDecision(
|
||||
S3PublicAccessEvaluator.PrincipalPolicyEvaluation policyEvaluation =
|
||||
S3PublicAccessEvaluator.principalPolicyEvaluation(
|
||||
objectMapper,
|
||||
bucket.getPolicy(),
|
||||
ownedBucket.value().getPolicy(),
|
||||
"AWS",
|
||||
principalArn.get(),
|
||||
action,
|
||||
resourceArn,
|
||||
Map.of("aws:PrincipalArn", principalArn.get()));
|
||||
return switch (policyDecision) {
|
||||
case ALLOW -> ResourcePolicyDecision.ALLOW;
|
||||
ResourcePolicyDecision decision = switch (policyEvaluation.decision()) {
|
||||
case ALLOW -> policyEvaluation.directPrincipalAllow() && principalArn.get().contains(":user/")
|
||||
? ResourcePolicyDecision.ALLOW_DIRECT_IAM_USER
|
||||
: ResourcePolicyDecision.ALLOW;
|
||||
case DENY -> ResourcePolicyDecision.EXPLICIT_DENY;
|
||||
case NEUTRAL -> ResourcePolicyDecision.NEUTRAL;
|
||||
};
|
||||
return new SignedPrincipalResourcePolicyEvaluation(decision, ownedBucket.account());
|
||||
}
|
||||
|
||||
private boolean readableObjectExists(String bucketName, String key) {
|
||||
@@ -1103,8 +1125,12 @@ public class S3Service implements Resettable, ResourceProvider {
|
||||
if (versionId != null) {
|
||||
// An explicit version's file is immutable once written (see storeObjectInternal) and
|
||||
// never reused by a later PUT, so this pairing can never race a concurrent overwrite.
|
||||
String bucketOwnerAccount = resolveBucketEntry(bucketName)
|
||||
.orElseThrow(() -> new AwsException("NoSuchBucket",
|
||||
"The specified bucket does not exist.", 404))
|
||||
.account();
|
||||
S3Object obj = getObjectMetadata(bucketName, key, versionId);
|
||||
obj.setData(readVersionedFile(bucketName, key, versionId));
|
||||
obj.setData(readVersionedFile(bucketOwnerAccount, bucketName, key, versionId));
|
||||
return obj;
|
||||
}
|
||||
return getLatestObject(bucketName, key);
|
||||
@@ -1130,18 +1156,20 @@ public class S3Service implements Resettable, ResourceProvider {
|
||||
* token is only ever observed when untouched, and untouched means nothing to race against.
|
||||
*/
|
||||
private S3Object getLatestObject(String bucketName, String key) {
|
||||
Bucket bucket = resolveBucket(bucketName)
|
||||
AccountAwareStorageBackend.OwnedEntry<Bucket> ownedBucket = resolveBucketEntry(bucketName)
|
||||
.orElseThrow(() -> new AwsException("NoSuchBucket",
|
||||
"The specified bucket does not exist.", 404));
|
||||
Bucket bucket = ownedBucket.value();
|
||||
String bucketOwnerAccount = ownedBucket.account();
|
||||
String storeKey = objectKey(bucketName, key);
|
||||
// A genuine race only ever needs a retry or two; this bound exists so a resolution bug
|
||||
// (the recheck disagreeing with getObjectMetadata about where this key lives) fails loudly
|
||||
// with a clear error instead of spinning forever re-reading the file and exhausting the heap.
|
||||
for (int attempt = 0; attempt < 10_000; attempt++) {
|
||||
S3Object obj = getObjectMetadata(bucketName, key, null);
|
||||
byte[] data = readFile(bucketName, key);
|
||||
byte[] data = readFile(bucketOwnerAccount, bucketName, key);
|
||||
synchronized (bucket) {
|
||||
S3Object current = resolveObject(storeKey).orElse(null);
|
||||
S3Object current = resolveObjectForAccount(bucketOwnerAccount, storeKey).orElse(null);
|
||||
if (current != null && !current.isDeleteMarker()
|
||||
&& Objects.equals(current.getDataGeneration(), obj.getDataGeneration())) {
|
||||
obj.setData(data);
|
||||
@@ -1182,10 +1210,14 @@ public class S3Service implements Resettable, ResourceProvider {
|
||||
|
||||
public InputStream openObjectStream(String bucketName, String key, String versionId) {
|
||||
getObjectMetadata(bucketName, key, versionId);
|
||||
String bucketOwnerAccount = resolveBucketEntry(bucketName)
|
||||
.orElseThrow(() -> new AwsException("NoSuchBucket",
|
||||
"The specified bucket does not exist.", 404))
|
||||
.account();
|
||||
if (inMemory) {
|
||||
byte[] data = versionId != null
|
||||
? memoryDataStore.get(physicalVersionedKey(bucketName, key, versionId))
|
||||
: memoryDataStore.get(physicalKey(bucketName, key));
|
||||
? memoryDataStore.get(physicalVersionedKey(bucketOwnerAccount, bucketName, key, versionId))
|
||||
: memoryDataStore.get(physicalKey(bucketOwnerAccount, bucketName, key));
|
||||
if (data == null) {
|
||||
throw new IllegalStateException("S3 object data is missing for " + bucketName + "/" + key);
|
||||
}
|
||||
@@ -1193,8 +1225,8 @@ public class S3Service implements Resettable, ResourceProvider {
|
||||
}
|
||||
try {
|
||||
Path path = versionId != null
|
||||
? resolveVersionedPathForRead(bucketName, key, versionId)
|
||||
: resolveObjectPathForRead(bucketName, key);
|
||||
? resolveVersionedPathForRead(bucketOwnerAccount, bucketName, key, versionId)
|
||||
: resolveObjectPathForRead(bucketOwnerAccount, bucketName, key);
|
||||
return Files.newInputStream(path);
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException("Failed to open S3 object stream", e);
|
||||
@@ -1234,17 +1266,24 @@ public class S3Service implements Resettable, ResourceProvider {
|
||||
}
|
||||
|
||||
private S3Object getStoredObject(String bucketName, String key, String versionId) {
|
||||
ensureBucketExists(bucketName);
|
||||
return getStoredObjectEntry(bucketName, key, versionId).value();
|
||||
}
|
||||
|
||||
private AccountAwareStorageBackend.OwnedEntry<S3Object> getStoredObjectEntry(
|
||||
String bucketName, String key, String versionId) {
|
||||
AccountAwareStorageBackend.OwnedEntry<Bucket> ownedBucket = resolveBucketEntry(bucketName)
|
||||
.orElseThrow(() -> new AwsException("NoSuchBucket",
|
||||
"The specified bucket does not exist.", 404));
|
||||
|
||||
String storeKey = versionId != null ? versionedKey(bucketName, key, versionId) : objectKey(bucketName, key);
|
||||
S3Object object = resolveObject(storeKey)
|
||||
S3Object object = resolveObjectForAccount(ownedBucket.account(), storeKey)
|
||||
.orElseThrow(() -> versionId != null
|
||||
? new AwsException("NoSuchVersion", "The specified version does not exist.", 404)
|
||||
: new AwsException("NoSuchKey", "The specified key does not exist.", 404));
|
||||
if (object.isDeleteMarker()) {
|
||||
throw new AwsException("NoSuchKey", "The specified key does not exist.", 404);
|
||||
}
|
||||
return object;
|
||||
return new AccountAwareStorageBackend.OwnedEntry<>(ownedBucket.account(), object);
|
||||
}
|
||||
|
||||
// AWS lists part-level checksums only for composite objects; a full-object multipart object
|
||||
@@ -1816,30 +1855,25 @@ public class S3Service implements Resettable, ResourceProvider {
|
||||
// --- Object Tagging ---
|
||||
|
||||
public void putObjectTagging(String bucketName, String key, Map<String, String> tags) {
|
||||
ensureBucketExists(bucketName);
|
||||
S3Object obj = objectStore.get(objectKey(bucketName, key))
|
||||
.orElseThrow(() -> new AwsException("NoSuchKey",
|
||||
"The specified key does not exist.", 404));
|
||||
AccountAwareStorageBackend.OwnedEntry<S3Object> ownedObject =
|
||||
getStoredObjectEntry(bucketName, key, null);
|
||||
S3Object obj = ownedObject.value();
|
||||
obj.setTags(tags != null ? tags : new java.util.HashMap<>());
|
||||
objectStore.put(objectKey(bucketName, key), obj);
|
||||
putObjectForAccount(ownedObject.account(), objectKey(bucketName, key), obj);
|
||||
LOG.debugv("Put tags on object: {0}/{1}", bucketName, key);
|
||||
}
|
||||
|
||||
public Map<String, String> getObjectTagging(String bucketName, String key) {
|
||||
ensureBucketExists(bucketName);
|
||||
S3Object obj = objectStore.get(objectKey(bucketName, key))
|
||||
.orElseThrow(() -> new AwsException("NoSuchKey",
|
||||
"The specified key does not exist.", 404));
|
||||
S3Object obj = getStoredObject(bucketName, key, null);
|
||||
return obj.getTags() != null ? obj.getTags() : Map.of();
|
||||
}
|
||||
|
||||
public void deleteObjectTagging(String bucketName, String key) {
|
||||
ensureBucketExists(bucketName);
|
||||
S3Object obj = objectStore.get(objectKey(bucketName, key))
|
||||
.orElseThrow(() -> new AwsException("NoSuchKey",
|
||||
"The specified key does not exist.", 404));
|
||||
AccountAwareStorageBackend.OwnedEntry<S3Object> ownedObject =
|
||||
getStoredObjectEntry(bucketName, key, null);
|
||||
S3Object obj = ownedObject.value();
|
||||
obj.setTags(new java.util.HashMap<>());
|
||||
objectStore.put(objectKey(bucketName, key), obj);
|
||||
putObjectForAccount(ownedObject.account(), objectKey(bucketName, key), obj);
|
||||
LOG.debugv("Deleted tags from object: {0}/{1}", bucketName, key);
|
||||
}
|
||||
|
||||
@@ -2833,13 +2867,12 @@ public class S3Service implements Resettable, ResourceProvider {
|
||||
|
||||
public void putObjectRetention(String bucketName, String key, String versionId,
|
||||
String mode, Instant retainUntil, boolean bypassGovernance) {
|
||||
ensureBucketExists(bucketName);
|
||||
AccountAwareStorageBackend.OwnedEntry<S3Object> ownedObject =
|
||||
getStoredObjectEntry(bucketName, key, versionId);
|
||||
String storeKey = versionId != null
|
||||
? versionedKey(bucketName, key, versionId)
|
||||
: objectKey(bucketName, key);
|
||||
S3Object obj = objectStore.get(storeKey)
|
||||
.orElseThrow(() -> new AwsException("NoSuchKey",
|
||||
"The specified key does not exist.", 404));
|
||||
S3Object obj = ownedObject.value();
|
||||
|
||||
boolean activeComplianceRetention = "COMPLIANCE".equals(obj.getObjectLockMode())
|
||||
&& obj.getRetainUntilDate() != null
|
||||
@@ -2873,41 +2906,28 @@ public class S3Service implements Resettable, ResourceProvider {
|
||||
|
||||
obj.setObjectLockMode(mode);
|
||||
obj.setRetainUntilDate(retainUntil);
|
||||
objectStore.put(storeKey, obj);
|
||||
putObjectForAccount(ownedObject.account(), storeKey, obj);
|
||||
LOG.debugv("Set retention on {0}/{1}: mode={2}, until={3}", bucketName, key, mode, retainUntil);
|
||||
}
|
||||
|
||||
public S3Object getObjectRetention(String bucketName, String key, String versionId) {
|
||||
ensureBucketExists(bucketName);
|
||||
String storeKey = versionId != null
|
||||
? versionedKey(bucketName, key, versionId)
|
||||
: objectKey(bucketName, key);
|
||||
return objectStore.get(storeKey)
|
||||
.orElseThrow(() -> new AwsException("NoSuchKey",
|
||||
"The specified key does not exist.", 404));
|
||||
return getStoredObject(bucketName, key, versionId);
|
||||
}
|
||||
|
||||
public void putObjectLegalHold(String bucketName, String key, String versionId, String status) {
|
||||
ensureBucketExists(bucketName);
|
||||
AccountAwareStorageBackend.OwnedEntry<S3Object> ownedObject =
|
||||
getStoredObjectEntry(bucketName, key, versionId);
|
||||
String storeKey = versionId != null
|
||||
? versionedKey(bucketName, key, versionId)
|
||||
: objectKey(bucketName, key);
|
||||
S3Object obj = objectStore.get(storeKey)
|
||||
.orElseThrow(() -> new AwsException("NoSuchKey",
|
||||
"The specified key does not exist.", 404));
|
||||
S3Object obj = ownedObject.value();
|
||||
obj.setLegalHoldStatus(status);
|
||||
objectStore.put(storeKey, obj);
|
||||
putObjectForAccount(ownedObject.account(), storeKey, obj);
|
||||
LOG.debugv("Set legal hold on {0}/{1}: {2}", bucketName, key, status);
|
||||
}
|
||||
|
||||
public S3Object getObjectLegalHold(String bucketName, String key, String versionId) {
|
||||
ensureBucketExists(bucketName);
|
||||
String storeKey = versionId != null
|
||||
? versionedKey(bucketName, key, versionId)
|
||||
: objectKey(bucketName, key);
|
||||
return objectStore.get(storeKey)
|
||||
.orElseThrow(() -> new AwsException("NoSuchKey",
|
||||
"The specified key does not exist.", 404));
|
||||
return getStoredObject(bucketName, key, versionId);
|
||||
}
|
||||
|
||||
// --- Multipart Upload Operations ---
|
||||
@@ -3438,24 +3458,32 @@ public class S3Service implements Resettable, ResourceProvider {
|
||||
String grantWrite, String grantFullControl, String grantReadAcp, String grantWriteAcp) {
|
||||
Bucket bucket = bucketStore.get(bucketName)
|
||||
.orElseThrow(() -> new AwsException("NoSuchBucket", "The specified bucket does not exist.", 404));
|
||||
String resolvedAcl = resolveObjectAclXml(cannedAcl, grantRead, grantWrite, grantFullControl, grantReadAcp, grantWriteAcp);
|
||||
String resolvedAcl = resolveObjectAclXml(
|
||||
cannedAcl, grantRead, grantWrite, grantFullControl, grantReadAcp, grantWriteAcp);
|
||||
bucket.setAcl(resolvedAcl != null ? resolvedAcl : (bodyAcl.isBlank() ? null : bodyAcl));
|
||||
bucketStore.put(bucketName, bucket);
|
||||
}
|
||||
|
||||
public String getObjectAcl(String bucketName, String key, String versionId) {
|
||||
S3Object obj = getObject(bucketName, key, versionId);
|
||||
return obj.getAcl() != null ? obj.getAcl() : defaultAclXml(ownerId(), DEFAULT_OWNER_DISPLAY_NAME);
|
||||
AccountAwareStorageBackend.OwnedEntry<S3Object> ownedObject =
|
||||
getStoredObjectEntry(bucketName, key, versionId);
|
||||
S3Object obj = ownedObject.value();
|
||||
return obj.getAcl() != null
|
||||
? obj.getAcl()
|
||||
: defaultAclXml(ownedObject.account(), DEFAULT_OWNER_DISPLAY_NAME);
|
||||
}
|
||||
|
||||
public void putObjectAcl(String bucketName, String key, String versionId, String bodyAcl, String cannedAcl,
|
||||
String grantRead, String grantWrite, String grantFullControl,
|
||||
String grantReadAcp, String grantWriteAcp) {
|
||||
S3Object obj = getObject(bucketName, key, versionId);
|
||||
String resolvedAcl = resolveObjectAclXml(cannedAcl, grantRead, grantWrite, grantFullControl, grantReadAcp, grantWriteAcp);
|
||||
AccountAwareStorageBackend.OwnedEntry<S3Object> ownedObject =
|
||||
getStoredObjectEntry(bucketName, key, versionId);
|
||||
S3Object obj = ownedObject.value();
|
||||
String resolvedAcl = resolveObjectAclXml(ownedObject.account(), cannedAcl, grantRead,
|
||||
grantWrite, grantFullControl, grantReadAcp, grantWriteAcp);
|
||||
obj.setAcl(resolvedAcl != null ? resolvedAcl : (bodyAcl.isBlank() ? null : bodyAcl));
|
||||
String storeKey = (versionId != null) ? versionedKey(bucketName, key, versionId) : objectKey(bucketName, key);
|
||||
objectStore.put(storeKey, obj);
|
||||
putObjectForAccount(ownedObject.account(), storeKey, obj);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -3791,21 +3819,29 @@ public class S3Service implements Resettable, ResourceProvider {
|
||||
*/
|
||||
String resolveObjectAclXml(String cannedAcl, String grantRead, String grantWrite,
|
||||
String grantFullControl, String grantReadAcp, String grantWriteAcp) {
|
||||
return resolveObjectAclXml(ownerId(), cannedAcl, grantRead, grantWrite,
|
||||
grantFullControl, grantReadAcp, grantWriteAcp);
|
||||
}
|
||||
|
||||
private String resolveObjectAclXml(String ownerAccount, String cannedAcl,
|
||||
String grantRead, String grantWrite,
|
||||
String grantFullControl, String grantReadAcp,
|
||||
String grantWriteAcp) {
|
||||
if (cannedAcl != null && !cannedAcl.isBlank()) {
|
||||
return cannedObjectAclXml(cannedAcl);
|
||||
return cannedObjectAclXml(ownerAccount, cannedAcl);
|
||||
}
|
||||
if (isBlank(grantRead) && isBlank(grantWrite) && isBlank(grantFullControl)
|
||||
&& isBlank(grantReadAcp) && isBlank(grantWriteAcp)) {
|
||||
return null;
|
||||
}
|
||||
List<String> grants = new ArrayList<>();
|
||||
grants.add(ownerFullControlGrant());
|
||||
grants.add(ownerFullControlGrant(ownerAccount));
|
||||
appendGrantHeader(grants, grantRead, "READ");
|
||||
appendGrantHeader(grants, grantWrite, "WRITE");
|
||||
appendGrantHeader(grants, grantFullControl, "FULL_CONTROL");
|
||||
appendGrantHeader(grants, grantReadAcp, "READ_ACP");
|
||||
appendGrantHeader(grants, grantWriteAcp, "WRITE_ACP");
|
||||
return objectAclXml(grants.toArray(new String[0]));
|
||||
return objectAclXml(ownerAccount, grants.toArray(new String[0]));
|
||||
}
|
||||
|
||||
private static boolean isBlank(String value) {
|
||||
@@ -3844,30 +3880,34 @@ public class S3Service implements Resettable, ResourceProvider {
|
||||
}
|
||||
|
||||
String cannedObjectAclXml(String cannedAcl) {
|
||||
return cannedObjectAclXml(ownerId(), cannedAcl);
|
||||
}
|
||||
|
||||
private String cannedObjectAclXml(String ownerAccount, String cannedAcl) {
|
||||
if (cannedAcl == null || cannedAcl.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
return switch (cannedAcl) {
|
||||
case "private", "bucket-owner-read", "bucket-owner-full-control" ->
|
||||
defaultAclXml(ownerId(), DEFAULT_OWNER_DISPLAY_NAME);
|
||||
defaultAclXml(ownerAccount, DEFAULT_OWNER_DISPLAY_NAME);
|
||||
// Floci currently runs as a single synthetic account, so there is no distinct EC2 bundle-reader
|
||||
// principal to represent in GetObjectAcl responses yet.
|
||||
case "aws-exec-read" -> defaultAclXml(ownerId(), DEFAULT_OWNER_DISPLAY_NAME);
|
||||
case "public-read" -> objectAclXml(
|
||||
ownerFullControlGrant(),
|
||||
case "aws-exec-read" -> defaultAclXml(ownerAccount, DEFAULT_OWNER_DISPLAY_NAME);
|
||||
case "public-read" -> objectAclXml(ownerAccount,
|
||||
ownerFullControlGrant(ownerAccount),
|
||||
groupGrant(S3AclPublicAccessEvaluator.ALL_USERS_GROUP_URI, "READ"));
|
||||
case "public-read-write" -> objectAclXml(
|
||||
ownerFullControlGrant(),
|
||||
case "public-read-write" -> objectAclXml(ownerAccount,
|
||||
ownerFullControlGrant(ownerAccount),
|
||||
groupGrant(S3AclPublicAccessEvaluator.ALL_USERS_GROUP_URI, "READ"),
|
||||
groupGrant(S3AclPublicAccessEvaluator.ALL_USERS_GROUP_URI, "WRITE"));
|
||||
case "authenticated-read" -> objectAclXml(
|
||||
ownerFullControlGrant(),
|
||||
case "authenticated-read" -> objectAclXml(ownerAccount,
|
||||
ownerFullControlGrant(ownerAccount),
|
||||
groupGrant(AUTHENTICATED_USERS_GROUP_URI, "READ"));
|
||||
// Standard canned ACL used by S3 server-access-logging (and Terraform's
|
||||
// aws_s3_bucket_acl / access-logging modules) to grant the S3 log-delivery service
|
||||
// group permission to write log objects into this bucket and read their own ACL.
|
||||
case "log-delivery-write" -> objectAclXml(
|
||||
ownerFullControlGrant(),
|
||||
case "log-delivery-write" -> objectAclXml(ownerAccount,
|
||||
ownerFullControlGrant(ownerAccount),
|
||||
groupGrant(LOG_DELIVERY_GROUP_URI, "WRITE"),
|
||||
groupGrant(LOG_DELIVERY_GROUP_URI, "READ_ACP"));
|
||||
default -> throw new AwsException("InvalidArgument",
|
||||
@@ -3988,8 +4028,8 @@ public class S3Service implements Resettable, ResourceProvider {
|
||||
static final SseCustomerHeaders EMPTY = new SseCustomerHeaders(null, null, null);
|
||||
}
|
||||
|
||||
private String ownerFullControlGrant() {
|
||||
return canonicalUserGrant(ownerId(), DEFAULT_OWNER_DISPLAY_NAME, "FULL_CONTROL");
|
||||
private static String ownerFullControlGrant(String ownerAccount) {
|
||||
return canonicalUserGrant(ownerAccount, DEFAULT_OWNER_DISPLAY_NAME, "FULL_CONTROL");
|
||||
}
|
||||
|
||||
private static String canonicalUserGrant(String id, String displayName, String permission) {
|
||||
@@ -4015,11 +4055,11 @@ public class S3Service implements Resettable, ResourceProvider {
|
||||
.build();
|
||||
}
|
||||
|
||||
private String objectAclXml(String... grants) {
|
||||
private static String objectAclXml(String ownerAccount, String... grants) {
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.start("AccessControlPolicy")
|
||||
.start("Owner")
|
||||
.elem("ID", ownerId())
|
||||
.elem("ID", ownerAccount)
|
||||
.elem("DisplayName", DEFAULT_OWNER_DISPLAY_NAME)
|
||||
.end("Owner")
|
||||
.start("AccessControlList");
|
||||
@@ -4392,12 +4432,17 @@ public class S3Service implements Resettable, ResourceProvider {
|
||||
* checks (CreateBucket, delete) intentionally do not use this — they remain account-scoped.
|
||||
*/
|
||||
private Optional<Bucket> resolveBucket(String bucketName) {
|
||||
return resolveBucketEntry(bucketName).map(AccountAwareStorageBackend.OwnedEntry::value);
|
||||
}
|
||||
|
||||
private Optional<AccountAwareStorageBackend.OwnedEntry<Bucket>> resolveBucketEntry(String bucketName) {
|
||||
if (globalBucketNamespace && bucketStore instanceof AccountAwareStorageBackend<?> aware) {
|
||||
@SuppressWarnings("unchecked")
|
||||
AccountAwareStorageBackend<Bucket> typed = (AccountAwareStorageBackend<Bucket>) aware;
|
||||
return typed.findAnyAccount(bucketName);
|
||||
return typed.findAnyAccountEntry(bucketName);
|
||||
}
|
||||
return bucketStore.get(bucketName);
|
||||
return bucketStore.get(bucketName)
|
||||
.map(bucket -> new AccountAwareStorageBackend.OwnedEntry<>(ownerId(), bucket));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -4445,6 +4490,25 @@ public class S3Service implements Resettable, ResourceProvider {
|
||||
return objectStore.get(storeKey);
|
||||
}
|
||||
|
||||
private Optional<S3Object> resolveObjectForAccount(String accountId, String storeKey) {
|
||||
if (objectStore instanceof AccountAwareStorageBackend<?> aware) {
|
||||
@SuppressWarnings("unchecked")
|
||||
AccountAwareStorageBackend<S3Object> typed = (AccountAwareStorageBackend<S3Object>) aware;
|
||||
return typed.getForAccount(accountId, storeKey);
|
||||
}
|
||||
return objectStore.get(storeKey);
|
||||
}
|
||||
|
||||
private void putObjectForAccount(String accountId, String storeKey, S3Object object) {
|
||||
if (objectStore instanceof AccountAwareStorageBackend<?> aware) {
|
||||
@SuppressWarnings("unchecked")
|
||||
AccountAwareStorageBackend<S3Object> typed = (AccountAwareStorageBackend<S3Object>) aware;
|
||||
typed.putForAccount(accountId, storeKey, object);
|
||||
return;
|
||||
}
|
||||
objectStore.put(storeKey, object);
|
||||
}
|
||||
|
||||
private String objectKey(String bucketName, String key) {
|
||||
return bucketName + "/" + key;
|
||||
}
|
||||
@@ -4463,15 +4527,27 @@ public class S3Service implements Resettable, ResourceProvider {
|
||||
// Unlike bucketStore/objectStore, object bytes get no automatic account prefixing — two
|
||||
// accounts can own a bucket named "orders" and would collide here without this scoping.
|
||||
private String physicalKey(String bucketName, String key) {
|
||||
return ownerId() + "/" + objectKey(bucketName, key);
|
||||
return physicalKey(ownerId(), bucketName, key);
|
||||
}
|
||||
|
||||
private String physicalKey(String accountId, String bucketName, String key) {
|
||||
return accountId + "/" + objectKey(bucketName, key);
|
||||
}
|
||||
|
||||
private String physicalVersionedKey(String bucketName, String key, String versionId) {
|
||||
return ownerId() + "/" + versionedKey(bucketName, key, versionId);
|
||||
return physicalVersionedKey(ownerId(), bucketName, key, versionId);
|
||||
}
|
||||
|
||||
private String physicalVersionedKey(String accountId, String bucketName, String key, String versionId) {
|
||||
return accountId + "/" + versionedKey(bucketName, key, versionId);
|
||||
}
|
||||
|
||||
private Path resolveObjectPath(String bucketName, String key) {
|
||||
Path bucketDir = dataRoot.resolve(ACCOUNT_STORAGE_ROOT).resolve(ownerId()).resolve(bucketName).normalize();
|
||||
return resolveObjectPath(ownerId(), bucketName, key);
|
||||
}
|
||||
|
||||
private Path resolveObjectPath(String accountId, String bucketName, String key) {
|
||||
Path bucketDir = dataRoot.resolve(ACCOUNT_STORAGE_ROOT).resolve(accountId).resolve(bucketName).normalize();
|
||||
|
||||
String safeKey = key;
|
||||
while (safeKey.startsWith("/")) {
|
||||
@@ -4501,13 +4577,21 @@ public class S3Service implements Resettable, ResourceProvider {
|
||||
* its own copy.
|
||||
*/
|
||||
private Path resolveObjectPathForRead(String bucketName, String key) {
|
||||
Path resolved = resolveObjectPath(bucketName, key);
|
||||
return resolveObjectPathForRead(ownerId(), bucketName, key);
|
||||
}
|
||||
|
||||
private Path resolveObjectPathForRead(String accountId, String bucketName, String key) {
|
||||
Path resolved = resolveObjectPath(accountId, bucketName, key);
|
||||
copyLegacyFileIfPresent(legacyObjectPath(bucketName, key), resolved);
|
||||
return resolved;
|
||||
}
|
||||
|
||||
private Path resolveVersionedPath(String bucketName, String key, String versionId) {
|
||||
Path baseDir = dataRoot.resolve(ACCOUNT_STORAGE_ROOT).resolve(ownerId()).resolve(".versions").resolve(bucketName).normalize();
|
||||
return resolveVersionedPath(ownerId(), bucketName, key, versionId);
|
||||
}
|
||||
|
||||
private Path resolveVersionedPath(String accountId, String bucketName, String key, String versionId) {
|
||||
Path baseDir = dataRoot.resolve(ACCOUNT_STORAGE_ROOT).resolve(accountId).resolve(".versions").resolve(bucketName).normalize();
|
||||
|
||||
String safeKey = key;
|
||||
while (safeKey.startsWith("/")) {
|
||||
@@ -4532,7 +4616,11 @@ public class S3Service implements Resettable, ResourceProvider {
|
||||
|
||||
/** Read-only counterpart of {@link #resolveObjectPathForRead} for versioned objects. */
|
||||
private Path resolveVersionedPathForRead(String bucketName, String key, String versionId) {
|
||||
Path resolved = resolveVersionedPath(bucketName, key, versionId);
|
||||
return resolveVersionedPathForRead(ownerId(), bucketName, key, versionId);
|
||||
}
|
||||
|
||||
private Path resolveVersionedPathForRead(String accountId, String bucketName, String key, String versionId) {
|
||||
Path resolved = resolveVersionedPath(accountId, bucketName, key, versionId);
|
||||
copyLegacyFileIfPresent(legacyVersionedPath(bucketName, key, versionId), resolved);
|
||||
return resolved;
|
||||
}
|
||||
@@ -4578,11 +4666,16 @@ public class S3Service implements Resettable, ResourceProvider {
|
||||
}
|
||||
|
||||
private void writeVersionedFile(String bucketName, String key, String versionId, byte[] data) {
|
||||
writeVersionedFile(ownerId(), bucketName, key, versionId, data);
|
||||
}
|
||||
|
||||
private void writeVersionedFile(
|
||||
String accountId, String bucketName, String key, String versionId, byte[] data) {
|
||||
if (inMemory) {
|
||||
memoryDataStore.put(physicalVersionedKey(bucketName, key, versionId), data);
|
||||
memoryDataStore.put(physicalVersionedKey(accountId, bucketName, key, versionId), data);
|
||||
return;
|
||||
}
|
||||
Path filePath = resolveVersionedPath(bucketName, key, versionId);
|
||||
Path filePath = resolveVersionedPath(accountId, bucketName, key, versionId);
|
||||
ReentrantLock lock = diskFileLock(filePath);
|
||||
lock.lock();
|
||||
try {
|
||||
@@ -4595,22 +4688,30 @@ public class S3Service implements Resettable, ResourceProvider {
|
||||
}
|
||||
|
||||
private byte[] readVersionedFile(String bucketName, String key, String versionId) {
|
||||
return readVersionedFile(ownerId(), bucketName, key, versionId);
|
||||
}
|
||||
|
||||
private byte[] readVersionedFile(String accountId, String bucketName, String key, String versionId) {
|
||||
if (inMemory) {
|
||||
return memoryDataStore.get(physicalVersionedKey(bucketName, key, versionId));
|
||||
return memoryDataStore.get(physicalVersionedKey(accountId, bucketName, key, versionId));
|
||||
}
|
||||
try {
|
||||
return Files.readAllBytes(resolveVersionedPathForRead(bucketName, key, versionId));
|
||||
return Files.readAllBytes(resolveVersionedPathForRead(accountId, bucketName, key, versionId));
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException("Failed to read versioned S3 object file", e);
|
||||
}
|
||||
}
|
||||
|
||||
private void writeFile(String bucketName, String key, byte[] data) {
|
||||
writeFile(ownerId(), bucketName, key, data);
|
||||
}
|
||||
|
||||
private void writeFile(String accountId, String bucketName, String key, byte[] data) {
|
||||
if (inMemory) {
|
||||
memoryDataStore.put(physicalKey(bucketName, key), data);
|
||||
memoryDataStore.put(physicalKey(accountId, bucketName, key), data);
|
||||
return;
|
||||
}
|
||||
Path filePath = resolveObjectPath(bucketName, key);
|
||||
Path filePath = resolveObjectPath(accountId, bucketName, key);
|
||||
ReentrantLock lock = diskFileLock(filePath);
|
||||
lock.lock();
|
||||
try {
|
||||
@@ -4651,11 +4752,15 @@ public class S3Service implements Resettable, ResourceProvider {
|
||||
}
|
||||
|
||||
private byte[] readFile(String bucketName, String key) {
|
||||
return readFile(ownerId(), bucketName, key);
|
||||
}
|
||||
|
||||
private byte[] readFile(String accountId, String bucketName, String key) {
|
||||
if (inMemory) {
|
||||
return memoryDataStore.get(physicalKey(bucketName, key));
|
||||
return memoryDataStore.get(physicalKey(accountId, bucketName, key));
|
||||
}
|
||||
try {
|
||||
return Files.readAllBytes(resolveObjectPathForRead(bucketName, key));
|
||||
return Files.readAllBytes(resolveObjectPathForRead(accountId, bucketName, key));
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException("Failed to read S3 object file", e);
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.iam;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.Decision;
|
||||
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.ResourceAccountRelationship;
|
||||
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.ResourcePolicyDecision;
|
||||
import io.github.hectorvent.floci.services.iam.model.CallerContext;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -83,6 +84,99 @@ class IamPolicyEvaluatorTest {
|
||||
null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void crossAccountIdentityAllowRequiresResourceAllow() {
|
||||
CallerContext caller = CallerContext.of(List.of(ALLOW_ALL));
|
||||
|
||||
assertEquals(Decision.DENY, evaluator.evaluateResolvedResourcePolicy(
|
||||
caller,
|
||||
ResourcePolicyDecision.NEUTRAL,
|
||||
ResourceAccountRelationship.CROSS_ACCOUNT,
|
||||
"s3:GetObject",
|
||||
"arn:aws:s3:::bucket/key",
|
||||
null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void crossAccountResourceAllowRequiresIdentityAllow() {
|
||||
CallerContext caller = CallerContext.of(List.of());
|
||||
|
||||
assertEquals(Decision.DENY, evaluator.evaluateResolvedResourcePolicy(
|
||||
caller,
|
||||
ResourcePolicyDecision.ALLOW,
|
||||
ResourceAccountRelationship.CROSS_ACCOUNT,
|
||||
"s3:GetObject",
|
||||
"arn:aws:s3:::bucket/key",
|
||||
null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void crossAccountAccessAllowsWhenIdentityAndResourcePoliciesAllow() {
|
||||
CallerContext caller = CallerContext.of(List.of(ALLOW_ALL));
|
||||
|
||||
assertEquals(Decision.ALLOW, evaluator.evaluateResolvedResourcePolicy(
|
||||
caller,
|
||||
ResourcePolicyDecision.ALLOW,
|
||||
ResourceAccountRelationship.CROSS_ACCOUNT,
|
||||
"s3:GetObject",
|
||||
"arn:aws:s3:::bucket/key",
|
||||
null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void sameAccountDirectUserGrantBypassesBoundaryImplicitDeny() {
|
||||
CallerContext caller = new CallerContext(
|
||||
List.of(),
|
||||
null,
|
||||
"""
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"dynamodb:*","Resource":"*"}
|
||||
]}""");
|
||||
|
||||
assertEquals(Decision.ALLOW, evaluator.evaluateResolvedResourcePolicy(
|
||||
caller,
|
||||
ResourcePolicyDecision.ALLOW_DIRECT_IAM_USER,
|
||||
ResourceAccountRelationship.SAME_ACCOUNT,
|
||||
"s3:GetObject",
|
||||
"arn:aws:s3:::bucket/key",
|
||||
null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void sameAccountWildcardGrantRemainsLimitedByBoundary() {
|
||||
CallerContext caller = new CallerContext(
|
||||
List.of(),
|
||||
null,
|
||||
"""
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"dynamodb:*","Resource":"*"}
|
||||
]}""");
|
||||
|
||||
assertEquals(Decision.DENY, evaluator.evaluateResolvedResourcePolicy(
|
||||
caller,
|
||||
ResourcePolicyDecision.ALLOW,
|
||||
ResourceAccountRelationship.SAME_ACCOUNT,
|
||||
"s3:GetObject",
|
||||
"arn:aws:s3:::bucket/key",
|
||||
null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void sameAccountDirectUserGrantDoesNotBypassBoundaryExplicitDeny() {
|
||||
CallerContext caller = new CallerContext(
|
||||
List.of(),
|
||||
null,
|
||||
DENY_S3);
|
||||
|
||||
assertEquals(Decision.DENY, evaluator.evaluateResolvedResourcePolicy(
|
||||
caller,
|
||||
ResourcePolicyDecision.ALLOW_DIRECT_IAM_USER,
|
||||
ResourceAccountRelationship.SAME_ACCOUNT,
|
||||
"s3:GetObject",
|
||||
"arn:aws:s3:::bucket/key",
|
||||
null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void scpDenyWinsOverIdentityAllow() {
|
||||
CallerContext caller = adminWithScps(List.of(List.of(DENY_S3)));
|
||||
|
||||
+97
-10
@@ -38,6 +38,8 @@ class S3CopyObjectSourcePermissionIntegrationTest {
|
||||
}
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String ACCOUNT_A = "111122223333";
|
||||
private static final String ACCOUNT_B = "222233334444";
|
||||
|
||||
@Test
|
||||
void copyObjectIsDeniedWhenCallerCannotReadTheSource() {
|
||||
@@ -121,6 +123,53 @@ class S3CopyObjectSourcePermissionIntegrationTest {
|
||||
.statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
void crossAccountCopyRequiresIdentityAndSourceBucketPolicyAllows() {
|
||||
String suffix = UUID.randomUUID().toString().substring(0, 8);
|
||||
String sourceBucket = "copy-cross-source-" + suffix;
|
||||
String destBucket = "copy-cross-dest-" + suffix;
|
||||
String userName = "copy-cross-user-" + suffix;
|
||||
|
||||
UserCredentials accountAAdmin = createAccountAdmin("copy-source-admin-" + suffix, ACCOUNT_A);
|
||||
UserCredentials accountBAdmin = createAccountAdmin("copy-dest-admin-" + suffix, ACCOUNT_B);
|
||||
createBucketAsRoot(sourceBucket, accountAAdmin.signer());
|
||||
putObjectAsRoot(sourceBucket, "shared.txt", "cross-account source", accountAAdmin.signer());
|
||||
createBucketAsRoot(destBucket, accountBAdmin.signer());
|
||||
|
||||
UserCredentials caller = createUser(userName, ACCOUNT_B);
|
||||
putUserPolicy(userName, "CopyAccess", """
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"s3:PutObject","Resource":"arn:aws:s3:::%s/*"}
|
||||
]}""".formatted(destBucket), ACCOUNT_B);
|
||||
putBucketPolicyAsRoot(
|
||||
sourceBucket,
|
||||
allowUserReadPolicy(sourceBucket, ACCOUNT_B, userName, "s3:GetObject"),
|
||||
accountAAdmin.signer());
|
||||
|
||||
given()
|
||||
.filter(caller.signer())
|
||||
.header("x-amz-copy-source", "/" + sourceBucket + "/shared.txt")
|
||||
.when()
|
||||
.put("/" + destBucket + "/denied.txt")
|
||||
.then()
|
||||
.statusCode(403)
|
||||
.body(containsString("<Code>AccessDenied</Code>"));
|
||||
|
||||
putUserPolicy(userName, "CopyAccess", """
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"s3:GetObject","Resource":"arn:aws:s3:::%1$s/*"},
|
||||
{"Effect":"Allow","Action":"s3:PutObject","Resource":"arn:aws:s3:::%2$s/*"}
|
||||
]}""".formatted(sourceBucket, destBucket), ACCOUNT_B);
|
||||
|
||||
given()
|
||||
.filter(caller.signer())
|
||||
.header("x-amz-copy-source", "/" + sourceBucket + "/shared.txt")
|
||||
.when()
|
||||
.put("/" + destBucket + "/copied.txt")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
void versionedCopyUsesGetObjectVersionPermission() {
|
||||
String suffix = UUID.randomUUID().toString().substring(0, 8);
|
||||
@@ -291,8 +340,12 @@ class S3CopyObjectSourcePermissionIntegrationTest {
|
||||
}
|
||||
|
||||
private static void createBucketAsRoot(String bucket) {
|
||||
createBucketAsRoot(bucket, ROOT_SIGNER);
|
||||
}
|
||||
|
||||
private static void createBucketAsRoot(String bucket, S3RequestSigner signer) {
|
||||
given()
|
||||
.filter(ROOT_SIGNER)
|
||||
.filter(signer)
|
||||
.when()
|
||||
.put("/" + bucket)
|
||||
.then()
|
||||
@@ -300,8 +353,13 @@ class S3CopyObjectSourcePermissionIntegrationTest {
|
||||
}
|
||||
|
||||
private static void putObjectAsRoot(String bucket, String key, String body) {
|
||||
putObjectAsRoot(bucket, key, body, ROOT_SIGNER);
|
||||
}
|
||||
|
||||
private static void putObjectAsRoot(
|
||||
String bucket, String key, String body, S3RequestSigner signer) {
|
||||
given()
|
||||
.filter(ROOT_SIGNER)
|
||||
.filter(signer)
|
||||
.contentType("text/plain")
|
||||
.body(body)
|
||||
.when()
|
||||
@@ -347,8 +405,13 @@ class S3CopyObjectSourcePermissionIntegrationTest {
|
||||
}
|
||||
|
||||
private static void putBucketPolicyAsRoot(String bucket, String policy) {
|
||||
putBucketPolicyAsRoot(bucket, policy, ROOT_SIGNER);
|
||||
}
|
||||
|
||||
private static void putBucketPolicyAsRoot(
|
||||
String bucket, String policy, S3RequestSigner signer) {
|
||||
given()
|
||||
.filter(ROOT_SIGNER)
|
||||
.filter(signer)
|
||||
.contentType("application/json")
|
||||
.body(policy)
|
||||
.when()
|
||||
@@ -365,11 +428,16 @@ class S3CopyObjectSourcePermissionIntegrationTest {
|
||||
}
|
||||
|
||||
private static String allowUserReadPolicy(String bucket, String userName, String action) {
|
||||
return allowUserReadPolicy(bucket, "000000000000", userName, action);
|
||||
}
|
||||
|
||||
private static String allowUserReadPolicy(
|
||||
String bucket, String accountId, String userName, String action) {
|
||||
return """
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Principal":{"AWS":"arn:aws:iam::000000000000:user/%1$s"},
|
||||
"Action":"%2$s","Resource":"arn:aws:s3:::%3$s/*"}
|
||||
]}""".formatted(userName, action, bucket);
|
||||
{"Effect":"Allow","Principal":{"AWS":"arn:aws:iam::%1$s:user/%2$s"},
|
||||
"Action":"%3$s","Resource":"arn:aws:s3:::%4$s/*"}
|
||||
]}""".formatted(accountId, userName, action, bucket);
|
||||
}
|
||||
|
||||
private static String allowPublicPutObjectPolicy(String bucket) {
|
||||
@@ -394,10 +462,14 @@ class S3CopyObjectSourcePermissionIntegrationTest {
|
||||
}
|
||||
|
||||
private static UserCredentials createUser(String userName) {
|
||||
return createUser(userName, "test");
|
||||
}
|
||||
|
||||
private static UserCredentials createUser(String userName, String accountId) {
|
||||
given()
|
||||
.formParam("Action", "CreateUser")
|
||||
.formParam("UserName", userName)
|
||||
.header("Authorization", auth("test", "iam"))
|
||||
.header("Authorization", auth(accountId, "iam"))
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
@@ -406,7 +478,7 @@ class S3CopyObjectSourcePermissionIntegrationTest {
|
||||
io.restassured.path.xml.XmlPath key = given()
|
||||
.formParam("Action", "CreateAccessKey")
|
||||
.formParam("UserName", userName)
|
||||
.header("Authorization", auth("test", "iam"))
|
||||
.header("Authorization", auth(accountId, "iam"))
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
@@ -418,13 +490,27 @@ class S3CopyObjectSourcePermissionIntegrationTest {
|
||||
key.getString("CreateAccessKeyResponse.CreateAccessKeyResult.AccessKey.SecretAccessKey"));
|
||||
}
|
||||
|
||||
private static UserCredentials createAccountAdmin(String userName, String accountId) {
|
||||
UserCredentials credentials = createUser(userName, accountId);
|
||||
putUserPolicy(userName, "S3Admin", """
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"s3:*","Resource":"*"}
|
||||
]}""", accountId);
|
||||
return credentials;
|
||||
}
|
||||
|
||||
private static void putUserPolicy(String userName, String policyName, String policyDocument) {
|
||||
putUserPolicy(userName, policyName, policyDocument, "test");
|
||||
}
|
||||
|
||||
private static void putUserPolicy(
|
||||
String userName, String policyName, String policyDocument, String accountId) {
|
||||
given()
|
||||
.formParam("Action", "PutUserPolicy")
|
||||
.formParam("UserName", userName)
|
||||
.formParam("PolicyName", policyName)
|
||||
.formParam("PolicyDocument", policyDocument)
|
||||
.header("Authorization", auth("test", "iam"))
|
||||
.header("Authorization", auth(accountId, "iam"))
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
@@ -441,7 +527,8 @@ class S3CopyObjectSourcePermissionIntegrationTest {
|
||||
public Map<String, String> getConfigOverrides() {
|
||||
return Map.of(
|
||||
"floci.services.iam.enforcement-enabled", "true",
|
||||
"floci.services.s3.enforce-auth", "true");
|
||||
"floci.services.s3.enforce-auth", "true",
|
||||
"floci.services.s3.global-bucket-namespace", "true");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import jakarta.enterprise.inject.Instance;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.time.Instant;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
@@ -17,6 +18,7 @@ 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.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.mock;
|
||||
@@ -85,6 +87,12 @@ class S3GlobalBucketNamespaceTest {
|
||||
assertDoesNotThrow(() ->
|
||||
globalNs.putObject("shared-assets-bucket", "member-asset.json", memberAsset,
|
||||
"application/json", Map.of()));
|
||||
assertTrue(objects.getForAccount(
|
||||
ACCOUNT_A, "shared-assets-bucket/member-asset.json").isPresent(),
|
||||
"a cross-account write must persist in the bucket owner's partition");
|
||||
assertTrue(objects.getForAccount(
|
||||
ACCOUNT_B, "shared-assets-bucket/member-asset.json").isEmpty(),
|
||||
"a cross-account write must not create a shadow object in the caller's partition");
|
||||
assertArrayEquals(memberAsset,
|
||||
globalNs.getObject("shared-assets-bucket", "member-asset.json").getData());
|
||||
|
||||
@@ -204,4 +212,67 @@ class S3GlobalBucketNamespaceTest {
|
||||
() -> globalNs.getBucketPolicy("central-logs-bucket"));
|
||||
assertEquals("NoSuchBucketPolicy", notFound.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void objectMetadataOperationsResolveAndPersistCrossAccount() {
|
||||
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-object-metadata-test"), true, true);
|
||||
|
||||
caller.set(ACCOUNT_A);
|
||||
globalNs.createBucket("shared-metadata-bucket", "us-east-1");
|
||||
globalNs.putBucketVersioning("shared-metadata-bucket", "Enabled");
|
||||
S3Object created = globalNs.putObject(
|
||||
"shared-metadata-bucket", "object.txt", "payload".getBytes(UTF_8),
|
||||
"text/plain", Map.of());
|
||||
String versionId = created.getVersionId();
|
||||
|
||||
caller.set(ACCOUNT_B);
|
||||
globalNs.putObjectTagging(
|
||||
"shared-metadata-bucket", "object.txt", Map.of("environment", "shared"));
|
||||
assertEquals(Map.of("environment", "shared"),
|
||||
globalNs.getObjectTagging("shared-metadata-bucket", "object.txt"));
|
||||
|
||||
Instant retainUntil = Instant.parse("2035-01-01T00:00:00Z");
|
||||
globalNs.putObjectRetention(
|
||||
"shared-metadata-bucket", "object.txt", versionId,
|
||||
"GOVERNANCE", retainUntil, true);
|
||||
assertEquals(retainUntil, globalNs.getObjectRetention(
|
||||
"shared-metadata-bucket", "object.txt", versionId).getRetainUntilDate());
|
||||
|
||||
globalNs.putObjectLegalHold("shared-metadata-bucket", "object.txt", null, "ON");
|
||||
assertEquals("ON", globalNs.getObjectLegalHold(
|
||||
"shared-metadata-bucket", "object.txt", null).getLegalHoldStatus());
|
||||
|
||||
String defaultAcl = globalNs.getObjectAcl(
|
||||
"shared-metadata-bucket", "object.txt", versionId);
|
||||
assertTrue(defaultAcl.contains(ACCOUNT_A));
|
||||
assertFalse(defaultAcl.contains(ACCOUNT_B));
|
||||
globalNs.putObjectAcl(
|
||||
"shared-metadata-bucket", "object.txt", versionId,
|
||||
"", "public-read", null, null, null, null, null);
|
||||
String storedAcl = globalNs.getObjectAcl(
|
||||
"shared-metadata-bucket", "object.txt", versionId);
|
||||
assertTrue(storedAcl.contains(ACCOUNT_A));
|
||||
assertFalse(storedAcl.contains(ACCOUNT_B));
|
||||
|
||||
globalNs.deleteObjectTagging("shared-metadata-bucket", "object.txt");
|
||||
assertTrue(globalNs.getObjectTagging("shared-metadata-bucket", "object.txt").isEmpty());
|
||||
|
||||
String currentKey = "shared-metadata-bucket/object.txt";
|
||||
String versionKey = currentKey + "#v#" + versionId;
|
||||
S3Object ownerVersion = objects.getForAccount(ACCOUNT_A, versionKey)
|
||||
.orElseThrow(() -> new AssertionError("version vanished from owner partition"));
|
||||
assertEquals(retainUntil, ownerVersion.getRetainUntilDate());
|
||||
assertEquals(storedAcl, ownerVersion.getAcl());
|
||||
assertTrue(objects.getForAccount(ACCOUNT_A, currentKey).isPresent());
|
||||
assertTrue(objects.getForAccount(ACCOUNT_B, currentKey).isEmpty(),
|
||||
"cross-account metadata writes must not create a caller shadow object");
|
||||
assertTrue(objects.getForAccount(ACCOUNT_B, versionKey).isEmpty(),
|
||||
"cross-account version metadata writes must stay in the owner partition");
|
||||
}
|
||||
}
|
||||
+131
@@ -1,8 +1,11 @@
|
||||
package io.github.hectorvent.floci.services.s3;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator;
|
||||
import io.github.hectorvent.floci.services.iam.model.CallerContext;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static io.github.hectorvent.floci.services.s3.S3PublicAccessEvaluator.PublicAccessDecision.ALLOW;
|
||||
@@ -142,6 +145,134 @@ class S3PublicAccessEvaluatorTest {
|
||||
"s3:GetObject", OBJECT_ARN, Map.of()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void exactAwsPrincipalIsReportedAsADirectGrant() {
|
||||
String userArn = "arn:aws:iam::123456789012:user/alice";
|
||||
String policy = """
|
||||
{"Version":"2012-10-17","Statement":{
|
||||
"Effect":"Allow",
|
||||
"Principal":{"AWS":"%s"},
|
||||
"Action":"s3:GetObject",
|
||||
"Resource":"arn:aws:s3:::public-bucket/*"
|
||||
}}""".formatted(userArn);
|
||||
|
||||
S3PublicAccessEvaluator.PrincipalPolicyEvaluation evaluation =
|
||||
S3PublicAccessEvaluator.principalPolicyEvaluation(
|
||||
OBJECT_MAPPER, policy, "AWS", userArn,
|
||||
"s3:GetObject", OBJECT_ARN, Map.of());
|
||||
|
||||
assertEquals(ALLOW, evaluation.decision());
|
||||
assertTrue(evaluation.directPrincipalAllow());
|
||||
}
|
||||
|
||||
@Test
|
||||
void exactPrincipalArnConditionIsReportedAsADirectGrant() {
|
||||
String userArn = "arn:aws:iam::123456789012:user/alice";
|
||||
String policy = """
|
||||
{"Version":"2012-10-17","Statement":{
|
||||
"Effect":"Allow",
|
||||
"Principal":"*",
|
||||
"Action":"s3:GetObject",
|
||||
"Resource":"arn:aws:s3:::public-bucket/*",
|
||||
"Condition":{"ArnEquals":{"aws:PrincipalArn":"%s"}}
|
||||
}}""".formatted(userArn);
|
||||
|
||||
S3PublicAccessEvaluator.PrincipalPolicyEvaluation evaluation =
|
||||
S3PublicAccessEvaluator.principalPolicyEvaluation(
|
||||
OBJECT_MAPPER, policy, "AWS", userArn,
|
||||
"s3:GetObject", OBJECT_ARN, Map.of("aws:PrincipalArn", userArn));
|
||||
|
||||
assertEquals(ALLOW, evaluation.decision());
|
||||
assertTrue(evaluation.directPrincipalAllow());
|
||||
}
|
||||
|
||||
@Test
|
||||
void exactPrincipalArnConditionBypassesBoundaryImplicitDeny() {
|
||||
String userArn = "arn:aws:iam::123456789012:user/alice";
|
||||
String policy = """
|
||||
{"Version":"2012-10-17","Statement":{
|
||||
"Effect":"Allow",
|
||||
"Principal":"*",
|
||||
"Action":"s3:GetObject",
|
||||
"Resource":"arn:aws:s3:::public-bucket/*",
|
||||
"Condition":{"ArnEquals":{"aws:PrincipalArn":"%s"}}
|
||||
}}""".formatted(userArn);
|
||||
S3PublicAccessEvaluator.PrincipalPolicyEvaluation evaluation =
|
||||
S3PublicAccessEvaluator.principalPolicyEvaluation(
|
||||
OBJECT_MAPPER, policy, "AWS", userArn,
|
||||
"s3:GetObject", OBJECT_ARN, Map.of("aws:PrincipalArn", userArn));
|
||||
IamPolicyEvaluator.ResourcePolicyDecision resourceDecision =
|
||||
evaluation.directPrincipalAllow()
|
||||
? IamPolicyEvaluator.ResourcePolicyDecision.ALLOW_DIRECT_IAM_USER
|
||||
: IamPolicyEvaluator.ResourcePolicyDecision.ALLOW;
|
||||
CallerContext caller = new CallerContext(
|
||||
List.of(), null,
|
||||
"""
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"dynamodb:*","Resource":"*"}
|
||||
]}""");
|
||||
|
||||
assertEquals(IamPolicyEvaluator.Decision.ALLOW,
|
||||
new IamPolicyEvaluator(OBJECT_MAPPER).evaluateResolvedResourcePolicy(
|
||||
caller,
|
||||
resourceDecision,
|
||||
IamPolicyEvaluator.ResourceAccountRelationship.SAME_ACCOUNT,
|
||||
"s3:GetObject",
|
||||
OBJECT_ARN,
|
||||
Map.of("aws:PrincipalArn", List.of(userArn))));
|
||||
}
|
||||
|
||||
@Test
|
||||
void wildcardPrincipalArnConditionIsNotReportedAsADirectGrant() {
|
||||
String userArn = "arn:aws:iam::123456789012:user/alice";
|
||||
String policy = """
|
||||
{"Version":"2012-10-17","Statement":{
|
||||
"Effect":"Allow",
|
||||
"Principal":{"AWS":"*"},
|
||||
"Action":"s3:GetObject",
|
||||
"Resource":"arn:aws:s3:::public-bucket/*",
|
||||
"Condition":{"ArnLike":{"aws:PrincipalArn":"arn:aws:iam::123456789012:user/*"}}
|
||||
}}""";
|
||||
|
||||
S3PublicAccessEvaluator.PrincipalPolicyEvaluation evaluation =
|
||||
S3PublicAccessEvaluator.principalPolicyEvaluation(
|
||||
OBJECT_MAPPER, policy, "AWS", userArn,
|
||||
"s3:GetObject", OBJECT_ARN, Map.of("aws:PrincipalArn", userArn));
|
||||
|
||||
assertEquals(ALLOW, evaluation.decision());
|
||||
assertFalse(evaluation.directPrincipalAllow());
|
||||
}
|
||||
|
||||
@Test
|
||||
void matchingDenyOverridesExactPrincipalArnCondition() {
|
||||
String userArn = "arn:aws:iam::123456789012:user/alice";
|
||||
String policy = """
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{
|
||||
"Effect":"Allow",
|
||||
"Principal":"*",
|
||||
"Action":"s3:GetObject",
|
||||
"Resource":"arn:aws:s3:::public-bucket/*",
|
||||
"Condition":{"StringEquals":{"aws:PrincipalArn":"%s"}}
|
||||
},
|
||||
{
|
||||
"Effect":"Deny",
|
||||
"Principal":"*",
|
||||
"Action":"s3:GetObject",
|
||||
"Resource":"arn:aws:s3:::public-bucket/*",
|
||||
"Condition":{"ArnEquals":{"aws:PrincipalArn":"%s"}}
|
||||
}
|
||||
]}""".formatted(userArn, userArn);
|
||||
|
||||
S3PublicAccessEvaluator.PrincipalPolicyEvaluation evaluation =
|
||||
S3PublicAccessEvaluator.principalPolicyEvaluation(
|
||||
OBJECT_MAPPER, policy, "AWS", userArn,
|
||||
"s3:GetObject", OBJECT_ARN, Map.of("aws:PrincipalArn", userArn));
|
||||
|
||||
assertEquals(DENY, evaluation.decision());
|
||||
assertFalse(evaluation.directPrincipalAllow());
|
||||
}
|
||||
|
||||
@Test
|
||||
void principalConditionalDenyOnlyAppliesWhenConditionMatches() {
|
||||
String policy = """
|
||||
|
||||
Reference in new issue
Block a user