Release ObjectStore 0.1.0
This commit is contained in:
1 parent
0cf5c11202
commit
35bd1d5703
34 files changed
+1273
-87
No files matched your search
@@ -6,6 +6,8 @@ POSTGRES_PASSWORD=[PG_Pass]
|
||||
S3_BUCKET=objects
|
||||
S3_CREDENTIALS_FILE=
|
||||
S3_KEY_SCOPES_FILE=
|
||||
S3_SESSION_CREDENTIALS_FILE=
|
||||
S3_IDENTITY_POLICIES_DIR=
|
||||
METRICS_BEARER_TOKEN=
|
||||
CLUSTER_HOST_PORT=9001
|
||||
MAX_OBJECT_BYTES=134217728
|
||||
@@ -16,6 +18,7 @@ OBJECTSTORE_RESPONSE_TIMEOUT_SECONDS=0
|
||||
CORS_ALLOWED_ORIGINS=
|
||||
HTTP_BACKLOG=64
|
||||
S3_VIRTUAL_HOST_SUFFIX=
|
||||
S3_PUBLIC_ENDPOINT=
|
||||
# For compose.cluster.encrypted.yaml only; provision and mount LUKS before setting these.
|
||||
ENCRYPTED_STORAGE_ROOT=
|
||||
ENCRYPTED_VOLUME_ID=
|
||||
@@ -6,6 +6,8 @@ S3_BUCKET=objects
|
||||
S3_REGION=us-east-1
|
||||
S3_CREDENTIALS_FILE=
|
||||
S3_KEY_SCOPES_FILE=
|
||||
S3_SESSION_CREDENTIALS_FILE=
|
||||
S3_IDENTITY_POLICIES_DIR=
|
||||
METRICS_BEARER_TOKEN=
|
||||
HOST_PORT=9000
|
||||
MAX_OBJECT_BYTES=134217728
|
||||
@@ -19,6 +21,7 @@ PUBLIC_TRUSTED_PROXY_IPS=
|
||||
MAX_IN_FLIGHT_REQUESTS=16
|
||||
HTTP_BACKLOG=64
|
||||
S3_VIRTUAL_HOST_SUFFIX=
|
||||
S3_PUBLIC_ENDPOINT=
|
||||
CORS_ALLOWED_ORIGINS=
|
||||
OBJECTSTORE_REQUEST_TIMEOUT_SECONDS=0
|
||||
OBJECTSTORE_RESPONSE_TIMEOUT_SECONDS=0
|
||||
|
||||
+14
-4
@@ -23,11 +23,19 @@ This does not cover Docker logs, swap, other temporary files, external backups,
|
||||
|
||||
`S3_ACCESS_KEY` and `S3_SECRET_KEY` define the owner. For additional identities, put one `ACCESSKEY:secret` pair per line in a private file and mount it read-only at `/run/secrets/s3-credentials` on `objectstore` (or `gateway` in cluster mode). Set `S3_CREDENTIALS_FILE` to that path. Keys need 16–128 alphanumeric characters; secrets need at least 32 characters. Changes load on restart. Additional identities have no access until granted it.
|
||||
|
||||
The owner can set `x-amz-acl: public-read` or signed `x-amz-grant-*` headers on bucket creation, uploads, copies, and multipart initiation. Use `GET ?acl` to read bucket or object grants; `PUT ?acl` accepts signed grant headers or an XML `AccessControlPolicy`. A grantee ID is its access key. Permissions are `READ`, `WRITE`, `READ_ACP`, `WRITE_ACP`, and `FULL_CONTROL`; `AllUsers` can only read, and `AuthenticatedUsers` is recognized. Anonymous reads require an `AllUsers` grant. Overwriting an object resets its ACL to private unless new grants are supplied; retained versions keep their ACLs.
|
||||
New buckets default to `BucketOwnerEnforced` and all four Block Public Access flags enabled. Existing buckets retain their prior ACL behavior on upgrade. The owner can inspect or change settings with `GET`/`PUT ?ownershipControls` and `GET`/`PUT ?publicAccessBlock`; changing a legacy bucket to owner-enforced immediately stops its ACL grants from authorizing requests. Public ACL writes are blocked when `BlockPublicAcls` is enabled, and existing public ACL grants are ignored when `IgnorePublicAcls` is enabled. `GET`/`PUT`/`DELETE ?policy` manages a bucket policy. `BlockPublicPolicy` rejects new policies that allow a wildcard principal; `RestrictPublicBuckets` prevents anonymous access through such a policy.
|
||||
|
||||
For a narrower additional key, mount a second private file and set `S3_KEY_SCOPES_FILE` to its container path. Each non-comment line has four **tab-separated** fields: access key, bucket, key prefix, and comma-separated actions (`read`, `write`, `list`). For example, `UPLOADKEY12345678<TAB>media<TAB>users/42/<TAB>read,write,list`. The file must name an identity in `S3_CREDENTIALS_FILE`; the owner key is always unrestricted. Once the scope file is enabled, an additional key with no scope is denied. A list request must include a prefix inside the granted prefix. Copy requires read permission on the source and write permission on the destination. Restricted keys cannot change ACLs or manage buckets. Existing S3 ACL checks still apply, so the bucket must also grant the key the corresponding permissions. Restart the service after editing either file.
|
||||
On a bucket with ACLs enabled, the owner can set `x-amz-acl: public-read` or signed `x-amz-grant-*` headers on bucket creation, uploads, copies, and multipart initiation. Use `GET ?acl` to read bucket or object grants; `PUT ?acl` accepts signed grant headers or an XML `AccessControlPolicy`. A grantee ID is its access key. Permissions are `READ`, `WRITE`, `READ_ACP`, `WRITE_ACP`, and `FULL_CONTROL`; `AllUsers` can only read, and `AuthenticatedUsers` is recognized. Anonymous reads require an `AllUsers` grant or an allowed bucket policy. Overwriting an object resets its ACL to private unless new grants are supplied; retained versions keep their ACLs. Email grantees return `405 MethodNotAllowed`, matching AWS's removal of that grant type.
|
||||
|
||||
The configured owner owns every bucket and object. A `WRITE_ACP` grantee can change an ACL only on a retained, non-null version; current unversioned and null versions require the owner key. Version lists, multipart inspection, tags, versioning controls, bucket creation/deletion, and capabilities remain owner-only. IAM policies, email grantees, Object Ownership, Block Public Access, and temporary credentials are unsupported. Public bucket `READ` exposes names; public object `READ` exposes bytes. Review grants before exposing a gateway.
|
||||
For a narrower additional key, mount a second private file and set `S3_KEY_SCOPES_FILE` to its container path. Each non-comment line has four **tab-separated** fields: access key, bucket, key prefix, and comma-separated actions (`read`, `write`, `list`). For example, `UPLOADKEY12345678<TAB>media<TAB>users/42/<TAB>read,write,list`. The file may name a permanent or session identity; the owner key is always unrestricted. Once the scope file is enabled, an additional key with no scope is denied. A list request must include a prefix inside the granted prefix. Copy requires read permission on the source and write permission on the destination. Restricted keys cannot change ACLs or manage buckets. A scope is a ceiling: the bucket ACL, bucket policy, or identity policy must also grant access. Restart the service after editing the files.
|
||||
|
||||
To use identity policies, mount a private directory and set `S3_IDENTITY_POLICIES_DIR` to its container path. Put one `<ACCESSKEY>.json` file per identity. The supported JSON subset uses `Version: "2012-10-17"` and `Statement` entries with `Effect`, `Action`, and `Resource`; it accepts S3 action wildcards and bucket/object ARNs. The bucket-policy form also requires `Principal`, using `*`, an access key, or `{ "AWS": "ACCESSKEY" }`. Policies govern object reads, writes, deletes, copies, ACLs, bucket listing, and multipart writes or aborts. Explicit denies win. `Condition`, `NotAction`, `NotResource`, `NotPrincipal`, and IAM roles are rejected rather than silently ignored. Files load on restart; protect the directory like credentials.
|
||||
|
||||
For a restricted key to upload **and read** files in a new owner-enforced bucket, give it both a `read,write` key scope for its prefix and an identity policy allowing `s3:PutObject` and `s3:GetObject` on that prefix. For example, a scope of `UPLOADKEY12345678<TAB>media<TAB>users/42/<TAB>read,write` pairs with `UPLOADKEY12345678.json` containing `{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["s3:PutObject","s3:GetObject"],"Resource":"arn:aws:s3:::media/users/42/*"}]}`. A scope alone is only a ceiling, and ObjectStore does not infer ownership from the uploader's key. Assign a distinct prefix per key when keys must not read each other's files.
|
||||
|
||||
For externally issued sessions, mount a private file and set `S3_SESSION_CREDENTIALS_FILE` to its container path. Each line is four **tab-separated** fields: session access key, secret, security token, and Unix expiry time in seconds. Session keys use the same 16–128 alphanumeric format as permanent keys; secrets and tokens need at least 32 characters. Signed requests must sign and send `x-amz-security-token`; presigned URLs must include signed `X-Amz-Security-Token`. Expired or mismatched tokens are denied on every request. ObjectStore does not issue or refresh sessions: provision and rotate the file outside the service, then restart. A session has no access until an ACL, bucket policy, or identity policy grants it; a configured key scope can narrow it further.
|
||||
|
||||
The configured owner owns every bucket and object. `BucketOwnerPreferred` and `ObjectWriter` are accepted as ACL-enabled modes, but there is one ObjectStore account, so cross-account object ownership is not modeled. A `WRITE_ACP` grantee can change an ACL only on a retained, non-null version; current unversioned and null versions require the owner key. Version lists, multipart inspection, tags, versioning controls, bucket creation/deletion, and capabilities remain owner-only. These policy features cover common object and bucket access, not full AWS IAM or STS. Public bucket `READ` exposes names; public object `READ` exposes bytes. Review grants before exposing a gateway.
|
||||
|
||||
## CLI and tests
|
||||
|
||||
@@ -154,12 +162,14 @@ Public-client limits are **disabled by default**. The localhost Compose setup is
|
||||
|
||||
Set `S3_VIRTUAL_HOST_SUFFIX` to a DNS suffix such as `s3.example.com` to accept `bucket.s3.example.com/key` alongside path-style `/bucket/key`. Configure DNS and TLS for the bucket hostnames, and preserve the client's original `Host` header through the proxy; Signature V4 signs it. The suffix is empty by default. This changes request parsing, not bucket naming rules or DNS configuration.
|
||||
|
||||
Set `S3_PUBLIC_ENDPOINT` to the external HTTP(S) origin, such as `https://s3.example.com`, when a TLS reverse proxy fronts ObjectStore. Multipart completion uses it to return a path-style `Location` URL. Without it, the response uses the request's signed `Host` and direct connection scheme, which may be `http` behind a TLS proxy. The value must be an origin without a path, query, user info, or fragment.
|
||||
|
||||
For example, to start with 100 requests per second and 16 MiB/s combined upload and download per IP, set `PUBLIC_REQUESTS_PER_SECOND=100` and `PUBLIC_BYTES_PER_SECOND=16777216`. Both start with a one-second burst. Adjust these numbers after measuring the actual workload; do not copy them as a universal production policy.
|
||||
|
||||
ObjectStore uses the socket peer as the client IP and ignores forwarded-IP headers by default. If a reverse proxy sits between external clients and ObjectStore, set `PUBLIC_TRUSTED_PROXY_IPS` to the exact IP address that ObjectStore sees for that proxy and configure the proxy to **replace** `X-Real-IP` with its actual client IP. A request from that trusted peer without exactly one valid numeric `X-Real-IP` is rejected. Do not trust an address reachable by arbitrary clients, and preserve the original `Host` header for Signature V4. In Docker, the proxy's address as seen by the container may be a bridge address rather than `127.0.0.1`. If proxy trust is not configured, all clients behind that proxy share its budget; this is safe from header spoofing but may throttle them together.
|
||||
|
||||
Enable these limits only on a deliberately public endpoint. They also apply to direct localhost storage calls to that same endpoint; leave them disabled for the local-only setup or run a separate local-only instance if local storage calls must be exempt. A direct loopback `/health` probe without a forwarded-IP header remains exempt. The byte limit is aggregate ingress plus egress for each IP, and several users behind one NAT share it. If a proxy buffers complete uploads before forwarding them, the upload byte limit controls proxy-to-ObjectStore traffic, not the client's initial upload speed; disable request buffering when end-to-end upload pacing is required. It is a fairness control, not a defense against connection floods before the Java handler runs. Put an internet-facing proxy or firewall in front of the gateway for TLS, connection limits, request timeouts, and buffering controls. Do not expose storage nodes or PostgreSQL publicly.
|
||||
|
||||
The default local cluster still uses plaintext node and PostgreSQL connections. The optional TLS overlay secures node traffic, but PostgreSQL TLS, automatic metadata failover, IAM policies, and physical host verification remain absent. The key-scope file limits additional signed identities; it is not an IAM replacement. Garbage collection can remove data required by an older metadata backup, so its retention guard is essential. Host UUIDs are operator labels, not proof that machines have separate power, disks, or network paths. Keep `CLUSTER_LOCAL_DEV=true` limited to local tests.
|
||||
The default local cluster still uses plaintext node and PostgreSQL connections. The optional TLS overlay secures node traffic, but PostgreSQL TLS, automatic metadata failover, full IAM, and physical host verification remain absent. The key-scope file and policy subset limit additional signed identities; they are not an IAM replacement. Garbage collection can remove data required by an older metadata backup, so its retention guard is essential. Host UUIDs are operator labels, not proof that machines have separate power, disks, or network paths. Keep `CLUSTER_LOCAL_DEV=true` limited to local tests.
|
||||
|
||||
The standalone cluster node binds to localhost by default. Set `NODE_BIND` only for a private test network; the Compose file binds inside its private Docker network. PostgreSQL JDBC 42.7.14 is bundled in the image with its license inside the JAR.
|
||||
@@ -42,14 +42,15 @@ Legacy single-node objects remain readable but stay out of listings until overwr
|
||||
- ✅ User metadata on object and multipart uploads; object tags on upload, copy, and the tagging subresource
|
||||
- ✅ CRC64NVME and XXHash checksums, checksum trailers, and persisted object checksum metadata
|
||||
- ✅ Bucket versioning with retained versions, delete markers, and version-specific reads, copies, deletes, and tags in both modes
|
||||
- ✅ Basic bucket and object ACL grants, public reads, and multiple access-key identities
|
||||
- ⬜ Full AWS ACL ownership controls, email grantees, and bucket policies
|
||||
- ✅ Bucket and object ACL grants, bucket policies, Object Ownership controls, and Block Public Access
|
||||
- ✅ Scoped identity policies and externally provisioned, expiring session credentials
|
||||
- ⬜ Full IAM, STS issuance, cross-account ACL ownership, and conditional policies
|
||||
|
||||
This is an S3 subset. Unsupported operations and Amazon-specific headers are rejected. Bucket names use three to 63 lowercase letters, digits, or hyphens; the default bucket cannot be deleted. Bucket creation accepts an empty body for the configured region. Tags do not control access.
|
||||
|
||||
Versioning supports enabled and suspended states. Old versions and delete markers count toward capacity; deleting a specific version is permanent. Lifecycle expiration, MFA Delete, and `ListObjectVersions` delimiter grouping are unsupported. User metadata accepts printable ASCII only.
|
||||
|
||||
`PutObject` checksums are validated and retained; without one, ObjectStore stores CRC64NVME, including for completed multipart uploads. Request `x-amz-checksum-mode: ENABLED` on GET or HEAD to receive it. `UploadPart` checksums are validated but are not returned by `ListParts` or combined into a multipart checksum. Presigned URLs expire within seven days. Signed `aws-chunked` uploads support one checksum trailer; temporary credentials and other streaming modes are unsupported. Copies obey the object size limit.
|
||||
`PutObject` checksums are validated and retained; without one, ObjectStore stores CRC64NVME, including for completed multipart uploads. Request `x-amz-checksum-mode: ENABLED` on GET or HEAD to receive it. `UploadPart` checksums are validated but are not returned by `ListParts` or combined into a multipart checksum. Presigned URLs expire within seven days. Signed `aws-chunked` uploads support one checksum trailer; other streaming modes are unsupported. Copies obey the object size limit.
|
||||
|
||||
## Single-node setup
|
||||
|
||||
|
||||
@@ -14,12 +14,15 @@ services:
|
||||
S3_REGION: ${S3_REGION:-us-east-1}
|
||||
S3_CREDENTIALS_FILE: ${S3_CREDENTIALS_FILE:-}
|
||||
S3_KEY_SCOPES_FILE: ${S3_KEY_SCOPES_FILE:-}
|
||||
S3_SESSION_CREDENTIALS_FILE: ${S3_SESSION_CREDENTIALS_FILE:-}
|
||||
S3_IDENTITY_POLICIES_DIR: ${S3_IDENTITY_POLICIES_DIR:-}
|
||||
METRICS_BEARER_TOKEN: ${METRICS_BEARER_TOKEN:-}
|
||||
MAX_OBJECT_BYTES: ${MAX_OBJECT_BYTES:-134217728}
|
||||
MAX_TOTAL_BYTES: ${MAX_TOTAL_BYTES:-2147483648}
|
||||
MAX_IN_FLIGHT_REQUESTS: ${MAX_IN_FLIGHT_REQUESTS:-16}
|
||||
HTTP_BACKLOG: ${HTTP_BACKLOG:-64}
|
||||
S3_VIRTUAL_HOST_SUFFIX: ${S3_VIRTUAL_HOST_SUFFIX:-}
|
||||
S3_PUBLIC_ENDPOINT: ${S3_PUBLIC_ENDPOINT:-}
|
||||
CORS_ALLOWED_ORIGINS: ${CORS_ALLOWED_ORIGINS:-}
|
||||
OBJECTSTORE_REQUEST_TIMEOUT_SECONDS: ${OBJECTSTORE_REQUEST_TIMEOUT_SECONDS:-0}
|
||||
OBJECTSTORE_RESPONSE_TIMEOUT_SECONDS: ${OBJECTSTORE_RESPONSE_TIMEOUT_SECONDS:-0}
|
||||
|
||||
@@ -13,12 +13,15 @@ services:
|
||||
S3_REGION: ${S3_REGION:-us-east-1}
|
||||
S3_CREDENTIALS_FILE: ${S3_CREDENTIALS_FILE:-}
|
||||
S3_KEY_SCOPES_FILE: ${S3_KEY_SCOPES_FILE:-}
|
||||
S3_SESSION_CREDENTIALS_FILE: ${S3_SESSION_CREDENTIALS_FILE:-}
|
||||
S3_IDENTITY_POLICIES_DIR: ${S3_IDENTITY_POLICIES_DIR:-}
|
||||
METRICS_BEARER_TOKEN: ${METRICS_BEARER_TOKEN:-}
|
||||
MAX_OBJECT_BYTES: ${MAX_OBJECT_BYTES:-134217728}
|
||||
MAX_TOTAL_BYTES: ${MAX_TOTAL_BYTES:-2147483648}
|
||||
MAX_IN_FLIGHT_REQUESTS: ${MAX_IN_FLIGHT_REQUESTS:-16}
|
||||
HTTP_BACKLOG: ${HTTP_BACKLOG:-64}
|
||||
S3_VIRTUAL_HOST_SUFFIX: ${S3_VIRTUAL_HOST_SUFFIX:-}
|
||||
S3_PUBLIC_ENDPOINT: ${S3_PUBLIC_ENDPOINT:-}
|
||||
CORS_ALLOWED_ORIGINS: ${CORS_ALLOWED_ORIGINS:-}
|
||||
PUBLIC_REQUESTS_PER_SECOND: ${PUBLIC_REQUESTS_PER_SECOND:-0}
|
||||
PUBLIC_REQUEST_BURST: ${PUBLIC_REQUEST_BURST:-}
|
||||
|
||||
@@ -15,7 +15,7 @@ for setting in request response; do
|
||||
[ "${#value}" -le 5 ] || { echo "$setting timeout exceeds one day" >&2; exit 1; }
|
||||
if [ "$value" -gt 0 ]; then
|
||||
[ "$value" -le 86400 ] || { echo "$setting timeout exceeds one day" >&2; exit 1; }
|
||||
set -- "$@" "-Dsun.net.httpserver.$property=$((value * 1000))"
|
||||
set -- "$@" "-Dsun.net.httpserver.$property=$value"
|
||||
fi
|
||||
done
|
||||
|
||||
|
||||
@@ -148,6 +148,15 @@ assert "ListParts" in capabilities["operations"], capabilities
|
||||
assert capabilities["limits"]["maxObjectBytes"] > 0, capabilities
|
||||
assert headers.get_content_type() == "application/json", headers
|
||||
|
||||
ownership = b"<OwnershipControls><Rule><ObjectOwnership>ObjectWriter</ObjectOwnership></Rule></OwnershipControls>"
|
||||
status, _, _ = request("PUT", f"/{bucket}?ownershipControls", ownership)
|
||||
assert status == 200, status
|
||||
public_access = (b"<PublicAccessBlockConfiguration><BlockPublicAcls>false</BlockPublicAcls>"
|
||||
b"<IgnorePublicAcls>false</IgnorePublicAcls><BlockPublicPolicy>false</BlockPublicPolicy>"
|
||||
b"<RestrictPublicBuckets>false</RestrictPublicBuckets></PublicAccessBlockConfiguration>")
|
||||
status, _, _ = request("PUT", f"/{bucket}?publicAccessBlock", public_access)
|
||||
assert status == 200, status
|
||||
|
||||
key = f"/{bucket}/cluster-test/http.txt"
|
||||
body = b"HTTP gateway integration test"
|
||||
status, _, _ = request("PUT", key, body)
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
test_dir=$(mktemp -d)
|
||||
trap 'rm -rf "$test_dir"' EXIT HUP INT TERM
|
||||
cat > "$test_dir/java" <<'EOF'
|
||||
#!/bin/sh
|
||||
printf '%s\n' "$@" > "$OBJECTSTORE_TEST_ARGS"
|
||||
EOF
|
||||
chmod +x "$test_dir/java"
|
||||
OBJECTSTORE_TEST_ARGS="$test_dir/args" PATH="$test_dir:$PATH" \
|
||||
OBJECTSTORE_REQUEST_TIMEOUT_SECONDS=300 OBJECTSTORE_RESPONSE_TIMEOUT_SECONDS=45 \
|
||||
sh scripts/start-server.sh
|
||||
grep -Fx -- '-Dsun.net.httpserver.maxReqTime=300' "$test_dir/args" >/dev/null
|
||||
grep -Fx -- '-Dsun.net.httpserver.maxRspTime=45' "$test_dir/args" >/dev/null
|
||||
if OBJECTSTORE_TEST_ARGS="$test_dir/args" PATH="$test_dir:$PATH" \
|
||||
OBJECTSTORE_REQUEST_TIMEOUT_SECONDS=86401 sh scripts/start-server.sh 2>/dev/null; then
|
||||
echo 'Oversized request timeout was accepted' >&2
|
||||
exit 1
|
||||
fi
|
||||
echo 'Server launcher timeout tests passed'
|
||||
@@ -1,6 +1,7 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
sh scripts/test-start-server.sh
|
||||
mkdir -p out/classes
|
||||
javac --release 21 --add-modules jdk.httpserver,java.net.http -cp lib/hash4j-0.30.0.jar -d out/classes \
|
||||
src/cloud/lunarsky/store/*.java test/cloud/lunarsky/store/*.java
|
||||
|
||||
@@ -65,6 +65,8 @@ final class Acl {
|
||||
principal = entry.substring(4, entry.length() - 1);
|
||||
else if (entry.startsWith("uri=\"") && entry.endsWith("\""))
|
||||
principal = entry.substring(5, entry.length() - 1);
|
||||
else if (entry.startsWith("emailAddress=\""))
|
||||
throw new StoreException(405, "MethodNotAllowed", "Email ACL grantees are no longer supported");
|
||||
else throw new StoreException(400, "InvalidArgument", "Invalid ACL grant");
|
||||
if (!identities.contains(principal) && !principal.equals(ALL_USERS) &&
|
||||
!principal.equals(AUTHENTICATED_USERS))
|
||||
@@ -122,6 +124,8 @@ final class Acl {
|
||||
String principal = switch (type) {
|
||||
case "CanonicalUser" -> text(grantee, "ID");
|
||||
case "Group" -> text(grantee, "URI");
|
||||
case "AmazonCustomerByEmail" -> throw new StoreException(405, "MethodNotAllowed",
|
||||
"Email ACL grantees are no longer supported");
|
||||
default -> throw new IllegalArgumentException();
|
||||
};
|
||||
Integer permission = PERMISSIONS.get(text(grant, "Permission"));
|
||||
@@ -130,7 +134,8 @@ final class Acl {
|
||||
}
|
||||
grants.remove(owner);
|
||||
return validate(encoded(grants), identities);
|
||||
} catch (Exception error) {
|
||||
} catch (StoreException error) { throw error; }
|
||||
catch (Exception error) {
|
||||
throw new StoreException(400, "MalformedACLError", "Invalid access control policy");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -40,30 +40,105 @@ final class BucketHandler {
|
||||
void handleBucket(HttpExchange exchange, Map<String, String> query, String hash,
|
||||
String bucketName, String principal) throws IOException {
|
||||
String method = exchange.getRequestMethod();
|
||||
if (query.size() >= 1 && query.size() <= 2 &&
|
||||
query.keySet().stream().allMatch(java.util.Set.of("ownershipControls", "x-id")::contains) &&
|
||||
query.containsKey("ownershipControls") && query.get("ownershipControls").isEmpty()) {
|
||||
access.requireOwner(principal);
|
||||
if (method.equals("GET")) {
|
||||
S3Request.requireEmptyBody(exchange, hash);
|
||||
S3Xml.sendXml(exchange, 200, BucketSecurity.ownershipXml(store.bucket(bucketName).ownership()));
|
||||
} else if (method.equals("PUT")) {
|
||||
byte[] body = S3Request.signedBody(exchange, hash, 65536);
|
||||
S3Request.verifyContentMd5(exchange.getRequestHeaders(), body);
|
||||
store.setBucketOwnership(bucketName, BucketSecurity.parseOwnership(body));
|
||||
exchange.sendResponseHeaders(200, -1);
|
||||
} else if (method.equals("DELETE")) {
|
||||
S3Request.requireEmptyBody(exchange, hash);
|
||||
store.setBucketOwnership(bucketName, ObjectStorage.ObjectOwnership.OBJECT_WRITER);
|
||||
exchange.sendResponseHeaders(204, -1);
|
||||
} else S3Request.unsupported("Ownership controls operation");
|
||||
return;
|
||||
}
|
||||
if (query.size() >= 1 && query.size() <= 2 &&
|
||||
query.keySet().stream().allMatch(java.util.Set.of("publicAccessBlock", "x-id")::contains) &&
|
||||
query.containsKey("publicAccessBlock") && query.get("publicAccessBlock").isEmpty()) {
|
||||
access.requireOwner(principal);
|
||||
if (method.equals("GET")) {
|
||||
S3Request.requireEmptyBody(exchange, hash);
|
||||
S3Xml.sendXml(exchange, 200, BucketSecurity.publicAccessXml(
|
||||
store.bucket(bucketName).publicAccessBlock()));
|
||||
} else if (method.equals("PUT")) {
|
||||
byte[] body = S3Request.signedBody(exchange, hash, 65536);
|
||||
S3Request.verifyContentMd5(exchange.getRequestHeaders(), body);
|
||||
store.setPublicAccessBlock(bucketName, BucketSecurity.parsePublicAccess(body));
|
||||
exchange.sendResponseHeaders(200, -1);
|
||||
} else if (method.equals("DELETE")) {
|
||||
S3Request.requireEmptyBody(exchange, hash);
|
||||
store.setPublicAccessBlock(bucketName, ObjectStorage.PublicAccessBlock.open());
|
||||
exchange.sendResponseHeaders(204, -1);
|
||||
} else S3Request.unsupported("Public access block operation");
|
||||
return;
|
||||
}
|
||||
if (query.size() >= 1 && query.size() <= 2 &&
|
||||
query.keySet().stream().allMatch(java.util.Set.of("policy", "x-id")::contains) &&
|
||||
query.containsKey("policy") && query.get("policy").isEmpty()) {
|
||||
access.requireOwner(principal);
|
||||
var current = store.bucket(bucketName);
|
||||
if (method.equals("GET")) {
|
||||
S3Request.requireEmptyBody(exchange, hash);
|
||||
if (current.policy() == null)
|
||||
throw new StoreException(404, "NoSuchBucketPolicy", "Bucket has no policy");
|
||||
byte[] body = current.policy().getBytes(StandardCharsets.UTF_8);
|
||||
exchange.getResponseHeaders().set("Content-Type", "application/json");
|
||||
exchange.sendResponseHeaders(200, body.length);
|
||||
exchange.getResponseBody().write(body);
|
||||
} else if (method.equals("PUT")) {
|
||||
byte[] body = S3Request.signedBody(exchange, hash, 20480);
|
||||
S3Request.verifyContentMd5(exchange.getRequestHeaders(), body);
|
||||
String policy = new String(body, StandardCharsets.UTF_8);
|
||||
BucketPolicy parsed = BucketPolicy.parse(policy, bucketName);
|
||||
if (current.publicAccessBlock().blockPublicPolicy() && parsed.publicAllow())
|
||||
throw new StoreException(403, "AccessDenied", "Public bucket policies are blocked");
|
||||
store.setBucketPolicy(bucketName, policy);
|
||||
exchange.sendResponseHeaders(204, -1);
|
||||
} else if (method.equals("DELETE")) {
|
||||
S3Request.requireEmptyBody(exchange, hash);
|
||||
store.setBucketPolicy(bucketName, null);
|
||||
exchange.sendResponseHeaders(204, -1);
|
||||
} else S3Request.unsupported("Bucket policy operation");
|
||||
return;
|
||||
}
|
||||
if (query.containsKey("acl") && query.get("acl").isEmpty() &&
|
||||
query.keySet().stream().allMatch(java.util.Set.of("acl", "x-id")::contains) &&
|
||||
(!query.containsKey("x-id") ||
|
||||
query.get("x-id").equals(method.equals("GET") ? "GetBucketAcl" : "PutBucketAcl")) &&
|
||||
(method.equals("GET") || method.equals("PUT"))) {
|
||||
var current = store.bucket(bucketName);
|
||||
Acl.require(current.acl(), principal, owner,
|
||||
access.requireBucket(bucketName, principal,
|
||||
method.equals("GET") ? Acl.READ_ACP : Acl.WRITE_ACP);
|
||||
if (method.equals("GET")) {
|
||||
S3Request.requireEmptyBody(exchange, hash);
|
||||
S3Xml.sendXml(exchange, 200, Acl.xml(current.acl(), owner));
|
||||
S3Xml.sendXml(exchange, 200, Acl.xml(
|
||||
current.ownership() == ObjectStorage.ObjectOwnership.BUCKET_OWNER_ENFORCED
|
||||
? Map.of() : current.acl(), owner));
|
||||
} else {
|
||||
if (current.ownership() == ObjectStorage.ObjectOwnership.BUCKET_OWNER_ENFORCED)
|
||||
throw new StoreException(400, "AccessControlListNotSupported", "ACLs are disabled for this bucket");
|
||||
if (exchange.getRequestHeaders().containsKey("x-amz-acl") ||
|
||||
exchange.getRequestHeaders().keySet().stream().anyMatch(
|
||||
name -> name.toLowerCase(Locale.ROOT).startsWith("x-amz-grant-"))) {
|
||||
S3Request.requireEmptyBody(exchange, hash);
|
||||
S3Request.verifyContentMd5(exchange.getRequestHeaders(), new byte[0]);
|
||||
store.setBucketAcl(bucketName, Acl.fromHeaders(exchange.getRequestHeaders(),
|
||||
authentication.identities()));
|
||||
Map<String, String> acl = Acl.fromHeaders(exchange.getRequestHeaders(),
|
||||
authentication.identities());
|
||||
BucketSecurity.checkAcl(current, exchange.getRequestHeaders(), acl, true);
|
||||
store.setBucketAcl(bucketName, acl);
|
||||
} else {
|
||||
byte[] body = S3Request.signedBody(exchange, hash, 65536);
|
||||
S3Request.verifyContentMd5(exchange.getRequestHeaders(), body);
|
||||
store.setBucketAcl(bucketName, Acl.fromXml(body,
|
||||
owner, authentication.identities()));
|
||||
Map<String, String> acl = Acl.fromXml(body, owner, authentication.identities());
|
||||
BucketSecurity.checkAcl(current, exchange.getRequestHeaders(), acl, true);
|
||||
store.setBucketAcl(bucketName, acl);
|
||||
}
|
||||
exchange.sendResponseHeaders(200, -1);
|
||||
}
|
||||
@@ -81,9 +156,20 @@ final class BucketHandler {
|
||||
switch (method) {
|
||||
case "PUT" -> {
|
||||
access.requireOwner(principal);
|
||||
String requestedOwnership = SigV4.single(exchange.getRequestHeaders(), "x-amz-object-ownership");
|
||||
ObjectStorage.ObjectOwnership ownership = requestedOwnership == null
|
||||
? ObjectStorage.ObjectOwnership.BUCKET_OWNER_ENFORCED
|
||||
: BucketSecurity.ownership(requestedOwnership);
|
||||
Map<String, String> acl = Acl.fromHeaders(exchange.getRequestHeaders(),
|
||||
authentication.identities());
|
||||
BucketSecurity.checkAcl(new ObjectStorage.Bucket(bucketName, 0,
|
||||
ObjectStorage.VersioningState.NEVER, Map.of(), ownership,
|
||||
ObjectStorage.PublicAccessBlock.secure(), null),
|
||||
exchange.getRequestHeaders(), acl, false);
|
||||
store.createBucket(bucketName);
|
||||
if (requestedOwnership != null &&
|
||||
ownership != ObjectStorage.ObjectOwnership.BUCKET_OWNER_ENFORCED)
|
||||
store.setBucketOwnership(bucketName, ownership);
|
||||
if (!acl.isEmpty()) store.setBucketAcl(bucketName, acl);
|
||||
exchange.getResponseHeaders().set("Location", "/" + bucketName);
|
||||
exchange.sendResponseHeaders(200, -1);
|
||||
|
||||
@@ -0,0 +1,228 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
final class BucketPolicy {
|
||||
private static final BucketPolicy EMPTY = new BucketPolicy(List.of());
|
||||
private record Statement(boolean allow, List<String> principals, List<String> actions,
|
||||
List<String> resources) {
|
||||
boolean matches(String principal, String action, String resource) {
|
||||
return (principals.contains("*") || principal != null && principals.contains(principal)) &&
|
||||
actions.stream().anyMatch(pattern -> glob(pattern, action)) &&
|
||||
resources.stream().anyMatch(pattern -> glob(pattern, resource));
|
||||
}
|
||||
}
|
||||
|
||||
private final List<Statement> statements;
|
||||
private final boolean publicAllow;
|
||||
|
||||
private BucketPolicy(List<Statement> statements) {
|
||||
this.statements = List.copyOf(statements);
|
||||
this.publicAllow = statements.stream().anyMatch(
|
||||
statement -> statement.allow() && statement.principals().contains("*"));
|
||||
}
|
||||
|
||||
static BucketPolicy empty() { return EMPTY; }
|
||||
|
||||
boolean publicAllow() { return publicAllow; }
|
||||
|
||||
int decide(String principal, String action, String resource) {
|
||||
boolean allowed = false;
|
||||
for (Statement statement : statements) {
|
||||
if (!statement.matches(principal, action, resource)) continue;
|
||||
if (!statement.allow()) return -1;
|
||||
allowed = true;
|
||||
}
|
||||
return allowed ? 1 : 0;
|
||||
}
|
||||
|
||||
static BucketPolicy parse(String json, String bucket) {
|
||||
return parse(json, bucket, false);
|
||||
}
|
||||
|
||||
static BucketPolicy parseIdentity(String json) {
|
||||
return parse(json, null, true);
|
||||
}
|
||||
|
||||
private static BucketPolicy parse(String json, String bucket, boolean identity) {
|
||||
if (json == null || json.isBlank() || json.getBytes(StandardCharsets.UTF_8).length > 20480)
|
||||
throw invalid();
|
||||
Object parsed = new Parser(json).parse();
|
||||
Map<String, Object> policy = object(parsed);
|
||||
if (!policy.keySet().stream().allMatch(Set.of("Version", "Id", "Statement")::contains) ||
|
||||
!"2012-10-17".equals(policy.get("Version"))) throw invalid();
|
||||
Object raw = policy.get("Statement");
|
||||
if (raw == null) throw invalid();
|
||||
List<?> entries = raw instanceof List<?> list ? list : List.of(raw);
|
||||
if (entries.isEmpty() || entries.size() > 64) throw invalid();
|
||||
List<Statement> statements = new ArrayList<>();
|
||||
for (Object entry : entries) {
|
||||
Map<String, Object> item = object(entry);
|
||||
Set<String> keys = identity ? Set.of("Sid", "Effect", "Action", "Resource") :
|
||||
Set.of("Sid", "Effect", "Principal", "Action", "Resource");
|
||||
if (!item.keySet().stream().allMatch(keys::contains))
|
||||
throw invalid();
|
||||
boolean allow;
|
||||
if ("Allow".equals(item.get("Effect"))) allow = true;
|
||||
else if ("Deny".equals(item.get("Effect"))) allow = false;
|
||||
else throw invalid();
|
||||
Object principal = item.get("Principal");
|
||||
List<String> principals = identity ? List.of("*") : principal instanceof Map<?, ?> map
|
||||
? strings(object(map).get("AWS")) : strings(principal);
|
||||
if (!identity && principal instanceof Map<?, ?> map && !map.keySet().equals(Set.of("AWS")))
|
||||
throw invalid();
|
||||
for (String name : principals)
|
||||
if (!name.equals("*") && !name.matches("[A-Za-z0-9]{16,128}")) throw invalid();
|
||||
List<String> actions = strings(item.get("Action"));
|
||||
for (String action : actions)
|
||||
if (!action.matches("s3:[A-Za-z*]+")) throw invalid();
|
||||
List<String> resources = strings(item.get("Resource"));
|
||||
String bucketArn = "arn:aws:s3:::" + bucket;
|
||||
for (String resource : resources)
|
||||
if (identity ? !resource.matches("arn:aws:s3:::[a-z0-9*?][a-z0-9*?.-]{0,62}(/[^\\p{Cntrl}]+)?") :
|
||||
!resource.equals(bucketArn) && !resource.startsWith(bucketArn + "/")) throw invalid();
|
||||
statements.add(new Statement(allow, principals, actions, resources));
|
||||
}
|
||||
return new BucketPolicy(statements);
|
||||
}
|
||||
|
||||
private static List<String> strings(Object value) {
|
||||
if (value == null) throw invalid();
|
||||
List<?> values = value instanceof List<?> list ? list : List.of(value);
|
||||
if (values.isEmpty() || values.size() > 64) throw invalid();
|
||||
List<String> result = new ArrayList<>();
|
||||
for (Object item : values) {
|
||||
if (!(item instanceof String text) || text.isBlank() || text.length() > 1024)
|
||||
throw invalid();
|
||||
result.add(text);
|
||||
}
|
||||
return List.copyOf(result);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static Map<String, Object> object(Object value) {
|
||||
if (!(value instanceof Map<?, ?>)) throw invalid();
|
||||
return (Map<String, Object>) value;
|
||||
}
|
||||
|
||||
private static StoreException invalid() {
|
||||
return new StoreException(400, "MalformedPolicy", "Unsupported or malformed bucket policy");
|
||||
}
|
||||
|
||||
private static boolean glob(String pattern, String text) {
|
||||
int p = 0, t = 0, star = -1, retry = 0;
|
||||
while (t < text.length()) {
|
||||
if (p < pattern.length() && pattern.charAt(p) == text.charAt(t)) { p++; t++; }
|
||||
else if (p < pattern.length() && pattern.charAt(p) == '*') { star = p++; retry = t; }
|
||||
else if (star >= 0) { p = star + 1; t = ++retry; }
|
||||
else return false;
|
||||
}
|
||||
while (p < pattern.length() && pattern.charAt(p) == '*') p++;
|
||||
return p == pattern.length();
|
||||
}
|
||||
|
||||
private static final class Parser {
|
||||
private final String input;
|
||||
private int index;
|
||||
|
||||
Parser(String input) { this.input = input; }
|
||||
|
||||
Object parse() {
|
||||
Object value = value(0);
|
||||
space();
|
||||
if (index != input.length()) throw invalid();
|
||||
return value;
|
||||
}
|
||||
|
||||
private Object value(int depth) {
|
||||
if (depth > 16) throw invalid();
|
||||
space();
|
||||
if (index == input.length()) throw invalid();
|
||||
return switch (input.charAt(index)) {
|
||||
case '"' -> string();
|
||||
case '{' -> object(depth + 1);
|
||||
case '[' -> array(depth + 1);
|
||||
default -> throw invalid();
|
||||
};
|
||||
}
|
||||
|
||||
private Map<String, Object> object(int depth) {
|
||||
index++;
|
||||
Map<String, Object> map = new LinkedHashMap<>();
|
||||
space();
|
||||
if (take('}')) return map;
|
||||
do {
|
||||
space();
|
||||
if (index == input.length() || input.charAt(index) != '"') throw invalid();
|
||||
String key = string();
|
||||
space();
|
||||
expect(':');
|
||||
if (map.putIfAbsent(key, value(depth)) != null) throw invalid();
|
||||
space();
|
||||
if (take('}')) return map;
|
||||
expect(',');
|
||||
} while (true);
|
||||
}
|
||||
|
||||
private List<Object> array(int depth) {
|
||||
index++;
|
||||
List<Object> list = new ArrayList<>();
|
||||
space();
|
||||
if (take(']')) return list;
|
||||
do {
|
||||
if (list.size() >= 64) throw invalid();
|
||||
list.add(value(depth));
|
||||
space();
|
||||
if (take(']')) return list;
|
||||
expect(',');
|
||||
} while (true);
|
||||
}
|
||||
|
||||
private String string() {
|
||||
expect('"');
|
||||
StringBuilder result = new StringBuilder();
|
||||
while (index < input.length()) {
|
||||
char c = input.charAt(index++);
|
||||
if (c == '"') return result.toString();
|
||||
if (c < 0x20) throw invalid();
|
||||
if (c != '\\') { result.append(c); continue; }
|
||||
if (index == input.length()) throw invalid();
|
||||
char escape = input.charAt(index++);
|
||||
switch (escape) {
|
||||
case '"', '\\', '/' -> result.append(escape);
|
||||
case 'b' -> result.append('\b');
|
||||
case 'f' -> result.append('\f');
|
||||
case 'n' -> result.append('\n');
|
||||
case 'r' -> result.append('\r');
|
||||
case 't' -> result.append('\t');
|
||||
case 'u' -> {
|
||||
if (index + 4 > input.length()) throw invalid();
|
||||
try { result.append((char) Integer.parseInt(input.substring(index, index + 4), 16)); }
|
||||
catch (NumberFormatException error) { throw invalid(); }
|
||||
index += 4;
|
||||
}
|
||||
default -> throw invalid();
|
||||
}
|
||||
}
|
||||
throw invalid();
|
||||
}
|
||||
|
||||
private void space() {
|
||||
while (index < input.length() && Character.isWhitespace(input.charAt(index))) index++;
|
||||
}
|
||||
|
||||
private boolean take(char expected) {
|
||||
if (index < input.length() && input.charAt(index) == expected) { index++; return true; }
|
||||
return false;
|
||||
}
|
||||
|
||||
private void expect(char expected) {
|
||||
if (!take(expected)) throw invalid();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import com.sun.net.httpserver.Headers;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import javax.xml.XMLConstants;
|
||||
import javax.xml.parsers.DocumentBuilderFactory;
|
||||
import org.w3c.dom.Element;
|
||||
|
||||
final class BucketSecurity {
|
||||
private BucketSecurity() { }
|
||||
|
||||
static String ownershipName(ObjectStorage.ObjectOwnership ownership) {
|
||||
return switch (ownership) {
|
||||
case BUCKET_OWNER_ENFORCED -> "BucketOwnerEnforced";
|
||||
case BUCKET_OWNER_PREFERRED -> "BucketOwnerPreferred";
|
||||
case OBJECT_WRITER -> "ObjectWriter";
|
||||
};
|
||||
}
|
||||
|
||||
static ObjectStorage.ObjectOwnership ownership(String value) {
|
||||
return switch (value) {
|
||||
case "BucketOwnerEnforced" -> ObjectStorage.ObjectOwnership.BUCKET_OWNER_ENFORCED;
|
||||
case "BucketOwnerPreferred" -> ObjectStorage.ObjectOwnership.BUCKET_OWNER_PREFERRED;
|
||||
case "ObjectWriter" -> ObjectStorage.ObjectOwnership.OBJECT_WRITER;
|
||||
default -> throw new StoreException(400, "InvalidArgument", "Invalid object ownership setting");
|
||||
};
|
||||
}
|
||||
|
||||
static String ownershipXml(ObjectStorage.ObjectOwnership ownership) {
|
||||
return "<OwnershipControls xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">" +
|
||||
"<Rule><ObjectOwnership>" + ownershipName(ownership) +
|
||||
"</ObjectOwnership></Rule></OwnershipControls>";
|
||||
}
|
||||
|
||||
static ObjectStorage.ObjectOwnership parseOwnership(byte[] body) {
|
||||
Element root = root(body, "OwnershipControls");
|
||||
Element rule = onlyChild(root, "Rule");
|
||||
return ownership(onlyChild(rule, "ObjectOwnership").getTextContent().trim());
|
||||
}
|
||||
|
||||
static String publicAccessXml(ObjectStorage.PublicAccessBlock block) {
|
||||
return "<PublicAccessBlockConfiguration xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">" +
|
||||
"<BlockPublicAcls>" + block.blockPublicAcls() + "</BlockPublicAcls>" +
|
||||
"<IgnorePublicAcls>" + block.ignorePublicAcls() + "</IgnorePublicAcls>" +
|
||||
"<BlockPublicPolicy>" + block.blockPublicPolicy() + "</BlockPublicPolicy>" +
|
||||
"<RestrictPublicBuckets>" + block.restrictPublicBuckets() +
|
||||
"</RestrictPublicBuckets></PublicAccessBlockConfiguration>";
|
||||
}
|
||||
|
||||
static ObjectStorage.PublicAccessBlock parsePublicAccess(byte[] body) {
|
||||
Element root = root(body, "PublicAccessBlockConfiguration");
|
||||
if (elements(root) != 4) malformed();
|
||||
return new ObjectStorage.PublicAccessBlock(
|
||||
bool(onlyNamedChild(root, "BlockPublicAcls")),
|
||||
bool(onlyNamedChild(root, "IgnorePublicAcls")),
|
||||
bool(onlyNamedChild(root, "BlockPublicPolicy")),
|
||||
bool(onlyNamedChild(root, "RestrictPublicBuckets")));
|
||||
}
|
||||
|
||||
static void checkAcl(ObjectStorage.Bucket bucket, Headers headers, Map<String, String> acl,
|
||||
boolean aclOperation) {
|
||||
if (bucket.ownership() == ObjectStorage.ObjectOwnership.BUCKET_OWNER_ENFORCED) {
|
||||
String canned = SigV4.single(headers, "x-amz-acl");
|
||||
if (aclOperation || !acl.isEmpty() ||
|
||||
canned != null && !canned.equals("bucket-owner-full-control"))
|
||||
throw new StoreException(400, "AccessControlListNotSupported", "ACLs are disabled for this bucket");
|
||||
}
|
||||
if (bucket.publicAccessBlock().blockPublicAcls() && isPublic(acl))
|
||||
throw new StoreException(403, "AccessDenied", "Public ACLs are blocked for this bucket");
|
||||
}
|
||||
|
||||
static boolean allowsAcl(ObjectStorage.Bucket bucket, Map<String, String> acl,
|
||||
String principal, String owner, int permission) {
|
||||
if (bucket.ownership() == ObjectStorage.ObjectOwnership.BUCKET_OWNER_ENFORCED)
|
||||
return owner.equals(principal);
|
||||
if (bucket.publicAccessBlock().ignorePublicAcls() && isPublicPrincipal(principal))
|
||||
return false;
|
||||
if (bucket.publicAccessBlock().ignorePublicAcls())
|
||||
acl = acl.entrySet().stream()
|
||||
.filter(entry -> !isPublicPrincipal(entry.getKey()))
|
||||
.collect(java.util.stream.Collectors.toUnmodifiableMap(Map.Entry::getKey, Map.Entry::getValue));
|
||||
return Acl.allows(acl, principal, owner, permission);
|
||||
}
|
||||
|
||||
static boolean isPublic(Map<String, String> acl) {
|
||||
return acl.containsKey(Acl.ALL_USERS) || acl.containsKey(Acl.AUTHENTICATED_USERS);
|
||||
}
|
||||
|
||||
private static boolean isPublicPrincipal(String principal) {
|
||||
return Acl.ALL_USERS.equals(principal) || Acl.AUTHENTICATED_USERS.equals(principal);
|
||||
}
|
||||
|
||||
private static boolean bool(Element element) {
|
||||
if (elements(element) != 0) malformed();
|
||||
return switch (element.getTextContent().trim().toLowerCase(java.util.Locale.ROOT)) {
|
||||
case "true" -> true;
|
||||
case "false" -> false;
|
||||
default -> throw new StoreException(400, "MalformedXML", "Invalid public access block setting");
|
||||
};
|
||||
}
|
||||
|
||||
private static Element root(byte[] body, String name) {
|
||||
try {
|
||||
var factory = DocumentBuilderFactory.newInstance();
|
||||
factory.setNamespaceAware(true);
|
||||
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
|
||||
factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
|
||||
factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
|
||||
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
|
||||
factory.setExpandEntityReferences(false);
|
||||
Element root = factory.newDocumentBuilder().parse(new ByteArrayInputStream(body)).getDocumentElement();
|
||||
if (!name.equals(root.getLocalName())) malformed();
|
||||
return root;
|
||||
} catch (StoreException error) { throw error; }
|
||||
catch (Exception error) { throw new StoreException(400, "MalformedXML", "Invalid bucket configuration"); }
|
||||
}
|
||||
|
||||
private static Element onlyChild(Element parent, String name) {
|
||||
if (elements(parent) != 1) malformed();
|
||||
return onlyNamedChild(parent, name);
|
||||
}
|
||||
|
||||
private static Element onlyNamedChild(Element parent, String name) {
|
||||
var children = parent.getChildNodes();
|
||||
Element found = null;
|
||||
for (int i = 0; i < children.getLength(); i++) {
|
||||
if (children.item(i) instanceof Element child && name.equals(child.getLocalName())) {
|
||||
if (found != null) malformed();
|
||||
found = child;
|
||||
}
|
||||
}
|
||||
if (found == null) malformed();
|
||||
return found;
|
||||
}
|
||||
|
||||
private static int elements(Element parent) {
|
||||
int count = 0;
|
||||
var children = parent.getChildNodes();
|
||||
for (int i = 0; i < children.getLength(); i++)
|
||||
if (children.item(i) instanceof Element) count++;
|
||||
return count;
|
||||
}
|
||||
|
||||
private static void malformed() {
|
||||
throw new StoreException(400, "MalformedXML", "Invalid bucket configuration");
|
||||
}
|
||||
}
|
||||
@@ -78,12 +78,16 @@ final class ClusterStore implements ObjectStorage, MultipartStorage {
|
||||
|
||||
@Override public Bucket bucket(String name) throws IOException {
|
||||
try (Connection connection = connect(); PreparedStatement query = connection.prepareStatement(
|
||||
"SELECT created_at, versioning_state, acl FROM cluster_buckets WHERE name=?")) {
|
||||
"SELECT created_at, versioning_state, acl, object_ownership, block_public_acls, " +
|
||||
"ignore_public_acls, block_public_policy, restrict_public_buckets, bucket_policy " +
|
||||
"FROM cluster_buckets WHERE name=?")) {
|
||||
query.setString(1, name);
|
||||
try (ResultSet result = query.executeQuery()) {
|
||||
if (!result.next()) throw new StoreException(404, "NoSuchBucket", "Bucket not found");
|
||||
return new Bucket(name, result.getLong(1), VersioningState.valueOf(result.getString(2)),
|
||||
ObjectAttributes.decode(result.getBytes(3)));
|
||||
ObjectAttributes.decode(result.getBytes(3)), ObjectOwnership.valueOf(result.getString(4)),
|
||||
new PublicAccessBlock(result.getBoolean(5), result.getBoolean(6),
|
||||
result.getBoolean(7), result.getBoolean(8)), result.getString(9));
|
||||
}
|
||||
} catch (SQLException error) { throw databaseError(error); }
|
||||
}
|
||||
@@ -91,9 +95,14 @@ final class ClusterStore implements ObjectStorage, MultipartStorage {
|
||||
@Override public List<Bucket> buckets() throws IOException {
|
||||
List<Bucket> result = new ArrayList<>();
|
||||
try (Connection connection = connect(); var query = connection.createStatement();
|
||||
ResultSet rows = query.executeQuery("SELECT name, created_at, versioning_state, acl FROM cluster_buckets ORDER BY name")) {
|
||||
ResultSet rows = query.executeQuery("SELECT name, created_at, versioning_state, acl, " +
|
||||
"object_ownership, block_public_acls, ignore_public_acls, block_public_policy, " +
|
||||
"restrict_public_buckets, bucket_policy FROM cluster_buckets ORDER BY name")) {
|
||||
while (rows.next()) result.add(new Bucket(rows.getString(1), rows.getLong(2),
|
||||
VersioningState.valueOf(rows.getString(3)), ObjectAttributes.decode(rows.getBytes(4))));
|
||||
VersioningState.valueOf(rows.getString(3)), ObjectAttributes.decode(rows.getBytes(4)),
|
||||
ObjectOwnership.valueOf(rows.getString(5)),
|
||||
new PublicAccessBlock(rows.getBoolean(6), rows.getBoolean(7),
|
||||
rows.getBoolean(8), rows.getBoolean(9)), rows.getString(10)));
|
||||
return result;
|
||||
} catch (SQLException error) { throw databaseError(error); }
|
||||
}
|
||||
@@ -133,6 +142,38 @@ final class ClusterStore implements ObjectStorage, MultipartStorage {
|
||||
} catch (SQLException error) { throw databaseError(error); }
|
||||
}
|
||||
|
||||
@Override public void setBucketOwnership(String bucket, ObjectOwnership ownership) throws IOException {
|
||||
updateBucketAccess(bucket, "object_ownership", ownership.name());
|
||||
}
|
||||
|
||||
@Override public void setPublicAccessBlock(String bucket, PublicAccessBlock block) throws IOException {
|
||||
try (Connection connection = connect(); PreparedStatement update = connection.prepareStatement(
|
||||
"UPDATE cluster_buckets SET block_public_acls=?, ignore_public_acls=?, " +
|
||||
"block_public_policy=?, restrict_public_buckets=? WHERE name=?")) {
|
||||
update.setBoolean(1, block.blockPublicAcls());
|
||||
update.setBoolean(2, block.ignorePublicAcls());
|
||||
update.setBoolean(3, block.blockPublicPolicy());
|
||||
update.setBoolean(4, block.restrictPublicBuckets());
|
||||
update.setString(5, bucket);
|
||||
if (update.executeUpdate() == 0)
|
||||
throw new StoreException(404, "NoSuchBucket", "Bucket not found");
|
||||
} catch (SQLException error) { throw databaseError(error); }
|
||||
}
|
||||
|
||||
@Override public void setBucketPolicy(String bucket, String policy) throws IOException {
|
||||
updateBucketAccess(bucket, "bucket_policy", policy);
|
||||
}
|
||||
|
||||
private void updateBucketAccess(String bucket, String column, String value) throws IOException {
|
||||
try (Connection connection = connect(); PreparedStatement update = connection.prepareStatement(
|
||||
"UPDATE cluster_buckets SET " + column + "=? WHERE name=?")) {
|
||||
update.setString(1, value);
|
||||
update.setString(2, bucket);
|
||||
if (update.executeUpdate() == 0)
|
||||
throw new StoreException(404, "NoSuchBucket", "Bucket not found");
|
||||
} catch (SQLException error) { throw databaseError(error); }
|
||||
}
|
||||
|
||||
private static VersioningState versioningState(Connection connection, String bucket) throws SQLException {
|
||||
try (PreparedStatement query = connection.prepareStatement(
|
||||
"SELECT versioning_state FROM cluster_buckets WHERE name=? FOR UPDATE")) {
|
||||
@@ -171,7 +212,9 @@ final class ClusterStore implements ObjectStorage, MultipartStorage {
|
||||
throw new StoreException(400, "TooManyBuckets", "Bucket limit reached");
|
||||
}
|
||||
try (PreparedStatement insert = connection.prepareStatement(
|
||||
"INSERT INTO cluster_buckets (name, created_at) VALUES (?, ?) ON CONFLICT DO NOTHING")) {
|
||||
"INSERT INTO cluster_buckets (name, created_at, object_ownership, block_public_acls, " +
|
||||
"ignore_public_acls, block_public_policy, restrict_public_buckets) " +
|
||||
"VALUES (?, ?, 'BUCKET_OWNER_ENFORCED', true, true, true, true) ON CONFLICT DO NOTHING")) {
|
||||
insert.setString(1, name);
|
||||
insert.setLong(2, Instant.now().toEpochMilli());
|
||||
if (insert.executeUpdate() == 0)
|
||||
@@ -599,17 +642,20 @@ final class ClusterStore implements ObjectStorage, MultipartStorage {
|
||||
throw new StoreException(413, "EntityTooLarge", "Object exceeds the configured size limit");
|
||||
total += part.length();
|
||||
MessageDigest partHash = digest("MD5");
|
||||
java.util.zip.CRC32 partCrc32 = new java.util.zip.CRC32();
|
||||
for (Segment segment : part.segments()) {
|
||||
byte[] bytes = readableSegment(segment);
|
||||
if (bytes == null) throw new StoreException(503, "SlowDown", "A part has no verified replica");
|
||||
fullHash.update(bytes);
|
||||
crc64.update(bytes, 0, bytes.length);
|
||||
partHash.update(bytes);
|
||||
partCrc32.update(bytes, 0, bytes.length);
|
||||
selected.add(segment);
|
||||
}
|
||||
byte[] md5 = partHash.digest();
|
||||
if (!part.etag().equals(HexFormat.of().formatHex(md5)))
|
||||
throw new StoreException(503, "SlowDown", "A part failed integrity verification");
|
||||
requested.verifyCrc32(partCrc32.getValue());
|
||||
etagHash.update(md5);
|
||||
}
|
||||
long replaced = state == VersioningState.ENABLED ? 0 : nullVersionLength(connection, bucket, key);
|
||||
|
||||
@@ -32,6 +32,7 @@ final class DiskStore implements ObjectStorage {
|
||||
private static final int BUCKET_MAGIC = 0x4c534243;
|
||||
private static final int BUCKET_MAGIC_V2 = 0x4c534244;
|
||||
private static final int BUCKET_MAGIC_V3 = 0x4c534245;
|
||||
private static final int BUCKET_MAGIC_V4 = 0x4c534246;
|
||||
private static final int VERSION_MAGIC = 0x4c53564d;
|
||||
private final Path root, objects, temporary, catalog, versions;
|
||||
private final FileChannel lockChannel;
|
||||
@@ -94,7 +95,8 @@ final class DiskStore implements ObjectStorage {
|
||||
if (Files.exists(catalog)) {
|
||||
try (DataInputStream input = new DataInputStream(Files.newInputStream(catalog))) {
|
||||
int magic = input.readInt();
|
||||
if (magic != BUCKET_MAGIC && magic != BUCKET_MAGIC_V2 && magic != BUCKET_MAGIC_V3)
|
||||
if (magic != BUCKET_MAGIC && magic != BUCKET_MAGIC_V2 &&
|
||||
magic != BUCKET_MAGIC_V3 && magic != BUCKET_MAGIC_V4)
|
||||
throw new IOException("Invalid bucket catalog");
|
||||
int count = input.readInt();
|
||||
if (count < 0 || count > 1000) throw new IOException("Invalid bucket catalog");
|
||||
@@ -102,20 +104,35 @@ final class DiskStore implements ObjectStorage {
|
||||
String name = input.readUTF();
|
||||
long created = input.readLong();
|
||||
VersioningState state = VersioningState.NEVER;
|
||||
if (magic == BUCKET_MAGIC_V2 || magic == BUCKET_MAGIC_V3) {
|
||||
if (magic != BUCKET_MAGIC) {
|
||||
int ordinal = input.readUnsignedByte();
|
||||
if (ordinal >= VersioningState.values().length)
|
||||
throw new IOException("Invalid bucket versioning state");
|
||||
state = VersioningState.values()[ordinal];
|
||||
}
|
||||
Map<String, String> acl = Map.of();
|
||||
if (magic == BUCKET_MAGIC_V3) {
|
||||
if (magic == BUCKET_MAGIC_V3 || magic == BUCKET_MAGIC_V4) {
|
||||
int size = input.readUnsignedShort();
|
||||
if (size > ACL_AREA) throw new IOException("Invalid bucket ACL");
|
||||
acl = ObjectAttributes.decode(input.readNBytes(size));
|
||||
}
|
||||
ObjectOwnership ownership = ObjectOwnership.OBJECT_WRITER;
|
||||
PublicAccessBlock block = PublicAccessBlock.open();
|
||||
String policy = null;
|
||||
if (magic == BUCKET_MAGIC_V4) {
|
||||
int ordinal = input.readUnsignedByte();
|
||||
int flags = input.readUnsignedByte();
|
||||
if (ordinal >= ObjectOwnership.values().length || (flags & ~15) != 0)
|
||||
throw new IOException("Invalid bucket access settings");
|
||||
ownership = ObjectOwnership.values()[ordinal];
|
||||
block = new PublicAccessBlock((flags & 1) != 0, (flags & 2) != 0,
|
||||
(flags & 4) != 0, (flags & 8) != 0);
|
||||
policy = input.readUTF();
|
||||
if (policy.isEmpty()) policy = null;
|
||||
}
|
||||
if (!validBucket(name) || created < 0 ||
|
||||
buckets.put(name, new Bucket(name, created, state, acl)) != null)
|
||||
buckets.put(name, new Bucket(name, created, state, acl,
|
||||
ownership, block, policy)) != null)
|
||||
throw new IOException("Invalid bucket catalog");
|
||||
}
|
||||
if (input.read() != -1) throw new IOException("Invalid bucket catalog");
|
||||
@@ -212,7 +229,7 @@ final class DiskStore implements ObjectStorage {
|
||||
Path pending = Files.createTempFile(temporary, "buckets-", ".part");
|
||||
try {
|
||||
try (DataOutputStream output = new DataOutputStream(Files.newOutputStream(pending))) {
|
||||
output.writeInt(BUCKET_MAGIC_V3);
|
||||
output.writeInt(BUCKET_MAGIC_V4);
|
||||
output.writeInt(next.size());
|
||||
for (Bucket entry : next.values()) {
|
||||
output.writeUTF(entry.name());
|
||||
@@ -221,6 +238,13 @@ final class DiskStore implements ObjectStorage {
|
||||
byte[] acl = ObjectAttributes.encode(entry.acl(), ACL_AREA);
|
||||
output.writeShort(acl.length);
|
||||
output.write(acl);
|
||||
output.writeByte(entry.ownership().ordinal());
|
||||
PublicAccessBlock block = entry.publicAccessBlock();
|
||||
output.writeByte((block.blockPublicAcls() ? 1 : 0) |
|
||||
(block.ignorePublicAcls() ? 2 : 0) |
|
||||
(block.blockPublicPolicy() ? 4 : 0) |
|
||||
(block.restrictPublicBuckets() ? 8 : 0));
|
||||
output.writeUTF(entry.policy() == null ? "" : entry.policy());
|
||||
}
|
||||
}
|
||||
try (FileChannel channel = FileChannel.open(pending, StandardOpenOption.WRITE)) { channel.force(true); }
|
||||
@@ -237,7 +261,8 @@ final class DiskStore implements ObjectStorage {
|
||||
if (old.versioning() == VersioningState.NEVER && state == VersioningState.SUSPENDED)
|
||||
throw new StoreException(400, "InvalidArgument", "Enable versioning before suspending it");
|
||||
NavigableMap<String, Bucket> next = new TreeMap<>(buckets);
|
||||
next.put(name, new Bucket(name, old.created(), state, old.acl()));
|
||||
next.put(name, new Bucket(name, old.created(), state, old.acl(),
|
||||
old.ownership(), old.publicAccessBlock(), old.policy()));
|
||||
saveBuckets(next);
|
||||
buckets.clear();
|
||||
buckets.putAll(next);
|
||||
@@ -246,7 +271,37 @@ final class DiskStore implements ObjectStorage {
|
||||
@Override public synchronized void setBucketAcl(String name, Map<String, String> acl) throws IOException {
|
||||
Bucket old = bucket(name);
|
||||
NavigableMap<String, Bucket> next = new TreeMap<>(buckets);
|
||||
next.put(name, new Bucket(name, old.created(), old.versioning(), Map.copyOf(acl)));
|
||||
next.put(name, new Bucket(name, old.created(), old.versioning(), Map.copyOf(acl),
|
||||
old.ownership(), old.publicAccessBlock(), old.policy()));
|
||||
saveBuckets(next);
|
||||
buckets.clear();
|
||||
buckets.putAll(next);
|
||||
}
|
||||
|
||||
@Override public synchronized void setBucketOwnership(String name, ObjectOwnership ownership)
|
||||
throws IOException {
|
||||
Bucket old = bucket(name);
|
||||
updateBucket(new Bucket(name, old.created(), old.versioning(), old.acl(),
|
||||
ownership, old.publicAccessBlock(), old.policy()));
|
||||
}
|
||||
|
||||
@Override public synchronized void setPublicAccessBlock(String name, PublicAccessBlock block)
|
||||
throws IOException {
|
||||
Bucket old = bucket(name);
|
||||
updateBucket(new Bucket(name, old.created(), old.versioning(), old.acl(),
|
||||
old.ownership(), block, old.policy()));
|
||||
}
|
||||
|
||||
@Override public synchronized void setBucketPolicy(String name, String policy)
|
||||
throws IOException {
|
||||
Bucket old = bucket(name);
|
||||
updateBucket(new Bucket(name, old.created(), old.versioning(), old.acl(),
|
||||
old.ownership(), old.publicAccessBlock(), policy));
|
||||
}
|
||||
|
||||
private void updateBucket(Bucket bucket) throws IOException {
|
||||
NavigableMap<String, Bucket> next = new TreeMap<>(buckets);
|
||||
next.put(bucket.name(), bucket);
|
||||
saveBuckets(next);
|
||||
buckets.clear();
|
||||
buckets.putAll(next);
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
final class IdentityPolicies {
|
||||
private IdentityPolicies() { }
|
||||
|
||||
static Map<String, BucketPolicy> fromEnvironment(Map<String, String> env, String owner,
|
||||
Set<String> identities)
|
||||
throws IOException {
|
||||
String configured = env.get("S3_IDENTITY_POLICIES_DIR");
|
||||
if (configured == null || configured.isBlank()) return Map.of();
|
||||
Map<String, BucketPolicy> policies = new HashMap<>();
|
||||
try (var files = Files.newDirectoryStream(Path.of(configured), "*.json")) {
|
||||
for (Path path : files) {
|
||||
String name = path.getFileName().toString();
|
||||
String key = name.substring(0, name.length() - 5);
|
||||
if (!identities.contains(key) || key.equals(owner) || Files.isSymbolicLink(path) ||
|
||||
Files.size(path) > 20480 || policies.size() >= 256)
|
||||
throw new IllegalArgumentException("Invalid identity policy file");
|
||||
String json = Files.readString(path, StandardCharsets.UTF_8);
|
||||
policies.put(key, BucketPolicy.parseIdentity(json));
|
||||
}
|
||||
}
|
||||
return Map.copyOf(policies);
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package cloud.lunarsky.store;
|
||||
|
||||
import com.sun.net.httpserver.HttpExchange;
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
@@ -62,12 +63,29 @@ public final class Main {
|
||||
Main(ObjectStorage store, MultipartStorage multipart, SigV4 authentication, String bucket,
|
||||
ClientLimits clientLimits, int maxInFlight, String virtualHostSuffix,
|
||||
BrowserCors cors, KeyScopes keyScopes, RequestMetrics metrics) throws IOException {
|
||||
this(store, multipart, authentication, bucket, clientLimits, maxInFlight, virtualHostSuffix,
|
||||
cors, keyScopes, metrics, Map.of());
|
||||
}
|
||||
|
||||
Main(ObjectStorage store, MultipartStorage multipart, SigV4 authentication, String bucket,
|
||||
ClientLimits clientLimits, int maxInFlight, String virtualHostSuffix,
|
||||
BrowserCors cors, KeyScopes keyScopes, RequestMetrics metrics,
|
||||
Map<String, BucketPolicy> identityPolicies) throws IOException {
|
||||
this(store, multipart, authentication, bucket, clientLimits, maxInFlight, virtualHostSuffix,
|
||||
cors, keyScopes, metrics, identityPolicies, null);
|
||||
}
|
||||
|
||||
Main(ObjectStorage store, MultipartStorage multipart, SigV4 authentication, String bucket,
|
||||
ClientLimits clientLimits, int maxInFlight, String virtualHostSuffix,
|
||||
BrowserCors cors, KeyScopes keyScopes, RequestMetrics metrics,
|
||||
Map<String, BucketPolicy> identityPolicies, URI publicEndpoint) throws IOException {
|
||||
if (maxInFlight < 1 || maxInFlight > 1024)
|
||||
throw new IllegalArgumentException("MAX_IN_FLIGHT_REQUESTS must be between 1 and 1024");
|
||||
this.store = store;
|
||||
this.authentication = authentication;
|
||||
this.access = new S3Access(store, authentication.root());
|
||||
MultipartHandler multipartHandler = new MultipartHandler(store, multipart, authentication);
|
||||
this.access = new S3Access(store, authentication.root(), identityPolicies);
|
||||
MultipartHandler multipartHandler = new MultipartHandler(store, multipart, authentication, access,
|
||||
publicEndpoint);
|
||||
this.bucketHandler = new BucketHandler(store, multipart, multipartHandler,
|
||||
authentication, access, bucket);
|
||||
this.objectHandler = new ObjectHandler(store, multipartHandler, authentication, access);
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import com.sun.net.httpserver.HttpExchange;
|
||||
import com.sun.net.httpserver.HttpsExchange;
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
@@ -12,13 +14,18 @@ final class MultipartHandler {
|
||||
private final ObjectStorage store;
|
||||
private final MultipartStorage multipart;
|
||||
private final SigV4 authentication;
|
||||
private final S3Access access;
|
||||
private final String owner;
|
||||
private final URI publicEndpoint;
|
||||
|
||||
MultipartHandler(ObjectStorage store, MultipartStorage multipart, SigV4 authentication) {
|
||||
MultipartHandler(ObjectStorage store, MultipartStorage multipart, SigV4 authentication,
|
||||
S3Access access, URI publicEndpoint) {
|
||||
this.store = store;
|
||||
this.multipart = multipart;
|
||||
this.authentication = authentication;
|
||||
this.access = access;
|
||||
this.owner = authentication.root();
|
||||
this.publicEndpoint = publicEndpoint;
|
||||
}
|
||||
|
||||
void handleMultipart(HttpExchange exchange, String method, Map<String, String> query,
|
||||
@@ -36,15 +43,24 @@ final class MultipartHandler {
|
||||
headers.containsKey("x-amz-acl") || headers.keySet().stream().anyMatch(
|
||||
name -> name.toLowerCase(Locale.ROOT).startsWith("x-amz-grant-"))))
|
||||
S3Request.unsupported("Multipart object attributes belong on initiation");
|
||||
boolean initiate = query.containsKey("uploads");
|
||||
if (!method.equals("PUT") && (headers.containsKey("content-md5") ||
|
||||
headers.containsKey("x-amz-sdk-checksum-algorithm") ||
|
||||
headers.keySet().stream().anyMatch(name -> name.toLowerCase(Locale.ROOT).startsWith("x-amz-checksum-"))))
|
||||
headers.keySet().stream().anyMatch(name -> {
|
||||
String lower = name.toLowerCase(Locale.ROOT);
|
||||
return lower.startsWith("x-amz-checksum-") &&
|
||||
!(initiate && lower.equals("x-amz-checksum-algorithm"));
|
||||
})))
|
||||
S3Request.unsupported("Multipart checksum header");
|
||||
if (query.containsKey("uploads")) {
|
||||
if (initiate) {
|
||||
String algorithm = SigV4.single(headers, "x-amz-checksum-algorithm");
|
||||
if (algorithm != null && !algorithm.equals("CRC32"))
|
||||
S3Request.unsupported("Multipart checksum algorithm");
|
||||
S3Request.requireEmptyBody(exchange, hash);
|
||||
Map<String, String> acl = Acl.fromHeaders(headers, authentication.identities());
|
||||
BucketSecurity.checkAcl(store.bucket(bucketName), headers, acl, false);
|
||||
if (!acl.isEmpty() && !owner.equals(verified.principal()))
|
||||
Acl.require(store.bucket(bucketName).acl(), verified.principal(), owner, Acl.WRITE_ACP);
|
||||
access.requireBucket(bucketName, verified.principal(), Acl.WRITE_ACP);
|
||||
String id = multipart.create(bucketName, key, S3Request.contentType(headers),
|
||||
ObjectAttributes.userMetadata(headers),
|
||||
ObjectAttributes.tagsHeader(SigV4.single(headers, "x-amz-tagging")), acl);
|
||||
@@ -77,7 +93,8 @@ final class MultipartHandler {
|
||||
var meta = multipart.complete(id, bucketName, key, parts);
|
||||
if (meta.versionId() != null)
|
||||
exchange.getResponseHeaders().set("x-amz-version-id", meta.versionId());
|
||||
S3Xml.sendXml(exchange, 200, "<CompleteMultipartUploadResult><Bucket>" + S3Xml.xml(bucketName) +
|
||||
S3Xml.sendXml(exchange, 200, "<CompleteMultipartUploadResult><Location>" +
|
||||
S3Xml.xml(location(exchange, bucketName, key)) + "</Location><Bucket>" + S3Xml.xml(bucketName) +
|
||||
"</Bucket><Key>" + S3Xml.xml(key) + "</Key><ETag>"" + meta.etag() +
|
||||
""</ETag></CompleteMultipartUploadResult>");
|
||||
}
|
||||
@@ -94,6 +111,20 @@ final class MultipartHandler {
|
||||
}
|
||||
}
|
||||
|
||||
private String location(HttpExchange exchange, String bucket, String key) {
|
||||
String host = SigV4.single(exchange.getRequestHeaders(), "host");
|
||||
if (host == null) throw new StoreException(400, "InvalidRequest", "Missing Host header");
|
||||
String scheme = exchange instanceof HttpsExchange ? "https" : "http";
|
||||
return objectLocation(publicEndpoint, host, scheme, exchange.getRequestURI().getRawPath(), bucket, key);
|
||||
}
|
||||
|
||||
static String objectLocation(URI endpoint, String host, String scheme, String rawPath,
|
||||
String bucket, String key) {
|
||||
if (endpoint != null)
|
||||
return endpoint + "/" + bucket + "/" + SigV4.encode(key, true);
|
||||
return URI.create(scheme + "://" + host + rawPath).toASCIIString();
|
||||
}
|
||||
|
||||
private void listParts(HttpExchange exchange, String id, String key, Map<String, String> query,
|
||||
String bucketName) throws IOException {
|
||||
int marker = S3Request.boundedNumber(query.get("part-number-marker"), 0, 10000, 0);
|
||||
|
||||
@@ -6,7 +6,16 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
interface MultipartStorage {
|
||||
record Part(int number, String etag) {}
|
||||
record Part(int number, String etag, String checksumCrc32) {
|
||||
Part(int number, String etag) { this(number, etag, null); }
|
||||
|
||||
void verifyCrc32(long value) {
|
||||
if (checksumCrc32 == null) return;
|
||||
byte[] bytes = java.nio.ByteBuffer.allocate(4).putInt((int) value).array();
|
||||
if (!checksumCrc32.equals(java.util.Base64.getEncoder().encodeToString(bytes)))
|
||||
throw new StoreException(400, "BadDigest", "Part CRC32 checksum mismatch");
|
||||
}
|
||||
}
|
||||
record PartInfo(int number, long length, String etag, long modified) {}
|
||||
record PartPage(List<PartInfo> parts, int nextMarker, boolean truncated) {}
|
||||
record UploadInfo(String id, String key, long created) {}
|
||||
|
||||
@@ -155,16 +155,19 @@ final class MultipartStore implements MultipartStorage {
|
||||
total += length;
|
||||
if (total > store.maxObject()) throw new StoreException(413, "EntityTooLarge", "Object exceeds the configured size limit");
|
||||
MessageDigest md5 = digest("MD5");
|
||||
java.util.zip.CRC32 crc32 = new java.util.zip.CRC32();
|
||||
try (var input = Files.newInputStream(file)) {
|
||||
byte[] buffer = new byte[65536];
|
||||
int n;
|
||||
while ((n = input.read(buffer)) != -1) {
|
||||
sha.update(buffer, 0, n);
|
||||
md5.update(buffer, 0, n);
|
||||
crc32.update(buffer, 0, n);
|
||||
}
|
||||
}
|
||||
if (!SigV4.hex(md5.digest()).equals(part.etag().replace("\"", "")))
|
||||
throw new StoreException(400, "InvalidPart", "Part ETag mismatch");
|
||||
part.verifyCrc32(crc32.getValue());
|
||||
paths.add(file);
|
||||
}
|
||||
ObjectStorage.Metadata result;
|
||||
|
||||
@@ -42,15 +42,20 @@ final class ObjectHandler {
|
||||
try (var object = store.open(bucketName, key, versionId)) {
|
||||
var metadata = object.metadata();
|
||||
if (method.equals("GET")) {
|
||||
Acl.require(metadata.acl(), principal, owner, Acl.READ_ACP);
|
||||
access.requireObject(bucketName, key, metadata, principal, Acl.READ_ACP,
|
||||
versionId == null ? "s3:GetObjectAcl" : "s3:GetObjectVersionAcl");
|
||||
S3Request.requireEmptyBody(exchange, hash);
|
||||
S3Xml.sendXml(exchange, 200, Acl.xml(metadata.acl(), owner));
|
||||
S3Xml.sendXml(exchange, 200, Acl.xml(
|
||||
store.bucket(bucketName).ownership() == ObjectStorage.ObjectOwnership.BUCKET_OWNER_ENFORCED
|
||||
? Map.of() : metadata.acl(), owner));
|
||||
} else {
|
||||
if (!owner.equals(principal)) {
|
||||
if (metadata.versionId() == null || metadata.versionId().equals("null"))
|
||||
throw new StoreException(403, "AccessDenied", "Access denied");
|
||||
Acl.require(metadata.acl(), principal, owner, Acl.WRITE_ACP);
|
||||
}
|
||||
if (store.bucket(bucketName).ownership() == ObjectStorage.ObjectOwnership.BUCKET_OWNER_ENFORCED)
|
||||
throw new StoreException(400, "AccessControlListNotSupported", "ACLs are disabled for this bucket");
|
||||
if (!owner.equals(principal) &&
|
||||
(metadata.versionId() == null || metadata.versionId().equals("null")))
|
||||
throw new StoreException(403, "AccessDenied", "Access denied");
|
||||
access.requireObject(bucketName, key, metadata, principal, Acl.WRITE_ACP,
|
||||
versionId == null ? "s3:PutObjectAcl" : "s3:PutObjectVersionAcl");
|
||||
Map<String, String> acl;
|
||||
if (exchange.getRequestHeaders().containsKey("x-amz-acl") ||
|
||||
exchange.getRequestHeaders().keySet().stream().anyMatch(
|
||||
@@ -63,6 +68,7 @@ final class ObjectHandler {
|
||||
S3Request.verifyContentMd5(exchange.getRequestHeaders(), body);
|
||||
acl = Acl.fromXml(body, owner, authentication.identities());
|
||||
}
|
||||
BucketSecurity.checkAcl(store.bucket(bucketName), exchange.getRequestHeaders(), acl, true);
|
||||
store.setObjectAcl(bucketName, key, metadata.versionId(), acl);
|
||||
exchange.sendResponseHeaders(200, -1);
|
||||
}
|
||||
@@ -84,12 +90,18 @@ final class ObjectHandler {
|
||||
return;
|
||||
}
|
||||
boolean multipartRequest = S3Request.multipartRequest(method, query);
|
||||
boolean copy = exchange.getRequestHeaders().containsKey("x-amz-copy-source");
|
||||
boolean versionRequest = (method.equals("GET") || method.equals("HEAD") || method.equals("DELETE")) &&
|
||||
query.containsKey("versionId") && (query.size() == 1 || query.size() == 2 && query.containsKey("x-id"));
|
||||
if (versionRequest && query.containsKey("x-id") &&
|
||||
!(method.equals("GET") ? "GetObject" : method.equals("HEAD") ? "HeadObject" : "DeleteObject")
|
||||
.equals(query.get("x-id"))) S3Request.unsupported("Version query operation");
|
||||
if (!multipartRequest && !versionRequest && !query.isEmpty() && !(query.size() == 1 &&
|
||||
boolean directUploadQuery = method.equals("PUT") && !copy &&
|
||||
(query.get("x-id") == null || query.get("x-id").equals("PutObject")) &&
|
||||
query.keySet().stream().allMatch(name -> name.equals("x-id") ||
|
||||
name.equals("x-amz-sdk-checksum-algorithm") ||
|
||||
name.startsWith("x-amz-checksum-") && name.equals(name.toLowerCase(Locale.ROOT)));
|
||||
if (!multipartRequest && !versionRequest && !query.isEmpty() && !directUploadQuery && !(query.size() == 1 &&
|
||||
("PutObject".equals(query.get("x-id")) || "CopyObject".equals(query.get("x-id")) ||
|
||||
"GetObject".equals(query.get("x-id")) ||
|
||||
"HeadObject".equals(query.get("x-id")) || "DeleteObject".equals(query.get("x-id")))))
|
||||
@@ -97,11 +109,11 @@ final class ObjectHandler {
|
||||
S3Request.validateObjectHeaders(exchange.getRequestHeaders());
|
||||
if (multipartRequest) {
|
||||
if (method.equals("GET")) access.requireOwner(principal);
|
||||
else access.requireBucket(bucketName, principal, Acl.WRITE);
|
||||
else access.requireWrite(bucketName, key, principal,
|
||||
method.equals("DELETE") ? "s3:AbortMultipartUpload" : "s3:PutObject");
|
||||
multipartHandler.handleMultipart(exchange, method, query, key, verified, bucketName);
|
||||
return;
|
||||
}
|
||||
boolean copy = exchange.getRequestHeaders().containsKey("x-amz-copy-source");
|
||||
if (!method.equals("PUT") && (copy || exchange.getRequestHeaders().containsKey("content-md5") ||
|
||||
exchange.getRequestHeaders().containsKey("x-amz-metadata-directive") ||
|
||||
exchange.getRequestHeaders().containsKey("x-amz-tagging") ||
|
||||
@@ -114,13 +126,14 @@ final class ObjectHandler {
|
||||
if (!method.equals("PUT") || copy) S3Request.requireEmptyBody(exchange, hash);
|
||||
switch (method) {
|
||||
case "PUT" -> {
|
||||
access.requireBucket(bucketName, principal, Acl.WRITE);
|
||||
access.requireWrite(bucketName, key, principal, "s3:PutObject");
|
||||
if (copy) copyObject(exchange, key, bucketName, principal);
|
||||
else putObject(exchange, key, verified, bucketName);
|
||||
else putObject(exchange, key, verified, bucketName, query);
|
||||
}
|
||||
case "GET", "HEAD" -> readObject(exchange, key, bucketName, query.get("versionId"), principal);
|
||||
case "DELETE" -> {
|
||||
access.requireBucket(bucketName, principal, Acl.WRITE);
|
||||
access.requireWrite(bucketName, key, principal,
|
||||
query.get("versionId") == null ? "s3:DeleteObject" : "s3:DeleteObjectVersion");
|
||||
deleteObject(exchange, key, bucketName, query.get("versionId"));
|
||||
}
|
||||
default -> S3Request.unsupported("HTTP method");
|
||||
@@ -128,7 +141,7 @@ final class ObjectHandler {
|
||||
}
|
||||
|
||||
private void putObject(HttpExchange exchange, String key, SigV4.Verified verified,
|
||||
String bucketName) throws IOException {
|
||||
String bucketName, Map<String, String> query) throws IOException {
|
||||
var headers = exchange.getRequestHeaders();
|
||||
String length = SigV4.single(headers, "content-length"), condition = SigV4.single(headers, "if-none-match");
|
||||
if (condition != null && !condition.equals("*")) S3Request.unsupported("Write condition");
|
||||
@@ -138,7 +151,7 @@ final class ObjectHandler {
|
||||
if (!verified.streaming() && headers.containsKey("content-encoding")) S3Request.unsupported("Encoded payload");
|
||||
if (headers.containsKey("x-amz-metadata-directive")) S3Request.unsupported("Copy metadata directive");
|
||||
if (headers.containsKey("x-amz-tagging-directive")) S3Request.unsupported("Copy tagging directive");
|
||||
UploadChecksums checksums = UploadChecksums.from(headers);
|
||||
UploadChecksums checksums = S3Request.uploadChecksums(headers, query);
|
||||
AwsChunkedInputStream chunked = verified.streaming() ? S3Request.chunkedBody(exchange, verified) : null;
|
||||
if (chunked != null) bytes = S3Request.decodedLength(headers);
|
||||
else if (headers.containsKey("x-amz-decoded-content-length") || headers.containsKey("x-amz-trailer"))
|
||||
@@ -147,6 +160,7 @@ final class ObjectHandler {
|
||||
Map<String, String> metadata = ObjectAttributes.userMetadata(headers);
|
||||
Map<String, String> tags = ObjectAttributes.tagsHeader(SigV4.single(headers, "x-amz-tagging"));
|
||||
Map<String, String> acl = Acl.fromHeaders(headers, authentication.identities());
|
||||
BucketSecurity.checkAcl(store.bucket(bucketName), headers, acl, false);
|
||||
if (!acl.isEmpty() && !owner.equals(verified.principal()))
|
||||
access.requireBucket(bucketName, verified.principal(), Acl.WRITE_ACP);
|
||||
ObjectStorage.Metadata data = store.put(bucketName, key,
|
||||
@@ -197,8 +211,6 @@ final class ObjectHandler {
|
||||
String directive = SigV4.single(headers, "x-amz-metadata-directive");
|
||||
if (directive != null && !directive.equals("COPY") && !directive.equals("REPLACE"))
|
||||
throw new StoreException(400, "InvalidArgument", "Invalid metadata directive");
|
||||
if (!"REPLACE".equals(directive) && headers.containsKey("content-type"))
|
||||
S3Request.unsupported("Content-Type requires REPLACE metadata directive");
|
||||
String tagDirective = SigV4.single(headers, "x-amz-tagging-directive");
|
||||
if (tagDirective != null && !tagDirective.equals("COPY") && !tagDirective.equals("REPLACE"))
|
||||
throw new StoreException(400, "InvalidArgument", "Invalid tagging directive");
|
||||
@@ -208,7 +220,8 @@ final class ObjectHandler {
|
||||
S3Request.unsupported("User metadata requires REPLACE metadata directive");
|
||||
try (var object = store.open(sourceBucket, sourceKey, sourceVersion)) {
|
||||
var sourceMetadata = object.metadata();
|
||||
Acl.require(sourceMetadata.acl(), principal, owner, Acl.READ);
|
||||
access.requireObject(sourceBucket, sourceKey, sourceMetadata, principal, Acl.READ,
|
||||
sourceVersion == null ? "s3:GetObject" : "s3:GetObjectVersion");
|
||||
if (sourceMetadata.versionId() != null)
|
||||
exchange.getResponseHeaders().set("x-amz-copy-source-version-id", sourceMetadata.versionId());
|
||||
String type = "REPLACE".equals(directive) ? S3Request.contentType(headers) : sourceMetadata.contentType();
|
||||
@@ -217,6 +230,7 @@ final class ObjectHandler {
|
||||
Map<String, String> tags = "REPLACE".equals(tagDirective)
|
||||
? ObjectAttributes.tagsHeader(SigV4.single(headers, "x-amz-tagging")) : sourceMetadata.tags();
|
||||
Map<String, String> acl = Acl.fromHeaders(headers, authentication.identities());
|
||||
BucketSecurity.checkAcl(store.bucket(bucketName), headers, acl, false);
|
||||
if (!acl.isEmpty() && !owner.equals(principal))
|
||||
access.requireBucket(bucketName, principal, Acl.WRITE_ACP);
|
||||
var copied = store.put(bucketName, key, object.stream(), sourceMetadata.length(),
|
||||
@@ -283,7 +297,8 @@ final class ObjectHandler {
|
||||
headers.containsKey("if-unmodified-since")) S3Request.unsupported("Conditional read");
|
||||
try (var object = store.open(bucketName, key, versionId)) {
|
||||
var meta = object.metadata();
|
||||
Acl.require(meta.acl(), principal, owner, Acl.READ);
|
||||
access.requireObject(bucketName, key, meta, principal, Acl.READ,
|
||||
versionId == null ? "s3:GetObject" : "s3:GetObjectVersion");
|
||||
String etag = "\"" + meta.etag() + "\"";
|
||||
String noneMatch = SigV4.single(headers, "if-none-match");
|
||||
if (noneMatch != null && (noneMatch.equals("*") ||
|
||||
|
||||
@@ -8,9 +8,23 @@ import java.util.Map;
|
||||
/** Storage operations shared by the local and cluster gateways. */
|
||||
interface ObjectStorage extends AutoCloseable {
|
||||
enum VersioningState { NEVER, ENABLED, SUSPENDED }
|
||||
enum ObjectOwnership { BUCKET_OWNER_ENFORCED, BUCKET_OWNER_PREFERRED, OBJECT_WRITER }
|
||||
record PublicAccessBlock(boolean blockPublicAcls, boolean ignorePublicAcls,
|
||||
boolean blockPublicPolicy, boolean restrictPublicBuckets) {
|
||||
static PublicAccessBlock secure() { return new PublicAccessBlock(true, true, true, true); }
|
||||
static PublicAccessBlock open() { return new PublicAccessBlock(false, false, false, false); }
|
||||
}
|
||||
record Limits(long maxObjectBytes, long maxTotalBytes) {}
|
||||
record Bucket(String name, long created, VersioningState versioning, Map<String, String> acl) {
|
||||
Bucket(String name, long created) { this(name, created, VersioningState.NEVER, Map.of()); }
|
||||
record Bucket(String name, long created, VersioningState versioning, Map<String, String> acl,
|
||||
ObjectOwnership ownership, PublicAccessBlock publicAccessBlock, String policy) {
|
||||
Bucket(String name, long created) {
|
||||
this(name, created, VersioningState.NEVER, Map.of(),
|
||||
ObjectOwnership.BUCKET_OWNER_ENFORCED, PublicAccessBlock.secure(), null);
|
||||
}
|
||||
Bucket(String name, long created, VersioningState versioning, Map<String, String> acl) {
|
||||
this(name, created, versioning, acl,
|
||||
ObjectOwnership.OBJECT_WRITER, PublicAccessBlock.open(), null);
|
||||
}
|
||||
Bucket(String name, long created, VersioningState versioning) {
|
||||
this(name, created, versioning, Map.of());
|
||||
}
|
||||
@@ -114,6 +128,9 @@ interface ObjectStorage extends AutoCloseable {
|
||||
void createBucket(String bucket) throws IOException;
|
||||
void deleteBucket(String bucket) throws IOException;
|
||||
void setBucketAcl(String bucket, Map<String, String> acl) throws IOException;
|
||||
void setBucketOwnership(String bucket, ObjectOwnership ownership) throws IOException;
|
||||
void setPublicAccessBlock(String bucket, PublicAccessBlock block) throws IOException;
|
||||
void setBucketPolicy(String bucket, String policy) throws IOException;
|
||||
void setObjectAcl(String bucket, String key, String versionId, Map<String, String> acl) throws IOException;
|
||||
Limits limits();
|
||||
default boolean ready() { return true; }
|
||||
|
||||
@@ -44,12 +44,17 @@ final class ObjectStoreServer {
|
||||
multipart = new MultipartStore(disk);
|
||||
} else throw new IllegalArgumentException("Invalid STORE_MODE");
|
||||
Map<String, String> identities = identities(env, access, secret);
|
||||
var app = new Main(store, multipart, new SigV4(identities,
|
||||
var sessions = SessionCredentials.fromEnvironment(env, identities.keySet());
|
||||
var allIdentities = new java.util.HashSet<>(identities.keySet());
|
||||
allIdentities.addAll(sessions.keySet());
|
||||
var app = new Main(store, multipart, new SigV4(identities, sessions,
|
||||
access, region, Clock.systemUTC()), bucket, ClientLimits.fromEnvironment(env),
|
||||
positiveInt(env, "MAX_IN_FLIGHT_REQUESTS", 16, 1024),
|
||||
env.getOrDefault("S3_VIRTUAL_HOST_SUFFIX", ""), BrowserCors.fromEnvironment(env),
|
||||
KeyScopes.fromEnvironment(env, access, identities.keySet()),
|
||||
new RequestMetrics(env.get("METRICS_BEARER_TOKEN")));
|
||||
KeyScopes.fromEnvironment(env, access, allIdentities),
|
||||
new RequestMetrics(env.get("METRICS_BEARER_TOKEN")),
|
||||
IdentityPolicies.fromEnvironment(env, access, allIdentities),
|
||||
publicEndpoint(env));
|
||||
int port = Integer.parseInt(env.getOrDefault("PORT", "9000"));
|
||||
var server = HttpServer.create(mode.equals("cluster")
|
||||
? new InetSocketAddress(env.getOrDefault("BIND_ADDRESS", "127.0.0.1"), port)
|
||||
@@ -88,6 +93,22 @@ final class ObjectStoreServer {
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
static URI publicEndpoint(Map<String, String> env) {
|
||||
String configured = env.get("S3_PUBLIC_ENDPOINT");
|
||||
if (configured == null || configured.isBlank()) return null;
|
||||
URI uri;
|
||||
try { uri = URI.create(configured); }
|
||||
catch (IllegalArgumentException error) {
|
||||
throw new IllegalArgumentException("Invalid S3_PUBLIC_ENDPOINT", error);
|
||||
}
|
||||
if (!"http".equals(uri.getScheme()) && !"https".equals(uri.getScheme()) ||
|
||||
uri.getHost() == null || uri.getUserInfo() != null || uri.getRawQuery() != null ||
|
||||
uri.getRawFragment() != null ||
|
||||
!(uri.getRawPath().isEmpty() || uri.getRawPath().equals("/")))
|
||||
throw new IllegalArgumentException("S3_PUBLIC_ENDPOINT must be an HTTP(S) origin");
|
||||
return URI.create(configured.endsWith("/") ? configured.substring(0, configured.length() - 1) : configured);
|
||||
}
|
||||
private static void printStartup(DiskStore store, MultipartStorage multipart,
|
||||
String bucket, String region, int port) {
|
||||
System.out.println(" *");
|
||||
|
||||
@@ -1,14 +1,23 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
final class S3Access {
|
||||
private final ObjectStorage store;
|
||||
private final String owner;
|
||||
private final java.util.Map<String, BucketPolicy> identityPolicies;
|
||||
private final ConcurrentHashMap<String, CachedPolicy> policies = new ConcurrentHashMap<>();
|
||||
private record CachedPolicy(String source, BucketPolicy parsed) { }
|
||||
|
||||
S3Access(ObjectStorage store, String owner) {
|
||||
this(store, owner, java.util.Map.of());
|
||||
}
|
||||
|
||||
S3Access(ObjectStorage store, String owner, java.util.Map<String, BucketPolicy> identityPolicies) {
|
||||
this.store = store;
|
||||
this.owner = owner;
|
||||
this.identityPolicies = java.util.Map.copyOf(identityPolicies);
|
||||
}
|
||||
|
||||
String owner() {
|
||||
@@ -20,6 +29,45 @@ final class S3Access {
|
||||
}
|
||||
|
||||
void requireBucket(String bucket, String principal, int permission) throws IOException {
|
||||
Acl.require(store.bucket(bucket).acl(), principal, owner, permission);
|
||||
var current = store.bucket(bucket);
|
||||
String action = permission == Acl.READ ? "s3:ListBucket" :
|
||||
permission == Acl.READ_ACP ? "s3:GetBucketAcl" :
|
||||
permission == Acl.WRITE_ACP ? "s3:PutBucketAcl" : "s3:PutObject";
|
||||
require(current, current.acl(), principal, permission, action, null);
|
||||
}
|
||||
|
||||
void requireWrite(String bucket, String key, String principal, String action) throws IOException {
|
||||
var current = store.bucket(bucket);
|
||||
require(current, current.acl(), principal, Acl.WRITE, action, key);
|
||||
}
|
||||
|
||||
void requireObject(String bucket, String key, ObjectStorage.Metadata metadata,
|
||||
String principal, int permission, String action) throws IOException {
|
||||
require(store.bucket(bucket), metadata.acl(), principal, permission, action, key);
|
||||
}
|
||||
|
||||
private void require(ObjectStorage.Bucket bucket, java.util.Map<String, String> acl,
|
||||
String principal, int permission, String action, String key) {
|
||||
String resource = "arn:aws:s3:::" + bucket.name() + (key == null ? "" : "/" + key);
|
||||
BucketPolicy policy = policy(bucket);
|
||||
int decision = policy.decide(principal, action, resource);
|
||||
int identityDecision = principal == null ? 0 :
|
||||
identityPolicies.getOrDefault(principal, BucketPolicy.empty()).decide(principal, action, resource);
|
||||
if (decision < 0 || identityDecision < 0 ||
|
||||
!BucketSecurity.allowsAcl(bucket, acl, principal, owner, permission) &&
|
||||
identityDecision <= 0 &&
|
||||
!(decision > 0 && (principal != null || !bucket.publicAccessBlock().restrictPublicBuckets() ||
|
||||
!policy.publicAllow())))
|
||||
throw new StoreException(403, "AccessDenied", "Access denied");
|
||||
}
|
||||
|
||||
private BucketPolicy policy(ObjectStorage.Bucket bucket) {
|
||||
String source = bucket.policy();
|
||||
if (source == null) return BucketPolicy.empty();
|
||||
CachedPolicy cached = policies.get(bucket.name());
|
||||
if (cached != null && cached.source().equals(source)) return cached.parsed();
|
||||
BucketPolicy parsed = BucketPolicy.parse(source, bucket.name());
|
||||
policies.put(bucket.name(), new CachedPolicy(source, parsed));
|
||||
return parsed;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import com.sun.net.httpserver.HttpExchange;
|
||||
import com.sun.net.httpserver.Headers;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
@@ -15,6 +16,7 @@ final class S3Request {
|
||||
for (String name : headers.keySet()) {
|
||||
String lower = name.toLowerCase(java.util.Locale.ROOT);
|
||||
if (lower.startsWith("x-amz-") && !lower.startsWith("x-amz-meta-") && !java.util.Set.of("x-amz-date", "x-amz-content-sha256",
|
||||
"x-amz-security-token",
|
||||
"x-amz-sdk-checksum-algorithm", "x-amz-user-agent", "x-amz-copy-source",
|
||||
"x-amz-metadata-directive", "x-amz-tagging", "x-amz-tagging-directive",
|
||||
"x-amz-decoded-content-length", "x-amz-trailer", "x-amz-checksum-mode",
|
||||
@@ -40,6 +42,19 @@ final class S3Request {
|
||||
throw new StoreException(400, "BadDigest", "Content-MD5 mismatch");
|
||||
} catch (java.security.NoSuchAlgorithmException error) { throw new IllegalStateException(error); }
|
||||
}
|
||||
static UploadChecksums uploadChecksums(Headers headers, Map<String, String> query) {
|
||||
if (query.keySet().stream().noneMatch(name -> name.startsWith("x-amz-checksum-") ||
|
||||
name.equals("x-amz-sdk-checksum-algorithm"))) return UploadChecksums.from(headers);
|
||||
Headers combined = new Headers();
|
||||
headers.forEach((name, values) -> combined.put(name, java.util.List.copyOf(values)));
|
||||
query.forEach((name, value) -> {
|
||||
if (!name.startsWith("x-amz-checksum-") && !name.equals("x-amz-sdk-checksum-algorithm")) return;
|
||||
if (combined.containsKey(name))
|
||||
throw new StoreException(400, "InvalidRequest", "Duplicate checksum in query and header");
|
||||
combined.set(name, value);
|
||||
});
|
||||
return UploadChecksums.from(combined);
|
||||
}
|
||||
static String contentType(com.sun.net.httpserver.Headers headers) {
|
||||
String value = SigV4.single(headers, "content-type");
|
||||
if (value == null) return "application/octet-stream";
|
||||
|
||||
@@ -77,17 +77,23 @@ final class S3Xml {
|
||||
for (int i = 0; i < nodes.getLength(); i++) {
|
||||
if (!(nodes.item(i) instanceof org.w3c.dom.Element element)) continue;
|
||||
if (!element.getTagName().equals("Part")) throw new IllegalArgumentException();
|
||||
String number = null, etag = null;
|
||||
String number = null, etag = null, checksumCrc32 = null;
|
||||
var fields = element.getChildNodes();
|
||||
for (int j = 0; j < fields.getLength(); j++) {
|
||||
if (!(fields.item(j) instanceof org.w3c.dom.Element field)) continue;
|
||||
if (field.getTagName().equals("PartNumber")) number = field.getTextContent().trim();
|
||||
else if (field.getTagName().equals("ETag")) etag = field.getTextContent().trim();
|
||||
if (field.getTagName().equals("PartNumber") && number == null)
|
||||
number = field.getTextContent().trim();
|
||||
else if (field.getTagName().equals("ETag") && etag == null)
|
||||
etag = field.getTextContent().trim();
|
||||
else if (field.getTagName().equals("ChecksumCRC32") && checksumCrc32 == null)
|
||||
checksumCrc32 = field.getTextContent().trim();
|
||||
else throw new IllegalArgumentException();
|
||||
}
|
||||
if (number == null || etag == null || !etag.matches("\"?[0-9a-f]{32}\"?"))
|
||||
throw new IllegalArgumentException();
|
||||
parts.add(new MultipartStorage.Part(Integer.parseInt(number), etag));
|
||||
if (checksumCrc32 != null && java.util.Base64.getDecoder().decode(checksumCrc32).length != 4)
|
||||
throw new IllegalArgumentException();
|
||||
parts.add(new MultipartStorage.Part(Integer.parseInt(number), etag, checksumCrc32));
|
||||
if (parts.size() > 10000) throw new IllegalArgumentException();
|
||||
}
|
||||
return parts;
|
||||
|
||||
@@ -21,7 +21,7 @@ final class SchemaMigrator {
|
||||
result.next();
|
||||
version = result.getInt(1);
|
||||
}
|
||||
if (version > 10) throw new IOException("Metadata schema is newer than this ObjectStore build");
|
||||
if (version > 11) throw new IOException("Metadata schema is newer than this ObjectStore build");
|
||||
if (version < 1) {
|
||||
statement.execute("CREATE TABLE IF NOT EXISTS cluster_usage (bucket text PRIMARY KEY, used_bytes bigint NOT NULL CHECK (used_bytes >= 0))");
|
||||
statement.execute("CREATE TABLE IF NOT EXISTS cluster_objects (bucket text NOT NULL, object_key text COLLATE \"C\" NOT NULL, generation uuid NOT NULL, length bigint NOT NULL, modified bigint NOT NULL, etag text NOT NULL, sha256 bytea NOT NULL, content_type text NOT NULL, PRIMARY KEY (bucket, object_key))");
|
||||
@@ -98,6 +98,17 @@ final class SchemaMigrator {
|
||||
statement.execute("ALTER TABLE cluster_uploads ADD COLUMN acl bytea");
|
||||
statement.execute("INSERT INTO cluster_schema_migrations VALUES (10)");
|
||||
}
|
||||
if (version < 11) {
|
||||
statement.execute("ALTER TABLE cluster_buckets ADD COLUMN object_ownership text NOT NULL " +
|
||||
"DEFAULT 'OBJECT_WRITER' CHECK (object_ownership IN " +
|
||||
"('BUCKET_OWNER_ENFORCED', 'BUCKET_OWNER_PREFERRED', 'OBJECT_WRITER'))");
|
||||
statement.execute("ALTER TABLE cluster_buckets ADD COLUMN block_public_acls boolean NOT NULL DEFAULT false");
|
||||
statement.execute("ALTER TABLE cluster_buckets ADD COLUMN ignore_public_acls boolean NOT NULL DEFAULT false");
|
||||
statement.execute("ALTER TABLE cluster_buckets ADD COLUMN block_public_policy boolean NOT NULL DEFAULT false");
|
||||
statement.execute("ALTER TABLE cluster_buckets ADD COLUMN restrict_public_buckets boolean NOT NULL DEFAULT false");
|
||||
statement.execute("ALTER TABLE cluster_buckets ADD COLUMN bucket_policy text");
|
||||
statement.execute("INSERT INTO cluster_schema_migrations VALUES (11)");
|
||||
}
|
||||
statement.execute("INSERT INTO cluster_format SELECT 1, CASE WHEN EXISTS (SELECT 1 FROM cluster_segments WHERE replica_ids IS NULL) THEN 1 ELSE 2 END WHERE NOT EXISTS (SELECT 1 FROM cluster_format)");
|
||||
}
|
||||
try (PreparedStatement insert = connection.prepareStatement("INSERT INTO cluster_usage VALUES (?, 0) ON CONFLICT DO NOTHING")) {
|
||||
@@ -105,7 +116,9 @@ final class SchemaMigrator {
|
||||
insert.executeUpdate();
|
||||
}
|
||||
try (PreparedStatement insert = connection.prepareStatement(
|
||||
"INSERT INTO cluster_buckets (name, created_at) VALUES (?, ?) ON CONFLICT DO NOTHING")) {
|
||||
"INSERT INTO cluster_buckets (name, created_at, object_ownership, block_public_acls, " +
|
||||
"ignore_public_acls, block_public_policy, restrict_public_buckets) " +
|
||||
"VALUES (?, ?, 'BUCKET_OWNER_ENFORCED', true, true, true, true) ON CONFLICT DO NOTHING")) {
|
||||
insert.setString(1, bucket);
|
||||
insert.setLong(2, System.currentTimeMillis());
|
||||
insert.executeUpdate();
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Instant;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
final class SessionCredentials {
|
||||
record Session(String secret, String token, Instant expires) { }
|
||||
|
||||
private SessionCredentials() { }
|
||||
|
||||
static Map<String, Session> fromEnvironment(Map<String, String> env, java.util.Set<String> permanent)
|
||||
throws IOException {
|
||||
String file = env.get("S3_SESSION_CREDENTIALS_FILE");
|
||||
if (file == null || file.isBlank()) return Map.of();
|
||||
var lines = Files.readAllLines(Path.of(file), StandardCharsets.UTF_8);
|
||||
if (lines.size() > 256) throw new IllegalArgumentException("Too many session credentials");
|
||||
Map<String, Session> sessions = new HashMap<>();
|
||||
for (String line : lines) {
|
||||
if (line.isBlank() || line.startsWith("#")) continue;
|
||||
String[] fields = line.split("\\t", -1);
|
||||
if (fields.length != 4 || !fields[0].matches("[A-Za-z0-9]{16,128}") ||
|
||||
permanent.contains(fields[0]) || fields[1].length() < 32 ||
|
||||
fields[2].length() < 32 || fields[2].length() > 2048 ||
|
||||
fields[2].indexOf('\n') >= 0 || fields[2].indexOf('\r') >= 0)
|
||||
throw new IllegalArgumentException("Invalid session credential entry");
|
||||
Instant expires;
|
||||
try { expires = Instant.ofEpochSecond(Long.parseLong(fields[3])); }
|
||||
catch (RuntimeException error) { throw new IllegalArgumentException("Invalid session expiry", error); }
|
||||
if (sessions.putIfAbsent(fields[0], new Session(fields[1], fields[2], expires)) != null)
|
||||
throw new IllegalArgumentException("Duplicate session credential");
|
||||
}
|
||||
return Map.copyOf(sessions);
|
||||
}
|
||||
}
|
||||
@@ -30,6 +30,7 @@ final class SigV4 {
|
||||
private static final DateTimeFormatter DATE = DateTimeFormatter.ofPattern("uuuuMMdd'T'HHmmss'Z'").withZone(ZoneOffset.UTC);
|
||||
private static final Pattern HEX = Pattern.compile("[0-9a-f]{64}");
|
||||
private final Map<String, String> identities;
|
||||
private final Map<String, SessionCredentials.Session> sessions;
|
||||
private final String root;
|
||||
private final String region;
|
||||
private final Clock clock;
|
||||
@@ -39,15 +40,27 @@ final class SigV4 {
|
||||
}
|
||||
|
||||
SigV4(Map<String, String> identities, String root, String region, Clock clock) {
|
||||
this(identities, Map.of(), root, region, clock);
|
||||
}
|
||||
|
||||
SigV4(Map<String, String> identities, Map<String, SessionCredentials.Session> sessions,
|
||||
String root, String region, Clock clock) {
|
||||
this.identities = Map.copyOf(identities);
|
||||
this.sessions = Map.copyOf(sessions);
|
||||
if (!this.identities.containsKey(root)) throw new IllegalArgumentException("Missing root identity");
|
||||
if (this.sessions.keySet().stream().anyMatch(this.identities::containsKey))
|
||||
throw new IllegalArgumentException("Session and permanent keys overlap");
|
||||
this.root = root;
|
||||
this.region = region;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
String root() { return root; }
|
||||
Set<String> identities() { return identities.keySet(); }
|
||||
Set<String> identities() {
|
||||
var all = new java.util.HashSet<>(identities.keySet());
|
||||
all.addAll(sessions.keySet());
|
||||
return Set.copyOf(all);
|
||||
}
|
||||
|
||||
String verify(String method, URI uri, Headers headers) {
|
||||
return verifyRequest(method, uri, headers).payload();
|
||||
@@ -57,6 +70,7 @@ final class SigV4 {
|
||||
if (hasPresignedQuery(uri.getRawQuery())) return verifyPresigned(method, uri, headers);
|
||||
Map<String, String> fields = authorizationFields(headers);
|
||||
String[] credential = credentialScope(fields.get("Credential"));
|
||||
validateSession(credential[0], single(headers, "x-amz-security-token"));
|
||||
String date = signingDate(headers, credential[1]);
|
||||
String payload = payloadHash(headers);
|
||||
String signedHeaders = fields.get("SignedHeaders");
|
||||
@@ -76,11 +90,19 @@ final class SigV4 {
|
||||
if (headers.containsKey("authorization")) denied("Use one authentication method");
|
||||
PresignedQuery query = presignedQuery(uri.getRawQuery());
|
||||
Map<String, String> fields = query.fields();
|
||||
if (!fields.keySet().equals(Set.of("X-Amz-Algorithm", "X-Amz-Credential", "X-Amz-Date",
|
||||
"X-Amz-Expires", "X-Amz-SignedHeaders", "X-Amz-Signature")) ||
|
||||
Set<String> expected = Set.of("X-Amz-Algorithm", "X-Amz-Credential", "X-Amz-Date",
|
||||
"X-Amz-Expires", "X-Amz-SignedHeaders", "X-Amz-Signature");
|
||||
Set<String> allowed = new java.util.HashSet<>(expected);
|
||||
allowed.add("X-Amz-Security-Token");
|
||||
allowed.add("X-Amz-Content-Sha256");
|
||||
if (!fields.keySet().containsAll(expected) || !allowed.containsAll(fields.keySet()) ||
|
||||
fields.containsKey("X-Amz-Content-Sha256") &&
|
||||
!"UNSIGNED-PAYLOAD".equals(fields.get("X-Amz-Content-Sha256")) ||
|
||||
!"AWS4-HMAC-SHA256".equals(fields.get("X-Amz-Algorithm")))
|
||||
denied("Invalid presigned parameters");
|
||||
String[] credential = credentialScope(fields.get("X-Amz-Credential"));
|
||||
if (headers.containsKey("x-amz-security-token")) denied("Presigned session token must be in the query");
|
||||
validateSession(credential[0], fields.get("X-Amz-Security-Token"));
|
||||
String date = fields.get("X-Amz-Date");
|
||||
validatePresignedTime(date, credential[1], fields.get("X-Amz-Expires"));
|
||||
String signedHeaders = fields.get("X-Amz-SignedHeaders");
|
||||
@@ -162,17 +184,29 @@ final class SigV4 {
|
||||
|
||||
private String[] credentialScope(String value) {
|
||||
String[] credential = value.split("/", -1);
|
||||
if (credential.length != 5 || !identities.containsKey(credential[0]) || !credential[2].equals(region)
|
||||
if (credential.length != 5 || !(identities.containsKey(credential[0]) || sessions.containsKey(credential[0])) || !credential[2].equals(region)
|
||||
|| !credential[3].equals("s3") || !credential[4].equals("aws4_request")) denied("Invalid credential scope");
|
||||
return credential;
|
||||
}
|
||||
|
||||
private String secret(String accessKey) {
|
||||
String secret = identities.get(accessKey);
|
||||
if (secret == null && sessions.containsKey(accessKey)) secret = sessions.get(accessKey).secret();
|
||||
if (secret == null) denied("Invalid credential scope");
|
||||
return secret;
|
||||
}
|
||||
|
||||
private void validateSession(String accessKey, String token) {
|
||||
SessionCredentials.Session session = sessions.get(accessKey);
|
||||
if (session == null) {
|
||||
if (token != null) denied("Unexpected session token");
|
||||
return;
|
||||
}
|
||||
if (token == null || !MessageDigest.isEqual(token.getBytes(StandardCharsets.UTF_8),
|
||||
session.token().getBytes(StandardCharsets.UTF_8)) || !clock.instant().isBefore(session.expires()))
|
||||
denied("Invalid or expired session token");
|
||||
}
|
||||
|
||||
private String signingDate(Headers headers, String credentialDate) {
|
||||
String date = single(headers, "x-amz-date");
|
||||
if (date == null || !credentialDate.matches("[0-9]{8}") || !date.matches("[0-9]{8}T[0-9]{6}Z") || !date.startsWith(credentialDate)) denied("Invalid signing date");
|
||||
@@ -190,7 +224,6 @@ final class SigV4 {
|
||||
payload.equals("STREAMING-AWS4-HMAC-SHA256-PAYLOAD") ||
|
||||
payload.equals("STREAMING-AWS4-HMAC-SHA256-PAYLOAD-TRAILER")))
|
||||
throw new StoreException(400, "NotImplemented", "Unsupported SHA-256 payload mode");
|
||||
if (headers.containsKey("x-amz-security-token")) denied("Temporary credentials are unsupported");
|
||||
return payload;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
final class Version {
|
||||
static final String VALUE = "0.0.9";
|
||||
static final String VALUE = "0.1.0";
|
||||
|
||||
private Version() {}
|
||||
}
|
||||
@@ -19,6 +19,9 @@ public final class FeatureTest {
|
||||
private static final String LIMITED = "LIMITEDACCESS1234";
|
||||
private static final String OWNER_SECRET = "test-secret-key-that-is-at-least-32-characters";
|
||||
private static final String LIMITED_SECRET = "limited-secret-key-that-is-at-least-32-characters";
|
||||
private static final String SESSION = "SESSIONACCESS1234";
|
||||
private static final String SESSION_SECRET = "session-secret-key-that-is-at-least-32-characters";
|
||||
private static final String SESSION_TOKEN = "session-token-that-is-at-least-32-characters";
|
||||
|
||||
private static void status(int expected, HttpResponse<?> response) {
|
||||
if (response.statusCode() != expected)
|
||||
@@ -27,10 +30,30 @@ public final class FeatureTest {
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
Path root = Files.createTempDirectory("objectstore-feature-test-");
|
||||
Path sessionFile = root.resolve("sessions");
|
||||
Files.writeString(sessionFile, SESSION + "\t" + SESSION_SECRET + "\t" + SESSION_TOKEN +
|
||||
"\t" + java.time.Instant.now().plusSeconds(3600).getEpochSecond() + "\n");
|
||||
var sessions = SessionCredentials.fromEnvironment(
|
||||
Map.of("S3_SESSION_CREDENTIALS_FILE", sessionFile.toString()), Set.of(OWNER, LIMITED));
|
||||
if (!sessions.containsKey(SESSION)) throw new AssertionError("Session credentials not loaded");
|
||||
Path identityDir = Files.createDirectory(root.resolve("identity-policies"));
|
||||
Files.writeString(identityDir.resolve(LIMITED + ".json"),
|
||||
"{\"Version\":\"2012-10-17\",\"Statement\":[" +
|
||||
statement("Deny", null, "s3:PutObject", "arn:aws:s3:::photos/users/one/blocked") + "," +
|
||||
statement("Allow", null, "s3:GetObject", "arn:aws:s3:::photos/users/one/self_readable") + "," +
|
||||
statement("Allow", null, "s3:PutObject", "arn:aws:s3:::secure/users/one/*") + "," +
|
||||
statement("Allow", null, "s3:GetObject", "arn:aws:s3:::secure/users/one/*") + "]}");
|
||||
Files.writeString(identityDir.resolve(SESSION + ".json"), policy("Allow", null,
|
||||
"s3:GetObject", "arn:aws:s3:::photos/users/one/allowed"));
|
||||
var identityPolicies = IdentityPolicies.fromEnvironment(
|
||||
Map.of("S3_IDENTITY_POLICIES_DIR", identityDir.toString()), OWNER,
|
||||
Set.of(OWNER, LIMITED, SESSION));
|
||||
Path policy = root.resolve("scopes");
|
||||
Files.writeString(policy, LIMITED + "\tphotos\tusers/one/\tread,write,list\n");
|
||||
Files.writeString(policy, LIMITED + "\tphotos\tusers/one/\tread,write,list\n" +
|
||||
LIMITED + "\tsecure\tusers/one/\tread,write\n" +
|
||||
SESSION + "\tphotos\tusers/one/\tread\n");
|
||||
KeyScopes scopes = KeyScopes.fromEnvironment(Map.of("S3_KEY_SCOPES_FILE", policy.toString()),
|
||||
OWNER, Set.of(OWNER, LIMITED));
|
||||
OWNER, Set.of(OWNER, LIMITED, SESSION));
|
||||
scopes.require(LIMITED, "write", "photos", "users/one/image.jpg");
|
||||
scopes.checkBucket(LIMITED, "photos", "GET", Map.of("list-type", "2", "prefix", "users/one/"));
|
||||
denied(() -> scopes.require(LIMITED, "read", "photos", "users/two/image.jpg"));
|
||||
@@ -47,9 +70,11 @@ public final class FeatureTest {
|
||||
DiskStore store = new DiskStore(root.resolve("data"), 1024, 4096);
|
||||
try {
|
||||
Main app = new Main(store, new MultipartStore(store),
|
||||
new SigV4(Map.of(OWNER, OWNER_SECRET, LIMITED, LIMITED_SECRET), OWNER,
|
||||
new SigV4(Map.of(OWNER, OWNER_SECRET, LIMITED, LIMITED_SECRET), sessions, OWNER,
|
||||
"us-east-1", Clock.systemUTC()),
|
||||
"photos", ClientLimits.disabled(), 16, "", cors, scopes, metrics);
|
||||
"photos", ClientLimits.disabled(), 16, "", cors, scopes, metrics, identityPolicies);
|
||||
store.setBucketOwnership("photos", ObjectStorage.ObjectOwnership.OBJECT_WRITER);
|
||||
store.setPublicAccessBlock("photos", ObjectStorage.PublicAccessBlock.open());
|
||||
server.setExecutor(executor);
|
||||
server.createContext("/", app::handle);
|
||||
server.start();
|
||||
@@ -83,9 +108,21 @@ public final class FeatureTest {
|
||||
status(200, client.send(HttpTest.signedUri(URI.create(base + "/photos?acl"),
|
||||
"PUT", new byte[0], Map.of("x-amz-grant-full-control", "id=\"" + LIMITED + "\"")),
|
||||
HttpResponse.BodyHandlers.ofString()));
|
||||
status(405, client.send(HttpTest.signedUri(URI.create(base + "/photos?acl"),
|
||||
"PUT", new byte[0], Map.of("x-amz-grant-read", "emailAddress=\"example@example.test\"")),
|
||||
HttpResponse.BodyHandlers.ofString()));
|
||||
byte[] content = "allowed".getBytes(java.nio.charset.StandardCharsets.UTF_8);
|
||||
status(200, client.send(HttpTest.signedUriAs(URI.create(base + "/photos/users/one/allowed"),
|
||||
"PUT", content, Map.of(), LIMITED, LIMITED_SECRET), HttpResponse.BodyHandlers.ofString()));
|
||||
URI ownReadable = URI.create(base + "/photos/users/one/self_readable");
|
||||
status(200, client.send(HttpTest.signedUriAs(ownReadable,
|
||||
"PUT", content, Map.of(), LIMITED, LIMITED_SECRET), HttpResponse.BodyHandlers.ofString()));
|
||||
status(200, client.send(HttpTest.signedUriAs(ownReadable,
|
||||
"GET", new byte[0], Map.of(), LIMITED, LIMITED_SECRET), HttpResponse.BodyHandlers.ofString()));
|
||||
status(403, client.send(HttpTest.signedUriAs(URI.create(base + "/photos/users/one/allowed"),
|
||||
"GET", new byte[0], Map.of(), LIMITED, LIMITED_SECRET), HttpResponse.BodyHandlers.ofString()));
|
||||
status(403, client.send(HttpTest.signedUriAs(URI.create(base + "/photos/users/one/blocked"),
|
||||
"PUT", content, Map.of(), LIMITED, LIMITED_SECRET), HttpResponse.BodyHandlers.ofString()));
|
||||
status(403, client.send(HttpTest.signedUriAs(URI.create(base + "/photos/users/two/denied"),
|
||||
"PUT", content, Map.of(), LIMITED, LIMITED_SECRET), HttpResponse.BodyHandlers.ofString()));
|
||||
status(200, client.send(HttpTest.signedUriAs(URI.create(base + "/photos?list-type=2&prefix=users%2Fone%2F"),
|
||||
@@ -94,6 +131,107 @@ public final class FeatureTest {
|
||||
"GET", new byte[0], Map.of(), LIMITED, LIMITED_SECRET), HttpResponse.BodyHandlers.ofString()));
|
||||
status(403, client.send(HttpTest.signedUriAs(URI.create(base + "/photos/users/one/allowed?acl"),
|
||||
"GET", new byte[0], Map.of(), LIMITED, LIMITED_SECRET), HttpResponse.BodyHandlers.ofString()));
|
||||
status(200, client.send(HttpTest.signedUri(URI.create(base + "/photos/users/one/allowed?acl"),
|
||||
"PUT", new byte[0], Map.of("x-amz-acl", "public-read")),
|
||||
HttpResponse.BodyHandlers.ofString()));
|
||||
status(200, client.send(HttpRequest.newBuilder(
|
||||
URI.create(base + "/photos/users/one/allowed")).GET().build(),
|
||||
HttpResponse.BodyHandlers.ofString()));
|
||||
store.setPublicAccessBlock("photos", ObjectStorage.PublicAccessBlock.secure());
|
||||
status(403, client.send(HttpRequest.newBuilder(
|
||||
URI.create(base + "/photos/users/one/allowed")).GET().build(),
|
||||
HttpResponse.BodyHandlers.ofString()));
|
||||
status(403, client.send(HttpTest.signedUri(URI.create(base + "/photos/users/one/public"),
|
||||
"PUT", content, Map.of("x-amz-acl", "public-read")),
|
||||
HttpResponse.BodyHandlers.ofString()));
|
||||
store.createBucket("secure");
|
||||
var secure = store.bucket("secure");
|
||||
if (secure.ownership() != ObjectStorage.ObjectOwnership.BUCKET_OWNER_ENFORCED ||
|
||||
!secure.publicAccessBlock().blockPublicAcls() ||
|
||||
!secure.publicAccessBlock().ignorePublicAcls() ||
|
||||
!secure.publicAccessBlock().blockPublicPolicy() ||
|
||||
!secure.publicAccessBlock().restrictPublicBuckets())
|
||||
throw new AssertionError("New bucket did not default to private access");
|
||||
URI scopedObject = URI.create(base + "/secure/users/one/photo.jpg");
|
||||
status(200, client.send(HttpTest.signedUriAs(scopedObject,
|
||||
"PUT", content, Map.of(), LIMITED, LIMITED_SECRET), HttpResponse.BodyHandlers.ofString()));
|
||||
status(200, client.send(HttpTest.signedUriAs(scopedObject,
|
||||
"GET", new byte[0], Map.of(), LIMITED, LIMITED_SECRET), HttpResponse.BodyHandlers.ofString()));
|
||||
status(403, client.send(HttpTest.signedUriAs(URI.create(base + "/secure/users/two/photo.jpg"),
|
||||
"GET", new byte[0], Map.of(), LIMITED, LIMITED_SECRET), HttpResponse.BodyHandlers.ofString()));
|
||||
status(400, client.send(HttpTest.signedUri(URI.create(base + "/secure/item"),
|
||||
"PUT", content, Map.of("x-amz-acl", "public-read")),
|
||||
HttpResponse.BodyHandlers.ofString()));
|
||||
URI ownership = URI.create(base + "/photos?ownershipControls");
|
||||
byte[] enforced = ("<OwnershipControls><Rule><ObjectOwnership>BucketOwnerEnforced" +
|
||||
"</ObjectOwnership></Rule></OwnershipControls>")
|
||||
.getBytes(java.nio.charset.StandardCharsets.UTF_8);
|
||||
status(200, client.send(HttpTest.signedUri(ownership, "PUT", enforced, Map.of()),
|
||||
HttpResponse.BodyHandlers.ofString()));
|
||||
status(403, client.send(HttpTest.signedUriAs(URI.create(base + "/photos/users/one/allowed"),
|
||||
"GET", new byte[0], Map.of(), LIMITED, LIMITED_SECRET), HttpResponse.BodyHandlers.ofString()));
|
||||
URI bucketPolicy = URI.create(base + "/photos?policy");
|
||||
String allow = policy("Allow", LIMITED, "s3:GetObject", "arn:aws:s3:::photos/users/one/*");
|
||||
status(204, client.send(HttpTest.signedUri(bucketPolicy, "PUT", allow.getBytes(), Map.of()),
|
||||
HttpResponse.BodyHandlers.ofString()));
|
||||
status(200, client.send(HttpTest.signedUriAs(URI.create(base + "/photos/users/one/allowed"),
|
||||
"GET", new byte[0], Map.of(), LIMITED, LIMITED_SECRET), HttpResponse.BodyHandlers.ofString()));
|
||||
String deny = "{\"Version\":\"2012-10-17\",\"Statement\":[" +
|
||||
statement("Allow", LIMITED, "s3:GetObject", "arn:aws:s3:::photos/users/one/*") + "," +
|
||||
statement("Deny", "*", "s3:GetObject", "arn:aws:s3:::photos/users/one/allowed") + "]}";
|
||||
status(204, client.send(HttpTest.signedUri(bucketPolicy, "PUT", deny.getBytes(), Map.of()),
|
||||
HttpResponse.BodyHandlers.ofString()));
|
||||
status(403, client.send(HttpTest.signedUriAs(URI.create(base + "/photos/users/one/allowed"),
|
||||
"GET", new byte[0], Map.of(), LIMITED, LIMITED_SECRET), HttpResponse.BodyHandlers.ofString()));
|
||||
status(403, client.send(HttpTest.signedUri(URI.create(base + "/photos/users/one/allowed"),
|
||||
"GET", new byte[0], Map.of()), HttpResponse.BodyHandlers.ofString()));
|
||||
String publicPolicy = policy("Allow", "*", "s3:GetObject", "arn:aws:s3:::photos/users/one/*");
|
||||
status(403, client.send(HttpTest.signedUri(bucketPolicy, "PUT", publicPolicy.getBytes(), Map.of()),
|
||||
HttpResponse.BodyHandlers.ofString()));
|
||||
byte[] block = ("<PublicAccessBlockConfiguration><BlockPublicAcls>true</BlockPublicAcls>" +
|
||||
"<IgnorePublicAcls>true</IgnorePublicAcls><BlockPublicPolicy>false</BlockPublicPolicy>" +
|
||||
"<RestrictPublicBuckets>true</RestrictPublicBuckets></PublicAccessBlockConfiguration>").getBytes();
|
||||
status(200, client.send(HttpTest.signedUri(URI.create(base + "/photos?publicAccessBlock"),
|
||||
"PUT", block, Map.of()), HttpResponse.BodyHandlers.ofString()));
|
||||
status(204, client.send(HttpTest.signedUri(bucketPolicy, "PUT", publicPolicy.getBytes(), Map.of()),
|
||||
HttpResponse.BodyHandlers.ofString()));
|
||||
status(403, client.send(HttpRequest.newBuilder(
|
||||
URI.create(base + "/photos/users/one/allowed")).GET().build(),
|
||||
HttpResponse.BodyHandlers.ofString()));
|
||||
status(200, client.send(HttpTest.signedUri(bucketPolicy, "GET", new byte[0], Map.of()),
|
||||
HttpResponse.BodyHandlers.ofString()));
|
||||
String sessionPolicy = policy("Allow", LIMITED, "s3:GetObject",
|
||||
"arn:aws:s3:::photos/users/one/*");
|
||||
status(204, client.send(HttpTest.signedUri(bucketPolicy, "PUT", sessionPolicy.getBytes(), Map.of()),
|
||||
HttpResponse.BodyHandlers.ofString()));
|
||||
URI sessionObject = URI.create(base + "/photos/users/one/allowed");
|
||||
status(200, client.send(HttpTest.signedUriAs(sessionObject, "GET", new byte[0],
|
||||
Map.of("x-amz-security-token", SESSION_TOKEN), SESSION, SESSION_SECRET),
|
||||
HttpResponse.BodyHandlers.ofString()));
|
||||
status(403, client.send(HttpTest.signedUriAs(sessionObject, "GET", new byte[0],
|
||||
Map.of(), SESSION, SESSION_SECRET), HttpResponse.BodyHandlers.ofString()));
|
||||
status(403, client.send(HttpTest.signedUriAs(sessionObject, "GET", new byte[0],
|
||||
Map.of("x-amz-security-token", SESSION_TOKEN + "wrong"), SESSION, SESSION_SECRET),
|
||||
HttpResponse.BodyHandlers.ofString()));
|
||||
status(403, client.send(HttpTest.signedUriAs(sessionObject, "PUT", content,
|
||||
Map.of("x-amz-security-token", SESSION_TOKEN), SESSION, SESSION_SECRET),
|
||||
HttpResponse.BodyHandlers.ofString()));
|
||||
status(200, client.send(HttpRequest.newBuilder(HttpTest.presignedUriAs(sessionObject, "GET", 60,
|
||||
SESSION, SESSION_SECRET, SESSION_TOKEN)).GET().build(), HttpResponse.BodyHandlers.ofString()));
|
||||
status(403, client.send(HttpRequest.newBuilder(HttpTest.presignedUriAs(sessionObject, "GET", 60,
|
||||
SESSION, SESSION_SECRET, null)).GET().build(), HttpResponse.BodyHandlers.ofString()));
|
||||
status(403, client.send(HttpTest.signedUriAs(sessionObject, "GET", new byte[0],
|
||||
Map.of("x-amz-security-token", SESSION_TOKEN), OWNER, OWNER_SECRET),
|
||||
HttpResponse.BodyHandlers.ofString()));
|
||||
var expired = new SigV4(Map.of(OWNER, OWNER_SECRET), Map.of(SESSION,
|
||||
new SessionCredentials.Session(SESSION_SECRET, SESSION_TOKEN,
|
||||
java.time.Instant.now().minusSeconds(1))), OWNER, "us-east-1", Clock.systemUTC());
|
||||
var signed = HttpTest.signedUriAs(sessionObject, "GET", new byte[0],
|
||||
Map.of("x-amz-security-token", SESSION_TOKEN), SESSION, SESSION_SECRET);
|
||||
var signedHeaders = new com.sun.net.httpserver.Headers();
|
||||
signed.headers().map().forEach(signedHeaders::put);
|
||||
signedHeaders.set("host", sessionObject.getAuthority());
|
||||
denied(() -> expired.verifyRequest("GET", sessionObject, signedHeaders));
|
||||
} finally {
|
||||
server.stop(0);
|
||||
executor.close();
|
||||
@@ -102,7 +240,18 @@ public final class FeatureTest {
|
||||
for (Path path : files.sorted(Comparator.reverseOrder()).toList()) Files.delete(path);
|
||||
}
|
||||
}
|
||||
System.out.println("Feature tests passed: scoped keys, CORS, metrics");
|
||||
System.out.println("Feature tests passed: scoped keys, CORS, metrics, bucket policy and public access");
|
||||
}
|
||||
|
||||
private static String policy(String effect, String principal, String action, String resource) {
|
||||
return "{\"Version\":\"2012-10-17\",\"Statement\":[" +
|
||||
statement(effect, principal, action, resource) + "]}";
|
||||
}
|
||||
|
||||
private static String statement(String effect, String principal, String action, String resource) {
|
||||
return "{\"Effect\":\"" + effect + "\"," +
|
||||
(principal == null ? "" : "\"Principal\":\"" + principal + "\",") +
|
||||
"\"Action\":\"" + action + "\",\"Resource\":\"" + resource + "\"}";
|
||||
}
|
||||
|
||||
private static com.sun.net.httpserver.Headers headers(String name, String value) {
|
||||
|
||||
@@ -71,17 +71,35 @@ public final class HttpTest {
|
||||
}
|
||||
|
||||
private static URI presignedUri(URI uri, String method, int expires) {
|
||||
return presignedUriAs(uri, method, expires, ACCESS, SECRET, null);
|
||||
}
|
||||
|
||||
static URI presignedUriAs(URI uri, String method, int expires, String access, String secret,
|
||||
String token) {
|
||||
return presignedUriAs(uri, method, expires, access, secret, token, false);
|
||||
}
|
||||
|
||||
private static URI presignedUriAs(URI uri, String method, int expires, String access, String secret,
|
||||
String token, boolean sdkContentHash) {
|
||||
return presignedUriAs(uri, method, expires, access, secret, token, sdkContentHash, "");
|
||||
}
|
||||
|
||||
private static URI presignedUriAs(URI uri, String method, int expires, String access, String secret,
|
||||
String token, boolean sdkContentHash, String applicationQuery) {
|
||||
String date = DATE.format(Instant.now());
|
||||
String scope = date.substring(0, 8) + "/" + REGION + "/s3/aws4_request";
|
||||
String query = "X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=" +
|
||||
SigV4.encode(ACCESS + "/" + scope, false) + "&X-Amz-Date=" + date +
|
||||
SigV4.encode(access + "/" + scope, false) + "&X-Amz-Date=" + date +
|
||||
"&X-Amz-Expires=" + expires + "&X-Amz-SignedHeaders=host";
|
||||
if (token != null) query += "&X-Amz-Security-Token=" + SigV4.encode(token, false);
|
||||
if (sdkContentHash) query += "&X-Amz-Content-Sha256=UNSIGNED-PAYLOAD";
|
||||
if (!applicationQuery.isEmpty()) query += "&" + applicationQuery;
|
||||
String canonical = method + "\n" + uri.getRawPath() + "\n" +
|
||||
SigV4.canonicalQuery(query) + "\nhost:" + uri.getAuthority() +
|
||||
"\n\nhost\nUNSIGNED-PAYLOAD";
|
||||
String toSign = "AWS4-HMAC-SHA256\n" + date + "\n" + scope + "\n" +
|
||||
SigV4.hex(SigV4.hash(canonical.getBytes(StandardCharsets.UTF_8)));
|
||||
String signature = SigV4.hex(SigV4.hmac(SigV4.signingKey(SECRET,
|
||||
String signature = SigV4.hex(SigV4.hmac(SigV4.signingKey(secret,
|
||||
date.substring(0, 8), REGION), toSign));
|
||||
return URI.create(uri + "?" + query + "&X-Amz-Signature=" + signature);
|
||||
}
|
||||
@@ -96,6 +114,27 @@ public final class HttpTest {
|
||||
HttpResponse.BodyHandlers.ofByteArray());
|
||||
status(200, read);
|
||||
if (!java.util.Arrays.equals(body, read.body())) throw new AssertionError("Presigned object mismatch");
|
||||
URI sdkObject = URI.create(base + "/objects/sdk-v3-presigned");
|
||||
URI sdkPut = presignedUriAs(sdkObject, "PUT", 60, ACCESS, SECRET, null, true);
|
||||
status(200, client.send(HttpRequest.newBuilder(sdkPut)
|
||||
.PUT(HttpRequest.BodyPublishers.ofByteArray(body)).build(), HttpResponse.BodyHandlers.ofByteArray()));
|
||||
URI sdkGet = presignedUriAs(sdkObject, "GET", 60, ACCESS, SECRET, null, true);
|
||||
status(200, client.send(HttpRequest.newBuilder(sdkGet).GET().build(),
|
||||
HttpResponse.BodyHandlers.ofByteArray()));
|
||||
status(403, client.send(HttpRequest.newBuilder(URI.create(sdkGet.toString().replace(
|
||||
"X-Amz-Content-Sha256=UNSIGNED-PAYLOAD", "X-Amz-Content-Sha256=changed")))
|
||||
.GET().build(), HttpResponse.BodyHandlers.ofByteArray()));
|
||||
status(204, client.send(HttpRequest.newBuilder(presignedUriAs(sdkObject, "DELETE", 60,
|
||||
ACCESS, SECRET, null, true)).DELETE().build(), HttpResponse.BodyHandlers.ofByteArray()));
|
||||
URI checksumObject = URI.create(base + "/objects/sdk-v3-checksum");
|
||||
String checksumQuery = "x-amz-checksum-crc32=" +
|
||||
SigV4.encode(encodedChecksum("CRC32", body), false) +
|
||||
"&x-amz-sdk-checksum-algorithm=CRC32&x-id=PutObject";
|
||||
status(200, client.send(HttpRequest.newBuilder(presignedUriAs(checksumObject, "PUT", 60,
|
||||
ACCESS, SECRET, null, true, checksumQuery))
|
||||
.PUT(HttpRequest.BodyPublishers.ofByteArray(body)).build(), HttpResponse.BodyHandlers.ofByteArray()));
|
||||
status(204, client.send(HttpRequest.newBuilder(presignedUri(checksumObject, "DELETE", 60))
|
||||
.DELETE().build(), HttpResponse.BodyHandlers.ofByteArray()));
|
||||
URI tampered = URI.create(presignedUri(object, "GET", 60).toString().replace("presigned-test", "different"));
|
||||
status(403, client.send(HttpRequest.newBuilder(tampered).GET().build(),
|
||||
HttpResponse.BodyHandlers.ofByteArray()));
|
||||
@@ -104,6 +143,7 @@ public final class HttpTest {
|
||||
}
|
||||
|
||||
private static void testAcl(HttpClient client, String base) throws Exception {
|
||||
enableAcl(client, URI.create(base + "/objects"));
|
||||
byte[] body = "private object".getBytes(StandardCharsets.UTF_8);
|
||||
URI object = URI.create(base + "/objects/acl-test");
|
||||
URI objectAcl = URI.create(object + "?acl");
|
||||
@@ -166,6 +206,7 @@ public final class HttpTest {
|
||||
URI historyBucket = URI.create(base + "/acl-history");
|
||||
status(200, client.send(signedUri(historyBucket, "PUT", new byte[0], Map.of()),
|
||||
HttpResponse.BodyHandlers.ofByteArray()));
|
||||
enableAcl(client, historyBucket);
|
||||
byte[] versioning = "<VersioningConfiguration><Status>Enabled</Status></VersioningConfiguration>"
|
||||
.getBytes(StandardCharsets.UTF_8);
|
||||
status(200, client.send(signedUri(URI.create(historyBucket + "?versioning"),
|
||||
@@ -197,6 +238,19 @@ public final class HttpTest {
|
||||
HttpResponse.BodyHandlers.ofByteArray()));
|
||||
}
|
||||
|
||||
private static void enableAcl(HttpClient client, URI bucket) throws Exception {
|
||||
byte[] ownership = ("<OwnershipControls><Rule><ObjectOwnership>ObjectWriter</ObjectOwnership>" +
|
||||
"</Rule></OwnershipControls>").getBytes(StandardCharsets.UTF_8);
|
||||
status(200, client.send(signedUri(URI.create(bucket + "?ownershipControls"),
|
||||
"PUT", ownership, Map.of()), HttpResponse.BodyHandlers.ofByteArray()));
|
||||
byte[] publicAccess = ("<PublicAccessBlockConfiguration><BlockPublicAcls>false</BlockPublicAcls>" +
|
||||
"<IgnorePublicAcls>false</IgnorePublicAcls><BlockPublicPolicy>false</BlockPublicPolicy>" +
|
||||
"<RestrictPublicBuckets>false</RestrictPublicBuckets></PublicAccessBlockConfiguration>")
|
||||
.getBytes(StandardCharsets.UTF_8);
|
||||
status(200, client.send(signedUri(URI.create(bucket + "?publicAccessBlock"),
|
||||
"PUT", publicAccess, Map.of()), HttpResponse.BodyHandlers.ofByteArray()));
|
||||
}
|
||||
|
||||
private static void testStreaming(HttpClient client, String base) throws Exception {
|
||||
URI object = URI.create(base + "/objects/streaming-test");
|
||||
byte[] body = "verified streaming payload".getBytes(StandardCharsets.UTF_8);
|
||||
@@ -413,7 +467,8 @@ public final class HttpTest {
|
||||
"PUT", body, Map.of("content-type", "text/plain")), HttpResponse.BodyHandlers.ofByteArray()));
|
||||
String header = "/objects/" + SigV4.encode(source, true);
|
||||
var result = client.send(signedUri(URI.create(base + "/objects/" + target), "PUT",
|
||||
new byte[0], Map.of("x-amz-copy-source", header)), HttpResponse.BodyHandlers.ofString());
|
||||
new byte[0], Map.of("x-amz-copy-source", header,
|
||||
"content-type", "application/x-sdk-copy")), HttpResponse.BodyHandlers.ofString());
|
||||
if (result.statusCode() != 200 || !result.body().contains("<CopyObjectResult>") ||
|
||||
!result.body().contains("<ETag>""))
|
||||
throw new AssertionError("CopyObject failed: " + result.body());
|
||||
@@ -536,18 +591,32 @@ public final class HttpTest {
|
||||
}
|
||||
|
||||
private static void testMultipart(HttpClient client, String base) throws Exception {
|
||||
URI endpoint = ObjectStoreServer.publicEndpoint(Map.of("S3_PUBLIC_ENDPOINT", "https://s3.example.test/"));
|
||||
if (!"https://s3.example.test/objects/folder/a%20b.mp4".equals(
|
||||
MultipartHandler.objectLocation(endpoint, "127.0.0.1:9000", "http",
|
||||
"/objects/folder/a%20b.mp4", "objects", "folder/a b.mp4")))
|
||||
throw new AssertionError("Configured multipart location is incorrect");
|
||||
try {
|
||||
ObjectStoreServer.publicEndpoint(Map.of("S3_PUBLIC_ENDPOINT", "https://s3.example.test/subpath"));
|
||||
throw new AssertionError("Public endpoint with a path was accepted");
|
||||
} catch (IllegalArgumentException expected) { }
|
||||
String movie = "folder/video.mp4";
|
||||
URI initiate = URI.create(base + "/objects/" + movie + "?uploads=");
|
||||
var created = client.send(signedUri(initiate, "POST", new byte[0],
|
||||
Map.of("content-type", "video/mp4")), HttpResponse.BodyHandlers.ofString());
|
||||
Map.of("content-type", "video/mp4", "x-amz-checksum-algorithm", "CRC32")),
|
||||
HttpResponse.BodyHandlers.ofString());
|
||||
if (created.statusCode() != 200) throw new AssertionError("Multipart initiation failed: " + created.body());
|
||||
String upload = created.body().split("<UploadId>")[1].split("</UploadId>")[0];
|
||||
byte[] first = "hello ".getBytes(StandardCharsets.UTF_8);
|
||||
byte[] second = "world".getBytes(StandardCharsets.UTF_8);
|
||||
var partOne = client.send(signedUri(URI.create(base + "/objects/" + movie +
|
||||
"?partNumber=1&uploadId=" + upload), "PUT", first, Map.of()), HttpResponse.BodyHandlers.ofByteArray());
|
||||
"?partNumber=1&uploadId=" + upload), "PUT", first,
|
||||
Map.of("x-amz-checksum-crc32", encodedChecksum("CRC32", first),
|
||||
"x-amz-sdk-checksum-algorithm", "CRC32")), HttpResponse.BodyHandlers.ofByteArray());
|
||||
var partTwo = client.send(signedUri(URI.create(base + "/objects/" + movie +
|
||||
"?partNumber=2&uploadId=" + upload), "PUT", second, Map.of()), HttpResponse.BodyHandlers.ofByteArray());
|
||||
"?partNumber=2&uploadId=" + upload), "PUT", second,
|
||||
Map.of("x-amz-checksum-crc32", encodedChecksum("CRC32", second),
|
||||
"x-amz-sdk-checksum-algorithm", "CRC32")), HttpResponse.BodyHandlers.ofByteArray());
|
||||
status(200, partOne);
|
||||
status(200, partTwo);
|
||||
var rejectedPart = client.send(signedUri(URI.create(base + "/objects/" + movie +
|
||||
@@ -567,11 +636,20 @@ public final class HttpTest {
|
||||
throw new AssertionError("Multipart upload listing failed: " + uploads.body());
|
||||
String completion = "<CompleteMultipartUpload><Part><PartNumber>1</PartNumber><ETag>" +
|
||||
partOne.headers().firstValue("etag").orElseThrow() +
|
||||
"</ETag></Part><Part><PartNumber>2</PartNumber><ETag>" +
|
||||
"</ETag><ChecksumCRC32>" + encodedChecksum("CRC32", first) +
|
||||
"</ChecksumCRC32></Part><Part><PartNumber>2</PartNumber><ETag>" +
|
||||
partTwo.headers().firstValue("etag").orElseThrow() +
|
||||
"</ETag></Part></CompleteMultipartUpload>";
|
||||
status(200, client.send(signedUri(URI.create(base + "/objects/" + movie + "?uploadId=" + upload),
|
||||
"POST", completion.getBytes(StandardCharsets.UTF_8), Map.of()), HttpResponse.BodyHandlers.ofByteArray()));
|
||||
"</ETag><ChecksumCRC32>" + encodedChecksum("CRC32", second) +
|
||||
"</ChecksumCRC32></Part></CompleteMultipartUpload>";
|
||||
String mismatched = completion.replace(encodedChecksum("CRC32", first), "AAAAAA==");
|
||||
status(400, client.send(signedUri(URI.create(base + "/objects/" + movie + "?uploadId=" + upload),
|
||||
"POST", mismatched.getBytes(StandardCharsets.UTF_8), Map.of()),
|
||||
HttpResponse.BodyHandlers.ofString()));
|
||||
var completed = client.send(signedUri(URI.create(base + "/objects/" + movie + "?uploadId=" + upload),
|
||||
"POST", completion.getBytes(StandardCharsets.UTF_8), Map.of()), HttpResponse.BodyHandlers.ofString());
|
||||
status(200, completed);
|
||||
if (!completed.body().contains("<Location>" + base + "/objects/" + movie + "</Location>"))
|
||||
throw new AssertionError("Multipart completion omitted the object location: " + completed.body());
|
||||
var assembled = client.send(signed(base, "GET", movie, new byte[0]), HttpResponse.BodyHandlers.ofByteArray());
|
||||
status(200, assembled);
|
||||
if (!"hello world".equals(new String(assembled.body(), StandardCharsets.UTF_8)) ||
|
||||
|
||||
@@ -295,6 +295,40 @@ public final class StoreTest {
|
||||
}
|
||||
}
|
||||
|
||||
private static void testBucketAccessUpgrade(Path root) throws Exception {
|
||||
Path data = Files.createDirectory(root.resolve("bucket-access-upgrade"));
|
||||
try (var output = new DataOutputStream(Files.newOutputStream(data.resolve("buckets.bin")))) {
|
||||
output.writeInt(0x4c534245);
|
||||
output.writeInt(1);
|
||||
output.writeUTF("legacy-bucket");
|
||||
output.writeLong(System.currentTimeMillis());
|
||||
output.writeByte(0);
|
||||
output.writeShort(0);
|
||||
}
|
||||
try (var store = new DiskStore(data, 8, 16)) {
|
||||
var legacy = store.bucket("legacy-bucket");
|
||||
if (legacy.ownership() != ObjectStorage.ObjectOwnership.OBJECT_WRITER ||
|
||||
legacy.publicAccessBlock().blockPublicAcls())
|
||||
throw new AssertionError("Existing bucket access changed during upgrade");
|
||||
store.createBucket("new-bucket");
|
||||
if (store.bucket("new-bucket").ownership() !=
|
||||
ObjectStorage.ObjectOwnership.BUCKET_OWNER_ENFORCED ||
|
||||
!store.bucket("new-bucket").publicAccessBlock().blockPublicPolicy())
|
||||
throw new AssertionError("New bucket did not use secure defaults");
|
||||
store.setBucketPolicy("legacy-bucket", "{\"Version\":\"2012-10-17\"," +
|
||||
"\"Statement\":{\"Effect\":\"Deny\",\"Principal\":\"*\"," +
|
||||
"\"Action\":\"s3:GetObject\",\"Resource\":\"arn:aws:s3:::legacy-bucket/*\"}}");
|
||||
}
|
||||
try (var store = new DiskStore(data, 8, 16)) {
|
||||
if (store.bucket("legacy-bucket").ownership() !=
|
||||
ObjectStorage.ObjectOwnership.OBJECT_WRITER ||
|
||||
store.bucket("legacy-bucket").policy() == null ||
|
||||
store.bucket("new-bucket").ownership() !=
|
||||
ObjectStorage.ObjectOwnership.BUCKET_OWNER_ENFORCED)
|
||||
throw new AssertionError("Bucket access settings were not durable");
|
||||
}
|
||||
}
|
||||
|
||||
private static void testAclPersistence(Path root) throws Exception {
|
||||
Path data = root.resolve("acl");
|
||||
Map<String, String> grant = Map.of("SECONDARYKEY1234", Integer.toString(Acl.READ));
|
||||
@@ -423,6 +457,7 @@ public final class StoreTest {
|
||||
testAttributesRestart(root);
|
||||
testV3Record(root);
|
||||
testBucketRestart(root);
|
||||
testBucketAccessUpgrade(root);
|
||||
testAclPersistence(root);
|
||||
testAdditionalKeys(root);
|
||||
testVersioning(root);
|
||||
|
||||
Reference in new issue
Block a user