Release ObjectStore 0.0.9

This commit is contained in:
admin committed 2026-10-25 07:02:09 +01:00
1 parent 31eb4d092e
commit 0cf5c11202
39 files changed
+4736 -1164

No files matched your search

+6
View File
@@ -4,10 +4,16 @@ CLUSTER_TOKEN=
CLUSTER_REPAIR_TOKEN= CLUSTER_REPAIR_TOKEN=
POSTGRES_PASSWORD=[PG_Pass] POSTGRES_PASSWORD=[PG_Pass]
S3_BUCKET=objects S3_BUCKET=objects
S3_CREDENTIALS_FILE=
S3_KEY_SCOPES_FILE=
METRICS_BEARER_TOKEN=
CLUSTER_HOST_PORT=9001 CLUSTER_HOST_PORT=9001
MAX_OBJECT_BYTES=134217728 MAX_OBJECT_BYTES=134217728
MAX_TOTAL_BYTES=2147483648 MAX_TOTAL_BYTES=2147483648
MAX_IN_FLIGHT_REQUESTS=16 MAX_IN_FLIGHT_REQUESTS=16
OBJECTSTORE_REQUEST_TIMEOUT_SECONDS=0
OBJECTSTORE_RESPONSE_TIMEOUT_SECONDS=0
CORS_ALLOWED_ORIGINS=
HTTP_BACKLOG=64 HTTP_BACKLOG=64
S3_VIRTUAL_HOST_SUFFIX= S3_VIRTUAL_HOST_SUFFIX=
# For compose.cluster.encrypted.yaml only; provision and mount LUKS before setting these. # For compose.cluster.encrypted.yaml only; provision and mount LUKS before setting these.
+10 -4
View File
@@ -1,9 +1,12 @@
# Copy to .env and replace both empty values with random credentials. # Copy to .env and set both values to unique random credentials.
# The Compose file refuses to start without them. # The Compose file refuses to start while either value is empty.
S3_ACCESS_KEY=[Replace_with_your_S3_Access_Key] S3_ACCESS_KEY=
S3_SECRET_KEY=[Replace_with_your_S3_Secret_Key] S3_SECRET_KEY=
S3_BUCKET=objects S3_BUCKET=objects
S3_REGION=us-east-1 S3_REGION=us-east-1
S3_CREDENTIALS_FILE=
S3_KEY_SCOPES_FILE=
METRICS_BEARER_TOKEN=
HOST_PORT=9000 HOST_PORT=9000
MAX_OBJECT_BYTES=134217728 MAX_OBJECT_BYTES=134217728
MAX_TOTAL_BYTES=2147483648 MAX_TOTAL_BYTES=2147483648
@@ -16,6 +19,9 @@ PUBLIC_TRUSTED_PROXY_IPS=
MAX_IN_FLIGHT_REQUESTS=16 MAX_IN_FLIGHT_REQUESTS=16
HTTP_BACKLOG=64 HTTP_BACKLOG=64
S3_VIRTUAL_HOST_SUFFIX= S3_VIRTUAL_HOST_SUFFIX=
CORS_ALLOWED_ORIGINS=
OBJECTSTORE_REQUEST_TIMEOUT_SECONDS=0
OBJECTSTORE_RESPONSE_TIMEOUT_SECONDS=0
# For compose.encrypted.yaml only; provision and mount LUKS before setting these. # For compose.encrypted.yaml only; provision and mount LUKS before setting these.
ENCRYPTED_STORAGE_ROOT= ENCRYPTED_STORAGE_ROOT=
ENCRYPTED_VOLUME_ID= ENCRYPTED_VOLUME_ID=
+1
View File
@@ -1,4 +1,5 @@
out/ out/
rust-client/target/
.env .env
.env.cluster .env.cluster
*.local.env *.local.env
+4 -2
View File
@@ -11,6 +11,7 @@ RUN java --add-modules jdk.httpserver -cp /out:/tmp/hash4j.jar cloud.lunarsky.st
RUN java --add-modules jdk.httpserver -cp /out:/tmp/hash4j.jar cloud.lunarsky.store.ConcurrencyTest RUN java --add-modules jdk.httpserver -cp /out:/tmp/hash4j.jar cloud.lunarsky.store.ConcurrencyTest
RUN java --add-modules jdk.httpserver,java.net.http -cp /out:/tmp/hash4j.jar cloud.lunarsky.store.HttpTest RUN java --add-modules jdk.httpserver,java.net.http -cp /out:/tmp/hash4j.jar cloud.lunarsky.store.HttpTest
RUN java --add-modules jdk.httpserver,java.net.http -cp /out:/tmp/hash4j.jar cloud.lunarsky.store.ClientLimitsTest RUN java --add-modules jdk.httpserver,java.net.http -cp /out:/tmp/hash4j.jar cloud.lunarsky.store.ClientLimitsTest
RUN java --add-modules jdk.httpserver,java.net.http -cp /out:/tmp/hash4j.jar cloud.lunarsky.store.FeatureTest
RUN java -cp /out:/tmp/hash4j.jar cloud.lunarsky.store.EncryptedVolumeTest RUN java -cp /out:/tmp/hash4j.jar cloud.lunarsky.store.EncryptedVolumeTest
RUN java --add-modules jdk.httpserver,java.net.http -cp /out:/tmp/hash4j.jar cloud.lunarsky.store.ClusterNodeTest RUN java --add-modules jdk.httpserver,java.net.http -cp /out:/tmp/hash4j.jar cloud.lunarsky.store.ClusterNodeTest
RUN java --add-modules jdk.httpserver,java.net.http -cp /out:/tmp/hash4j.jar cloud.lunarsky.store.ClusterTlsTest RUN java --add-modules jdk.httpserver,java.net.http -cp /out:/tmp/hash4j.jar cloud.lunarsky.store.ClusterTlsTest
@@ -23,7 +24,8 @@ COPY --from=build /tmp/postgresql.jar /app/postgresql.jar
COPY --from=build /tmp/hash4j.jar /app/hash4j.jar COPY --from=build /tmp/hash4j.jar /app/hash4j.jar
COPY lib/LICENSE.hash4j /app/LICENSE.hash4j COPY lib/LICENSE.hash4j /app/LICENSE.hash4j
COPY scripts/objectstore /usr/local/bin/objectstore COPY scripts/objectstore /usr/local/bin/objectstore
RUN chmod 755 /usr/local/bin/objectstore COPY scripts/start-server.sh /usr/local/bin/objectstore-server
RUN chmod 755 /usr/local/bin/objectstore /usr/local/bin/objectstore-server
USER store USER store
EXPOSE 9000 EXPOSE 9000
ENTRYPOINT ["java", "-XX:MaxRAMPercentage=70", "-Dsun.net.httpserver.maxReqTime=30", "-Dsun.net.httpserver.maxRspTime=60", "-Dsun.net.httpserver.maxReqHeaders=64", "--add-modules", "jdk.httpserver,java.net.http", "-cp", "/app:/app/postgresql.jar:/app/hash4j.jar", "cloud.lunarsky.store.Main"] ENTRYPOINT ["/usr/local/bin/objectstore-server"]
+28 -2
View File
@@ -25,6 +25,8 @@ This does not cover Docker logs, swap, other temporary files, external backups,
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. 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.
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.
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. 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.
## CLI and tests ## CLI and tests
@@ -47,6 +49,30 @@ Signed `GET /_objectstore/capabilities` returns schema version 1, software versi
Run `sh scripts/test.sh` with JDK 21 to test from source. See [TESTS.md](TESTS.md) for coverage, the disposable Docker cluster suite, and the limits of those tests. Run `sh scripts/test.sh` with JDK 21 to test from source. See [TESTS.md](TESTS.md) for coverage, the disposable Docker cluster suite, and the limits of those tests.
## Browser access, transfer limits, and metrics
`CORS_ALLOWED_ORIGINS` is disabled by default. Set a comma-separated list of exact `http://` or `https://` origins to permit browser preflight for GET, HEAD, PUT, POST, and DELETE. Browsers still need a signed request or presigned URL; CORS does not grant access. Do not put secret access keys in browser code. For direct browser uploads, issue short-lived presigned URLs from a trusted server and allow that site's origin. Browser preflight requests count against the same admission limits as other requests.
The Docker image no longer has a fixed 30-second request or 60-second response deadline. `OBJECTSTORE_REQUEST_TIMEOUT_SECONDS` and `OBJECTSTORE_RESPONSE_TIMEOUT_SECONDS` default to `0` (no total transfer deadline); positive values are capped at one day. A reverse proxy may have its own upload size, buffering, idle timeout, and response timeout. Configure those for expected video sizes and slow clients. `MAX_OBJECT_BYTES` defaults to 128 MiB and can be raised up to 1 GiB; `MAX_TOTAL_BYTES` defaults to 2 GiB. For a 250 MB video workload, a starting configuration is `MAX_OBJECT_BYTES=536870912` (512 MiB) and a `MAX_TOTAL_BYTES` based on the actual free disk and retention plan. The in-flight cap remains 16 by default. Measure the target machine before raising it; 256 concurrent uploads can exhaust memory or disk bandwidth.
Set `METRICS_BEARER_TOKEN` to a random value of at least 32 characters to enable `GET /metrics` in Prometheus text format. Scrape with `Authorization: Bearer <token>` over a private network or HTTPS. The endpoint reports counts by response class, total request time, and in-flight requests without bucket or user labels. Keep the token private. Metrics are disabled when the variable is empty.
For a bounded local write baseline, run `python3 scripts/benchmark-writes.py --requests 100 --concurrency 8 --size 4096` with `S3_ACCESS_KEY` and `S3_SECRET_KEY` in the environment. It writes under a unique `benchmark/` prefix and deletes successful objects afterward. Results depend on CPU, disks, network, connection reuse, and durability settings; a laptop number does not predict another server. Run a mixed upload/download workload before changing concurrency or public limits.
## Cold snapshots
The local Compose stacks support a cold snapshot of **all** their named data volumes. Stop the stack first, then run one of the following with absolute paths:
```sh
docker compose --env-file /path/to/objectstore.env -f compose.yaml stop
sh scripts/snapshot-local.sh single backup /path/to/objectstore.env /path/to/objectstore-snapshot.tar
docker compose --env-file /path/to/cluster.env -f compose.cluster.yaml stop
sh scripts/snapshot-local.sh cluster backup /path/to/cluster.env /path/to/cluster-snapshot.tar
```
The script refuses to run while any service in that Compose project is running. It includes PostgreSQL and node volumes for the local cluster, checks each component archive, and writes a checksum manifest. Store the snapshot and a separate copy of the private environment, key-scope, credential, and encryption recovery material off the machine. To restore, build or pull the images, then use the same command with `restore` instead of `backup` on a **fresh empty** set of stopped volumes; the script refuses to overwrite nonempty volumes. Start the stack and run `objectstore verify` or the cluster repair check, then read test objects. The script refuses encrypted bind-mount overlays, which need a separate host-filesystem snapshot. A snapshot is not a substitute for an off-site restore drill. The local Compose cluster is still one physical-host prototype; this script is not a coordinated backup of a deployed multi-host cluster.
The server includes [hash4j](https://github.com/dynatrace-oss/hash4j) for streaming XXHash checksums. Its Apache-2.0 license is included at [lib/LICENSE.hash4j](lib/LICENSE.hash4j). The server includes [hash4j](https://github.com/dynatrace-oss/hash4j) for streaming XXHash checksums. Its Apache-2.0 license is included at [lib/LICENSE.hash4j](lib/LICENSE.hash4j).
## Local cluster prototype ## Local cluster prototype
@@ -80,7 +106,7 @@ CLUSTER_TLS_DIR=/private/objectstore-certs docker compose --env-file /path/to/cl
The files must be readable by container UID 10001 without making private keys or passwords world-readable. Add HTTPS URLs for additional nodes when expanding the cluster. The files must be readable by container UID 10001 without making private keys or passwords world-readable. Add HTTPS URLs for additional nodes when expanding the cluster.
This secures node traffic only. The local cluster still lacks automatic PostgreSQL failover, database TLS configuration, encryption at rest, and production multi-server validation. Its HTTP S3 gateway remains bound to localhost; use a separate trusted proxy for external TLS. Do not treat the TLS overlay as a production deployment. This secures node traffic only. The local cluster still lacks automatic PostgreSQL failover and production multi-server validation. PostgreSQL TLS must be configured separately, and at-rest encryption uses the host overlay described above. Its HTTP S3 gateway remains bound to localhost; use a separate trusted proxy for external TLS. Do not treat the TLS overlay as a production deployment.
## Metadata primary routing ## Metadata primary routing
@@ -134,6 +160,6 @@ ObjectStore uses the socket peer as the client IP and ignores forwarded-IP heade
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. 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, scoped credentials, and physical host verification remain absent. 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, 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 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. 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.
+5
View File
@@ -21,6 +21,7 @@ ObjectStore creates the default bucket at startup. All buckets share one capacit
- ✅ Configurable size limits and CLI verification - ✅ Configurable size limits and CLI verification
- ✅ Local cluster prototype with host-aware placement and optional node TLS - ✅ Local cluster prototype with host-aware placement and optional node TLS
- ✅ Opt-in repair, rebalance, guarded garbage collection, and metadata backup - ✅ Opt-in repair, rebalance, guarded garbage collection, and metadata backup
- ✅ Cold snapshot and restore tooling for the local Compose stacks
- ✅ Manual [two-machine durability and restore drill](tests/two-host/README.md) - ✅ Manual [two-machine durability and restore drill](tests/two-host/README.md)
- ⬜ Production multi-server deployment and metadata failover - ⬜ Production multi-server deployment and metadata failover
@@ -103,6 +104,10 @@ Maven (`pom.xml`):
See [client installation and examples](https://docs.lunarsky.cloud/objectstore/v0.0.8/client/install). The [AWT image manager](client/examples/README.md) is a small desktop example. See [client installation and examples](https://docs.lunarsky.cloud/objectstore/v0.0.8/client/install). The [AWT image manager](client/examples/README.md) is a small desktop example.
## Rust client
The [Rust adapter](rust-client/README.md) configures the official AWS SDK for path-style ObjectStore endpoints and streams file transfers. It is local source code, not a published crate.
## Disclaimer ## Disclaimer
ObjectStore is independent software. It is not affiliated with, sponsored by, or endorsed by Amazon or Amazon Web Services (AWS). “S3-compatible” describes only the API subset listed above. ObjectStore is independent software. It is not affiliated with, sponsored by, or endorsed by Amazon or Amazon Web Services (AWS). “S3-compatible” describes only the API subset listed above.
+2 -2
View File
@@ -17,7 +17,7 @@ The script compiles the source and test programs into `out/classes`, then runs:
| Test | Checks | | Test | Checks |
| --- | --- | | --- | --- |
| `StoreTest` | Signature V4 and signed-stream vectors, CRC64NVME and XXHash reference vectors, local writes and reads, quotas, restart persistence for objects, checksums, ACLs, attributes, buckets, and versions, multipart recovery, legacy reads, locking, and corruption rejection. | | `StoreTest` | Signature V4 and signed-stream vectors, CRC64NVME and XXHash reference vectors, local writes and reads, quotas, restart persistence for objects, checksums, ACLs, attributes, buckets, and versions, multipart recovery, legacy reads, locking, and corruption rejection. |
| `ConcurrencyTest` | Atomic local overwrites and consistent reads, listings, and deletes during concurrent access. | | `ConcurrencyTest` | Atomic local overwrites, consistent reads, listings and deletes, plus concurrent quota enforcement and restart recovery. |
| `HttpTest` | Signed capability discovery, presigned URLs, streaming uploads and trailers, object and bucket operations, ACL grants with a second access key and public reads, copies, checksum persistence and rejection, ranges, listing, metadata, tags, multipart uploads, versioning, and signed virtual-hosted requests in single-node mode. | | `HttpTest` | Signed capability discovery, presigned URLs, streaming uploads and trailers, object and bucket operations, ACL grants with a second access key and public reads, copies, checksum persistence and rejection, ranges, listing, metadata, tags, multipart uploads, versioning, and signed virtual-hosted requests in single-node mode. |
| `ClientLimitsTest` | Disabled defaults, trusted-proxy address validation, ignored untrusted headers, per-IP request refusal, and paced response bytes. | | `ClientLimitsTest` | Disabled defaults, trusted-proxy address validation, ignored untrusted headers, per-IP request refusal, and paced response bytes. |
| `EncryptedVolumeTest` | Marker acceptance and refusal when the configured encrypted directory is missing, mismatched, or a symlink. | | `EncryptedVolumeTest` | Marker acceptance and refusal when the configured encrypted directory is missing, mismatched, or a symlink. |
@@ -69,6 +69,6 @@ The [manual two-machine drill](tests/two-host/README.md) uses machine A and mach
- Container stops are not physical power cuts or disk failures. The automated suite does not reboot a host or test every possible crash point. - Container stops are not physical power cuts or disk failures. The automated suite does not reboot a host or test every possible crash point.
- The Compose nodes share one machine. Passing the local-only quorum override does not demonstrate durability across independent hosts, racks, or sites. - The Compose nodes share one machine. Passing the local-only quorum override does not demonstrate durability across independent hosts, racks, or sites.
- The suite does not test automatic metadata failover, an off-site backup restore, prolonged load, or full AWS S3 compatibility. - The suite does not test automatic metadata failover, an off-site backup restore, prolonged load, or full AWS S3 compatibility. `scripts/test.sh` checks scoped keys, CORS, and metrics. A separate local cold-snapshot drill restored one object into fresh single-node and cluster Compose projects and confirmed its bytes; the single-node restore also refused a nonempty destination. This does not test a multi-host restore. The Rust client passed live local upload/download and presigned GET/PUT smoke tests, but is not covered by the Java test script.
See [Limits and safety](README.md#limits-and-safety) before evaluating any multi-server deployment. See [Limits and safety](README.md#limits-and-safety) before evaluating any multi-server deployment.
+9 -1
View File
@@ -4,7 +4,11 @@ A small, synchronous S3-compatible client built with the JDK alone. It uses path
## Build and test ## Build and test
Requires JDK 21 or newer. No Maven, Gradle, or third-party Java libraries are needed. Requires JDK 21 or newer. Building from source needs no Maven or Gradle, and the client has no third-party runtime dependencies.
For Maven or Gradle consumers, release 0.0.8 is published as
`cloud.lunarsky:objectstore-client:0.0.8` at
`https://repo.lunarsky.cloud/`. See the [installation examples](https://docs.lunarsky.cloud/objectstore/v0.0.8/client/install).
```sh ```sh
bash client/scripts/test.sh bash client/scripts/test.sh
@@ -13,6 +17,10 @@ bash client/scripts/build.sh
Run these commands from the ObjectStore repository root. The second command writes `client/dist/objectstore-client.jar` and `client/dist/javadoc/`. Run these commands from the ObjectStore repository root. The second command writes `client/dist/objectstore-client.jar` and `client/dist/javadoc/`.
To assemble a versioned Maven directory from a matching source tag, run
`bash client/scripts/build-maven-repo.sh VERSION`. It writes the JAR, POM,
sources, Javadocs, metadata, and checksums under `client/dist/maven-repo/`.
The [AWT image manager](examples/README.md) is a small drag-and-drop app for trying uploads, listing, previews, downloads, and deletes against an existing bucket. The [AWT image manager](examples/README.md) is a small drag-and-drop app for trying uploads, listing, previews, downloads, and deletes against an existing bucket.
## Use ## Use
+68
View File
@@ -0,0 +1,68 @@
#!/usr/bin/env bash
set -euo pipefail
version="${1:?usage: build-maven-repo.sh VERSION}"
if [[ ! "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+([.-][A-Za-z0-9]+)*$ ]]; then
echo "Invalid version: $version" >&2
exit 1
fi
cd "$(dirname "$0")/.."
bash scripts/build.sh
artifact_root="dist/maven-repo/cloud/lunarsky/objectstore-client"
version_dir="$artifact_root/$version"
mkdir -p "$version_dir"
base="objectstore-client-$version"
cp dist/objectstore-client.jar "$version_dir/$base.jar"
jar --create --file "$version_dir/$base-sources.jar" \
-C src/main/java . -C dist/classes META-INF/LICENSE
jar --create --file "$version_dir/$base-javadoc.jar" \
-C dist/javadoc . -C dist/classes META-INF/LICENSE
cat > "$version_dir/$base.pom" <<EOF
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>cloud.lunarsky</groupId>
<artifactId>objectstore-client</artifactId>
<version>$version</version>
<name>ObjectStore Java Client</name>
<description>JDK-only client for S3-compatible object storage.</description>
<url>https://github.com/LunarSkyOSS/ObjectStore</url>
<licenses>
<license>
<name>MIT License</name>
<url>https://opensource.org/license/mit</url>
</license>
</licenses>
<developers>
<developer><name>Justin Haag</name></developer>
</developers>
<scm>
<connection>scm:git:https://github.com/LunarSkyOSS/ObjectStore.git</connection>
<url>https://github.com/LunarSkyOSS/ObjectStore</url>
</scm>
</project>
EOF
mapfile -t versions < <(find "$artifact_root" -mindepth 1 -maxdepth 1 -type d -printf '%f\n' | sort -V)
latest="${versions[${#versions[@]}-1]}"
{
printf '%s\n' '<?xml version="1.0" encoding="UTF-8"?>' '<metadata>'
printf ' <groupId>cloud.lunarsky</groupId>\n <artifactId>objectstore-client</artifactId>\n'
printf ' <versioning>\n <latest>%s</latest>\n <release>%s</release>\n <versions>\n' "$latest" "$latest"
for item in "${versions[@]}"; do printf ' <version>%s</version>\n' "$item"; done
printf ' </versions>\n <lastUpdated>%s</lastUpdated>\n </versioning>\n</metadata>\n' "$(date -u +%Y%m%d%H%M%S)"
} > "$artifact_root/maven-metadata.xml"
for file in "$version_dir"/* "$artifact_root/maven-metadata.xml"; do
[[ "$file" == *.md5 || "$file" == *.sha1 || "$file" == *.sha256 ]] && continue
md5sum "$file" | cut -d ' ' -f 1 > "$file.md5"
sha1sum "$file" | cut -d ' ' -f 1 > "$file.sha1"
sha256sum "$file" | cut -d ' ' -f 1 > "$file.sha256"
done
echo "Built $version_dir"
+5
View File
@@ -13,11 +13,16 @@ services:
S3_BUCKET: ${S3_BUCKET:-objects} S3_BUCKET: ${S3_BUCKET:-objects}
S3_REGION: ${S3_REGION:-us-east-1} S3_REGION: ${S3_REGION:-us-east-1}
S3_CREDENTIALS_FILE: ${S3_CREDENTIALS_FILE:-} S3_CREDENTIALS_FILE: ${S3_CREDENTIALS_FILE:-}
S3_KEY_SCOPES_FILE: ${S3_KEY_SCOPES_FILE:-}
METRICS_BEARER_TOKEN: ${METRICS_BEARER_TOKEN:-}
MAX_OBJECT_BYTES: ${MAX_OBJECT_BYTES:-134217728} MAX_OBJECT_BYTES: ${MAX_OBJECT_BYTES:-134217728}
MAX_TOTAL_BYTES: ${MAX_TOTAL_BYTES:-2147483648} MAX_TOTAL_BYTES: ${MAX_TOTAL_BYTES:-2147483648}
MAX_IN_FLIGHT_REQUESTS: ${MAX_IN_FLIGHT_REQUESTS:-16} MAX_IN_FLIGHT_REQUESTS: ${MAX_IN_FLIGHT_REQUESTS:-16}
HTTP_BACKLOG: ${HTTP_BACKLOG:-64} HTTP_BACKLOG: ${HTTP_BACKLOG:-64}
S3_VIRTUAL_HOST_SUFFIX: ${S3_VIRTUAL_HOST_SUFFIX:-} S3_VIRTUAL_HOST_SUFFIX: ${S3_VIRTUAL_HOST_SUFFIX:-}
CORS_ALLOWED_ORIGINS: ${CORS_ALLOWED_ORIGINS:-}
OBJECTSTORE_REQUEST_TIMEOUT_SECONDS: ${OBJECTSTORE_REQUEST_TIMEOUT_SECONDS:-0}
OBJECTSTORE_RESPONSE_TIMEOUT_SECONDS: ${OBJECTSTORE_RESPONSE_TIMEOUT_SECONDS:-0}
PUBLIC_REQUESTS_PER_SECOND: ${PUBLIC_REQUESTS_PER_SECOND:-0} PUBLIC_REQUESTS_PER_SECOND: ${PUBLIC_REQUESTS_PER_SECOND:-0}
PUBLIC_REQUEST_BURST: ${PUBLIC_REQUEST_BURST:-} PUBLIC_REQUEST_BURST: ${PUBLIC_REQUEST_BURST:-}
PUBLIC_BYTES_PER_SECOND: ${PUBLIC_BYTES_PER_SECOND:-0} PUBLIC_BYTES_PER_SECOND: ${PUBLIC_BYTES_PER_SECOND:-0}
+6
View File
@@ -4,16 +4,22 @@ services:
image: lunarsky-objectstore:local image: lunarsky-objectstore:local
restart: unless-stopped restart: unless-stopped
environment: environment:
JAVA_TOOL_OPTIONS: "-XX:+UseSerialGC -Xms64m"
OBJECTSTORE_REQUEST_TIMEOUT_SECONDS: ${OBJECTSTORE_REQUEST_TIMEOUT_SECONDS:-0}
OBJECTSTORE_RESPONSE_TIMEOUT_SECONDS: ${OBJECTSTORE_RESPONSE_TIMEOUT_SECONDS:-0}
S3_ACCESS_KEY: ${S3_ACCESS_KEY:?Set S3_ACCESS_KEY in .env} S3_ACCESS_KEY: ${S3_ACCESS_KEY:?Set S3_ACCESS_KEY in .env}
S3_SECRET_KEY: ${S3_SECRET_KEY:?Set S3_SECRET_KEY in .env} S3_SECRET_KEY: ${S3_SECRET_KEY:?Set S3_SECRET_KEY in .env}
S3_BUCKET: ${S3_BUCKET:-objects} S3_BUCKET: ${S3_BUCKET:-objects}
S3_REGION: ${S3_REGION:-us-east-1} S3_REGION: ${S3_REGION:-us-east-1}
S3_CREDENTIALS_FILE: ${S3_CREDENTIALS_FILE:-} S3_CREDENTIALS_FILE: ${S3_CREDENTIALS_FILE:-}
S3_KEY_SCOPES_FILE: ${S3_KEY_SCOPES_FILE:-}
METRICS_BEARER_TOKEN: ${METRICS_BEARER_TOKEN:-}
MAX_OBJECT_BYTES: ${MAX_OBJECT_BYTES:-134217728} MAX_OBJECT_BYTES: ${MAX_OBJECT_BYTES:-134217728}
MAX_TOTAL_BYTES: ${MAX_TOTAL_BYTES:-2147483648} MAX_TOTAL_BYTES: ${MAX_TOTAL_BYTES:-2147483648}
MAX_IN_FLIGHT_REQUESTS: ${MAX_IN_FLIGHT_REQUESTS:-16} MAX_IN_FLIGHT_REQUESTS: ${MAX_IN_FLIGHT_REQUESTS:-16}
HTTP_BACKLOG: ${HTTP_BACKLOG:-64} HTTP_BACKLOG: ${HTTP_BACKLOG:-64}
S3_VIRTUAL_HOST_SUFFIX: ${S3_VIRTUAL_HOST_SUFFIX:-} S3_VIRTUAL_HOST_SUFFIX: ${S3_VIRTUAL_HOST_SUFFIX:-}
CORS_ALLOWED_ORIGINS: ${CORS_ALLOWED_ORIGINS:-}
PUBLIC_REQUESTS_PER_SECOND: ${PUBLIC_REQUESTS_PER_SECOND:-0} PUBLIC_REQUESTS_PER_SECOND: ${PUBLIC_REQUESTS_PER_SECOND:-0}
PUBLIC_REQUEST_BURST: ${PUBLIC_REQUEST_BURST:-} PUBLIC_REQUEST_BURST: ${PUBLIC_REQUEST_BURST:-}
PUBLIC_BYTES_PER_SECOND: ${PUBLIC_BYTES_PER_SECOND:-0} PUBLIC_BYTES_PER_SECOND: ${PUBLIC_BYTES_PER_SECOND:-0}
+2339
View File
File diff suppressed because it is too large. Load diff
+17
View File
@@ -0,0 +1,17 @@
[package]
name = "lunarsky-objectstore-client"
version = "0.0.1"
edition = "2021"
license = "MIT"
description = "Small Rust integration layer for LunarSky ObjectStore"
[dependencies]
aws-config = { version = "1", default-features = false, features = ["default-https-client", "rt-tokio"] }
aws-credential-types = "1"
aws-sdk-s3 = "1"
aws-types = "1"
tokio = { version = "1", features = ["fs", "io-util"] }
url = "2"
[dev-dependencies]
tokio = { version = "1", features = ["macros", "rt-multi-thread", "fs", "io-util"] }
+27
View File
@@ -0,0 +1,27 @@
# ObjectStore Rust client
This small adapter configures the official AWS SDK for Rust for ObjectStore's path-style S3 endpoint. It reuses the SDK's signing, connection pooling, and streaming body support. `put_file` streams a file and `get_to_writer` streams a response into any Tokio async writer. `put_bytes` accepts an existing buffer; `presigned_get_url` and `presigned_put_url` make short-lived links for trusted server code. The underlying SDK client is available through `sdk()` for listing, multipart uploads, and other supported S3 operations.
```toml
[dependencies]
lunarsky-objectstore-client = { path = "../rust-client" }
tokio = { version = "1", features = ["macros", "rt-multi-thread", "fs"] }
```
```rust
use lunarsky_objectstore_client::ObjectStoreClient;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let client = ObjectStoreClient::connect(
"http://127.0.0.1:9000", "us-east-1",
&std::env::var("S3_ACCESS_KEY")?, &std::env::var("S3_SECRET_KEY")?,
).await?;
client.put_file("objects", "example.bin", "example.bin").await?;
let mut output = tokio::fs::File::create("downloaded.bin").await?;
client.get_to_writer("objects", "example.bin", &mut output).await?;
Ok(())
}
```
The constructor requires HTTPS except for loopback tests. Keep access keys on the server, never in browser code. The wrapper is untested against every AWS S3 option; inspect ObjectStore's supported-operation list before using SDK methods directly. This crate is not published yet.
+27
View File
@@ -0,0 +1,27 @@
use lunarsky_objectstore_client::ObjectStoreClient;
use std::time::Duration;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let args: Vec<String> = std::env::args().collect();
if args.len() != 6 {
return Err(
"usage: presign ENDPOINT BUCKET KEY ACCESS_KEY get|put (set S3_SECRET_KEY)".into(),
);
}
let client = ObjectStoreClient::connect(
&args[1],
"us-east-1",
&args[4],
&std::env::var("S3_SECRET_KEY")?,
)
.await?;
let expiry = Duration::from_secs(60);
let url = match args[5].as_str() {
"get" => client.presigned_get_url(&args[2], &args[3], expiry).await?,
"put" => client.presigned_put_url(&args[2], &args[3], expiry).await?,
_ => return Err("method must be get or put".into()),
};
println!("{url}");
Ok(())
}
+22
View File
@@ -0,0 +1,22 @@
use lunarsky_objectstore_client::ObjectStoreClient;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let args: Vec<String> = std::env::args().collect();
if args.len() != 7 {
return Err(
"usage: smoke ENDPOINT BUCKET KEY INPUT OUTPUT ACCESS_KEY (set S3_SECRET_KEY)".into(),
);
}
let client = ObjectStoreClient::connect(
&args[1],
"us-east-1",
&args[6],
&std::env::var("S3_SECRET_KEY")?,
)
.await?;
client.put_file(&args[2], &args[3], &args[4]).await?;
let mut file = tokio::fs::File::create(&args[5]).await?;
client.get_to_writer(&args[2], &args[3], &mut file).await?;
Ok(())
}
+175
View File
@@ -0,0 +1,175 @@
use aws_config::BehaviorVersion;
use aws_credential_types::Credentials;
use aws_sdk_s3::{operation, presigning::PresigningConfig, primitives::ByteStream, Client};
use aws_types::region::Region;
use std::{error::Error, path::Path, time::Duration};
use tokio::io::{AsyncWrite, AsyncWriteExt};
use url::Url;
pub type ClientResult<T> = Result<T, Box<dyn Error + Send + Sync>>;
#[derive(Clone)]
pub struct ObjectStoreClient {
client: Client,
}
impl ObjectStoreClient {
pub async fn connect(
endpoint: &str,
region: &str,
access_key: &str,
secret_key: &str,
) -> ClientResult<Self> {
let parsed = Url::parse(endpoint)?;
let host = parsed.host_str().ok_or("endpoint needs a host")?;
let local = matches!(host, "localhost" | "127.0.0.1" | "::1");
if parsed.scheme() != "https" && !(parsed.scheme() == "http" && local) {
return Err("use HTTPS for a nonlocal ObjectStore endpoint".into());
}
if parsed.path() != "/"
|| parsed.query().is_some()
|| parsed.fragment().is_some()
|| !parsed.username().is_empty()
|| parsed.password().is_some()
{
return Err("endpoint must be an origin without path, query, or credentials".into());
}
let credentials = Credentials::new(access_key, secret_key, None, None, "objectstore");
let shared = aws_config::defaults(BehaviorVersion::latest())
.credentials_provider(credentials)
.region(Region::new(region.to_owned()))
.load()
.await;
let config = aws_sdk_s3::config::Builder::from(&shared)
.endpoint_url(endpoint)
.force_path_style(true)
.build();
Ok(Self {
client: Client::from_conf(config),
})
}
pub fn sdk(&self) -> &Client {
&self.client
}
pub async fn put_file(
&self,
bucket: &str,
key: &str,
path: impl AsRef<Path>,
) -> ClientResult<operation::put_object::PutObjectOutput> {
let body = ByteStream::from_path(path.as_ref().to_path_buf()).await?;
Ok(self
.client
.put_object()
.bucket(bucket)
.key(key)
.body(body)
.send()
.await?)
}
pub async fn put_bytes(
&self,
bucket: &str,
key: &str,
bytes: Vec<u8>,
) -> ClientResult<operation::put_object::PutObjectOutput> {
Ok(self
.client
.put_object()
.bucket(bucket)
.key(key)
.body(ByteStream::from(bytes))
.send()
.await?)
}
pub async fn get_to_writer<W: AsyncWrite + Unpin>(
&self,
bucket: &str,
key: &str,
writer: &mut W,
) -> ClientResult<u64> {
let response = self
.client
.get_object()
.bucket(bucket)
.key(key)
.send()
.await?;
let mut reader = response.body.into_async_read();
let bytes = tokio::io::copy(&mut reader, writer).await?;
writer.flush().await?;
Ok(bytes)
}
pub async fn delete(&self, bucket: &str, key: &str) -> ClientResult<()> {
self.client
.delete_object()
.bucket(bucket)
.key(key)
.send()
.await?;
Ok(())
}
pub async fn presigned_get_url(
&self,
bucket: &str,
key: &str,
expires_in: Duration,
) -> ClientResult<String> {
let request = self
.client
.get_object()
.bucket(bucket)
.key(key)
.presigned(PresigningConfig::expires_in(expires_in)?)
.await?;
Ok(request.uri().to_string())
}
pub async fn presigned_put_url(
&self,
bucket: &str,
key: &str,
expires_in: Duration,
) -> ClientResult<String> {
let request = self
.client
.put_object()
.bucket(bucket)
.key(key)
.presigned(PresigningConfig::expires_in(expires_in)?)
.await?;
Ok(request.uri().to_string())
}
}
#[cfg(test)]
mod tests {
use super::ObjectStoreClient;
#[tokio::test]
async fn rejects_insecure_remote_endpoint() {
assert!(
ObjectStoreClient::connect("http://storage.example", "us-east-1", "key", "secret")
.await
.is_err()
);
}
#[tokio::test]
async fn rejects_endpoint_with_path() {
assert!(ObjectStoreClient::connect(
"https://storage.example/bucket",
"us-east-1",
"key",
"secret"
)
.await
.is_err());
}
}
+125
View File
@@ -0,0 +1,125 @@
#!/usr/bin/env python3
import argparse
import concurrent.futures
import hashlib
import hmac
import http.client
import json
import os
import statistics
import threading
import time
import uuid
from datetime import datetime, timezone
from urllib.parse import quote, urlsplit
def sign(method, path, body, host, access, secret, region):
now = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
date = now[:8]
digest = hashlib.sha256(body).hexdigest()
names = "host;x-amz-content-sha256;x-amz-date"
headers = {"Host": host, "x-amz-content-sha256": digest, "x-amz-date": now}
canonical = (f"{method}\n{path}\n\nhost:{host}\nx-amz-content-sha256:{digest}\n"
f"x-amz-date:{now}\n\n{names}\n{digest}")
scope = f"{date}/{region}/s3/aws4_request"
message = f"AWS4-HMAC-SHA256\n{now}\n{scope}\n{hashlib.sha256(canonical.encode()).hexdigest()}"
key = ("AWS4" + secret).encode()
for part in (date, region, "s3", "aws4_request"):
key = hmac.new(key, part.encode(), hashlib.sha256).digest()
signature = hmac.new(key, message.encode(), hashlib.sha256).hexdigest()
headers["Authorization"] = (f"AWS4-HMAC-SHA256 Credential={access}/{scope},"
f"SignedHeaders={names},Signature={signature}")
return headers
def main():
parser = argparse.ArgumentParser(description="Bounded ObjectStore PUT benchmark")
parser.add_argument("--endpoint", default="http://127.0.0.1:9000")
parser.add_argument("--bucket", default="objects")
parser.add_argument("--region", default="us-east-1")
parser.add_argument("--requests", type=int, default=100)
parser.add_argument("--concurrency", type=int, default=8)
parser.add_argument("--size", type=int, default=4096)
args = parser.parse_args()
if not 1 <= args.requests <= 5000 or not 1 <= args.concurrency <= 256 or not 1 <= args.size <= 1048576:
parser.error("requests 1–5000, concurrency 1–256, size 1–1048576 are required")
access, secret = os.environ["S3_ACCESS_KEY"], os.environ["S3_SECRET_KEY"]
endpoint = urlsplit(args.endpoint)
if endpoint.scheme not in ("http", "https") or not endpoint.hostname or endpoint.path not in ("", "/"):
parser.error("endpoint must be an HTTP(S) origin")
if endpoint.scheme == "http" and endpoint.hostname not in ("localhost", "127.0.0.1", "::1"):
parser.error("use HTTPS outside localhost")
host = endpoint.netloc
payload = os.urandom(args.size)
prefix = f"benchmark/{uuid.uuid4().hex}/"
local = threading.local()
completed = []
lock = threading.Lock()
def connection():
if not hasattr(local, "connection"):
cls = http.client.HTTPSConnection if endpoint.scheme == "https" else http.client.HTTPConnection
local.connection = cls(endpoint.hostname, endpoint.port, timeout=30)
return local.connection
def request(method, key, body=b""):
path = "/" + quote(args.bucket, safe="") + "/" + quote(key, safe="/~")
conn = connection()
conn.request(method, path, body, sign(method, path, body, host, access, secret, args.region))
response = conn.getresponse()
data = response.read()
return response.status, data
def put(index):
key = prefix + str(index)
start = time.perf_counter()
status, body = request("PUT", key, payload)
elapsed = time.perf_counter() - start
if status != 200:
raise RuntimeError(f"PUT {index} returned {status}: {body[:200]!r}")
with lock:
completed.append(key)
return elapsed
started = time.perf_counter()
failures = []
latencies = []
try:
with concurrent.futures.ThreadPoolExecutor(max_workers=args.concurrency) as pool:
futures = [pool.submit(put, index) for index in range(args.requests)]
for future in concurrent.futures.as_completed(futures):
try:
latencies.append(future.result())
except Exception as error:
failures.append(str(error))
duration = time.perf_counter() - started
ordered = sorted(latencies)
result = {
"completed": len(ordered), "failed": len(failures), "seconds": round(duration, 3),
"writes_per_second": round(len(ordered) / duration, 1),
"median_ms": round(statistics.median(ordered) * 1000, 1) if ordered else None,
"p95_ms": round(ordered[min(len(ordered) - 1, int(len(ordered) * .95))] * 1000, 1)
if ordered else None, "size_bytes": args.size, "concurrency": args.concurrency,
"prefix": prefix,
}
print(json.dumps(result, indent=2))
for error in failures[:5]:
print(error)
finally:
cleanup_failed = 0
for key in completed:
try:
status, _ = request("DELETE", key)
if status != 204:
cleanup_failed += 1
except Exception:
cleanup_failed += 1
if cleanup_failed:
print(f"Cleanup failed for {cleanup_failed} objects under {prefix}")
if failures:
raise SystemExit(1)
if __name__ == "__main__":
main()
+84
View File
@@ -0,0 +1,84 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
mode=${1:?Usage: sh scripts/snapshot-local.sh single|cluster backup|restore ENV_FILE ARCHIVE}
action=${2:?Usage: sh scripts/snapshot-local.sh single|cluster backup|restore ENV_FILE ARCHIVE}
env_file=${3:?Usage: sh scripts/snapshot-local.sh single|cluster backup|restore ENV_FILE ARCHIVE}
archive=${4:?Usage: sh scripts/snapshot-local.sh single|cluster backup|restore ENV_FILE ARCHIVE}
[ -f "$env_file" ] || { echo "Environment file is missing" >&2; exit 1; }
encrypted_root=
while IFS= read -r line; do
case "$line" in ENCRYPTED_STORAGE_ROOT=*) encrypted_root=${line#*=} ;; esac
done < "$env_file"
[ -z "$encrypted_root" ] || {
echo "Encrypted bind-mount overlays are not covered by this volume snapshot tool" >&2
exit 1
}
case "$mode" in
single)
compose=compose.yaml
components='objectstore:/data'
;;
cluster)
compose=compose.cluster.yaml
components='metadata:/var/lib/postgresql/data metadata-recovery:/var/lib/postgresql/data node-a:/data node-b:/data node-c:/data node-d:/data'
;;
*) echo "Unknown snapshot mode" >&2; exit 1 ;;
esac
case "$action" in backup|restore) ;; *) echo "Unknown snapshot action" >&2; exit 1 ;; esac
if [ "$mode" = cluster ]; then
running=$(docker compose --env-file "$env_file" -f "$compose" \
--profile recovery --profile maintenance --profile automatic --profile expansion \
ps --status running --services)
else
running=$(docker compose --env-file "$env_file" -f "$compose" ps --status running --services)
fi
[ -z "$running" ] || { echo "Stop all services in this Compose project before $action: $running" >&2; exit 1; }
umask 077
stage=$(mktemp -d)
trap 'rm -rf "$stage"' EXIT HUP INT TERM
if [ "$action" = backup ]; then
[ ! -e "$archive" ] || { echo "Snapshot already exists" >&2; exit 1; }
printf '%s\n' "$mode" > "$stage/MODE"
for component in $components; do
service=${component%%:*}
directory=${component#*:}
docker compose --env-file "$env_file" -f "$compose" run --rm --no-deps \
--entrypoint tar "$service" -C "$directory" -cf - . > "$stage/$service.tar"
tar -tf "$stage/$service.tar" > /dev/null
done
(cd "$stage" && sha256sum ./*.tar > SHA256SUMS)
temporary=$(mktemp "${archive}.tmp.XXXXXX")
trap 'rm -f "$temporary"; rm -rf "$stage"' EXIT HUP INT TERM
tar -C "$stage" -cf "$temporary" .
mv "$temporary" "$archive"
echo "Cold $mode snapshot written to $archive"
else
[ -f "$archive" ] || { echo "Snapshot is missing" >&2; exit 1; }
tar -tf "$archive" > /dev/null
tar -C "$stage" -xf "$archive"
[ "$(cat "$stage/MODE")" = "$mode" ] || { echo "Snapshot mode mismatch" >&2; exit 1; }
(cd "$stage" && sha256sum -c SHA256SUMS)
for component in $components; do
service=${component%%:*}
directory=${component#*:}
[ -f "$stage/$service.tar" ] || { echo "Snapshot component missing: $service" >&2; exit 1; }
docker compose --env-file "$env_file" -f "$compose" run --rm --no-deps \
--entrypoint sh "$service" -c \
'test -z "$(find "$1" -mindepth 1 -print -quit)"' sh "$directory" || {
echo "Restore destination is not empty: $service" >&2
exit 1
}
done
for component in $components; do
service=${component%%:*}
directory=${component#*:}
docker compose --env-file "$env_file" -f "$compose" run --rm --no-deps \
--entrypoint tar "$service" -C "$directory" -xpf - < "$stage/$service.tar"
done
echo "Cold $mode snapshot restored; start services and run verification"
fi
+23
View File
@@ -0,0 +1,23 @@
#!/bin/sh
set -eu
set -- -XX:MaxRAMPercentage=70 -Dsun.net.httpserver.maxReqHeaders=64
for setting in request response; do
case "$setting" in
request) value=${OBJECTSTORE_REQUEST_TIMEOUT_SECONDS:-0}; property=maxReqTime ;;
response) value=${OBJECTSTORE_RESPONSE_TIMEOUT_SECONDS:-0}; property=maxRspTime ;;
esac
case "$value" in
''|*[!0-9]*) echo "Invalid $setting timeout" >&2; exit 1 ;;
esac
while [ "${value#0}" != "$value" ]; do value=${value#0}; done
value=${value:-0}
[ "${#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))"
fi
done
exec java "$@" --add-modules jdk.httpserver,java.net.http \
-cp /app:/app/postgresql.jar:/app/hash4j.jar cloud.lunarsky.store.Main
+1
View File
@@ -8,6 +8,7 @@ java --add-modules jdk.httpserver -cp out/classes:lib/hash4j-0.30.0.jar cloud.lu
java --add-modules jdk.httpserver -cp out/classes:lib/hash4j-0.30.0.jar cloud.lunarsky.store.ConcurrencyTest java --add-modules jdk.httpserver -cp out/classes:lib/hash4j-0.30.0.jar cloud.lunarsky.store.ConcurrencyTest
java --add-modules jdk.httpserver,java.net.http -cp out/classes:lib/hash4j-0.30.0.jar cloud.lunarsky.store.HttpTest java --add-modules jdk.httpserver,java.net.http -cp out/classes:lib/hash4j-0.30.0.jar cloud.lunarsky.store.HttpTest
java --add-modules jdk.httpserver,java.net.http -cp out/classes:lib/hash4j-0.30.0.jar cloud.lunarsky.store.ClientLimitsTest java --add-modules jdk.httpserver,java.net.http -cp out/classes:lib/hash4j-0.30.0.jar cloud.lunarsky.store.ClientLimitsTest
java --add-modules jdk.httpserver,java.net.http -cp out/classes:lib/hash4j-0.30.0.jar cloud.lunarsky.store.FeatureTest
java -cp out/classes:lib/hash4j-0.30.0.jar cloud.lunarsky.store.EncryptedVolumeTest java -cp out/classes:lib/hash4j-0.30.0.jar cloud.lunarsky.store.EncryptedVolumeTest
java --add-modules jdk.httpserver,java.net.http -cp out/classes:lib/hash4j-0.30.0.jar cloud.lunarsky.store.ClusterNodeTest java --add-modules jdk.httpserver,java.net.http -cp out/classes:lib/hash4j-0.30.0.jar cloud.lunarsky.store.ClusterNodeTest
java --add-modules jdk.httpserver,java.net.http -cp out/classes:lib/hash4j-0.30.0.jar cloud.lunarsky.store.ClusterTlsTest java --add-modules jdk.httpserver,java.net.http -cp out/classes:lib/hash4j-0.30.0.jar cloud.lunarsky.store.ClusterTlsTest
@@ -127,7 +127,7 @@ final class AwsChunkedInputStream extends FilterInputStream {
if (!Base64.getEncoder().encodeToString(trailerChecksum()).equals(trailerValue)) if (!Base64.getEncoder().encodeToString(trailerChecksum()).equals(trailerValue))
throw new StoreException(400, "BadDigest", "Checksum trailer mismatch"); throw new StoreException(400, "BadDigest", "Checksum trailer mismatch");
String signature = line(); String signature = line();
if (!signature.matches("x-amz-trailer-signature=[0-9a-f]{64}")) if (!signature.matches("x-amz-trailer-signature:[0-9a-f]{64}"))
throw invalid("Missing trailer signature"); throw invalid("Missing trailer signature");
String toSign = "AWS4-HMAC-SHA256-TRAILER\n" + authorization.date() + "\n" + String toSign = "AWS4-HMAC-SHA256-TRAILER\n" + authorization.date() + "\n" +
authorization.scope() + "\n" + previousSignature + "\n" + authorization.scope() + "\n" + previousSignature + "\n" +
+83
View File
@@ -0,0 +1,83 @@
package cloud.lunarsky.store;
import com.sun.net.httpserver.HttpExchange;
import java.io.IOException;
import java.net.URI;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
final class BrowserCors {
private static final Set<String> METHODS = Set.of("GET", "HEAD", "PUT", "POST", "DELETE");
private static final Set<String> HEADERS = Set.of("authorization", "content-type", "content-md5",
"range", "if-match", "if-none-match");
private final Set<String> origins;
private BrowserCors(Set<String> origins) { this.origins = origins; }
static BrowserCors disabled() { return new BrowserCors(Set.of()); }
static BrowserCors fromEnvironment(Map<String, String> env) {
String value = env.getOrDefault("CORS_ALLOWED_ORIGINS", "").trim();
if (value.isEmpty()) return disabled();
Set<String> allowed = new HashSet<>();
for (String item : value.split(",", -1)) {
String origin = item.trim();
URI uri;
try { uri = URI.create(origin); }
catch (IllegalArgumentException error) { throw new IllegalArgumentException("Invalid CORS origin", error); }
if (origin.length() > 255 || uri.getScheme() == null ||
!Set.of("http", "https").contains(uri.getScheme()) ||
uri.getHost() == null || uri.getRawUserInfo() != null ||
uri.getRawQuery() != null || uri.getRawFragment() != null ||
uri.getRawPath() != null && !uri.getRawPath().isEmpty() ||
!origin.equals(uri.getScheme() + "://" + uri.getRawAuthority()))
throw new IllegalArgumentException("CORS origins must be exact http(s) origins");
allowed.add(origin);
}
if (allowed.size() > 32) throw new IllegalArgumentException("Too many CORS origins");
return new BrowserCors(Set.copyOf(allowed));
}
void decorate(HttpExchange exchange) {
if (origins.isEmpty()) return;
exchange.getResponseHeaders().set("Vary", "Origin");
String origin = exchange.getRequestHeaders().getFirst("Origin");
if (origin == null || !origins.contains(origin)) return;
exchange.getResponseHeaders().set("Access-Control-Allow-Origin", origin);
exchange.getResponseHeaders().set("Access-Control-Expose-Headers",
"ETag, Content-Length, Content-Range, Last-Modified, x-amz-request-id, " +
"x-amz-version-id, x-amz-delete-marker, x-amz-checksum-crc64nvme, x-amz-checksum-sha256");
}
boolean preflight(HttpExchange exchange) throws IOException {
if (!exchange.getRequestMethod().equals("OPTIONS") || origins.isEmpty()) return false;
String origin = exchange.getRequestHeaders().getFirst("Origin");
if (origin == null || !origins.contains(origin))
throw new StoreException(403, "AccessDenied", "CORS origin is not allowed");
String method = exchange.getRequestHeaders().getFirst("Access-Control-Request-Method");
if (method == null || !METHODS.contains(method))
throw new StoreException(403, "AccessDenied", "CORS method is not allowed");
String requested = exchange.getRequestHeaders().getFirst("Access-Control-Request-Headers");
if (requested != null && !requested.isBlank()) {
String[] headers = requested.split(",", -1);
if (headers.length > 32 || Arrays.stream(headers).anyMatch(header -> !allowedHeader(header.trim())))
throw new StoreException(403, "AccessDenied", "CORS header is not allowed");
exchange.getResponseHeaders().set("Access-Control-Allow-Headers",
String.join(", ", Arrays.stream(headers).map(String::trim).toList()));
}
exchange.getResponseHeaders().set("Vary", "Origin, Access-Control-Request-Method, Access-Control-Request-Headers");
exchange.getResponseHeaders().set("Access-Control-Allow-Methods", String.join(", ", METHODS));
exchange.getResponseHeaders().set("Access-Control-Max-Age", "600");
exchange.sendResponseHeaders(204, -1);
return true;
}
private static boolean allowedHeader(String header) {
String name = header.toLowerCase(Locale.ROOT);
return name.matches("[a-z0-9-]{1,80}") &&
(HEADERS.contains(name) || name.startsWith("x-amz-"));
}
}
+224
View File
@@ -0,0 +1,224 @@
package cloud.lunarsky.store;
import com.sun.net.httpserver.HttpExchange;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.Base64;
import java.util.Locale;
import java.util.Map;
final class BucketHandler {
private final ObjectStorage store;
private final MultipartStorage multipart;
private final MultipartHandler multipartHandler;
private final SigV4 authentication;
private final S3Access access;
private final String owner;
private final String bucket;
BucketHandler(ObjectStorage store, MultipartStorage multipart, MultipartHandler multipartHandler,
SigV4 authentication, S3Access access, String bucket) {
this.store = store;
this.multipart = multipart;
this.multipartHandler = multipartHandler;
this.authentication = authentication;
this.access = access;
this.owner = access.owner();
this.bucket = bucket;
}
void listBuckets(HttpExchange exchange) throws IOException {
StringBuilder body = new StringBuilder("<ListAllMyBucketsResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">" +
"<Owner><ID>" + owner + "</ID><DisplayName>ObjectStore</DisplayName></Owner><Buckets>");
for (ObjectStorage.Bucket entry : store.buckets())
body.append("<Bucket><Name>").append(S3Xml.xml(entry.name())).append("</Name><CreationDate>")
.append(Instant.ofEpochMilli(entry.created())).append("</CreationDate></Bucket>");
S3Xml.sendXml(exchange, 200, body.append("</Buckets></ListAllMyBucketsResult>").toString());
}
void handleBucket(HttpExchange exchange, Map<String, String> query, String hash,
String bucketName, String principal) throws IOException {
String method = exchange.getRequestMethod();
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,
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));
} else {
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()));
} else {
byte[] body = S3Request.signedBody(exchange, hash, 65536);
S3Request.verifyContentMd5(exchange.getRequestHeaders(), body);
store.setBucketAcl(bucketName, Acl.fromXml(body,
owner, authentication.identities()));
}
exchange.sendResponseHeaders(200, -1);
}
return;
}
String bucketOperation = switch (method) {
case "PUT" -> "CreateBucket";
case "HEAD" -> "HeadBucket";
case "DELETE" -> "DeleteBucket";
default -> null;
};
if (bucketOperation != null && (query.isEmpty() ||
query.size() == 1 && bucketOperation.equals(query.get("x-id")))) {
S3Request.requireEmptyBody(exchange, hash);
switch (method) {
case "PUT" -> {
access.requireOwner(principal);
Map<String, String> acl = Acl.fromHeaders(exchange.getRequestHeaders(),
authentication.identities());
store.createBucket(bucketName);
if (!acl.isEmpty()) store.setBucketAcl(bucketName, acl);
exchange.getResponseHeaders().set("Location", "/" + bucketName);
exchange.sendResponseHeaders(200, -1);
}
case "HEAD" -> {
access.requireBucket(bucketName, principal, Acl.READ);
exchange.sendResponseHeaders(200, -1);
}
case "DELETE" -> {
access.requireOwner(principal);
if (bucketName.equals(bucket))
throw new StoreException(409, "BucketNotEmpty", "The configured default bucket cannot be deleted");
synchronized (multipart) {
if (!multipart.listUploads(bucketName, "").isEmpty())
throw new StoreException(409, "BucketNotEmpty", "Bucket has active uploads");
store.deleteBucket(bucketName);
}
exchange.sendResponseHeaders(204, -1);
}
}
return;
}
store.bucket(bucketName);
String versioningOperation = method.equals("GET") ? "GetBucketVersioning" :
method.equals("PUT") ? "PutBucketVersioning" : null;
if (query.containsKey("versioning") && query.get("versioning").isEmpty() &&
(query.size() == 1 || query.size() == 2 && versioningOperation != null &&
versioningOperation.equals(query.get("x-id")))) {
access.requireOwner(principal);
handleVersioning(exchange, hash, bucketName);
return;
}
if (method.equals("GET") && query.containsKey("versions") && query.get("versions").isEmpty()) {
access.requireOwner(principal);
if (!query.keySet().stream().allMatch(java.util.Set.of("versions", "prefix", "key-marker",
"version-id-marker", "max-keys", "encoding-type", "x-id")::contains) ||
query.containsKey("x-id") && !"ListObjectVersions".equals(query.get("x-id")))
S3Request.unsupported("Version listing option");
S3Request.requireEmptyBody(exchange, hash);
listVersions(exchange, query, bucketName);
return;
}
if (exchange.getRequestMethod().equals("GET") && query.containsKey("uploads")) {
access.requireOwner(principal);
if (!query.get("uploads").isEmpty() ||
!query.keySet().stream().allMatch(java.util.Set.of("uploads", "prefix", "key-marker",
"upload-id-marker", "max-uploads", "x-id")::contains) ||
(query.containsKey("x-id") && !"ListMultipartUploads".equals(query.get("x-id"))))
S3Request.unsupported("Bucket operation");
S3Request.requireEmptyBody(exchange, hash);
multipartHandler.listUploads(exchange, query, bucketName);
return;
}
if (!exchange.getRequestMethod().equals("GET") || !"2".equals(query.get("list-type")) ||
!query.keySet().stream().allMatch(java.util.Set.of("list-type", "prefix", "delimiter", "max-keys",
"continuation-token", "start-after", "encoding-type", "x-id")::contains) ||
(query.containsKey("x-id") && !"ListObjectsV2".equals(query.get("x-id"))))
S3Request.unsupported("Bucket operation");
access.requireBucket(bucketName, principal, Acl.READ);
S3Request.requireEmptyBody(exchange, hash);
listObjects(exchange, query, bucketName);
}
private void handleVersioning(HttpExchange exchange, String hash, String bucketName) throws IOException {
switch (exchange.getRequestMethod()) {
case "GET" -> {
S3Request.requireEmptyBody(exchange, hash);
var state = store.bucket(bucketName).versioning();
String status = state == ObjectStorage.VersioningState.NEVER ? "" :
"<Status>" + state.name().charAt(0) + state.name().substring(1).toLowerCase(Locale.ROOT) +
"</Status>";
S3Xml.sendXml(exchange, 200, "<VersioningConfiguration xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">" +
status + "</VersioningConfiguration>");
}
case "PUT" -> {
byte[] body = S3Request.signedBody(exchange, hash, 65536);
S3Request.verifyContentMd5(exchange.getRequestHeaders(), body);
store.setVersioning(bucketName, S3Xml.parseVersioning(body));
exchange.sendResponseHeaders(200, -1);
}
default -> S3Request.unsupported("Bucket versioning operation");
}
}
private void listVersions(HttpExchange exchange, Map<String, String> query,
String bucketName) throws IOException {
String encoding = query.get("encoding-type");
if (encoding != null && !encoding.equals("url")) S3Request.unsupported("Encoding type");
int maximum = S3Request.boundedNumber(query.get("max-keys"), 0, 1000, 1000);
String keyMarker = query.get("key-marker");
String versionMarker = query.get("version-id-marker");
if (versionMarker != null && keyMarker == null)
throw new StoreException(400, "InvalidArgument", "Version ID marker requires a key marker");
var page = store.listVersions(bucketName, query.getOrDefault("prefix", ""),
keyMarker, versionMarker, maximum);
StringBuilder body = new StringBuilder("<ListVersionsResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\"><Name>")
.append(S3Xml.xml(bucketName)).append("</Name><Prefix>")
.append(S3Xml.xml(S3Xml.listKey(query.getOrDefault("prefix", ""), encoding))).append("</Prefix><KeyMarker>")
.append(S3Xml.xml(S3Xml.listKey(query.getOrDefault("key-marker", ""), encoding)))
.append("</KeyMarker><VersionIdMarker>")
.append(S3Xml.xml(query.getOrDefault("version-id-marker", "")))
.append("</VersionIdMarker><MaxKeys>").append(maximum)
.append("</MaxKeys><IsTruncated>").append(page.truncated()).append("</IsTruncated>");
if (encoding != null) body.append("<EncodingType>url</EncodingType>");
if (page.truncated()) body.append("<NextKeyMarker>")
.append(S3Xml.xml(S3Xml.listKey(page.nextKey(), encoding))).append("</NextKeyMarker><NextVersionIdMarker>")
.append(S3Xml.xml(page.nextVersionId())).append("</NextVersionIdMarker>");
for (var entry : page.entries()) {
body.append(entry.deleteMarker() ? "<DeleteMarker>" : "<Version>")
.append("<Key>").append(S3Xml.xml(S3Xml.listKey(entry.key(), encoding)))
.append("</Key><VersionId>").append(S3Xml.xml(entry.versionId()))
.append("</VersionId><IsLatest>").append(entry.latest())
.append("</IsLatest><LastModified>")
.append(Instant.ofEpochMilli(entry.modified())).append("</LastModified>");
if (!entry.deleteMarker()) body.append("<ETag>&quot;").append(entry.metadata().etag())
.append("&quot;</ETag><Size>").append(entry.metadata().length()).append("</Size>");
body.append("<Owner><ID>objectstore</ID><DisplayName>ObjectStore</DisplayName></Owner>")
.append(entry.deleteMarker() ? "</DeleteMarker>" : "<StorageClass>STANDARD</StorageClass></Version>");
}
S3Xml.sendXml(exchange, 200, body.append("</ListVersionsResult>").toString());
}
private void listObjects(HttpExchange exchange, Map<String, String> query, String bucketName) throws IOException {
S3Request.ListRequest request = S3Request.listRequest(query);
var page = store.list(bucketName, request.prefix(), request.delimiter(), request.maxKeys(), request.after());
StringBuilder xml = new StringBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\"?><ListBucketResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">");
S3Xml.appendListHeader(xml, query, request, page, bucketName);
S3Xml.appendListEntries(xml, page, request.encoding());
if (page.truncated()) xml.append("<NextContinuationToken>")
.append(Base64.getUrlEncoder().withoutPadding().encodeToString(page.nextKey().getBytes(StandardCharsets.UTF_8)))
.append("</NextContinuationToken>");
xml.append("</ListBucketResult>");
byte[] body = xml.toString().getBytes(StandardCharsets.UTF_8);
exchange.getResponseHeaders().set("Content-Type", "application/xml");
exchange.sendResponseHeaders(200, body.length);
exchange.getResponseBody().write(body);
}
}
+36 -4
View File
@@ -41,7 +41,9 @@ final class DiskStore implements ObjectStorage {
private final NavigableMap<String, Metadata> index = new TreeMap<>(); private final NavigableMap<String, Metadata> index = new TreeMap<>();
private final NavigableMap<String, Bucket> buckets = new TreeMap<>(); private final NavigableMap<String, Bucket> buckets = new TreeMap<>();
private final NavigableMap<String, List<VersionRecord>> histories = new TreeMap<>(); private final NavigableMap<String, List<VersionRecord>> histories = new TreeMap<>();
private final Map<String, Integer> publishingByBucket = new HashMap<>();
private long used; private long used;
private long reservedBytes;
private long objectCount, legacyCount; private long objectCount, legacyCount;
record Record(Metadata metadata, int headerLength) {} record Record(Metadata metadata, int headerLength) {}
@@ -174,6 +176,7 @@ final class DiskStore implements ObjectStorage {
@Override public synchronized void deleteBucket(String name) throws IOException { @Override public synchronized void deleteBucket(String name) throws IOException {
bucket(name); bucket(name);
awaitPublications(name);
if (index.values().stream().anyMatch(meta -> name.equals(meta.bucket()))) if (index.values().stream().anyMatch(meta -> name.equals(meta.bucket())))
throw new StoreException(409, "BucketNotEmpty", "Bucket contains objects"); throw new StoreException(409, "BucketNotEmpty", "Bucket contains objects");
if (histories.entrySet().stream().anyMatch(entry -> entry.getKey().startsWith(name + "\0") && if (histories.entrySet().stream().anyMatch(entry -> entry.getKey().startsWith(name + "\0") &&
@@ -227,6 +230,7 @@ final class DiskStore implements ObjectStorage {
} }
@Override public synchronized void setVersioning(String name, VersioningState state) throws IOException { @Override public synchronized void setVersioning(String name, VersioningState state) throws IOException {
awaitPublications(name);
if (state == VersioningState.NEVER) if (state == VersioningState.NEVER)
throw new StoreException(400, "InvalidArgument", "Versioning cannot be disabled after it is enabled"); throw new StoreException(400, "InvalidArgument", "Versioning cannot be disabled after it is enabled");
Bucket old = bucket(name); Bucket old = bucket(name);
@@ -249,6 +253,15 @@ final class DiskStore implements ObjectStorage {
} }
private static String indexKey(String bucket, String key) { return bucket + "\0" + key; } private static String indexKey(String bucket, String key) { return bucket + "\0" + key; }
private void awaitPublications(String bucket) throws IOException {
while (publishingByBucket.containsKey(bucket)) {
try { wait(); }
catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IOException("Interrupted while waiting for object writes", e);
}
}
}
private Path historyDirectory(String bucket, String key) { private Path historyDirectory(String bucket, String key) {
String id = SigV4.hex(SigV4.hash((bucket + "/" + key).getBytes(StandardCharsets.UTF_8))); String id = SigV4.hex(SigV4.hash((bucket + "/" + key).getBytes(StandardCharsets.UTF_8)));
return versions.resolve(id.substring(0, 2)).resolve(id); return versions.resolve(id.substring(0, 2)).resolve(id);
@@ -505,17 +518,36 @@ final class DiskStore implements ObjectStorage {
legacy = old.key() == null; legacy = old.key() == null;
} }
} }
long additional = Math.max(0, metadata.length() - previous);
synchronized (this) { synchronized (this) {
if (Files.exists(catalog) && !buckets.containsKey(metadata.bucket())) Bucket configured = buckets.get(metadata.bucket());
if (configured != null && configured.versioning() != VersioningState.NEVER)
return installVersionedPending(destination, pending, metadata, createOnly,
configured.versioning());
if (Files.exists(catalog) && configured == null)
throw new StoreException(404, "NoSuchBucket", "Bucket not found"); throw new StoreException(404, "NoSuchBucket", "Bucket not found");
if (used - previous + metadata.length() > maxTotal) if (maxTotal - used - reservedBytes < additional)
throw new StoreException(507, "InsufficientStorage", "Store capacity limit reached"); throw new StoreException(507, "InsufficientStorage", "Store capacity limit reached");
reservedBytes += additional;
publishingByBucket.merge(metadata.bucket(), 1, Integer::sum);
}
boolean moved = false;
try {
Files.move(pending, destination, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); Files.move(pending, destination, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
moved = true;
syncDirectory(destination.getParent());
} finally {
synchronized (this) {
if (moved) {
used = used - previous + metadata.length(); used = used - previous + metadata.length();
if (!existed) objectCount++; if (!existed) objectCount++;
if (legacy) legacyCount--; if (legacy) legacyCount--;
index.put(indexKey(metadata.bucket(), metadata.key()), metadata); index.put(indexKey(metadata.bucket(), metadata.key()), metadata);
syncDirectory(destination.getParent()); }
reservedBytes -= additional;
publishingByBucket.compute(metadata.bucket(), (bucket, count) -> count == 1 ? null : count - 1);
notifyAll();
}
} }
return metadata; return metadata;
} }
@@ -542,7 +574,7 @@ final class DiskStore implements ObjectStorage {
} }
} }
} }
if (maxTotal - (used - replaced) < metadata.length()) if (maxTotal - (used - replaced) - reservedBytes < metadata.length())
throw new StoreException(507, "InsufficientStorage", "Store capacity limit reached"); throw new StoreException(507, "InsufficientStorage", "Store capacity limit reached");
Path target = versionPath(bucket, key, storageId); Path target = versionPath(bucket, key, storageId);
Files.createDirectories(target.getParent()); Files.createDirectories(target.getParent());
+90
View File
@@ -0,0 +1,90 @@
package cloud.lunarsky.store;
import com.sun.net.httpserver.Headers;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
final class KeyScopes {
private record Scope(String bucket, String prefix, Set<String> actions) {
boolean grants(String action, String bucket, String key) {
return this.bucket.equals(bucket) && key.startsWith(prefix) && actions.contains(action);
}
}
private final String owner;
private final Map<String, List<Scope>> grants;
private KeyScopes(String owner, Map<String, List<Scope>> grants) {
this.owner = owner;
this.grants = grants;
}
static KeyScopes unrestricted(String owner) { return new KeyScopes(owner, null); }
static KeyScopes fromEnvironment(Map<String, String> env, String owner, Set<String> identities)
throws IOException {
String file = env.get("S3_KEY_SCOPES_FILE");
if (file == null || file.isBlank()) return unrestricted(owner);
Map<String, List<Scope>> grants = new HashMap<>();
List<String> lines = Files.readAllLines(Path.of(file), StandardCharsets.UTF_8);
if (lines.size() > 256) throw new IllegalArgumentException("Too many key scopes");
for (String line : lines) {
if (line.isBlank() || line.startsWith("#")) continue;
String[] fields = line.split("\\t", -1);
if (fields.length != 4 || !identities.contains(fields[0]) || fields[0].equals(owner) ||
!fields[1].matches("[a-z0-9][a-z0-9-]{1,61}[a-z0-9]") ||
fields[2].getBytes(StandardCharsets.UTF_8).length > 1024 || fields[2].indexOf('\0') >= 0)
throw new IllegalArgumentException("Invalid key scope");
Set<String> actions = Set.of(fields[3].split(",", -1));
if (actions.isEmpty() || !Set.of("read", "write", "list").containsAll(actions))
throw new IllegalArgumentException("Invalid key scope actions");
grants.computeIfAbsent(fields[0], ignored -> new ArrayList<>())
.add(new Scope(fields[1], fields[2], actions));
}
grants.replaceAll((key, value) -> List.copyOf(value));
return new KeyScopes(owner, Map.copyOf(grants));
}
void require(String principal, String action, String bucket, String key) {
if (grants == null || principal == null || owner.equals(principal)) return;
if (grants.getOrDefault(principal, List.of()).stream().noneMatch(scope -> scope.grants(action, bucket, key)))
throw new StoreException(403, "AccessDenied", "Access denied");
}
void checkObject(String principal, String bucket, String key, String method,
Map<String, String> query, Headers headers) {
if (grants == null || principal == null || owner.equals(principal)) return;
if (query.containsKey("acl") || headers.containsKey("x-amz-acl") ||
headers.keySet().stream().anyMatch(name -> name.toLowerCase(java.util.Locale.ROOT)
.startsWith("x-amz-grant-")))
throw new StoreException(403, "AccessDenied", "Access denied");
String action = method.equals("GET") || method.equals("HEAD") ? "read" : "write";
require(principal, action, bucket, key);
String source = headers.getFirst("x-amz-copy-source");
if (source != null) {
if (source.startsWith("/")) source = source.substring(1);
int question = source.indexOf('?');
if (question >= 0) source = source.substring(0, question);
int slash = source.indexOf('/');
if (slash <= 0 || slash == source.length() - 1)
throw new StoreException(400, "InvalidArgument", "Invalid copy source");
require(principal, "read", SigV4.decode(source.substring(0, slash)),
SigV4.decode(source.substring(slash + 1)));
}
}
void checkBucket(String principal, String bucket, String method, Map<String, String> query) {
if (grants == null || principal == null || owner.equals(principal)) return;
if (!method.equals("GET") || !"2".equals(query.get("list-type")) ||
!query.containsKey("prefix"))
throw new StoreException(403, "AccessDenied", "Access denied");
require(principal, "list", bucket, query.get("prefix"));
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,151 @@
package cloud.lunarsky.store;
import com.sun.net.httpserver.HttpExchange;
import java.io.IOException;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
final class MultipartHandler {
private final ObjectStorage store;
private final MultipartStorage multipart;
private final SigV4 authentication;
private final String owner;
MultipartHandler(ObjectStorage store, MultipartStorage multipart, SigV4 authentication) {
this.store = store;
this.multipart = multipart;
this.authentication = authentication;
this.owner = authentication.root();
}
void handleMultipart(HttpExchange exchange, String method, Map<String, String> query,
String key, SigV4.Verified verified, String bucketName) throws IOException {
String hash = verified.payload();
var headers = exchange.getRequestHeaders();
if ((headers.containsKey("content-encoding") && !(method.equals("PUT") && verified.streaming())) ||
headers.containsKey("if-none-match"))
S3Request.unsupported("Multipart request header");
if (headers.containsKey("x-amz-copy-source") || headers.containsKey("x-amz-metadata-directive") ||
headers.containsKey("x-amz-tagging-directive"))
S3Request.unsupported("Multipart copy request");
if (!query.containsKey("uploads") &&
(headers.containsKey("x-amz-tagging") || !ObjectAttributes.userMetadata(headers).isEmpty() ||
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");
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-"))))
S3Request.unsupported("Multipart checksum header");
if (query.containsKey("uploads")) {
S3Request.requireEmptyBody(exchange, hash);
Map<String, String> acl = Acl.fromHeaders(headers, authentication.identities());
if (!acl.isEmpty() && !owner.equals(verified.principal()))
Acl.require(store.bucket(bucketName).acl(), verified.principal(), owner, Acl.WRITE_ACP);
String id = multipart.create(bucketName, key, S3Request.contentType(headers),
ObjectAttributes.userMetadata(headers),
ObjectAttributes.tagsHeader(SigV4.single(headers, "x-amz-tagging")), acl);
S3Xml.sendXml(exchange, 200, "<InitiateMultipartUploadResult><Bucket>" + S3Xml.xml(bucketName) +
"</Bucket><Key>" + S3Xml.xml(key) + "</Key><UploadId>" + id +
"</UploadId></InitiateMultipartUploadResult>");
return;
}
String id = query.get("uploadId");
switch (method) {
case "PUT" -> {
int number;
try { number = Integer.parseInt(query.get("partNumber")); }
catch (NumberFormatException e) { throw new StoreException(400, "InvalidArgument", "Invalid part number"); }
long length = verified.streaming() ? S3Request.decodedLength(headers) : S3Request.contentLength(headers);
UploadChecksums checksums = UploadChecksums.from(headers);
AwsChunkedInputStream chunked = verified.streaming() ? S3Request.chunkedBody(exchange, verified) : null;
String etag = multipart.putPart(id, bucketName, key, number,
checksums.verifying(chunked == null ? exchange.getRequestBody() : chunked),
length, S3Request.expectedPayloadHash(hash), checksums.sha256());
exchange.getResponseHeaders().set("ETag", "\"" + etag + "\"");
checksums.response(exchange.getResponseHeaders());
if (chunked != null && chunked.trailerValue() != null)
exchange.getResponseHeaders().set(SigV4.single(headers, "x-amz-trailer"), chunked.trailerValue());
exchange.sendResponseHeaders(200, -1);
}
case "POST" -> {
byte[] body = S3Request.signedBody(exchange, hash, 65536);
List<MultipartStorage.Part> parts = S3Xml.completedParts(body);
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) +
"</Bucket><Key>" + S3Xml.xml(key) + "</Key><ETag>&quot;" + meta.etag() +
"&quot;</ETag></CompleteMultipartUploadResult>");
}
case "DELETE" -> {
S3Request.requireEmptyBody(exchange, hash);
multipart.abort(id, bucketName, key);
exchange.sendResponseHeaders(204, -1);
}
case "GET" -> {
S3Request.requireEmptyBody(exchange, hash);
listParts(exchange, id, key, query, bucketName);
}
default -> S3Request.unsupported("Multipart operation");
}
}
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);
int maxParts = S3Request.boundedNumber(query.get("max-parts"), 1, 1000, 1000);
MultipartStorage.PartPage page = multipart.listParts(id, bucketName, key, marker, maxParts);
StringBuilder body = new StringBuilder("<ListPartsResult><Bucket>").append(S3Xml.xml(bucketName))
.append("</Bucket><Key>").append(S3Xml.xml(key)).append("</Key><UploadId>").append(S3Xml.xml(id))
.append("</UploadId><PartNumberMarker>").append(marker)
.append("</PartNumberMarker><NextPartNumberMarker>").append(page.nextMarker())
.append("</NextPartNumberMarker><MaxParts>").append(maxParts)
.append("</MaxParts><IsTruncated>").append(page.truncated()).append("</IsTruncated>");
for (MultipartStorage.PartInfo part : page.parts()) {
body.append("<Part><PartNumber>").append(part.number()).append("</PartNumber><LastModified>")
.append(Instant.ofEpochMilli(part.modified())).append("</LastModified><ETag>&quot;")
.append(part.etag()).append("&quot;</ETag><Size>").append(part.length()).append("</Size></Part>");
}
S3Xml.sendXml(exchange, 200, body.append("</ListPartsResult>").toString());
}
void listUploads(HttpExchange exchange, Map<String, String> query, String bucketName) throws IOException {
String prefix = query.getOrDefault("prefix", "");
String marker = query.getOrDefault("key-marker", "");
String uploadMarker = query.getOrDefault("upload-id-marker", "");
if (!uploadMarker.isEmpty() && marker.isEmpty())
throw new StoreException(400, "InvalidArgument", "Upload ID marker requires a key marker");
int maximum = S3Request.boundedNumber(query.get("max-uploads"), 1, 1000, 1000);
List<MultipartStorage.UploadInfo> uploads = multipart.listUploads(bucketName, prefix);
List<MultipartStorage.UploadInfo> page = new ArrayList<>();
boolean truncated = false;
for (MultipartStorage.UploadInfo upload : uploads) {
if (upload.key().compareTo(marker) < 0 ||
(upload.key().equals(marker) && upload.id().compareTo(uploadMarker) <= 0)) continue;
if (page.size() == maximum) {
truncated = true;
break;
}
page.add(upload);
}
StringBuilder body = new StringBuilder("<ListMultipartUploadsResult><Bucket>").append(S3Xml.xml(bucketName))
.append("</Bucket><KeyMarker>").append(S3Xml.xml(marker)).append("</KeyMarker><UploadIdMarker>")
.append(S3Xml.xml(uploadMarker)).append("</UploadIdMarker><MaxUploads>").append(maximum)
.append("</MaxUploads><IsTruncated>").append(truncated).append("</IsTruncated>");
if (truncated) {
MultipartStorage.UploadInfo last = page.getLast();
body.append("<NextKeyMarker>").append(S3Xml.xml(last.key())).append("</NextKeyMarker><NextUploadIdMarker>")
.append(S3Xml.xml(last.id())).append("</NextUploadIdMarker>");
}
for (MultipartStorage.UploadInfo upload : page) {
body.append("<Upload><Key>").append(S3Xml.xml(upload.key())).append("</Key><UploadId>")
.append(S3Xml.xml(upload.id())).append("</UploadId><Initiated>")
.append(Instant.ofEpochMilli(upload.created())).append("</Initiated></Upload>");
}
S3Xml.sendXml(exchange, 200, body.append("</ListMultipartUploadsResult>").toString());
}
}
+331
View File
@@ -0,0 +1,331 @@
package cloud.lunarsky.store;
import com.sun.net.httpserver.HttpExchange;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Base64;
import java.util.Locale;
import java.util.Map;
final class ObjectHandler {
private final ObjectStorage store;
private final MultipartHandler multipartHandler;
private final SigV4 authentication;
private final S3Access access;
private final String owner;
ObjectHandler(ObjectStorage store, MultipartHandler multipartHandler,
SigV4 authentication, S3Access access) {
this.store = store;
this.multipartHandler = multipartHandler;
this.authentication = authentication;
this.access = access;
this.owner = access.owner();
}
void handleObject(HttpExchange exchange, String key, Map<String, String> query,
SigV4.Verified verified, String bucketName) throws IOException {
String hash = verified.payload();
String principal = verified.principal();
if (key.isEmpty() || key.getBytes(StandardCharsets.UTF_8).length > 1024 || key.indexOf('\0') >= 0)
throw new StoreException(400, "InvalidArgument", "Invalid object key");
String method = exchange.getRequestMethod();
if (query.containsKey("acl") && query.get("acl").isEmpty() &&
query.keySet().stream().allMatch(java.util.Set.of("acl", "versionId", "x-id")::contains) &&
(!query.containsKey("x-id") ||
query.get("x-id").equals(method.equals("GET") ? "GetObjectAcl" : "PutObjectAcl")) &&
(method.equals("GET") || method.equals("PUT"))) {
String versionId = query.get("versionId");
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);
S3Request.requireEmptyBody(exchange, hash);
S3Xml.sendXml(exchange, 200, Acl.xml(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);
}
Map<String, String> acl;
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]);
acl = Acl.fromHeaders(exchange.getRequestHeaders(), authentication.identities());
} else {
byte[] body = S3Request.signedBody(exchange, hash, 65536);
S3Request.verifyContentMd5(exchange.getRequestHeaders(), body);
acl = Acl.fromXml(body, owner, authentication.identities());
}
store.setObjectAcl(bucketName, key, metadata.versionId(), acl);
exchange.sendResponseHeaders(200, -1);
}
}
return;
}
String taggingOperation = switch (method) {
case "GET" -> "GetObjectTagging";
case "PUT" -> "PutObjectTagging";
case "DELETE" -> "DeleteObjectTagging";
default -> null;
};
if (taggingOperation != null && query.containsKey("tagging") && query.get("tagging").isEmpty() &&
query.keySet().stream().allMatch(java.util.Set.of("tagging", "versionId", "x-id")::contains) &&
(!query.containsKey("x-id") || taggingOperation.equals(query.get("x-id")))) {
S3Request.validateObjectHeaders(exchange.getRequestHeaders());
access.requireOwner(principal);
handleTagging(exchange, method, key, hash, bucketName, query.get("versionId"));
return;
}
boolean multipartRequest = S3Request.multipartRequest(method, query);
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 &&
("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")))))
S3Request.unsupported("Query operation");
S3Request.validateObjectHeaders(exchange.getRequestHeaders());
if (multipartRequest) {
if (method.equals("GET")) access.requireOwner(principal);
else access.requireBucket(bucketName, principal, Acl.WRITE);
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") ||
exchange.getRequestHeaders().containsKey("x-amz-tagging-directive") ||
exchange.getRequestHeaders().containsKey("x-amz-sdk-checksum-algorithm") ||
exchange.getRequestHeaders().keySet().stream().anyMatch(name ->
name.toLowerCase(Locale.ROOT).startsWith("x-amz-checksum-") &&
!name.equalsIgnoreCase("x-amz-checksum-mode"))))
S3Request.unsupported("Object upload header");
if (!method.equals("PUT") || copy) S3Request.requireEmptyBody(exchange, hash);
switch (method) {
case "PUT" -> {
access.requireBucket(bucketName, principal, Acl.WRITE);
if (copy) copyObject(exchange, key, bucketName, principal);
else putObject(exchange, key, verified, bucketName);
}
case "GET", "HEAD" -> readObject(exchange, key, bucketName, query.get("versionId"), principal);
case "DELETE" -> {
access.requireBucket(bucketName, principal, Acl.WRITE);
deleteObject(exchange, key, bucketName, query.get("versionId"));
}
default -> S3Request.unsupported("HTTP method");
}
}
private void putObject(HttpExchange exchange, String key, SigV4.Verified verified,
String bucketName) 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");
long bytes;
try { bytes = length == null ? -1 : Long.parseLong(length); }
catch (NumberFormatException e) { throw new StoreException(400, "InvalidArgument", "Invalid Content-Length"); }
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);
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"))
S3Request.unsupported("Chunked upload header");
String type = S3Request.contentType(headers);
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());
if (!acl.isEmpty() && !owner.equals(verified.principal()))
access.requireBucket(bucketName, verified.principal(), Acl.WRITE_ACP);
ObjectStorage.Metadata data = store.put(bucketName, key,
checksums.verifying(chunked == null ? exchange.getRequestBody() : chunked),
bytes, S3Request.expectedPayloadHash(verified.payload()), checksums.sha256(), condition != null, type,
metadata, tags, () -> {
if (chunked == null || chunked.trailerValue() == null) return checksums.metadata();
String trailer = SigV4.single(headers, "x-amz-trailer");
if (!checksums.metadata().isEmpty())
throw new StoreException(400, "InvalidRequest", "Supply one checksum algorithm");
return Map.of(trailer, chunked.trailerValue());
}, acl);
exchange.getResponseHeaders().set("ETag", "\"" + data.etag() + "\"");
if (data.versionId() != null) exchange.getResponseHeaders().set("x-amz-version-id", data.versionId());
exchange.getResponseHeaders().set("x-amz-checksum-sha256", Base64.getEncoder().encodeToString(data.sha256()));
data.checksums().forEach(exchange.getResponseHeaders()::set);
exchange.sendResponseHeaders(200, -1);
}
private void copyObject(HttpExchange exchange, String key, String bucketName,
String principal) throws IOException {
var headers = exchange.getRequestHeaders();
if (headers.containsKey("content-encoding") || headers.containsKey("content-md5") ||
headers.containsKey("if-none-match") || headers.containsKey("x-amz-sdk-checksum-algorithm") ||
headers.keySet().stream().anyMatch(name -> name.toLowerCase(Locale.ROOT).startsWith("x-amz-checksum-")))
S3Request.unsupported("Copy request header");
String source = SigV4.single(headers, "x-amz-copy-source");
if (source == null) throw new StoreException(400, "InvalidArgument", "Missing copy source");
if (source.startsWith("/")) source = source.substring(1);
String sourceVersion = null;
int question = source.indexOf('?');
if (question >= 0) {
Map<String, String> sourceQuery = S3Request.query(source.substring(question + 1));
if (sourceQuery.size() != 1 || !sourceQuery.containsKey("versionId"))
throw new StoreException(400, "InvalidArgument", "Invalid copy source version");
sourceVersion = sourceQuery.get("versionId");
source = source.substring(0, question);
}
int separator = source.indexOf('/');
if (separator <= 0 || separator == source.length() - 1)
throw new StoreException(400, "InvalidArgument", "Invalid copy source");
String sourceBucket = SigV4.decode(source.substring(0, separator));
String sourceKey = SigV4.decode(source.substring(separator + 1));
store.bucket(sourceBucket);
if (sourceKey.isEmpty() || sourceKey.getBytes(StandardCharsets.UTF_8).length > 1024 ||
sourceKey.indexOf('\0') >= 0)
throw new StoreException(400, "InvalidArgument", "Invalid copy source key");
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");
if (!"REPLACE".equals(tagDirective) && headers.containsKey("x-amz-tagging"))
S3Request.unsupported("Tagging header requires REPLACE tagging directive");
if (!"REPLACE".equals(directive) && !ObjectAttributes.userMetadata(headers).isEmpty())
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);
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();
Map<String, String> metadata = "REPLACE".equals(directive)
? ObjectAttributes.userMetadata(headers) : sourceMetadata.userMetadata();
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());
if (!acl.isEmpty() && !owner.equals(principal))
access.requireBucket(bucketName, principal, Acl.WRITE_ACP);
var copied = store.put(bucketName, key, object.stream(), sourceMetadata.length(),
SigV4.hex(sourceMetadata.sha256()), null, false, type, metadata, tags,
sourceMetadata::checksums, acl);
if (copied.versionId() != null)
exchange.getResponseHeaders().set("x-amz-version-id", copied.versionId());
S3Xml.sendXml(exchange, 200, "<CopyObjectResult><LastModified>" +
Instant.ofEpochMilli(copied.modified()) + "</LastModified><ETag>&quot;" +
copied.etag() + "&quot;</ETag></CopyObjectResult>");
}
}
private void deleteObject(HttpExchange exchange, String key, String bucketName,
String versionId) throws IOException {
if (exchange.getRequestHeaders().containsKey("if-none-match")) S3Request.unsupported("Conditional delete");
var result = store.delete(bucketName, key, versionId);
if (result.versionId() != null)
exchange.getResponseHeaders().set("x-amz-version-id", result.versionId());
if (result.deleteMarker()) exchange.getResponseHeaders().set("x-amz-delete-marker", "true");
exchange.sendResponseHeaders(204, -1);
}
private void handleTagging(HttpExchange exchange, String method, String key,
String hash, String bucketName, String versionId) throws IOException {
if (exchange.getRequestHeaders().containsKey("x-amz-tagging") ||
exchange.getRequestHeaders().containsKey("x-amz-tagging-directive") ||
exchange.getRequestHeaders().containsKey("x-amz-sdk-checksum-algorithm") ||
!method.equals("PUT") && exchange.getRequestHeaders().containsKey("content-md5") ||
exchange.getRequestHeaders().keySet().stream().anyMatch(name ->
name.toLowerCase(Locale.ROOT).startsWith("x-amz-checksum-")) ||
!ObjectAttributes.userMetadata(exchange.getRequestHeaders()).isEmpty())
S3Request.unsupported("Tagging request header");
switch (method) {
case "GET" -> {
S3Request.requireEmptyBody(exchange, hash);
if (versionId != null) exchange.getResponseHeaders().set("x-amz-version-id", versionId);
S3Xml.sendXml(exchange, 200, S3Xml.tagXml(store.tags(bucketName, key, versionId)));
}
case "PUT" -> {
byte[] body = S3Request.signedBody(exchange, hash, 65536);
S3Request.verifyContentMd5(exchange.getRequestHeaders(), body);
store.setTags(bucketName, key, versionId, S3Xml.parseTags(body));
if (versionId != null) exchange.getResponseHeaders().set("x-amz-version-id", versionId);
exchange.sendResponseHeaders(200, -1);
}
case "DELETE" -> {
S3Request.requireEmptyBody(exchange, hash);
store.setTags(bucketName, key, versionId, Map.of());
if (versionId != null) exchange.getResponseHeaders().set("x-amz-version-id", versionId);
exchange.sendResponseHeaders(204, -1);
}
default -> S3Request.unsupported("Tagging operation");
}
}
private void readObject(HttpExchange exchange, String key, String bucketName,
String versionId, String principal) throws IOException {
var headers = exchange.getRequestHeaders();
String checksumMode = SigV4.single(headers, "x-amz-checksum-mode");
if (checksumMode != null && !checksumMode.equals("ENABLED"))
throw new StoreException(400, "InvalidArgument", "Invalid checksum mode");
if (headers.containsKey("if-match") || headers.containsKey("if-modified-since") ||
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);
String etag = "\"" + meta.etag() + "\"";
String noneMatch = SigV4.single(headers, "if-none-match");
if (noneMatch != null && (noneMatch.equals("*") ||
java.util.Arrays.stream(noneMatch.split(",")).map(String::trim).anyMatch(etag::equals))) {
exchange.getResponseHeaders().set("ETag", etag);
exchange.sendResponseHeaders(304, -1);
return;
}
S3Request.Range range;
try { range = S3Request.range(SigV4.single(headers, "range"), meta.length()); }
catch (StoreException error) {
if (error.status == 416) exchange.getResponseHeaders().set("Content-Range", "bytes */" + meta.length());
throw error;
}
var response = exchange.getResponseHeaders();
response.set("Content-Type", meta.contentType());
response.set("Content-Length", Long.toString(range.length()));
response.set("Accept-Ranges", "bytes");
response.set("ETag", etag);
if (meta.versionId() != null) response.set("x-amz-version-id", meta.versionId());
response.set("Last-Modified", DateTimeFormatter.RFC_1123_DATE_TIME.withZone(ZoneOffset.UTC)
.format(Instant.ofEpochMilli(meta.modified())));
meta.userMetadata().forEach((name, value) -> response.set("x-amz-meta-" + name, value));
if (checksumMode != null)
meta.checksums().forEach(response::set);
if (!meta.tags().isEmpty()) response.set("x-amz-tagging-count", Integer.toString(meta.tags().size()));
if (range.partial()) response.set("Content-Range", "bytes " + range.start() + "-" + range.end() + "/" + meta.length());
int status = range.partial() ? 206 : 200;
if (exchange.getRequestMethod().equals("HEAD") || range.length() == 0)
exchange.sendResponseHeaders(status, -1);
else {
object.stream().skipNBytes(range.start());
exchange.sendResponseHeaders(status, range.length());
byte[] buffer = new byte[65536];
long left = range.length();
while (left > 0) {
int n = object.stream().read(buffer, 0, (int) Math.min(buffer.length, left));
if (n < 0) throw new IOException("Object body ended before its recorded length");
exchange.getResponseBody().write(buffer, 0, n);
left -= n;
}
}
}
}
}
@@ -0,0 +1,135 @@
package cloud.lunarsky.store;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.time.Clock;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.Executors;
final class ObjectStoreServer {
private ObjectStoreServer() { }
static void start() throws Exception {
Map<String, String> env = System.getenv();
String access = required(env, "S3_ACCESS_KEY"), secret = required(env, "S3_SECRET_KEY");
String bucket = env.getOrDefault("S3_BUCKET", "lunaris-files"), region = env.getOrDefault("S3_REGION", "us-east-1");
if (!access.matches("[A-Za-z0-9]{16,128}") || secret.length() < 32 ||
!bucket.matches("[a-z0-9][a-z0-9-]{1,61}[a-z0-9]"))
throw new IllegalArgumentException("Invalid storage credentials/bucket configuration");
ObjectStorage.Limits limits = StorageLimits.fromEnvironment(env);
long maxObject = limits.maxObjectBytes(), maxTotal = limits.maxTotalBytes();
String mode = env.getOrDefault("STORE_MODE", "disk");
ObjectStorage store;
MultipartStorage multipart;
if (mode.equals("cluster")) {
if (!"true".equals(env.get("CLUSTER_LOCAL_DEV")))
throw new IllegalArgumentException("Cluster mode is local development only; set CLUSTER_LOCAL_DEV=true");
String[] urls = required(env, "CLUSTER_NODES").split(",", -1);
if (urls.length < 2) throw new IllegalArgumentException("CLUSTER_NODES requires at least two URLs");
store = new ClusterStore(required(env, "POSTGRES_JDBC_URL"), required(env, "POSTGRES_USER"),
required(env, "POSTGRES_PASSWORD"), bucket,
java.util.Arrays.stream(urls).map(URI::create).toList(), required(env, "CLUSTER_TOKEN"), null,
maxObject, maxTotal, "true".equals(env.get("CLUSTER_TEST_NODE_DOMAINS")));
multipart = (ClusterStore) store;
} else if (mode.equals("disk")) {
DiskStore disk = new DiskStore(Path.of(env.getOrDefault("DATA_DIR", "/data")), maxObject, maxTotal);
store = disk;
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,
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")));
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)
: new InetSocketAddress(port), positiveInt(env, "HTTP_BACKLOG", 64, 4096));
var executor = Executors.newVirtualThreadPerTaskExecutor();
server.setExecutor(executor);
server.createContext("/", app::handle);
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
server.stop(5);
executor.close();
try { store.close(); }
catch (IOException error) { System.err.println("Could not release ObjectStore data lock: " + error.getMessage()); }
}));
server.start();
if (store instanceof DiskStore disk) printStartup(disk, multipart, bucket, region, port);
else System.out.println("ObjectStore local cluster prototype v" + Version.VALUE + " listening on :" + port);
}
static Map<String, String> identities(Map<String, String> env, String access, String secret)
throws IOException {
Map<String, String> values = new HashMap<>();
values.put(access, secret);
String file = env.get("S3_CREDENTIALS_FILE");
if (file == null || file.isBlank()) return values;
List<String> lines = java.nio.file.Files.readAllLines(Path.of(file), StandardCharsets.UTF_8);
if (lines.size() > 63) throw new IllegalArgumentException("Too many additional identities");
for (String line : lines) {
if (line.isBlank() || line.startsWith("#")) continue;
int separator = line.indexOf(':');
if (separator < 0) throw new IllegalArgumentException("Invalid additional credential entry");
String key = line.substring(0, separator);
String value = line.substring(separator + 1);
if (!key.matches("[A-Za-z0-9]{16,128}") || value.length() < 32 ||
values.putIfAbsent(key, value) != null)
throw new IllegalArgumentException("Invalid or duplicate additional credential");
}
return values;
}
private static void printStartup(DiskStore store, MultipartStorage multipart,
String bucket, String region, int port) {
System.out.println(" *");
System.out.println(" / \\ LUNARSKY");
System.out.println(" / L \\ ObjectStore");
System.out.println(" /_____\\ v" + Version.VALUE);
System.out.println();
System.out.println(" Bucket " + bucket + " (" + region + ")");
System.out.println(" Objects " + store.objectCount() + " total, " +
store.indexedObjects() + " indexed, " + size(store.usedBytes()) + " / " + size(store.maxTotal()));
if (store.legacyObjects() > 0)
System.out.println(" Legacy " + store.legacyObjects() + " objects without stored keys");
System.out.println(" Multipart " + multipart.activeUploads() + " active, " +
size(multipart.stagedBytes()) + " staged");
System.out.println(" Listening :" + port);
}
private static String size(long bytes) {
if (bytes < 1024) return bytes + " B";
String[] units = {"KiB", "MiB", "GiB", "TiB"};
double value = bytes;
int unit = -1;
do {
value /= 1024;
unit++;
} while (value >= 1024 && unit < units.length - 1);
return String.format(Locale.ROOT, "%.1f %s", value, units[unit]);
}
private static String required(Map<String, String> env, String key) {
String value = env.get(key);
if (value == null || value.isBlank()) throw new IllegalArgumentException("Missing " + key);
return value;
}
private static int positiveInt(Map<String, String> env, String key, int fallback, int maximum) {
String configured = env.get(key);
if (configured == null || configured.isBlank()) return fallback;
try {
int value = Integer.parseInt(configured);
if (value < 1 || value > maximum) throw new NumberFormatException();
return value;
} catch (NumberFormatException error) {
throw new IllegalArgumentException(key + " must be between 1 and " + maximum, error);
}
}
}
@@ -0,0 +1,43 @@
package cloud.lunarsky.store;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.concurrent.atomic.LongAdder;
final class RequestMetrics {
private final String token;
private final LongAdder requests = new LongAdder();
private final LongAdder failures4xx = new LongAdder();
private final LongAdder failures5xx = new LongAdder();
private final LongAdder durationNanos = new LongAdder();
RequestMetrics(String token) {
if (token != null && !token.isBlank() && token.length() < 32)
throw new IllegalArgumentException("METRICS_BEARER_TOKEN must have at least 32 characters");
this.token = token == null || token.isBlank() ? null : token;
}
boolean enabled() { return token != null; }
boolean authorized(String authorization) {
if (token == null || authorization == null || !authorization.startsWith("Bearer ")) return false;
return MessageDigest.isEqual(token.getBytes(StandardCharsets.UTF_8),
authorization.substring(7).getBytes(StandardCharsets.UTF_8));
}
void record(int status, long elapsedNanos) {
requests.increment();
if (status >= 500) failures5xx.increment();
else if (status >= 400) failures4xx.increment();
durationNanos.add(Math.max(0, elapsedNanos));
}
String render(int inFlight) {
return "# TYPE objectstore_requests_total counter\nobjectstore_requests_total " + requests.sum() +
"\n# TYPE objectstore_responses_4xx_total counter\nobjectstore_responses_4xx_total " + failures4xx.sum() +
"\n# TYPE objectstore_responses_5xx_total counter\nobjectstore_responses_5xx_total " + failures5xx.sum() +
"\n# TYPE objectstore_request_duration_seconds_total counter\nobjectstore_request_duration_seconds_total " +
durationNanos.sum() / 1_000_000_000.0 +
"\n# TYPE objectstore_in_flight gauge\nobjectstore_in_flight " + inFlight + "\n";
}
}
+25
View File
@@ -0,0 +1,25 @@
package cloud.lunarsky.store;
import java.io.IOException;
final class S3Access {
private final ObjectStorage store;
private final String owner;
S3Access(ObjectStorage store, String owner) {
this.store = store;
this.owner = owner;
}
String owner() {
return owner;
}
void requireOwner(String principal) {
if (!owner.equals(principal)) throw new StoreException(403, "AccessDenied", "Access denied");
}
void requireBucket(String bucket, String principal, int permission) throws IOException {
Acl.require(store.bucket(bucket).acl(), principal, owner, permission);
}
}
+203
View File
@@ -0,0 +1,203 @@
package cloud.lunarsky.store;
import com.sun.net.httpserver.HttpExchange;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
final class S3Request {
private S3Request() { }
static void validateObjectHeaders(com.sun.net.httpserver.Headers headers) {
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-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",
"x-amz-acl").contains(lower) && !lower.startsWith("x-amz-checksum-") &&
!lower.startsWith("x-amz-grant-"))
unsupported("Amazon header");
if (lower.startsWith("x-amz-server-side-") ||
lower.startsWith("x-amz-copy-source-")) unsupported("Object metadata, encryption, ACL or tagging header");
}
}
static void verifyContentMd5(com.sun.net.httpserver.Headers headers, byte[] body) {
String encoded = SigV4.single(headers, "content-md5");
if (encoded == null) return;
byte[] expected;
try { expected = Base64.getDecoder().decode(encoded); }
catch (IllegalArgumentException error) {
throw new StoreException(400, "InvalidDigest", "Invalid Content-MD5");
}
if (expected.length != 16) throw new StoreException(400, "InvalidDigest", "Invalid Content-MD5");
try {
byte[] actual = MessageDigest.getInstance("MD5").digest(body);
if (!MessageDigest.isEqual(expected, actual))
throw new StoreException(400, "BadDigest", "Content-MD5 mismatch");
} catch (java.security.NoSuchAlgorithmException error) { throw new IllegalStateException(error); }
}
static String contentType(com.sun.net.httpserver.Headers headers) {
String value = SigV4.single(headers, "content-type");
if (value == null) return "application/octet-stream";
if (value.isBlank() || value.getBytes(StandardCharsets.UTF_8).length > 255 ||
!value.chars().allMatch(c -> c >= 32 && c <= 126))
throw new StoreException(400, "InvalidArgument", "Invalid Content-Type");
return value;
}
static void requireEmptyBody(HttpExchange exchange, String hash) {
var headers = exchange.getRequestHeaders();
if (headers.containsKey("transfer-encoding") ||
(headers.containsKey("content-length") && !"0".equals(SigV4.single(headers, "content-length"))) ||
!(hash.equals("UNSIGNED-PAYLOAD") || hash.equals(SigV4.hex(SigV4.hash(new byte[0])))))
throw new StoreException(400, "InvalidRequest", "Request must have an empty body");
}
static boolean multipartRequest(String method, Map<String, String> query) {
if (query.containsKey("uploads"))
return method.equals("POST") && query.get("uploads").isEmpty() &&
query.keySet().stream().allMatch(java.util.Set.of("uploads", "x-id")::contains) &&
(!query.containsKey("x-id") || query.get("x-id").equals("CreateMultipartUpload"));
if (!query.containsKey("uploadId") ||
!query.keySet().stream().allMatch(java.util.Set.of("uploadId", "partNumber",
"part-number-marker", "max-parts", "x-id")::contains))
return false;
String xId = query.get("x-id");
if (method.equals("PUT")) return query.containsKey("partNumber") &&
!query.containsKey("part-number-marker") && !query.containsKey("max-parts") &&
(xId == null || xId.equals("UploadPart"));
if (query.containsKey("partNumber")) return false;
if (method.equals("GET")) return xId == null || xId.equals("ListParts");
if (query.containsKey("part-number-marker") || query.containsKey("max-parts")) return false;
return (method.equals("POST") && (xId == null || xId.equals("CompleteMultipartUpload"))) ||
(method.equals("DELETE") && (xId == null || xId.equals("AbortMultipartUpload")));
}
static int boundedNumber(String text, int minimum, int maximum, int defaultValue) {
if (text == null) return defaultValue;
int value;
try {
value = Integer.parseInt(text);
} catch (NumberFormatException error) {
throw new StoreException(400, "InvalidArgument", "Invalid listing limit or marker");
}
if (value < minimum || value > maximum)
throw new StoreException(400, "InvalidArgument", "Invalid listing limit or marker");
return value;
}
static long decodedLength(com.sun.net.httpserver.Headers headers) {
String value = SigV4.single(headers, "x-amz-decoded-content-length");
if (value == null || !value.matches("[0-9]{1,19}"))
throw new StoreException(400, "InvalidArgument", "Invalid decoded content length");
try { return Long.parseLong(value); }
catch (NumberFormatException error) {
throw new StoreException(400, "InvalidArgument", "Invalid decoded content length");
}
}
static AwsChunkedInputStream chunkedBody(HttpExchange exchange,
SigV4.Verified verified) {
var headers = exchange.getRequestHeaders();
if (!"aws-chunked".equals(SigV4.single(headers, "content-encoding")))
throw new StoreException(400, "InvalidRequest", "Signed chunk upload requires aws-chunked encoding");
if (contentLength(headers) < 0 && !headers.containsKey("transfer-encoding"))
throw new StoreException(411, "MissingContentLength", "Encoded content length is required");
long length = decodedLength(headers);
String trailer = SigV4.single(headers, "x-amz-trailer");
if (verified.payload().endsWith("-TRAILER")) {
if (trailer == null || !trailer.matches("x-amz-checksum-[a-z0-9]+"))
throw new StoreException(400, "InvalidRequest", "A checksum trailer is required");
} else if (trailer != null) {
throw new StoreException(400, "InvalidRequest", "Unexpected checksum trailer");
}
return new AwsChunkedInputStream(exchange.getRequestBody(), verified, length, trailer);
}
static long contentLength(com.sun.net.httpserver.Headers headers) {
String text = SigV4.single(headers, "content-length");
if (text == null) return -1;
try { return Long.parseLong(text); }
catch (NumberFormatException e) { throw new StoreException(400, "InvalidArgument", "Invalid Content-Length"); }
}
static String expectedPayloadHash(String hash) {
return hash.matches("[0-9a-f]{64}") ? hash : null;
}
static byte[] signedBody(HttpExchange exchange, String hash, int limit) throws IOException {
if (!hash.equals("UNSIGNED-PAYLOAD") && !hash.matches("[0-9a-f]{64}"))
throw new StoreException(400, "InvalidRequest", "Unsupported body signing mode");
long length = contentLength(exchange.getRequestHeaders());
if (length < 0) throw new StoreException(411, "MissingContentLength", "Content-Length is required");
if (length > limit) throw new StoreException(413, "EntityTooLarge", "Request body is too large");
byte[] body = exchange.getRequestBody().readNBytes(limit + 1);
if (body.length != length) throw new StoreException(400, "IncompleteBody", "Body length does not match Content-Length");
if (!hash.equals("UNSIGNED-PAYLOAD") && !SigV4.hex(SigV4.hash(body)).equals(hash))
throw new StoreException(400, "XAmzContentSHA256Mismatch", "Payload hash mismatch");
return body;
}
record Range(long start, long end, boolean partial) {
long length() { return end < start ? 0 : end - start + 1; }
}
static Range range(String header, long size) {
if (header == null) return new Range(0, size - 1, false);
if (!header.matches("bytes=[0-9]*-[0-9]*") || header.equals("bytes=-") || size == 0)
throw new StoreException(416, "InvalidRange", "The requested range is not satisfiable");
String[] parts = header.substring(6).split("-", -1);
try {
long start, end;
if (parts[0].isEmpty()) {
long suffix = Long.parseLong(parts[1]);
if (suffix == 0) throw new NumberFormatException();
start = Math.max(0, size - suffix);
end = size - 1;
} else {
start = Long.parseLong(parts[0]);
end = parts[1].isEmpty() ? size - 1 : Math.min(Long.parseLong(parts[1]), size - 1);
}
if (start >= size || end < start) throw new NumberFormatException();
return new Range(start, end, true);
} catch (NumberFormatException e) {
throw new StoreException(416, "InvalidRange", "The requested range is not satisfiable");
}
}
record ListRequest(String prefix, String delimiter, String encoding, int maxKeys, String after) { }
static ListRequest listRequest(Map<String, String> query) {
String prefix = query.getOrDefault("prefix", ""), delimiter = query.getOrDefault("delimiter", "");
String encoding = query.get("encoding-type");
if (encoding != null && !encoding.equals("url")) unsupported("Encoding type");
if (query.containsKey("continuation-token") && query.containsKey("start-after"))
throw new StoreException(400, "InvalidArgument", "Use either continuation-token or start-after");
int maxKeys;
try { maxKeys = Integer.parseInt(query.getOrDefault("max-keys", "1000")); }
catch (NumberFormatException e) { throw new StoreException(400, "InvalidArgument", "Invalid max-keys"); }
if (maxKeys < 0 || maxKeys > 1000) throw new StoreException(400, "InvalidArgument", "Invalid max-keys");
String after = query.get("start-after");
if (query.containsKey("continuation-token")) {
try {
byte[] decoded = Base64.getUrlDecoder().decode(query.get("continuation-token"));
after = StandardCharsets.UTF_8.newDecoder().onMalformedInput(java.nio.charset.CodingErrorAction.REPORT)
.decode(java.nio.ByteBuffer.wrap(decoded)).toString();
} catch (IllegalArgumentException | java.nio.charset.CharacterCodingException e) {
throw new StoreException(400, "InvalidArgument", "Invalid continuation token");
}
}
return new ListRequest(prefix, delimiter, encoding, maxKeys, after);
}
static Map<String, String> query(String raw) {
Map<String, String> result = new HashMap<>();
if (raw == null || raw.isEmpty()) return result;
for (String part : raw.split("&", -1)) {
String[] pair = part.split("=", 2);
String name = SigV4.decode(pair[0]);
String value = SigV4.decode(pair.length == 2 ? pair[1] : "");
if (result.put(name, value) != null)
throw new StoreException(400, "InvalidArgument", "Duplicate query parameter");
}
return result;
}
static void unsupported(String feature) { throw new StoreException(501, "NotImplemented", feature + " is not supported"); }
}
+177
View File
@@ -0,0 +1,177 @@
package cloud.lunarsky.store;
import com.sun.net.httpserver.HttpExchange;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
final class S3Xml {
private S3Xml() { }
static String tagXml(Map<String, String> tags) {
StringBuilder body = new StringBuilder("<Tagging><TagSet>");
new java.util.TreeMap<>(tags).forEach((key, value) -> body.append("<Tag><Key>")
.append(xml(key)).append("</Key><Value>").append(xml(value)).append("</Value></Tag>"));
return body.append("</TagSet></Tagging>").toString();
}
static Map<String, String> parseTags(byte[] body) {
try {
var factory = javax.xml.parsers.DocumentBuilderFactory.newInstance();
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(javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, true);
factory.setExpandEntityReferences(false);
var builder = factory.newDocumentBuilder();
builder.setErrorHandler(new org.xml.sax.helpers.DefaultHandler() {
@Override public void fatalError(org.xml.sax.SAXParseException error) throws org.xml.sax.SAXException {
throw error;
}
});
var document = builder.parse(new ByteArrayInputStream(body));
var root = document.getDocumentElement();
if (!root.getTagName().equals("Tagging")) throw new IllegalArgumentException();
var sets = root.getElementsByTagName("TagSet");
if (sets.getLength() != 1) throw new IllegalArgumentException();
for (int i = 0; i < root.getChildNodes().getLength(); i++) {
var child = root.getChildNodes().item(i);
if (child instanceof org.w3c.dom.Element && child != sets.item(0))
throw new IllegalArgumentException();
}
Map<String, String> tags = new java.util.TreeMap<>();
var entries = sets.item(0).getChildNodes();
for (int i = 0; i < entries.getLength(); i++) {
if (!(entries.item(i) instanceof org.w3c.dom.Element tag)) continue;
if (!tag.getTagName().equals("Tag")) throw new IllegalArgumentException();
var keys = tag.getElementsByTagName("Key");
var values = tag.getElementsByTagName("Value");
if (keys.getLength() != 1 || values.getLength() != 1 ||
tag.getElementsByTagName("*").getLength() != 2) throw new IllegalArgumentException();
if (tags.put(keys.item(0).getTextContent(), values.item(0).getTextContent()) != null)
throw new IllegalArgumentException();
}
ObjectAttributes.validateTags(tags);
return Map.copyOf(tags);
} catch (Exception error) {
throw new StoreException(400, "MalformedXML", "Invalid object tagging body");
}
}
static List<MultipartStorage.Part> completedParts(byte[] body) {
try {
var factory = javax.xml.parsers.DocumentBuilderFactory.newInstance();
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(javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, true);
factory.setExpandEntityReferences(false);
var document = factory.newDocumentBuilder().parse(new ByteArrayInputStream(body));
if (!document.getDocumentElement().getNodeName().equals("CompleteMultipartUpload"))
throw new IllegalArgumentException();
var nodes = document.getDocumentElement().getChildNodes();
List<MultipartStorage.Part> parts = new ArrayList<>();
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;
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();
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 (parts.size() > 10000) throw new IllegalArgumentException();
}
return parts;
} catch (Exception error) {
throw new StoreException(400, "MalformedXML", "Invalid multipart completion body");
}
}
static void sendXml(HttpExchange exchange, int status, String xml) throws IOException {
byte[] body = ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + xml).getBytes(StandardCharsets.UTF_8);
exchange.getResponseHeaders().set("Content-Type", "application/xml");
exchange.sendResponseHeaders(status, body.length);
exchange.getResponseBody().write(body);
}
static ObjectStorage.VersioningState parseVersioning(byte[] body) {
try {
var factory = javax.xml.parsers.DocumentBuilderFactory.newInstance();
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(javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, true);
factory.setExpandEntityReferences(false);
var document = factory.newDocumentBuilder().parse(new ByteArrayInputStream(body));
var root = document.getDocumentElement();
if (!root.getNodeName().equals("VersioningConfiguration")) throw new IllegalArgumentException();
String status = null;
for (int i = 0; i < root.getChildNodes().getLength(); i++) {
var child = root.getChildNodes().item(i);
if (!(child instanceof org.w3c.dom.Element element)) continue;
if (!element.getNodeName().equals("Status") || status != null)
throw new IllegalArgumentException();
status = element.getTextContent().trim();
}
if ("Enabled".equals(status)) return ObjectStorage.VersioningState.ENABLED;
if ("Suspended".equals(status)) return ObjectStorage.VersioningState.SUSPENDED;
} catch (Exception ignored) { }
throw new StoreException(400, "MalformedXML", "Invalid versioning configuration");
}
static void appendListHeader(StringBuilder xml, Map<String, String> query, S3Request.ListRequest request,
ObjectStorage.ListPage page, String bucketName) {
String prefix = request.prefix(), delimiter = request.delimiter(), encoding = request.encoding();
xml.append("<Name>").append(xml(bucketName)).append("</Name><Prefix>").append(xml(listKey(prefix, encoding))).append("</Prefix>");
if (!delimiter.isEmpty()) xml.append("<Delimiter>").append(xml(listKey(delimiter, encoding))).append("</Delimiter>");
if (encoding != null) xml.append("<EncodingType>url</EncodingType>");
if (query.containsKey("continuation-token")) xml.append("<ContinuationToken>")
.append(xml(query.get("continuation-token"))).append("</ContinuationToken>");
if (query.containsKey("start-after")) xml.append("<StartAfter>")
.append(xml(listKey(query.get("start-after"), encoding))).append("</StartAfter>");
xml.append("<KeyCount>").append(page.keyCount()).append("</KeyCount><MaxKeys>").append(request.maxKeys())
.append("</MaxKeys><IsTruncated>").append(page.truncated()).append("</IsTruncated>");
}
static void appendListEntries(StringBuilder xml, ObjectStorage.ListPage page, String encoding) {
int objectAt = 0, prefixAt = 0;
while (objectAt < page.objects().size() || prefixAt < page.prefixes().size()) {
if (objectAt < page.objects().size() &&
(prefixAt == page.prefixes().size() ||
page.objects().get(objectAt).key().compareTo(page.prefixes().get(prefixAt)) < 0)) {
var entry = page.objects().get(objectAt++);
var meta = entry.metadata();
xml.append("<Contents><Key>").append(xml(listKey(entry.key(), encoding))).append("</Key><LastModified>")
.append(Instant.ofEpochMilli(meta.modified())).append("</LastModified><ETag>&quot;")
.append(meta.etag()).append("&quot;</ETag><Size>").append(meta.length())
.append("</Size><StorageClass>STANDARD</StorageClass></Contents>");
} else {
xml.append("<CommonPrefixes><Prefix>")
.append(xml(listKey(page.prefixes().get(prefixAt++), encoding)))
.append("</Prefix></CommonPrefixes>");
}
}
}
static String listKey(String key, String encoding) {
return encoding == null ? key : SigV4.encode(key, false);
}
static String xml(String text) {
return text.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;").replace("\"", "&quot;");
}
static void sendError(HttpExchange exchange, int status, String code, String message, String id) throws IOException {
if (exchange.getResponseCode() != -1) return;
byte[] body = ("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Error><Code>" + xml(code) +
"</Code><Message>" + xml(message) + "</Message><RequestId>" + id + "</RequestId></Error>")
.getBytes(StandardCharsets.UTF_8);
exchange.getResponseHeaders().set("Content-Type", "application/xml");
exchange.sendResponseHeaders(status, exchange.getRequestMethod().equals("HEAD") ? -1 : body.length);
if (!exchange.getRequestMethod().equals("HEAD")) exchange.getResponseBody().write(body);
}
}
+1 -1
View File
@@ -1,7 +1,7 @@
package cloud.lunarsky.store; package cloud.lunarsky.store;
final class Version { final class Version {
static final String VALUE = "0.0.8"; static final String VALUE = "0.0.9";
private Version() {} private Version() {}
} }
+56 -1
View File
@@ -3,14 +3,68 @@ package cloud.lunarsky.store;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Comparator; import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CountDownLatch; import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.Future; import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
public final class ConcurrencyTest { public final class ConcurrencyTest {
private static void parallelCapacity() throws Exception {
Path root = Files.createTempDirectory("store-parallel-capacity-");
byte[] body = new byte[4096];
Set<String> saved = new HashSet<>();
try {
try (var store = new DiskStore(root, body.length, 8L * body.length);
var workers = Executors.newFixedThreadPool(16)) {
CountDownLatch start = new CountDownLatch(1);
List<Future<String>> writes = new ArrayList<>();
for (int i = 0; i < 16; i++) {
String key = "parallel-" + i;
writes.add(workers.submit(() -> {
start.await();
try {
store.put("test", key, new ByteArrayInputStream(body), body.length,
SigV4.hex(SigV4.hash(body)), null, true, "application/octet-stream");
return key;
} catch (StoreException error) {
if (error.status != 507) throw error;
return null;
}
}));
}
start.countDown();
for (Future<String> write : writes) {
String key = write.get();
if (key != null) saved.add(key);
}
if (saved.size() != 8 || store.usedBytes() != 8L * body.length ||
store.list("test", "", "", 100, null).objects().size() != 8)
throw new AssertionError("Concurrent writes exceeded capacity or lost an acknowledgement");
}
try (var restarted = new DiskStore(root, body.length, 8L * body.length)) {
if (restarted.usedBytes() != 8L * body.length ||
restarted.list("test", "", "", 100, null).objects().size() != 8)
throw new AssertionError("Concurrent writes were not recovered after restart");
for (String key : saved) {
try (var object = restarted.open("test", key)) {
if (!Arrays.equals(object.stream().readAllBytes(), body))
throw new AssertionError("Recovered object differs from acknowledged write");
}
}
}
} finally {
try (var paths = Files.walk(root)) {
for (Path path : paths.sorted(Comparator.reverseOrder()).toList()) Files.delete(path);
}
}
}
private static ObjectStorage.Metadata put(DiskStore store, byte[] body) throws Exception { private static ObjectStorage.Metadata put(DiskStore store, byte[] body) throws Exception {
return store.put("test", "shared", new ByteArrayInputStream(body), body.length, return store.put("test", "shared", new ByteArrayInputStream(body), body.length,
SigV4.hex(SigV4.hash(body)), null, false, "application/octet-stream"); SigV4.hex(SigV4.hash(body)), null, false, "application/octet-stream");
@@ -78,11 +132,12 @@ public final class ConcurrencyTest {
} catch (StoreException expected) { } catch (StoreException expected) {
if (expected.status != 404) throw expected; if (expected.status != 404) throw expected;
} }
System.out.println("Concurrent storage tests passed: atomic overwrite, read and listing after acknowledgement, delete");
} finally { } finally {
try (var paths = Files.walk(root)) { try (var paths = Files.walk(root)) {
for (Path path : paths.sorted(Comparator.reverseOrder()).toList()) Files.delete(path); for (Path path : paths.sorted(Comparator.reverseOrder()).toList()) Files.delete(path);
} }
} }
parallelCapacity();
System.out.println("Concurrent storage tests passed: atomic overwrite, read and listing after acknowledgement, delete, parallel quota and restart");
} }
} }
+122
View File
@@ -0,0 +1,122 @@
package cloud.lunarsky.store;
import com.sun.net.httpserver.HttpServer;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Clock;
import java.util.Comparator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Executors;
public final class FeatureTest {
private static final String OWNER = "TESTACCESSKEY123";
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 void status(int expected, HttpResponse<?> response) {
if (response.statusCode() != expected)
throw new AssertionError("Expected " + expected + ", got " + response.statusCode() + ": " + response.body());
}
public static void main(String[] args) throws Exception {
Path root = Files.createTempDirectory("objectstore-feature-test-");
Path policy = root.resolve("scopes");
Files.writeString(policy, LIMITED + "\tphotos\tusers/one/\tread,write,list\n");
KeyScopes scopes = KeyScopes.fromEnvironment(Map.of("S3_KEY_SCOPES_FILE", policy.toString()),
OWNER, Set.of(OWNER, LIMITED));
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"));
denied(() -> scopes.checkBucket(LIMITED, "photos", "GET", Map.of("list-type", "2")));
denied(() -> scopes.checkBucket(LIMITED, "photos", "GET", Map.of("list-type", "2", "prefix", "users/")));
denied(() -> scopes.checkObject(LIMITED, "photos", "users/one/copy.jpg", "PUT", Map.of(),
headers("x-amz-copy-source", "/photos/users/two/private.jpg")));
denied(() -> scopes.checkObject(LIMITED, "photos", "users/one/file", "PUT", Map.of(),
headers("x-amz-acl", "public-read")));
var cors = BrowserCors.fromEnvironment(Map.of("CORS_ALLOWED_ORIGINS", "https://dashboard.example"));
var metrics = new RequestMetrics("metrics-test-token-at-least-32-characters");
var executor = Executors.newVirtualThreadPerTaskExecutor();
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 16);
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,
"us-east-1", Clock.systemUTC()),
"photos", ClientLimits.disabled(), 16, "", cors, scopes, metrics);
server.setExecutor(executor);
server.createContext("/", app::handle);
server.start();
String base = "http://127.0.0.1:" + server.getAddress().getPort();
HttpClient client = HttpClient.newHttpClient();
status(204, client.send(HttpRequest.newBuilder(URI.create(base + "/photos/file"))
.header("Origin", "https://dashboard.example")
.header("Access-Control-Request-Method", "PUT")
.header("Access-Control-Request-Headers", "content-type,x-amz-date")
.method("OPTIONS", HttpRequest.BodyPublishers.noBody()).build(),
HttpResponse.BodyHandlers.ofString()));
status(403, client.send(HttpRequest.newBuilder(URI.create(base + "/photos/file"))
.header("Origin", "https://other.example")
.header("Access-Control-Request-Method", "PUT")
.method("OPTIONS", HttpRequest.BodyPublishers.noBody()).build(),
HttpResponse.BodyHandlers.ofString()));
var health = client.send(HttpRequest.newBuilder(URI.create(base + "/health"))
.header("Origin", "https://dashboard.example").GET().build(),
HttpResponse.BodyHandlers.ofString());
status(200, health);
if (!"https://dashboard.example".equals(health.headers().firstValue("Access-Control-Allow-Origin").orElse(null)))
throw new AssertionError("Allowed origin missing from response");
status(401, client.send(HttpRequest.newBuilder(URI.create(base + "/metrics")).GET().build(),
HttpResponse.BodyHandlers.ofString()));
var snapshot = client.send(HttpRequest.newBuilder(URI.create(base + "/metrics"))
.header("Authorization", "Bearer metrics-test-token-at-least-32-characters").GET().build(),
HttpResponse.BodyHandlers.ofString());
status(200, snapshot);
if (!snapshot.body().contains("objectstore_requests_total 4"))
throw new AssertionError("Metrics did not count requests: " + snapshot.body());
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()));
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()));
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"),
"GET", new byte[0], Map.of(), LIMITED, LIMITED_SECRET), HttpResponse.BodyHandlers.ofString()));
status(403, client.send(HttpTest.signedUriAs(URI.create(base + "/photos?list-type=2"),
"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()));
} finally {
server.stop(0);
executor.close();
store.close();
try (var files = Files.walk(root)) {
for (Path path : files.sorted(Comparator.reverseOrder()).toList()) Files.delete(path);
}
}
System.out.println("Feature tests passed: scoped keys, CORS, metrics");
}
private static com.sun.net.httpserver.Headers headers(String name, String value) {
var headers = new com.sun.net.httpserver.Headers();
headers.set(name, value);
return headers;
}
private static void denied(Runnable action) {
try { action.run(); }
catch (StoreException error) {
if (error.status == 403) return;
throw new AssertionError("Wrong denial", error);
}
throw new AssertionError("Expected access denial");
}
}
+2 -2
View File
@@ -39,7 +39,7 @@ public final class HttpTest {
return signedUriAs(uri, method, body, extra, ACCESS, SECRET); return signedUriAs(uri, method, body, extra, ACCESS, SECRET);
} }
private static HttpRequest signedUriAs(URI uri, String method, byte[] body, Map<String, String> extra, static HttpRequest signedUriAs(URI uri, String method, byte[] body, Map<String, String> extra,
String access, String secret) { String access, String secret) {
String host = uri.getAuthority(); String host = uri.getAuthority();
String date = DATE.format(Instant.now()); String date = DATE.format(Instant.now());
@@ -274,7 +274,7 @@ public final class HttpTest {
String trailerToSign = "AWS4-HMAC-SHA256-TRAILER\n" + date + "\n" + scope + "\n" + String trailerToSign = "AWS4-HMAC-SHA256-TRAILER\n" + date + "\n" + scope + "\n" +
previous + "\n" + SigV4.hex(SigV4.hash((trailerName + ":" + checksum + "\n") previous + "\n" + SigV4.hex(SigV4.hash((trailerName + ":" + checksum + "\n")
.getBytes(StandardCharsets.UTF_8))); .getBytes(StandardCharsets.UTF_8)));
encoded.write(("x-amz-trailer-signature=" + SigV4.hex(SigV4.hmac(key, trailerToSign)) + encoded.write(("x-amz-trailer-signature:" + SigV4.hex(SigV4.hmac(key, trailerToSign)) +
"\r\n\r\n").getBytes(StandardCharsets.US_ASCII)); "\r\n\r\n").getBytes(StandardCharsets.US_ASCII));
byte[] upload = encoded.toByteArray(); byte[] upload = encoded.toByteArray();
HttpRequest.Builder request = HttpRequest.newBuilder(object) HttpRequest.Builder request = HttpRequest.newBuilder(object)
+3 -3
View File
@@ -85,7 +85,7 @@ public final class StoreTest {
withTrailer.write(body, 65536, 1024); withTrailer.write(body, 65536, 1024);
withTrailer.write("\r\n0;chunk-signature=2ca2aba2005185cf7159c6277faf83795951dd77a3a99e6e65d5c9f85863f992\r\n".getBytes()); withTrailer.write("\r\n0;chunk-signature=2ca2aba2005185cf7159c6277faf83795951dd77a3a99e6e65d5c9f85863f992\r\n".getBytes());
withTrailer.write("x-amz-checksum-crc32c:sOO8/Q==\r\n".getBytes()); withTrailer.write("x-amz-checksum-crc32c:sOO8/Q==\r\n".getBytes());
withTrailer.write("x-amz-trailer-signature=d81f82fc3505edab99d459891051a732e8730629a2e4a59689829ca17fe2e435\r\n\r\n".getBytes()); withTrailer.write("x-amz-trailer-signature:d81f82fc3505edab99d459891051a732e8730629a2e4a59689829ca17fe2e435\r\n\r\n".getBytes());
var trailerAuthorization = new SigV4.Verified("STREAMING-AWS4-HMAC-SHA256-PAYLOAD-TRAILER", var trailerAuthorization = new SigV4.Verified("STREAMING-AWS4-HMAC-SHA256-PAYLOAD-TRAILER",
"", key, date, scope, "106e2a8a18243abcf37539882f36619c00e2dfc72633413f02d3b74544bfeb8e"); "", key, date, scope, "106e2a8a18243abcf37539882f36619c00e2dfc72633413f02d3b74544bfeb8e");
try (var stream = new AwsChunkedInputStream(new ByteArrayInputStream(withTrailer.toByteArray()), try (var stream = new AwsChunkedInputStream(new ByteArrayInputStream(withTrailer.toByteArray()),
@@ -328,14 +328,14 @@ public final class StoreTest {
private static void testAdditionalKeys(Path root) throws Exception { private static void testAdditionalKeys(Path root) throws Exception {
Path file = root.resolve("access-keys"); Path file = root.resolve("access-keys");
Files.writeString(file, "SECONDARYKEY1234:secondary-secret-key-that-is-at-least-32-characters\n"); Files.writeString(file, "SECONDARYKEY1234:secondary-secret-key-that-is-at-least-32-characters\n");
Map<String, String> keys = Main.identities( Map<String, String> keys = ObjectStoreServer.identities(
Map.of("S3_CREDENTIALS_FILE", file.toString()), Map.of("S3_CREDENTIALS_FILE", file.toString()),
"TESTACCESSKEY123", "test-secret-key-that-is-at-least-32-characters"); "TESTACCESSKEY123", "test-secret-key-that-is-at-least-32-characters");
if (keys.size() != 2 || !keys.containsKey("SECONDARYKEY1234")) if (keys.size() != 2 || !keys.containsKey("SECONDARYKEY1234"))
throw new AssertionError("Additional access key was not loaded"); throw new AssertionError("Additional access key was not loaded");
Files.writeString(file, "TESTACCESSKEY123:duplicate-root-secret-that-is-at-least-32-characters\n"); Files.writeString(file, "TESTACCESSKEY123:duplicate-root-secret-that-is-at-least-32-characters\n");
try { try {
Main.identities(Map.of("S3_CREDENTIALS_FILE", file.toString()), ObjectStoreServer.identities(Map.of("S3_CREDENTIALS_FILE", file.toString()),
"TESTACCESSKEY123", "test-secret-key-that-is-at-least-32-characters"); "TESTACCESSKEY123", "test-secret-key-that-is-at-least-32-characters");
throw new AssertionError("Duplicate root key was accepted"); throw new AssertionError("Duplicate root key was accepted");
} catch (IllegalArgumentException expected) { } } catch (IllegalArgumentException expected) { }