Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
35bd1d5703 | ||
|
|
0cf5c11202 | ||
|
|
31eb4d092e | ||
|
|
a4f55a5bde | ||
|
|
49e2bdb869 | ||
|
|
510e519bd1 | ||
|
|
43987bbadb | ||
|
|
a71c4fa5f1 | ||
|
|
1d1f329220 | ||
|
|
91f6825726 | ||
|
|
885239be1c | ||
|
|
d6427fbac9 | ||
|
|
ed7712a8af | ||
|
|
00d2af2fb0 | ||
|
|
11bfe71124 | ||
|
|
01c82a8223 | ||
|
|
350611d562 | ||
|
|
2276fee60c | ||
|
|
b6b8e0adfb |
No files matched your search
+20
-3
@@ -1,7 +1,24 @@
|
||||
S3_ACCESS_KEY=
|
||||
S3_SECRET_KEY=
|
||||
S3_ACCESS_KEY=[Replace_with_your_S3_Access_Key]
|
||||
S3_SECRET_KEY=[Replace_with_your_S3_Secret_Key]
|
||||
CLUSTER_TOKEN=
|
||||
CLUSTER_REPAIR_TOKEN=
|
||||
POSTGRES_PASSWORD=
|
||||
POSTGRES_PASSWORD=[PG_Pass]
|
||||
S3_BUCKET=objects
|
||||
S3_CREDENTIALS_FILE=
|
||||
S3_KEY_SCOPES_FILE=
|
||||
S3_SESSION_CREDENTIALS_FILE=
|
||||
S3_IDENTITY_POLICIES_DIR=
|
||||
METRICS_BEARER_TOKEN=
|
||||
CLUSTER_HOST_PORT=9001
|
||||
MAX_OBJECT_BYTES=134217728
|
||||
MAX_TOTAL_BYTES=2147483648
|
||||
MAX_IN_FLIGHT_REQUESTS=16
|
||||
OBJECTSTORE_REQUEST_TIMEOUT_SECONDS=0
|
||||
OBJECTSTORE_RESPONSE_TIMEOUT_SECONDS=0
|
||||
CORS_ALLOWED_ORIGINS=
|
||||
HTTP_BACKLOG=64
|
||||
S3_VIRTUAL_HOST_SUFFIX=
|
||||
S3_PUBLIC_ENDPOINT=
|
||||
# For compose.cluster.encrypted.yaml only; provision and mount LUKS before setting these.
|
||||
ENCRYPTED_STORAGE_ROOT=
|
||||
ENCRYPTED_VOLUME_ID=
|
||||
+23
-2
@@ -1,9 +1,30 @@
|
||||
# Copy to .env and replace both empty values with random credentials.
|
||||
# The Compose file refuses to start without them.
|
||||
# Copy to .env and set both values to unique random credentials.
|
||||
# The Compose file refuses to start while either value is empty.
|
||||
S3_ACCESS_KEY=
|
||||
S3_SECRET_KEY=
|
||||
S3_BUCKET=objects
|
||||
S3_REGION=us-east-1
|
||||
S3_CREDENTIALS_FILE=
|
||||
S3_KEY_SCOPES_FILE=
|
||||
S3_SESSION_CREDENTIALS_FILE=
|
||||
S3_IDENTITY_POLICIES_DIR=
|
||||
METRICS_BEARER_TOKEN=
|
||||
HOST_PORT=9000
|
||||
MAX_OBJECT_BYTES=134217728
|
||||
MAX_TOTAL_BYTES=2147483648
|
||||
PUBLIC_REQUESTS_PER_SECOND=0
|
||||
PUBLIC_REQUEST_BURST=
|
||||
PUBLIC_BYTES_PER_SECOND=0
|
||||
PUBLIC_BYTE_BURST=
|
||||
PUBLIC_MAX_IN_FLIGHT_PER_IP=
|
||||
PUBLIC_TRUSTED_PROXY_IPS=
|
||||
MAX_IN_FLIGHT_REQUESTS=16
|
||||
HTTP_BACKLOG=64
|
||||
S3_VIRTUAL_HOST_SUFFIX=
|
||||
S3_PUBLIC_ENDPOINT=
|
||||
CORS_ALLOWED_ORIGINS=
|
||||
OBJECTSTORE_REQUEST_TIMEOUT_SECONDS=0
|
||||
OBJECTSTORE_RESPONSE_TIMEOUT_SECONDS=0
|
||||
# For compose.encrypted.yaml only; provision and mount LUKS before setting these.
|
||||
ENCRYPTED_STORAGE_ROOT=
|
||||
ENCRYPTED_VOLUME_ID=
|
||||
@@ -1,4 +1,5 @@
|
||||
out/
|
||||
rust-client/target/
|
||||
.env
|
||||
.env.cluster
|
||||
*.local.env
|
||||
|
||||
+17
-8
@@ -4,19 +4,28 @@ RUN wget -q -O /tmp/postgresql.jar https://jdbc.postgresql.org/download/postgres
|
||||
echo '73914527305a40cce504b0d3d90b23caf565136912d607ae8ae7c5895512332c /tmp/postgresql.jar' | sha256sum -c -
|
||||
COPY src ./src
|
||||
COPY test ./test
|
||||
RUN mkdir /out && javac --release 21 --add-modules jdk.httpserver,java.net.http -d /out src/cloud/lunarsky/store/*.java test/cloud/lunarsky/store/*.java
|
||||
RUN java --add-modules jdk.httpserver -cp /out cloud.lunarsky.store.StoreTest
|
||||
RUN java --add-modules jdk.httpserver -cp /out cloud.lunarsky.store.ConcurrencyTest
|
||||
RUN java --add-modules jdk.httpserver,java.net.http -cp /out cloud.lunarsky.store.HttpTest
|
||||
RUN java --add-modules jdk.httpserver,java.net.http -cp /out cloud.lunarsky.store.ClusterNodeTest
|
||||
RUN java -cp /out cloud.lunarsky.store.CliTest
|
||||
COPY lib/hash4j-0.30.0.jar /tmp/hash4j.jar
|
||||
RUN echo 'd3224b113ea835ce3452097747e5209ec760cf443dbed770d6ba68a0d480178f /tmp/hash4j.jar' | sha256sum -c -
|
||||
RUN mkdir /out && javac --release 21 --add-modules jdk.httpserver,java.net.http -cp /tmp/hash4j.jar -d /out src/cloud/lunarsky/store/*.java test/cloud/lunarsky/store/*.java
|
||||
RUN java --add-modules jdk.httpserver -cp /out:/tmp/hash4j.jar cloud.lunarsky.store.StoreTest
|
||||
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.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 --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 -cp /out:/tmp/hash4j.jar cloud.lunarsky.store.CliTest
|
||||
|
||||
FROM eclipse-temurin:21-jre-alpine
|
||||
RUN addgroup -g 10001 store && adduser -D -u 10001 -G store store && mkdir /data && chown store:store /data
|
||||
COPY --from=build /out /app
|
||||
COPY --from=build /tmp/postgresql.jar /app/postgresql.jar
|
||||
COPY --from=build /tmp/hash4j.jar /app/hash4j.jar
|
||||
COPY lib/LICENSE.hash4j /app/LICENSE.hash4j
|
||||
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
|
||||
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", "cloud.lunarsky.store.Main"]
|
||||
ENTRYPOINT ["/usr/local/bin/objectstore-server"]
|
||||
+175
@@ -0,0 +1,175 @@
|
||||
# Operations
|
||||
|
||||
These notes describe the development branch and may be ahead of the latest tagged release. For v0.0.8, use the [versioned operations docs](https://docs.lunarsky.cloud/objectstore/v0.0.8/operations).
|
||||
|
||||
## Encrypted storage
|
||||
|
||||
At-rest encryption is **opt-in** through a host-mounted dm-crypt/LUKS filesystem. ObjectStore does not encrypt data itself or manage the key. Unlock and mount the filesystem outside Docker, then set `ENCRYPTED_STORAGE_ROOT` to its mount point and `ENCRYPTED_VOLUME_ID` to a stable 32-character lowercase hex identifier in a private environment file. Generate the ID with `openssl rand -hex 16`; it guards the mount and is **not** a key. Store the LUKS recovery key separately from data and backups.
|
||||
|
||||
On the mounted filesystem, run `sh scripts/prepare-encrypted-storage.sh single /path/to/objectstore.env` or `sh scripts/prepare-encrypted-storage.sh cluster /path/to/cluster.env`. It reads only the encryption settings, verifies the dm-crypt mount, and refuses nonempty directories. Give it permission to create directories and set container ownership. Start the matching Compose overlay:
|
||||
|
||||
```sh
|
||||
docker compose --env-file /path/to/objectstore.env -f compose.yaml -f compose.encrypted.yaml up -d --build
|
||||
docker compose --env-file /path/to/cluster.env -f compose.cluster.yaml -f compose.cluster.encrypted.yaml up -d --build
|
||||
```
|
||||
|
||||
Use the first command for single-node mode or the second for the **local development cluster**. The overlays mount encrypted directories for object data, nodes, PostgreSQL, and staging. A marker check prevents startup on a missing or wrong mount; it does not unlock LUKS. Arrange host unlock and mount before Compose starts.
|
||||
|
||||
**Existing volumes are not migrated automatically.** Stop the stack, verify a backup, and copy the stopped volumes into prepared encrypted directories. For PostgreSQL, copy its data into `cluster/metadata/pgdata` because the overlay changes `PGDATA`. Verify the restore before retiring old volumes. Each host in a future multi-host deployment needs its own encrypted mount and key recovery plan.
|
||||
|
||||
This does not cover Docker logs, swap, other temporary files, external backups, or a compromised running host. Protect those separately, use TLS, and test backup recovery. Encryption alone does not establish GDPR compliance.
|
||||
|
||||
## Access keys and ACLs
|
||||
|
||||
`S3_ACCESS_KEY` and `S3_SECRET_KEY` define the owner. For additional identities, put one `ACCESSKEY:secret` pair per line in a private file and mount it read-only at `/run/secrets/s3-credentials` on `objectstore` (or `gateway` in cluster mode). Set `S3_CREDENTIALS_FILE` to that path. Keys need 16–128 alphanumeric characters; secrets need at least 32 characters. Changes load on restart. Additional identities have no access until granted it.
|
||||
|
||||
New buckets default to `BucketOwnerEnforced` and all four Block Public Access flags enabled. Existing buckets retain their prior ACL behavior on upgrade. The owner can inspect or change settings with `GET`/`PUT ?ownershipControls` and `GET`/`PUT ?publicAccessBlock`; changing a legacy bucket to owner-enforced immediately stops its ACL grants from authorizing requests. Public ACL writes are blocked when `BlockPublicAcls` is enabled, and existing public ACL grants are ignored when `IgnorePublicAcls` is enabled. `GET`/`PUT`/`DELETE ?policy` manages a bucket policy. `BlockPublicPolicy` rejects new policies that allow a wildcard principal; `RestrictPublicBuckets` prevents anonymous access through such a policy.
|
||||
|
||||
On a bucket with ACLs enabled, the owner can set `x-amz-acl: public-read` or signed `x-amz-grant-*` headers on bucket creation, uploads, copies, and multipart initiation. Use `GET ?acl` to read bucket or object grants; `PUT ?acl` accepts signed grant headers or an XML `AccessControlPolicy`. A grantee ID is its access key. Permissions are `READ`, `WRITE`, `READ_ACP`, `WRITE_ACP`, and `FULL_CONTROL`; `AllUsers` can only read, and `AuthenticatedUsers` is recognized. Anonymous reads require an `AllUsers` grant or an allowed bucket policy. Overwriting an object resets its ACL to private unless new grants are supplied; retained versions keep their ACLs. Email grantees return `405 MethodNotAllowed`, matching AWS's removal of that grant type.
|
||||
|
||||
For a narrower additional key, mount a second private file and set `S3_KEY_SCOPES_FILE` to its container path. Each non-comment line has four **tab-separated** fields: access key, bucket, key prefix, and comma-separated actions (`read`, `write`, `list`). For example, `UPLOADKEY12345678<TAB>media<TAB>users/42/<TAB>read,write,list`. The file may name a permanent or session identity; the owner key is always unrestricted. Once the scope file is enabled, an additional key with no scope is denied. A list request must include a prefix inside the granted prefix. Copy requires read permission on the source and write permission on the destination. Restricted keys cannot change ACLs or manage buckets. A scope is a ceiling: the bucket ACL, bucket policy, or identity policy must also grant access. Restart the service after editing the files.
|
||||
|
||||
To use identity policies, mount a private directory and set `S3_IDENTITY_POLICIES_DIR` to its container path. Put one `<ACCESSKEY>.json` file per identity. The supported JSON subset uses `Version: "2012-10-17"` and `Statement` entries with `Effect`, `Action`, and `Resource`; it accepts S3 action wildcards and bucket/object ARNs. The bucket-policy form also requires `Principal`, using `*`, an access key, or `{ "AWS": "ACCESSKEY" }`. Policies govern object reads, writes, deletes, copies, ACLs, bucket listing, and multipart writes or aborts. Explicit denies win. `Condition`, `NotAction`, `NotResource`, `NotPrincipal`, and IAM roles are rejected rather than silently ignored. Files load on restart; protect the directory like credentials.
|
||||
|
||||
For a restricted key to upload **and read** files in a new owner-enforced bucket, give it both a `read,write` key scope for its prefix and an identity policy allowing `s3:PutObject` and `s3:GetObject` on that prefix. For example, a scope of `UPLOADKEY12345678<TAB>media<TAB>users/42/<TAB>read,write` pairs with `UPLOADKEY12345678.json` containing `{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["s3:PutObject","s3:GetObject"],"Resource":"arn:aws:s3:::media/users/42/*"}]}`. A scope alone is only a ceiling, and ObjectStore does not infer ownership from the uploader's key. Assign a distinct prefix per key when keys must not read each other's files.
|
||||
|
||||
For externally issued sessions, mount a private file and set `S3_SESSION_CREDENTIALS_FILE` to its container path. Each line is four **tab-separated** fields: session access key, secret, security token, and Unix expiry time in seconds. Session keys use the same 16–128 alphanumeric format as permanent keys; secrets and tokens need at least 32 characters. Signed requests must sign and send `x-amz-security-token`; presigned URLs must include signed `X-Amz-Security-Token`. Expired or mismatched tokens are denied on every request. ObjectStore does not issue or refresh sessions: provision and rotate the file outside the service, then restart. A session has no access until an ACL, bucket policy, or identity policy grants it; a configured key scope can narrow it further.
|
||||
|
||||
The configured owner owns every bucket and object. `BucketOwnerPreferred` and `ObjectWriter` are accepted as ACL-enabled modes, but there is one ObjectStore account, so cross-account object ownership is not modeled. A `WRITE_ACP` grantee can change an ACL only on a retained, non-null version; current unversioned and null versions require the owner key. Version lists, multipart inspection, tags, versioning controls, bucket creation/deletion, and capabilities remain owner-only. These policy features cover common object and bucket access, not full AWS IAM or STS. Public bucket `READ` exposes names; public object `READ` exposes bytes. Review grants before exposing a gateway.
|
||||
|
||||
## CLI and tests
|
||||
|
||||
From the server shell, run the CLI inside the running container from the directory containing `compose.yaml`:
|
||||
|
||||
```sh
|
||||
docker compose exec objectstore objectstore status
|
||||
docker compose exec objectstore objectstore verify
|
||||
docker compose exec objectstore objectstore version
|
||||
```
|
||||
|
||||
The startup log shows the LunarSky banner, version, and a small storage summary (`docker compose logs --tail=20 objectstore`). `status` reports object and multipart usage. `verify` also checks stored payload hashes and exits nonzero on an error. Both commands can run while the service is live; they are not a snapshot or a backup.
|
||||
|
||||
## Capability discovery
|
||||
|
||||
Signed `GET /_objectstore/capabilities` returns schema version 1, software version, storage mode, operation names, and configured limits. Use header-based Signature V4. It does not disclose credentials or topology, and responses are not cached.
|
||||
|
||||
`operations` does not imply every AWS option or permission for the caller. `maxObjectBytes` limits completed objects and individual parts; `maxTotalBytes` is logical capacity; `maxParts` is 10,000. Clients should ignore new fields and unknown operations. This endpoint is an ObjectStore extension, so its absence elsewhere does not imply missing S3 features.
|
||||
|
||||
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).
|
||||
|
||||
## Local cluster prototype
|
||||
|
||||
The local cluster prototype starts three segment containers and one PostgreSQL container on the same Docker host. Copy `.env.cluster.example` to a private environment file, replace all five credential values, and run:
|
||||
|
||||
```sh
|
||||
docker compose --env-file /path/to/cluster.env -f compose.cluster.yaml up -d --build
|
||||
sh scripts/test-cluster.sh /path/to/cluster.env
|
||||
docker compose --env-file /path/to/cluster.env -f compose.cluster.yaml run --rm repair
|
||||
```
|
||||
|
||||
The cluster S3 endpoint binds to `127.0.0.1:9001`; storage nodes and PostgreSQL have no published ports. The separate repair container holds the repair credential and restores missing or corrupt replicas.
|
||||
|
||||
Multipart parts are stored on cluster nodes and indexed in PostgreSQL. Incomplete uploads count toward the logical capacity limit; abort them to release that capacity. Repair includes staged parts. The gateway upgrades the metadata schema when it starts, so back up the database before upgrading an existing cluster.
|
||||
|
||||
Node UUIDs persist on their volumes, and replica manifests use those UUIDs so reordering configured URLs cannot move an existing replica. Each node also has an operator-assigned physical host UUID. New writes require acknowledgements from two different host UUIDs. The optional `CLUSTER_TEST_NODE_DOMAINS=true` override counts containers instead, solely for local process tests; all containers in this Compose file share one physical host.
|
||||
|
||||
## Node transport TLS
|
||||
|
||||
The default local Compose cluster uses HTTP inside its private Docker network. For an HTTPS test, give each node a PKCS#12 keystore containing its private key and a certificate whose DNS subject alternative name matches its `CLUSTER_NODES` hostname. Give the gateway, repair, garbage collection, and maintenance processes a PKCS#12 truststore containing the issuing CA or each node certificate. Mount the files read-only and keep the keystores and password files outside Git.
|
||||
|
||||
Set `NODE_TLS_KEYSTORE` and `NODE_TLS_PASSWORD_FILE` on each node. Set `CLUSTER_TLS_TRUSTSTORE` and `CLUSTER_TLS_PASSWORD_FILE` on every process that contacts nodes, and change each node URL to `https://`. With a truststore configured, HTTP node URLs are rejected. The client verifies the certificate chain and hostname; a failed handshake does not fall back to HTTP. Both settings in each pair are required. Restart affected processes after rotating certificates or truststores.
|
||||
|
||||
The optional [Compose TLS overlay](compose.cluster.tls.yaml) expects `node-a.p12` through `node-d.p12`, matching `.pass` files, and `trust.p12` with `trust.pass` in `CLUSTER_TLS_DIR`. Set that variable to a private certificate directory and include both Compose files:
|
||||
|
||||
```sh
|
||||
CLUSTER_TLS_DIR=/private/objectstore-certs docker compose --env-file /path/to/cluster.env \
|
||||
-f compose.cluster.yaml -f compose.cluster.tls.yaml up -d --build
|
||||
```
|
||||
|
||||
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 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
|
||||
|
||||
`POSTGRES_JDBC_URL` can override the database URL for the gateway, repair, garbage collection, and maintenance processes. Its local Compose default now uses `targetServerType=primary`, and `/ready` returns unavailable when the database is read-only or in recovery. The base Compose file still starts and waits for its own single PostgreSQL container; it is not an HA deployment. In an independently managed deployment, list the PostgreSQL hosts in the JDBC URL and keep `targetServerType=primary`:
|
||||
|
||||
```text
|
||||
jdbc:postgresql://db-a:5432,db-b:5432/objectstore?targetServerType=primary&connectTimeout=3&socketTimeout=10
|
||||
```
|
||||
|
||||
ObjectStore opens a new database connection for each operation, so the JDBC driver can select a promoted primary after the old one is stopped. This does **not** promote a standby, fence the old primary, configure synchronous replication, or guarantee that a recently acknowledged write reached the standby. Those jobs belong to a separately operated PostgreSQL HA system. Never allow two writable metadata databases: they can diverge while serving different ObjectStore requests. A request interrupted during failover has an uncertain outcome; verify it before retrying a non-idempotent operation. For remote database connections, configure PostgreSQL TLS and use JDBC `sslmode=verify-full` with a mounted CA certificate. The provided local Compose database does not enable TLS.
|
||||
|
||||
## Migrating a local cluster
|
||||
|
||||
For an existing **local** three-node cluster that stores replicas by URL position:
|
||||
|
||||
1. Stop the old gateway. Back up PostgreSQL and every node volume, and record the original ordered `CLUSTER_NODES`.
|
||||
2. Start the nodes with the new image and a separate `CLUSTER_REPAIR_TOKEN`. Do not start the new gateway yet.
|
||||
3. Run `objectstore cluster-migrate --check` in a one-off gateway container. Compare `legacy_0` through `legacy_2` and their URLs with the pre-upgrade inventory.
|
||||
4. Run `objectstore cluster-migrate --apply id0,id1,id2` with those node IDs in the original order. The command verifies every listed live replica before conversion.
|
||||
5. Start the new gateway only after the command reports `cluster_format=2`. Do not restart an old gateway against the converted database.
|
||||
|
||||
The old format did not record the original URL mapping, so the inventory check is essential. The isolated migration fixture tests conversion; building this code does not automatically upgrade the running local prototype.
|
||||
|
||||
## Adding a cluster node
|
||||
|
||||
`objectstore cluster-join http://new-node:9100 expected-host-uuid` registers an additional local node. Add its URL to `CLUSTER_NODES` and restart the gateway. A repair pass then copies existing segments to their preferred nodes and removes obsolete replicas from the manifest only after verifying the replacements. `scripts/test-cluster.sh` exercises a fourth container joining, receiving new segments, and rebalancing existing ones.
|
||||
|
||||
## Cluster maintenance and recovery
|
||||
|
||||
From the Compose directory, use `docker compose --env-file /path/to/cluster.env -f compose.cluster.yaml` as the command prefix:
|
||||
|
||||
```sh
|
||||
docker compose --env-file /path/to/cluster.env -f compose.cluster.yaml --profile automatic up -d maintenance
|
||||
docker compose --env-file /path/to/cluster.env -f compose.cluster.yaml run --rm gc
|
||||
sh scripts/backup-cluster-metadata.sh /path/to/cluster.env /path/to/metadata.dump
|
||||
```
|
||||
|
||||
The maintenance service is opt-in. It repairs missing or corrupt replicas and rebalances them every 60 seconds by default. Set `CLUSTER_MAINTENANCE_INTERVAL_SECONDS` to change the interval. The `gc` command is a dry run; use `gc --apply` only after checking its candidate count and keeping independent backups. Cleanup records each orphan on one pass and waits at least `CLUSTER_GC_MIN_AGE_SECONDS` before deleting it on a later pass. The default age is 14 days. To permit deletion, set `CLUSTER_BACKUP_RETENTION_SECONDS` to your actual backup retention in seconds; it must be at least one day and shorter than the cleanup age. Scheduled cleanup also requires `CLUSTER_GC_ENABLED=true` on the maintenance service. The backup command writes a verified PostgreSQL archive with private file permissions. Restore it to a separate database and point a gateway at that database only after validating the restore. A backup restore is manual recovery, not automatic failover.
|
||||
|
||||
## Limits and safety
|
||||
|
||||
Public-client limits are **disabled by default**. The localhost Compose setup is unchanged. For an endpoint that accepts external clients, set one or both of `PUBLIC_REQUESTS_PER_SECOND` and `PUBLIC_BYTES_PER_SECOND` to a positive number in `.env`. The first limits requests per client IP with a token bucket; the second paces upload and download bytes through one shared per-IP budget. `PUBLIC_REQUEST_BURST` and `PUBLIC_BYTE_BURST` default to one second of their respective rates. `PUBLIC_MAX_IN_FLIGHT_PER_IP` defaults to 8 when either rate is enabled. Requests above the rate or concurrency limit receive S3 `503 SlowDown` and `Retry-After: 1`; an admitted transfer is paced rather than cut off. These are per-gateway limits, not cluster-wide quotas.
|
||||
|
||||
`MAX_IN_FLIGHT_REQUESTS` controls the per-gateway concurrency cap (default 16, range 1–1024); an additional request receives `503 SlowDown`. `HTTP_BACKLOG` controls the listening socket backlog (default 64, range 1–4096). Raise either only after a mixed upload/download load test, because each active request can hold memory, disk space, and database connections. The configured object and total storage limits still apply. `MAX_OBJECT_BYTES` currently cannot exceed 1 GiB.
|
||||
|
||||
Set `S3_VIRTUAL_HOST_SUFFIX` to a DNS suffix such as `s3.example.com` to accept `bucket.s3.example.com/key` alongside path-style `/bucket/key`. Configure DNS and TLS for the bucket hostnames, and preserve the client's original `Host` header through the proxy; Signature V4 signs it. The suffix is empty by default. This changes request parsing, not bucket naming rules or DNS configuration.
|
||||
|
||||
Set `S3_PUBLIC_ENDPOINT` to the external HTTP(S) origin, such as `https://s3.example.com`, when a TLS reverse proxy fronts ObjectStore. Multipart completion uses it to return a path-style `Location` URL. Without it, the response uses the request's signed `Host` and direct connection scheme, which may be `http` behind a TLS proxy. The value must be an origin without a path, query, user info, or fragment.
|
||||
|
||||
For example, to start with 100 requests per second and 16 MiB/s combined upload and download per IP, set `PUBLIC_REQUESTS_PER_SECOND=100` and `PUBLIC_BYTES_PER_SECOND=16777216`. Both start with a one-second burst. Adjust these numbers after measuring the actual workload; do not copy them as a universal production policy.
|
||||
|
||||
ObjectStore uses the socket peer as the client IP and ignores forwarded-IP headers by default. If a reverse proxy sits between external clients and ObjectStore, set `PUBLIC_TRUSTED_PROXY_IPS` to the exact IP address that ObjectStore sees for that proxy and configure the proxy to **replace** `X-Real-IP` with its actual client IP. A request from that trusted peer without exactly one valid numeric `X-Real-IP` is rejected. Do not trust an address reachable by arbitrary clients, and preserve the original `Host` header for Signature V4. In Docker, the proxy's address as seen by the container may be a bridge address rather than `127.0.0.1`. If proxy trust is not configured, all clients behind that proxy share its budget; this is safe from header spoofing but may throttle them together.
|
||||
|
||||
Enable these limits only on a deliberately public endpoint. They also apply to direct localhost storage calls to that same endpoint; leave them disabled for the local-only setup or run a separate local-only instance if local storage calls must be exempt. A direct loopback `/health` probe without a forwarded-IP header remains exempt. The byte limit is aggregate ingress plus egress for each IP, and several users behind one NAT share it. If a proxy buffers complete uploads before forwarding them, the upload byte limit controls proxy-to-ObjectStore traffic, not the client's initial upload speed; disable request buffering when end-to-end upload pacing is required. It is a fairness control, not a defense against connection floods before the Java handler runs. Put an internet-facing proxy or firewall in front of the gateway for TLS, connection limits, request timeouts, and buffering controls. Do not expose storage nodes or PostgreSQL publicly.
|
||||
|
||||
The default local cluster still uses plaintext node and PostgreSQL connections. The optional TLS overlay secures node traffic, but PostgreSQL TLS, automatic metadata failover, full IAM, and physical host verification remain absent. The key-scope file and policy subset limit additional signed identities; they are not an IAM replacement. Garbage collection can remove data required by an older metadata backup, so its retention guard is essential. Host UUIDs are operator labels, not proof that machines have separate power, disks, or network paths. Keep `CLUSTER_LOCAL_DEV=true` limited to local tests.
|
||||
|
||||
The standalone cluster node binds to localhost by default. Set `NODE_BIND` only for a private test network; the Compose file binds inside its private Docker network. PostgreSQL JDBC 42.7.14 is bundled in the image with its license inside the JAR.
|
||||
@@ -4,53 +4,53 @@
|
||||
|
||||
Small S3-compatible object storage for LunarSky.
|
||||
|
||||
Source: [GitHub](https://github.com/LunarSkyOSS/ObjectStore) · [Gitea mirror](https://git.lunarsky.cloud/admin/ObjectStore)
|
||||
Source: [GitHub](https://github.com/LunarSkyOSS/ObjectStore) · [Gitea mirror](https://git.lunarsky.cloud/admin/ObjectStore) · [Docs v0.0.8](https://docs.lunarsky.cloud/objectstore/v0.0.8/)
|
||||
|
||||
**Development software. Do not use it for production data.** It is provided as is, without warranty, under the [MIT License](LICENSE).
|
||||
|
||||
[](#limits-and-safety) [](LICENSE) [](Dockerfile) [](#s3-api-support-checklist)
|
||||
[](OPERATIONS.md#limits-and-safety) [](LICENSE) [](Dockerfile) [](#s3-api-support-checklist) [](https://www.codefactor.io/repository/github/lunarskyoss/objectstore)
|
||||
|
||||
## Contents
|
||||
|
||||
- [Capability checklist](#capability-checklist)
|
||||
- [S3 API support checklist](#s3-api-support-checklist)
|
||||
- [Tests](TESTS.md)
|
||||
- [Single-node setup](#single-node-setup)
|
||||
- [CLI and tests](#cli-and-tests)
|
||||
- [Local cluster prototype](#local-cluster-prototype)
|
||||
- [Migrating a local cluster](#migrating-a-local-cluster)
|
||||
- [Adding a cluster node](#adding-a-cluster-node)
|
||||
- [Limits and safety](#limits-and-safety)
|
||||
- [Disclaimer](#disclaimer)
|
||||
- [AI contributions](#ai-contributions)
|
||||
The [v0.0.8 docs](https://docs.lunarsky.cloud/objectstore/v0.0.8/) cover released behavior, the [ObjectStore Java client](https://docs.lunarsky.cloud/objectstore/v0.0.8/client/), and operations. This README describes the development branch; [TESTS.md](TESTS.md) records test coverage and limits.
|
||||
|
||||
## Capability checklist
|
||||
|
||||
ObjectStore serves one configured bucket.
|
||||
ObjectStore creates the default bucket at startup. All buckets share one capacity limit.
|
||||
|
||||
- ✅ Persistent single-node storage with checksum verification
|
||||
- ✅ Configurable per-object and total logical size limits
|
||||
- ✅ CLI status, version, and full payload verification
|
||||
- ✅ Local cluster prototype with stable node IDs and host-aware placement code
|
||||
- ⬜ Automatic repair, rebalance, and garbage collection
|
||||
- ✅ Optional dm-crypt-backed data mounts with startup guards
|
||||
- ✅ Configurable size limits and CLI verification
|
||||
- ✅ Local cluster prototype with host-aware placement and optional node TLS
|
||||
- ✅ 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)
|
||||
- ⬜ Production multi-server deployment and metadata failover
|
||||
|
||||
New objects retain their content type and key. Objects written by the earlier single-node format remain readable, but cannot appear in listings until overwritten because their original keys were not stored.
|
||||
Legacy single-node objects remain readable but stay out of listings until overwritten because their keys were not stored.
|
||||
|
||||
## S3 API support checklist
|
||||
|
||||
- ✅ Header-based AWS Signature Version 4 authentication
|
||||
- ✅ Header-based and presigned-query AWS Signature Version 4 authentication
|
||||
- ✅ Path-style and configurable virtual-hosted-style bucket addresses
|
||||
- ✅ `PutObject`, `GetObject`, `HeadObject`, and `DeleteObject` in both modes
|
||||
- ✅ Single-range GET and `ListObjectsV2` in both modes
|
||||
- ✅ SHA-256 payload verification and `x-amz-checksum-sha256` in both modes
|
||||
- ✅ `CreateMultipartUpload`, `UploadPart`, `CompleteMultipartUpload`, and `AbortMultipartUpload` in single-node mode
|
||||
- ⬜ Multipart uploads in cluster mode
|
||||
- ⬜ Presigned URLs and streaming Signature V4 uploads
|
||||
- ⬜ `CopyObject`, `ListParts`, and `ListMultipartUploads`
|
||||
- ⬜ `Content-MD5` and checksum algorithms other than SHA-256
|
||||
- ⬜ Bucket creation and listing, object versioning, ACLs, tags, and user metadata
|
||||
- ✅ `Content-MD5` and CRC32, CRC32C, CRC64NVME, XXHash64, XXHash3, XXHash128, SHA-1, SHA-256, SHA-512, and MD5 checksum headers on `PutObject` and `UploadPart`
|
||||
- ✅ `CreateMultipartUpload`, `UploadPart`, `ListParts`, `CompleteMultipartUpload`, `AbortMultipartUpload`, and `ListMultipartUploads` in both modes
|
||||
- ✅ Presigned URLs and signed streaming Signature V4 uploads, including signed checksum trailers
|
||||
- ✅ `CreateBucket`, `HeadBucket`, `DeleteBucket`, and `ListBuckets` in both modes
|
||||
- ✅ `CopyObject` across owned buckets, with `COPY` and `REPLACE` content-type and user-metadata behavior
|
||||
- ✅ User metadata on object and multipart uploads; object tags on upload, copy, and the tagging subresource
|
||||
- ✅ CRC64NVME and XXHash checksums, checksum trailers, and persisted object checksum metadata
|
||||
- ✅ Bucket versioning with retained versions, delete markers, and version-specific reads, copies, deletes, and tags in both modes
|
||||
- ✅ Bucket and object ACL grants, bucket policies, Object Ownership controls, and Block Public Access
|
||||
- ✅ Scoped identity policies and externally provisioned, expiring session credentials
|
||||
- ⬜ Full IAM, STS issuance, cross-account ACL ownership, and conditional policies
|
||||
|
||||
This is an S3 API subset, not full AWS S3 compatibility. Unsupported S3 operations and Amazon-specific headers are rejected.
|
||||
This is an S3 subset. Unsupported operations and Amazon-specific headers are rejected. Bucket names use three to 63 lowercase letters, digits, or hyphens; the default bucket cannot be deleted. Bucket creation accepts an empty body for the configured region. Tags do not control access.
|
||||
|
||||
Versioning supports enabled and suspended states. Old versions and delete markers count toward capacity; deleting a specific version is permanent. Lifecycle expiration, MFA Delete, and `ListObjectVersions` delimiter grouping are unsupported. User metadata accepts printable ASCII only.
|
||||
|
||||
`PutObject` checksums are validated and retained; without one, ObjectStore stores CRC64NVME, including for completed multipart uploads. Request `x-amz-checksum-mode: ENABLED` on GET or HEAD to receive it. `UploadPart` checksums are validated but are not returned by `ListParts` or combined into a multipart checksum. Presigned URLs expire within seven days. Signed `aws-chunked` uploads support one checksum trailer; other streaming modes are unsupported. Copies obey the object size limit.
|
||||
|
||||
## Single-node setup
|
||||
|
||||
@@ -66,55 +66,48 @@ Port 9000 binds to localhost. Data stays in the `object-data` Docker volume. `do
|
||||
|
||||
The standalone defaults are 128 MiB per object and 2 GiB total. Set `MAX_OBJECT_BYTES` and `MAX_TOTAL_BYTES` in `.env` to change them. Incomplete multipart uploads consume space until aborted.
|
||||
|
||||
## CLI and tests
|
||||
## Operations
|
||||
|
||||
From the server shell, run the CLI inside the running container from the directory containing `compose.yaml`:
|
||||
The [operations guide](OPERATIONS.md) covers encrypted mounts, access keys and ACLs, the CLI, cluster setup and maintenance, migration, metadata routing, and public-client limits. Read it before exposing an endpoint or upgrading a cluster.
|
||||
|
||||
```sh
|
||||
docker compose exec objectstore objectstore status
|
||||
docker compose exec objectstore objectstore verify
|
||||
docker compose exec objectstore objectstore version
|
||||
## Java client
|
||||
|
||||
The [JDK-only Java client](client/README.md) works with ObjectStore and other S3-compatible endpoints. Version 0.0.8 is available from `https://repo.lunarsky.cloud/` without an account. Add that URL as a Maven repository, then use `cloud.lunarsky:objectstore-client:0.0.8`.
|
||||
|
||||
Gradle (Kotlin DSL):
|
||||
|
||||
```kotlin
|
||||
repositories {
|
||||
maven { url = uri("https://repo.lunarsky.cloud/") }
|
||||
}
|
||||
dependencies {
|
||||
implementation("cloud.lunarsky:objectstore-client:0.0.8")
|
||||
}
|
||||
```
|
||||
|
||||
The startup log shows the LunarSky banner, version, and a small storage summary (`docker compose logs --tail=20 objectstore`). `status` reports object and multipart usage. `verify` also checks stored payload hashes and exits nonzero on an error. Both commands can run while the service is live; they are not a snapshot or a backup.
|
||||
Maven (`pom.xml`):
|
||||
|
||||
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.
|
||||
|
||||
## Local cluster prototype
|
||||
|
||||
The local cluster prototype starts three segment containers and one PostgreSQL container on the same Docker host. Copy `.env.cluster.example` to a private environment file, replace all four credentials, and run:
|
||||
|
||||
```sh
|
||||
docker compose --env-file /path/to/cluster.env -f compose.cluster.yaml up -d --build
|
||||
sh scripts/test-cluster.sh /path/to/cluster.env
|
||||
docker compose --env-file /path/to/cluster.env -f compose.cluster.yaml run --rm repair
|
||||
```xml
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>lunarsky</id>
|
||||
<url>https://repo.lunarsky.cloud/</url>
|
||||
</repository>
|
||||
</repositories>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>cloud.lunarsky</groupId>
|
||||
<artifactId>objectstore-client</artifactId>
|
||||
<version>0.0.8</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
```
|
||||
|
||||
The cluster S3 endpoint binds to `127.0.0.1:9001`; storage nodes and PostgreSQL have no published ports. The separate repair container holds the repair credential and restores missing or corrupt replicas.
|
||||
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.
|
||||
|
||||
Node UUIDs persist on their volumes, and replica manifests use those UUIDs so reordering configured URLs cannot move an existing replica. Each node also has an operator-assigned physical host UUID. New writes require acknowledgements from two different host UUIDs. The optional `CLUSTER_TEST_NODE_DOMAINS=true` override counts containers instead, solely for local process tests; all containers in this Compose file share one physical host.
|
||||
## Rust client
|
||||
|
||||
## Migrating a local cluster
|
||||
|
||||
For an existing **local** three-node cluster that stores replicas by URL position:
|
||||
|
||||
1. Stop the old gateway. Back up PostgreSQL and every node volume, and record the original ordered `CLUSTER_NODES`.
|
||||
2. Start the nodes with the new image and a separate `CLUSTER_REPAIR_TOKEN`. Do not start the new gateway yet.
|
||||
3. Run `objectstore cluster-migrate --check` in a one-off gateway container. Compare `legacy_0` through `legacy_2` and their URLs with the pre-upgrade inventory.
|
||||
4. Run `objectstore cluster-migrate --apply id0,id1,id2` with those node IDs in the original order. The command verifies every listed live replica before conversion.
|
||||
5. Start the new gateway only after the command reports `cluster_format=2`. Do not restart an old gateway against the converted database.
|
||||
|
||||
The old format did not record the original URL mapping, so the inventory check is essential. The isolated migration fixture tests conversion; building this code does not automatically upgrade the running local prototype.
|
||||
|
||||
## Adding a cluster node
|
||||
|
||||
`objectstore cluster-join http://new-node:9100 expected-host-uuid` registers an additional local node. Add its URL to `CLUSTER_NODES` and restart the gateway to use it for new writes. Existing segments stay where their manifests say; this is capacity expansion for new writes, not a rebalance. `scripts/test-cluster.sh` exercises a fourth container joining and receiving new segments.
|
||||
|
||||
## Limits and safety
|
||||
|
||||
The cluster retains old and failed-write segments. It has no garbage collection, metadata standby, automated rebalance, private-network TLS, scoped credentials, or physical host verification yet. 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 [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
|
||||
|
||||
|
||||
@@ -16,17 +16,27 @@ The script compiles the source and test programs into `out/classes`, then runs:
|
||||
|
||||
| Test | Checks |
|
||||
| --- | --- |
|
||||
| `StoreTest` | Signature V4 test vector and tampering, local writes and reads, quotas, restart persistence, multipart recovery, legacy reads, locking, and corruption rejection. |
|
||||
| `ConcurrencyTest` | Atomic local overwrites and consistent reads, listings, and deletes during concurrent access. |
|
||||
| `HttpTest` | Signed HTTP requests, object operations, ranges, listing, and single-node multipart uploads. |
|
||||
| `ClusterNodeTest` | Node identity and locking, authenticated segment transfers, checksum rejection, repair authorization, and restart cleanup. |
|
||||
| `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, 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. |
|
||||
| `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. |
|
||||
| `ClusterNodeTest` | Node identity and locking, authenticated segment transfers, checksum rejection, repair authorization, inventory and guarded deletion, and restart cleanup. |
|
||||
| `ClusterTlsTest` | HTTPS node identity and segment roundtrip with a trusted certificate, plus rejection of untrusted and wrong-host certificates. |
|
||||
| `CliTest` | Version, status, verification, and a nonzero result for corrupt data. |
|
||||
| `ClientTest` and `MultipartClientTest` | Java client request signing, capability discovery, error handling, and multipart operations. |
|
||||
|
||||
The script exits nonzero on failure. The test programs use temporary local directories and loopback HTTP ports; they do not use an existing ObjectStore volume.
|
||||
The script exits nonzero on failure. The test programs use temporary local directories and loopback HTTP or HTTPS ports; they do not use an existing ObjectStore volume. `ClusterTlsTest` uses the JDK's `keytool` to create disposable test certificates.
|
||||
|
||||
The encrypted Compose overlays can be checked with `docker compose config` without starting the stack. This verifies their bind mounts and startup settings, not that a host filesystem is actually encrypted. `scripts/prepare-encrypted-storage.sh` must also verify an active dm-crypt-backed mount. A complete deployment drill must unlock it, prepare directories, start with the overlay, write data, restart, restore from backup, and confirm that the stack refuses to start while the mount is unavailable. Do not point that drill at existing data.
|
||||
|
||||
## Disposable metadata routing test
|
||||
|
||||
Run `sh scripts/test-metadata.sh` with Docker Compose. It creates a separate, temporary PostgreSQL container and two in-process storage nodes. The test connects through a two-host JDBC URL whose first host is unavailable, checks writable readiness, then makes the test database read-only and verifies that readiness drops. The script removes its test containers and temporary database afterward. It does not promote a standby or test automatic failover.
|
||||
|
||||
## Disposable Docker cluster tests
|
||||
|
||||
Requires Docker with Compose, Python 3, `curl`, and a free local port 9001. Make a test-only environment file from `.env.cluster.example` and fill in all five blank credentials with test-only values. Keep that file private and out of Git.
|
||||
Requires Docker with Compose, Python 3.9 or newer, `curl`, and a free local port 9001. Make a test-only environment file from `.env.cluster.example` and replace all five credential values with test-only values. Keep that file private and out of Git.
|
||||
|
||||
```sh
|
||||
cp .env.cluster.example /tmp/objectstore-cluster-tests.env
|
||||
@@ -42,19 +52,23 @@ COMPOSE_PROJECT_NAME=objectstore-tests sh scripts/test-cluster.sh /tmp/objectsto
|
||||
Use a fresh, disposable Compose project. The script writes test objects, stops and restarts storage nodes and PostgreSQL, corrupts a replica to exercise repair, and joins a fourth node. It leaves the test stack running. To remove **only that test project's** containers and volumes after review:
|
||||
|
||||
```sh
|
||||
COMPOSE_PROJECT_NAME=objectstore-tests docker compose --env-file /tmp/objectstore-cluster-tests.env -f compose.cluster.yaml --profile expansion down -v
|
||||
COMPOSE_PROJECT_NAME=objectstore-tests docker compose --env-file /tmp/objectstore-cluster-tests.env -f compose.cluster.yaml --profile expansion --profile automatic --profile recovery down -v
|
||||
```
|
||||
|
||||
If port 9001 is occupied, set `CLUSTER_HOST_PORT` to the same free port in both the environment file and the shell before running the script. The script reads that port from the shell; Compose reads it from the file.
|
||||
|
||||
The Docker suite checks signed S3 operations, multi-segment objects, concurrent overwrites, reads and writes with a node stopped, refusal to write without a storage quorum, restart recovery, corrupt-replica repair, metadata unavailability, and placement on a newly joined node. It also checks that containers labeled as one physical host cannot satisfy the normal host quorum. Its local-only override permits the remaining phases to use containers as separate test domains.
|
||||
The Docker suite checks signed capability discovery and S3 operations, bucket creation and deletion, metadata and tags, public-read ACLs and anonymous access, copies, upload checksums, multi-segment objects, concurrent overwrites, multipart staging and listings, versioned reads and delete markers, versioned multipart completion, completion after a gateway restart and node loss, reads and writes with a node stopped, refusal to write without a storage quorum, restart recovery, corrupt-replica repair including staged parts, metadata unavailability, read-only metadata readiness rejection, and placement on a newly joined node. It then checks rebalance to the fourth node, automatic repair, garbage collection dry run and delayed deletion, and a metadata backup restored to a separate PostgreSQL instance while the original database is stopped. A two-host JDBC URL selects that restored writable database. Historical regular and multipart versions are checked after repair and cleanup. It also checks that containers labeled as one physical host cannot satisfy the normal host quorum. Its local-only override permits the remaining phases to use containers as separate test domains.
|
||||
|
||||
`ClusterMigrationTest` is a separate legacy-format fixture and is **not** run by either test script. Do not run its `create` phase against a populated metadata database. The migration procedure is in the [README](README.md#migrating-a-local-cluster).
|
||||
|
||||
## Two-machine durability drill
|
||||
|
||||
The [manual two-machine drill](tests/two-host/README.md) uses machine A and machine B with disposable volumes. It records acknowledged writes during a machine interruption, checks reads and write rejection with either storage machine unavailable, restarts test containers during writes, and restores a metadata backup on machine B. This drill is not part of `scripts/test.sh` because it requires two machines and a coordinated interruption.
|
||||
|
||||
## What these tests do not prove
|
||||
|
||||
- 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 suite does not test 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.
|
||||
@@ -0,0 +1 @@
|
||||
dist/
|
||||
@@ -0,0 +1,66 @@
|
||||
# ObjectStore Java client
|
||||
|
||||
A small, synchronous S3-compatible client built with the JDK alone. It uses path-style URLs and AWS Signature Version 4. The code is covered by the repository's MIT license.
|
||||
|
||||
## Build and test
|
||||
|
||||
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
|
||||
bash client/scripts/test.sh
|
||||
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/`.
|
||||
|
||||
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.
|
||||
|
||||
## Use
|
||||
|
||||
```java
|
||||
import cloud.lunarsky.objectstore.client.ObjectStorageClient;
|
||||
import cloud.lunarsky.objectstore.client.ObjectStorageClientBuilder;
|
||||
import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
try (ObjectStorageClient storage = new ObjectStorageClientBuilder()
|
||||
.endpoint(URI.create("https://storage.example.com"))
|
||||
.region("us-east-1")
|
||||
.credentials(accessKey, secretKey)
|
||||
.build()) {
|
||||
storage.putObject("photos", "hello.txt", "hello".getBytes(StandardCharsets.UTF_8), "text/plain");
|
||||
try (ObjectStorageClient.ObjectData data = storage.getObject("photos", "hello.txt")) {
|
||||
data.body().transferTo(System.out);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`getObject` returns an open stream. Close it even if you do not read every byte. The client requires HTTPS unless you explicitly call `allowInsecureHttp()` for a trusted local endpoint.
|
||||
|
||||
## Scope
|
||||
|
||||
This version implements single-request object PUT, GET, HEAD, DELETE, ListObjectsV2 pages, standard S3 multipart initiation/part upload/list/complete/abort, unfinished-upload listing, bucket/object ACL GET and PUT, and service detection. ACLs are S3 ACL requests, not a calculation of effective permissions from IAM policies or bucket policies. An S3 service with ACLs disabled can reject them; ObjectStore implements a limited ACL subset.
|
||||
|
||||
`getCapabilities()` reads ObjectStore's signed `GET /_objectstore/capabilities` response when available. It reports implemented S3 operation names, service version, storage mode, and configured limits. A listed operation means the service implements it; it does not establish that the current key may perform it or that every AWS option is supported. Older ObjectStore builds fall back to `/health` and leave unverified operations `UNKNOWN`. The response is not cached.
|
||||
|
||||
For a generic S3 endpoint, successful operations on this client are recorded as `SUPPORTED`; all untested operations remain `UNKNOWN`. Call `probeReadOnlyCapabilities(bucket, existingObjectKey)` to opt into safe read probes. An S3 denial or missing object leaves that operation `UNKNOWN`, not `UNSUPPORTED`. The client never infers features from a hostname or vendor header. The older `/health` identity fallback is self-reported, not cryptographic attestation.
|
||||
|
||||
Multipart upload sessions expose their bucket, key, and upload ID so a caller can persist them and inspect already uploaded parts after a restart. `uploadFileParts` sends a file in sequential parts and leaves completion to the caller. If it fails, the upload remains open for retry or explicit abort; keep the returned upload ID and do not change the source file.
|
||||
|
||||
The client does not yet implement presigned URLs, credential providers, automatic retries, region redirects, or streaming uploads of unknown length. A single-request file upload hashes the file before sending it; do not modify the file while the upload runs. The client does not retry writes because a lost response can leave their outcome uncertain.
|
||||
|
||||
## Errors
|
||||
|
||||
- `ObjectStorageException`: an HTTP error, with status, S3 error code, request ID, and a retryability hint.
|
||||
- `TransportException`: connection or I/O failure. A write may already have completed.
|
||||
- `ProtocolException`: an unexpected or malformed successful response.
|
||||
|
||||
The client does not include access keys, secret keys, or response bodies in exception messages.
|
||||
@@ -0,0 +1,37 @@
|
||||
# Examples
|
||||
|
||||
## AWT image manager
|
||||
|
||||

|
||||
|
||||
Cat photo in the screenshot: [IOP Publishing source image](https://ioppublishing.org/wp-content/uploads/2017/03/cat-web-cc0.jpg).
|
||||
|
||||
Run from the ObjectStore repository root with JDK 21 or newer:
|
||||
|
||||
```sh
|
||||
bash client/examples/awt-images/run.sh
|
||||
```
|
||||
|
||||
The example uses only the Java client and the JDK. Enter an S3-compatible endpoint, region, existing bucket, and access keys. Use **Connect** to verify listing access. Drag PNG, JPEG, GIF, or BMP files onto the window, or use **Add images**. Select an object to preview it; use **Download** or **Delete** to manage it. Objects go under the specified key prefix with a short random ID, so uploading the same filename does not silently replace an earlier image. The list loads 100 objects at a time.
|
||||
|
||||
The example does not create a bucket. When launched directly, it keeps credentials in memory and requires explicit opt-in for plain HTTP. Use HTTP only with a trusted test service. Uploads are limited to 64 MiB per file, and previews to 12 MiB. This is a small interoperability test app, not a production asset manager.
|
||||
|
||||
### Local Docker test
|
||||
|
||||
Prerequisites: JDK 21 or newer, Bash, Python 3, `curl`, and a graphical desktop session. Docker must be running and accessible to your user, and `127.0.0.1:9002` must be free for the test container.
|
||||
|
||||
To try the app with a separate ObjectStore service, run:
|
||||
|
||||
```sh
|
||||
bash client/examples/awt-images/run-test.sh
|
||||
```
|
||||
|
||||
The launcher builds its local image if needed, starts a test container on `127.0.0.1:9002`, and opens the app connected to a `photos` bucket. Set `OBJECTSTORE_TEST_IMAGE` to use a different image. Closing the app leaves the container and its dedicated data volume running; run the launcher again to reconnect. Its generated test credentials are stored in the container's Docker configuration.
|
||||
|
||||
When finished, remove only this example's container and volume:
|
||||
|
||||
```sh
|
||||
docker stop objectstore-image-example
|
||||
docker rm objectstore-image-example
|
||||
docker volume rm objectstore-image-example-data
|
||||
```
|
||||
@@ -0,0 +1,508 @@
|
||||
import cloud.lunarsky.objectstore.client.Capabilities;
|
||||
import cloud.lunarsky.objectstore.client.ObjectStorageClient;
|
||||
import cloud.lunarsky.objectstore.client.ObjectStorageClientBuilder;
|
||||
|
||||
import java.awt.BorderLayout;
|
||||
import java.awt.Button;
|
||||
import java.awt.Canvas;
|
||||
import java.awt.Checkbox;
|
||||
import java.awt.Color;
|
||||
import java.awt.Dialog;
|
||||
import java.awt.Dimension;
|
||||
import java.awt.EventQueue;
|
||||
import java.awt.FileDialog;
|
||||
import java.awt.FlowLayout;
|
||||
import java.awt.Font;
|
||||
import java.awt.Frame;
|
||||
import java.awt.Graphics;
|
||||
import java.awt.GridLayout;
|
||||
import java.awt.Label;
|
||||
import java.awt.Panel;
|
||||
import java.awt.TextField;
|
||||
import java.awt.dnd.DnDConstants;
|
||||
import java.awt.dnd.DropTarget;
|
||||
import java.awt.dnd.DropTargetAdapter;
|
||||
import java.awt.dnd.DropTargetDropEvent;
|
||||
import java.awt.datatransfer.DataFlavor;
|
||||
import java.awt.event.WindowAdapter;
|
||||
import java.awt.event.WindowEvent;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import javax.imageio.ImageIO;
|
||||
import javax.imageio.ImageReader;
|
||||
import javax.imageio.stream.ImageInputStream;
|
||||
import javax.imageio.stream.MemoryCacheImageInputStream;
|
||||
|
||||
/** A small, dependency-free image browser for testing an S3-compatible endpoint. */
|
||||
@SuppressWarnings("serial")
|
||||
public final class ImageManager extends Frame {
|
||||
private static final long MAX_UPLOAD = 64L * 1024 * 1024;
|
||||
private static final int MAX_PREVIEW = 12 * 1024 * 1024;
|
||||
private static final Color BACKGROUND = new Color(29, 27, 38);
|
||||
private static final Color FOREGROUND = new Color(231, 223, 240);
|
||||
|
||||
private final TextField endpoint = new TextField(env("S3_ENDPOINT", "http://localhost:9000"));
|
||||
private final TextField region = new TextField(env("S3_REGION", "us-east-1"));
|
||||
private final TextField bucket = new TextField(env("S3_BUCKET", "photos"));
|
||||
private final TextField prefix = new TextField("images/");
|
||||
private final TextField access = new TextField(env("S3_ACCESS_KEY", ""));
|
||||
private final TextField secret = new TextField(env("S3_SECRET_KEY", ""));
|
||||
private final Checkbox allowHttp = new Checkbox("Allow HTTP for trusted tests", null,
|
||||
Boolean.parseBoolean(env("S3_ALLOW_HTTP", "false")));
|
||||
private final java.awt.List images = new java.awt.List(15, false);
|
||||
private final ImageCanvas preview = new ImageCanvas();
|
||||
private final Label status = new Label("Enter a bucket and credentials, then connect. Drop images to upload.");
|
||||
private final Button connectButton = new Button("Connect");
|
||||
private final Button moreButton = new Button("Load more");
|
||||
private final ExecutorService io = Executors.newSingleThreadExecutor(r -> {
|
||||
Thread thread = new Thread(r, "objectstore-image-example");
|
||||
thread.setDaemon(true);
|
||||
return thread;
|
||||
});
|
||||
private final AtomicLong previewRevision = new AtomicLong();
|
||||
private final List<ObjectStorageClient.ObjectEntry> entries = new ArrayList<>();
|
||||
private volatile ObjectStorageClient client;
|
||||
private volatile String activeBucket;
|
||||
private volatile String activePrefix;
|
||||
private String nextToken;
|
||||
|
||||
private ImageManager() {
|
||||
super("ObjectStore image manager");
|
||||
setLayout(new BorderLayout(8, 8));
|
||||
setBackground(BACKGROUND);
|
||||
setForeground(FOREGROUND);
|
||||
setSize(920, 640);
|
||||
setMinimumSize(new Dimension(650, 440));
|
||||
setLocationRelativeTo(null);
|
||||
secret.setEchoChar('\u2022');
|
||||
|
||||
Panel serviceFields = new Panel(new GridLayout(2, 4, 8, 3));
|
||||
serviceFields.add(label("Endpoint"));
|
||||
serviceFields.add(label("Region"));
|
||||
serviceFields.add(label("Bucket"));
|
||||
serviceFields.add(label("Key prefix"));
|
||||
serviceFields.add(endpoint);
|
||||
serviceFields.add(region);
|
||||
serviceFields.add(bucket);
|
||||
serviceFields.add(prefix);
|
||||
Panel credentialFields = new Panel(new GridLayout(2, 2, 8, 3));
|
||||
credentialFields.add(label("Access key"));
|
||||
credentialFields.add(label("Secret key"));
|
||||
credentialFields.add(access);
|
||||
credentialFields.add(secret);
|
||||
Panel connection = new Panel(new BorderLayout(0, 5));
|
||||
connection.add(serviceFields, BorderLayout.NORTH);
|
||||
connection.add(credentialFields, BorderLayout.CENTER);
|
||||
|
||||
Panel actions = new Panel(new FlowLayout(FlowLayout.LEFT, 8, 4));
|
||||
Button upload = new Button("Add images...");
|
||||
Button refresh = new Button("Refresh");
|
||||
Button download = new Button("Download");
|
||||
Button delete = new Button("Delete");
|
||||
actions.add(allowHttp);
|
||||
actions.add(connectButton);
|
||||
actions.add(upload);
|
||||
actions.add(refresh);
|
||||
actions.add(moreButton);
|
||||
actions.add(download);
|
||||
actions.add(delete);
|
||||
moreButton.setEnabled(false);
|
||||
|
||||
Panel top = new Panel(new BorderLayout(0, 5));
|
||||
top.add(connection, BorderLayout.CENTER);
|
||||
top.add(actions, BorderLayout.SOUTH);
|
||||
add(top, BorderLayout.NORTH);
|
||||
|
||||
Panel listing = new Panel(new BorderLayout(0, 5));
|
||||
listing.setPreferredSize(new Dimension(285, 400));
|
||||
listing.add(label("Images in this prefix"), BorderLayout.NORTH);
|
||||
listing.add(images, BorderLayout.CENTER);
|
||||
add(listing, BorderLayout.WEST);
|
||||
add(preview, BorderLayout.CENTER);
|
||||
add(status, BorderLayout.SOUTH);
|
||||
|
||||
connectButton.addActionListener(event -> connect());
|
||||
upload.addActionListener(event -> chooseImages());
|
||||
refresh.addActionListener(event -> loadPage(true));
|
||||
moreButton.addActionListener(event -> loadPage(false));
|
||||
download.addActionListener(event -> downloadSelected());
|
||||
delete.addActionListener(event -> deleteSelected());
|
||||
images.addItemListener(event -> previewSelected());
|
||||
installDropTarget(this);
|
||||
installDropTarget(preview);
|
||||
installDropTarget(images);
|
||||
addWindowListener(new WindowAdapter() {
|
||||
@Override public void windowClosing(WindowEvent event) {
|
||||
io.shutdownNow();
|
||||
ObjectStorageClient previous = client;
|
||||
if (previous != null) Thread.ofVirtual().start(previous::close);
|
||||
dispose();
|
||||
}
|
||||
});
|
||||
if (Boolean.parseBoolean(env("S3_AUTO_CONNECT", "false"))) {
|
||||
EventQueue.invokeLater(this::connect);
|
||||
}
|
||||
}
|
||||
|
||||
private void connect() {
|
||||
String url = endpoint.getText().trim();
|
||||
String location = region.getText().trim();
|
||||
String name = bucket.getText().trim();
|
||||
String folder = normalizePrefix(prefix.getText());
|
||||
String user = access.getText().trim();
|
||||
String password = secret.getText();
|
||||
boolean insecure = allowHttp.getState();
|
||||
connectButton.setEnabled(false);
|
||||
setStatus("Connecting...", false);
|
||||
io.execute(() -> {
|
||||
ObjectStorageClient candidate = null;
|
||||
try {
|
||||
ObjectStorageClientBuilder builder = new ObjectStorageClientBuilder()
|
||||
.endpoint(URI.create(url)).region(location).credentials(user, password)
|
||||
.timeout(Duration.ofSeconds(30));
|
||||
if (insecure) builder.allowInsecureHttp();
|
||||
candidate = builder.build();
|
||||
candidate.listObjects(name, folder, null, 1);
|
||||
ObjectStorageClient previous = client;
|
||||
client = candidate;
|
||||
activeBucket = name;
|
||||
activePrefix = folder;
|
||||
candidate = null;
|
||||
if (previous != null) previous.close();
|
||||
String service = "S3-compatible service";
|
||||
try {
|
||||
Capabilities found = client.getCapabilities();
|
||||
if (found.service() == Capabilities.ServiceKind.OBJECTSTORE) {
|
||||
service = "ObjectStore" + (found.serviceVersion() == null ? "" : " " + found.serviceVersion());
|
||||
}
|
||||
} catch (IOException ignored) {
|
||||
// Listing already established the connection; service detection is optional.
|
||||
}
|
||||
String connectedService = service;
|
||||
EventQueue.invokeLater(() -> {
|
||||
connectButton.setEnabled(true);
|
||||
setStatus("Connected to " + connectedService + ".", false);
|
||||
loadPage(true);
|
||||
});
|
||||
} catch (Exception error) {
|
||||
if (candidate != null) candidate.close();
|
||||
showFailure("Connection failed", error);
|
||||
EventQueue.invokeLater(() -> connectButton.setEnabled(true));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void loadPage(boolean first) {
|
||||
if (client == null) {
|
||||
setStatus("Connect first.", true);
|
||||
return;
|
||||
}
|
||||
if (!first && nextToken == null) return;
|
||||
String token = first ? null : nextToken;
|
||||
moreButton.setEnabled(false);
|
||||
setStatus(first ? "Loading images..." : "Loading more images...", false);
|
||||
io.execute(() -> {
|
||||
try {
|
||||
ObjectStorageClient.ObjectPage page = client.listObjects(activeBucket, activePrefix, token, 100);
|
||||
EventQueue.invokeLater(() -> {
|
||||
if (first) {
|
||||
previewRevision.incrementAndGet();
|
||||
entries.clear();
|
||||
images.removeAll();
|
||||
preview.show(null, "Select an image to preview");
|
||||
}
|
||||
for (ObjectStorageClient.ObjectEntry entry : page.objects()) {
|
||||
if (!isImage(entry.key())) continue;
|
||||
entries.add(entry);
|
||||
String name = entry.key().substring(activePrefix.length());
|
||||
images.add(name + " · " + sizeLabel(entry.size()));
|
||||
}
|
||||
nextToken = page.nextContinuationToken();
|
||||
moreButton.setEnabled(nextToken != null);
|
||||
setStatus(entries.size() + " image(s) loaded" +
|
||||
(nextToken == null ? "." : "; more available."), false);
|
||||
});
|
||||
} catch (Exception error) {
|
||||
showFailure("Could not list images", error);
|
||||
EventQueue.invokeLater(() -> moreButton.setEnabled(token != null));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void chooseImages() {
|
||||
FileDialog picker = new FileDialog(this, "Add images", FileDialog.LOAD);
|
||||
picker.setMultipleMode(true);
|
||||
picker.setVisible(true);
|
||||
java.io.File[] selected = picker.getFiles();
|
||||
if (selected.length > 0) uploadImages(List.of(selected));
|
||||
}
|
||||
|
||||
private void uploadImages(List<java.io.File> files) {
|
||||
if (client == null) {
|
||||
setStatus("Connect first.", true);
|
||||
return;
|
||||
}
|
||||
io.execute(() -> {
|
||||
int uploaded = 0;
|
||||
for (java.io.File file : files) {
|
||||
try {
|
||||
Path path = file.toPath();
|
||||
String name = path.getFileName().toString();
|
||||
String type = contentType(name);
|
||||
if (type == null) throw new IOException("Unsupported image type");
|
||||
if (!Files.isRegularFile(path) || Files.size(path) > MAX_UPLOAD)
|
||||
throw new IOException("Image must be a file of at most 64 MiB");
|
||||
String key = activePrefix + UUID.randomUUID() + "-" + name;
|
||||
client.putObject(activeBucket, key, path, type);
|
||||
uploaded++;
|
||||
int completed = uploaded;
|
||||
EventQueue.invokeLater(() -> setStatus("Uploaded " + completed + " of " + files.size() + ".", false));
|
||||
} catch (Exception error) {
|
||||
showFailure("Could not upload " + file.getName(), error);
|
||||
}
|
||||
}
|
||||
if (uploaded > 0) EventQueue.invokeLater(() -> loadPage(true));
|
||||
});
|
||||
}
|
||||
|
||||
private void previewSelected() {
|
||||
ObjectStorageClient.ObjectEntry entry = selectedEntry();
|
||||
long revision = previewRevision.incrementAndGet();
|
||||
if (entry == null) {
|
||||
preview.show(null, "Select an image to preview");
|
||||
return;
|
||||
}
|
||||
preview.show(null, "Loading preview...");
|
||||
io.execute(() -> {
|
||||
try (ObjectStorageClient.ObjectData data = client.getObject(activeBucket, entry.key())) {
|
||||
if (data.length() > MAX_PREVIEW) throw new IOException("Preview exceeds 12 MiB");
|
||||
byte[] bytes = data.body().readNBytes(MAX_PREVIEW + 1);
|
||||
if (bytes.length > MAX_PREVIEW) throw new IOException("Preview exceeds 12 MiB");
|
||||
BufferedImage image = decodePreview(bytes);
|
||||
EventQueue.invokeLater(() -> {
|
||||
if (previewRevision.get() == revision) preview.show(image, null);
|
||||
});
|
||||
} catch (Exception error) {
|
||||
EventQueue.invokeLater(() -> {
|
||||
if (previewRevision.get() == revision) preview.show(null, "Preview unavailable");
|
||||
});
|
||||
showFailure("Could not preview image", error);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void downloadSelected() {
|
||||
ObjectStorageClient.ObjectEntry entry = selectedEntry();
|
||||
if (entry == null) {
|
||||
setStatus("Select an image first.", true);
|
||||
return;
|
||||
}
|
||||
FileDialog picker = new FileDialog(this, "Save image", FileDialog.SAVE);
|
||||
picker.setFile(Path.of(entry.key()).getFileName().toString());
|
||||
picker.setVisible(true);
|
||||
if (picker.getFile() == null) return;
|
||||
Path destination = Path.of(picker.getDirectory(), picker.getFile());
|
||||
if (Files.exists(destination) && !confirm("Replace this file?", destination.toString())) return;
|
||||
io.execute(() -> {
|
||||
Path temporary = null;
|
||||
try {
|
||||
Path parent = destination.toAbsolutePath().getParent();
|
||||
temporary = Files.createTempFile(parent, ".objectstore-image-", ".part");
|
||||
try (ObjectStorageClient.ObjectData data = client.getObject(activeBucket, entry.key())) {
|
||||
Files.copy(data.body(), temporary, StandardCopyOption.REPLACE_EXISTING);
|
||||
}
|
||||
Files.move(temporary, destination, StandardCopyOption.REPLACE_EXISTING);
|
||||
EventQueue.invokeLater(() -> setStatus("Saved " + destination.getFileName() + ".", false));
|
||||
} catch (Exception error) {
|
||||
showFailure("Download failed", error);
|
||||
} finally {
|
||||
if (temporary != null) {
|
||||
try { Files.deleteIfExists(temporary); } catch (IOException ignored) { }
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void deleteSelected() {
|
||||
ObjectStorageClient.ObjectEntry entry = selectedEntry();
|
||||
if (entry == null) {
|
||||
setStatus("Select an image first.", true);
|
||||
return;
|
||||
}
|
||||
if (!confirm("Delete this image?", entry.key())) return;
|
||||
io.execute(() -> {
|
||||
try {
|
||||
client.deleteObject(activeBucket, entry.key());
|
||||
EventQueue.invokeLater(() -> {
|
||||
previewRevision.incrementAndGet();
|
||||
loadPage(true);
|
||||
});
|
||||
} catch (Exception error) { showFailure("Delete failed", error); }
|
||||
});
|
||||
}
|
||||
|
||||
private ObjectStorageClient.ObjectEntry selectedEntry() {
|
||||
int index = images.getSelectedIndex();
|
||||
return index < 0 || index >= entries.size() ? null : entries.get(index);
|
||||
}
|
||||
|
||||
private void installDropTarget(java.awt.Component target) {
|
||||
new DropTarget(target, DnDConstants.ACTION_COPY, new DropTargetAdapter() {
|
||||
@Override public void drop(DropTargetDropEvent event) {
|
||||
if (!event.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
|
||||
event.rejectDrop();
|
||||
return;
|
||||
}
|
||||
try {
|
||||
event.acceptDrop(DnDConstants.ACTION_COPY);
|
||||
Object value = event.getTransferable().getTransferData(DataFlavor.javaFileListFlavor);
|
||||
List<?> dropped = (List<?>) value;
|
||||
List<java.io.File> files = new ArrayList<>();
|
||||
for (Object item : dropped) {
|
||||
if (item instanceof java.io.File file) files.add(file);
|
||||
}
|
||||
event.dropComplete(true);
|
||||
EventQueue.invokeLater(() -> uploadImages(files));
|
||||
} catch (Exception error) {
|
||||
event.dropComplete(false);
|
||||
showFailure("Drop failed", error);
|
||||
}
|
||||
}
|
||||
}, true);
|
||||
}
|
||||
|
||||
private boolean confirm(String title, String detail) {
|
||||
Dialog dialog = new Dialog(this, title, true);
|
||||
dialog.setLayout(new BorderLayout(12, 12));
|
||||
dialog.add(new Label(detail), BorderLayout.CENTER);
|
||||
Panel buttons = new Panel(new FlowLayout(FlowLayout.RIGHT));
|
||||
boolean[] accepted = { false };
|
||||
Button cancel = new Button("Cancel");
|
||||
Button proceed = new Button("Continue");
|
||||
cancel.addActionListener(event -> dialog.dispose());
|
||||
proceed.addActionListener(event -> {
|
||||
accepted[0] = true;
|
||||
dialog.dispose();
|
||||
});
|
||||
buttons.add(cancel);
|
||||
buttons.add(proceed);
|
||||
dialog.add(buttons, BorderLayout.SOUTH);
|
||||
dialog.setSize(490, 120);
|
||||
dialog.setLocationRelativeTo(this);
|
||||
dialog.setVisible(true);
|
||||
return accepted[0];
|
||||
}
|
||||
|
||||
private void showFailure(String action, Exception error) {
|
||||
EventQueue.invokeLater(() -> setStatus(action + ": " + error.getMessage(), true));
|
||||
}
|
||||
|
||||
private void setStatus(String message, boolean failed) {
|
||||
status.setForeground(failed ? new Color(245, 143, 157) : FOREGROUND);
|
||||
status.setText(message);
|
||||
}
|
||||
|
||||
private static Label label(String text) {
|
||||
return new Label(text);
|
||||
}
|
||||
|
||||
private static String normalizePrefix(String value) {
|
||||
String cleaned = value.trim().replace('\\', '/');
|
||||
while (cleaned.startsWith("/")) cleaned = cleaned.substring(1);
|
||||
return cleaned.isEmpty() || cleaned.endsWith("/") ? cleaned : cleaned + "/";
|
||||
}
|
||||
|
||||
private static String contentType(String name) {
|
||||
String lower = name.toLowerCase(Locale.ROOT);
|
||||
if (lower.endsWith(".png")) return "image/png";
|
||||
if (lower.endsWith(".jpg") || lower.endsWith(".jpeg")) return "image/jpeg";
|
||||
if (lower.endsWith(".gif")) return "image/gif";
|
||||
if (lower.endsWith(".bmp")) return "image/bmp";
|
||||
return null;
|
||||
}
|
||||
|
||||
private static boolean isImage(String name) {
|
||||
return contentType(name) != null;
|
||||
}
|
||||
|
||||
private static String sizeLabel(long bytes) {
|
||||
return bytes < 1024 ? bytes + " B" : String.format(Locale.ROOT, "%.1f KiB", bytes / 1024.0);
|
||||
}
|
||||
|
||||
private static BufferedImage decodePreview(byte[] bytes) throws IOException {
|
||||
try (ImageInputStream stream = new MemoryCacheImageInputStream(new ByteArrayInputStream(bytes))) {
|
||||
var readers = ImageIO.getImageReaders(stream);
|
||||
if (!readers.hasNext()) throw new IOException("Unsupported image data");
|
||||
ImageReader reader = readers.next();
|
||||
try {
|
||||
reader.setInput(stream, true, true);
|
||||
int width = reader.getWidth(0);
|
||||
int height = reader.getHeight(0);
|
||||
if (width < 1 || height < 1 || width > 16000 || height > 16000 ||
|
||||
(long) width * height > 40_000_000)
|
||||
throw new IOException("Image dimensions are too large for preview");
|
||||
int step = Math.max(1, (Math.max(width, height) + 1199) / 1200);
|
||||
var parameters = reader.getDefaultReadParam();
|
||||
parameters.setSourceSubsampling(step, step, 0, 0);
|
||||
return reader.read(0, parameters);
|
||||
} finally { reader.dispose(); }
|
||||
}
|
||||
}
|
||||
|
||||
private static String env(String name, String fallback) {
|
||||
String value = System.getenv(name);
|
||||
return value == null ? fallback : value;
|
||||
}
|
||||
|
||||
@SuppressWarnings("serial")
|
||||
private static final class ImageCanvas extends Canvas {
|
||||
private BufferedImage image;
|
||||
private String message = "Select an image to preview";
|
||||
|
||||
private ImageCanvas() {
|
||||
setBackground(new Color(21, 20, 29));
|
||||
setForeground(FOREGROUND);
|
||||
setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 16));
|
||||
}
|
||||
|
||||
private void show(BufferedImage value, String text) {
|
||||
image = value;
|
||||
message = text;
|
||||
repaint();
|
||||
}
|
||||
|
||||
@Override public void paint(Graphics graphics) {
|
||||
int width = getWidth();
|
||||
int height = getHeight();
|
||||
if (image == null) {
|
||||
graphics.setColor(FOREGROUND);
|
||||
graphics.drawString(message, 20, Math.max(35, height / 2));
|
||||
return;
|
||||
}
|
||||
double scale = Math.min((width - 24.0) / image.getWidth(),
|
||||
(height - 24.0) / image.getHeight());
|
||||
scale = Math.max(0.01, Math.min(scale, 1.0));
|
||||
int drawWidth = (int) Math.round(image.getWidth() * scale);
|
||||
int drawHeight = (int) Math.round(image.getHeight() * scale);
|
||||
graphics.drawImage(image, (width - drawWidth) / 2, (height - drawHeight) / 2,
|
||||
drawWidth, drawHeight, null);
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
EventQueue.invokeLater(() -> new ImageManager().setVisible(true));
|
||||
}
|
||||
}
|
||||
Executable
+51
@@ -0,0 +1,51 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
client_dir="$(cd "$(dirname "$0")/../.." && pwd)"
|
||||
project_dir="$(cd "$client_dir/.." && pwd)"
|
||||
container="objectstore-image-example"
|
||||
volume="objectstore-image-example-data"
|
||||
image="${OBJECTSTORE_TEST_IMAGE:-objectstore-image-example:local}"
|
||||
|
||||
if ! docker container inspect "$container" >/dev/null 2>&1; then
|
||||
if ! docker image inspect "$image" >/dev/null 2>&1; then
|
||||
docker build --tag "$image" "$project_dir"
|
||||
fi
|
||||
export S3_ACCESS_KEY="ImageExampleTest1"
|
||||
export S3_SECRET_KEY="$(python3 -c 'import secrets; print(secrets.token_hex(32))')"
|
||||
docker volume create "$volume" >/dev/null
|
||||
docker run --detach --name "$container" \
|
||||
--publish 127.0.0.1:9002:9000 \
|
||||
--volume "$volume:/data" \
|
||||
--env S3_ACCESS_KEY --env S3_SECRET_KEY \
|
||||
--env S3_BUCKET=photos --env S3_REGION=us-east-1 \
|
||||
--env MAX_OBJECT_BYTES=67108864 --env MAX_TOTAL_BYTES=1073741824 \
|
||||
"$image" >/dev/null
|
||||
else
|
||||
while IFS='=' read -r key value; do
|
||||
case "$key" in
|
||||
S3_ACCESS_KEY) export S3_ACCESS_KEY="$value" ;;
|
||||
S3_SECRET_KEY) export S3_SECRET_KEY="$value" ;;
|
||||
esac
|
||||
done < <(docker inspect --format '{{range .Config.Env}}{{println .}}{{end}}' "$container")
|
||||
if [[ "$(docker inspect --format '{{.State.Running}}' "$container")" != true ]]; then
|
||||
docker start "$container" >/dev/null
|
||||
fi
|
||||
fi
|
||||
|
||||
for attempt in {1..40}; do
|
||||
if curl --silent --fail --output /dev/null http://127.0.0.1:9002/health; then
|
||||
break
|
||||
fi
|
||||
sleep 0.25
|
||||
done
|
||||
if ! curl --silent --fail --output /dev/null http://127.0.0.1:9002/health; then
|
||||
echo "The isolated ObjectStore container did not become healthy; check docker logs $container." >&2
|
||||
exit 1
|
||||
fi
|
||||
export S3_ENDPOINT=http://127.0.0.1:9002
|
||||
export S3_REGION=us-east-1
|
||||
export S3_BUCKET=photos
|
||||
export S3_ALLOW_HTTP=true
|
||||
export S3_AUTO_CONNECT=true
|
||||
exec "$client_dir/examples/awt-images/run.sh"
|
||||
Executable
+11
@@ -0,0 +1,11 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
client_dir="$(cd "$(dirname "$0")/../.." && pwd)"
|
||||
if [[ ! -f "$client_dir/dist/objectstore-client.jar" ]]; then
|
||||
bash "$client_dir/scripts/build.sh"
|
||||
fi
|
||||
classes="$client_dir/dist/examples/awt-images"
|
||||
mkdir -p "$classes"
|
||||
javac --release 21 -cp "$client_dir/dist/objectstore-client.jar" \
|
||||
-d "$classes" "$client_dir/examples/awt-images/ImageManager.java"
|
||||
exec java -cp "$classes:$client_dir/dist/objectstore-client.jar" ImageManager
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 381 KiB |
@@ -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"
|
||||
@@ -0,0 +1,13 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
rm -rf dist/classes
|
||||
mkdir -p dist/classes
|
||||
find src/main/java -name '*.java' -print0 |
|
||||
xargs -0 javac --release 21 -d dist/classes
|
||||
mkdir -p dist/classes/META-INF
|
||||
cp ../LICENSE dist/classes/META-INF/LICENSE
|
||||
jar --create --file dist/objectstore-client.jar -C dist/classes .
|
||||
javadoc --release 21 -quiet -Xdoclint:reference,syntax,html -d dist/javadoc \
|
||||
$(find src/main/java -name '*.java' -print)
|
||||
echo "Built dist/objectstore-client.jar"
|
||||
@@ -0,0 +1,9 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
build_dir="$(mktemp -d)"
|
||||
trap 'rm -rf "$build_dir"' EXIT
|
||||
find src/main/java src/test/java -name '*.java' -print0 |
|
||||
xargs -0 javac --release 21 -d "$build_dir"
|
||||
java -cp "$build_dir" cloud.lunarsky.objectstore.client.ClientTest
|
||||
java -cp "$build_dir" cloud.lunarsky.objectstore.client.MultipartClientTest
|
||||
@@ -0,0 +1,27 @@
|
||||
package cloud.lunarsky.objectstore.client;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
/** A bucket or object ACL. This is not an effective-permissions calculation. */
|
||||
public record AclPolicy(String ownerId, List<Grant> grants) {
|
||||
/** A canonical user or predefined S3 group. */
|
||||
public enum GranteeType { CANONICAL_USER, GROUP }
|
||||
|
||||
/** An S3 ACL permission. */
|
||||
public enum Permission { READ, WRITE, READ_ACP, WRITE_ACP, FULL_CONTROL }
|
||||
|
||||
/** One ACL grant to a canonical user ID or S3 group URI. */
|
||||
public record Grant(GranteeType type, String grantee, Permission permission) {
|
||||
public Grant {
|
||||
Objects.requireNonNull(type, "type");
|
||||
if (grantee == null || grantee.isBlank()) throw new IllegalArgumentException("grantee is required");
|
||||
Objects.requireNonNull(permission, "permission");
|
||||
}
|
||||
}
|
||||
|
||||
public AclPolicy {
|
||||
if (ownerId == null || ownerId.isBlank()) throw new IllegalArgumentException("owner ID is required");
|
||||
grants = List.copyOf(grants);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package cloud.lunarsky.objectstore.client;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
|
||||
/** Reported or observed operation support, separate from the caller's authorization. */
|
||||
public record Capabilities(ServiceKind service, Map<String, Support> operations, Map<String, Long> limits,
|
||||
String serviceVersion, String storageMode, boolean completeOperationInventory) {
|
||||
private static final Set<String> KNOWN_OPERATIONS = Set.of(
|
||||
"ListBuckets", "CreateBucket", "HeadBucket", "DeleteBucket", "ListObjectsV2",
|
||||
"PutObject", "GetObject", "HeadObject", "DeleteObject", "CopyObject",
|
||||
"GetObjectTagging", "PutObjectTagging", "DeleteObjectTagging",
|
||||
"CreateMultipartUpload", "UploadPart", "ListParts", "CompleteMultipartUpload",
|
||||
"AbortMultipartUpload", "ListMultipartUploads", "GetBucketVersioning",
|
||||
"PutBucketVersioning", "ListObjectVersions", "GetBucketAcl", "PutBucketAcl",
|
||||
"GetObjectAcl", "PutObjectAcl");
|
||||
|
||||
/** Identifies a self-reported ObjectStore service or an unrecognized S3-compatible service. */
|
||||
public enum ServiceKind { OBJECTSTORE, UNKNOWN_S3 }
|
||||
|
||||
/** Three-state feature support; a generic S3 server cannot be inferred from its hostname. */
|
||||
public enum Support { SUPPORTED, UNSUPPORTED, UNKNOWN }
|
||||
|
||||
public Capabilities {
|
||||
Objects.requireNonNull(service, "service");
|
||||
operations = Map.copyOf(operations);
|
||||
limits = Map.copyOf(limits);
|
||||
}
|
||||
|
||||
/** Constructs a result without a server manifest or configured limits. */
|
||||
public Capabilities(ServiceKind service, Map<String, Support> operations) {
|
||||
this(service, operations, Map.of(), null, null, false);
|
||||
}
|
||||
|
||||
/** Returns support for a named operation. A missing manifest or denied probe stays UNKNOWN. */
|
||||
public Support support(String operation) {
|
||||
Support observed = operations.get(operation);
|
||||
if (observed != null) return observed;
|
||||
if (completeOperationInventory && KNOWN_OPERATIONS.contains(operation)) return Support.UNSUPPORTED;
|
||||
return Support.UNKNOWN;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
package cloud.lunarsky.objectstore.client;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.CharacterCodingException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
final class Json {
|
||||
private Json() { }
|
||||
|
||||
static Object parse(byte[] bytes) throws ProtocolException {
|
||||
String source;
|
||||
try { source = StandardCharsets.UTF_8.newDecoder().decode(ByteBuffer.wrap(bytes)).toString(); }
|
||||
catch (CharacterCodingException e) { throw new ProtocolException("Capability JSON is not UTF-8", e); }
|
||||
Parser parser = new Parser(source);
|
||||
Object value = parser.value(0);
|
||||
parser.space();
|
||||
if (parser.index != source.length()) throw new ProtocolException("Trailing capability JSON data");
|
||||
return value;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
static Map<String, Object> object(Object value, String name) throws ProtocolException {
|
||||
if (!(value instanceof Map<?, ?>)) throw new ProtocolException(name + " must be an object");
|
||||
return (Map<String, Object>) value;
|
||||
}
|
||||
|
||||
static List<?> array(Object value, String name) throws ProtocolException {
|
||||
if (!(value instanceof List<?> list)) throw new ProtocolException(name + " must be an array");
|
||||
return list;
|
||||
}
|
||||
|
||||
static String string(Object value, String name) throws ProtocolException {
|
||||
if (!(value instanceof String text) || text.isBlank())
|
||||
throw new ProtocolException(name + " must be a nonempty string");
|
||||
return text;
|
||||
}
|
||||
|
||||
static long integer(Object value, String name) throws ProtocolException {
|
||||
if (!(value instanceof BigDecimal number)) throw new ProtocolException(name + " must be an integer");
|
||||
try { return number.longValueExact(); }
|
||||
catch (ArithmeticException e) { throw new ProtocolException(name + " is out of range", e); }
|
||||
}
|
||||
|
||||
private static final class Parser {
|
||||
private final String source;
|
||||
private int index;
|
||||
|
||||
private Parser(String source) { this.source = source; }
|
||||
|
||||
private void space() {
|
||||
while (index < source.length() && (source.charAt(index) == ' ' || source.charAt(index) == '\n' ||
|
||||
source.charAt(index) == '\r' || source.charAt(index) == '\t')) index++;
|
||||
}
|
||||
|
||||
private Object value(int depth) throws ProtocolException {
|
||||
if (depth > 16) throw new ProtocolException("Capability JSON is too deeply nested");
|
||||
space();
|
||||
if (index >= source.length()) throw new ProtocolException("Incomplete capability JSON");
|
||||
return switch (source.charAt(index)) {
|
||||
case '{' -> object(depth + 1);
|
||||
case '[' -> array(depth + 1);
|
||||
case '"' -> string();
|
||||
case 't' -> literal("true", Boolean.TRUE);
|
||||
case 'f' -> literal("false", Boolean.FALSE);
|
||||
case 'n' -> literal("null", null);
|
||||
default -> number();
|
||||
};
|
||||
}
|
||||
|
||||
private Map<String, Object> object(int depth) throws ProtocolException {
|
||||
index++;
|
||||
space();
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
if (take('}')) return result;
|
||||
do {
|
||||
space();
|
||||
if (index >= source.length() || source.charAt(index) != '"')
|
||||
throw new ProtocolException("Capability JSON object key is missing");
|
||||
String key = string();
|
||||
space();
|
||||
require(':');
|
||||
if (result.containsKey(key)) throw new ProtocolException("Duplicate capability JSON key");
|
||||
result.put(key, value(depth));
|
||||
if (result.size() > 256) throw new ProtocolException("Capability JSON object is too large");
|
||||
space();
|
||||
if (take('}')) return result;
|
||||
require(',');
|
||||
} while (true);
|
||||
}
|
||||
|
||||
private List<Object> array(int depth) throws ProtocolException {
|
||||
index++;
|
||||
space();
|
||||
List<Object> result = new ArrayList<>();
|
||||
if (take(']')) return result;
|
||||
do {
|
||||
result.add(value(depth));
|
||||
if (result.size() > 2048) throw new ProtocolException("Capability JSON array is too large");
|
||||
space();
|
||||
if (take(']')) return result;
|
||||
require(',');
|
||||
} while (true);
|
||||
}
|
||||
|
||||
private String string() throws ProtocolException {
|
||||
index++;
|
||||
StringBuilder result = new StringBuilder();
|
||||
while (index < source.length()) {
|
||||
char current = source.charAt(index++);
|
||||
if (current == '"') {
|
||||
for (int i = 0; i < result.length(); i++) {
|
||||
char unit = result.charAt(i);
|
||||
if (Character.isHighSurrogate(unit)) {
|
||||
if (++i >= result.length() || !Character.isLowSurrogate(result.charAt(i)))
|
||||
throw new ProtocolException("Invalid JSON Unicode surrogate");
|
||||
} else if (Character.isLowSurrogate(unit))
|
||||
throw new ProtocolException("Invalid JSON Unicode surrogate");
|
||||
}
|
||||
return result.toString();
|
||||
}
|
||||
if (current < 0x20) throw new ProtocolException("Unescaped control character in JSON string");
|
||||
if (current != '\\') {
|
||||
result.append(current);
|
||||
continue;
|
||||
}
|
||||
if (index >= source.length()) throw new ProtocolException("Incomplete JSON escape");
|
||||
char escaped = source.charAt(index++);
|
||||
switch (escaped) {
|
||||
case '"', '\\', '/' -> result.append(escaped);
|
||||
case 'b' -> result.append('\b');
|
||||
case 'f' -> result.append('\f');
|
||||
case 'n' -> result.append('\n');
|
||||
case 'r' -> result.append('\r');
|
||||
case 't' -> result.append('\t');
|
||||
case 'u' -> {
|
||||
if (index + 4 > source.length()) throw new ProtocolException("Incomplete Unicode escape");
|
||||
int unit = 0;
|
||||
for (int i = 0; i < 4; i++) {
|
||||
int digit = Character.digit(source.charAt(index++), 16);
|
||||
if (digit < 0) throw new ProtocolException("Invalid Unicode escape");
|
||||
unit = unit * 16 + digit;
|
||||
}
|
||||
result.append((char) unit);
|
||||
}
|
||||
default -> throw new ProtocolException("Invalid JSON escape");
|
||||
}
|
||||
}
|
||||
throw new ProtocolException("Unterminated JSON string");
|
||||
}
|
||||
|
||||
private Object literal(String expected, Object value) throws ProtocolException {
|
||||
if (!source.startsWith(expected, index)) throw new ProtocolException("Invalid JSON literal");
|
||||
index += expected.length();
|
||||
return value;
|
||||
}
|
||||
|
||||
private BigDecimal number() throws ProtocolException {
|
||||
int start = index;
|
||||
if (take('-') && index >= source.length()) throw new ProtocolException("Invalid JSON number");
|
||||
integerDigits();
|
||||
if (take('.')) requireDigits("Invalid JSON fraction");
|
||||
if (take('e') || take('E')) {
|
||||
if (!take('+')) take('-');
|
||||
requireDigits("Invalid JSON exponent");
|
||||
}
|
||||
try { return new BigDecimal(source.substring(start, index)); }
|
||||
catch (NumberFormatException e) { throw new ProtocolException("Invalid JSON number", e); }
|
||||
}
|
||||
|
||||
private void integerDigits() throws ProtocolException {
|
||||
if (take('0')) {
|
||||
if (index < source.length() && Character.isDigit(source.charAt(index)))
|
||||
throw new ProtocolException("Invalid JSON number");
|
||||
} else {
|
||||
if (index >= source.length() || source.charAt(index) < '1' || source.charAt(index) > '9')
|
||||
throw new ProtocolException("Invalid JSON number");
|
||||
scanDigits();
|
||||
}
|
||||
}
|
||||
|
||||
private void requireDigits(String message) throws ProtocolException {
|
||||
int first = index;
|
||||
scanDigits();
|
||||
if (first == index) throw new ProtocolException(message);
|
||||
}
|
||||
|
||||
private void scanDigits() {
|
||||
while (index < source.length() && source.charAt(index) >= '0' && source.charAt(index) <= '9') index++;
|
||||
}
|
||||
|
||||
private boolean take(char value) {
|
||||
if (index < source.length() && source.charAt(index) == value) {
|
||||
index++;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private void require(char value) throws ProtocolException {
|
||||
if (!take(value)) throw new ProtocolException("Expected '" + value + "' in capability JSON");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,633 @@
|
||||
package cloud.lunarsky.objectstore.client;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.URI;
|
||||
import java.net.URLDecoder;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import org.w3c.dom.Element;
|
||||
|
||||
/** A synchronous, path-style S3 client. Instances are safe to share between threads. */
|
||||
public final class ObjectStorageClient implements AutoCloseable {
|
||||
private static final int MAX_XML = 4 * 1024 * 1024;
|
||||
private static final int MAX_ERROR = 64 * 1024;
|
||||
private static final String EMPTY_HASH = SigV4.hash(new byte[0]);
|
||||
private final URI endpoint;
|
||||
private final String region;
|
||||
private final String accessKey;
|
||||
private final String secretKey;
|
||||
private final Duration timeout;
|
||||
private final Clock clock;
|
||||
private final HttpClient http;
|
||||
private final Set<String> observedOperations = ConcurrentHashMap.newKeySet();
|
||||
|
||||
ObjectStorageClient(URI endpoint, String region, String accessKey, String secretKey,
|
||||
Duration timeout, Clock clock) {
|
||||
this.endpoint = endpoint;
|
||||
this.region = region;
|
||||
this.accessKey = accessKey;
|
||||
this.secretKey = secretKey;
|
||||
this.timeout = timeout;
|
||||
this.clock = clock;
|
||||
this.http = HttpClient.newBuilder().followRedirects(HttpClient.Redirect.NEVER)
|
||||
.connectTimeout(timeout).version(HttpClient.Version.HTTP_1_1).build();
|
||||
}
|
||||
|
||||
/** Returns one open object stream. The caller must close the returned result. */
|
||||
public ObjectData getObject(String bucket, String key) throws IOException {
|
||||
HttpResponse<InputStream> response = send("GET", objectPath(bucket, key), Map.of(), Map.of(),
|
||||
HttpRequest.BodyPublishers.noBody(), EMPTY_HASH);
|
||||
if (!successful(response)) {
|
||||
try (InputStream ignored = response.body()) { throw failure(response); }
|
||||
}
|
||||
observedOperations.add("GetObject");
|
||||
return new ObjectData(response.body(), length(response), response.headers().firstValue("content-type").orElse(null),
|
||||
response.headers().firstValue("etag").orElse(null));
|
||||
}
|
||||
|
||||
/** Returns object headers without downloading content. */
|
||||
public ObjectMetadata headObject(String bucket, String key) throws IOException {
|
||||
HttpResponse<InputStream> response = send("HEAD", objectPath(bucket, key), Map.of(), Map.of(),
|
||||
HttpRequest.BodyPublishers.noBody(), EMPTY_HASH);
|
||||
try (InputStream ignored = response.body()) {
|
||||
if (!successful(response)) throw failure(response);
|
||||
observedOperations.add("HeadObject");
|
||||
return new ObjectMetadata(length(response), response.headers().firstValue("content-type").orElse(null),
|
||||
response.headers().firstValue("etag").orElse(null));
|
||||
}
|
||||
}
|
||||
|
||||
/** Uploads an immutable byte array as one object. No automatic write retry is performed. */
|
||||
public void putObject(String bucket, String key, byte[] content, String contentType) throws IOException {
|
||||
Objects.requireNonNull(content, "content");
|
||||
put(bucket, key, HttpRequest.BodyPublishers.ofByteArray(content), SigV4.hash(content), contentType);
|
||||
}
|
||||
|
||||
/** Uploads a file. Do not change the file between hashing and completion of the upload. */
|
||||
public void putObject(String bucket, String key, Path file, String contentType) throws IOException {
|
||||
Objects.requireNonNull(file, "file");
|
||||
String hash;
|
||||
try (InputStream input = Files.newInputStream(file)) {
|
||||
MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
||||
byte[] buffer = new byte[65536];
|
||||
for (int count; (count = input.read(buffer)) >= 0; ) digest.update(buffer, 0, count);
|
||||
hash = java.util.HexFormat.of().formatHex(digest.digest());
|
||||
} catch (NoSuchAlgorithmException e) { throw new IllegalStateException(e); }
|
||||
put(bucket, key, HttpRequest.BodyPublishers.ofFile(file), hash, contentType);
|
||||
}
|
||||
|
||||
private void put(String bucket, String key, HttpRequest.BodyPublisher body, String hash,
|
||||
String contentType) throws IOException {
|
||||
Map<String, String> headers = contentType == null ? Map.of() : Map.of("content-type", contentType);
|
||||
HttpResponse<InputStream> response = send("PUT", objectPath(bucket, key), Map.of(), headers, body, hash);
|
||||
try (InputStream ignored = response.body()) {
|
||||
if (!successful(response)) throw failure(response);
|
||||
observedOperations.add("PutObject");
|
||||
}
|
||||
}
|
||||
|
||||
/** Deletes the current object. A versioned backend may create a delete marker. */
|
||||
public void deleteObject(String bucket, String key) throws IOException {
|
||||
HttpResponse<InputStream> response = send("DELETE", objectPath(bucket, key), Map.of(), Map.of(),
|
||||
HttpRequest.BodyPublishers.noBody(), EMPTY_HASH);
|
||||
try (InputStream ignored = response.body()) {
|
||||
if (!successful(response)) throw failure(response);
|
||||
observedOperations.add("DeleteObject");
|
||||
}
|
||||
}
|
||||
|
||||
/** Lists one page of objects using S3 ListObjectsV2. Pass the returned token to get the next page. */
|
||||
public ObjectPage listObjects(String bucket, String prefix, String continuationToken, int maxKeys)
|
||||
throws IOException {
|
||||
if (maxKeys < 1 || maxKeys > 1000) throw new IllegalArgumentException("maxKeys must be 1..1000");
|
||||
Map<String, String> query = new HashMap<>();
|
||||
query.put("list-type", "2");
|
||||
query.put("encoding-type", "url");
|
||||
query.put("max-keys", Integer.toString(maxKeys));
|
||||
if (prefix != null) query.put("prefix", prefix);
|
||||
if (continuationToken != null) query.put("continuation-token", continuationToken);
|
||||
Element root = xml("GET", bucketPath(bucket), query);
|
||||
requireRoot(root, "ListBucketResult");
|
||||
observedOperations.add("ListObjectsV2");
|
||||
List<ObjectEntry> entries = new ArrayList<>();
|
||||
var nodes = Xml.descendants(root, "Contents");
|
||||
for (int i = 0; i < nodes.getLength(); i++) {
|
||||
Element entry = (Element) nodes.item(i);
|
||||
String key = Xml.text(entry, "Key");
|
||||
String size = Xml.text(entry, "Size");
|
||||
if (key == null || size == null) throw new ProtocolException("Incomplete object listing");
|
||||
try {
|
||||
entries.add(new ObjectEntry(URLDecoder.decode(key.replace("+", "%2B"), StandardCharsets.UTF_8),
|
||||
Long.parseLong(size), Xml.text(entry, "ETag")));
|
||||
} catch (IllegalArgumentException e) { throw new ProtocolException("Invalid object listing entry", e); }
|
||||
}
|
||||
String next = Xml.text(root, "NextContinuationToken");
|
||||
if ("true".equalsIgnoreCase(Xml.text(root, "IsTruncated")) && (next == null || next.isEmpty()))
|
||||
throw new ProtocolException("Truncated listing has no continuation token");
|
||||
return new ObjectPage(entries, next);
|
||||
}
|
||||
|
||||
/** Starts a standard S3 multipart upload. Keep the returned upload ID to resume or abort later. */
|
||||
public MultipartUpload createMultipartUpload(String bucket, String key, String contentType) throws IOException {
|
||||
String path = objectPath(bucket, key);
|
||||
Map<String, String> headers = contentType == null ? Map.of() : Map.of("content-type", contentType);
|
||||
HttpResponse<InputStream> response = send("POST", path, Map.of("uploads", ""), headers,
|
||||
HttpRequest.BodyPublishers.noBody(), EMPTY_HASH);
|
||||
Element root = responseXml(response, "InitiateMultipartUploadResult");
|
||||
String id = Xml.text(root, "UploadId");
|
||||
if (id == null || id.isBlank()) throw new ProtocolException("Multipart initiation has no upload ID");
|
||||
observedOperations.add("CreateMultipartUpload");
|
||||
return new MultipartUpload(bucket, key, id);
|
||||
}
|
||||
|
||||
/** Uploads one part. The ETag in the result must be supplied when completing the upload. */
|
||||
public Part uploadPart(MultipartUpload upload, int partNumber, byte[] content) throws IOException {
|
||||
Objects.requireNonNull(upload, "upload");
|
||||
Objects.requireNonNull(content, "content");
|
||||
checkPartNumber(partNumber);
|
||||
HttpResponse<InputStream> response = send("PUT", objectPath(upload.bucket(), upload.key()),
|
||||
Map.of("uploadId", upload.uploadId(), "partNumber", Integer.toString(partNumber)), Map.of(),
|
||||
HttpRequest.BodyPublishers.ofByteArray(content), SigV4.hash(content));
|
||||
try (InputStream ignored = response.body()) {
|
||||
if (!successful(response)) throw failure(response);
|
||||
String etag = response.headers().firstValue("etag").orElse(null);
|
||||
if (etag == null || etag.isBlank()) throw new ProtocolException("Part upload has no ETag");
|
||||
observedOperations.add("UploadPart");
|
||||
return new Part(partNumber, etag, content.length);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Uploads an immutable file as sequential parts without completing it. The caller owns the
|
||||
* upload session and can retry, list parts, complete, or abort it after any failure.
|
||||
* Each part is held in memory once; partSize must be 5 to 128 MiB.
|
||||
*/
|
||||
public List<Part> uploadFileParts(MultipartUpload upload, Path file, int partSize) throws IOException {
|
||||
Objects.requireNonNull(upload, "upload");
|
||||
Objects.requireNonNull(file, "file");
|
||||
if (partSize < 5 * 1024 * 1024 || partSize > 128 * 1024 * 1024)
|
||||
throw new IllegalArgumentException("partSize must be 5..128 MiB");
|
||||
long size = Files.size(file);
|
||||
if (size < 1 || (size + partSize - 1L) / partSize > 10000)
|
||||
throw new IllegalArgumentException("file requires 1..10000 parts");
|
||||
List<Part> parts = new ArrayList<>();
|
||||
try (InputStream input = Files.newInputStream(file)) {
|
||||
long remaining = size;
|
||||
for (int number = 1; remaining > 0; number++) {
|
||||
int length = (int) Math.min(remaining, partSize);
|
||||
byte[] bytes = input.readNBytes(length);
|
||||
if (bytes.length != length) throw new IOException("File changed during multipart upload");
|
||||
parts.add(uploadPart(upload, number, bytes));
|
||||
remaining -= length;
|
||||
}
|
||||
if (input.read() != -1) throw new IOException("File changed during multipart upload");
|
||||
}
|
||||
return List.copyOf(parts);
|
||||
}
|
||||
|
||||
/** Lists one page of uploaded parts for resume or verification. */
|
||||
public PartPage listParts(MultipartUpload upload, int partNumberMarker, int maxParts) throws IOException {
|
||||
Objects.requireNonNull(upload, "upload");
|
||||
if (partNumberMarker < 0 || partNumberMarker > 10000 || maxParts < 1 || maxParts > 1000)
|
||||
throw new IllegalArgumentException("invalid part marker or page size");
|
||||
Element root = xml("GET", objectPath(upload.bucket(), upload.key()),
|
||||
Map.of("uploadId", upload.uploadId(), "part-number-marker", Integer.toString(partNumberMarker),
|
||||
"max-parts", Integer.toString(maxParts)));
|
||||
requireRoot(root, "ListPartsResult");
|
||||
observedOperations.add("ListParts");
|
||||
List<Part> parts = new ArrayList<>();
|
||||
var nodes = Xml.descendants(root, "Part");
|
||||
for (int i = 0; i < nodes.getLength(); i++) {
|
||||
Element entry = (Element) nodes.item(i);
|
||||
try {
|
||||
parts.add(new Part(Integer.parseInt(requiredText(entry, "PartNumber")),
|
||||
requiredText(entry, "ETag"), Long.parseLong(requiredText(entry, "Size"))));
|
||||
} catch (NumberFormatException e) { throw new ProtocolException("Invalid part listing entry", e); }
|
||||
}
|
||||
boolean truncated = Boolean.parseBoolean(Xml.text(root, "IsTruncated"));
|
||||
int next = partNumberMarker;
|
||||
if (truncated) {
|
||||
try { next = Integer.parseInt(requiredText(root, "NextPartNumberMarker")); }
|
||||
catch (NumberFormatException e) { throw new ProtocolException("Invalid next part marker", e); }
|
||||
if (next <= partNumberMarker) throw new ProtocolException("Part listing did not advance");
|
||||
}
|
||||
return new PartPage(parts, truncated, next);
|
||||
}
|
||||
|
||||
/** Completes the upload using the exact part numbers and ETags returned by the service. */
|
||||
public String completeMultipartUpload(MultipartUpload upload, List<Part> parts) throws IOException {
|
||||
Objects.requireNonNull(upload, "upload");
|
||||
Objects.requireNonNull(parts, "parts");
|
||||
if (parts.isEmpty() || parts.size() > 10000) throw new IllegalArgumentException("1..10000 parts required");
|
||||
List<Part> ordered = new ArrayList<>(parts);
|
||||
ordered.sort(Comparator.comparingInt(Part::number));
|
||||
StringBuilder xml = new StringBuilder("<CompleteMultipartUpload>");
|
||||
int previous = 0;
|
||||
for (Part part : ordered) {
|
||||
Objects.requireNonNull(part, "part");
|
||||
checkPartNumber(part.number());
|
||||
if (part.number() == previous) throw new IllegalArgumentException("duplicate part number");
|
||||
previous = part.number();
|
||||
xml.append("<Part><PartNumber>").append(part.number()).append("</PartNumber><ETag>")
|
||||
.append(Xml.escape(part.etag())).append("</ETag></Part>");
|
||||
}
|
||||
byte[] bytes = xml.append("</CompleteMultipartUpload>").toString().getBytes(StandardCharsets.UTF_8);
|
||||
HttpResponse<InputStream> response = send("POST", objectPath(upload.bucket(), upload.key()),
|
||||
Map.of("uploadId", upload.uploadId()), Map.of("content-type", "application/xml"),
|
||||
HttpRequest.BodyPublishers.ofByteArray(bytes), SigV4.hash(bytes));
|
||||
Element root = responseXml(response, "CompleteMultipartUploadResult");
|
||||
observedOperations.add("CompleteMultipartUpload");
|
||||
return requiredText(root, "ETag");
|
||||
}
|
||||
|
||||
/** Aborts an unfinished upload. A completed upload cannot be aborted. */
|
||||
public void abortMultipartUpload(MultipartUpload upload) throws IOException {
|
||||
Objects.requireNonNull(upload, "upload");
|
||||
HttpResponse<InputStream> response = send("DELETE", objectPath(upload.bucket(), upload.key()),
|
||||
Map.of("uploadId", upload.uploadId()), Map.of(), HttpRequest.BodyPublishers.noBody(), EMPTY_HASH);
|
||||
try (InputStream ignored = response.body()) {
|
||||
if (!successful(response)) throw failure(response);
|
||||
observedOperations.add("AbortMultipartUpload");
|
||||
}
|
||||
}
|
||||
|
||||
/** Lists one page of unfinished uploads in a bucket. */
|
||||
public MultipartUploadPage listMultipartUploads(String bucket, String prefix, String keyMarker,
|
||||
String uploadIdMarker, int maxUploads) throws IOException {
|
||||
if (maxUploads < 1 || maxUploads > 1000) throw new IllegalArgumentException("maxUploads must be 1..1000");
|
||||
if (uploadIdMarker != null && keyMarker == null)
|
||||
throw new IllegalArgumentException("upload ID marker requires key marker");
|
||||
Map<String, String> query = new HashMap<>();
|
||||
query.put("uploads", "");
|
||||
query.put("max-uploads", Integer.toString(maxUploads));
|
||||
if (prefix != null) query.put("prefix", prefix);
|
||||
if (keyMarker != null) query.put("key-marker", keyMarker);
|
||||
if (uploadIdMarker != null) query.put("upload-id-marker", uploadIdMarker);
|
||||
Element root = xml("GET", bucketPath(bucket), query);
|
||||
requireRoot(root, "ListMultipartUploadsResult");
|
||||
observedOperations.add("ListMultipartUploads");
|
||||
List<MultipartUpload> uploads = new ArrayList<>();
|
||||
var nodes = Xml.descendants(root, "Upload");
|
||||
for (int i = 0; i < nodes.getLength(); i++) {
|
||||
Element entry = (Element) nodes.item(i);
|
||||
uploads.add(new MultipartUpload(bucket, requiredText(entry, "Key"), requiredText(entry, "UploadId")));
|
||||
}
|
||||
boolean truncated = Boolean.parseBoolean(Xml.text(root, "IsTruncated"));
|
||||
String nextKey = Xml.text(root, "NextKeyMarker");
|
||||
String nextId = Xml.text(root, "NextUploadIdMarker");
|
||||
if (truncated && (nextKey == null || nextId == null))
|
||||
throw new ProtocolException("Truncated upload listing has no markers");
|
||||
return new MultipartUploadPage(uploads, truncated, nextKey, nextId);
|
||||
}
|
||||
|
||||
private static String requiredText(Element element, String name) throws ProtocolException {
|
||||
String value = Xml.text(element, name);
|
||||
if (value == null || value.isBlank()) throw new ProtocolException("Multipart response missing " + name);
|
||||
return value;
|
||||
}
|
||||
|
||||
private static void checkPartNumber(int number) {
|
||||
if (number < 1 || number > 10000) throw new IllegalArgumentException("part number must be 1..10000");
|
||||
}
|
||||
|
||||
/** Gets a bucket ACL. The backend may reject ACL operations when ACLs are disabled. */
|
||||
public AclPolicy getBucketAcl(String bucket) throws IOException {
|
||||
AclPolicy policy = readAcl(bucketPath(bucket));
|
||||
observedOperations.add("GetBucketAcl");
|
||||
return policy;
|
||||
}
|
||||
|
||||
/** Gets an object ACL. This does not calculate permissions from policies or other grants. */
|
||||
public AclPolicy getObjectAcl(String bucket, String key) throws IOException {
|
||||
AclPolicy policy = readAcl(objectPath(bucket, key));
|
||||
observedOperations.add("GetObjectAcl");
|
||||
return policy;
|
||||
}
|
||||
|
||||
/** Replaces a bucket ACL. No automatic retry is performed. */
|
||||
public void putBucketAcl(String bucket, AclPolicy policy) throws IOException {
|
||||
writeAcl(bucketPath(bucket), policy);
|
||||
observedOperations.add("PutBucketAcl");
|
||||
}
|
||||
|
||||
/** Replaces an object ACL. No automatic retry is performed. */
|
||||
public void putObjectAcl(String bucket, String key, AclPolicy policy) throws IOException {
|
||||
writeAcl(objectPath(bucket, key), policy);
|
||||
observedOperations.add("PutObjectAcl");
|
||||
}
|
||||
|
||||
private AclPolicy readAcl(String path) throws IOException {
|
||||
Element root = xml("GET", path, Map.of("acl", ""));
|
||||
requireRoot(root, "AccessControlPolicy");
|
||||
Element owner = Xml.child(root, "Owner");
|
||||
String ownerId = owner == null ? null : Xml.text(owner, "ID");
|
||||
if (ownerId == null || ownerId.isBlank()) throw new ProtocolException("ACL response has no owner ID");
|
||||
List<AclPolicy.Grant> grants = new ArrayList<>();
|
||||
var nodes = Xml.descendants(root, "Grant");
|
||||
for (int i = 0; i < nodes.getLength(); i++) {
|
||||
Element grant = (Element) nodes.item(i);
|
||||
Element grantee = Xml.child(grant, "Grantee");
|
||||
if (grantee == null) throw new ProtocolException("ACL grant has no grantee");
|
||||
String type = grantee.getAttributeNS("http://www.w3.org/2001/XMLSchema-instance", "type");
|
||||
if (type.isEmpty()) type = grantee.getAttribute("xsi:type");
|
||||
AclPolicy.GranteeType kind = switch (type) {
|
||||
case "CanonicalUser" -> AclPolicy.GranteeType.CANONICAL_USER;
|
||||
case "Group" -> AclPolicy.GranteeType.GROUP;
|
||||
default -> throw new ProtocolException("Unsupported ACL grantee type");
|
||||
};
|
||||
String id = Xml.text(grantee, kind == AclPolicy.GranteeType.GROUP ? "URI" : "ID");
|
||||
String permission = Xml.text(grant, "Permission");
|
||||
if (id == null || permission == null) throw new ProtocolException("Incomplete ACL grant");
|
||||
try { grants.add(new AclPolicy.Grant(kind, id, AclPolicy.Permission.valueOf(permission))); }
|
||||
catch (IllegalArgumentException e) { throw new ProtocolException("Unsupported ACL permission", e); }
|
||||
}
|
||||
return new AclPolicy(ownerId, grants);
|
||||
}
|
||||
|
||||
private void writeAcl(String path, AclPolicy policy) throws IOException {
|
||||
Objects.requireNonNull(policy, "policy");
|
||||
StringBuilder xml = new StringBuilder("<AccessControlPolicy xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\" ")
|
||||
.append("xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><Owner><ID>")
|
||||
.append(Xml.escape(policy.ownerId())).append("</ID></Owner><AccessControlList>");
|
||||
for (AclPolicy.Grant grant : policy.grants()) {
|
||||
boolean group = grant.type() == AclPolicy.GranteeType.GROUP;
|
||||
xml.append("<Grant><Grantee xsi:type=\"").append(group ? "Group" : "CanonicalUser")
|
||||
.append("\"><").append(group ? "URI" : "ID").append('>')
|
||||
.append(Xml.escape(grant.grantee())).append("</").append(group ? "URI" : "ID")
|
||||
.append("></Grantee><Permission>").append(grant.permission()).append("</Permission></Grant>");
|
||||
}
|
||||
xml.append("</AccessControlList></AccessControlPolicy>");
|
||||
byte[] bytes = xml.toString().getBytes(StandardCharsets.UTF_8);
|
||||
String md5;
|
||||
try { md5 = Base64.getEncoder().encodeToString(MessageDigest.getInstance("MD5").digest(bytes)); }
|
||||
catch (NoSuchAlgorithmException e) { throw new IllegalStateException(e); }
|
||||
HttpResponse<InputStream> response = send("PUT", path, Map.of("acl", ""),
|
||||
Map.of("content-type", "application/xml", "content-md5", md5),
|
||||
HttpRequest.BodyPublishers.ofByteArray(bytes), SigV4.hash(bytes));
|
||||
try (InputStream ignored = response.body()) {
|
||||
if (!successful(response)) throw failure(response);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads ObjectStore's signed manifest when present. Other S3 endpoints report only operations
|
||||
* observed succeeding on this client. A denied or missing manifest does not imply a feature is
|
||||
* unsupported. Service identity from /health is self-reported, not cryptographic attestation.
|
||||
*/
|
||||
public Capabilities getCapabilities() throws IOException {
|
||||
HttpResponse<InputStream> response = send("GET", "/_objectstore/capabilities", Map.of(), Map.of(),
|
||||
HttpRequest.BodyPublishers.noBody(), EMPTY_HASH);
|
||||
ProtocolException invalidManifest = null;
|
||||
try (InputStream body = response.body()) {
|
||||
if (successful(response)) {
|
||||
try { return withObserved(parseManifest(readLimited(body, 64 * 1024))); }
|
||||
catch (ProtocolException e) { invalidManifest = e; }
|
||||
}
|
||||
}
|
||||
boolean objectStore = probeHealth();
|
||||
if (invalidManifest != null && objectStore) throw invalidManifest;
|
||||
return withObserved(new Capabilities(objectStore ? Capabilities.ServiceKind.OBJECTSTORE :
|
||||
Capabilities.ServiceKind.UNKNOWN_S3, Map.of()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Opts into read-only probes on a known bucket and, optionally, an existing object key.
|
||||
* Successful calls establish support for this principal. S3 error responses leave support
|
||||
* UNKNOWN; transport and malformed-response errors are still reported to the caller.
|
||||
*/
|
||||
public Capabilities probeReadOnlyCapabilities(String bucket, String existingObjectKey) throws IOException {
|
||||
Capabilities base = getCapabilities();
|
||||
probe(base, "ListObjectsV2", () -> listObjects(bucket, null, null, 1));
|
||||
probe(base, "ListMultipartUploads", () -> listMultipartUploads(bucket, null, null, null, 1));
|
||||
probe(base, "GetBucketAcl", () -> getBucketAcl(bucket));
|
||||
if (existingObjectKey != null) {
|
||||
probe(base, "HeadObject", () -> headObject(bucket, existingObjectKey));
|
||||
probe(base, "GetObjectAcl", () -> getObjectAcl(bucket, existingObjectKey));
|
||||
}
|
||||
return withObserved(base);
|
||||
}
|
||||
|
||||
private void probe(Capabilities base, String operation, Probe call) throws IOException {
|
||||
if (base.support(operation) == Capabilities.Support.UNSUPPORTED) return;
|
||||
try { call.run(); }
|
||||
catch (ObjectStorageException ignored) { }
|
||||
}
|
||||
|
||||
@FunctionalInterface private interface Probe { void run() throws IOException; }
|
||||
|
||||
private Capabilities withObserved(Capabilities base) {
|
||||
Map<String, Capabilities.Support> operations = new HashMap<>(base.operations());
|
||||
observedOperations.forEach(name -> operations.put(name, Capabilities.Support.SUPPORTED));
|
||||
return new Capabilities(base.service(), operations, base.limits(), base.serviceVersion(),
|
||||
base.storageMode(), base.completeOperationInventory());
|
||||
}
|
||||
|
||||
private static Capabilities parseManifest(byte[] bytes) throws ProtocolException {
|
||||
Map<String, Object> document = Json.object(Json.parse(bytes), "capability manifest");
|
||||
if (Json.integer(document.get("schemaVersion"), "schemaVersion") != 1 ||
|
||||
!"lunarsky-objectstore".equals(Json.string(document.get("service"), "service")))
|
||||
throw new ProtocolException("Unsupported capability manifest");
|
||||
String version = Json.string(document.get("serviceVersion"), "serviceVersion");
|
||||
String mode = Json.string(document.get("storageMode"), "storageMode");
|
||||
Map<String, Capabilities.Support> operations = new HashMap<>();
|
||||
for (Object value : Json.array(document.get("operations"), "operations")) {
|
||||
String name = Json.string(value, "operation name");
|
||||
if (operations.put(name, Capabilities.Support.SUPPORTED) != null)
|
||||
throw new ProtocolException("Duplicate capability operation");
|
||||
}
|
||||
Map<String, Object> rawLimits = Json.object(document.get("limits"), "limits");
|
||||
Map<String, Long> limits = new HashMap<>();
|
||||
for (var entry : rawLimits.entrySet()) {
|
||||
long value = Json.integer(entry.getValue(), "limit " + entry.getKey());
|
||||
if (value < 0) throw new ProtocolException("Negative capability limit");
|
||||
limits.put(entry.getKey(), value);
|
||||
}
|
||||
for (String required : List.of("maxObjectBytes", "maxTotalBytes", "maxParts"))
|
||||
if (!limits.containsKey(required)) throw new ProtocolException("Missing capability limit " + required);
|
||||
return new Capabilities(Capabilities.ServiceKind.OBJECTSTORE, operations, limits, version, mode, true);
|
||||
}
|
||||
|
||||
private boolean probeHealth() throws IOException {
|
||||
URI uri = URI.create(origin() + "/health");
|
||||
HttpRequest request = HttpRequest.newBuilder(uri).timeout(timeout).GET().build();
|
||||
HttpResponse<InputStream> response = execute(request);
|
||||
try (InputStream body = response.body()) {
|
||||
if (response.statusCode() != 200) return false;
|
||||
String value = new String(readLimited(body, 1024), StandardCharsets.UTF_8);
|
||||
return value.matches("(?s)\\s*\\{\\s*\"status\"\\s*:\\s*\"ok\"\\s*,\\s*\"service\"\\s*:\\s*\"lunarsky-objectstore\"\\s*}\\s*");
|
||||
}
|
||||
}
|
||||
|
||||
private Element xml(String method, String path, Map<String, String> query) throws IOException {
|
||||
HttpResponse<InputStream> response = send(method, path, query, Map.of(),
|
||||
HttpRequest.BodyPublishers.noBody(), EMPTY_HASH);
|
||||
return responseXml(response, null);
|
||||
}
|
||||
|
||||
private static Element responseXml(HttpResponse<InputStream> response, String expectedRoot) throws IOException {
|
||||
try (InputStream body = response.body()) {
|
||||
if (!successful(response)) throw failure(response);
|
||||
Element root = Xml.parse(readLimited(body, MAX_XML)).getDocumentElement();
|
||||
if ("Error".equals(root.getLocalName())) {
|
||||
String code = Xml.text(root, "Code");
|
||||
throw new ObjectStorageException(response.statusCode(), code,
|
||||
response.headers().firstValue("x-amz-request-id").orElse(null));
|
||||
}
|
||||
if (expectedRoot != null) requireRoot(root, expectedRoot);
|
||||
return root;
|
||||
}
|
||||
}
|
||||
|
||||
private HttpResponse<InputStream> send(String method, String path, Map<String, String> query,
|
||||
Map<String, String> extra, HttpRequest.BodyPublisher body,
|
||||
String payloadHash) throws IOException {
|
||||
String queryString = SigV4.query(query);
|
||||
URI uri = URI.create(origin() + path + (queryString.isEmpty() ? "" : "?" + queryString));
|
||||
Instant now = clock.instant();
|
||||
Map<String, String> headers = new HashMap<>(extra);
|
||||
headers.put("host", uri.getRawAuthority().toLowerCase(Locale.ROOT));
|
||||
headers.put("x-amz-date", SigV4.timestamp(now));
|
||||
headers.put("x-amz-content-sha256", payloadHash);
|
||||
String authorization = SigV4.authorization(method, uri, headers, payloadHash, now,
|
||||
region, accessKey, secretKey);
|
||||
HttpRequest.Builder request = HttpRequest.newBuilder(uri).timeout(timeout);
|
||||
headers.forEach((name, value) -> {
|
||||
if (!"host".equals(name)) request.header(name, value);
|
||||
});
|
||||
request.header("Authorization", authorization);
|
||||
return execute(request.method(method, body).build());
|
||||
}
|
||||
|
||||
private HttpResponse<InputStream> execute(HttpRequest request) throws IOException {
|
||||
try { return http.send(request, HttpResponse.BodyHandlers.ofInputStream()); }
|
||||
catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new IOException("Storage request interrupted", e);
|
||||
} catch (IOException e) { throw new TransportException(e); }
|
||||
}
|
||||
|
||||
private static boolean successful(HttpResponse<?> response) {
|
||||
return response.statusCode() >= 200 && response.statusCode() < 300;
|
||||
}
|
||||
|
||||
private static ObjectStorageException failure(HttpResponse<InputStream> response) throws IOException {
|
||||
String code = null;
|
||||
String requestId = response.headers().firstValue("x-amz-request-id").orElse(null);
|
||||
try {
|
||||
byte[] bytes = readLimited(response.body(), MAX_ERROR);
|
||||
if (bytes.length > 0) {
|
||||
Element root = Xml.parse(bytes).getDocumentElement();
|
||||
if ("Error".equals(root.getLocalName())) {
|
||||
code = Xml.text(root, "Code");
|
||||
if (requestId == null) requestId = Xml.text(root, "RequestId");
|
||||
}
|
||||
}
|
||||
} catch (IOException ignored) {
|
||||
}
|
||||
return new ObjectStorageException(response.statusCode(), code, requestId);
|
||||
}
|
||||
|
||||
private static byte[] readLimited(InputStream stream, int limit) throws IOException {
|
||||
byte[] bytes = stream.readNBytes(limit + 1);
|
||||
if (bytes.length > limit) throw new ProtocolException("Storage response exceeds size limit");
|
||||
return bytes;
|
||||
}
|
||||
|
||||
private static long length(HttpResponse<?> response) {
|
||||
return response.headers().firstValueAsLong("content-length").orElse(-1);
|
||||
}
|
||||
|
||||
private static void requireRoot(Element root, String name) throws IOException {
|
||||
if (!name.equals(root.getLocalName())) throw new ProtocolException("Unexpected storage XML response");
|
||||
}
|
||||
|
||||
private String origin() {
|
||||
return endpoint.getScheme() + "://" + endpoint.getRawAuthority();
|
||||
}
|
||||
|
||||
private static String bucketPath(String bucket) {
|
||||
validateBucket(bucket);
|
||||
return "/" + SigV4.encode(bucket, false);
|
||||
}
|
||||
|
||||
private static String objectPath(String bucket, String key) {
|
||||
if (key == null || key.isEmpty() || key.indexOf('\0') >= 0 ||
|
||||
key.getBytes(StandardCharsets.UTF_8).length > 1024)
|
||||
throw new IllegalArgumentException("object key must be 1..1024 UTF-8 bytes without NUL");
|
||||
return bucketPath(bucket) + "/" + SigV4.encode(key, true);
|
||||
}
|
||||
|
||||
private static void validateBucket(String bucket) {
|
||||
if (bucket == null || !bucket.matches("[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]"))
|
||||
throw new IllegalArgumentException("bucket must be a 3..63 character DNS-style name");
|
||||
}
|
||||
|
||||
/** Closes the underlying HTTP client. Do not use this instance afterward. */
|
||||
@Override public void close() { http.close(); }
|
||||
|
||||
/** An open response stream and selected object headers. Close this result after reading. */
|
||||
public record ObjectData(InputStream body, long length, String contentType, String etag)
|
||||
implements AutoCloseable {
|
||||
@Override public void close() throws IOException { body.close(); }
|
||||
}
|
||||
|
||||
/** Headers returned by a HEAD request. A negative length means it was not supplied. */
|
||||
public record ObjectMetadata(long length, String contentType, String etag) { }
|
||||
|
||||
/** A listed object. */
|
||||
public record ObjectEntry(String key, long size, String etag) { }
|
||||
|
||||
/** One listing page. A null next token means no next page was reported. */
|
||||
public record ObjectPage(List<ObjectEntry> objects, String nextContinuationToken) {
|
||||
public ObjectPage { objects = List.copyOf(objects); }
|
||||
}
|
||||
|
||||
/** An unfinished multipart upload. Persist all three fields if resuming in a later process. */
|
||||
public record MultipartUpload(String bucket, String key, String uploadId) {
|
||||
public MultipartUpload {
|
||||
validateBucket(bucket);
|
||||
if (key == null || key.isEmpty()) throw new IllegalArgumentException("key is required");
|
||||
if (uploadId == null || uploadId.isBlank()) throw new IllegalArgumentException("upload ID is required");
|
||||
}
|
||||
}
|
||||
|
||||
/** A successfully uploaded part, including the service-provided ETag. */
|
||||
public record Part(int number, String etag, long size) {
|
||||
public Part {
|
||||
checkPartNumber(number);
|
||||
if (etag == null || etag.isBlank()) throw new IllegalArgumentException("ETag is required");
|
||||
if (size < 0) throw new IllegalArgumentException("part size must not be negative");
|
||||
}
|
||||
}
|
||||
|
||||
/** A page of uploaded parts. Pass nextPartNumberMarker to the next call when truncated. */
|
||||
public record PartPage(List<Part> parts, boolean truncated, int nextPartNumberMarker) {
|
||||
public PartPage { parts = List.copyOf(parts); }
|
||||
}
|
||||
|
||||
/** A page of unfinished uploads. Pass both next markers to the next call when truncated. */
|
||||
public record MultipartUploadPage(List<MultipartUpload> uploads, boolean truncated,
|
||||
String nextKeyMarker, String nextUploadIdMarker) {
|
||||
public MultipartUploadPage { uploads = List.copyOf(uploads); }
|
||||
}
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
package cloud.lunarsky.objectstore.client;
|
||||
|
||||
import java.net.URI;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.util.Objects;
|
||||
|
||||
/** Configures a path-style, Signature V4 S3 client without third-party dependencies. */
|
||||
public final class ObjectStorageClientBuilder {
|
||||
private URI endpoint;
|
||||
private String region = "us-east-1";
|
||||
private String accessKey;
|
||||
private String secretKey;
|
||||
private Duration timeout = Duration.ofSeconds(30);
|
||||
private boolean allowInsecureHttp;
|
||||
|
||||
/** Sets the service root, for example {@code https://storage.example.com}. */
|
||||
public ObjectStorageClientBuilder endpoint(URI value) {
|
||||
endpoint = Objects.requireNonNull(value, "endpoint");
|
||||
return this;
|
||||
}
|
||||
|
||||
/** Sets the Signature V4 region. The default is {@code us-east-1}. */
|
||||
public ObjectStorageClientBuilder region(String value) {
|
||||
region = requireText(value, "region");
|
||||
return this;
|
||||
}
|
||||
|
||||
/** Sets credentials used only in request signatures. Keep them out of logs. */
|
||||
public ObjectStorageClientBuilder credentials(String access, String secret) {
|
||||
accessKey = requireText(access, "access key");
|
||||
secretKey = requireText(secret, "secret key");
|
||||
return this;
|
||||
}
|
||||
|
||||
/** Sets the per-request timeout. */
|
||||
public ObjectStorageClientBuilder timeout(Duration value) {
|
||||
if (Objects.requireNonNull(value, "timeout").isNegative() || value.isZero())
|
||||
throw new IllegalArgumentException("timeout must be positive");
|
||||
timeout = value;
|
||||
return this;
|
||||
}
|
||||
|
||||
/** Allows plain HTTP for a trusted local test endpoint. HTTPS is required by default. */
|
||||
public ObjectStorageClientBuilder allowInsecureHttp() {
|
||||
allowInsecureHttp = true;
|
||||
return this;
|
||||
}
|
||||
|
||||
/** Builds an independent client. */
|
||||
public ObjectStorageClient build() {
|
||||
if (endpoint == null) throw new IllegalStateException("endpoint is required");
|
||||
if (accessKey == null || secretKey == null) throw new IllegalStateException("credentials are required");
|
||||
if (!region.matches("[a-z0-9-]+")) throw new IllegalArgumentException("invalid region");
|
||||
if (!accessKey.matches("[A-Za-z0-9_+=./@-]+")) throw new IllegalArgumentException("invalid access key");
|
||||
String scheme = endpoint.getScheme();
|
||||
if (!"https".equalsIgnoreCase(scheme) && !(allowInsecureHttp && "http".equalsIgnoreCase(scheme)))
|
||||
throw new IllegalArgumentException("HTTPS endpoint required unless insecure HTTP is explicitly allowed");
|
||||
if (endpoint.getHost() == null || endpoint.getUserInfo() != null || endpoint.getRawQuery() != null ||
|
||||
endpoint.getRawFragment() != null || !(endpoint.getRawPath() == null || endpoint.getRawPath().isEmpty() ||
|
||||
"/".equals(endpoint.getRawPath())))
|
||||
throw new IllegalArgumentException("endpoint must be an origin without path, query, fragment, or user info");
|
||||
return new ObjectStorageClient(endpoint, region, accessKey, secretKey, timeout, Clock.systemUTC());
|
||||
}
|
||||
|
||||
private static String requireText(String value, String name) {
|
||||
if (value == null || value.isBlank()) throw new IllegalArgumentException(name + " is required");
|
||||
return value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package cloud.lunarsky.objectstore.client;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
/** An S3 error response with stable fields for callers to inspect. */
|
||||
public final class ObjectStorageException extends IOException {
|
||||
private final int statusCode;
|
||||
private final String errorCode;
|
||||
private final String requestId;
|
||||
|
||||
ObjectStorageException(int statusCode, String errorCode, String requestId) {
|
||||
super("Storage request failed: HTTP " + statusCode + (errorCode == null ? "" : " (" + errorCode + ")"));
|
||||
this.statusCode = statusCode;
|
||||
this.errorCode = errorCode;
|
||||
this.requestId = requestId;
|
||||
}
|
||||
|
||||
/** Returns the HTTP status. */
|
||||
public int statusCode() { return statusCode; }
|
||||
|
||||
/** Returns the S3 error code, or {@code null} if the server supplied none. */
|
||||
public String errorCode() { return errorCode; }
|
||||
|
||||
/** Returns the request ID, or {@code null}. */
|
||||
public String requestId() { return requestId; }
|
||||
|
||||
/** Returns whether retry might help. A failed write may already have reached the server. */
|
||||
public boolean retryable() { return statusCode == 429 || statusCode == 500 || statusCode == 502 ||
|
||||
statusCode == 503 || statusCode == 504; }
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package cloud.lunarsky.objectstore.client;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
/** A successful HTTP response that does not match the expected storage protocol. */
|
||||
public final class ProtocolException extends IOException {
|
||||
ProtocolException(String message) { super(message); }
|
||||
ProtocolException(String message, Throwable cause) { super(message, cause); }
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package cloud.lunarsky.objectstore.client;
|
||||
|
||||
import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
|
||||
final class SigV4 {
|
||||
private static final DateTimeFormatter DATE = DateTimeFormatter.ofPattern("yyyyMMdd", Locale.ROOT)
|
||||
.withZone(ZoneOffset.UTC);
|
||||
private static final DateTimeFormatter TIME = DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'", Locale.ROOT)
|
||||
.withZone(ZoneOffset.UTC);
|
||||
|
||||
private SigV4() { }
|
||||
|
||||
static String hash(byte[] bytes) {
|
||||
try { return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); }
|
||||
catch (NoSuchAlgorithmException e) { throw new IllegalStateException(e); }
|
||||
}
|
||||
|
||||
static String encode(String text, boolean keepSlash) {
|
||||
StringBuilder result = new StringBuilder();
|
||||
for (byte value : text.getBytes(StandardCharsets.UTF_8)) {
|
||||
int b = value & 0xff;
|
||||
if (b >= 'A' && b <= 'Z' || b >= 'a' && b <= 'z' || b >= '0' && b <= '9' ||
|
||||
b == '-' || b == '_' || b == '.' || b == '~' || keepSlash && b == '/') result.append((char) b);
|
||||
else result.append('%').append(Character.toUpperCase(Character.forDigit(b >>> 4, 16)))
|
||||
.append(Character.toUpperCase(Character.forDigit(b & 15, 16)));
|
||||
}
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
static String query(Map<String, String> values) {
|
||||
List<String> entries = new ArrayList<>();
|
||||
values.forEach((key, value) -> entries.add(encode(key, false) + "=" + encode(value, false)));
|
||||
entries.sort(String::compareTo);
|
||||
return String.join("&", entries);
|
||||
}
|
||||
|
||||
static String authorization(String method, URI uri, Map<String, String> headers, String payloadHash,
|
||||
Instant now, String region, String accessKey, String secretKey) {
|
||||
TreeMap<String, String> signed = new TreeMap<>();
|
||||
headers.forEach((name, value) -> signed.put(name.toLowerCase(Locale.ROOT),
|
||||
value.trim().replaceAll("\\s+", " ")));
|
||||
String names = String.join(";", signed.keySet());
|
||||
StringBuilder canonicalHeaders = new StringBuilder();
|
||||
signed.forEach((name, value) -> canonicalHeaders.append(name).append(':').append(value).append('\n'));
|
||||
String canonical = method + '\n' + uri.getRawPath() + '\n' +
|
||||
(uri.getRawQuery() == null ? "" : uri.getRawQuery()) + '\n' + canonicalHeaders + '\n' +
|
||||
names + '\n' + payloadHash;
|
||||
String day = DATE.format(now);
|
||||
String scope = day + '/' + region + "/s3/aws4_request";
|
||||
String toSign = "AWS4-HMAC-SHA256\n" + TIME.format(now) + '\n' + scope + '\n' +
|
||||
hash(canonical.getBytes(StandardCharsets.UTF_8));
|
||||
byte[] key = hmac(("AWS4" + secretKey).getBytes(StandardCharsets.UTF_8), day);
|
||||
key = hmac(key, region);
|
||||
key = hmac(key, "s3");
|
||||
key = hmac(key, "aws4_request");
|
||||
return "AWS4-HMAC-SHA256 Credential=" + accessKey + '/' + scope + ",SignedHeaders=" + names +
|
||||
",Signature=" + HexFormat.of().formatHex(hmac(key, toSign));
|
||||
}
|
||||
|
||||
private static byte[] hmac(byte[] key, String value) {
|
||||
try {
|
||||
Mac mac = Mac.getInstance("HmacSHA256");
|
||||
mac.init(new SecretKeySpec(key, "HmacSHA256"));
|
||||
return mac.doFinal(value.getBytes(StandardCharsets.UTF_8));
|
||||
} catch (Exception e) { throw new IllegalStateException("HMAC-SHA256 unavailable", e); }
|
||||
}
|
||||
|
||||
static String timestamp(Instant now) { return TIME.format(now); }
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package cloud.lunarsky.objectstore.client;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
/** A connection or I/O failure. A write may have completed before this was observed. */
|
||||
public final class TransportException extends IOException {
|
||||
TransportException(IOException cause) { super("Storage transport failed", cause); }
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package cloud.lunarsky.objectstore.client;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import javax.xml.XMLConstants;
|
||||
import javax.xml.parsers.DocumentBuilderFactory;
|
||||
import javax.xml.parsers.ParserConfigurationException;
|
||||
import org.w3c.dom.Document;
|
||||
import org.w3c.dom.Element;
|
||||
import org.w3c.dom.Node;
|
||||
import org.w3c.dom.NodeList;
|
||||
import org.xml.sax.SAXException;
|
||||
|
||||
final class Xml {
|
||||
private Xml() { }
|
||||
|
||||
static Document parse(byte[] bytes) throws IOException {
|
||||
try {
|
||||
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
|
||||
factory.setNamespaceAware(true);
|
||||
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
|
||||
factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
|
||||
factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
|
||||
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
|
||||
factory.setXIncludeAware(false);
|
||||
factory.setExpandEntityReferences(false);
|
||||
factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
|
||||
factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");
|
||||
return factory.newDocumentBuilder().parse(new ByteArrayInputStream(bytes));
|
||||
} catch (ParserConfigurationException | SAXException | IllegalArgumentException e) {
|
||||
throw new ProtocolException("Malformed or unsafe XML response", e);
|
||||
}
|
||||
}
|
||||
|
||||
static Element child(Element element, String name) {
|
||||
for (Node node = element.getFirstChild(); node != null; node = node.getNextSibling())
|
||||
if (node instanceof Element found && name.equals(found.getLocalName())) return found;
|
||||
return null;
|
||||
}
|
||||
|
||||
static String text(Element element, String name) {
|
||||
Element found = child(element, name);
|
||||
return found == null ? null : found.getTextContent();
|
||||
}
|
||||
|
||||
static NodeList descendants(Element element, String name) {
|
||||
return element.getElementsByTagNameNS("*", name);
|
||||
}
|
||||
|
||||
static String escape(String text) {
|
||||
return text.replace("&", "&").replace("<", "<").replace(">", ">")
|
||||
.replace("\"", """).replace("'", "'");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
package cloud.lunarsky.objectstore.client;
|
||||
|
||||
import com.sun.net.httpserver.HttpExchange;
|
||||
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.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
public final class ClientTest {
|
||||
private static final String S3_NS = "http://s3.amazonaws.com/doc/2006-03-01/";
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
signingVector();
|
||||
protocol();
|
||||
System.out.println("Client tests passed");
|
||||
}
|
||||
|
||||
private static void signingVector() {
|
||||
URI uri = URI.create("https://examplebucket.s3.amazonaws.com/test.txt");
|
||||
String empty = SigV4.hash(new byte[0]);
|
||||
String actual = SigV4.authorization("GET", uri, Map.of(
|
||||
"host", "examplebucket.s3.amazonaws.com", "range", "bytes=0-9",
|
||||
"x-amz-content-sha256", empty, "x-amz-date", "20130524T000000Z"), empty,
|
||||
Instant.parse("2013-05-24T00:00:00Z"), "us-east-1", "AKIAIOSFODNN7EXAMPLE",
|
||||
"wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY");
|
||||
check(actual.endsWith("Signature=f0e8bdb87c964420e857bd35b5d6ed310bd44f0170aba48dd91039c6036bdb41"),
|
||||
"AWS Signature V4 vector");
|
||||
check("a=%20&z=%2F".equals(SigV4.query(Map.of("z", "/", "a", " "))), "query encoding");
|
||||
}
|
||||
|
||||
private static void protocol() throws Exception {
|
||||
AtomicReference<String> observedHash = new AtomicReference<>();
|
||||
AtomicReference<String> observedAcl = new AtomicReference<>();
|
||||
AtomicReference<String> manifest = new AtomicReference<>();
|
||||
AtomicInteger manifestStatus = new AtomicInteger(200);
|
||||
AtomicBoolean health = new AtomicBoolean(true);
|
||||
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
|
||||
server.createContext("/", exchange -> {
|
||||
try { handle(exchange, observedHash, observedAcl, manifest, manifestStatus, health); }
|
||||
finally { exchange.close(); }
|
||||
});
|
||||
server.start();
|
||||
try (ObjectStorageClient client = new ObjectStorageClientBuilder()
|
||||
.endpoint(URI.create("http://127.0.0.1:" + server.getAddress().getPort()))
|
||||
.allowInsecureHttp().credentials("test-key", "test-secret").build()) {
|
||||
client.putObject("mybucket", "hello world.txt", "hello".getBytes(StandardCharsets.UTF_8), "text/plain");
|
||||
check(SigV4.hash("hello".getBytes(StandardCharsets.UTF_8)).equals(observedHash.get()), "payload hash");
|
||||
try (ObjectStorageClient.ObjectData data = client.getObject("mybucket", "hello world.txt")) {
|
||||
check("hello".equals(new String(data.body().readAllBytes(), StandardCharsets.UTF_8)), "GET body");
|
||||
}
|
||||
check("text/plain".equals(client.headObject("mybucket", "hello world.txt").contentType()),
|
||||
"HEAD content type");
|
||||
var page = client.listObjects("mybucket", "hello", null, 10);
|
||||
check(page.objects().size() == 1 && "hello world.txt".equals(page.objects().getFirst().key()),
|
||||
"list object key");
|
||||
check("next-token".equals(page.nextContinuationToken()), "list continuation");
|
||||
AclPolicy policy = client.getBucketAcl("mybucket");
|
||||
check(policy.grants().size() == 1 && policy.grants().getFirst().permission() ==
|
||||
AclPolicy.Permission.FULL_CONTROL, "GET ACL");
|
||||
client.putObjectAcl("mybucket", "hello world.txt", new AclPolicy("owner-id", List.of(
|
||||
new AclPolicy.Grant(AclPolicy.GranteeType.GROUP,
|
||||
"http://acs.amazonaws.com/groups/global/AllUsers", AclPolicy.Permission.READ))));
|
||||
check(observedAcl.get().contains("<Permission>READ</Permission>"), "PUT ACL");
|
||||
check(client.getCapabilities().service() == Capabilities.ServiceKind.OBJECTSTORE, "service discovery");
|
||||
check(client.getCapabilities().support("versioning") == Capabilities.Support.UNKNOWN,
|
||||
"unknown support remains unknown");
|
||||
manifest.set("{\"schemaVersion\":1,\"service\":\"lunarsky-objectstore\"," +
|
||||
"\"serviceVersion\":\"0.0.5\",\"storageMode\":\"disk\"," +
|
||||
"\"operations\":[\"PutObject\",\"ListParts\"]," +
|
||||
"\"limits\":{\"maxObjectBytes\":1024,\"maxTotalBytes\":4096,\"maxParts\":10000}}");
|
||||
var capabilities = client.getCapabilities();
|
||||
check(capabilities.service() == Capabilities.ServiceKind.OBJECTSTORE &&
|
||||
capabilities.support("ListParts") == Capabilities.Support.SUPPORTED &&
|
||||
capabilities.support("PutBucketAcl") == Capabilities.Support.UNSUPPORTED &&
|
||||
capabilities.limits().get("maxParts") == 10000 &&
|
||||
"0.0.5".equals(capabilities.serviceVersion()), "signed manifest");
|
||||
manifest.set("{\"schemaVersion\":1,\"schemaVersion\":1}");
|
||||
try {
|
||||
client.getCapabilities();
|
||||
throw new AssertionError("Expected malformed manifest");
|
||||
} catch (ProtocolException expected) { }
|
||||
health.set(false);
|
||||
check(client.getCapabilities().service() == Capabilities.ServiceKind.UNKNOWN_S3,
|
||||
"generic S3 with unrelated matching path");
|
||||
manifestStatus.set(503);
|
||||
check(client.getCapabilities().support("CopyObject") == Capabilities.Support.UNKNOWN,
|
||||
"ambiguous manifest failure stays unknown");
|
||||
manifestStatus.set(200);
|
||||
manifest.set(null);
|
||||
check(client.getCapabilities().service() == Capabilities.ServiceKind.UNKNOWN_S3, "generic S3 fallback");
|
||||
check(client.getCapabilities().support("PutObject") == Capabilities.Support.SUPPORTED &&
|
||||
client.getCapabilities().support("CopyObject") == Capabilities.Support.UNKNOWN,
|
||||
"generic S3 observed support");
|
||||
capabilities = client.probeReadOnlyCapabilities("mybucket", "hello world.txt");
|
||||
check(capabilities.support("ListMultipartUploads") == Capabilities.Support.UNKNOWN &&
|
||||
capabilities.support("ListObjectsV2") == Capabilities.Support.SUPPORTED,
|
||||
"denied generic probe remains unknown");
|
||||
client.deleteObject("mybucket", "hello world.txt");
|
||||
try {
|
||||
client.getObject("mybucket", "denied");
|
||||
throw new AssertionError("Expected AccessDenied");
|
||||
} catch (ObjectStorageException error) {
|
||||
check(error.statusCode() == 403 && "AccessDenied".equals(error.errorCode()) &&
|
||||
"request-123".equals(error.requestId()), "typed S3 error");
|
||||
}
|
||||
} finally { server.stop(0); }
|
||||
}
|
||||
|
||||
private static void handle(HttpExchange exchange, AtomicReference<String> hash,
|
||||
AtomicReference<String> acl, AtomicReference<String> manifest,
|
||||
AtomicInteger manifestStatus, AtomicBoolean health) throws IOException {
|
||||
String path = exchange.getRequestURI().getRawPath();
|
||||
String query = exchange.getRequestURI().getRawQuery();
|
||||
if ("/health".equals(path)) {
|
||||
respond(exchange, health.get() ? 200 : 404,
|
||||
health.get() ? "{\"status\":\"ok\",\"service\":\"lunarsky-objectstore\"}" : "");
|
||||
return;
|
||||
}
|
||||
check(exchange.getRequestHeaders().getFirst("Authorization") != null, "signed request");
|
||||
if ("/_objectstore/capabilities".equals(path)) {
|
||||
String value = manifest.get();
|
||||
respond(exchange, value == null ? 404 : manifestStatus.get(), value == null ? "" : value);
|
||||
return;
|
||||
}
|
||||
if ("/mybucket".equals(path) && query != null && query.contains("uploads=")) {
|
||||
respond(exchange, 403, "<Error><Code>AccessDenied</Code></Error>");
|
||||
return;
|
||||
}
|
||||
if ("/mybucket".equals(path) && query != null && query.contains("list-type=2")) {
|
||||
respond(exchange, 200, "<ListBucketResult xmlns=\"" + S3_NS + "\"><Contents><Key>hello%20world.txt</Key>" +
|
||||
"<Size>5</Size><ETag>\"abc\"</ETag></Contents><NextContinuationToken>next-token" +
|
||||
"</NextContinuationToken></ListBucketResult>");
|
||||
return;
|
||||
}
|
||||
if (query != null && query.equals("acl=")) {
|
||||
if ("GET".equals(exchange.getRequestMethod())) {
|
||||
respond(exchange, 200, "<AccessControlPolicy xmlns=\"" + S3_NS + "\" " +
|
||||
"xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><Owner><ID>owner-id</ID></Owner>" +
|
||||
"<AccessControlList><Grant><Grantee xsi:type=\"CanonicalUser\"><ID>owner-id</ID>" +
|
||||
"</Grantee><Permission>FULL_CONTROL</Permission></Grant></AccessControlList></AccessControlPolicy>");
|
||||
} else {
|
||||
acl.set(new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8));
|
||||
check(exchange.getRequestHeaders().getFirst("Content-MD5") != null, "ACL Content-MD5");
|
||||
respond(exchange, 200, "");
|
||||
}
|
||||
return;
|
||||
}
|
||||
if ("/mybucket/denied".equals(path)) {
|
||||
exchange.getResponseHeaders().add("x-amz-request-id", "request-123");
|
||||
respond(exchange, 403, "<Error><Code>AccessDenied</Code></Error>");
|
||||
return;
|
||||
}
|
||||
check("/mybucket/hello%20world.txt".equals(path), "path-style key encoding");
|
||||
switch (exchange.getRequestMethod()) {
|
||||
case "PUT" -> {
|
||||
byte[] body = exchange.getRequestBody().readAllBytes();
|
||||
hash.set(exchange.getRequestHeaders().getFirst("x-amz-content-sha256"));
|
||||
check(SigV4.hash(body).equals(hash.get()), "uploaded body hash");
|
||||
respond(exchange, 200, "");
|
||||
}
|
||||
case "GET" -> respond(exchange, 200, "hello");
|
||||
case "HEAD" -> {
|
||||
exchange.getResponseHeaders().add("Content-Type", "text/plain");
|
||||
exchange.sendResponseHeaders(200, -1);
|
||||
}
|
||||
case "DELETE" -> respond(exchange, 204, "");
|
||||
default -> throw new AssertionError("Unexpected method");
|
||||
}
|
||||
}
|
||||
|
||||
private static void respond(HttpExchange exchange, int status, String content) throws IOException {
|
||||
byte[] bytes = content.getBytes(StandardCharsets.UTF_8);
|
||||
if (status == 204 || bytes.length == 0) exchange.sendResponseHeaders(status, -1);
|
||||
else {
|
||||
exchange.sendResponseHeaders(status, bytes.length);
|
||||
exchange.getResponseBody().write(bytes);
|
||||
}
|
||||
}
|
||||
|
||||
private static void check(boolean condition, String description) {
|
||||
if (!condition) throw new AssertionError(description);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
package cloud.lunarsky.objectstore.client;
|
||||
|
||||
import com.sun.net.httpserver.HttpExchange;
|
||||
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.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
public final class MultipartClientTest {
|
||||
public static void main(String[] args) throws Exception {
|
||||
AtomicReference<String> completion = new AtomicReference<>();
|
||||
AtomicBoolean completionError = new AtomicBoolean();
|
||||
List<Integer> sizes = new ArrayList<>();
|
||||
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
|
||||
server.createContext("/", exchange -> {
|
||||
try { handle(exchange, completion, completionError, sizes); }
|
||||
finally { exchange.close(); }
|
||||
});
|
||||
server.start();
|
||||
try (ObjectStorageClient client = new ObjectStorageClientBuilder()
|
||||
.endpoint(URI.create("http://127.0.0.1:" + server.getAddress().getPort()))
|
||||
.allowInsecureHttp().credentials("test-key", "test-secret").build()) {
|
||||
var upload = client.createMultipartUpload("mybucket", "large file.bin", "application/octet-stream");
|
||||
check("u-1".equals(upload.uploadId()), "initiation ID");
|
||||
var first = client.uploadPart(upload, 1, "first".getBytes(StandardCharsets.UTF_8));
|
||||
var second = client.uploadPart(upload, 2, "second".getBytes(StandardCharsets.UTF_8));
|
||||
check(first.number() == 1 && "\"etag-1\"".equals(first.etag()), "part result");
|
||||
var page = client.listParts(upload, 0, 1);
|
||||
check(page.truncated() && page.nextPartNumberMarker() == 1 && page.parts().size() == 1,
|
||||
"first part page");
|
||||
page = client.listParts(upload, page.nextPartNumberMarker(), 1);
|
||||
check(!page.truncated() && page.parts().getFirst().number() == 2, "second part page");
|
||||
var uploads = client.listMultipartUploads("mybucket", "large", null, null, 10);
|
||||
check(uploads.uploads().size() == 1 && "u-1".equals(uploads.uploads().getFirst().uploadId()),
|
||||
"unfinished upload listing");
|
||||
String etag = client.completeMultipartUpload(upload, List.of(second, first));
|
||||
check("\"final-etag\"".equals(etag), "completion ETag");
|
||||
check(completion.get().indexOf("<PartNumber>1</PartNumber>") <
|
||||
completion.get().indexOf("<PartNumber>2</PartNumber>"), "completion part order");
|
||||
completionError.set(true);
|
||||
try {
|
||||
client.completeMultipartUpload(upload, List.of(first));
|
||||
throw new AssertionError("Expected embedded S3 error");
|
||||
} catch (ObjectStorageException error) {
|
||||
check("InvalidPart".equals(error.errorCode()), "HTTP 200 completion error");
|
||||
}
|
||||
completionError.set(false);
|
||||
Path file = Files.createTempFile("objectstore-client-multipart", ".bin");
|
||||
try {
|
||||
byte[] content = new byte[5 * 1024 * 1024 + 3];
|
||||
content[content.length - 1] = 42;
|
||||
Files.write(file, content);
|
||||
var fileParts = client.uploadFileParts(upload, file, 5 * 1024 * 1024);
|
||||
check(fileParts.size() == 2 && fileParts.getLast().size() == 3, "file part slicing");
|
||||
check(sizes.contains(5 * 1024 * 1024) && sizes.contains(3), "part request sizes");
|
||||
} finally { Files.deleteIfExists(file); }
|
||||
client.abortMultipartUpload(upload);
|
||||
System.out.println("Multipart client tests passed");
|
||||
} finally { server.stop(0); }
|
||||
}
|
||||
|
||||
private static void handle(HttpExchange exchange, AtomicReference<String> completion,
|
||||
AtomicBoolean completionError, List<Integer> sizes) throws IOException {
|
||||
check(exchange.getRequestHeaders().getFirst("Authorization") != null, "signed multipart request");
|
||||
String path = exchange.getRequestURI().getRawPath();
|
||||
String query = exchange.getRequestURI().getRawQuery();
|
||||
String method = exchange.getRequestMethod();
|
||||
if ("/mybucket".equals(path) && "GET".equals(method) && query.contains("uploads=")) {
|
||||
reply(exchange, 200, "<ListMultipartUploadsResult><Upload><Key>large file.bin</Key>" +
|
||||
"<UploadId>u-1</UploadId></Upload><IsTruncated>false</IsTruncated></ListMultipartUploadsResult>");
|
||||
return;
|
||||
}
|
||||
check("/mybucket/large%20file.bin".equals(path), "multipart path");
|
||||
if ("POST".equals(method) && "uploads=".equals(query)) {
|
||||
reply(exchange, 200, "<InitiateMultipartUploadResult><UploadId>u-1" +
|
||||
"</UploadId></InitiateMultipartUploadResult>");
|
||||
} else if ("PUT".equals(method) && query.contains("partNumber=")) {
|
||||
int number = query.contains("partNumber=1") ? 1 : 2;
|
||||
byte[] body = exchange.getRequestBody().readAllBytes();
|
||||
check(SigV4.hash(body).equals(exchange.getRequestHeaders().getFirst("x-amz-content-sha256")),
|
||||
"part hash");
|
||||
sizes.add(body.length);
|
||||
exchange.getResponseHeaders().set("ETag", "\"etag-" + number + "\"");
|
||||
reply(exchange, 200, "");
|
||||
} else if ("GET".equals(method) && query.contains("uploadId=")) {
|
||||
boolean first = query.contains("part-number-marker=0");
|
||||
reply(exchange, 200, "<ListPartsResult><Part><PartNumber>" + (first ? 1 : 2) +
|
||||
"</PartNumber><ETag>\"etag-" + (first ? 1 : 2) + "\"</ETag><Size>" +
|
||||
(first ? 5 : 6) + "</Size></Part><IsTruncated>" + first + "</IsTruncated>" +
|
||||
"<NextPartNumberMarker>" + (first ? 1 : 2) + "</NextPartNumberMarker></ListPartsResult>");
|
||||
} else if ("POST".equals(method) && query.contains("uploadId=")) {
|
||||
completion.set(new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8));
|
||||
reply(exchange, 200, completionError.get() ? "<Error><Code>InvalidPart</Code></Error>" :
|
||||
"<CompleteMultipartUploadResult><ETag>\"final-etag\"</ETag></CompleteMultipartUploadResult>");
|
||||
} else if ("DELETE".equals(method) && query.contains("uploadId=")) {
|
||||
reply(exchange, 204, "");
|
||||
} else throw new AssertionError("Unexpected multipart operation: " + method + " " + query);
|
||||
}
|
||||
|
||||
private static void reply(HttpExchange exchange, int status, String content) throws IOException {
|
||||
byte[] bytes = content.getBytes(StandardCharsets.UTF_8);
|
||||
if (bytes.length == 0) exchange.sendResponseHeaders(status, -1);
|
||||
else {
|
||||
exchange.sendResponseHeaders(status, bytes.length);
|
||||
exchange.getResponseBody().write(bytes);
|
||||
}
|
||||
}
|
||||
|
||||
private static void check(boolean condition, String description) {
|
||||
if (!condition) throw new AssertionError(description);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
x-encrypted-id: &encrypted-id ${ENCRYPTED_VOLUME_ID:?Set ENCRYPTED_VOLUME_ID}
|
||||
x-encrypted-data: &encrypted-data
|
||||
ENCRYPTED_VOLUME_ID: *encrypted-id
|
||||
ENCRYPTED_VOLUME_MARKER_FILE: /data/.objectstore-encrypted
|
||||
x-encrypted-staging: &encrypted-staging
|
||||
ENCRYPTED_VOLUME_ID: *encrypted-id
|
||||
ENCRYPTED_VOLUME_MARKER_FILE: /tmp/.objectstore-encrypted
|
||||
x-metadata-entrypoint: &metadata-entrypoint
|
||||
- /bin/sh
|
||||
- -ec
|
||||
- |
|
||||
test -f /var/lib/postgresql/data/.objectstore-encrypted &&
|
||||
test ! -L /var/lib/postgresql/data/.objectstore-encrypted &&
|
||||
printf '%s\n' "$(printenv ENCRYPTED_VOLUME_ID)" | grep -Eq '^[a-f0-9]{32}$' &&
|
||||
grep -Fxq -e "$(printenv ENCRYPTED_VOLUME_ID)" /var/lib/postgresql/data/.objectstore-encrypted ||
|
||||
{ echo 'Encrypted metadata volume unavailable' >&2; exit 1; }
|
||||
exec docker-entrypoint.sh postgres
|
||||
|
||||
services:
|
||||
gateway:
|
||||
environment: *encrypted-staging
|
||||
volumes:
|
||||
- type: bind
|
||||
source: ${ENCRYPTED_STORAGE_ROOT:?Set ENCRYPTED_STORAGE_ROOT}/cluster/gateway-staging
|
||||
target: /tmp
|
||||
bind:
|
||||
create_host_path: false
|
||||
|
||||
metadata:
|
||||
environment:
|
||||
ENCRYPTED_VOLUME_ID: *encrypted-id
|
||||
PGDATA: /var/lib/postgresql/data/pgdata
|
||||
entrypoint: *metadata-entrypoint
|
||||
volumes:
|
||||
- type: bind
|
||||
source: ${ENCRYPTED_STORAGE_ROOT:?Set ENCRYPTED_STORAGE_ROOT}/cluster/metadata
|
||||
target: /var/lib/postgresql/data
|
||||
bind:
|
||||
create_host_path: false
|
||||
|
||||
metadata-recovery:
|
||||
environment:
|
||||
ENCRYPTED_VOLUME_ID: *encrypted-id
|
||||
PGDATA: /var/lib/postgresql/data/pgdata
|
||||
entrypoint: *metadata-entrypoint
|
||||
volumes:
|
||||
- type: bind
|
||||
source: ${ENCRYPTED_STORAGE_ROOT:?Set ENCRYPTED_STORAGE_ROOT}/cluster/metadata-recovery
|
||||
target: /var/lib/postgresql/data
|
||||
bind:
|
||||
create_host_path: false
|
||||
|
||||
repair:
|
||||
environment: *encrypted-staging
|
||||
volumes:
|
||||
- type: bind
|
||||
source: ${ENCRYPTED_STORAGE_ROOT:?Set ENCRYPTED_STORAGE_ROOT}/cluster/repair-staging
|
||||
target: /tmp
|
||||
bind:
|
||||
create_host_path: false
|
||||
|
||||
gc:
|
||||
environment: *encrypted-staging
|
||||
volumes:
|
||||
- type: bind
|
||||
source: ${ENCRYPTED_STORAGE_ROOT:?Set ENCRYPTED_STORAGE_ROOT}/cluster/gc-staging
|
||||
target: /tmp
|
||||
bind:
|
||||
create_host_path: false
|
||||
|
||||
maintenance:
|
||||
environment: *encrypted-staging
|
||||
volumes:
|
||||
- type: bind
|
||||
source: ${ENCRYPTED_STORAGE_ROOT:?Set ENCRYPTED_STORAGE_ROOT}/cluster/maintenance-staging
|
||||
target: /tmp
|
||||
bind:
|
||||
create_host_path: false
|
||||
|
||||
node-a:
|
||||
environment: *encrypted-data
|
||||
volumes:
|
||||
- type: bind
|
||||
source: ${ENCRYPTED_STORAGE_ROOT:?Set ENCRYPTED_STORAGE_ROOT}/cluster/node-a
|
||||
target: /data
|
||||
bind:
|
||||
create_host_path: false
|
||||
|
||||
node-b:
|
||||
environment: *encrypted-data
|
||||
volumes:
|
||||
- type: bind
|
||||
source: ${ENCRYPTED_STORAGE_ROOT:?Set ENCRYPTED_STORAGE_ROOT}/cluster/node-b
|
||||
target: /data
|
||||
bind:
|
||||
create_host_path: false
|
||||
|
||||
node-c:
|
||||
environment: *encrypted-data
|
||||
volumes:
|
||||
- type: bind
|
||||
source: ${ENCRYPTED_STORAGE_ROOT:?Set ENCRYPTED_STORAGE_ROOT}/cluster/node-c
|
||||
target: /data
|
||||
bind:
|
||||
create_host_path: false
|
||||
|
||||
node-d:
|
||||
environment: *encrypted-data
|
||||
volumes:
|
||||
- type: bind
|
||||
source: ${ENCRYPTED_STORAGE_ROOT:?Set ENCRYPTED_STORAGE_ROOT}/cluster/node-d
|
||||
target: /data
|
||||
bind:
|
||||
create_host_path: false
|
||||
@@ -0,0 +1,58 @@
|
||||
x-client-tls: &client-tls
|
||||
CLUSTER_NODES: https://node-a:9100,https://node-b:9100,https://node-c:9100
|
||||
CLUSTER_TLS_TRUSTSTORE: /run/objectstore-tls/trust.p12
|
||||
CLUSTER_TLS_PASSWORD_FILE: /run/objectstore-tls/trust.pass
|
||||
|
||||
x-tls-volume: &tls-volume
|
||||
- ${CLUSTER_TLS_DIR:?Set CLUSTER_TLS_DIR to a private certificate directory}:/run/objectstore-tls:ro
|
||||
|
||||
x-node-health: &node-health
|
||||
test: ["CMD", "nc", "-z", "-w", "2", "127.0.0.1", "9100"]
|
||||
interval: 10s
|
||||
timeout: 3s
|
||||
retries: 3
|
||||
|
||||
services:
|
||||
gateway:
|
||||
environment: *client-tls
|
||||
volumes: *tls-volume
|
||||
|
||||
repair:
|
||||
environment: *client-tls
|
||||
volumes: *tls-volume
|
||||
|
||||
gc:
|
||||
environment: *client-tls
|
||||
volumes: *tls-volume
|
||||
|
||||
maintenance:
|
||||
environment: *client-tls
|
||||
volumes: *tls-volume
|
||||
|
||||
node-a:
|
||||
environment:
|
||||
NODE_TLS_KEYSTORE: /run/objectstore-tls/node-a.p12
|
||||
NODE_TLS_PASSWORD_FILE: /run/objectstore-tls/node-a.pass
|
||||
volumes: *tls-volume
|
||||
healthcheck: *node-health
|
||||
|
||||
node-b:
|
||||
environment:
|
||||
NODE_TLS_KEYSTORE: /run/objectstore-tls/node-b.p12
|
||||
NODE_TLS_PASSWORD_FILE: /run/objectstore-tls/node-b.pass
|
||||
volumes: *tls-volume
|
||||
healthcheck: *node-health
|
||||
|
||||
node-c:
|
||||
environment:
|
||||
NODE_TLS_KEYSTORE: /run/objectstore-tls/node-c.p12
|
||||
NODE_TLS_PASSWORD_FILE: /run/objectstore-tls/node-c.pass
|
||||
volumes: *tls-volume
|
||||
healthcheck: *node-health
|
||||
|
||||
node-d:
|
||||
environment:
|
||||
NODE_TLS_KEYSTORE: /run/objectstore-tls/node-d.p12
|
||||
NODE_TLS_PASSWORD_FILE: /run/objectstore-tls/node-d.pass
|
||||
volumes: *tls-volume
|
||||
healthcheck: *node-health
|
||||
+89
-4
@@ -12,11 +12,29 @@ services:
|
||||
S3_SECRET_KEY: ${S3_SECRET_KEY:?Set S3_SECRET_KEY}
|
||||
S3_BUCKET: ${S3_BUCKET:-objects}
|
||||
S3_REGION: ${S3_REGION:-us-east-1}
|
||||
S3_CREDENTIALS_FILE: ${S3_CREDENTIALS_FILE:-}
|
||||
S3_KEY_SCOPES_FILE: ${S3_KEY_SCOPES_FILE:-}
|
||||
S3_SESSION_CREDENTIALS_FILE: ${S3_SESSION_CREDENTIALS_FILE:-}
|
||||
S3_IDENTITY_POLICIES_DIR: ${S3_IDENTITY_POLICIES_DIR:-}
|
||||
METRICS_BEARER_TOKEN: ${METRICS_BEARER_TOKEN:-}
|
||||
MAX_OBJECT_BYTES: ${MAX_OBJECT_BYTES:-134217728}
|
||||
MAX_TOTAL_BYTES: ${MAX_TOTAL_BYTES:-2147483648}
|
||||
MAX_IN_FLIGHT_REQUESTS: ${MAX_IN_FLIGHT_REQUESTS:-16}
|
||||
HTTP_BACKLOG: ${HTTP_BACKLOG:-64}
|
||||
S3_VIRTUAL_HOST_SUFFIX: ${S3_VIRTUAL_HOST_SUFFIX:-}
|
||||
S3_PUBLIC_ENDPOINT: ${S3_PUBLIC_ENDPOINT:-}
|
||||
CORS_ALLOWED_ORIGINS: ${CORS_ALLOWED_ORIGINS:-}
|
||||
OBJECTSTORE_REQUEST_TIMEOUT_SECONDS: ${OBJECTSTORE_REQUEST_TIMEOUT_SECONDS:-0}
|
||||
OBJECTSTORE_RESPONSE_TIMEOUT_SECONDS: ${OBJECTSTORE_RESPONSE_TIMEOUT_SECONDS:-0}
|
||||
PUBLIC_REQUESTS_PER_SECOND: ${PUBLIC_REQUESTS_PER_SECOND:-0}
|
||||
PUBLIC_REQUEST_BURST: ${PUBLIC_REQUEST_BURST:-}
|
||||
PUBLIC_BYTES_PER_SECOND: ${PUBLIC_BYTES_PER_SECOND:-0}
|
||||
PUBLIC_BYTE_BURST: ${PUBLIC_BYTE_BURST:-}
|
||||
PUBLIC_MAX_IN_FLIGHT_PER_IP: ${PUBLIC_MAX_IN_FLIGHT_PER_IP:-}
|
||||
PUBLIC_TRUSTED_PROXY_IPS: ${PUBLIC_TRUSTED_PROXY_IPS:-}
|
||||
CLUSTER_TOKEN: ${CLUSTER_TOKEN:?Set CLUSTER_TOKEN}
|
||||
CLUSTER_NODES: ${CLUSTER_NODES:-http://node-a:9100,http://node-b:9100,http://node-c:9100}
|
||||
POSTGRES_JDBC_URL: jdbc:postgresql://metadata:5432/objectstore?connectTimeout=3&socketTimeout=10
|
||||
POSTGRES_JDBC_URL: ${POSTGRES_JDBC_URL:-jdbc:postgresql://metadata:5432/objectstore?connectTimeout=3&socketTimeout=10&targetServerType=primary}
|
||||
POSTGRES_USER: objectstore
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD}
|
||||
ports:
|
||||
@@ -31,7 +49,7 @@ services:
|
||||
node-c:
|
||||
condition: service_healthy
|
||||
healthcheck:
|
||||
test: ["CMD", "wget", "-qO-", "http://127.0.0.1:9000/ready"]
|
||||
test: ["CMD", "wget", "-qO-", "--header", "X-Real-IP: 127.0.0.1", "http://127.0.0.1:9000/ready"]
|
||||
interval: 10s
|
||||
timeout: 4s
|
||||
retries: 3
|
||||
@@ -59,7 +77,25 @@ services:
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
|
||||
repair:
|
||||
metadata-recovery:
|
||||
image: postgres:17-alpine
|
||||
profiles: [recovery]
|
||||
environment:
|
||||
POSTGRES_DB: objectstore
|
||||
POSTGRES_USER: objectstore
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD}
|
||||
volumes:
|
||||
- cluster-metadata-recovery:/var/lib/postgresql/data
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U objectstore -d objectstore"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 10
|
||||
mem_limit: 256m
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
|
||||
repair: &repair
|
||||
image: lunarsky-objectstore:cluster-local
|
||||
profiles: [maintenance]
|
||||
entrypoint: ["/usr/local/bin/objectstore", "cluster-repair"]
|
||||
@@ -71,9 +107,57 @@ services:
|
||||
CLUSTER_TOKEN: ${CLUSTER_TOKEN:?Set CLUSTER_TOKEN}
|
||||
CLUSTER_REPAIR_TOKEN: ${CLUSTER_REPAIR_TOKEN:?Set CLUSTER_REPAIR_TOKEN}
|
||||
S3_BUCKET: ${S3_BUCKET:-objects}
|
||||
POSTGRES_JDBC_URL: jdbc:postgresql://metadata:5432/objectstore?connectTimeout=3&socketTimeout=10
|
||||
POSTGRES_JDBC_URL: ${POSTGRES_JDBC_URL:-jdbc:postgresql://metadata:5432/objectstore?connectTimeout=3&socketTimeout=10&targetServerType=primary}
|
||||
POSTGRES_USER: objectstore
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD}
|
||||
MAX_OBJECT_BYTES: ${MAX_OBJECT_BYTES:-134217728}
|
||||
MAX_TOTAL_BYTES: ${MAX_TOTAL_BYTES:-2147483648}
|
||||
CLUSTER_GC_MIN_AGE_SECONDS: ${CLUSTER_GC_MIN_AGE_SECONDS:-1209600}
|
||||
CLUSTER_BACKUP_RETENTION_SECONDS: ${CLUSTER_BACKUP_RETENTION_SECONDS:-0}
|
||||
CLUSTER_GC_TEST_MODE: ${CLUSTER_GC_TEST_MODE:-false}
|
||||
mem_limit: 384m
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
cap_drop:
|
||||
- ALL
|
||||
|
||||
gc:
|
||||
<<: *repair
|
||||
entrypoint: ["/usr/local/bin/objectstore", "cluster-gc"]
|
||||
|
||||
maintenance:
|
||||
image: lunarsky-objectstore:cluster-local
|
||||
profiles: [automatic]
|
||||
restart: unless-stopped
|
||||
entrypoint: ["/usr/local/bin/objectstore", "cluster-repair", "--loop"]
|
||||
environment:
|
||||
STORE_MODE: cluster
|
||||
CLUSTER_LOCAL_DEV: "true"
|
||||
CLUSTER_TEST_NODE_DOMAINS: "true"
|
||||
CLUSTER_NODES: ${CLUSTER_NODES:-http://node-a:9100,http://node-b:9100,http://node-c:9100}
|
||||
CLUSTER_TOKEN: ${CLUSTER_TOKEN:?Set CLUSTER_TOKEN}
|
||||
CLUSTER_REPAIR_TOKEN: ${CLUSTER_REPAIR_TOKEN:?Set CLUSTER_REPAIR_TOKEN}
|
||||
CLUSTER_MAINTENANCE_INTERVAL_SECONDS: ${CLUSTER_MAINTENANCE_INTERVAL_SECONDS:-60}
|
||||
CLUSTER_GC_ENABLED: ${CLUSTER_GC_ENABLED:-false}
|
||||
CLUSTER_GC_INTERVAL_SECONDS: ${CLUSTER_GC_INTERVAL_SECONDS:-86400}
|
||||
CLUSTER_GC_MIN_AGE_SECONDS: ${CLUSTER_GC_MIN_AGE_SECONDS:-1209600}
|
||||
CLUSTER_BACKUP_RETENTION_SECONDS: ${CLUSTER_BACKUP_RETENTION_SECONDS:-0}
|
||||
CLUSTER_GC_TEST_MODE: ${CLUSTER_GC_TEST_MODE:-false}
|
||||
S3_BUCKET: ${S3_BUCKET:-objects}
|
||||
POSTGRES_JDBC_URL: ${POSTGRES_JDBC_URL:-jdbc:postgresql://metadata:5432/objectstore?connectTimeout=3&socketTimeout=10&targetServerType=primary}
|
||||
POSTGRES_USER: objectstore
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD}
|
||||
MAX_OBJECT_BYTES: ${MAX_OBJECT_BYTES:-134217728}
|
||||
MAX_TOTAL_BYTES: ${MAX_TOTAL_BYTES:-2147483648}
|
||||
depends_on:
|
||||
metadata:
|
||||
condition: service_healthy
|
||||
node-a:
|
||||
condition: service_healthy
|
||||
node-b:
|
||||
condition: service_healthy
|
||||
node-c:
|
||||
condition: service_healthy
|
||||
mem_limit: 384m
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
@@ -121,6 +205,7 @@ services:
|
||||
|
||||
volumes:
|
||||
cluster-metadata:
|
||||
cluster-metadata-recovery:
|
||||
cluster-node-a:
|
||||
cluster-node-b:
|
||||
cluster-node-c:
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
services:
|
||||
objectstore:
|
||||
environment:
|
||||
ENCRYPTED_VOLUME_ID: ${ENCRYPTED_VOLUME_ID:?Set ENCRYPTED_VOLUME_ID}
|
||||
ENCRYPTED_VOLUME_MARKER_FILE: /data/.objectstore-encrypted
|
||||
volumes:
|
||||
- type: bind
|
||||
source: ${ENCRYPTED_STORAGE_ROOT:?Set ENCRYPTED_STORAGE_ROOT}/single
|
||||
target: /data
|
||||
bind:
|
||||
create_host_path: false
|
||||
@@ -4,12 +4,31 @@ services:
|
||||
image: lunarsky-objectstore:local
|
||||
restart: unless-stopped
|
||||
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_SECRET_KEY: ${S3_SECRET_KEY:?Set S3_SECRET_KEY in .env}
|
||||
S3_BUCKET: ${S3_BUCKET:-objects}
|
||||
S3_REGION: ${S3_REGION:-us-east-1}
|
||||
S3_CREDENTIALS_FILE: ${S3_CREDENTIALS_FILE:-}
|
||||
S3_KEY_SCOPES_FILE: ${S3_KEY_SCOPES_FILE:-}
|
||||
S3_SESSION_CREDENTIALS_FILE: ${S3_SESSION_CREDENTIALS_FILE:-}
|
||||
S3_IDENTITY_POLICIES_DIR: ${S3_IDENTITY_POLICIES_DIR:-}
|
||||
METRICS_BEARER_TOKEN: ${METRICS_BEARER_TOKEN:-}
|
||||
MAX_OBJECT_BYTES: ${MAX_OBJECT_BYTES:-134217728}
|
||||
MAX_TOTAL_BYTES: ${MAX_TOTAL_BYTES:-2147483648}
|
||||
MAX_IN_FLIGHT_REQUESTS: ${MAX_IN_FLIGHT_REQUESTS:-16}
|
||||
HTTP_BACKLOG: ${HTTP_BACKLOG:-64}
|
||||
S3_VIRTUAL_HOST_SUFFIX: ${S3_VIRTUAL_HOST_SUFFIX:-}
|
||||
S3_PUBLIC_ENDPOINT: ${S3_PUBLIC_ENDPOINT:-}
|
||||
CORS_ALLOWED_ORIGINS: ${CORS_ALLOWED_ORIGINS:-}
|
||||
PUBLIC_REQUESTS_PER_SECOND: ${PUBLIC_REQUESTS_PER_SECOND:-0}
|
||||
PUBLIC_REQUEST_BURST: ${PUBLIC_REQUEST_BURST:-}
|
||||
PUBLIC_BYTES_PER_SECOND: ${PUBLIC_BYTES_PER_SECOND:-0}
|
||||
PUBLIC_BYTE_BURST: ${PUBLIC_BYTE_BURST:-}
|
||||
PUBLIC_MAX_IN_FLIGHT_PER_IP: ${PUBLIC_MAX_IN_FLIGHT_PER_IP:-}
|
||||
PUBLIC_TRUSTED_PROXY_IPS: ${PUBLIC_TRUSTED_PROXY_IPS:-}
|
||||
ports:
|
||||
- "127.0.0.1:${HOST_PORT:-9000}:9000"
|
||||
volumes:
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
Binary file not shown.
Generated
+2339
File diff suppressed because it is too large.
Load diff
@@ -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"] }
|
||||
@@ -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.
|
||||
@@ -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(())
|
||||
}
|
||||
@@ -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(())
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
env_file=${1:?Usage: sh scripts/backup-cluster-metadata.sh /path/to/cluster.env /path/to/metadata.dump}
|
||||
output=${2:?Usage: sh scripts/backup-cluster-metadata.sh /path/to/cluster.env /path/to/metadata.dump}
|
||||
if [ -e "$output" ]; then
|
||||
echo "Backup destination already exists" >&2
|
||||
exit 1
|
||||
fi
|
||||
umask 077
|
||||
temporary=$(mktemp "${output}.tmp.XXXXXX")
|
||||
trap 'rm -f "$temporary"' EXIT
|
||||
docker compose --env-file "$env_file" -f compose.cluster.yaml exec -T metadata \
|
||||
pg_dump -U objectstore -d objectstore --format=custom --no-owner --no-acl > "$temporary"
|
||||
test -s "$temporary"
|
||||
docker compose --env-file "$env_file" -f compose.cluster.yaml exec -T metadata \
|
||||
pg_restore --list < "$temporary" > /dev/null
|
||||
mv "$temporary" "$output"
|
||||
echo "Metadata backup written to $output"
|
||||
@@ -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()
|
||||
+8
-4
@@ -1,14 +1,18 @@
|
||||
#!/bin/sh
|
||||
if [ "${1:-}" = "cluster-repair" ]; then
|
||||
shift
|
||||
exec java -XX:MaxRAMPercentage=70 --add-modules java.net.http -cp /app:/app/postgresql.jar cloud.lunarsky.store.ClusterRepair "$@"
|
||||
exec java -XX:MaxRAMPercentage=70 --add-modules java.net.http -cp /app:/app/postgresql.jar:/app/hash4j.jar cloud.lunarsky.store.ClusterRepair "$@"
|
||||
fi
|
||||
if [ "${1:-}" = "cluster-gc" ]; then
|
||||
shift
|
||||
exec java -XX:MaxRAMPercentage=70 --add-modules java.net.http -cp /app:/app/postgresql.jar:/app/hash4j.jar cloud.lunarsky.store.ClusterGc "$@"
|
||||
fi
|
||||
if [ "${1:-}" = "cluster-migrate" ]; then
|
||||
shift
|
||||
exec java -XX:MaxRAMPercentage=70 --add-modules java.net.http -cp /app:/app/postgresql.jar cloud.lunarsky.store.ClusterMigrate "$@"
|
||||
exec java -XX:MaxRAMPercentage=70 --add-modules java.net.http -cp /app:/app/postgresql.jar:/app/hash4j.jar cloud.lunarsky.store.ClusterMigrate "$@"
|
||||
fi
|
||||
if [ "${1:-}" = "cluster-join" ]; then
|
||||
shift
|
||||
exec java -XX:MaxRAMPercentage=70 --add-modules java.net.http -cp /app:/app/postgresql.jar cloud.lunarsky.store.ClusterJoin "$@"
|
||||
exec java -XX:MaxRAMPercentage=70 --add-modules java.net.http -cp /app:/app/postgresql.jar:/app/hash4j.jar cloud.lunarsky.store.ClusterJoin "$@"
|
||||
fi
|
||||
exec java -XX:MaxRAMPercentage=70 -cp /app cloud.lunarsky.store.Cli "$@"
|
||||
exec java -XX:MaxRAMPercentage=70 -cp /app:/app/hash4j.jar cloud.lunarsky.store.Cli "$@"
|
||||
@@ -0,0 +1,69 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
mode=${1:-}
|
||||
case "$mode" in
|
||||
single) directories='single' ;;
|
||||
cluster) directories='cluster/gateway-staging cluster/metadata cluster/metadata-recovery cluster/repair-staging cluster/gc-staging cluster/maintenance-staging cluster/node-a cluster/node-b cluster/node-c cluster/node-d' ;;
|
||||
*) echo 'Usage: prepare-encrypted-storage.sh single|cluster [environment-file]' >&2; exit 2 ;;
|
||||
esac
|
||||
|
||||
if [ "$#" -gt 2 ]; then
|
||||
echo 'Too many arguments' >&2
|
||||
exit 2
|
||||
fi
|
||||
if [ "$#" -eq 2 ]; then
|
||||
[ -r "$2" ] || { echo 'Environment file is not readable' >&2; exit 2; }
|
||||
while IFS='=' read -r name value || [ -n "${name:-}" ]; do
|
||||
case "$name" in
|
||||
ENCRYPTED_STORAGE_ROOT) ENCRYPTED_STORAGE_ROOT=$value ;;
|
||||
ENCRYPTED_VOLUME_ID) ENCRYPTED_VOLUME_ID=$value ;;
|
||||
esac
|
||||
done < "$2"
|
||||
fi
|
||||
|
||||
root=${ENCRYPTED_STORAGE_ROOT:?Set ENCRYPTED_STORAGE_ROOT to an existing mounted LUKS directory}
|
||||
id=${ENCRYPTED_VOLUME_ID:?Set ENCRYPTED_VOLUME_ID to 32 lowercase hex characters}
|
||||
case "$id" in *[!0-9a-f]*|'') echo 'ENCRYPTED_VOLUME_ID must be lowercase hex' >&2; exit 2 ;; esac
|
||||
[ "${#id}" -eq 32 ] || { echo 'ENCRYPTED_VOLUME_ID must be 32 characters' >&2; exit 2; }
|
||||
[ -d "$root" ] && [ ! -L "$root" ] || { echo 'Encrypted root is missing or a symlink' >&2; exit 1; }
|
||||
root=$(realpath -e "$root")
|
||||
source=$(findmnt -n -M "$root" -o SOURCE) || { echo 'Encrypted root is not a mount point' >&2; exit 1; }
|
||||
device=$(printf '%s\n' "$source" | sed 's/\[.*$//')
|
||||
case "$device" in /dev/*) ;; *) echo 'Encrypted root must be backed by a block device' >&2; exit 1 ;; esac
|
||||
lsblk -s -n -r -o TYPE "$device" | grep -Fxq crypt || {
|
||||
echo 'Encrypted root is not backed by an active dm-crypt mapping' >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
for relative in $directories; do
|
||||
path=$root/$relative
|
||||
[ ! -L "$root/cluster" ] || { echo 'Refusing symlink under encrypted root' >&2; exit 1; }
|
||||
[ ! -L "$path" ] || { echo "Refusing symlink: $path" >&2; exit 1; }
|
||||
if [ -d "$path" ] && [ ! -e "$path/.objectstore-encrypted" ] &&
|
||||
[ -n "$(find "$path" -mindepth 1 -maxdepth 1 -print -quit)" ]; then
|
||||
echo "Refusing to mark nonempty directory: $path" >&2
|
||||
exit 1
|
||||
fi
|
||||
install -d -m 0700 "$path"
|
||||
[ "$(findmnt -n -T "$path" -o TARGET)" = "$root" ] || {
|
||||
echo "Directory is not on the encrypted mount: $path" >&2
|
||||
exit 1
|
||||
}
|
||||
marker=$path/.objectstore-encrypted
|
||||
if [ -e "$marker" ]; then
|
||||
[ ! -L "$marker" ] && [ "$(cat "$marker")" = "$id" ] || {
|
||||
echo "Encrypted volume marker mismatch: $path" >&2
|
||||
exit 1
|
||||
}
|
||||
else
|
||||
printf '%s\n' "$id" > "$marker"
|
||||
fi
|
||||
chmod 0600 "$marker"
|
||||
case "$relative" in
|
||||
cluster/metadata|cluster/metadata-recovery) chown 70:70 "$path" "$marker" ;;
|
||||
*) chown 10001:10001 "$path" "$marker" ;;
|
||||
esac
|
||||
done
|
||||
|
||||
echo "Prepared $mode paths on the active encrypted mount: $root"
|
||||
@@ -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
|
||||
@@ -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"
|
||||
fi
|
||||
done
|
||||
|
||||
exec java "$@" --add-modules jdk.httpserver,java.net.http \
|
||||
-cp /app:/app/postgresql.jar:/app/hash4j.jar cloud.lunarsky.store.Main
|
||||
+267
-11
@@ -1,12 +1,16 @@
|
||||
#!/usr/bin/env python3
|
||||
import datetime
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import http.client
|
||||
import json
|
||||
import pathlib
|
||||
import re
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
import zlib
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
|
||||
values = dict(line.strip().split("=", 1) for line in pathlib.Path(sys.argv[1]).read_text().splitlines()
|
||||
@@ -14,14 +18,35 @@ values = dict(line.strip().split("=", 1) for line in pathlib.Path(sys.argv[1]).r
|
||||
access = values["S3_ACCESS_KEY"]
|
||||
secret = values["S3_SECRET_KEY"]
|
||||
bucket = values.get("S3_BUCKET", "objects")
|
||||
port = values.get("CLUSTER_HOST_PORT", "9001")
|
||||
port = int(values.get("CLUSTER_HOST_PORT", "9001"))
|
||||
if not 1 <= port <= 65535:
|
||||
raise ValueError("CLUSTER_HOST_PORT must be between 1 and 65535")
|
||||
host = f"127.0.0.1:{port}"
|
||||
MAX_RESPONSE_BYTES = 1024 * 1024
|
||||
|
||||
|
||||
def sign(key, message):
|
||||
return hmac.new(key, message.encode(), hashlib.sha256).digest()
|
||||
|
||||
|
||||
def parse_xml(content):
|
||||
if len(content) > MAX_RESPONSE_BYTES:
|
||||
raise ValueError("Unsafe XML response from test server")
|
||||
text = content.decode("utf-8")
|
||||
if "<!DOCTYPE" in text or "<!ENTITY" in text:
|
||||
raise ValueError("Unsafe XML response from test server")
|
||||
parser = ET.XMLParser()
|
||||
parser.feed(text)
|
||||
return parser.close()
|
||||
|
||||
|
||||
def read_response(response):
|
||||
content = response.read(MAX_RESPONSE_BYTES + 1)
|
||||
if len(content) > MAX_RESPONSE_BYTES:
|
||||
raise ValueError("Oversized response from test server")
|
||||
return content
|
||||
|
||||
|
||||
def request(method, path, body=b"", extra=None):
|
||||
extra = extra or {}
|
||||
date = datetime.datetime.now(datetime.timezone.utc).strftime("%Y%m%dT%H%M%SZ")
|
||||
@@ -40,14 +65,23 @@ def request(method, path, body=b"", extra=None):
|
||||
signature = hmac.new(key, to_sign.encode(), hashlib.sha256).hexdigest()
|
||||
headers["authorization"] = (f"AWS4-HMAC-SHA256 Credential={access}/{scope},"
|
||||
f"SignedHeaders={signed_names},Signature={signature}")
|
||||
url = f"http://{host}{path}"
|
||||
outgoing = urllib.request.Request(url, data=body if method == "PUT" else None,
|
||||
method=method, headers=headers)
|
||||
connection = http.client.HTTPConnection("127.0.0.1", port, timeout=30)
|
||||
try:
|
||||
with urllib.request.urlopen(outgoing, timeout=30) as response:
|
||||
return response.status, response.read(), response.headers
|
||||
except urllib.error.HTTPError as error:
|
||||
return error.code, error.read(), error.headers
|
||||
connection.request(method, path, body=body if method in ("PUT", "POST") else None, headers=headers)
|
||||
response = connection.getresponse()
|
||||
return response.status, read_response(response), response.headers
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
|
||||
def anonymous(method, path):
|
||||
connection = http.client.HTTPConnection("127.0.0.1", port, timeout=30)
|
||||
try:
|
||||
connection.request(method, path)
|
||||
response = connection.getresponse()
|
||||
return response.status, read_response(response)
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
|
||||
if len(sys.argv) > 2 and sys.argv[2] == "survivor":
|
||||
@@ -56,6 +90,26 @@ if len(sys.argv) > 2 and sys.argv[2] == "survivor":
|
||||
print("Cluster surviving-replica HTTP read passed")
|
||||
sys.exit(0)
|
||||
|
||||
if len(sys.argv) > 2 and sys.argv[2] == "acl":
|
||||
path = f"/{bucket}/cluster-test/acl-multipart"
|
||||
status, content, _ = request("POST", path + "?uploads", extra={"x-amz-acl": "public-read"})
|
||||
assert status == 200, (status, content)
|
||||
upload_id = parse_xml(content).findtext("UploadId")
|
||||
status, _, headers = request("PUT", path + f"?partNumber=1&uploadId={upload_id}", b"public part")
|
||||
assert status == 200, status
|
||||
completion = ("<CompleteMultipartUpload><Part><PartNumber>1</PartNumber><ETag>" +
|
||||
headers["etag"] + "</ETag></Part></CompleteMultipartUpload>").encode()
|
||||
status, _, _ = request("POST", path + f"?uploadId={upload_id}", completion)
|
||||
assert status == 200, status
|
||||
status, content = anonymous("GET", path)
|
||||
assert status == 200 and content == b"public part", (status, content)
|
||||
status, _, _ = request("PUT", path, b"private replacement")
|
||||
assert status == 200, status
|
||||
status, _ = anonymous("GET", path)
|
||||
assert status == 403, status
|
||||
print("Cluster multipart ACL and replacement tests passed")
|
||||
sys.exit(0)
|
||||
|
||||
if len(sys.argv) > 4 and sys.argv[2] == "status":
|
||||
key = urllib.parse.quote(sys.argv[3], safe="/")
|
||||
expected = int(sys.argv[4])
|
||||
@@ -64,6 +118,44 @@ if len(sys.argv) > 4 and sys.argv[2] == "status":
|
||||
print(f"Cluster GET status passed: {status}")
|
||||
sys.exit(0)
|
||||
|
||||
if len(sys.argv) > 2 and sys.argv[2] == "version-survivor":
|
||||
status, listing, _ = request("GET", "/version-bucket?versions")
|
||||
assert status == 200, status
|
||||
root = parse_xml(listing)
|
||||
namespace = {"s3": "http://s3.amazonaws.com/doc/2006-03-01/"}
|
||||
expected_etag = '"' + hashlib.md5(b"older cluster version", usedforsecurity=False).hexdigest() + '"'
|
||||
versions = [version for version in root.findall("s3:Version", namespace)
|
||||
if version.findtext("s3:ETag", namespaces=namespace) == expected_etag]
|
||||
assert len(versions) == 1, listing
|
||||
version_id = versions[0].findtext("s3:VersionId", namespaces=namespace)
|
||||
status, content, _ = request("GET", "/version-bucket/note.txt?versionId=" + version_id)
|
||||
assert status == 200 and content == b"older cluster version", (status, content)
|
||||
multipart_versions = [version for version in root.findall("s3:Version", namespace)
|
||||
if version.findtext("s3:Key", namespaces=namespace) == "multipart.txt"]
|
||||
assert len(multipart_versions) == 1, listing
|
||||
multipart_id = multipart_versions[0].findtext("s3:VersionId", namespaces=namespace)
|
||||
status, content, _ = request("GET", "/version-bucket/multipart.txt?versionId=" + multipart_id)
|
||||
assert status == 200 and content == b"retained multipart version", (status, content)
|
||||
print("Cluster historical version survived repair and cleanup")
|
||||
sys.exit(0)
|
||||
|
||||
|
||||
status, content, headers = request("GET", "/_objectstore/capabilities")
|
||||
capabilities = json.loads(content)
|
||||
assert status == 200 and capabilities["schemaVersion"] == 1, (status, content)
|
||||
assert capabilities["storageMode"] == "cluster", capabilities
|
||||
assert "ListParts" in capabilities["operations"], capabilities
|
||||
assert capabilities["limits"]["maxObjectBytes"] > 0, capabilities
|
||||
assert headers.get_content_type() == "application/json", headers
|
||||
|
||||
ownership = b"<OwnershipControls><Rule><ObjectOwnership>ObjectWriter</ObjectOwnership></Rule></OwnershipControls>"
|
||||
status, _, _ = request("PUT", f"/{bucket}?ownershipControls", ownership)
|
||||
assert status == 200, status
|
||||
public_access = (b"<PublicAccessBlockConfiguration><BlockPublicAcls>false</BlockPublicAcls>"
|
||||
b"<IgnorePublicAcls>false</IgnorePublicAcls><BlockPublicPolicy>false</BlockPublicPolicy>"
|
||||
b"<RestrictPublicBuckets>false</RestrictPublicBuckets></PublicAccessBlockConfiguration>")
|
||||
status, _, _ = request("PUT", f"/{bucket}?publicAccessBlock", public_access)
|
||||
assert status == 200, status
|
||||
|
||||
key = f"/{bucket}/cluster-test/http.txt"
|
||||
body = b"HTTP gateway integration test"
|
||||
@@ -81,4 +173,168 @@ status, _, _ = request("DELETE", key)
|
||||
assert status == 204, status
|
||||
status, _, _ = request("GET", key)
|
||||
assert status == 404, status
|
||||
print("Cluster HTTP tests passed: signed PUT, GET, range, HEAD, LIST, DELETE")
|
||||
|
||||
public_key = f"/{bucket}/cluster-test/public.txt"
|
||||
status, _, _ = request("PUT", public_key, b"public object", {"x-amz-acl": "public-read"})
|
||||
assert status == 200, status
|
||||
status, content = anonymous("GET", public_key)
|
||||
assert status == 200 and content == b"public object", (status, content)
|
||||
status, acl, _ = request("GET", public_key + "?acl")
|
||||
assert status == 200 and b"AllUsers" in acl, (status, acl)
|
||||
status, _, _ = request("PUT", public_key, b"private replacement")
|
||||
assert status == 200, status
|
||||
status, _ = anonymous("GET", public_key)
|
||||
assert status == 403, status
|
||||
status, _, _ = request("PUT", public_key + "?acl", extra={"x-amz-acl": "public-read"})
|
||||
assert status == 200, status
|
||||
status, content = anonymous("GET", public_key)
|
||||
assert status == 200 and content == b"private replacement", (status, content)
|
||||
|
||||
copy_source = f"/{bucket}/cluster-test/copy-source.txt"
|
||||
copy_target = f"/{bucket}/cluster-test/copied.txt"
|
||||
body = b"cluster copy and checksum test"
|
||||
crc32 = base64.b64encode(zlib.crc32(body).to_bytes(4, "big")).decode()
|
||||
md5 = base64.b64encode(hashlib.md5(body, usedforsecurity=False).digest()).decode()
|
||||
status, _, headers = request("PUT", copy_source, body,
|
||||
{"content-type": "text/plain", "content-md5": md5,
|
||||
"x-amz-checksum-crc32": crc32,
|
||||
"x-amz-sdk-checksum-algorithm": "CRC32"})
|
||||
assert status == 200 and headers["x-amz-checksum-crc32"] == crc32, status
|
||||
status, _, headers = request("HEAD", copy_source,
|
||||
extra={"x-amz-checksum-mode": "ENABLED"})
|
||||
assert status == 200 and headers["x-amz-checksum-crc32"] == crc32, status
|
||||
status, content, _ = request("PUT", copy_source, body,
|
||||
{"content-md5": base64.b64encode(bytes(16)).decode()})
|
||||
assert status == 400 and b"BadDigest" in content, (status, content)
|
||||
status, content, _ = request("GET", copy_source)
|
||||
assert status == 200 and content == body, (status, content)
|
||||
status, content, _ = request("PUT", copy_target, extra={"x-amz-copy-source": copy_source})
|
||||
assert status == 200 and b"<CopyObjectResult>" in content, (status, content)
|
||||
status, content, headers = request("GET", copy_target)
|
||||
assert status == 200 and content == body and headers["content-type"] == "text/plain", (status, content)
|
||||
status, _, headers = request("HEAD", copy_target, extra={"x-amz-checksum-mode": "ENABLED"})
|
||||
assert status == 200 and headers["x-amz-checksum-crc32"] == crc32, status
|
||||
status, _, _ = request("DELETE", copy_source)
|
||||
assert status == 204, status
|
||||
status, _, _ = request("DELETE", copy_target)
|
||||
assert status == 204, status
|
||||
|
||||
attribute_key = f"/{bucket}/cluster-test/attributes.txt"
|
||||
status, _, _ = request("PUT", attribute_key, b"cluster attributes",
|
||||
{"x-amz-meta-project": "LunarSky", "x-amz-tagging": "stage=one"})
|
||||
assert status == 200, status
|
||||
status, content, headers = request("GET", attribute_key)
|
||||
assert status == 200 and content == b"cluster attributes", (status, content)
|
||||
assert headers["x-amz-meta-project"] == "LunarSky" and headers["x-amz-tagging-count"] == "1"
|
||||
status, content, _ = request("GET", attribute_key + "?tagging")
|
||||
assert status == 200 and b"<Key>stage</Key><Value>one</Value>" in content, (status, content)
|
||||
replacement = b"<Tagging><TagSet><Tag><Key>stage</Key><Value>two</Value></Tag></TagSet></Tagging>"
|
||||
status, _, _ = request("PUT", attribute_key + "?tagging", replacement)
|
||||
assert status == 200, status
|
||||
status, content, _ = request("GET", attribute_key + "?tagging")
|
||||
assert status == 200 and b"<Value>two</Value>" in content, (status, content)
|
||||
status, _, _ = request("DELETE", attribute_key + "?tagging")
|
||||
assert status == 204, status
|
||||
status, content, _ = request("GET", attribute_key + "?tagging")
|
||||
assert status == 200 and b"<TagSet></TagSet>" in content, (status, content)
|
||||
status, content, _ = request("GET", "/")
|
||||
assert status == 200 and f"<Name>{bucket}</Name>".encode() in content, (status, content)
|
||||
status, _, _ = request("PUT", "/second-bucket")
|
||||
assert status == 200, status
|
||||
status, _, _ = request("PUT", "/second-bucket/one.txt", b"second bucket")
|
||||
assert status == 200, status
|
||||
status, content, _ = request("PUT", "/second-bucket/copied.txt", extra={"x-amz-copy-source": attribute_key})
|
||||
assert status == 200 and b"<CopyObjectResult>" in content, (status, content)
|
||||
status, content, headers = request("GET", "/second-bucket/copied.txt")
|
||||
assert status == 200 and content == b"cluster attributes", (status, content)
|
||||
assert headers["x-amz-meta-project"] == "LunarSky"
|
||||
status, _, _ = request("DELETE", attribute_key)
|
||||
assert status == 204, status
|
||||
status, content, _ = request("GET", "/second-bucket/one.txt")
|
||||
assert status == 200 and content == b"second bucket", (status, content)
|
||||
status, _, _ = request("DELETE", "/second-bucket")
|
||||
assert status == 409, status
|
||||
status, _, _ = request("DELETE", "/second-bucket/one.txt")
|
||||
assert status == 204, status
|
||||
status, _, _ = request("DELETE", "/second-bucket/copied.txt")
|
||||
assert status == 204, status
|
||||
status, _, _ = request("DELETE", "/second-bucket")
|
||||
assert status == 204, status
|
||||
|
||||
status, _, _ = request("PUT", "/version-bucket")
|
||||
assert status == 200, status
|
||||
version_key = "/version-bucket/note.txt"
|
||||
status, _, _ = request("PUT", version_key, b"pre-versioning")
|
||||
assert status == 200, status
|
||||
versioning = b"<VersioningConfiguration><Status>Enabled</Status></VersioningConfiguration>"
|
||||
status, _, _ = request("PUT", "/version-bucket?versioning", versioning)
|
||||
assert status == 200, status
|
||||
status, _, headers = request("PUT", version_key, b"older cluster version")
|
||||
assert status == 200, status
|
||||
old_version = headers["x-amz-version-id"]
|
||||
status, _, headers = request("PUT", version_key, b"newer cluster version")
|
||||
assert status == 200 and headers["x-amz-version-id"] != old_version, status
|
||||
status, content, _ = request("GET", version_key + "?versionId=" + old_version)
|
||||
assert status == 200 and content == b"older cluster version", (status, content)
|
||||
status, _, headers = request("DELETE", version_key)
|
||||
assert status == 204 and headers["x-amz-delete-marker"] == "true", status
|
||||
status, content, _ = request("GET", version_key)
|
||||
assert status == 404, (status, content)
|
||||
status, content, _ = request("GET", "/version-bucket?versions")
|
||||
assert status == 200 and b"<DeleteMarker>" in content and old_version.encode() in content, (status, content)
|
||||
versioned_multipart = "/version-bucket/multipart.txt"
|
||||
status, content, _ = request("POST", versioned_multipart + "?uploads")
|
||||
assert status == 200, (status, content)
|
||||
versioned_upload = parse_xml(content).findtext("UploadId")
|
||||
assert versioned_upload, content
|
||||
versioned_part = b"retained multipart version"
|
||||
status, _, headers = request("PUT", versioned_multipart +
|
||||
f"?partNumber=1&uploadId={versioned_upload}", versioned_part)
|
||||
assert status == 200, status
|
||||
completion = ("<CompleteMultipartUpload><Part><PartNumber>1</PartNumber><ETag>" +
|
||||
headers["etag"] + "</ETag></Part></CompleteMultipartUpload>").encode()
|
||||
status, _, headers = request("POST", versioned_multipart + f"?uploadId={versioned_upload}", completion)
|
||||
assert status == 200 and headers.get("x-amz-version-id"), status
|
||||
versioned_part_id = headers["x-amz-version-id"]
|
||||
status, _, _ = request("DELETE", versioned_multipart)
|
||||
assert status == 204, status
|
||||
status, content, _ = request("GET", versioned_multipart + "?versionId=" + versioned_part_id)
|
||||
assert status == 200 and content == versioned_part, (status, content)
|
||||
|
||||
multipart_key = f"/{bucket}/cluster-test/http-multipart.txt"
|
||||
status, content, _ = request("POST", multipart_key + "?uploads",
|
||||
extra={"x-amz-meta-project": "multipart", "x-amz-tagging": "stage=upload",
|
||||
"x-amz-acl": "public-read"})
|
||||
assert status == 200, (status, content)
|
||||
match = re.search(rb"<UploadId>([0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12})</UploadId>",
|
||||
content[:8192])
|
||||
assert match, content
|
||||
upload_id = match.group(1).decode("ascii")
|
||||
part_etags = []
|
||||
for number, part in enumerate((b"hello ", b"world"), start=1):
|
||||
checksum = base64.b64encode(hashlib.sha1(part).digest()).decode()
|
||||
status, _, headers = request("PUT", multipart_key + f"?partNumber={number}&uploadId={upload_id}",
|
||||
part, {"x-amz-checksum-sha1": checksum})
|
||||
assert status == 200, status
|
||||
assert headers["x-amz-checksum-sha1"] == checksum, headers
|
||||
part_etags.append(headers["etag"])
|
||||
status, content, _ = request("GET", multipart_key + f"?uploadId={upload_id}&max-parts=1")
|
||||
assert status == 200 and b"<IsTruncated>true</IsTruncated>" in content, (status, content)
|
||||
status, content, _ = request("GET", f"/{bucket}?uploads&prefix=cluster-test%2Fhttp-multipart")
|
||||
assert status == 200 and upload_id.encode() in content, (status, content)
|
||||
completion = "<CompleteMultipartUpload>" + "".join(
|
||||
f"<Part><PartNumber>{number}</PartNumber><ETag>{etag}</ETag></Part>"
|
||||
for number, etag in enumerate(part_etags, start=1)) + "</CompleteMultipartUpload>"
|
||||
status, content, _ = request("POST", multipart_key + f"?uploadId={upload_id}", completion.encode(),
|
||||
{"content-type": "application/xml"})
|
||||
assert status == 200 and b"<CompleteMultipartUploadResult>" in content, (status, content)
|
||||
status, content, headers = request("GET", multipart_key)
|
||||
assert status == 200 and content == b"hello world", (status, content)
|
||||
status, public_content = anonymous("GET", multipart_key)
|
||||
assert status == 200 and public_content == b"hello world", (status, public_content)
|
||||
assert headers["x-amz-meta-project"] == "multipart" and headers["x-amz-tagging-count"] == "1"
|
||||
status, _, headers = request("HEAD", multipart_key, extra={"x-amz-checksum-mode": "ENABLED"})
|
||||
assert status == 200 and len(base64.b64decode(headers["x-amz-checksum-crc64nvme"])) == 8, status
|
||||
status, content, _ = request("GET", f"/{bucket}?uploads&prefix=cluster-test%2Fhttp-multipart")
|
||||
assert status == 200 and upload_id.encode() not in content, (status, content)
|
||||
print("Cluster HTTP tests passed: signed objects, copies, checksums, multipart, and versioning")
|
||||
+85
-2
@@ -3,13 +3,20 @@ set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
env_file=${1:?Usage: sh scripts/test-cluster.sh /path/to/local-cluster.env}
|
||||
host_port=${CLUSTER_HOST_PORT:-9001}
|
||||
backup_dir=
|
||||
compose() { docker compose --env-file "$env_file" -f compose.cluster.yaml "$@"; }
|
||||
restore() { compose start metadata node-a node-b >/dev/null 2>&1 || true; }
|
||||
restore() {
|
||||
compose stop maintenance >/dev/null 2>&1 || true
|
||||
compose start metadata node-a node-b node-c >/dev/null 2>&1 || true
|
||||
compose exec -T metadata psql -U objectstore -d postgres -c \
|
||||
'ALTER DATABASE objectstore RESET default_transaction_read_only' >/dev/null 2>&1 || true
|
||||
if [ -n "$backup_dir" ]; then rm -rf "$backup_dir"; fi
|
||||
}
|
||||
trap restore EXIT
|
||||
compose up -d --build
|
||||
run_phase() {
|
||||
compose exec -T gateway java --add-modules jdk.httpserver,java.net.http \
|
||||
-cp /app:/app/postgresql.jar cloud.lunarsky.store.ClusterIntegrationTest "$1"
|
||||
-cp /app:/app/postgresql.jar:/app/hash4j.jar cloud.lunarsky.store.ClusterIntegrationTest "$1"
|
||||
}
|
||||
wait_ready() {
|
||||
attempt=0
|
||||
@@ -20,10 +27,24 @@ wait_ready() {
|
||||
done
|
||||
}
|
||||
run_phase basic
|
||||
run_phase multipart-stage
|
||||
compose restart gateway
|
||||
wait_ready
|
||||
part_segment=$(compose exec -T metadata psql -U objectstore -d objectstore -At -c \
|
||||
"SELECT segment_id FROM cluster_upload_segments LIMIT 1")
|
||||
printf '%s\n' "$part_segment" | grep -Eq '^[0-9a-f-]{36}$'
|
||||
part_shard=$(printf '%s' "$part_segment" | cut -c1-2)
|
||||
compose exec -T node-a sh -c 'printf corrupted > "/data/segments/$1/$2"' _ "$part_shard" "$part_segment"
|
||||
compose run --rm -T repair
|
||||
part_expected=$(compose exec -T metadata psql -U objectstore -d objectstore -At -c \
|
||||
"SELECT encode(sha256,'hex') FROM cluster_upload_segments WHERE segment_id='$part_segment'")
|
||||
part_actual=$(compose exec -T node-a sha256sum "/data/segments/$part_shard/$part_segment" | cut -d' ' -f1)
|
||||
[ "$part_expected" = "$part_actual" ]
|
||||
run_phase same-host
|
||||
run_phase concurrent
|
||||
compose stop node-a
|
||||
run_phase degraded
|
||||
run_phase multipart-complete
|
||||
compose stop node-b
|
||||
run_phase quorum-lost
|
||||
compose start node-a node-b
|
||||
@@ -40,6 +61,13 @@ expected=$(compose exec -T metadata psql -U objectstore -d objectstore -At -c \
|
||||
"SELECT encode(s.sha256,'hex') FROM cluster_segments s JOIN cluster_objects o ON o.generation=s.generation WHERE o.object_key='cluster-test/survivor' LIMIT 1")
|
||||
actual=$(compose exec -T node-a sha256sum "/data/segments/$shard/$segment_id" | cut -d' ' -f1)
|
||||
[ "$expected" = "$actual" ]
|
||||
compose exec -T metadata psql -U objectstore -d postgres -c \
|
||||
'ALTER DATABASE objectstore SET default_transaction_read_only=on' >/dev/null
|
||||
status=$(curl -sS -o /dev/null -w '%{http_code}' "http://127.0.0.1:$host_port/ready")
|
||||
[ "$status" = 503 ]
|
||||
compose exec -T metadata psql -U objectstore -d postgres -c \
|
||||
'ALTER DATABASE objectstore RESET default_transaction_read_only' >/dev/null
|
||||
wait_ready
|
||||
compose stop metadata
|
||||
status=$(curl -sS -o /dev/null -w '%{http_code}' "http://127.0.0.1:$host_port/ready")
|
||||
[ "$status" = 503 ]
|
||||
@@ -55,4 +83,59 @@ compose up -d --no-deps gateway
|
||||
wait_ready
|
||||
run_phase recovered
|
||||
run_phase joined
|
||||
compose run --rm -T repair
|
||||
run_phase balanced
|
||||
export CLUSTER_MAINTENANCE_INTERVAL_SECONDS=1
|
||||
compose --profile automatic up -d maintenance
|
||||
node_a_id=$(compose exec -T metadata psql -U objectstore -d objectstore -At -c \
|
||||
"SELECT node_id FROM cluster_nodes WHERE endpoint='http://node-a:9100'")
|
||||
segment_id=$(compose exec -T metadata psql -U objectstore -d objectstore -At -c \
|
||||
"SELECT s.segment_id FROM cluster_segments s JOIN cluster_objects o ON o.generation=s.generation WHERE '$node_a_id'::uuid = ANY(s.replica_ids) LIMIT 1")
|
||||
expected=$(compose exec -T metadata psql -U objectstore -d objectstore -At -c \
|
||||
"SELECT encode(s.sha256,'hex') FROM cluster_segments s WHERE s.segment_id='$segment_id' LIMIT 1")
|
||||
shard=$(printf '%s' "$segment_id" | cut -c1-2)
|
||||
compose exec -T node-a sh -c 'printf corrupted > "/data/segments/$1/$2"' _ "$shard" "$segment_id"
|
||||
attempt=0
|
||||
while :; do
|
||||
actual=$(compose exec -T node-a sha256sum "/data/segments/$shard/$segment_id" | cut -d' ' -f1)
|
||||
[ "$actual" = "$expected" ] && break
|
||||
attempt=$((attempt + 1))
|
||||
[ "$attempt" -lt 90 ] || { echo 'Automatic repair did not restore the replica' >&2; exit 1; }
|
||||
sleep 1
|
||||
done
|
||||
compose stop maintenance
|
||||
export CLUSTER_GC_TEST_MODE=true CLUSTER_GC_MIN_AGE_SECONDS=0
|
||||
compose stop node-c
|
||||
if gc_refusal=$(compose run --rm -T gc --apply 2>&1); then
|
||||
echo 'Cleanup proceeded while replicas needed repair' >&2
|
||||
exit 1
|
||||
fi
|
||||
printf '%s\n' "$gc_refusal" | grep -q 'Refusing cleanup while live segments need repair'
|
||||
compose start node-c
|
||||
before=$(compose exec -T metadata psql -U objectstore -d objectstore -At -c \
|
||||
'SELECT count(*) FROM cluster_gc_candidates')
|
||||
compose run --rm -T gc
|
||||
after=$(compose exec -T metadata psql -U objectstore -d objectstore -At -c \
|
||||
'SELECT count(*) FROM cluster_gc_candidates')
|
||||
[ "$before" = "$after" ]
|
||||
first_gc=$(compose run --rm -T gc --apply)
|
||||
printf '%s\n' "$first_gc" | grep -q '^orphan_candidates=[1-9]'
|
||||
printf '%s\n' "$first_gc" | grep -q '^segments_deleted=0$'
|
||||
second_gc=$(compose run --rm -T gc --apply)
|
||||
printf '%s\n' "$second_gc" | grep -q '^segments_deleted=[1-9]'
|
||||
run_phase recovered
|
||||
python3 scripts/test-cluster-http.py "$env_file" version-survivor
|
||||
run_phase verify-expanded
|
||||
backup_dir=$(mktemp -d)
|
||||
sh scripts/backup-cluster-metadata.sh "$env_file" "$backup_dir/metadata.dump"
|
||||
compose --profile recovery up -d --wait metadata-recovery
|
||||
compose exec -T metadata-recovery pg_restore -U objectstore -d objectstore --no-owner --no-acl \
|
||||
< "$backup_dir/metadata.dump"
|
||||
compose stop metadata
|
||||
compose run --rm -T --no-deps \
|
||||
-e 'POSTGRES_JDBC_URL=jdbc:postgresql://metadata:5432,metadata-recovery:5432/objectstore?connectTimeout=3&socketTimeout=10&targetServerType=primary&hostRecheckSeconds=0' \
|
||||
--entrypoint java gateway --add-modules jdk.httpserver,java.net.http \
|
||||
-cp /app:/app/postgresql.jar:/app/hash4j.jar cloud.lunarsky.store.ClusterIntegrationTest recovered
|
||||
compose start metadata
|
||||
wait_ready
|
||||
echo 'Cluster failure tests passed'
|
||||
@@ -0,0 +1,7 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
project="objectstore-metadata-test-$$"
|
||||
compose() { docker compose -p "$project" -f tests/metadata/compose.yaml "$@"; }
|
||||
trap 'compose down -v --remove-orphans >/dev/null 2>&1 || true' EXIT
|
||||
compose up --build --abort-on-container-exit --exit-code-from check check
|
||||
@@ -0,0 +1,21 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
test_dir=$(mktemp -d)
|
||||
trap 'rm -rf "$test_dir"' EXIT HUP INT TERM
|
||||
cat > "$test_dir/java" <<'EOF'
|
||||
#!/bin/sh
|
||||
printf '%s\n' "$@" > "$OBJECTSTORE_TEST_ARGS"
|
||||
EOF
|
||||
chmod +x "$test_dir/java"
|
||||
OBJECTSTORE_TEST_ARGS="$test_dir/args" PATH="$test_dir:$PATH" \
|
||||
OBJECTSTORE_REQUEST_TIMEOUT_SECONDS=300 OBJECTSTORE_RESPONSE_TIMEOUT_SECONDS=45 \
|
||||
sh scripts/start-server.sh
|
||||
grep -Fx -- '-Dsun.net.httpserver.maxReqTime=300' "$test_dir/args" >/dev/null
|
||||
grep -Fx -- '-Dsun.net.httpserver.maxRspTime=45' "$test_dir/args" >/dev/null
|
||||
if OBJECTSTORE_TEST_ARGS="$test_dir/args" PATH="$test_dir:$PATH" \
|
||||
OBJECTSTORE_REQUEST_TIMEOUT_SECONDS=86401 sh scripts/start-server.sh 2>/dev/null; then
|
||||
echo 'Oversized request timeout was accepted' >&2
|
||||
exit 1
|
||||
fi
|
||||
echo 'Server launcher timeout tests passed'
|
||||
+12
-6
@@ -1,11 +1,17 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
sh scripts/test-start-server.sh
|
||||
mkdir -p out/classes
|
||||
javac --release 21 --add-modules jdk.httpserver,java.net.http -d out/classes \
|
||||
javac --release 21 --add-modules jdk.httpserver,java.net.http -cp lib/hash4j-0.30.0.jar -d out/classes \
|
||||
src/cloud/lunarsky/store/*.java test/cloud/lunarsky/store/*.java
|
||||
java --add-modules jdk.httpserver -cp out/classes cloud.lunarsky.store.StoreTest
|
||||
java --add-modules jdk.httpserver -cp out/classes cloud.lunarsky.store.ConcurrencyTest
|
||||
java --add-modules jdk.httpserver,java.net.http -cp out/classes cloud.lunarsky.store.HttpTest
|
||||
java --add-modules jdk.httpserver,java.net.http -cp out/classes cloud.lunarsky.store.ClusterNodeTest
|
||||
java -cp out/classes cloud.lunarsky.store.CliTest
|
||||
java --add-modules jdk.httpserver -cp out/classes:lib/hash4j-0.30.0.jar cloud.lunarsky.store.StoreTest
|
||||
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.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 --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 -cp out/classes:lib/hash4j-0.30.0.jar cloud.lunarsky.store.CliTest
|
||||
bash client/scripts/test.sh
|
||||
@@ -0,0 +1,184 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import com.sun.net.httpserver.Headers;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.TreeMap;
|
||||
|
||||
final class Acl {
|
||||
static final String ALL_USERS = "http://acs.amazonaws.com/groups/global/AllUsers";
|
||||
static final String AUTHENTICATED_USERS =
|
||||
"http://acs.amazonaws.com/groups/global/AuthenticatedUsers";
|
||||
static final int READ = 1;
|
||||
static final int WRITE = 2;
|
||||
static final int READ_ACP = 4;
|
||||
static final int WRITE_ACP = 8;
|
||||
static final int FULL_CONTROL = READ | WRITE | READ_ACP | WRITE_ACP;
|
||||
private static final Map<String, Integer> PERMISSIONS = Map.of(
|
||||
"READ", READ, "WRITE", WRITE, "READ_ACP", READ_ACP,
|
||||
"WRITE_ACP", WRITE_ACP, "FULL_CONTROL", FULL_CONTROL);
|
||||
|
||||
private Acl() {}
|
||||
|
||||
static boolean allows(Map<String, String> grants, String principal, String owner, int permission) {
|
||||
if (owner.equals(principal)) return true;
|
||||
if (principal != null && (bits(grants.get(principal)) & permission) == permission) return true;
|
||||
if (principal != null && (bits(grants.get(AUTHENTICATED_USERS)) & permission) == permission)
|
||||
return true;
|
||||
return (bits(grants.get(ALL_USERS)) & permission) == permission;
|
||||
}
|
||||
|
||||
static void require(Map<String, String> grants, String principal, String owner, int permission) {
|
||||
if (!allows(grants, principal, owner, permission))
|
||||
throw new StoreException(403, "AccessDenied", "Access denied");
|
||||
}
|
||||
|
||||
static Map<String, String> fromHeaders(Headers headers, Set<String> identities) {
|
||||
String canned = SigV4.single(headers, "x-amz-acl");
|
||||
Set<String> grantNames = Set.of("x-amz-grant-read", "x-amz-grant-write",
|
||||
"x-amz-grant-read-acp", "x-amz-grant-write-acp", "x-amz-grant-full-control");
|
||||
for (String name : headers.keySet()) {
|
||||
String lower = name.toLowerCase(java.util.Locale.ROOT);
|
||||
if (lower.startsWith("x-amz-grant-") && !grantNames.contains(lower))
|
||||
throw new StoreException(501, "NotImplemented", "Unsupported ACL grant header");
|
||||
if (canned != null && grantNames.contains(lower))
|
||||
throw new StoreException(400, "InvalidRequest", "Use either a canned ACL or explicit grants");
|
||||
}
|
||||
TreeMap<String, Integer> grants = new TreeMap<>();
|
||||
if (canned != null) {
|
||||
if (!canned.equals("private") && !canned.equals("public-read") &&
|
||||
!canned.equals("authenticated-read") &&
|
||||
!canned.equals("bucket-owner-full-control"))
|
||||
throw new StoreException(400, "InvalidArgument", "Unsupported canned ACL");
|
||||
if (canned.equals("public-read")) grants.put(ALL_USERS, READ);
|
||||
if (canned.equals("authenticated-read")) grants.put(AUTHENTICATED_USERS, READ);
|
||||
}
|
||||
for (String name : new String[]{"read", "write", "read-acp", "write-acp", "full-control"}) {
|
||||
String value = SigV4.single(headers, "x-amz-grant-" + name);
|
||||
if (value == null) continue;
|
||||
int permission = PERMISSIONS.get(name.replace('-', '_').toUpperCase(java.util.Locale.ROOT));
|
||||
for (String grant : value.split(",")) {
|
||||
String entry = grant.trim();
|
||||
String principal;
|
||||
if (entry.startsWith("id=\"") && entry.endsWith("\""))
|
||||
principal = entry.substring(4, entry.length() - 1);
|
||||
else if (entry.startsWith("uri=\"") && entry.endsWith("\""))
|
||||
principal = entry.substring(5, entry.length() - 1);
|
||||
else if (entry.startsWith("emailAddress=\""))
|
||||
throw new StoreException(405, "MethodNotAllowed", "Email ACL grantees are no longer supported");
|
||||
else throw new StoreException(400, "InvalidArgument", "Invalid ACL grant");
|
||||
if (!identities.contains(principal) && !principal.equals(ALL_USERS) &&
|
||||
!principal.equals(AUTHENTICATED_USERS))
|
||||
throw new StoreException(400, "InvalidArgument", "Unknown ACL grantee");
|
||||
if (principal.equals(ALL_USERS) && permission != READ)
|
||||
throw new StoreException(400, "InvalidArgument", "Only public read is supported");
|
||||
grants.merge(principal, permission, (left, right) -> left | right);
|
||||
}
|
||||
}
|
||||
return encoded(grants);
|
||||
}
|
||||
|
||||
static Map<String, String> validate(Map<String, String> values, Set<String> identities) {
|
||||
if (values.size() > 64) throw new StoreException(400, "InvalidArgument", "Too many ACL grantees");
|
||||
TreeMap<String, String> valid = new TreeMap<>();
|
||||
for (var entry : values.entrySet()) {
|
||||
String principal = entry.getKey();
|
||||
int bits = bits(entry.getValue());
|
||||
if ((!identities.contains(principal) && !principal.equals(ALL_USERS) &&
|
||||
!principal.equals(AUTHENTICATED_USERS)) ||
|
||||
bits == 0 || (bits & ~FULL_CONTROL) != 0 ||
|
||||
principal.equals(ALL_USERS) && bits != READ)
|
||||
throw new StoreException(400, "InvalidArgument", "Invalid ACL grantee or permission");
|
||||
valid.put(principal, Integer.toString(bits));
|
||||
}
|
||||
return Map.copyOf(valid);
|
||||
}
|
||||
|
||||
static Map<String, String> fromXml(byte[] body, String owner, Set<String> identities) {
|
||||
try {
|
||||
var factory = javax.xml.parsers.DocumentBuilderFactory.newInstance();
|
||||
factory.setNamespaceAware(true);
|
||||
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
|
||||
factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
|
||||
factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
|
||||
factory.setFeature(javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, true);
|
||||
factory.setExpandEntityReferences(false);
|
||||
var document = factory.newDocumentBuilder().parse(new ByteArrayInputStream(body));
|
||||
var root = document.getDocumentElement();
|
||||
if (!root.getLocalName().equals("AccessControlPolicy")) throw new IllegalArgumentException();
|
||||
var ownerNodes = root.getElementsByTagNameNS("*", "Owner");
|
||||
var lists = root.getElementsByTagNameNS("*", "AccessControlList");
|
||||
if (ownerNodes.getLength() != 1 || lists.getLength() != 1 ||
|
||||
!owner.equals(text((org.w3c.dom.Element) ownerNodes.item(0), "ID")))
|
||||
throw new IllegalArgumentException();
|
||||
TreeMap<String, Integer> grants = new TreeMap<>();
|
||||
var nodes = ((org.w3c.dom.Element) lists.item(0)).getElementsByTagNameNS("*", "Grant");
|
||||
if (nodes.getLength() > 64) throw new IllegalArgumentException();
|
||||
for (int i = 0; i < nodes.getLength(); i++) {
|
||||
var grant = (org.w3c.dom.Element) nodes.item(i);
|
||||
var grantees = grant.getElementsByTagNameNS("*", "Grantee");
|
||||
if (grantees.getLength() != 1) throw new IllegalArgumentException();
|
||||
var grantee = (org.w3c.dom.Element) grantees.item(0);
|
||||
String type = grantee.getAttributeNS("http://www.w3.org/2001/XMLSchema-instance", "type");
|
||||
String principal = switch (type) {
|
||||
case "CanonicalUser" -> text(grantee, "ID");
|
||||
case "Group" -> text(grantee, "URI");
|
||||
case "AmazonCustomerByEmail" -> throw new StoreException(405, "MethodNotAllowed",
|
||||
"Email ACL grantees are no longer supported");
|
||||
default -> throw new IllegalArgumentException();
|
||||
};
|
||||
Integer permission = PERMISSIONS.get(text(grant, "Permission"));
|
||||
if (permission == null) throw new IllegalArgumentException();
|
||||
grants.merge(principal, permission, (left, right) -> left | right);
|
||||
}
|
||||
grants.remove(owner);
|
||||
return validate(encoded(grants), identities);
|
||||
} catch (StoreException error) { throw error; }
|
||||
catch (Exception error) {
|
||||
throw new StoreException(400, "MalformedACLError", "Invalid access control policy");
|
||||
}
|
||||
}
|
||||
|
||||
private static String text(org.w3c.dom.Element element, String name) {
|
||||
var nodes = element.getElementsByTagNameNS("*", name);
|
||||
if (nodes.getLength() != 1) throw new IllegalArgumentException();
|
||||
return nodes.item(0).getTextContent().trim();
|
||||
}
|
||||
|
||||
static String xml(Map<String, String> grants, String owner) {
|
||||
StringBuilder xml = new StringBuilder("<AccessControlPolicy xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\"><Owner><ID>")
|
||||
.append(owner).append("</ID></Owner><AccessControlList>");
|
||||
grant(xml, owner, "FULL_CONTROL", false);
|
||||
for (var entry : new TreeMap<>(grants).entrySet()) {
|
||||
if (entry.getKey().equals(owner)) continue;
|
||||
int bits = bits(entry.getValue());
|
||||
if (bits == FULL_CONTROL) grant(xml, entry.getKey(), "FULL_CONTROL",
|
||||
entry.getKey().equals(ALL_USERS) || entry.getKey().equals(AUTHENTICATED_USERS));
|
||||
else for (var permission : PERMISSIONS.entrySet())
|
||||
if (!permission.getKey().equals("FULL_CONTROL") && (bits & permission.getValue()) != 0)
|
||||
grant(xml, entry.getKey(), permission.getKey(),
|
||||
entry.getKey().equals(ALL_USERS) || entry.getKey().equals(AUTHENTICATED_USERS));
|
||||
}
|
||||
return xml.append("</AccessControlList></AccessControlPolicy>").toString();
|
||||
}
|
||||
|
||||
private static void grant(StringBuilder xml, String principal, String permission, boolean group) {
|
||||
xml.append("<Grant><Grantee xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"")
|
||||
.append(group ? "Group\"><URI>" : "CanonicalUser\"><ID>")
|
||||
.append(principal).append(group ? "</URI>" : "</ID>")
|
||||
.append("</Grantee><Permission>").append(permission).append("</Permission></Grant>");
|
||||
}
|
||||
|
||||
private static Map<String, String> encoded(Map<String, Integer> grants) {
|
||||
TreeMap<String, String> values = new TreeMap<>();
|
||||
grants.forEach((key, value) -> values.put(key, Integer.toString(value)));
|
||||
return Map.copyOf(values);
|
||||
}
|
||||
|
||||
private static int bits(String value) {
|
||||
if (value == null) return 0;
|
||||
try { return Integer.parseInt(value); }
|
||||
catch (NumberFormatException error) { return 0; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import java.io.FilterInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.Base64;
|
||||
import java.util.HexFormat;
|
||||
import java.util.zip.CRC32;
|
||||
import java.util.zip.CRC32C;
|
||||
import java.util.zip.Checksum;
|
||||
|
||||
final class AwsChunkedInputStream extends FilterInputStream {
|
||||
private static final String EMPTY_HASH = SigV4.hex(SigV4.hash(new byte[0]));
|
||||
private final SigV4.Verified authorization;
|
||||
private final long decodedLength;
|
||||
private final String trailerName;
|
||||
private final MessageDigest chunkHash;
|
||||
private final MessageDigest trailerHash;
|
||||
private final Checksum trailerCrc;
|
||||
private final XxHashes trailerXxhash;
|
||||
private long decoded;
|
||||
private long chunkLeft;
|
||||
private String suppliedSignature;
|
||||
private String previousSignature;
|
||||
private boolean finished;
|
||||
private String trailerValue;
|
||||
|
||||
AwsChunkedInputStream(InputStream input, SigV4.Verified authorization,
|
||||
long decodedLength, String trailerName) {
|
||||
super(input);
|
||||
this.authorization = authorization;
|
||||
this.decodedLength = decodedLength;
|
||||
this.trailerName = trailerName;
|
||||
this.previousSignature = authorization.signature();
|
||||
try { this.chunkHash = MessageDigest.getInstance("SHA-256"); }
|
||||
catch (java.security.NoSuchAlgorithmException error) { throw new IllegalStateException(error); }
|
||||
this.trailerCrc = trailerName == null ? null : switch (trailerName) {
|
||||
case "x-amz-checksum-crc32" -> new CRC32();
|
||||
case "x-amz-checksum-crc32c" -> new CRC32C();
|
||||
case "x-amz-checksum-crc64nvme" -> new Crc64Nvme();
|
||||
default -> null;
|
||||
};
|
||||
this.trailerXxhash = trailerName != null && java.util.Set.of("x-amz-checksum-xxhash64",
|
||||
"x-amz-checksum-xxhash3", "x-amz-checksum-xxhash128").contains(trailerName)
|
||||
? new XxHashes(trailerName.substring("x-amz-checksum-".length()).toUpperCase(java.util.Locale.ROOT))
|
||||
: null;
|
||||
String algorithm = trailerName == null ? null : switch (trailerName) {
|
||||
case "x-amz-checksum-sha1" -> "SHA-1";
|
||||
case "x-amz-checksum-sha256" -> "SHA-256";
|
||||
case "x-amz-checksum-sha512" -> "SHA-512";
|
||||
case "x-amz-checksum-md5" -> "MD5";
|
||||
default -> null;
|
||||
};
|
||||
if (trailerName != null && trailerCrc == null && trailerXxhash == null && algorithm == null)
|
||||
throw new StoreException(501, "NotImplemented", "Checksum trailer is unsupported");
|
||||
try { this.trailerHash = algorithm == null ? null : MessageDigest.getInstance(algorithm); }
|
||||
catch (java.security.NoSuchAlgorithmException error) { throw new IllegalStateException(error); }
|
||||
}
|
||||
|
||||
String trailerValue() { return trailerValue; }
|
||||
|
||||
@Override public int read() throws IOException {
|
||||
byte[] one = new byte[1];
|
||||
int count;
|
||||
do {
|
||||
count = read(one, 0, 1);
|
||||
} while (count == 0);
|
||||
return count < 0 ? -1 : one[0] & 255;
|
||||
}
|
||||
|
||||
@Override public int read(byte[] bytes, int offset, int length) throws IOException {
|
||||
java.util.Objects.checkFromIndexSize(offset, length, bytes.length);
|
||||
if (length == 0) return 0;
|
||||
if (finished) return -1;
|
||||
if (chunkLeft == 0) nextChunk();
|
||||
if (finished) return -1;
|
||||
int count = in.read(bytes, offset, (int) Math.min(length, chunkLeft));
|
||||
if (count < 0) throw invalid("Incomplete signed chunk");
|
||||
if (count == 0) return 0;
|
||||
chunkHash.update(bytes, offset, count);
|
||||
if (trailerCrc != null) trailerCrc.update(bytes, offset, count);
|
||||
if (trailerHash != null) trailerHash.update(bytes, offset, count);
|
||||
if (trailerXxhash != null) trailerXxhash.update(bytes, offset, count);
|
||||
chunkLeft -= count;
|
||||
decoded += count;
|
||||
if (chunkLeft == 0) {
|
||||
if (!line().isEmpty()) throw invalid("Missing signed chunk separator");
|
||||
finishChunk();
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
private void nextChunk() throws IOException {
|
||||
String line = line();
|
||||
int separator = line.indexOf(";chunk-signature=");
|
||||
if (separator < 1 || separator != line.lastIndexOf(";chunk-signature="))
|
||||
throw invalid("Invalid signed chunk header");
|
||||
String size = line.substring(0, separator);
|
||||
suppliedSignature = line.substring(separator + 17);
|
||||
if (!size.matches("[0-9a-fA-F]{1,16}") || !suppliedSignature.matches("[0-9a-f]{64}"))
|
||||
throw invalid("Invalid signed chunk header");
|
||||
try { chunkLeft = Long.parseUnsignedLong(size, 16); }
|
||||
catch (NumberFormatException error) { throw invalid("Invalid signed chunk size"); }
|
||||
if (chunkLeft > decodedLength - decoded) throw invalid("Signed chunks exceed decoded length");
|
||||
chunkHash.reset();
|
||||
if (chunkLeft == 0) finishPayload();
|
||||
}
|
||||
|
||||
private void finishPayload() throws IOException {
|
||||
finishChunk();
|
||||
if (decoded != decodedLength) throw invalid("Decoded length mismatch");
|
||||
if (trailerName == null) {
|
||||
if (!line().isEmpty()) throw invalid("Invalid signed chunk ending");
|
||||
} else {
|
||||
verifyTrailer();
|
||||
}
|
||||
if (in.read() != -1) throw invalid("Extra bytes after signed payload");
|
||||
finished = true;
|
||||
}
|
||||
|
||||
private void verifyTrailer() throws IOException {
|
||||
String trailer = line();
|
||||
if (!trailer.startsWith(trailerName + ":")) throw invalid("Missing signed checksum trailer");
|
||||
trailerValue = trailer.substring(trailerName.length() + 1);
|
||||
if (!Base64.getEncoder().encodeToString(trailerChecksum()).equals(trailerValue))
|
||||
throw new StoreException(400, "BadDigest", "Checksum trailer mismatch");
|
||||
String signature = line();
|
||||
if (!signature.matches("x-amz-trailer-signature:[0-9a-f]{64}"))
|
||||
throw invalid("Missing trailer signature");
|
||||
String toSign = "AWS4-HMAC-SHA256-TRAILER\n" + authorization.date() + "\n" +
|
||||
authorization.scope() + "\n" + previousSignature + "\n" +
|
||||
SigV4.hex(SigV4.hash((trailerName + ":" + trailerValue + "\n")
|
||||
.getBytes(StandardCharsets.UTF_8)));
|
||||
String expected = SigV4.hex(SigV4.hmac(authorization.signingKey(), toSign));
|
||||
if (!MessageDigest.isEqual(expected.getBytes(StandardCharsets.US_ASCII),
|
||||
signature.substring(24).getBytes(StandardCharsets.US_ASCII)))
|
||||
throw invalid("Trailer signature mismatch");
|
||||
if (!line().isEmpty()) throw invalid("Invalid trailer ending");
|
||||
}
|
||||
|
||||
private byte[] trailerChecksum() {
|
||||
if (trailerCrc == null)
|
||||
return trailerXxhash != null ? trailerXxhash.digest() : trailerHash.digest();
|
||||
long value = trailerCrc.getValue();
|
||||
byte[] actual = new byte[trailerName.equals("x-amz-checksum-crc64nvme") ? 8 : 4];
|
||||
for (int i = actual.length - 1; i >= 0; i--) {
|
||||
actual[i] = (byte) value;
|
||||
value >>>= 8;
|
||||
}
|
||||
return actual;
|
||||
}
|
||||
|
||||
private void finishChunk() throws IOException {
|
||||
String toSign = "AWS4-HMAC-SHA256-PAYLOAD\n" + authorization.date() + "\n" +
|
||||
authorization.scope() + "\n" + previousSignature + "\n" + EMPTY_HASH + "\n" +
|
||||
SigV4.hex(chunkHash.digest());
|
||||
byte[] expected = SigV4.hmac(authorization.signingKey(), toSign);
|
||||
if (!MessageDigest.isEqual(expected, HexFormat.of().parseHex(suppliedSignature)))
|
||||
throw invalid("Signed chunk signature mismatch");
|
||||
previousSignature = suppliedSignature;
|
||||
}
|
||||
|
||||
private String line() throws IOException {
|
||||
byte[] bytes = new byte[512];
|
||||
int count = 0;
|
||||
while (count < bytes.length) {
|
||||
int value = in.read();
|
||||
if (value < 0) throw invalid("Incomplete signed chunk framing");
|
||||
if (value == '\r') {
|
||||
if (in.read() != '\n') throw invalid("Invalid signed chunk line ending");
|
||||
return new String(bytes, 0, count, StandardCharsets.US_ASCII);
|
||||
}
|
||||
if (value < 32 || value > 126) throw invalid("Invalid signed chunk line");
|
||||
bytes[count++] = (byte) value;
|
||||
}
|
||||
throw invalid("Signed chunk header is too long");
|
||||
}
|
||||
|
||||
private static StoreException invalid(String message) {
|
||||
return new StoreException(400, "InvalidRequest", message);
|
||||
}
|
||||
}
|
||||
@@ -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-"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,310 @@
|
||||
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.size() >= 1 && query.size() <= 2 &&
|
||||
query.keySet().stream().allMatch(java.util.Set.of("ownershipControls", "x-id")::contains) &&
|
||||
query.containsKey("ownershipControls") && query.get("ownershipControls").isEmpty()) {
|
||||
access.requireOwner(principal);
|
||||
if (method.equals("GET")) {
|
||||
S3Request.requireEmptyBody(exchange, hash);
|
||||
S3Xml.sendXml(exchange, 200, BucketSecurity.ownershipXml(store.bucket(bucketName).ownership()));
|
||||
} else if (method.equals("PUT")) {
|
||||
byte[] body = S3Request.signedBody(exchange, hash, 65536);
|
||||
S3Request.verifyContentMd5(exchange.getRequestHeaders(), body);
|
||||
store.setBucketOwnership(bucketName, BucketSecurity.parseOwnership(body));
|
||||
exchange.sendResponseHeaders(200, -1);
|
||||
} else if (method.equals("DELETE")) {
|
||||
S3Request.requireEmptyBody(exchange, hash);
|
||||
store.setBucketOwnership(bucketName, ObjectStorage.ObjectOwnership.OBJECT_WRITER);
|
||||
exchange.sendResponseHeaders(204, -1);
|
||||
} else S3Request.unsupported("Ownership controls operation");
|
||||
return;
|
||||
}
|
||||
if (query.size() >= 1 && query.size() <= 2 &&
|
||||
query.keySet().stream().allMatch(java.util.Set.of("publicAccessBlock", "x-id")::contains) &&
|
||||
query.containsKey("publicAccessBlock") && query.get("publicAccessBlock").isEmpty()) {
|
||||
access.requireOwner(principal);
|
||||
if (method.equals("GET")) {
|
||||
S3Request.requireEmptyBody(exchange, hash);
|
||||
S3Xml.sendXml(exchange, 200, BucketSecurity.publicAccessXml(
|
||||
store.bucket(bucketName).publicAccessBlock()));
|
||||
} else if (method.equals("PUT")) {
|
||||
byte[] body = S3Request.signedBody(exchange, hash, 65536);
|
||||
S3Request.verifyContentMd5(exchange.getRequestHeaders(), body);
|
||||
store.setPublicAccessBlock(bucketName, BucketSecurity.parsePublicAccess(body));
|
||||
exchange.sendResponseHeaders(200, -1);
|
||||
} else if (method.equals("DELETE")) {
|
||||
S3Request.requireEmptyBody(exchange, hash);
|
||||
store.setPublicAccessBlock(bucketName, ObjectStorage.PublicAccessBlock.open());
|
||||
exchange.sendResponseHeaders(204, -1);
|
||||
} else S3Request.unsupported("Public access block operation");
|
||||
return;
|
||||
}
|
||||
if (query.size() >= 1 && query.size() <= 2 &&
|
||||
query.keySet().stream().allMatch(java.util.Set.of("policy", "x-id")::contains) &&
|
||||
query.containsKey("policy") && query.get("policy").isEmpty()) {
|
||||
access.requireOwner(principal);
|
||||
var current = store.bucket(bucketName);
|
||||
if (method.equals("GET")) {
|
||||
S3Request.requireEmptyBody(exchange, hash);
|
||||
if (current.policy() == null)
|
||||
throw new StoreException(404, "NoSuchBucketPolicy", "Bucket has no policy");
|
||||
byte[] body = current.policy().getBytes(StandardCharsets.UTF_8);
|
||||
exchange.getResponseHeaders().set("Content-Type", "application/json");
|
||||
exchange.sendResponseHeaders(200, body.length);
|
||||
exchange.getResponseBody().write(body);
|
||||
} else if (method.equals("PUT")) {
|
||||
byte[] body = S3Request.signedBody(exchange, hash, 20480);
|
||||
S3Request.verifyContentMd5(exchange.getRequestHeaders(), body);
|
||||
String policy = new String(body, StandardCharsets.UTF_8);
|
||||
BucketPolicy parsed = BucketPolicy.parse(policy, bucketName);
|
||||
if (current.publicAccessBlock().blockPublicPolicy() && parsed.publicAllow())
|
||||
throw new StoreException(403, "AccessDenied", "Public bucket policies are blocked");
|
||||
store.setBucketPolicy(bucketName, policy);
|
||||
exchange.sendResponseHeaders(204, -1);
|
||||
} else if (method.equals("DELETE")) {
|
||||
S3Request.requireEmptyBody(exchange, hash);
|
||||
store.setBucketPolicy(bucketName, null);
|
||||
exchange.sendResponseHeaders(204, -1);
|
||||
} else S3Request.unsupported("Bucket policy operation");
|
||||
return;
|
||||
}
|
||||
if (query.containsKey("acl") && query.get("acl").isEmpty() &&
|
||||
query.keySet().stream().allMatch(java.util.Set.of("acl", "x-id")::contains) &&
|
||||
(!query.containsKey("x-id") ||
|
||||
query.get("x-id").equals(method.equals("GET") ? "GetBucketAcl" : "PutBucketAcl")) &&
|
||||
(method.equals("GET") || method.equals("PUT"))) {
|
||||
var current = store.bucket(bucketName);
|
||||
access.requireBucket(bucketName, principal,
|
||||
method.equals("GET") ? Acl.READ_ACP : Acl.WRITE_ACP);
|
||||
if (method.equals("GET")) {
|
||||
S3Request.requireEmptyBody(exchange, hash);
|
||||
S3Xml.sendXml(exchange, 200, Acl.xml(
|
||||
current.ownership() == ObjectStorage.ObjectOwnership.BUCKET_OWNER_ENFORCED
|
||||
? Map.of() : current.acl(), owner));
|
||||
} else {
|
||||
if (current.ownership() == ObjectStorage.ObjectOwnership.BUCKET_OWNER_ENFORCED)
|
||||
throw new StoreException(400, "AccessControlListNotSupported", "ACLs are disabled for this bucket");
|
||||
if (exchange.getRequestHeaders().containsKey("x-amz-acl") ||
|
||||
exchange.getRequestHeaders().keySet().stream().anyMatch(
|
||||
name -> name.toLowerCase(Locale.ROOT).startsWith("x-amz-grant-"))) {
|
||||
S3Request.requireEmptyBody(exchange, hash);
|
||||
S3Request.verifyContentMd5(exchange.getRequestHeaders(), new byte[0]);
|
||||
Map<String, String> acl = Acl.fromHeaders(exchange.getRequestHeaders(),
|
||||
authentication.identities());
|
||||
BucketSecurity.checkAcl(current, exchange.getRequestHeaders(), acl, true);
|
||||
store.setBucketAcl(bucketName, acl);
|
||||
} else {
|
||||
byte[] body = S3Request.signedBody(exchange, hash, 65536);
|
||||
S3Request.verifyContentMd5(exchange.getRequestHeaders(), body);
|
||||
Map<String, String> acl = Acl.fromXml(body, owner, authentication.identities());
|
||||
BucketSecurity.checkAcl(current, exchange.getRequestHeaders(), acl, true);
|
||||
store.setBucketAcl(bucketName, acl);
|
||||
}
|
||||
exchange.sendResponseHeaders(200, -1);
|
||||
}
|
||||
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);
|
||||
String requestedOwnership = SigV4.single(exchange.getRequestHeaders(), "x-amz-object-ownership");
|
||||
ObjectStorage.ObjectOwnership ownership = requestedOwnership == null
|
||||
? ObjectStorage.ObjectOwnership.BUCKET_OWNER_ENFORCED
|
||||
: BucketSecurity.ownership(requestedOwnership);
|
||||
Map<String, String> acl = Acl.fromHeaders(exchange.getRequestHeaders(),
|
||||
authentication.identities());
|
||||
BucketSecurity.checkAcl(new ObjectStorage.Bucket(bucketName, 0,
|
||||
ObjectStorage.VersioningState.NEVER, Map.of(), ownership,
|
||||
ObjectStorage.PublicAccessBlock.secure(), null),
|
||||
exchange.getRequestHeaders(), acl, false);
|
||||
store.createBucket(bucketName);
|
||||
if (requestedOwnership != null &&
|
||||
ownership != ObjectStorage.ObjectOwnership.BUCKET_OWNER_ENFORCED)
|
||||
store.setBucketOwnership(bucketName, ownership);
|
||||
if (!acl.isEmpty()) store.setBucketAcl(bucketName, acl);
|
||||
exchange.getResponseHeaders().set("Location", "/" + bucketName);
|
||||
exchange.sendResponseHeaders(200, -1);
|
||||
}
|
||||
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>"").append(entry.metadata().etag())
|
||||
.append(""</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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
final class BucketPolicy {
|
||||
private static final BucketPolicy EMPTY = new BucketPolicy(List.of());
|
||||
private record Statement(boolean allow, List<String> principals, List<String> actions,
|
||||
List<String> resources) {
|
||||
boolean matches(String principal, String action, String resource) {
|
||||
return (principals.contains("*") || principal != null && principals.contains(principal)) &&
|
||||
actions.stream().anyMatch(pattern -> glob(pattern, action)) &&
|
||||
resources.stream().anyMatch(pattern -> glob(pattern, resource));
|
||||
}
|
||||
}
|
||||
|
||||
private final List<Statement> statements;
|
||||
private final boolean publicAllow;
|
||||
|
||||
private BucketPolicy(List<Statement> statements) {
|
||||
this.statements = List.copyOf(statements);
|
||||
this.publicAllow = statements.stream().anyMatch(
|
||||
statement -> statement.allow() && statement.principals().contains("*"));
|
||||
}
|
||||
|
||||
static BucketPolicy empty() { return EMPTY; }
|
||||
|
||||
boolean publicAllow() { return publicAllow; }
|
||||
|
||||
int decide(String principal, String action, String resource) {
|
||||
boolean allowed = false;
|
||||
for (Statement statement : statements) {
|
||||
if (!statement.matches(principal, action, resource)) continue;
|
||||
if (!statement.allow()) return -1;
|
||||
allowed = true;
|
||||
}
|
||||
return allowed ? 1 : 0;
|
||||
}
|
||||
|
||||
static BucketPolicy parse(String json, String bucket) {
|
||||
return parse(json, bucket, false);
|
||||
}
|
||||
|
||||
static BucketPolicy parseIdentity(String json) {
|
||||
return parse(json, null, true);
|
||||
}
|
||||
|
||||
private static BucketPolicy parse(String json, String bucket, boolean identity) {
|
||||
if (json == null || json.isBlank() || json.getBytes(StandardCharsets.UTF_8).length > 20480)
|
||||
throw invalid();
|
||||
Object parsed = new Parser(json).parse();
|
||||
Map<String, Object> policy = object(parsed);
|
||||
if (!policy.keySet().stream().allMatch(Set.of("Version", "Id", "Statement")::contains) ||
|
||||
!"2012-10-17".equals(policy.get("Version"))) throw invalid();
|
||||
Object raw = policy.get("Statement");
|
||||
if (raw == null) throw invalid();
|
||||
List<?> entries = raw instanceof List<?> list ? list : List.of(raw);
|
||||
if (entries.isEmpty() || entries.size() > 64) throw invalid();
|
||||
List<Statement> statements = new ArrayList<>();
|
||||
for (Object entry : entries) {
|
||||
Map<String, Object> item = object(entry);
|
||||
Set<String> keys = identity ? Set.of("Sid", "Effect", "Action", "Resource") :
|
||||
Set.of("Sid", "Effect", "Principal", "Action", "Resource");
|
||||
if (!item.keySet().stream().allMatch(keys::contains))
|
||||
throw invalid();
|
||||
boolean allow;
|
||||
if ("Allow".equals(item.get("Effect"))) allow = true;
|
||||
else if ("Deny".equals(item.get("Effect"))) allow = false;
|
||||
else throw invalid();
|
||||
Object principal = item.get("Principal");
|
||||
List<String> principals = identity ? List.of("*") : principal instanceof Map<?, ?> map
|
||||
? strings(object(map).get("AWS")) : strings(principal);
|
||||
if (!identity && principal instanceof Map<?, ?> map && !map.keySet().equals(Set.of("AWS")))
|
||||
throw invalid();
|
||||
for (String name : principals)
|
||||
if (!name.equals("*") && !name.matches("[A-Za-z0-9]{16,128}")) throw invalid();
|
||||
List<String> actions = strings(item.get("Action"));
|
||||
for (String action : actions)
|
||||
if (!action.matches("s3:[A-Za-z*]+")) throw invalid();
|
||||
List<String> resources = strings(item.get("Resource"));
|
||||
String bucketArn = "arn:aws:s3:::" + bucket;
|
||||
for (String resource : resources)
|
||||
if (identity ? !resource.matches("arn:aws:s3:::[a-z0-9*?][a-z0-9*?.-]{0,62}(/[^\\p{Cntrl}]+)?") :
|
||||
!resource.equals(bucketArn) && !resource.startsWith(bucketArn + "/")) throw invalid();
|
||||
statements.add(new Statement(allow, principals, actions, resources));
|
||||
}
|
||||
return new BucketPolicy(statements);
|
||||
}
|
||||
|
||||
private static List<String> strings(Object value) {
|
||||
if (value == null) throw invalid();
|
||||
List<?> values = value instanceof List<?> list ? list : List.of(value);
|
||||
if (values.isEmpty() || values.size() > 64) throw invalid();
|
||||
List<String> result = new ArrayList<>();
|
||||
for (Object item : values) {
|
||||
if (!(item instanceof String text) || text.isBlank() || text.length() > 1024)
|
||||
throw invalid();
|
||||
result.add(text);
|
||||
}
|
||||
return List.copyOf(result);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static Map<String, Object> object(Object value) {
|
||||
if (!(value instanceof Map<?, ?>)) throw invalid();
|
||||
return (Map<String, Object>) value;
|
||||
}
|
||||
|
||||
private static StoreException invalid() {
|
||||
return new StoreException(400, "MalformedPolicy", "Unsupported or malformed bucket policy");
|
||||
}
|
||||
|
||||
private static boolean glob(String pattern, String text) {
|
||||
int p = 0, t = 0, star = -1, retry = 0;
|
||||
while (t < text.length()) {
|
||||
if (p < pattern.length() && pattern.charAt(p) == text.charAt(t)) { p++; t++; }
|
||||
else if (p < pattern.length() && pattern.charAt(p) == '*') { star = p++; retry = t; }
|
||||
else if (star >= 0) { p = star + 1; t = ++retry; }
|
||||
else return false;
|
||||
}
|
||||
while (p < pattern.length() && pattern.charAt(p) == '*') p++;
|
||||
return p == pattern.length();
|
||||
}
|
||||
|
||||
private static final class Parser {
|
||||
private final String input;
|
||||
private int index;
|
||||
|
||||
Parser(String input) { this.input = input; }
|
||||
|
||||
Object parse() {
|
||||
Object value = value(0);
|
||||
space();
|
||||
if (index != input.length()) throw invalid();
|
||||
return value;
|
||||
}
|
||||
|
||||
private Object value(int depth) {
|
||||
if (depth > 16) throw invalid();
|
||||
space();
|
||||
if (index == input.length()) throw invalid();
|
||||
return switch (input.charAt(index)) {
|
||||
case '"' -> string();
|
||||
case '{' -> object(depth + 1);
|
||||
case '[' -> array(depth + 1);
|
||||
default -> throw invalid();
|
||||
};
|
||||
}
|
||||
|
||||
private Map<String, Object> object(int depth) {
|
||||
index++;
|
||||
Map<String, Object> map = new LinkedHashMap<>();
|
||||
space();
|
||||
if (take('}')) return map;
|
||||
do {
|
||||
space();
|
||||
if (index == input.length() || input.charAt(index) != '"') throw invalid();
|
||||
String key = string();
|
||||
space();
|
||||
expect(':');
|
||||
if (map.putIfAbsent(key, value(depth)) != null) throw invalid();
|
||||
space();
|
||||
if (take('}')) return map;
|
||||
expect(',');
|
||||
} while (true);
|
||||
}
|
||||
|
||||
private List<Object> array(int depth) {
|
||||
index++;
|
||||
List<Object> list = new ArrayList<>();
|
||||
space();
|
||||
if (take(']')) return list;
|
||||
do {
|
||||
if (list.size() >= 64) throw invalid();
|
||||
list.add(value(depth));
|
||||
space();
|
||||
if (take(']')) return list;
|
||||
expect(',');
|
||||
} while (true);
|
||||
}
|
||||
|
||||
private String string() {
|
||||
expect('"');
|
||||
StringBuilder result = new StringBuilder();
|
||||
while (index < input.length()) {
|
||||
char c = input.charAt(index++);
|
||||
if (c == '"') return result.toString();
|
||||
if (c < 0x20) throw invalid();
|
||||
if (c != '\\') { result.append(c); continue; }
|
||||
if (index == input.length()) throw invalid();
|
||||
char escape = input.charAt(index++);
|
||||
switch (escape) {
|
||||
case '"', '\\', '/' -> result.append(escape);
|
||||
case 'b' -> result.append('\b');
|
||||
case 'f' -> result.append('\f');
|
||||
case 'n' -> result.append('\n');
|
||||
case 'r' -> result.append('\r');
|
||||
case 't' -> result.append('\t');
|
||||
case 'u' -> {
|
||||
if (index + 4 > input.length()) throw invalid();
|
||||
try { result.append((char) Integer.parseInt(input.substring(index, index + 4), 16)); }
|
||||
catch (NumberFormatException error) { throw invalid(); }
|
||||
index += 4;
|
||||
}
|
||||
default -> throw invalid();
|
||||
}
|
||||
}
|
||||
throw invalid();
|
||||
}
|
||||
|
||||
private void space() {
|
||||
while (index < input.length() && Character.isWhitespace(input.charAt(index))) index++;
|
||||
}
|
||||
|
||||
private boolean take(char expected) {
|
||||
if (index < input.length() && input.charAt(index) == expected) { index++; return true; }
|
||||
return false;
|
||||
}
|
||||
|
||||
private void expect(char expected) {
|
||||
if (!take(expected)) throw invalid();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import com.sun.net.httpserver.Headers;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import javax.xml.XMLConstants;
|
||||
import javax.xml.parsers.DocumentBuilderFactory;
|
||||
import org.w3c.dom.Element;
|
||||
|
||||
final class BucketSecurity {
|
||||
private BucketSecurity() { }
|
||||
|
||||
static String ownershipName(ObjectStorage.ObjectOwnership ownership) {
|
||||
return switch (ownership) {
|
||||
case BUCKET_OWNER_ENFORCED -> "BucketOwnerEnforced";
|
||||
case BUCKET_OWNER_PREFERRED -> "BucketOwnerPreferred";
|
||||
case OBJECT_WRITER -> "ObjectWriter";
|
||||
};
|
||||
}
|
||||
|
||||
static ObjectStorage.ObjectOwnership ownership(String value) {
|
||||
return switch (value) {
|
||||
case "BucketOwnerEnforced" -> ObjectStorage.ObjectOwnership.BUCKET_OWNER_ENFORCED;
|
||||
case "BucketOwnerPreferred" -> ObjectStorage.ObjectOwnership.BUCKET_OWNER_PREFERRED;
|
||||
case "ObjectWriter" -> ObjectStorage.ObjectOwnership.OBJECT_WRITER;
|
||||
default -> throw new StoreException(400, "InvalidArgument", "Invalid object ownership setting");
|
||||
};
|
||||
}
|
||||
|
||||
static String ownershipXml(ObjectStorage.ObjectOwnership ownership) {
|
||||
return "<OwnershipControls xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">" +
|
||||
"<Rule><ObjectOwnership>" + ownershipName(ownership) +
|
||||
"</ObjectOwnership></Rule></OwnershipControls>";
|
||||
}
|
||||
|
||||
static ObjectStorage.ObjectOwnership parseOwnership(byte[] body) {
|
||||
Element root = root(body, "OwnershipControls");
|
||||
Element rule = onlyChild(root, "Rule");
|
||||
return ownership(onlyChild(rule, "ObjectOwnership").getTextContent().trim());
|
||||
}
|
||||
|
||||
static String publicAccessXml(ObjectStorage.PublicAccessBlock block) {
|
||||
return "<PublicAccessBlockConfiguration xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">" +
|
||||
"<BlockPublicAcls>" + block.blockPublicAcls() + "</BlockPublicAcls>" +
|
||||
"<IgnorePublicAcls>" + block.ignorePublicAcls() + "</IgnorePublicAcls>" +
|
||||
"<BlockPublicPolicy>" + block.blockPublicPolicy() + "</BlockPublicPolicy>" +
|
||||
"<RestrictPublicBuckets>" + block.restrictPublicBuckets() +
|
||||
"</RestrictPublicBuckets></PublicAccessBlockConfiguration>";
|
||||
}
|
||||
|
||||
static ObjectStorage.PublicAccessBlock parsePublicAccess(byte[] body) {
|
||||
Element root = root(body, "PublicAccessBlockConfiguration");
|
||||
if (elements(root) != 4) malformed();
|
||||
return new ObjectStorage.PublicAccessBlock(
|
||||
bool(onlyNamedChild(root, "BlockPublicAcls")),
|
||||
bool(onlyNamedChild(root, "IgnorePublicAcls")),
|
||||
bool(onlyNamedChild(root, "BlockPublicPolicy")),
|
||||
bool(onlyNamedChild(root, "RestrictPublicBuckets")));
|
||||
}
|
||||
|
||||
static void checkAcl(ObjectStorage.Bucket bucket, Headers headers, Map<String, String> acl,
|
||||
boolean aclOperation) {
|
||||
if (bucket.ownership() == ObjectStorage.ObjectOwnership.BUCKET_OWNER_ENFORCED) {
|
||||
String canned = SigV4.single(headers, "x-amz-acl");
|
||||
if (aclOperation || !acl.isEmpty() ||
|
||||
canned != null && !canned.equals("bucket-owner-full-control"))
|
||||
throw new StoreException(400, "AccessControlListNotSupported", "ACLs are disabled for this bucket");
|
||||
}
|
||||
if (bucket.publicAccessBlock().blockPublicAcls() && isPublic(acl))
|
||||
throw new StoreException(403, "AccessDenied", "Public ACLs are blocked for this bucket");
|
||||
}
|
||||
|
||||
static boolean allowsAcl(ObjectStorage.Bucket bucket, Map<String, String> acl,
|
||||
String principal, String owner, int permission) {
|
||||
if (bucket.ownership() == ObjectStorage.ObjectOwnership.BUCKET_OWNER_ENFORCED)
|
||||
return owner.equals(principal);
|
||||
if (bucket.publicAccessBlock().ignorePublicAcls() && isPublicPrincipal(principal))
|
||||
return false;
|
||||
if (bucket.publicAccessBlock().ignorePublicAcls())
|
||||
acl = acl.entrySet().stream()
|
||||
.filter(entry -> !isPublicPrincipal(entry.getKey()))
|
||||
.collect(java.util.stream.Collectors.toUnmodifiableMap(Map.Entry::getKey, Map.Entry::getValue));
|
||||
return Acl.allows(acl, principal, owner, permission);
|
||||
}
|
||||
|
||||
static boolean isPublic(Map<String, String> acl) {
|
||||
return acl.containsKey(Acl.ALL_USERS) || acl.containsKey(Acl.AUTHENTICATED_USERS);
|
||||
}
|
||||
|
||||
private static boolean isPublicPrincipal(String principal) {
|
||||
return Acl.ALL_USERS.equals(principal) || Acl.AUTHENTICATED_USERS.equals(principal);
|
||||
}
|
||||
|
||||
private static boolean bool(Element element) {
|
||||
if (elements(element) != 0) malformed();
|
||||
return switch (element.getTextContent().trim().toLowerCase(java.util.Locale.ROOT)) {
|
||||
case "true" -> true;
|
||||
case "false" -> false;
|
||||
default -> throw new StoreException(400, "MalformedXML", "Invalid public access block setting");
|
||||
};
|
||||
}
|
||||
|
||||
private static Element root(byte[] body, String name) {
|
||||
try {
|
||||
var factory = DocumentBuilderFactory.newInstance();
|
||||
factory.setNamespaceAware(true);
|
||||
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
|
||||
factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
|
||||
factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
|
||||
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
|
||||
factory.setExpandEntityReferences(false);
|
||||
Element root = factory.newDocumentBuilder().parse(new ByteArrayInputStream(body)).getDocumentElement();
|
||||
if (!name.equals(root.getLocalName())) malformed();
|
||||
return root;
|
||||
} catch (StoreException error) { throw error; }
|
||||
catch (Exception error) { throw new StoreException(400, "MalformedXML", "Invalid bucket configuration"); }
|
||||
}
|
||||
|
||||
private static Element onlyChild(Element parent, String name) {
|
||||
if (elements(parent) != 1) malformed();
|
||||
return onlyNamedChild(parent, name);
|
||||
}
|
||||
|
||||
private static Element onlyNamedChild(Element parent, String name) {
|
||||
var children = parent.getChildNodes();
|
||||
Element found = null;
|
||||
for (int i = 0; i < children.getLength(); i++) {
|
||||
if (children.item(i) instanceof Element child && name.equals(child.getLocalName())) {
|
||||
if (found != null) malformed();
|
||||
found = child;
|
||||
}
|
||||
}
|
||||
if (found == null) malformed();
|
||||
return found;
|
||||
}
|
||||
|
||||
private static int elements(Element parent) {
|
||||
int count = 0;
|
||||
var children = parent.getChildNodes();
|
||||
for (int i = 0; i < children.getLength(); i++)
|
||||
if (children.item(i) instanceof Element) count++;
|
||||
return count;
|
||||
}
|
||||
|
||||
private static void malformed() {
|
||||
throw new StoreException(400, "MalformedXML", "Invalid bucket configuration");
|
||||
}
|
||||
}
|
||||
@@ -79,6 +79,15 @@ public final class Cli {
|
||||
try (var paths = Files.walk(objects)) {
|
||||
for (Path path : paths.filter(Files::isRegularFile).toList()) inspectObject(objects, path, verify, report);
|
||||
}
|
||||
Path versions = root.resolve("versions");
|
||||
if (Files.isDirectory(versions)) {
|
||||
try (var paths = Files.walk(versions)) {
|
||||
for (Path path : paths.filter(Files::isRegularFile).toList()) {
|
||||
if (!path.getFileName().toString().equals("manifest"))
|
||||
inspectObject(versions, path, verify, report);
|
||||
}
|
||||
}
|
||||
}
|
||||
Path multipart = root.resolve("multipart");
|
||||
if (Files.isDirectory(multipart)) {
|
||||
try (var uploads = Files.list(multipart)) {
|
||||
@@ -100,7 +109,9 @@ public final class Cli {
|
||||
if (meta.key() == null) report.legacyObjects++;
|
||||
else {
|
||||
String id = SigV4.hex(SigV4.hash((meta.bucket() + "/" + meta.key()).getBytes(StandardCharsets.UTF_8)));
|
||||
Path expected = objects.resolve(id.substring(0, 2)).resolve(id);
|
||||
Path expected = objects.getFileName().toString().equals("versions")
|
||||
? objects.resolve(id.substring(0, 2)).resolve(id).resolve(path.getFileName())
|
||||
: objects.resolve(id.substring(0, 2)).resolve(id);
|
||||
if (!path.equals(expected)) report.problem("Mismatched object path: " + path);
|
||||
}
|
||||
if (size - record.headerLength() != meta.length()) {
|
||||
@@ -109,7 +120,9 @@ public final class Cli {
|
||||
}
|
||||
if (verify) {
|
||||
MessageDigest sha = digest("SHA-256"), md5 = digest("MD5");
|
||||
byte[] buffer = new byte[65536]; long count = 0; int n;
|
||||
byte[] buffer = new byte[65536];
|
||||
long count = 0;
|
||||
int n;
|
||||
while ((n = input.read(buffer)) != -1) {
|
||||
count += n;
|
||||
sha.update(buffer, 0, n);
|
||||
|
||||
@@ -0,0 +1,253 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import com.sun.net.httpserver.HttpExchange;
|
||||
import java.io.FilterInputStream;
|
||||
import java.io.FilterOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.net.InetAddress;
|
||||
import java.net.UnknownHostException;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
final class ClientLimits {
|
||||
private static final int MAX_CLIENTS = 10_000;
|
||||
private static final long IDLE_NANOS = 300_000_000_000L;
|
||||
private final int requestsPerSecond;
|
||||
private final int requestBurst;
|
||||
private final long bytesPerSecond;
|
||||
private final long byteBurst;
|
||||
private final int maxInFlight;
|
||||
private final Set<String> trustedProxies;
|
||||
private final Map<String, Client> clients = new HashMap<>();
|
||||
private long admissions;
|
||||
|
||||
private ClientLimits(int requestsPerSecond, int requestBurst, long bytesPerSecond,
|
||||
long byteBurst, int maxInFlight, Set<String> trustedProxies) {
|
||||
this.requestsPerSecond = requestsPerSecond;
|
||||
this.requestBurst = requestBurst;
|
||||
this.bytesPerSecond = bytesPerSecond;
|
||||
this.byteBurst = byteBurst;
|
||||
this.maxInFlight = maxInFlight;
|
||||
this.trustedProxies = trustedProxies;
|
||||
}
|
||||
|
||||
static ClientLimits disabled() {
|
||||
return new ClientLimits(0, 0, 0, 0, 0, Set.of());
|
||||
}
|
||||
|
||||
static ClientLimits fromEnvironment(Map<String, String> environment) {
|
||||
int requests = number(environment, "PUBLIC_REQUESTS_PER_SECOND", 0);
|
||||
int requestBurst = number(environment, "PUBLIC_REQUEST_BURST", requests);
|
||||
long bytes = longNumber(environment, "PUBLIC_BYTES_PER_SECOND", 0);
|
||||
long byteBurst = longNumber(environment, "PUBLIC_BYTE_BURST", bytes);
|
||||
int inFlight = number(environment, "PUBLIC_MAX_IN_FLIGHT_PER_IP",
|
||||
requests > 0 || bytes > 0 ? 8 : 0);
|
||||
if (requests < 0 || requestBurst < 0 || bytes < 0 || byteBurst < 0 || inFlight < 0 ||
|
||||
requests > 0 && requestBurst < 1 || requests == 0 && requestBurst != 0 ||
|
||||
bytes > 0 && (byteBurst < 1 || byteBurst > 1_073_741_824L) ||
|
||||
bytes == 0 && byteBurst != 0 ||
|
||||
(requests > 0 || bytes > 0) && inFlight < 1)
|
||||
throw new IllegalArgumentException("Invalid public client limits");
|
||||
Set<String> proxies = new HashSet<>();
|
||||
String configured = environment.getOrDefault("PUBLIC_TRUSTED_PROXY_IPS", "").trim();
|
||||
if (!configured.isEmpty()) {
|
||||
for (String item : configured.split(",", -1))
|
||||
proxies.add(numericAddress(item.trim()).getHostAddress());
|
||||
}
|
||||
if (requests == 0 && bytes == 0 && inFlight == 0 && !proxies.isEmpty())
|
||||
throw new IllegalArgumentException("Trusted proxy IPs require public client limits");
|
||||
return new ClientLimits(requests, requestBurst, bytes, byteBurst, inFlight, Set.copyOf(proxies));
|
||||
}
|
||||
|
||||
private static int number(Map<String, String> environment, String name, int fallback) {
|
||||
String value = environment.get(name);
|
||||
if (value == null || value.isBlank()) return fallback;
|
||||
try { return Integer.parseInt(value); }
|
||||
catch (NumberFormatException error) { throw new IllegalArgumentException("Invalid " + name, error); }
|
||||
}
|
||||
|
||||
private static long longNumber(Map<String, String> environment, String name, long fallback) {
|
||||
String value = environment.get(name);
|
||||
if (value == null || value.isBlank()) return fallback;
|
||||
try { return Long.parseLong(value); }
|
||||
catch (NumberFormatException error) { throw new IllegalArgumentException("Invalid " + name, error); }
|
||||
}
|
||||
|
||||
private static InetAddress numericAddress(String value) {
|
||||
try {
|
||||
if (value.matches("[0-9]{1,3}(\\.[0-9]{1,3}){3}")) {
|
||||
String[] parts = value.split("\\.");
|
||||
byte[] octets = new byte[4];
|
||||
for (int i = 0; i < 4; i++) {
|
||||
int octet = Integer.parseInt(parts[i]);
|
||||
if (octet > 255) throw new IllegalArgumentException("Invalid IP address");
|
||||
octets[i] = (byte) octet;
|
||||
}
|
||||
return InetAddress.getByAddress(octets);
|
||||
}
|
||||
if (value.contains(":") && value.matches("[0-9A-Fa-f:.]+"))
|
||||
return InetAddress.getByName(value);
|
||||
} catch (UnknownHostException error) {
|
||||
throw new IllegalArgumentException("Invalid IP address", error);
|
||||
}
|
||||
throw new IllegalArgumentException("Expected numeric IP address");
|
||||
}
|
||||
|
||||
private String address(HttpExchange exchange) {
|
||||
InetAddress peer = exchange.getRemoteAddress().getAddress();
|
||||
String peerAddress = peer.getHostAddress();
|
||||
if (!trustedProxies.contains(peerAddress)) return peerAddress;
|
||||
var values = exchange.getRequestHeaders().get("X-Real-IP");
|
||||
if (values == null || values.size() != 1)
|
||||
throw new StoreException(400, "InvalidRequest", "Trusted proxy must supply one X-Real-IP address");
|
||||
try { return numericAddress(values.getFirst()).getHostAddress(); }
|
||||
catch (IllegalArgumentException error) {
|
||||
throw new StoreException(400, "InvalidRequest", "Trusted proxy supplied an invalid client address");
|
||||
}
|
||||
}
|
||||
|
||||
Client enter(HttpExchange exchange) {
|
||||
if (requestsPerSecond == 0 && bytesPerSecond == 0 && maxInFlight == 0) return null;
|
||||
String path = exchange.getRequestURI().getRawPath();
|
||||
if (exchange.getRemoteAddress().getAddress().isLoopbackAddress() &&
|
||||
exchange.getRequestHeaders().get("X-Real-IP") == null &&
|
||||
path.equals("/health")) return null;
|
||||
Client client = admit(address(exchange));
|
||||
if (bytesPerSecond > 0) {
|
||||
try {
|
||||
exchange.setStreams(new LimitedInput(exchange.getRequestBody(), client),
|
||||
new LimitedOutput(exchange.getResponseBody(), client));
|
||||
} catch (RuntimeException error) {
|
||||
leave(client);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
return client;
|
||||
}
|
||||
|
||||
private synchronized Client admit(String address) {
|
||||
Client client;
|
||||
long now = System.nanoTime();
|
||||
if (++admissions % 1024 == 0 || clients.size() >= MAX_CLIENTS)
|
||||
clients.entrySet().removeIf(entry -> entry.getValue().inFlight == 0 &&
|
||||
now - entry.getValue().lastSeen > IDLE_NANOS);
|
||||
client = clients.get(address);
|
||||
if (client == null) {
|
||||
if (clients.size() >= MAX_CLIENTS)
|
||||
throw new StoreException(503, "SlowDown", "Client limit table is full");
|
||||
client = new Client(now, requestBurst, byteBurst);
|
||||
clients.put(address, client);
|
||||
}
|
||||
refill(client, now);
|
||||
client.lastSeen = now;
|
||||
if (maxInFlight > 0 && client.inFlight >= maxInFlight)
|
||||
throw new StoreException(503, "SlowDown", "Too many concurrent requests from this client");
|
||||
if (requestsPerSecond > 0 && client.requestTokens < 1)
|
||||
throw new StoreException(503, "SlowDown", "Client request rate exceeded");
|
||||
if (requestsPerSecond > 0) client.requestTokens--;
|
||||
client.inFlight++;
|
||||
return client;
|
||||
}
|
||||
|
||||
synchronized void leave(Client client) {
|
||||
if (client != null) {
|
||||
client.inFlight--;
|
||||
client.lastSeen = System.nanoTime();
|
||||
}
|
||||
}
|
||||
|
||||
private void refill(Client client, long now) {
|
||||
double seconds = Math.max(0, now - client.lastRefill) / 1_000_000_000.0;
|
||||
if (requestsPerSecond > 0)
|
||||
client.requestTokens = Math.min(requestBurst, client.requestTokens + seconds * requestsPerSecond);
|
||||
if (bytesPerSecond > 0)
|
||||
client.byteTokens = Math.min(byteBurst, client.byteTokens + seconds * bytesPerSecond);
|
||||
client.lastRefill = now;
|
||||
}
|
||||
|
||||
private void pace(Client client, int count) throws IOException {
|
||||
while (true) {
|
||||
long wait;
|
||||
synchronized (this) {
|
||||
refill(client, System.nanoTime());
|
||||
if (client.byteTokens >= count) {
|
||||
client.byteTokens -= count;
|
||||
return;
|
||||
}
|
||||
wait = Math.max(1_000_000L,
|
||||
(long) Math.ceil((count - client.byteTokens) * 1_000_000_000.0 / bytesPerSecond));
|
||||
}
|
||||
try { Thread.sleep(Math.min(wait / 1_000_000L + 1, 1000)); }
|
||||
catch (InterruptedException error) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new IOException("Transfer interrupted while waiting for client bandwidth", error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private int chunk() { return (int) Math.min(16_384, byteBurst); }
|
||||
|
||||
static final class Client {
|
||||
private long lastSeen;
|
||||
private long lastRefill;
|
||||
private double requestTokens;
|
||||
private double byteTokens;
|
||||
private int inFlight;
|
||||
|
||||
private Client(long now, int requestBurst, long byteBurst) {
|
||||
lastSeen = now;
|
||||
lastRefill = now;
|
||||
requestTokens = requestBurst;
|
||||
byteTokens = byteBurst;
|
||||
}
|
||||
}
|
||||
|
||||
private final class LimitedInput extends FilterInputStream {
|
||||
private final Client client;
|
||||
|
||||
private LimitedInput(java.io.InputStream input, Client client) {
|
||||
super(input);
|
||||
this.client = client;
|
||||
}
|
||||
|
||||
@Override public int read() throws IOException {
|
||||
int value = in.read();
|
||||
if (value >= 0) pace(client, 1);
|
||||
return value;
|
||||
}
|
||||
|
||||
@Override public int read(byte[] bytes, int offset, int length) throws IOException {
|
||||
int count = in.read(bytes, offset, Math.min(length, chunk()));
|
||||
if (count > 0) pace(client, count);
|
||||
return count;
|
||||
}
|
||||
}
|
||||
|
||||
private final class LimitedOutput extends FilterOutputStream {
|
||||
private final Client client;
|
||||
|
||||
private LimitedOutput(java.io.OutputStream output, Client client) {
|
||||
super(output);
|
||||
this.client = client;
|
||||
}
|
||||
|
||||
@Override public void write(int value) throws IOException {
|
||||
pace(client, 1);
|
||||
out.write(value);
|
||||
}
|
||||
|
||||
@Override public void write(byte[] bytes, int offset, int length) throws IOException {
|
||||
java.util.Objects.checkFromIndexSize(offset, length, bytes.length);
|
||||
int left = length;
|
||||
while (left > 0) {
|
||||
int count = Math.min(left, chunk());
|
||||
pace(client, count);
|
||||
out.write(bytes, offset, count);
|
||||
offset += count;
|
||||
left -= count;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.Arrays;
|
||||
import java.util.Map;
|
||||
|
||||
public final class ClusterGc {
|
||||
public static void main(String[] args) throws Exception {
|
||||
if (args.length > 1 || (args.length == 1 && !args[0].equals("--apply")))
|
||||
throw new IllegalArgumentException("Usage: objectstore cluster-gc [--apply]");
|
||||
run(System.getenv(), args.length == 1);
|
||||
}
|
||||
|
||||
static void run(Map<String, String> env, boolean apply) throws Exception {
|
||||
if (!"cluster".equals(env.get("STORE_MODE")) || !"true".equals(env.get("CLUSTER_LOCAL_DEV")))
|
||||
throw new IllegalArgumentException("Cluster garbage collection is only enabled in local cluster mode");
|
||||
boolean testDomains = "true".equals(env.get("CLUSTER_TEST_NODE_DOMAINS"));
|
||||
ObjectStorage.Limits limits = StorageLimits.fromEnvironment(env);
|
||||
boolean disposableTest = testDomains && "true".equals(env.get("CLUSTER_GC_TEST_MODE"));
|
||||
long age = Long.parseLong(env.getOrDefault("CLUSTER_GC_MIN_AGE_SECONDS", "1209600"));
|
||||
long backupRetention = Long.parseLong(env.getOrDefault("CLUSTER_BACKUP_RETENTION_SECONDS", "0"));
|
||||
if (age < 0 || age > 315360000 || (age == 0 && !disposableTest))
|
||||
throw new IllegalArgumentException("Invalid garbage collection age");
|
||||
if (apply && !disposableTest && (backupRetention < 86400 || age <= backupRetention))
|
||||
throw new IllegalArgumentException("Set a garbage collection age longer than the backup retention");
|
||||
try (ClusterStore store = new ClusterStore(env.get("POSTGRES_JDBC_URL"), env.get("POSTGRES_USER"),
|
||||
env.get("POSTGRES_PASSWORD"), env.get("S3_BUCKET"),
|
||||
Arrays.stream(env.get("CLUSTER_NODES").split(",")).map(URI::create).toList(),
|
||||
env.get("CLUSTER_TOKEN"), env.get("CLUSTER_REPAIR_TOKEN"),
|
||||
limits.maxObjectBytes(), limits.maxTotalBytes(),
|
||||
testDomains)) {
|
||||
if (apply) {
|
||||
var repair = store.repairOnce();
|
||||
if (repair.underReplicated() > 0 || repair.unrecoverable() > 0)
|
||||
throw new IllegalStateException("Refusing cleanup while live segments need repair");
|
||||
}
|
||||
var report = store.collectGarbage(age * 1000, apply);
|
||||
System.out.println("segments_scanned=" + report.scanned());
|
||||
System.out.println("orphan_candidates=" + report.eligible());
|
||||
System.out.println("segments_deleted=" + report.deleted());
|
||||
System.out.println("unavailable_nodes=" + report.unavailableNodes());
|
||||
if (report.unavailableNodes() > 0) throw new IllegalStateException("Cleanup did not scan every node");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,8 @@ public final class ClusterJoin {
|
||||
if (args.length != 2)
|
||||
throw new IllegalArgumentException("Usage: objectstore cluster-join node-url expected-host-uuid");
|
||||
Map<String, String> env = System.getenv();
|
||||
EncryptedVolume.requireConfigured(env,
|
||||
java.nio.file.Path.of(System.getProperty("java.io.tmpdir")));
|
||||
if (!"cluster".equals(env.get("STORE_MODE")) || !"true".equals(env.get("CLUSTER_LOCAL_DEV")))
|
||||
throw new IllegalArgumentException("Node registration is only enabled in local cluster mode");
|
||||
URI url = URI.create(args[0]);
|
||||
|
||||
@@ -24,6 +24,8 @@ public final class ClusterMigrate {
|
||||
(args.length != 2 || !args[0].equals("--apply")))
|
||||
throw new IllegalArgumentException("Usage: objectstore cluster-migrate --check | --apply node-id-0,node-id-1,node-id-2");
|
||||
Map<String, String> env = System.getenv();
|
||||
EncryptedVolume.requireConfigured(env,
|
||||
java.nio.file.Path.of(System.getProperty("java.io.tmpdir")));
|
||||
if (!"cluster".equals(env.get("STORE_MODE")) || !"true".equals(env.get("CLUSTER_LOCAL_DEV")))
|
||||
throw new IllegalArgumentException("Migration is enabled only in local cluster mode");
|
||||
List<URI> urls = Arrays.stream(env.get("CLUSTER_NODES").split(",", -1)).map(URI::create).toList();
|
||||
@@ -148,7 +150,8 @@ public final class ClusterMigrate {
|
||||
}
|
||||
connection.commit();
|
||||
} catch (SQLException | IOException | RuntimeException error) {
|
||||
try { connection.rollback(); } catch (SQLException rollback) { error.addSuppressed(rollback); }
|
||||
try { connection.rollback(); }
|
||||
catch (SQLException rollback) { error.addSuppressed(rollback); }
|
||||
if (error instanceof IOException io) throw io;
|
||||
if (error instanceof SQLException sql) throw sql;
|
||||
throw (RuntimeException) error;
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import com.sun.net.httpserver.HttpExchange;
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
@@ -15,7 +14,9 @@ import java.nio.file.StandardCopyOption;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.Arrays;
|
||||
import java.util.Comparator;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.Executors;
|
||||
@@ -31,6 +32,7 @@ public final class ClusterNode implements AutoCloseable {
|
||||
private final FileLock lock;
|
||||
|
||||
ClusterNode(Path root, String token, String repairToken, UUID hostId) throws IOException {
|
||||
EncryptedVolume.requireConfigured(System.getenv(), root);
|
||||
if (token == null || token.length() < 32) throw new IllegalArgumentException("Cluster token must have at least 32 characters");
|
||||
if (repairToken == null || repairToken.length() < 32 || repairToken.equals(token))
|
||||
throw new IllegalArgumentException("A separate repair token of at least 32 characters is required");
|
||||
@@ -78,43 +80,24 @@ public final class ClusterNode implements AutoCloseable {
|
||||
respond(exchange, 200, "ok");
|
||||
return;
|
||||
}
|
||||
byte[] supplied = exchange.getRequestHeaders().getFirst("X-Cluster-Token") == null
|
||||
? new byte[0] : exchange.getRequestHeaders().getFirst("X-Cluster-Token")
|
||||
.getBytes(java.nio.charset.StandardCharsets.UTF_8);
|
||||
if (!MessageDigest.isEqual(token, supplied)) {
|
||||
respond(exchange, 403, "Forbidden");
|
||||
return;
|
||||
}
|
||||
if (!authorized(exchange)) return;
|
||||
if (path.equals("/identity") && exchange.getRequestMethod().equals("GET")) {
|
||||
respond(exchange, 200, identity.nodeId() + " " + identity.hostId());
|
||||
return;
|
||||
}
|
||||
if (!identity.nodeId().toString().equals(exchange.getRequestHeaders().getFirst("X-Cluster-Expected-Node"))) {
|
||||
respond(exchange, 409, "Wrong storage node");
|
||||
return;
|
||||
}
|
||||
if (exchange.getRequestMethod().equals("PUT") &&
|
||||
"true".equals(exchange.getRequestHeaders().getFirst("X-Cluster-Repair"))) {
|
||||
String suppliedRepair = exchange.getRequestHeaders().getFirst("X-Cluster-Repair-Token");
|
||||
byte[] suppliedBytes = suppliedRepair == null ? new byte[0]
|
||||
: suppliedRepair.getBytes(java.nio.charset.StandardCharsets.UTF_8);
|
||||
if (!MessageDigest.isEqual(repairToken, suppliedBytes)) {
|
||||
respond(exchange, 403, "Repair authority required");
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (!path.matches("/segments/[0-9a-f-]{36}")) {
|
||||
respond(exchange, 404, "Not found");
|
||||
return;
|
||||
}
|
||||
String id = path.substring("/segments/".length());
|
||||
if (!UUID.fromString(id).toString().equals(id)) {
|
||||
respond(exchange, 400, "Invalid segment ID");
|
||||
if (!expectedNodeAndRepairAuthorized(exchange)) return;
|
||||
if (path.equals("/segments") && exchange.getRequestMethod().equals("GET")) {
|
||||
if (maintenanceAuthorized(exchange)) inventory(exchange);
|
||||
return;
|
||||
}
|
||||
String id = segmentId(exchange, path);
|
||||
if (id == null) return;
|
||||
switch (exchange.getRequestMethod()) {
|
||||
case "PUT" -> put(exchange, segmentPath(id, true));
|
||||
case "GET" -> get(exchange, segmentPath(id, false));
|
||||
case "DELETE" -> {
|
||||
if (maintenanceAuthorized(exchange)) delete(exchange, segmentPath(id, false));
|
||||
}
|
||||
default -> respond(exchange, 405, "Method not allowed");
|
||||
}
|
||||
} catch (IllegalArgumentException error) {
|
||||
@@ -127,6 +110,119 @@ public final class ClusterNode implements AutoCloseable {
|
||||
}
|
||||
}
|
||||
|
||||
private boolean authorized(HttpExchange exchange) throws IOException {
|
||||
byte[] supplied = exchange.getRequestHeaders().getFirst("X-Cluster-Token") == null
|
||||
? new byte[0] : exchange.getRequestHeaders().getFirst("X-Cluster-Token")
|
||||
.getBytes(java.nio.charset.StandardCharsets.UTF_8);
|
||||
if (!MessageDigest.isEqual(token, supplied)) {
|
||||
respond(exchange, 403, "Forbidden");
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private boolean expectedNodeAndRepairAuthorized(HttpExchange exchange) throws IOException {
|
||||
if (!identity.nodeId().toString().equals(exchange.getRequestHeaders().getFirst("X-Cluster-Expected-Node"))) {
|
||||
respond(exchange, 409, "Wrong storage node");
|
||||
return false;
|
||||
}
|
||||
if (exchange.getRequestMethod().equals("PUT") &&
|
||||
"true".equals(exchange.getRequestHeaders().getFirst("X-Cluster-Repair"))) {
|
||||
String suppliedRepair = exchange.getRequestHeaders().getFirst("X-Cluster-Repair-Token");
|
||||
byte[] suppliedBytes = suppliedRepair == null ? new byte[0]
|
||||
: suppliedRepair.getBytes(java.nio.charset.StandardCharsets.UTF_8);
|
||||
if (!MessageDigest.isEqual(repairToken, suppliedBytes)) {
|
||||
respond(exchange, 403, "Repair authority required");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private boolean maintenanceAuthorized(HttpExchange exchange) throws IOException {
|
||||
String supplied = exchange.getRequestHeaders().getFirst("X-Cluster-Repair-Token");
|
||||
byte[] value = supplied == null ? new byte[0] : supplied.getBytes(java.nio.charset.StandardCharsets.UTF_8);
|
||||
if (MessageDigest.isEqual(repairToken, value)) return true;
|
||||
respond(exchange, 403, "Repair authority required");
|
||||
return false;
|
||||
}
|
||||
|
||||
private void inventory(HttpExchange exchange) throws IOException {
|
||||
String query = exchange.getRequestURI().getRawQuery();
|
||||
if (query == null || !query.matches("shard=[0-9a-f]{2}(&after=[0-9a-f-]{36})?")) {
|
||||
respond(exchange, 400, "Invalid inventory request");
|
||||
return;
|
||||
}
|
||||
String shard = query.substring(6, 8);
|
||||
String after = query.length() > 8 ? query.substring(15) : "";
|
||||
if (!after.isEmpty() && (!after.startsWith(shard) || !UUID.fromString(after).toString().equals(after))) {
|
||||
respond(exchange, 400, "Invalid inventory cursor");
|
||||
return;
|
||||
}
|
||||
Path directory = segments.resolve(shard);
|
||||
if (!Files.isDirectory(directory)) {
|
||||
respond(exchange, 200, "");
|
||||
return;
|
||||
}
|
||||
List<Path> files;
|
||||
try (var entries = Files.list(directory)) {
|
||||
files = entries.filter(Files::isRegularFile).sorted(Comparator.comparing(path ->
|
||||
path.getFileName().toString())).toList();
|
||||
}
|
||||
StringBuilder body = new StringBuilder();
|
||||
int count = 0;
|
||||
for (Path file : files) {
|
||||
String id = file.getFileName().toString();
|
||||
if (id.compareTo(after) <= 0 || !id.matches("[0-9a-f-]{36}")) continue;
|
||||
if (!UUID.fromString(id).toString().equals(id)) continue;
|
||||
body.append(id).append(' ').append(Files.getLastModifiedTime(file).toMillis()).append('\n');
|
||||
if (++count == 1000) break;
|
||||
}
|
||||
respond(exchange, 200, body.toString());
|
||||
}
|
||||
|
||||
private synchronized void delete(HttpExchange exchange, Path target) throws IOException {
|
||||
String expected = exchange.getRequestHeaders().getFirst("X-Cluster-Expected-Mtime");
|
||||
String age = exchange.getRequestHeaders().getFirst("X-Cluster-Gc-Min-Age-Millis");
|
||||
long expectedTime, minimumAge;
|
||||
try {
|
||||
expectedTime = Long.parseLong(expected);
|
||||
minimumAge = Long.parseLong(age);
|
||||
} catch (NumberFormatException error) {
|
||||
respond(exchange, 400, "Invalid deletion guard");
|
||||
return;
|
||||
}
|
||||
if (minimumAge < 0 || minimumAge > System.currentTimeMillis()) {
|
||||
respond(exchange, 400, "Invalid deletion age");
|
||||
return;
|
||||
}
|
||||
if (!Files.isRegularFile(target)) {
|
||||
exchange.sendResponseHeaders(404, -1);
|
||||
return;
|
||||
}
|
||||
long modified = Files.getLastModifiedTime(target).toMillis();
|
||||
if (modified != expectedTime || modified > System.currentTimeMillis() - minimumAge) {
|
||||
exchange.sendResponseHeaders(409, -1);
|
||||
return;
|
||||
}
|
||||
Files.delete(target);
|
||||
DiskStore.syncDirectory(target.getParent());
|
||||
exchange.sendResponseHeaders(204, -1);
|
||||
}
|
||||
|
||||
private static String segmentId(HttpExchange exchange, String path) throws IOException {
|
||||
if (!path.matches("/segments/[0-9a-f-]{36}")) {
|
||||
respond(exchange, 404, "Not found");
|
||||
return null;
|
||||
}
|
||||
String id = path.substring("/segments/".length());
|
||||
if (!UUID.fromString(id).toString().equals(id)) {
|
||||
respond(exchange, 400, "Invalid segment ID");
|
||||
return null;
|
||||
}
|
||||
return id;
|
||||
}
|
||||
|
||||
private synchronized Path segmentPath(String id, boolean createShard) throws IOException {
|
||||
Path shard = segments.resolve(id.substring(0, 2));
|
||||
if (createShard && !Files.isDirectory(shard)) {
|
||||
@@ -229,16 +325,19 @@ public final class ClusterNode implements AutoCloseable {
|
||||
env.get("CLUSTER_REPAIR_TOKEN"),
|
||||
UUID.fromString(env.get("CLUSTER_HOST_ID")));
|
||||
int port = Integer.parseInt(env.getOrDefault("NODE_PORT", "9100"));
|
||||
var server = HttpServer.create(new InetSocketAddress(env.getOrDefault("NODE_BIND", "127.0.0.1"), port), 64);
|
||||
var server = ClusterTls.nodeServer(
|
||||
new InetSocketAddress(env.getOrDefault("NODE_BIND", "127.0.0.1"), port), env);
|
||||
var executor = Executors.newVirtualThreadPerTaskExecutor();
|
||||
server.setExecutor(executor);
|
||||
server.createContext("/", node::handle);
|
||||
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
|
||||
server.stop(5);
|
||||
executor.close();
|
||||
try { node.close(); } catch (IOException error) { System.err.println("Node close failed: " + error); }
|
||||
try { node.close(); }
|
||||
catch (IOException error) { System.err.println("Node close failed: " + error); }
|
||||
}));
|
||||
server.start();
|
||||
System.out.println("ObjectStore cluster node listening on :" + port);
|
||||
System.out.println("ObjectStore cluster node listening on :" + port +
|
||||
(server instanceof com.sun.net.httpserver.HttpsServer ? " (TLS)" : " (HTTP)"));
|
||||
}
|
||||
}
|
||||
@@ -6,21 +6,43 @@ import java.util.Map;
|
||||
|
||||
public final class ClusterRepair {
|
||||
public static void main(String[] args) throws Exception {
|
||||
if (args.length != 0) throw new IllegalArgumentException("Usage: objectstore cluster-repair");
|
||||
if (args.length > 1 || (args.length == 1 && !args[0].equals("--loop")))
|
||||
throw new IllegalArgumentException("Usage: objectstore cluster-repair [--loop]");
|
||||
Map<String, String> env = System.getenv();
|
||||
if (!"cluster".equals(env.get("STORE_MODE")) || !"true".equals(env.get("CLUSTER_LOCAL_DEV")))
|
||||
throw new IllegalArgumentException("Cluster repair is only enabled in local cluster mode");
|
||||
try (ClusterStore store = new ClusterStore(env.get("POSTGRES_JDBC_URL"), env.get("POSTGRES_USER"),
|
||||
env.get("POSTGRES_PASSWORD"), env.get("S3_BUCKET"),
|
||||
Arrays.stream(env.get("CLUSTER_NODES").split(",")).map(URI::create).toList(),
|
||||
env.get("CLUSTER_TOKEN"), env.get("CLUSTER_REPAIR_TOKEN"), 134217728, 2147483648L,
|
||||
"true".equals(env.get("CLUSTER_TEST_NODE_DOMAINS")))) {
|
||||
var report = store.repairOnce();
|
||||
System.out.println("segments_scanned=" + report.scanned());
|
||||
System.out.println("replicas_restored=" + report.restored());
|
||||
System.out.println("segments_under_replicated=" + report.underReplicated());
|
||||
System.out.println("segments_unrecoverable=" + report.unrecoverable());
|
||||
if (report.unrecoverable() > 0) System.exit(1);
|
||||
}
|
||||
boolean loop = args.length == 1;
|
||||
ObjectStorage.Limits limits = StorageLimits.fromEnvironment(env);
|
||||
long seconds = Long.parseLong(env.getOrDefault("CLUSTER_MAINTENANCE_INTERVAL_SECONDS", "60"));
|
||||
if (seconds < 1 || seconds > 3600) throw new IllegalArgumentException("Invalid maintenance interval");
|
||||
boolean gcEnabled = loop && "true".equals(env.get("CLUSTER_GC_ENABLED"));
|
||||
long gcInterval = Long.parseLong(env.getOrDefault("CLUSTER_GC_INTERVAL_SECONDS", "86400"));
|
||||
if (gcEnabled && (gcInterval < 1 || gcInterval > 604800))
|
||||
throw new IllegalArgumentException("Invalid garbage collection interval");
|
||||
long nextGc = 0;
|
||||
do {
|
||||
try (ClusterStore store = new ClusterStore(env.get("POSTGRES_JDBC_URL"), env.get("POSTGRES_USER"),
|
||||
env.get("POSTGRES_PASSWORD"), env.get("S3_BUCKET"),
|
||||
Arrays.stream(env.get("CLUSTER_NODES").split(",")).map(URI::create).toList(),
|
||||
env.get("CLUSTER_TOKEN"), env.get("CLUSTER_REPAIR_TOKEN"),
|
||||
limits.maxObjectBytes(), limits.maxTotalBytes(),
|
||||
"true".equals(env.get("CLUSTER_TEST_NODE_DOMAINS")))) {
|
||||
var report = store.repairOnce();
|
||||
System.out.println("segments_scanned=" + report.scanned());
|
||||
System.out.println("replicas_restored=" + report.restored());
|
||||
System.out.println("segments_rebalanced=" + report.rebalanced());
|
||||
System.out.println("segments_under_replicated=" + report.underReplicated());
|
||||
System.out.println("segments_unrecoverable=" + report.unrecoverable());
|
||||
if (!loop && report.unrecoverable() > 0) System.exit(1);
|
||||
if (gcEnabled && System.currentTimeMillis() >= nextGc) {
|
||||
ClusterGc.run(env, true);
|
||||
nextGc = System.currentTimeMillis() + gcInterval * 1000;
|
||||
}
|
||||
} catch (Exception error) {
|
||||
if (!loop) throw error;
|
||||
System.err.println("Cluster maintenance failed: " + error.getMessage());
|
||||
}
|
||||
if (loop) Thread.sleep(seconds * 1000);
|
||||
} while (loop);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,99 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
import com.sun.net.httpserver.HttpsConfigurator;
|
||||
import com.sun.net.httpserver.HttpsServer;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.http.HttpClient;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.security.GeneralSecurityException;
|
||||
import java.security.KeyStore;
|
||||
import java.time.Duration;
|
||||
import java.util.Arrays;
|
||||
import java.util.Map;
|
||||
import javax.net.ssl.KeyManagerFactory;
|
||||
import javax.net.ssl.SSLContext;
|
||||
import javax.net.ssl.TrustManagerFactory;
|
||||
|
||||
final class ClusterTls {
|
||||
private ClusterTls() { }
|
||||
|
||||
static HttpServer nodeServer(InetSocketAddress address, Map<String, String> env) throws IOException {
|
||||
String keyStore = env.get("NODE_TLS_KEYSTORE");
|
||||
String passwordFile = env.get("NODE_TLS_PASSWORD_FILE");
|
||||
if (missing(keyStore) && missing(passwordFile)) return HttpServer.create(address, 64);
|
||||
if (missing(keyStore) || missing(passwordFile))
|
||||
throw new IOException("Node TLS requires both NODE_TLS_KEYSTORE and NODE_TLS_PASSWORD_FILE");
|
||||
SSLContext context = serverContext(Path.of(keyStore), Path.of(passwordFile));
|
||||
HttpsServer server = HttpsServer.create(address, 64);
|
||||
server.setHttpsConfigurator(new HttpsConfigurator(context));
|
||||
return server;
|
||||
}
|
||||
|
||||
static HttpClient client(Map<String, String> env, Duration timeout) throws IOException {
|
||||
String trustStore = env.get("CLUSTER_TLS_TRUSTSTORE");
|
||||
String passwordFile = env.get("CLUSTER_TLS_PASSWORD_FILE");
|
||||
if (missing(trustStore) != missing(passwordFile))
|
||||
throw new IOException("Cluster TLS requires both CLUSTER_TLS_TRUSTSTORE and CLUSTER_TLS_PASSWORD_FILE");
|
||||
HttpClient.Builder builder = HttpClient.newBuilder().connectTimeout(timeout);
|
||||
if (!missing(trustStore))
|
||||
builder.sslContext(clientContext(Path.of(trustStore), Path.of(passwordFile)));
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
private static SSLContext serverContext(Path keyStore, Path passwordFile) throws IOException {
|
||||
char[] password = password(passwordFile);
|
||||
try {
|
||||
KeyStore keys = load(keyStore, password);
|
||||
KeyManagerFactory managers = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
|
||||
managers.init(keys, password);
|
||||
SSLContext context = SSLContext.getInstance("TLS");
|
||||
context.init(managers.getKeyManagers(), null, null);
|
||||
return context;
|
||||
} catch (GeneralSecurityException error) {
|
||||
throw new IOException("Could not configure node TLS", error);
|
||||
} finally {
|
||||
Arrays.fill(password, '\0');
|
||||
}
|
||||
}
|
||||
|
||||
private static SSLContext clientContext(Path trustStore, Path passwordFile) throws IOException {
|
||||
char[] password = password(passwordFile);
|
||||
try {
|
||||
KeyStore trust = load(trustStore, password);
|
||||
TrustManagerFactory managers = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
|
||||
managers.init(trust);
|
||||
SSLContext context = SSLContext.getInstance("TLS");
|
||||
context.init(null, managers.getTrustManagers(), null);
|
||||
return context;
|
||||
} catch (GeneralSecurityException error) {
|
||||
throw new IOException("Could not configure cluster TLS trust", error);
|
||||
} finally {
|
||||
Arrays.fill(password, '\0');
|
||||
}
|
||||
}
|
||||
|
||||
private static KeyStore load(Path path, char[] password) throws IOException, GeneralSecurityException {
|
||||
KeyStore store = KeyStore.getInstance("PKCS12");
|
||||
try (InputStream input = Files.newInputStream(path)) {
|
||||
store.load(input, password);
|
||||
}
|
||||
return store;
|
||||
}
|
||||
|
||||
private static char[] password(Path file) throws IOException {
|
||||
String value = Files.readString(file, StandardCharsets.UTF_8);
|
||||
if (value.endsWith("\n")) value = value.substring(0, value.length() - 1);
|
||||
if (value.endsWith("\r")) value = value.substring(0, value.length() - 1);
|
||||
if (value.isEmpty()) throw new IOException("Cluster TLS password file is empty");
|
||||
return value.toCharArray();
|
||||
}
|
||||
|
||||
private static boolean missing(String value) {
|
||||
return value == null || value.isBlank();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import java.util.zip.Checksum;
|
||||
import java.util.Base64;
|
||||
import java.nio.ByteBuffer;
|
||||
|
||||
final class Crc64Nvme implements Checksum {
|
||||
private static final long POLYNOMIAL = 0x9a6c9329ac4bc9b5L;
|
||||
private static final long[] TABLE = table();
|
||||
private long state = -1L;
|
||||
|
||||
private static long[] table() {
|
||||
long[] values = new long[256];
|
||||
for (int index = 0; index < values.length; index++) {
|
||||
long value = index;
|
||||
for (int bit = 0; bit < 8; bit++)
|
||||
value = (value >>> 1) ^ ((value & 1L) == 0 ? 0 : POLYNOMIAL);
|
||||
values[index] = value;
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
@Override public void update(int value) {
|
||||
state = (state >>> 8) ^ TABLE[(int) (state ^ value) & 255];
|
||||
}
|
||||
|
||||
@Override public void update(byte[] bytes, int offset, int length) {
|
||||
java.util.Objects.checkFromIndexSize(offset, length, bytes.length);
|
||||
for (int i = offset; i < offset + length; i++) update(bytes[i]);
|
||||
}
|
||||
|
||||
@Override public long getValue() { return ~state; }
|
||||
|
||||
String encoded() {
|
||||
return Base64.getEncoder().encodeToString(ByteBuffer.allocate(8).putLong(getValue()).array());
|
||||
}
|
||||
|
||||
@Override public void reset() { state = -1L; }
|
||||
}
|
||||
@@ -19,23 +19,46 @@ import cloud.lunarsky.store.ObjectStorage.ListPage;
|
||||
final class DiskStore implements ObjectStorage {
|
||||
private static final long MAGIC_V1 = 0x4c534f424a303031L;
|
||||
private static final long MAGIC_V2 = 0x4c534f424a303032L;
|
||||
private static final long MAGIC_V3 = 0x4c534f424a303033L;
|
||||
private static final long MAGIC_V4 = 0x4c534f424a303034L;
|
||||
private static final long MAGIC_V5 = 0x4c534f424a303035L;
|
||||
private static final int HEADER_V1 = 72;
|
||||
private static final int HEADER_V2 = 78;
|
||||
private final Path root, objects, temporary;
|
||||
private static final int HEADER_V3 = 82;
|
||||
private static final int CHECKSUM_AREA = 512;
|
||||
private static final int HEADER_V4 = HEADER_V3 + 2 + CHECKSUM_AREA;
|
||||
private static final int ACL_AREA = 2048;
|
||||
private static final int HEADER_V5 = HEADER_V4 + 2;
|
||||
private static final int BUCKET_MAGIC = 0x4c534243;
|
||||
private static final int BUCKET_MAGIC_V2 = 0x4c534244;
|
||||
private static final int BUCKET_MAGIC_V3 = 0x4c534245;
|
||||
private static final int BUCKET_MAGIC_V4 = 0x4c534246;
|
||||
private static final int VERSION_MAGIC = 0x4c53564d;
|
||||
private final Path root, objects, temporary, catalog, versions;
|
||||
private final FileChannel lockChannel;
|
||||
private final FileLock processLock;
|
||||
private final long maxObject, maxTotal;
|
||||
private final Object[] locks = new Object[128];
|
||||
private final NavigableMap<String, Metadata> index = new TreeMap<>();
|
||||
private final NavigableMap<String, Bucket> buckets = new TreeMap<>();
|
||||
private final NavigableMap<String, List<VersionRecord>> histories = new TreeMap<>();
|
||||
private final Map<String, Integer> publishingByBucket = new HashMap<>();
|
||||
private long used;
|
||||
private long reservedBytes;
|
||||
private long objectCount, legacyCount;
|
||||
|
||||
record Record(Metadata metadata, int headerLength) {}
|
||||
private record VersionRecord(String id, String storageId, boolean marker, long modified) {}
|
||||
|
||||
DiskStore(Path root, long maxObject, long maxTotal) throws IOException {
|
||||
EncryptedVolume.requireConfigured(System.getenv(), root);
|
||||
this.root = root;
|
||||
objects = root.resolve("objects"); temporary = root.resolve("pending");
|
||||
this.maxObject = maxObject; this.maxTotal = maxTotal;
|
||||
objects = root.resolve("objects");
|
||||
temporary = root.resolve("pending");
|
||||
catalog = root.resolve("buckets.bin");
|
||||
versions = root.resolve("versions");
|
||||
this.maxObject = maxObject;
|
||||
this.maxTotal = maxTotal;
|
||||
Arrays.setAll(locks, i -> new Object());
|
||||
Files.createDirectories(root);
|
||||
FileChannel channel = FileChannel.open(root.resolve(".process.lock"), StandardOpenOption.CREATE, StandardOpenOption.WRITE);
|
||||
@@ -45,7 +68,9 @@ final class DiskStore implements ObjectStorage {
|
||||
try { acquired = channel.tryLock(); }
|
||||
catch (OverlappingFileLockException e) { throw new IOException("Data directory is already in use", e); }
|
||||
if (acquired == null) throw new IOException("Data directory is already in use");
|
||||
Files.createDirectories(objects); Files.createDirectories(temporary);
|
||||
Files.createDirectories(objects);
|
||||
Files.createDirectories(temporary);
|
||||
Files.createDirectories(versions);
|
||||
syncDirectory(root);
|
||||
try (var paths = Files.list(temporary)) {
|
||||
for (Path p : paths.toList()) if (p.getFileName().toString().endsWith(".part")) Files.delete(p);
|
||||
@@ -67,6 +92,53 @@ final class DiskStore implements ObjectStorage {
|
||||
used = Math.addExact(used, meta.length());
|
||||
}
|
||||
}
|
||||
if (Files.exists(catalog)) {
|
||||
try (DataInputStream input = new DataInputStream(Files.newInputStream(catalog))) {
|
||||
int magic = input.readInt();
|
||||
if (magic != BUCKET_MAGIC && magic != BUCKET_MAGIC_V2 &&
|
||||
magic != BUCKET_MAGIC_V3 && magic != BUCKET_MAGIC_V4)
|
||||
throw new IOException("Invalid bucket catalog");
|
||||
int count = input.readInt();
|
||||
if (count < 0 || count > 1000) throw new IOException("Invalid bucket catalog");
|
||||
for (int i = 0; i < count; i++) {
|
||||
String name = input.readUTF();
|
||||
long created = input.readLong();
|
||||
VersioningState state = VersioningState.NEVER;
|
||||
if (magic != BUCKET_MAGIC) {
|
||||
int ordinal = input.readUnsignedByte();
|
||||
if (ordinal >= VersioningState.values().length)
|
||||
throw new IOException("Invalid bucket versioning state");
|
||||
state = VersioningState.values()[ordinal];
|
||||
}
|
||||
Map<String, String> acl = Map.of();
|
||||
if (magic == BUCKET_MAGIC_V3 || magic == BUCKET_MAGIC_V4) {
|
||||
int size = input.readUnsignedShort();
|
||||
if (size > ACL_AREA) throw new IOException("Invalid bucket ACL");
|
||||
acl = ObjectAttributes.decode(input.readNBytes(size));
|
||||
}
|
||||
ObjectOwnership ownership = ObjectOwnership.OBJECT_WRITER;
|
||||
PublicAccessBlock block = PublicAccessBlock.open();
|
||||
String policy = null;
|
||||
if (magic == BUCKET_MAGIC_V4) {
|
||||
int ordinal = input.readUnsignedByte();
|
||||
int flags = input.readUnsignedByte();
|
||||
if (ordinal >= ObjectOwnership.values().length || (flags & ~15) != 0)
|
||||
throw new IOException("Invalid bucket access settings");
|
||||
ownership = ObjectOwnership.values()[ordinal];
|
||||
block = new PublicAccessBlock((flags & 1) != 0, (flags & 2) != 0,
|
||||
(flags & 4) != 0, (flags & 8) != 0);
|
||||
policy = input.readUTF();
|
||||
if (policy.isEmpty()) policy = null;
|
||||
}
|
||||
if (!validBucket(name) || created < 0 ||
|
||||
buckets.put(name, new Bucket(name, created, state, acl,
|
||||
ownership, block, policy)) != null)
|
||||
throw new IOException("Invalid bucket catalog");
|
||||
}
|
||||
if (input.read() != -1) throw new IOException("Invalid bucket catalog");
|
||||
}
|
||||
}
|
||||
loadHistories();
|
||||
ready = true;
|
||||
} finally {
|
||||
if (!ready) {
|
||||
@@ -85,12 +157,300 @@ final class DiskStore implements ObjectStorage {
|
||||
Path root() { return root; }
|
||||
long maxObject() { return maxObject; }
|
||||
long maxTotal() { return maxTotal; }
|
||||
@Override public Limits limits() { return new Limits(maxObject, maxTotal); }
|
||||
synchronized long usedBytes() { return used; }
|
||||
synchronized int indexedObjects() { return index.size(); }
|
||||
synchronized long objectCount() { return objectCount; }
|
||||
synchronized long legacyObjects() { return legacyCount; }
|
||||
|
||||
private static boolean validBucket(String name) {
|
||||
return name.matches("[a-z0-9][a-z0-9-]{1,61}[a-z0-9]");
|
||||
}
|
||||
|
||||
@Override public synchronized void ensureBucket(String bucket) throws IOException {
|
||||
if (!buckets.containsKey(bucket)) createBucket(bucket);
|
||||
}
|
||||
|
||||
@Override public synchronized Bucket bucket(String name) {
|
||||
Bucket found = buckets.get(name);
|
||||
if (found == null) throw new StoreException(404, "NoSuchBucket", "Bucket not found");
|
||||
return found;
|
||||
}
|
||||
|
||||
@Override public synchronized List<Bucket> buckets() { return List.copyOf(buckets.values()); }
|
||||
|
||||
@Override public synchronized void createBucket(String name) throws IOException {
|
||||
if (!validBucket(name)) throw new StoreException(400, "InvalidBucketName", "Invalid bucket name");
|
||||
if (buckets.containsKey(name))
|
||||
throw new StoreException(409, "BucketAlreadyOwnedByYou", "Bucket already exists");
|
||||
if (buckets.size() >= 1000) throw new StoreException(400, "TooManyBuckets", "Bucket limit reached");
|
||||
NavigableMap<String, Bucket> next = new TreeMap<>(buckets);
|
||||
next.put(name, new Bucket(name, Instant.now().toEpochMilli()));
|
||||
saveBuckets(next);
|
||||
buckets.clear();
|
||||
buckets.putAll(next);
|
||||
}
|
||||
|
||||
@Override public synchronized void deleteBucket(String name) throws IOException {
|
||||
bucket(name);
|
||||
awaitPublications(name);
|
||||
if (index.values().stream().anyMatch(meta -> name.equals(meta.bucket())))
|
||||
throw new StoreException(409, "BucketNotEmpty", "Bucket contains objects");
|
||||
if (histories.entrySet().stream().anyMatch(entry -> entry.getKey().startsWith(name + "\0") &&
|
||||
!entry.getValue().isEmpty()))
|
||||
throw new StoreException(409, "BucketNotEmpty", "Bucket contains object versions");
|
||||
if (legacyCount > 0) {
|
||||
try (var paths = Files.walk(objects)) {
|
||||
for (Path path : paths.filter(Files::isRegularFile).toList()) {
|
||||
try (var input = new DataInputStream(Files.newInputStream(path))) {
|
||||
Metadata metadata = readRecord(input).metadata();
|
||||
if (metadata.key() == null && name.equals(metadata.bucket()))
|
||||
throw new StoreException(409, "BucketNotEmpty", "Bucket contains legacy objects");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
NavigableMap<String, Bucket> next = new TreeMap<>(buckets);
|
||||
next.remove(name);
|
||||
saveBuckets(next);
|
||||
buckets.clear();
|
||||
buckets.putAll(next);
|
||||
for (String key : new ArrayList<>(histories.keySet())) {
|
||||
if (!key.startsWith(name + "\0") || !histories.get(key).isEmpty()) continue;
|
||||
String objectKey = key.substring(name.length() + 1);
|
||||
Path directory = historyDirectory(name, objectKey);
|
||||
Files.deleteIfExists(directory.resolve("manifest"));
|
||||
syncDirectory(directory);
|
||||
histories.remove(key);
|
||||
}
|
||||
}
|
||||
|
||||
private void saveBuckets(NavigableMap<String, Bucket> next) throws IOException {
|
||||
Path pending = Files.createTempFile(temporary, "buckets-", ".part");
|
||||
try {
|
||||
try (DataOutputStream output = new DataOutputStream(Files.newOutputStream(pending))) {
|
||||
output.writeInt(BUCKET_MAGIC_V4);
|
||||
output.writeInt(next.size());
|
||||
for (Bucket entry : next.values()) {
|
||||
output.writeUTF(entry.name());
|
||||
output.writeLong(entry.created());
|
||||
output.writeByte(entry.versioning().ordinal());
|
||||
byte[] acl = ObjectAttributes.encode(entry.acl(), ACL_AREA);
|
||||
output.writeShort(acl.length);
|
||||
output.write(acl);
|
||||
output.writeByte(entry.ownership().ordinal());
|
||||
PublicAccessBlock block = entry.publicAccessBlock();
|
||||
output.writeByte((block.blockPublicAcls() ? 1 : 0) |
|
||||
(block.ignorePublicAcls() ? 2 : 0) |
|
||||
(block.blockPublicPolicy() ? 4 : 0) |
|
||||
(block.restrictPublicBuckets() ? 8 : 0));
|
||||
output.writeUTF(entry.policy() == null ? "" : entry.policy());
|
||||
}
|
||||
}
|
||||
try (FileChannel channel = FileChannel.open(pending, StandardOpenOption.WRITE)) { channel.force(true); }
|
||||
Files.move(pending, catalog, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
|
||||
syncDirectory(root);
|
||||
} finally { Files.deleteIfExists(pending); }
|
||||
}
|
||||
|
||||
@Override public synchronized void setVersioning(String name, VersioningState state) throws IOException {
|
||||
awaitPublications(name);
|
||||
if (state == VersioningState.NEVER)
|
||||
throw new StoreException(400, "InvalidArgument", "Versioning cannot be disabled after it is enabled");
|
||||
Bucket old = bucket(name);
|
||||
if (old.versioning() == VersioningState.NEVER && state == VersioningState.SUSPENDED)
|
||||
throw new StoreException(400, "InvalidArgument", "Enable versioning before suspending it");
|
||||
NavigableMap<String, Bucket> next = new TreeMap<>(buckets);
|
||||
next.put(name, new Bucket(name, old.created(), state, old.acl(),
|
||||
old.ownership(), old.publicAccessBlock(), old.policy()));
|
||||
saveBuckets(next);
|
||||
buckets.clear();
|
||||
buckets.putAll(next);
|
||||
}
|
||||
|
||||
@Override public synchronized void setBucketAcl(String name, Map<String, String> acl) throws IOException {
|
||||
Bucket old = bucket(name);
|
||||
NavigableMap<String, Bucket> next = new TreeMap<>(buckets);
|
||||
next.put(name, new Bucket(name, old.created(), old.versioning(), Map.copyOf(acl),
|
||||
old.ownership(), old.publicAccessBlock(), old.policy()));
|
||||
saveBuckets(next);
|
||||
buckets.clear();
|
||||
buckets.putAll(next);
|
||||
}
|
||||
|
||||
@Override public synchronized void setBucketOwnership(String name, ObjectOwnership ownership)
|
||||
throws IOException {
|
||||
Bucket old = bucket(name);
|
||||
updateBucket(new Bucket(name, old.created(), old.versioning(), old.acl(),
|
||||
ownership, old.publicAccessBlock(), old.policy()));
|
||||
}
|
||||
|
||||
@Override public synchronized void setPublicAccessBlock(String name, PublicAccessBlock block)
|
||||
throws IOException {
|
||||
Bucket old = bucket(name);
|
||||
updateBucket(new Bucket(name, old.created(), old.versioning(), old.acl(),
|
||||
old.ownership(), block, old.policy()));
|
||||
}
|
||||
|
||||
@Override public synchronized void setBucketPolicy(String name, String policy)
|
||||
throws IOException {
|
||||
Bucket old = bucket(name);
|
||||
updateBucket(new Bucket(name, old.created(), old.versioning(), old.acl(),
|
||||
old.ownership(), old.publicAccessBlock(), policy));
|
||||
}
|
||||
|
||||
private void updateBucket(Bucket bucket) throws IOException {
|
||||
NavigableMap<String, Bucket> next = new TreeMap<>(buckets);
|
||||
next.put(bucket.name(), bucket);
|
||||
saveBuckets(next);
|
||||
buckets.clear();
|
||||
buckets.putAll(next);
|
||||
}
|
||||
|
||||
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) {
|
||||
String id = SigV4.hex(SigV4.hash((bucket + "/" + key).getBytes(StandardCharsets.UTF_8)));
|
||||
return versions.resolve(id.substring(0, 2)).resolve(id);
|
||||
}
|
||||
private Path versionPath(String bucket, String key, String storageId) {
|
||||
return storageId.equals("legacy") ? objectPath(bucket, key) :
|
||||
historyDirectory(bucket, key).resolve(storageId);
|
||||
}
|
||||
private static Metadata withVersion(Metadata old, String id, String bucket, String key) {
|
||||
return new Metadata(old.length(), old.modified(), old.etag(), old.sha256(), bucket, key,
|
||||
old.contentType(), old.userMetadata(), old.tags(), id, old.checksums(), old.acl());
|
||||
}
|
||||
private List<VersionRecord> history(String bucket, String key) throws IOException {
|
||||
List<VersionRecord> found = histories.get(indexKey(bucket, key));
|
||||
if (found != null) return found;
|
||||
Metadata old = index.get(indexKey(bucket, key));
|
||||
if (old == null && Files.isRegularFile(objectPath(bucket, key))) {
|
||||
try (DataInputStream input = new DataInputStream(Files.newInputStream(objectPath(bucket, key)))) {
|
||||
old = readRecord(input).metadata();
|
||||
}
|
||||
}
|
||||
return old == null ? List.of() : List.of(new VersionRecord("null", "legacy", false, old.modified()));
|
||||
}
|
||||
private void saveHistory(String bucket, String key, List<VersionRecord> entries) throws IOException {
|
||||
Path directory = historyDirectory(bucket, key);
|
||||
if (!Files.isDirectory(directory)) {
|
||||
Files.createDirectories(directory);
|
||||
syncDirectory(directory.getParent());
|
||||
}
|
||||
Path pending = Files.createTempFile(temporary, "history-", ".part");
|
||||
try {
|
||||
try (DataOutputStream output = new DataOutputStream(Files.newOutputStream(pending))) {
|
||||
output.writeInt(VERSION_MAGIC);
|
||||
output.writeUTF(bucket);
|
||||
output.writeUTF(key);
|
||||
output.writeInt(entries.size());
|
||||
for (VersionRecord entry : entries) {
|
||||
output.writeUTF(entry.id());
|
||||
output.writeUTF(entry.storageId());
|
||||
output.writeBoolean(entry.marker());
|
||||
output.writeLong(entry.modified());
|
||||
}
|
||||
}
|
||||
try (FileChannel channel = FileChannel.open(pending, StandardOpenOption.WRITE)) {
|
||||
channel.force(true);
|
||||
}
|
||||
Files.move(pending, directory.resolve("manifest"), StandardCopyOption.ATOMIC_MOVE,
|
||||
StandardCopyOption.REPLACE_EXISTING);
|
||||
syncDirectory(directory);
|
||||
} finally { Files.deleteIfExists(pending); }
|
||||
histories.put(indexKey(bucket, key), List.copyOf(entries));
|
||||
}
|
||||
private void loadHistories() throws IOException {
|
||||
Set<Path> referenced = new HashSet<>();
|
||||
try (var paths = Files.walk(versions)) {
|
||||
for (Path manifest : paths.filter(p -> p.getFileName().toString().equals("manifest")).toList()) {
|
||||
String bucket;
|
||||
String key;
|
||||
List<VersionRecord> entries = new ArrayList<>();
|
||||
try (DataInputStream input = new DataInputStream(Files.newInputStream(manifest))) {
|
||||
if (input.readInt() != VERSION_MAGIC) throw new IOException("Invalid version manifest: " + manifest);
|
||||
bucket = input.readUTF();
|
||||
key = input.readUTF();
|
||||
int count = input.readInt();
|
||||
if (count < 0 || count > 1_000_000 || !manifest.getParent().equals(historyDirectory(bucket, key)))
|
||||
throw new IOException("Invalid version manifest: " + manifest);
|
||||
Set<String> ids = new HashSet<>();
|
||||
for (int i = 0; i < count; i++) {
|
||||
String id = input.readUTF();
|
||||
String storageId = input.readUTF();
|
||||
boolean marker = input.readBoolean();
|
||||
long modified = input.readLong();
|
||||
if ((!id.equals("null") && !id.matches("[0-9a-f-]{36}")) ||
|
||||
(!marker && !storageId.equals("legacy") && !storageId.matches("[0-9a-f-]{36}")) ||
|
||||
(marker && !storageId.isEmpty()) || !ids.add(id) || modified < 0)
|
||||
throw new IOException("Invalid version manifest entry: " + manifest);
|
||||
entries.add(new VersionRecord(id, storageId, marker, modified));
|
||||
if (!marker) {
|
||||
Path file = versionPath(bucket, key, storageId);
|
||||
if (!Files.isRegularFile(file)) throw new IOException("Missing object version: " + file);
|
||||
referenced.add(file);
|
||||
if (!storageId.equals("legacy")) {
|
||||
Record record;
|
||||
try (DataInputStream data = new DataInputStream(Files.newInputStream(file))) {
|
||||
record = readRecord(data);
|
||||
}
|
||||
Metadata meta = record.metadata();
|
||||
if (!bucket.equals(meta.bucket()) || !key.equals(meta.key()) ||
|
||||
Files.size(file) - record.headerLength() != meta.length())
|
||||
throw new IOException("Invalid object version: " + file);
|
||||
objectCount++;
|
||||
used = Math.addExact(used, meta.length());
|
||||
}
|
||||
}
|
||||
}
|
||||
if (input.read() != -1 || histories.put(indexKey(bucket, key), List.copyOf(entries)) != null)
|
||||
throw new IOException("Invalid version manifest: " + manifest);
|
||||
}
|
||||
if (entries.isEmpty() || entries.getFirst().marker()) index.remove(indexKey(bucket, key));
|
||||
else {
|
||||
VersionRecord current = entries.getFirst();
|
||||
Path file = versionPath(bucket, key, current.storageId());
|
||||
try (DataInputStream input = new DataInputStream(Files.newInputStream(file))) {
|
||||
index.put(indexKey(bucket, key),
|
||||
withVersion(readRecord(input).metadata(), current.id(), bucket, key));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
try (var paths = Files.walk(versions)) {
|
||||
for (Path file : paths.filter(Files::isRegularFile).toList()) {
|
||||
if (!file.getFileName().toString().equals("manifest") && !referenced.contains(file)) {
|
||||
Files.delete(file);
|
||||
syncDirectory(file.getParent());
|
||||
}
|
||||
}
|
||||
}
|
||||
for (var entry : histories.entrySet()) {
|
||||
String[] parts = entry.getKey().split("\0", 2);
|
||||
if (entry.getValue().stream().anyMatch(version -> version.storageId().equals("legacy") && !version.marker()))
|
||||
continue;
|
||||
Path orphan = objectPath(parts[0], parts[1]);
|
||||
if (Files.isRegularFile(orphan)) {
|
||||
try (DataInputStream input = new DataInputStream(Files.newInputStream(orphan))) {
|
||||
Metadata old = readRecord(input).metadata();
|
||||
used -= old.length();
|
||||
if (old.key() == null) legacyCount--;
|
||||
}
|
||||
Files.delete(orphan);
|
||||
objectCount--;
|
||||
syncDirectory(orphan.getParent());
|
||||
}
|
||||
}
|
||||
}
|
||||
private Path objectPath(String bucket, String key) {
|
||||
String id = SigV4.hex(SigV4.hash((bucket + "/" + key).getBytes(StandardCharsets.UTF_8)));
|
||||
return objects.resolve(id.substring(0, 2)).resolve(id);
|
||||
@@ -111,88 +471,245 @@ final class DiskStore implements ObjectStorage {
|
||||
private Object lock(Path p) { return locks[(p.hashCode() & 0x7fffffff) % locks.length]; }
|
||||
|
||||
public Metadata put(String bucket, String key, InputStream input, long length, String expectedHash,
|
||||
String checksum, boolean createOnly, String contentType) throws IOException {
|
||||
String checksum, boolean createOnly, String contentType,
|
||||
Map<String, String> userMetadata, Map<String, String> tags,
|
||||
java.util.function.Supplier<Map<String, String>> checksums,
|
||||
Map<String, String> acl) throws IOException {
|
||||
if (length < 0) throw new StoreException(411, "MissingContentLength", "Content-Length is required");
|
||||
if (length > maxObject) throw new StoreException(413, "EntityTooLarge", "Object exceeds the configured size limit");
|
||||
byte[] bucketBytes = bucket.getBytes(StandardCharsets.UTF_8);
|
||||
byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8);
|
||||
byte[] typeBytes = contentType.getBytes(StandardCharsets.UTF_8);
|
||||
if (bucketBytes.length > 63 || keyBytes.length > 1024 || typeBytes.length > 255)
|
||||
throw new StoreException(400, "InvalidArgument", "Object metadata is too long");
|
||||
int headerLength = HEADER_V2 + bucketBytes.length + keyBytes.length + typeBytes.length;
|
||||
byte[] metadataBytes = ObjectAttributes.encode(userMetadata, 4096);
|
||||
byte[] tagBytes = ObjectAttributes.encode(tags, 8192);
|
||||
validateMetadataLengths(bucketBytes, keyBytes, typeBytes);
|
||||
Path destination = object(bucket, key), pending = Files.createTempFile(temporary, "upload-", ".part");
|
||||
try {
|
||||
MessageDigest sha = digest("SHA-256"), md5 = digest("MD5");
|
||||
long count = 0;
|
||||
try (OutputStream out = Files.newOutputStream(pending)) {
|
||||
out.write(new byte[headerLength]);
|
||||
byte[] buffer = new byte[65536]; int n;
|
||||
while ((n = input.read(buffer)) != -1) {
|
||||
count += n;
|
||||
if (count > length || count > maxObject)
|
||||
throw new StoreException(413, "EntityTooLarge", "Payload exceeds declared size");
|
||||
sha.update(buffer, 0, n); md5.update(buffer, 0, n); out.write(buffer, 0, n);
|
||||
}
|
||||
}
|
||||
if (count != length) throw new StoreException(400, "IncompleteBody", "Payload length does not match Content-Length");
|
||||
byte[] hash = sha.digest(), etag = md5.digest();
|
||||
if (!MessageDigest.isEqual(hash, HexFormat.of().parseHex(expectedHash)))
|
||||
throw new StoreException(400, "XAmzContentSHA256Mismatch", "Payload hash mismatch");
|
||||
if (checksum != null && !Base64.getEncoder().encodeToString(hash).equals(checksum))
|
||||
throw new StoreException(400, "BadDigest", "SHA-256 checksum mismatch");
|
||||
long modified = Instant.now().toEpochMilli();
|
||||
ByteBuffer header = ByteBuffer.allocate(headerLength).putLong(MAGIC_V2).putLong(count)
|
||||
.putLong(modified).put(etag).put(hash).putShort((short) bucketBytes.length)
|
||||
.putShort((short) keyBytes.length).putShort((short) typeBytes.length)
|
||||
.put(bucketBytes).put(keyBytes).put(typeBytes);
|
||||
header.flip();
|
||||
try (FileChannel file = FileChannel.open(pending, StandardOpenOption.WRITE)) {
|
||||
while (header.hasRemaining()) file.write(header, header.position());
|
||||
file.force(true);
|
||||
}
|
||||
Metadata metadata = new Metadata(count, modified, SigV4.hex(etag), hash, bucket, key, contentType);
|
||||
synchronized (lock(destination)) {
|
||||
long previous = 0;
|
||||
boolean existed = Files.exists(destination);
|
||||
boolean legacy = false;
|
||||
if (existed) {
|
||||
if (createOnly) throw new StoreException(412, "PreconditionFailed", "Object already exists");
|
||||
try (var in = new DataInputStream(Files.newInputStream(destination))) {
|
||||
Metadata old = readRecord(in).metadata();
|
||||
previous = old.length();
|
||||
legacy = old.key() == null;
|
||||
}
|
||||
}
|
||||
synchronized (this) {
|
||||
if (used - previous + count > maxTotal)
|
||||
throw new StoreException(507, "InsufficientStorage", "Store capacity limit reached");
|
||||
Files.move(pending, destination, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
|
||||
used = used - previous + count;
|
||||
if (!existed) objectCount++;
|
||||
if (legacy) legacyCount--;
|
||||
index.put(indexKey(bucket, key), metadata);
|
||||
syncDirectory(destination.getParent());
|
||||
}
|
||||
}
|
||||
return metadata;
|
||||
Metadata metadata = stagePut(pending, input, length, expectedHash, checksum,
|
||||
bucket, key, contentType, bucketBytes, keyBytes, typeBytes,
|
||||
metadataBytes, tagBytes, userMetadata, tags, checksums, acl);
|
||||
return installPending(destination, pending, metadata, createOnly);
|
||||
} finally { Files.deleteIfExists(pending); }
|
||||
}
|
||||
|
||||
private static void validateMetadataLengths(byte[] bucketBytes, byte[] keyBytes, byte[] typeBytes) {
|
||||
if (bucketBytes.length > 63 || keyBytes.length > 1024 || typeBytes.length > 255)
|
||||
throw new StoreException(400, "InvalidArgument", "Object metadata is too long");
|
||||
}
|
||||
|
||||
private Metadata stagePut(Path pending, InputStream input, long length, String expectedHash, String checksum,
|
||||
String bucket, String key, String contentType,
|
||||
byte[] bucketBytes, byte[] keyBytes, byte[] typeBytes,
|
||||
byte[] metadataBytes, byte[] tagBytes,
|
||||
Map<String, String> userMetadata, Map<String, String> tags,
|
||||
java.util.function.Supplier<Map<String, String>> checksums,
|
||||
Map<String, String> acl) throws IOException {
|
||||
byte[] aclBytes = ObjectAttributes.encode(acl, ACL_AREA);
|
||||
int headerLength = HEADER_V5 + aclBytes.length +
|
||||
bucketBytes.length + keyBytes.length + typeBytes.length +
|
||||
metadataBytes.length + tagBytes.length;
|
||||
MessageDigest sha = digest("SHA-256"), md5 = digest("MD5");
|
||||
Crc64Nvme crc64 = new Crc64Nvme();
|
||||
long count = 0;
|
||||
try (OutputStream out = Files.newOutputStream(pending)) {
|
||||
out.write(new byte[headerLength]);
|
||||
byte[] buffer = new byte[65536];
|
||||
int n;
|
||||
while ((n = input.read(buffer)) != -1) {
|
||||
count += n;
|
||||
if (count > length || count > maxObject)
|
||||
throw new StoreException(413, "EntityTooLarge", "Payload exceeds declared size");
|
||||
sha.update(buffer, 0, n);
|
||||
md5.update(buffer, 0, n);
|
||||
crc64.update(buffer, 0, n);
|
||||
out.write(buffer, 0, n);
|
||||
}
|
||||
}
|
||||
if (count != length) throw new StoreException(400, "IncompleteBody", "Payload length does not match Content-Length");
|
||||
byte[] hash = sha.digest(), etag = md5.digest();
|
||||
if (expectedHash != null && !MessageDigest.isEqual(hash, HexFormat.of().parseHex(expectedHash)))
|
||||
throw new StoreException(400, "XAmzContentSHA256Mismatch", "Payload hash mismatch");
|
||||
if (checksum != null && !Base64.getEncoder().encodeToString(hash).equals(checksum))
|
||||
throw new StoreException(400, "BadDigest", "SHA-256 checksum mismatch");
|
||||
Map<String, String> suppliedChecksums = checksums.get();
|
||||
Map<String, String> storedChecksums = suppliedChecksums.isEmpty() ?
|
||||
Map.of("x-amz-checksum-crc64nvme", crc64.encoded()) : Map.copyOf(suppliedChecksums);
|
||||
byte[] checksumBytes = ObjectAttributes.encode(storedChecksums, CHECKSUM_AREA);
|
||||
long modified = Instant.now().toEpochMilli();
|
||||
ByteBuffer header = ByteBuffer.allocate(headerLength).putLong(MAGIC_V5).putLong(count)
|
||||
.putLong(modified).put(etag).put(hash).putShort((short) bucketBytes.length)
|
||||
.putShort((short) keyBytes.length).putShort((short) typeBytes.length)
|
||||
.putShort((short) metadataBytes.length).putShort((short) tagBytes.length)
|
||||
.putShort((short) checksumBytes.length);
|
||||
header.position(header.position() + CHECKSUM_AREA - checksumBytes.length);
|
||||
header.put(checksumBytes).putShort((short) aclBytes.length);
|
||||
header.put(aclBytes).put(bucketBytes).put(keyBytes).put(typeBytes).put(metadataBytes).put(tagBytes);
|
||||
header.flip();
|
||||
try (FileChannel file = FileChannel.open(pending, StandardOpenOption.WRITE)) {
|
||||
while (header.hasRemaining()) file.write(header, header.position());
|
||||
file.force(true);
|
||||
}
|
||||
return new Metadata(count, modified, SigV4.hex(etag), hash, bucket, key, contentType,
|
||||
Map.copyOf(userMetadata), Map.copyOf(tags), null, storedChecksums, Map.copyOf(acl));
|
||||
}
|
||||
|
||||
private Metadata installPending(Path destination, Path pending, Metadata metadata,
|
||||
boolean createOnly) throws IOException {
|
||||
synchronized (lock(destination)) {
|
||||
synchronized (this) {
|
||||
Bucket configured = buckets.get(metadata.bucket());
|
||||
if (configured != null && configured.versioning() != VersioningState.NEVER)
|
||||
return installVersionedPending(destination, pending, metadata, createOnly,
|
||||
configured.versioning());
|
||||
}
|
||||
long previous = 0;
|
||||
boolean existed = Files.exists(destination);
|
||||
boolean legacy = false;
|
||||
if (existed) {
|
||||
if (createOnly) throw new StoreException(412, "PreconditionFailed", "Object already exists");
|
||||
try (var in = new DataInputStream(Files.newInputStream(destination))) {
|
||||
Metadata old = readRecord(in).metadata();
|
||||
previous = old.length();
|
||||
legacy = old.key() == null;
|
||||
}
|
||||
}
|
||||
long additional = Math.max(0, metadata.length() - previous);
|
||||
synchronized (this) {
|
||||
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");
|
||||
if (maxTotal - used - reservedBytes < additional)
|
||||
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);
|
||||
moved = true;
|
||||
syncDirectory(destination.getParent());
|
||||
} finally {
|
||||
synchronized (this) {
|
||||
if (moved) {
|
||||
used = used - previous + metadata.length();
|
||||
if (!existed) objectCount++;
|
||||
if (legacy) legacyCount--;
|
||||
index.put(indexKey(metadata.bucket(), metadata.key()), metadata);
|
||||
}
|
||||
reservedBytes -= additional;
|
||||
publishingByBucket.compute(metadata.bucket(), (bucket, count) -> count == 1 ? null : count - 1);
|
||||
notifyAll();
|
||||
}
|
||||
}
|
||||
return metadata;
|
||||
}
|
||||
}
|
||||
|
||||
private Metadata installVersionedPending(Path destination, Path pending, Metadata metadata,
|
||||
boolean createOnly, VersioningState state) throws IOException {
|
||||
String bucket = metadata.bucket();
|
||||
String key = metadata.key();
|
||||
if (createOnly && index.containsKey(indexKey(bucket, key)))
|
||||
throw new StoreException(412, "PreconditionFailed", "Object already exists");
|
||||
List<VersionRecord> old = history(bucket, key);
|
||||
String id = state == VersioningState.ENABLED ? UUID.randomUUID().toString() : "null";
|
||||
String storageId = UUID.randomUUID().toString();
|
||||
VersionRecord discarded = null;
|
||||
long replaced = 0;
|
||||
if (id.equals("null")) {
|
||||
for (VersionRecord entry : old) {
|
||||
if (!entry.id().equals("null") || entry.marker()) continue;
|
||||
discarded = entry;
|
||||
try (DataInputStream input = new DataInputStream(Files.newInputStream(
|
||||
versionPath(bucket, key, entry.storageId())))) {
|
||||
replaced = readRecord(input).metadata().length();
|
||||
}
|
||||
}
|
||||
}
|
||||
if (maxTotal - (used - replaced) - reservedBytes < metadata.length())
|
||||
throw new StoreException(507, "InsufficientStorage", "Store capacity limit reached");
|
||||
Path target = versionPath(bucket, key, storageId);
|
||||
Files.createDirectories(target.getParent());
|
||||
syncDirectory(target.getParent().getParent());
|
||||
Files.move(pending, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
|
||||
syncDirectory(target.getParent());
|
||||
List<VersionRecord> next = new ArrayList<>();
|
||||
next.add(new VersionRecord(id, storageId, false, metadata.modified()));
|
||||
for (VersionRecord entry : old) if (!entry.id().equals(id)) next.add(entry);
|
||||
saveHistory(bucket, key, next);
|
||||
used += metadata.length();
|
||||
objectCount++;
|
||||
Metadata current = withVersion(metadata, id, bucket, key);
|
||||
index.put(indexKey(bucket, key), current);
|
||||
if (discarded != null) removeStoredVersion(bucket, key, discarded, replaced);
|
||||
return current;
|
||||
}
|
||||
|
||||
private void removeStoredVersion(String bucket, String key, VersionRecord entry, long length) throws IOException {
|
||||
Path file = versionPath(bucket, key, entry.storageId());
|
||||
if (entry.storageId().equals("legacy")) {
|
||||
try (DataInputStream input = new DataInputStream(Files.newInputStream(file))) {
|
||||
if (readRecord(input).metadata().key() == null) legacyCount--;
|
||||
}
|
||||
}
|
||||
Files.deleteIfExists(file);
|
||||
syncDirectory(file.getParent());
|
||||
used -= length;
|
||||
objectCount--;
|
||||
}
|
||||
|
||||
public OpenObject open(String bucket, String key) throws IOException {
|
||||
return open(bucket, key, null);
|
||||
}
|
||||
|
||||
@Override public OpenObject open(String bucket, String key, String versionId) throws IOException {
|
||||
Path destination = object(bucket, key);
|
||||
synchronized (lock(destination)) {
|
||||
VersionRecord selected;
|
||||
synchronized (this) {
|
||||
List<VersionRecord> entries = history(bucket, key);
|
||||
selected = versionId == null ? (entries.isEmpty() ? null : entries.getFirst()) :
|
||||
entries.stream().filter(entry -> entry.id().equals(versionId)).findFirst().orElse(null);
|
||||
}
|
||||
if (selected == null)
|
||||
throw new StoreException(404, versionId == null ? "NoSuchKey" : "NoSuchVersion",
|
||||
"Object version not found");
|
||||
if (selected.marker())
|
||||
throw StoreException.deletedVersion(selected.id(), selected.modified(), versionId != null);
|
||||
final DataInputStream input;
|
||||
try { input = new DataInputStream(Files.newInputStream(destination)); }
|
||||
try { input = new DataInputStream(Files.newInputStream(
|
||||
versionPath(bucket, key, selected.storageId()))); }
|
||||
catch (NoSuchFileException e) { throw new StoreException(404, "NoSuchKey", "Object not found"); }
|
||||
try { return new OpenObject(readRecord(input).metadata(), input); }
|
||||
catch (IOException e) { input.close(); throw e; }
|
||||
try {
|
||||
Bucket configured = buckets.get(bucket);
|
||||
String exposedId = histories.containsKey(indexKey(bucket, key)) ||
|
||||
configured != null && configured.versioning() != VersioningState.NEVER ? selected.id() : null;
|
||||
return new OpenObject(withVersion(readRecord(input).metadata(), exposedId, bucket, key), input);
|
||||
}
|
||||
catch (IOException e) {
|
||||
input.close();
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void delete(String bucket, String key) throws IOException {
|
||||
delete(bucket, key, null);
|
||||
}
|
||||
|
||||
@Override public DeleteResult delete(String bucket, String key, String versionId) throws IOException {
|
||||
Path destination = object(bucket, key);
|
||||
synchronized (lock(destination)) {
|
||||
if (!Files.exists(destination)) return;
|
||||
synchronized (this) {
|
||||
Bucket configured = buckets.get(bucket);
|
||||
VersioningState state = configured == null ? VersioningState.NEVER : configured.versioning();
|
||||
if (state != VersioningState.NEVER || versionId != null)
|
||||
return deleteVersioned(bucket, key, versionId, state);
|
||||
}
|
||||
if (!Files.exists(destination)) return new DeleteResult(null, false);
|
||||
long length;
|
||||
boolean legacy;
|
||||
try (var input = new DataInputStream(Files.newInputStream(destination))) {
|
||||
@@ -208,9 +725,146 @@ final class DiskStore implements ObjectStorage {
|
||||
index.remove(indexKey(bucket, key));
|
||||
syncDirectory(destination.getParent());
|
||||
}
|
||||
return new DeleteResult(null, false);
|
||||
}
|
||||
}
|
||||
|
||||
private DeleteResult deleteVersioned(String bucket, String key, String versionId,
|
||||
VersioningState state) throws IOException {
|
||||
List<VersionRecord> old = history(bucket, key);
|
||||
List<VersionRecord> next = new ArrayList<>();
|
||||
VersionRecord removed = null;
|
||||
if (versionId != null) {
|
||||
for (VersionRecord entry : old) {
|
||||
if (entry.id().equals(versionId)) removed = entry;
|
||||
else next.add(entry);
|
||||
}
|
||||
if (removed == null)
|
||||
throw new StoreException(404, "NoSuchVersion", "Object version not found");
|
||||
} else {
|
||||
String id = state == VersioningState.ENABLED ? UUID.randomUUID().toString() : "null";
|
||||
next.add(new VersionRecord(id, "", true, Instant.now().toEpochMilli()));
|
||||
for (VersionRecord entry : old) {
|
||||
if (state == VersioningState.SUSPENDED && entry.id().equals("null")) removed = entry;
|
||||
else next.add(entry);
|
||||
}
|
||||
}
|
||||
saveHistory(bucket, key, next);
|
||||
updateCurrentIndex(bucket, key, next);
|
||||
if (removed != null && !removed.marker()) {
|
||||
Path file = versionPath(bucket, key, removed.storageId());
|
||||
long length;
|
||||
try (DataInputStream input = new DataInputStream(Files.newInputStream(file))) {
|
||||
length = readRecord(input).metadata().length();
|
||||
}
|
||||
removeStoredVersion(bucket, key, removed, length);
|
||||
}
|
||||
if (versionId != null) return new DeleteResult(versionId, removed.marker());
|
||||
return new DeleteResult(next.getFirst().id(), true);
|
||||
}
|
||||
|
||||
private void updateCurrentIndex(String bucket, String key, List<VersionRecord> entries) throws IOException {
|
||||
if (entries.isEmpty() || entries.getFirst().marker()) {
|
||||
index.remove(indexKey(bucket, key));
|
||||
return;
|
||||
}
|
||||
VersionRecord latest = entries.getFirst();
|
||||
try (DataInputStream input = new DataInputStream(Files.newInputStream(
|
||||
versionPath(bucket, key, latest.storageId())))) {
|
||||
index.put(indexKey(bucket, key),
|
||||
withVersion(readRecord(input).metadata(), latest.id(), bucket, key));
|
||||
}
|
||||
}
|
||||
|
||||
@Override public Map<String, String> tags(String bucket, String key) throws IOException {
|
||||
return tags(bucket, key, null);
|
||||
}
|
||||
|
||||
@Override public Map<String, String> tags(String bucket, String key, String versionId) throws IOException {
|
||||
try (OpenObject object = open(bucket, key, versionId)) { return object.metadata().tags(); }
|
||||
}
|
||||
|
||||
@Override public void setTags(String bucket, String key, Map<String, String> tags) throws IOException {
|
||||
setTags(bucket, key, null, tags);
|
||||
}
|
||||
|
||||
@Override public void setTags(String bucket, String key, String versionId,
|
||||
Map<String, String> tags) throws IOException {
|
||||
rewriteAttributes(bucket, key, versionId, tags, null);
|
||||
}
|
||||
|
||||
@Override public void setObjectAcl(String bucket, String key, String versionId,
|
||||
Map<String, String> acl) throws IOException {
|
||||
rewriteAttributes(bucket, key, versionId, null, acl);
|
||||
}
|
||||
|
||||
private void rewriteAttributes(String bucket, String key, String versionId,
|
||||
Map<String, String> tags, Map<String, String> acl) throws IOException {
|
||||
Path destination = object(bucket, key);
|
||||
synchronized (lock(destination)) {
|
||||
VersionRecord selected;
|
||||
boolean current;
|
||||
synchronized (this) {
|
||||
List<VersionRecord> entries = history(bucket, key);
|
||||
selected = versionId == null ? (entries.isEmpty() ? null : entries.getFirst()) :
|
||||
entries.stream().filter(entry -> entry.id().equals(versionId)).findFirst().orElse(null);
|
||||
current = selected != null && !entries.isEmpty() && selected == entries.getFirst();
|
||||
}
|
||||
if (selected == null || selected.marker())
|
||||
throw new StoreException(404, versionId == null ? "NoSuchKey" : "NoSuchVersion",
|
||||
"Object version not found");
|
||||
destination = versionPath(bucket, key, selected.storageId());
|
||||
Path pending = Files.createTempFile(temporary, "tags-", ".part");
|
||||
try {
|
||||
try (DataInputStream input = new DataInputStream(Files.newInputStream(destination));
|
||||
OutputStream output = Files.newOutputStream(pending)) {
|
||||
Metadata old = readRecord(input).metadata();
|
||||
if (old.key() == null) throw new StoreException(501, "NotImplemented", "Legacy object tags are unsupported");
|
||||
Metadata updated = new Metadata(old.length(), old.modified(), old.etag(), old.sha256(),
|
||||
bucket, key, old.contentType(), old.userMetadata(),
|
||||
tags == null ? old.tags() : Map.copyOf(tags),
|
||||
old.versionId(), old.checksums(),
|
||||
acl == null ? old.acl() : Map.copyOf(acl));
|
||||
output.write(recordHeader(updated));
|
||||
if (input.transferTo(output) != old.length()) throw new IOException("Object length changed during tag update");
|
||||
}
|
||||
try (FileChannel channel = FileChannel.open(pending, StandardOpenOption.WRITE)) { channel.force(true); }
|
||||
synchronized (this) {
|
||||
Files.move(pending, destination, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
|
||||
if (current) {
|
||||
Metadata old = index.get(indexKey(bucket, key));
|
||||
index.put(indexKey(bucket, key), new Metadata(old.length(), old.modified(), old.etag(),
|
||||
old.sha256(), bucket, key, old.contentType(), old.userMetadata(),
|
||||
tags == null ? old.tags() : Map.copyOf(tags),
|
||||
old.versionId(), old.checksums(),
|
||||
acl == null ? old.acl() : Map.copyOf(acl)));
|
||||
}
|
||||
syncDirectory(destination.getParent());
|
||||
}
|
||||
} finally { Files.deleteIfExists(pending); }
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] recordHeader(Metadata metadata) {
|
||||
byte[] bucket = metadata.bucket().getBytes(StandardCharsets.UTF_8);
|
||||
byte[] key = metadata.key().getBytes(StandardCharsets.UTF_8);
|
||||
byte[] type = metadata.contentType().getBytes(StandardCharsets.UTF_8);
|
||||
byte[] custom = ObjectAttributes.encode(metadata.userMetadata(), 4096);
|
||||
byte[] tags = ObjectAttributes.encode(metadata.tags(), 8192);
|
||||
byte[] checksums = ObjectAttributes.encode(metadata.checksums(), CHECKSUM_AREA);
|
||||
byte[] acl = ObjectAttributes.encode(metadata.acl(), ACL_AREA);
|
||||
ByteBuffer header = ByteBuffer.allocate(HEADER_V5 + acl.length +
|
||||
bucket.length + key.length + type.length + custom.length + tags.length)
|
||||
.putLong(MAGIC_V5).putLong(metadata.length()).putLong(metadata.modified())
|
||||
.put(HexFormat.of().parseHex(metadata.etag())).put(metadata.sha256())
|
||||
.putShort((short) bucket.length).putShort((short) key.length).putShort((short) type.length)
|
||||
.putShort((short) custom.length).putShort((short) tags.length)
|
||||
.putShort((short) checksums.length);
|
||||
header.position(header.position() + CHECKSUM_AREA - checksums.length);
|
||||
header.put(checksums).putShort((short) acl.length);
|
||||
return header.put(acl).put(bucket).put(key).put(type).put(custom).put(tags).array();
|
||||
}
|
||||
|
||||
public synchronized ListPage list(String bucket, String prefix, String delimiter, int maxKeys, String after) {
|
||||
List<ListedObject> entries = new ArrayList<>();
|
||||
List<String> prefixes = new ArrayList<>();
|
||||
@@ -227,28 +881,111 @@ final class DiskStore implements ObjectStorage {
|
||||
int at = key.indexOf(delimiter, prefix.length());
|
||||
if (at >= 0) group = key.substring(0, at + delimiter.length());
|
||||
}
|
||||
if (group != null && group.equals(activePrefix)) { lastKey = key; continue; }
|
||||
if (entries.size() + prefixes.size() >= maxKeys) { truncated = true; break; }
|
||||
if (group != null) { prefixes.add(group); activePrefix = group; }
|
||||
else { entries.add(new ListedObject(key, meta)); activePrefix = null; }
|
||||
if (group != null && group.equals(activePrefix)) {
|
||||
lastKey = key;
|
||||
continue;
|
||||
}
|
||||
if (entries.size() + prefixes.size() >= maxKeys) {
|
||||
truncated = true;
|
||||
break;
|
||||
}
|
||||
if (group != null) {
|
||||
prefixes.add(group);
|
||||
activePrefix = group;
|
||||
} else {
|
||||
entries.add(new ListedObject(key, meta));
|
||||
activePrefix = null;
|
||||
}
|
||||
lastKey = key;
|
||||
}
|
||||
return new ListPage(entries, prefixes, truncated ? lastKey : null, truncated);
|
||||
}
|
||||
|
||||
@Override public synchronized VersionPage listVersions(String bucket, String prefix,
|
||||
String keyMarker, String versionMarker,
|
||||
int maxKeys) throws IOException {
|
||||
bucket(bucket);
|
||||
if (versionMarker != null && keyMarker == null)
|
||||
throw new StoreException(400, "InvalidArgument", "Version marker requires a key marker");
|
||||
if (maxKeys == 0) return new VersionPage(List.of(), null, null, false);
|
||||
NavigableSet<String> keys = new TreeSet<>();
|
||||
for (String name : histories.keySet()) if (name.startsWith(bucket + "\0")) keys.add(name.substring(bucket.length() + 1));
|
||||
for (Metadata meta : index.values()) if (bucket.equals(meta.bucket())) keys.add(meta.key());
|
||||
List<VersionEntry> page = new ArrayList<>();
|
||||
String nextKey = null;
|
||||
String nextVersion = null;
|
||||
boolean truncated = false;
|
||||
for (String key : keys) {
|
||||
if (!key.startsWith(prefix) || keyMarker != null && key.compareTo(keyMarker) < 0) continue;
|
||||
List<VersionRecord> entries = history(bucket, key);
|
||||
boolean pastMarker = keyMarker == null || !key.equals(keyMarker) || versionMarker == null;
|
||||
for (int i = 0; i < entries.size(); i++) {
|
||||
VersionRecord entry = entries.get(i);
|
||||
if (keyMarker != null && key.equals(keyMarker)) {
|
||||
if (versionMarker == null) continue;
|
||||
if (!pastMarker) {
|
||||
if (entry.id().equals(versionMarker)) pastMarker = true;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (page.size() == maxKeys) {
|
||||
truncated = true;
|
||||
break;
|
||||
}
|
||||
Metadata meta = null;
|
||||
if (!entry.marker()) {
|
||||
try (DataInputStream input = new DataInputStream(Files.newInputStream(
|
||||
versionPath(bucket, key, entry.storageId())))) {
|
||||
meta = withVersion(readRecord(input).metadata(), entry.id(), bucket, key);
|
||||
}
|
||||
}
|
||||
page.add(new VersionEntry(key, entry.id(), entry.modified(), entry.marker(), i == 0, meta));
|
||||
nextKey = key;
|
||||
nextVersion = entry.id();
|
||||
}
|
||||
if (truncated) break;
|
||||
}
|
||||
return new VersionPage(page, truncated ? nextKey : null, truncated ? nextVersion : null, truncated);
|
||||
}
|
||||
|
||||
static Record readRecord(DataInputStream in) throws IOException {
|
||||
long magic = in.readLong();
|
||||
if (magic != MAGIC_V1 && magic != MAGIC_V2) throw new IOException("Invalid object record");
|
||||
if (magic != MAGIC_V1 && magic != MAGIC_V2 && magic != MAGIC_V3 && magic != MAGIC_V4 &&
|
||||
magic != MAGIC_V5)
|
||||
throw new IOException("Invalid object record");
|
||||
long length = in.readLong(), modified = in.readLong();
|
||||
byte[] md5 = new byte[16], sha = new byte[32];
|
||||
in.readFully(md5); in.readFully(sha);
|
||||
in.readFully(md5);
|
||||
in.readFully(sha);
|
||||
if (length < 0) throw new IOException("Invalid object record length");
|
||||
if (magic == MAGIC_V1)
|
||||
return new Record(new Metadata(length, modified, SigV4.hex(md5), sha,
|
||||
null, null, "application/octet-stream"), HEADER_V1);
|
||||
int bucketLength = in.readUnsignedShort(), keyLength = in.readUnsignedShort(), typeLength = in.readUnsignedShort();
|
||||
int metadataLength = magic == MAGIC_V3 || magic == MAGIC_V4 || magic == MAGIC_V5 ? in.readUnsignedShort() : 0;
|
||||
int tagsLength = magic == MAGIC_V3 || magic == MAGIC_V4 || magic == MAGIC_V5 ? in.readUnsignedShort() : 0;
|
||||
int checksumLength = magic == MAGIC_V4 || magic == MAGIC_V5 ? in.readUnsignedShort() : 0;
|
||||
if (bucketLength < 1 || bucketLength > 63 || keyLength < 1 || keyLength > 1024 || typeLength < 1 || typeLength > 255)
|
||||
throw new IOException("Invalid object record metadata");
|
||||
if (metadataLength > 4096 || tagsLength > 8192 || checksumLength > CHECKSUM_AREA)
|
||||
throw new IOException("Invalid object attributes");
|
||||
Map<String, String> checksums = Map.of();
|
||||
if (magic == MAGIC_V4 || magic == MAGIC_V5) {
|
||||
byte[] area = in.readNBytes(CHECKSUM_AREA);
|
||||
if (area.length != CHECKSUM_AREA) throw new IOException("Truncated checksum attributes");
|
||||
checksums = ObjectAttributes.decode(Arrays.copyOfRange(area,
|
||||
CHECKSUM_AREA - checksumLength, CHECKSUM_AREA));
|
||||
}
|
||||
Map<String, String> acl = Map.of();
|
||||
int aclLength = 0;
|
||||
if (magic == MAGIC_V5) {
|
||||
int size = in.readUnsignedShort();
|
||||
if (size > ACL_AREA) throw new IOException("Invalid object ACL");
|
||||
byte[] bytes = in.readNBytes(size);
|
||||
if (bytes.length != size) throw new IOException("Truncated object ACL");
|
||||
acl = ObjectAttributes.decode(bytes);
|
||||
aclLength = size;
|
||||
}
|
||||
String bucket = utf8(in.readNBytes(bucketLength));
|
||||
String key = utf8(in.readNBytes(keyLength));
|
||||
String contentType = utf8(in.readNBytes(typeLength));
|
||||
@@ -256,8 +993,13 @@ final class DiskStore implements ObjectStorage {
|
||||
key.getBytes(StandardCharsets.UTF_8).length != keyLength ||
|
||||
contentType.getBytes(StandardCharsets.UTF_8).length != typeLength)
|
||||
throw new IOException("Invalid object record metadata");
|
||||
Map<String, String> metadata = ObjectAttributes.decode(in.readNBytes(metadataLength));
|
||||
Map<String, String> tags = ObjectAttributes.decode(in.readNBytes(tagsLength));
|
||||
return new Record(new Metadata(length, modified, SigV4.hex(md5), sha,
|
||||
bucket, key, contentType), HEADER_V2 + bucketLength + keyLength + typeLength);
|
||||
bucket, key, contentType, metadata, tags, null, checksums, acl),
|
||||
(magic == MAGIC_V5 ? HEADER_V5 + aclLength :
|
||||
magic == MAGIC_V4 ? HEADER_V4 : magic == MAGIC_V3 ? HEADER_V3 : HEADER_V2) +
|
||||
bucketLength + keyLength + typeLength + metadataLength + tagsLength);
|
||||
}
|
||||
private static String utf8(byte[] bytes) throws IOException {
|
||||
return StandardCharsets.UTF_8.newDecoder().onMalformedInput(CodingErrorAction.REPORT)
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Map;
|
||||
|
||||
final class EncryptedVolume {
|
||||
private EncryptedVolume() {}
|
||||
|
||||
static void requireConfigured(Map<String, String> environment) throws IOException {
|
||||
requireConfigured(environment, null);
|
||||
}
|
||||
|
||||
static void requireConfigured(Map<String, String> environment, Path dataDirectory) throws IOException {
|
||||
String marker = environment.getOrDefault("ENCRYPTED_VOLUME_MARKER_FILE", "");
|
||||
String expected = environment.getOrDefault("ENCRYPTED_VOLUME_ID", "");
|
||||
if (marker.isEmpty() && expected.isEmpty()) return;
|
||||
if (!expected.matches("[a-f0-9]{32}") || marker.isEmpty())
|
||||
throw new IOException("Encrypted storage marker configuration is incomplete");
|
||||
Path path = Path.of(marker);
|
||||
if (!path.isAbsolute() || dataDirectory != null &&
|
||||
!path.normalize().equals(dataDirectory.toAbsolutePath().normalize().resolve(".objectstore-encrypted")) ||
|
||||
Files.isSymbolicLink(path) || !Files.isRegularFile(path) ||
|
||||
Files.size(path) > 33 || !Files.readString(path, StandardCharsets.US_ASCII).trim().equals(expected))
|
||||
throw new IOException("Encrypted storage volume is unavailable or does not match its marker");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
final class IdentityPolicies {
|
||||
private IdentityPolicies() { }
|
||||
|
||||
static Map<String, BucketPolicy> fromEnvironment(Map<String, String> env, String owner,
|
||||
Set<String> identities)
|
||||
throws IOException {
|
||||
String configured = env.get("S3_IDENTITY_POLICIES_DIR");
|
||||
if (configured == null || configured.isBlank()) return Map.of();
|
||||
Map<String, BucketPolicy> policies = new HashMap<>();
|
||||
try (var files = Files.newDirectoryStream(Path.of(configured), "*.json")) {
|
||||
for (Path path : files) {
|
||||
String name = path.getFileName().toString();
|
||||
String key = name.substring(0, name.length() - 5);
|
||||
if (!identities.contains(key) || key.equals(owner) || Files.isSymbolicLink(path) ||
|
||||
Files.size(path) > 20480 || policies.size() >= 256)
|
||||
throw new IllegalArgumentException("Invalid identity policy file");
|
||||
String json = Files.readString(path, StandardCharsets.UTF_8);
|
||||
policies.put(key, BucketPolicy.parseIdentity(json));
|
||||
}
|
||||
}
|
||||
return Map.copyOf(policies);
|
||||
}
|
||||
}
|
||||
@@ -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"));
|
||||
}
|
||||
}
|
||||
+238
-450
@@ -1,500 +1,288 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import com.sun.net.httpserver.HttpExchange;
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
import java.io.IOException;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.Base64;
|
||||
import java.util.HashMap;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Semaphore;
|
||||
|
||||
public final class Main {
|
||||
private static final String CAPABILITIES_PATH = "/_objectstore/capabilities";
|
||||
private final ObjectStorage store;
|
||||
private final SigV4 authentication;
|
||||
private final String bucket;
|
||||
private final MultipartStorage multipart;
|
||||
private final Semaphore slots = new Semaphore(16);
|
||||
private final S3Access access;
|
||||
private final BucketHandler bucketHandler;
|
||||
private final ObjectHandler objectHandler;
|
||||
private final ClientLimits clientLimits;
|
||||
private final Semaphore slots;
|
||||
private final String virtualHostSuffix;
|
||||
private final BrowserCors cors;
|
||||
private final KeyScopes keyScopes;
|
||||
private final RequestMetrics metrics;
|
||||
private final int maxInFlight;
|
||||
|
||||
Main(DiskStore store, SigV4 authentication, String bucket) throws IOException {
|
||||
this(store, new MultipartStore(store), authentication, bucket);
|
||||
}
|
||||
|
||||
Main(ObjectStorage store, MultipartStorage multipart, SigV4 authentication, String bucket) {
|
||||
this.store = store; this.multipart = multipart;
|
||||
this.authentication = authentication; this.bucket = bucket;
|
||||
Main(ObjectStorage store, MultipartStorage multipart, SigV4 authentication, String bucket) throws IOException {
|
||||
this(store, multipart, authentication, bucket, ClientLimits.disabled());
|
||||
}
|
||||
|
||||
Main(ObjectStorage store, MultipartStorage multipart, SigV4 authentication, String bucket,
|
||||
ClientLimits clientLimits) throws IOException {
|
||||
this(store, multipart, authentication, bucket, clientLimits, 16, "");
|
||||
}
|
||||
|
||||
Main(ObjectStorage store, MultipartStorage multipart, SigV4 authentication, String bucket,
|
||||
ClientLimits clientLimits, int maxInFlight, String virtualHostSuffix) throws IOException {
|
||||
this(store, multipart, authentication, bucket, clientLimits, maxInFlight,
|
||||
virtualHostSuffix, BrowserCors.disabled());
|
||||
}
|
||||
|
||||
Main(ObjectStorage store, MultipartStorage multipart, SigV4 authentication, String bucket,
|
||||
ClientLimits clientLimits, int maxInFlight, String virtualHostSuffix,
|
||||
BrowserCors cors) throws IOException {
|
||||
this(store, multipart, authentication, bucket, clientLimits, maxInFlight, virtualHostSuffix,
|
||||
cors, KeyScopes.unrestricted(authentication.root()));
|
||||
}
|
||||
|
||||
Main(ObjectStorage store, MultipartStorage multipart, SigV4 authentication, String bucket,
|
||||
ClientLimits clientLimits, int maxInFlight, String virtualHostSuffix,
|
||||
BrowserCors cors, KeyScopes keyScopes) throws IOException {
|
||||
this(store, multipart, authentication, bucket, clientLimits, maxInFlight,
|
||||
virtualHostSuffix, cors, keyScopes, new RequestMetrics(null));
|
||||
}
|
||||
|
||||
Main(ObjectStorage store, MultipartStorage multipart, SigV4 authentication, String bucket,
|
||||
ClientLimits clientLimits, int maxInFlight, String virtualHostSuffix,
|
||||
BrowserCors cors, KeyScopes keyScopes, RequestMetrics metrics) throws IOException {
|
||||
this(store, multipart, authentication, bucket, clientLimits, maxInFlight, virtualHostSuffix,
|
||||
cors, keyScopes, metrics, Map.of());
|
||||
}
|
||||
|
||||
Main(ObjectStorage store, MultipartStorage multipart, SigV4 authentication, String bucket,
|
||||
ClientLimits clientLimits, int maxInFlight, String virtualHostSuffix,
|
||||
BrowserCors cors, KeyScopes keyScopes, RequestMetrics metrics,
|
||||
Map<String, BucketPolicy> identityPolicies) throws IOException {
|
||||
this(store, multipart, authentication, bucket, clientLimits, maxInFlight, virtualHostSuffix,
|
||||
cors, keyScopes, metrics, identityPolicies, null);
|
||||
}
|
||||
|
||||
Main(ObjectStorage store, MultipartStorage multipart, SigV4 authentication, String bucket,
|
||||
ClientLimits clientLimits, int maxInFlight, String virtualHostSuffix,
|
||||
BrowserCors cors, KeyScopes keyScopes, RequestMetrics metrics,
|
||||
Map<String, BucketPolicy> identityPolicies, URI publicEndpoint) throws IOException {
|
||||
if (maxInFlight < 1 || maxInFlight > 1024)
|
||||
throw new IllegalArgumentException("MAX_IN_FLIGHT_REQUESTS must be between 1 and 1024");
|
||||
this.store = store;
|
||||
this.authentication = authentication;
|
||||
this.access = new S3Access(store, authentication.root(), identityPolicies);
|
||||
MultipartHandler multipartHandler = new MultipartHandler(store, multipart, authentication, access,
|
||||
publicEndpoint);
|
||||
this.bucketHandler = new BucketHandler(store, multipart, multipartHandler,
|
||||
authentication, access, bucket);
|
||||
this.objectHandler = new ObjectHandler(store, multipartHandler, authentication, access);
|
||||
this.clientLimits = clientLimits;
|
||||
this.slots = new Semaphore(maxInFlight);
|
||||
this.maxInFlight = maxInFlight;
|
||||
this.virtualHostSuffix = validateVirtualHostSuffix(virtualHostSuffix);
|
||||
this.cors = cors;
|
||||
this.keyScopes = keyScopes;
|
||||
this.metrics = metrics;
|
||||
store.ensureBucket(bucket);
|
||||
}
|
||||
|
||||
void handle(HttpExchange exchange) throws IOException {
|
||||
boolean admitted = slots.tryAcquire();
|
||||
long started = System.nanoTime();
|
||||
boolean admitted = false;
|
||||
ClientLimits.Client client = null;
|
||||
String requestId = UUID.randomUUID().toString();
|
||||
exchange.getResponseHeaders().set("x-amz-request-id", requestId);
|
||||
exchange.getResponseHeaders().set("X-Content-Type-Options", "nosniff");
|
||||
cors.decorate(exchange);
|
||||
try {
|
||||
client = clientLimits.enter(exchange);
|
||||
admitted = slots.tryAcquire();
|
||||
if (!admitted) throw new StoreException(503, "SlowDown", "Too many concurrent requests");
|
||||
if (exchange.getRequestURI().getRawPath().equals("/health") && exchange.getRequestMethod().equals("GET")) {
|
||||
byte[] body = "{\"status\":\"ok\",\"service\":\"lunarsky-objectstore\"}".getBytes(StandardCharsets.UTF_8);
|
||||
exchange.getResponseHeaders().set("Content-Type", "application/json");
|
||||
exchange.sendResponseHeaders(200, body.length);
|
||||
exchange.getResponseBody().write(body);
|
||||
return;
|
||||
}
|
||||
if (exchange.getRequestURI().getRawPath().equals("/ready") && exchange.getRequestMethod().equals("GET")) {
|
||||
boolean ready = store.ready();
|
||||
byte[] body = (ready ? "ready" : "unavailable").getBytes(StandardCharsets.UTF_8);
|
||||
exchange.getResponseHeaders().set("Content-Type", "text/plain; charset=utf-8");
|
||||
exchange.sendResponseHeaders(ready ? 200 : 503, body.length);
|
||||
exchange.getResponseBody().write(body);
|
||||
return;
|
||||
}
|
||||
String hash = authentication.verify(exchange.getRequestMethod(), exchange.getRequestURI(), exchange.getRequestHeaders());
|
||||
String path = SigV4.decode(exchange.getRequestURI().getRawPath());
|
||||
Map<String, String> query = query(exchange.getRequestURI().getRawQuery());
|
||||
if (path.equals("/" + bucket) || path.equals("/" + bucket + "/")) {
|
||||
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"))))
|
||||
unsupported("Bucket operation");
|
||||
requireEmptyBody(exchange, hash);
|
||||
listObjects(exchange, query);
|
||||
return;
|
||||
}
|
||||
String prefix = "/" + bucket + "/";
|
||||
if (!path.startsWith(prefix)) throw new StoreException(404, "NoSuchBucket", "Bucket not found");
|
||||
String key = path.substring(prefix.length());
|
||||
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();
|
||||
boolean multipartRequest = multipartRequest(method, query);
|
||||
if (!multipartRequest && !query.isEmpty() && !(query.size() == 1 &&
|
||||
("PutObject".equals(query.get("x-id")) || "GetObject".equals(query.get("x-id")) ||
|
||||
"HeadObject".equals(query.get("x-id")) || "DeleteObject".equals(query.get("x-id")))))
|
||||
unsupported("Query operation");
|
||||
var headers = exchange.getRequestHeaders();
|
||||
for (String name : headers.keySet()) {
|
||||
String lower = name.toLowerCase(java.util.Locale.ROOT);
|
||||
if (lower.startsWith("x-amz-") && !java.util.Set.of("x-amz-date", "x-amz-content-sha256",
|
||||
"x-amz-checksum-sha256", "x-amz-sdk-checksum-algorithm", "x-amz-user-agent").contains(lower))
|
||||
unsupported("Amazon header");
|
||||
if (lower.startsWith("x-amz-meta-") || lower.startsWith("x-amz-server-side-") ||
|
||||
lower.startsWith("x-amz-copy-") || lower.startsWith("x-amz-acl") ||
|
||||
lower.startsWith("x-amz-grant") || lower.startsWith("x-amz-tagging") ||
|
||||
lower.equals("content-md5")) unsupported("Object metadata, encryption, ACL, copy, tagging or MD5 header");
|
||||
if (lower.startsWith("x-amz-checksum-") && !lower.equals("x-amz-checksum-sha256"))
|
||||
unsupported("Checksum algorithm");
|
||||
}
|
||||
String algorithm = SigV4.single(headers, "x-amz-sdk-checksum-algorithm");
|
||||
if (algorithm != null && !algorithm.equals("SHA256")) unsupported("Checksum algorithm");
|
||||
if (multipartRequest) {
|
||||
handleMultipart(exchange, method, query, key, hash);
|
||||
return;
|
||||
}
|
||||
if (!method.equals("PUT")) requireEmptyBody(exchange, hash);
|
||||
switch (method) {
|
||||
case "PUT" -> {
|
||||
String length = SigV4.single(headers, "content-length"), condition = SigV4.single(headers, "if-none-match");
|
||||
if (condition != null && !condition.equals("*")) 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 (headers.containsKey("content-encoding")) unsupported("Encoded payload");
|
||||
String contentType = contentType(headers);
|
||||
ObjectStorage.Metadata data = store.put(bucket, key, exchange.getRequestBody(), bytes, hash,
|
||||
SigV4.single(headers, "x-amz-checksum-sha256"), condition != null, contentType);
|
||||
exchange.getResponseHeaders().set("ETag", "\"" + data.etag() + "\"");
|
||||
exchange.getResponseHeaders().set("x-amz-checksum-sha256", Base64.getEncoder().encodeToString(data.sha256()));
|
||||
exchange.sendResponseHeaders(200, -1);
|
||||
}
|
||||
case "GET", "HEAD" -> readObject(exchange, key);
|
||||
case "DELETE" -> {
|
||||
if (headers.containsKey("if-none-match")) unsupported("Conditional delete");
|
||||
store.delete(bucket, key);
|
||||
exchange.sendResponseHeaders(204, -1);
|
||||
}
|
||||
default -> unsupported("HTTP method");
|
||||
}
|
||||
} catch (StoreException error) { sendError(exchange, error.status, error.code, error.getMessage(), requestId); }
|
||||
catch (Exception error) {
|
||||
if (cors.preflight(exchange)) return;
|
||||
if (handleStatus(exchange)) return;
|
||||
dispatch(exchange);
|
||||
} catch (StoreException error) {
|
||||
sendStoreError(exchange, error, requestId);
|
||||
} catch (Exception error) {
|
||||
System.err.println("ObjectStore request failed: " + requestId + " " + error.getClass().getSimpleName());
|
||||
sendError(exchange, 500, "InternalError", "Storage operation failed", requestId);
|
||||
} finally { if (admitted) slots.release(); exchange.close(); }
|
||||
S3Xml.sendError(exchange, 500, "InternalError", "Storage operation failed", requestId);
|
||||
} finally {
|
||||
try { exchange.close(); }
|
||||
finally {
|
||||
if (admitted) slots.release();
|
||||
clientLimits.leave(client);
|
||||
metrics.record(exchange.getResponseCode(), System.nanoTime() - started);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private 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;
|
||||
}
|
||||
|
||||
private 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(SigV4.hex(SigV4.hash(new byte[0]))))
|
||||
throw new StoreException(400, "InvalidRequest", "Request must have an empty body");
|
||||
}
|
||||
|
||||
private 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", "x-id")::contains))
|
||||
return false;
|
||||
String xId = query.get("x-id");
|
||||
if (method.equals("PUT")) return query.containsKey("partNumber") &&
|
||||
(xId == null || xId.equals("UploadPart"));
|
||||
if (query.containsKey("partNumber")) return false;
|
||||
return (method.equals("POST") && (xId == null || xId.equals("CompleteMultipartUpload"))) ||
|
||||
(method.equals("DELETE") && (xId == null || xId.equals("AbortMultipartUpload")));
|
||||
}
|
||||
|
||||
private void handleMultipart(HttpExchange exchange, String method, Map<String, String> query,
|
||||
String key, String hash) throws IOException {
|
||||
var headers = exchange.getRequestHeaders();
|
||||
if (headers.containsKey("content-encoding") || headers.containsKey("if-none-match"))
|
||||
unsupported("Multipart request header");
|
||||
if (query.containsKey("uploads")) {
|
||||
requireEmptyBody(exchange, hash);
|
||||
String id = multipart.create(bucket, key, contentType(headers));
|
||||
sendXml(exchange, 200, "<InitiateMultipartUploadResult><Bucket>" + xml(bucket) +
|
||||
"</Bucket><Key>" + xml(key) + "</Key><UploadId>" + id +
|
||||
"</UploadId></InitiateMultipartUploadResult>");
|
||||
private void dispatch(HttpExchange exchange) throws IOException {
|
||||
SigV4.Verified verified = anonymousRead(exchange)
|
||||
? new SigV4.Verified("UNSIGNED-PAYLOAD", exchange.getRequestURI().getRawQuery(),
|
||||
null, null, null, null, null)
|
||||
: authentication.verifyRequest(exchange.getRequestMethod(),
|
||||
exchange.getRequestURI(), exchange.getRequestHeaders());
|
||||
String path = SigV4.decode(exchange.getRequestURI().getRawPath());
|
||||
Map<String, String> query = S3Request.query(verified.applicationQuery());
|
||||
if (path.equals(CAPABILITIES_PATH)) {
|
||||
access.requireOwner(verified.principal());
|
||||
if (!exchange.getRequestMethod().equals("GET")) S3Request.unsupported("Capability operation");
|
||||
if (!query.isEmpty())
|
||||
throw new StoreException(400, "InvalidArgument", "Capability request has unsupported query parameters");
|
||||
S3Request.requireEmptyBody(exchange, verified.payload());
|
||||
capabilities(exchange);
|
||||
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 = contentLength(headers);
|
||||
String etag = multipart.putPart(id, bucket, key, number, exchange.getRequestBody(), length,
|
||||
hash, SigV4.single(headers, "x-amz-checksum-sha256"));
|
||||
exchange.getResponseHeaders().set("ETag", "\"" + etag + "\"");
|
||||
exchange.sendResponseHeaders(200, -1);
|
||||
}
|
||||
case "POST" -> {
|
||||
byte[] body = signedBody(exchange, hash, 65536);
|
||||
List<MultipartStorage.Part> parts = completedParts(body);
|
||||
var meta = multipart.complete(id, bucket, key, parts);
|
||||
sendXml(exchange, 200, "<CompleteMultipartUploadResult><Bucket>" + xml(bucket) +
|
||||
"</Bucket><Key>" + xml(key) + "</Key><ETag>"" + meta.etag() +
|
||||
""</ETag></CompleteMultipartUploadResult>");
|
||||
}
|
||||
case "DELETE" -> {
|
||||
requireEmptyBody(exchange, hash);
|
||||
multipart.abort(id, bucket, key);
|
||||
exchange.sendResponseHeaders(204, -1);
|
||||
}
|
||||
default -> unsupported("Multipart operation");
|
||||
String hostBucket = virtualHostBucket(exchange);
|
||||
if (path.equals("/") && hostBucket == null) {
|
||||
access.requireOwner(verified.principal());
|
||||
if (!exchange.getRequestMethod().equals("GET") ||
|
||||
!(query.isEmpty() || query.size() == 1 && "ListBuckets".equals(query.get("x-id"))))
|
||||
S3Request.unsupported("Service operation");
|
||||
S3Request.requireEmptyBody(exchange, verified.payload());
|
||||
bucketHandler.listBuckets(exchange);
|
||||
return;
|
||||
}
|
||||
int slash = path.indexOf('/', 1);
|
||||
String requestedBucket = hostBucket == null ?
|
||||
(slash < 0 ? path.substring(1) : path.substring(1, slash)) : hostBucket;
|
||||
if (requestedBucket.isEmpty()) throw new StoreException(404, "NoSuchBucket", "Bucket not found");
|
||||
if (hostBucket != null ? path.equals("/") : slash < 0 || slash == path.length() - 1) {
|
||||
keyScopes.checkBucket(verified.principal(), requestedBucket, exchange.getRequestMethod(), query);
|
||||
bucketHandler.handleBucket(exchange, query, verified.payload(), requestedBucket, verified.principal());
|
||||
} else {
|
||||
store.bucket(requestedBucket);
|
||||
String key = hostBucket == null ? path.substring(slash + 1) : path.substring(1);
|
||||
keyScopes.checkObject(verified.principal(), requestedBucket, key,
|
||||
exchange.getRequestMethod(), query, exchange.getRequestHeaders());
|
||||
objectHandler.handleObject(exchange, key,
|
||||
query, verified, requestedBucket);
|
||||
}
|
||||
}
|
||||
|
||||
private 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"); }
|
||||
private static String validateVirtualHostSuffix(String value) {
|
||||
if (value == null || value.isBlank()) return "";
|
||||
String suffix = value.toLowerCase(Locale.ROOT);
|
||||
if (suffix.length() > 253 || !suffix.matches("[a-z0-9-]+(?:\\.[a-z0-9-]+)*") ||
|
||||
java.util.Arrays.stream(suffix.split("\\.")).anyMatch(
|
||||
label -> label.length() > 63 || label.startsWith("-") || label.endsWith("-")))
|
||||
throw new IllegalArgumentException("Invalid S3_VIRTUAL_HOST_SUFFIX");
|
||||
return suffix;
|
||||
}
|
||||
private static byte[] signedBody(HttpExchange exchange, String hash, int limit) throws IOException {
|
||||
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 (!SigV4.hex(SigV4.hash(body)).equals(hash))
|
||||
throw new StoreException(400, "XAmzContentSHA256Mismatch", "Payload hash mismatch");
|
||||
return body;
|
||||
|
||||
private String virtualHostBucket(HttpExchange exchange) {
|
||||
if (virtualHostSuffix.isEmpty()) return null;
|
||||
String host = exchange.getRequestHeaders().getFirst("Host");
|
||||
if (host == null) throw new StoreException(400, "InvalidRequest", "Missing Host header");
|
||||
host = host.toLowerCase(Locale.ROOT).replaceFirst(":\\d+$", "");
|
||||
String ending = "." + virtualHostSuffix;
|
||||
if (!host.endsWith(ending)) return null;
|
||||
String bucketName = host.substring(0, host.length() - ending.length());
|
||||
if (!bucketName.matches("[a-z0-9][a-z0-9-]{1,61}[a-z0-9]"))
|
||||
throw new StoreException(400, "InvalidRequest", "Invalid bucket hostname");
|
||||
return bucketName;
|
||||
}
|
||||
private 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");
|
||||
|
||||
private void sendStoreError(HttpExchange exchange, StoreException error, String requestId) throws IOException {
|
||||
if (error.status == 503 && error.code.equals("SlowDown"))
|
||||
exchange.getResponseHeaders().set("Retry-After", "1");
|
||||
if (anonymousRead(exchange) && error.status == 404)
|
||||
error = new StoreException(403, "AccessDenied", "Access denied");
|
||||
if (error.deleteMarker) {
|
||||
exchange.getResponseHeaders().set("x-amz-delete-marker", "true");
|
||||
exchange.getResponseHeaders().set("x-amz-version-id", error.versionId);
|
||||
if (error.modified >= 0) exchange.getResponseHeaders().set("Last-Modified",
|
||||
DateTimeFormatter.RFC_1123_DATE_TIME.withZone(ZoneOffset.UTC)
|
||||
.format(Instant.ofEpochMilli(error.modified)));
|
||||
}
|
||||
S3Xml.sendError(exchange, error.status, error.code, error.getMessage(), requestId);
|
||||
}
|
||||
private 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);
|
||||
|
||||
private static boolean anonymousRead(HttpExchange exchange) {
|
||||
if (!exchange.getRequestMethod().equals("GET") &&
|
||||
!exchange.getRequestMethod().equals("HEAD")) return false;
|
||||
if (exchange.getRequestHeaders().containsKey("authorization")) return false;
|
||||
if (exchange.getRequestHeaders().keySet().stream().anyMatch(
|
||||
name -> name.toLowerCase(Locale.ROOT).startsWith("x-amz-"))) return false;
|
||||
String query = exchange.getRequestURI().getRawQuery();
|
||||
return query == null || !query.toLowerCase(Locale.ROOT).contains("x-amz-");
|
||||
}
|
||||
|
||||
private boolean handleStatus(HttpExchange exchange) throws IOException {
|
||||
if (!exchange.getRequestMethod().equals("GET")) return false;
|
||||
String path = exchange.getRequestURI().getRawPath();
|
||||
if (path.equals("/metrics") && metrics.enabled()) {
|
||||
if (!metrics.authorized(exchange.getRequestHeaders().getFirst("Authorization")))
|
||||
throw new StoreException(401, "AccessDenied", "Metrics token is required");
|
||||
byte[] body = metrics.render(maxInFlight - slots.availablePermits())
|
||||
.getBytes(StandardCharsets.UTF_8);
|
||||
exchange.getResponseHeaders().set("Content-Type", "text/plain; version=0.0.4; charset=utf-8");
|
||||
exchange.sendResponseHeaders(200, body.length);
|
||||
exchange.getResponseBody().write(body);
|
||||
return true;
|
||||
}
|
||||
if (path.equals("/health")) {
|
||||
byte[] body = "{\"status\":\"ok\",\"service\":\"lunarsky-objectstore\"}".getBytes(StandardCharsets.UTF_8);
|
||||
exchange.getResponseHeaders().set("Content-Type", "application/json");
|
||||
exchange.sendResponseHeaders(200, body.length);
|
||||
exchange.getResponseBody().write(body);
|
||||
return true;
|
||||
}
|
||||
if (!path.equals("/ready")) return false;
|
||||
boolean ready = store.ready();
|
||||
byte[] body = (ready ? "ready" : "unavailable").getBytes(StandardCharsets.UTF_8);
|
||||
exchange.getResponseHeaders().set("Content-Type", "text/plain; charset=utf-8");
|
||||
exchange.sendResponseHeaders(ready ? 200 : 503, body.length);
|
||||
exchange.getResponseBody().write(body);
|
||||
return true;
|
||||
}
|
||||
|
||||
private void readObject(HttpExchange exchange, String key) throws IOException {
|
||||
var headers = exchange.getRequestHeaders();
|
||||
if (headers.containsKey("if-match") || headers.containsKey("if-modified-since") ||
|
||||
headers.containsKey("if-unmodified-since")) unsupported("Conditional read");
|
||||
try (var object = store.open(bucket, key)) {
|
||||
var meta = object.metadata();
|
||||
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;
|
||||
private void capabilities(HttpExchange exchange) throws IOException {
|
||||
ObjectStorage.Limits limits = store.limits();
|
||||
String mode = store instanceof ClusterStore ? "cluster" : "disk";
|
||||
String body = """
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"service": "lunarsky-objectstore",
|
||||
"serviceVersion": "%s",
|
||||
"storageMode": "%s",
|
||||
"operations": [
|
||||
"ListBuckets", "CreateBucket", "HeadBucket", "DeleteBucket", "ListObjectsV2",
|
||||
"PutObject", "GetObject", "HeadObject", "DeleteObject", "CopyObject",
|
||||
"GetObjectTagging", "PutObjectTagging", "DeleteObjectTagging",
|
||||
"CreateMultipartUpload", "UploadPart", "ListParts", "CompleteMultipartUpload",
|
||||
"AbortMultipartUpload", "ListMultipartUploads",
|
||||
"GetBucketVersioning", "PutBucketVersioning", "ListObjectVersions",
|
||||
"GetBucketAcl", "PutBucketAcl", "GetObjectAcl", "PutObjectAcl"
|
||||
],
|
||||
"limits": {
|
||||
"maxObjectBytes": %d,
|
||||
"maxTotalBytes": %d,
|
||||
"maxParts": 10000
|
||||
}
|
||||
}
|
||||
Range range;
|
||||
try { range = 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);
|
||||
response.set("Last-Modified", DateTimeFormatter.RFC_1123_DATE_TIME.withZone(ZoneOffset.UTC)
|
||||
.format(Instant.ofEpochMilli(meta.modified())));
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
""".formatted(Version.VALUE, mode, limits.maxObjectBytes(), limits.maxTotalBytes());
|
||||
byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
|
||||
exchange.getResponseHeaders().set("Content-Type", "application/json; charset=utf-8");
|
||||
exchange.getResponseHeaders().set("Cache-Control", "no-store");
|
||||
exchange.sendResponseHeaders(200, bytes.length);
|
||||
exchange.getResponseBody().write(bytes);
|
||||
}
|
||||
|
||||
private record Range(long start, long end, boolean partial) {
|
||||
long length() { return end < start ? 0 : end - start + 1; }
|
||||
}
|
||||
private 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");
|
||||
}
|
||||
}
|
||||
|
||||
private void listObjects(HttpExchange exchange, Map<String, String> query) throws IOException {
|
||||
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");
|
||||
}
|
||||
}
|
||||
var page = store.list(bucket, prefix, delimiter, maxKeys, after);
|
||||
StringBuilder xml = new StringBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\"?><ListBucketResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">");
|
||||
xml.append("<Name>").append(xml(bucket)).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(maxKeys)
|
||||
.append("</MaxKeys><IsTruncated>").append(page.truncated()).append("</IsTruncated>");
|
||||
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>"")
|
||||
.append(meta.etag()).append(""</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>");
|
||||
}
|
||||
}
|
||||
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);
|
||||
}
|
||||
|
||||
private static String listKey(String key, String encoding) {
|
||||
return encoding == null ? key : SigV4.encode(key, false);
|
||||
}
|
||||
private 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;
|
||||
}
|
||||
private static void unsupported(String feature) { throw new StoreException(501, "NotImplemented", feature + " is not supported"); }
|
||||
private static String xml(String text) {
|
||||
return text.replace("&", "&").replace("<", "<").replace(">", ">").replace("\"", """);
|
||||
}
|
||||
private 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);
|
||||
}
|
||||
public static void main(String[] args) 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");
|
||||
long maxObject = Long.parseLong(env.getOrDefault("MAX_OBJECT_BYTES", "134217728"));
|
||||
long maxTotal = Long.parseLong(env.getOrDefault("MAX_TOTAL_BYTES", "2147483648"));
|
||||
if (maxObject < 1 || maxObject > 1073741824L || maxTotal < maxObject)
|
||||
throw new IllegalArgumentException("Invalid size limits");
|
||||
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 = new UnavailableMultipart();
|
||||
} 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");
|
||||
var app = new Main(store, multipart, new SigV4(access, secret, region, Clock.systemUTC()), bucket);
|
||||
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), 64);
|
||||
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, app.multipart, bucket, region, port);
|
||||
else System.out.println("ObjectStore local cluster prototype v" + Version.VALUE + " listening on :" + port);
|
||||
}
|
||||
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;
|
||||
ObjectStoreServer.start();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import com.sun.net.httpserver.HttpExchange;
|
||||
import com.sun.net.httpserver.HttpsExchange;
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
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 S3Access access;
|
||||
private final String owner;
|
||||
private final URI publicEndpoint;
|
||||
|
||||
MultipartHandler(ObjectStorage store, MultipartStorage multipart, SigV4 authentication,
|
||||
S3Access access, URI publicEndpoint) {
|
||||
this.store = store;
|
||||
this.multipart = multipart;
|
||||
this.authentication = authentication;
|
||||
this.access = access;
|
||||
this.owner = authentication.root();
|
||||
this.publicEndpoint = publicEndpoint;
|
||||
}
|
||||
|
||||
void handleMultipart(HttpExchange exchange, String method, Map<String, String> query,
|
||||
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");
|
||||
boolean initiate = query.containsKey("uploads");
|
||||
if (!method.equals("PUT") && (headers.containsKey("content-md5") ||
|
||||
headers.containsKey("x-amz-sdk-checksum-algorithm") ||
|
||||
headers.keySet().stream().anyMatch(name -> {
|
||||
String lower = name.toLowerCase(Locale.ROOT);
|
||||
return lower.startsWith("x-amz-checksum-") &&
|
||||
!(initiate && lower.equals("x-amz-checksum-algorithm"));
|
||||
})))
|
||||
S3Request.unsupported("Multipart checksum header");
|
||||
if (initiate) {
|
||||
String algorithm = SigV4.single(headers, "x-amz-checksum-algorithm");
|
||||
if (algorithm != null && !algorithm.equals("CRC32"))
|
||||
S3Request.unsupported("Multipart checksum algorithm");
|
||||
S3Request.requireEmptyBody(exchange, hash);
|
||||
Map<String, String> acl = Acl.fromHeaders(headers, authentication.identities());
|
||||
BucketSecurity.checkAcl(store.bucket(bucketName), headers, acl, false);
|
||||
if (!acl.isEmpty() && !owner.equals(verified.principal()))
|
||||
access.requireBucket(bucketName, verified.principal(), Acl.WRITE_ACP);
|
||||
String id = multipart.create(bucketName, key, S3Request.contentType(headers),
|
||||
ObjectAttributes.userMetadata(headers),
|
||||
ObjectAttributes.tagsHeader(SigV4.single(headers, "x-amz-tagging")), acl);
|
||||
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><Location>" +
|
||||
S3Xml.xml(location(exchange, bucketName, key)) + "</Location><Bucket>" + S3Xml.xml(bucketName) +
|
||||
"</Bucket><Key>" + S3Xml.xml(key) + "</Key><ETag>"" + meta.etag() +
|
||||
""</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 String location(HttpExchange exchange, String bucket, String key) {
|
||||
String host = SigV4.single(exchange.getRequestHeaders(), "host");
|
||||
if (host == null) throw new StoreException(400, "InvalidRequest", "Missing Host header");
|
||||
String scheme = exchange instanceof HttpsExchange ? "https" : "http";
|
||||
return objectLocation(publicEndpoint, host, scheme, exchange.getRequestURI().getRawPath(), bucket, key);
|
||||
}
|
||||
|
||||
static String objectLocation(URI endpoint, String host, String scheme, String rawPath,
|
||||
String bucket, String key) {
|
||||
if (endpoint != null)
|
||||
return endpoint + "/" + bucket + "/" + SigV4.encode(key, true);
|
||||
return URI.create(scheme + "://" + host + rawPath).toASCIIString();
|
||||
}
|
||||
|
||||
private void listParts(HttpExchange exchange, String id, String key, Map<String, String> query,
|
||||
String bucketName) throws IOException {
|
||||
int marker = S3Request.boundedNumber(query.get("part-number-marker"), 0, 10000, 0);
|
||||
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>"")
|
||||
.append(part.etag()).append(""</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());
|
||||
}
|
||||
}
|
||||
@@ -3,15 +3,39 @@ package cloud.lunarsky.store;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
interface MultipartStorage {
|
||||
record Part(int number, String etag) {}
|
||||
record Part(int number, String etag, String checksumCrc32) {
|
||||
Part(int number, String etag) { this(number, etag, null); }
|
||||
|
||||
String create(String bucket, String key, String contentType) throws IOException;
|
||||
void verifyCrc32(long value) {
|
||||
if (checksumCrc32 == null) return;
|
||||
byte[] bytes = java.nio.ByteBuffer.allocate(4).putInt((int) value).array();
|
||||
if (!checksumCrc32.equals(java.util.Base64.getEncoder().encodeToString(bytes)))
|
||||
throw new StoreException(400, "BadDigest", "Part CRC32 checksum mismatch");
|
||||
}
|
||||
}
|
||||
record PartInfo(int number, long length, String etag, long modified) {}
|
||||
record PartPage(List<PartInfo> parts, int nextMarker, boolean truncated) {}
|
||||
record UploadInfo(String id, String key, long created) {}
|
||||
|
||||
String create(String bucket, String key, String contentType,
|
||||
Map<String, String> userMetadata, Map<String, String> tags,
|
||||
Map<String, String> acl) throws IOException;
|
||||
default String create(String bucket, String key, String contentType,
|
||||
Map<String, String> userMetadata, Map<String, String> tags) throws IOException {
|
||||
return create(bucket, key, contentType, userMetadata, tags, Map.of());
|
||||
}
|
||||
default String create(String bucket, String key, String contentType) throws IOException {
|
||||
return create(bucket, key, contentType, Map.of(), Map.of());
|
||||
}
|
||||
String putPart(String id, String bucket, String key, int number, InputStream input,
|
||||
long length, String expectedHash, String checksum) throws IOException;
|
||||
ObjectStorage.Metadata complete(String id, String bucket, String key, List<Part> parts) throws IOException;
|
||||
void abort(String id, String bucket, String key) throws IOException;
|
||||
PartPage listParts(String id, String bucket, String key, int marker, int maxParts) throws IOException;
|
||||
List<UploadInfo> listUploads(String bucket, String prefix) throws IOException;
|
||||
int activeUploads();
|
||||
long stagedBytes();
|
||||
}
|
||||
@@ -8,12 +8,16 @@ import cloud.lunarsky.store.MultipartStorage.Part;
|
||||
|
||||
final class MultipartStore implements MultipartStorage {
|
||||
private static final int MAGIC = 0x4c534d50;
|
||||
private static final int MAGIC_V2 = 0x4c534d51;
|
||||
private static final int MAGIC_V3 = 0x4c534d52;
|
||||
private final DiskStore store;
|
||||
private final Path root;
|
||||
private long staged;
|
||||
private int active;
|
||||
|
||||
private record Upload(String bucket, String key, String contentType) {}
|
||||
private record Upload(String bucket, String key, String contentType,
|
||||
Map<String, String> userMetadata, Map<String, String> tags,
|
||||
Map<String, String> acl) {}
|
||||
|
||||
MultipartStore(DiskStore store) throws IOException {
|
||||
this.store = store;
|
||||
@@ -42,17 +46,29 @@ final class MultipartStore implements MultipartStorage {
|
||||
if (staged > store.maxTotal()) throw new IOException("Multipart staging limit exceeded");
|
||||
}
|
||||
|
||||
public synchronized String create(String bucket, String key, String contentType) throws IOException {
|
||||
public synchronized String create(String bucket, String key, String contentType,
|
||||
Map<String, String> userMetadata, Map<String, String> tags,
|
||||
Map<String, String> acl) throws IOException {
|
||||
if (Files.exists(store.root().resolve("buckets.bin"))) store.bucket(bucket);
|
||||
if (active >= 32) throw new StoreException(503, "SlowDown", "Too many active uploads");
|
||||
String id = UUID.randomUUID().toString();
|
||||
Path pending = root.resolve(".creating-" + id), dir = root.resolve(id);
|
||||
Files.createDirectory(pending);
|
||||
try {
|
||||
try (var output = new DataOutputStream(Files.newOutputStream(pending.resolve("manifest"), StandardOpenOption.CREATE_NEW))) {
|
||||
output.writeInt(MAGIC);
|
||||
output.writeInt(MAGIC_V3);
|
||||
output.writeUTF(bucket);
|
||||
output.writeUTF(key);
|
||||
output.writeUTF(contentType);
|
||||
byte[] custom = ObjectAttributes.encode(userMetadata, 4096);
|
||||
byte[] encodedTags = ObjectAttributes.encode(tags, 8192);
|
||||
output.writeShort(custom.length);
|
||||
output.write(custom);
|
||||
output.writeShort(encodedTags.length);
|
||||
output.write(encodedTags);
|
||||
byte[] encodedAcl = ObjectAttributes.encode(acl, 2048);
|
||||
output.writeShort(encodedAcl.length);
|
||||
output.write(encodedAcl);
|
||||
}
|
||||
try (var channel = java.nio.channels.FileChannel.open(pending.resolve("manifest"), StandardOpenOption.READ)) {
|
||||
channel.force(true);
|
||||
@@ -97,16 +113,19 @@ final class MultipartStore implements MultipartStorage {
|
||||
MessageDigest sha = digest("SHA-256"), md5 = digest("MD5");
|
||||
long count = 0;
|
||||
try (var output = Files.newOutputStream(pending)) {
|
||||
byte[] buffer = new byte[65536]; int n;
|
||||
byte[] buffer = new byte[65536];
|
||||
int n;
|
||||
while ((n = input.read(buffer)) != -1) {
|
||||
count += n;
|
||||
if (count > length) throw new StoreException(413, "EntityTooLarge", "Part exceeds declared size");
|
||||
sha.update(buffer, 0, n); md5.update(buffer, 0, n); output.write(buffer, 0, n);
|
||||
sha.update(buffer, 0, n);
|
||||
md5.update(buffer, 0, n);
|
||||
output.write(buffer, 0, n);
|
||||
}
|
||||
}
|
||||
if (count != length) throw new StoreException(400, "IncompleteBody", "Part length does not match Content-Length");
|
||||
byte[] actual = sha.digest();
|
||||
if (!MessageDigest.isEqual(actual, HexFormat.of().parseHex(expectedHash)))
|
||||
if (expectedHash != null && !MessageDigest.isEqual(actual, HexFormat.of().parseHex(expectedHash)))
|
||||
throw new StoreException(400, "XAmzContentSHA256Mismatch", "Part hash mismatch");
|
||||
if (checksum != null && !Base64.getEncoder().encodeToString(actual).equals(checksum))
|
||||
throw new StoreException(400, "BadDigest", "SHA-256 checksum mismatch");
|
||||
@@ -124,7 +143,8 @@ final class MultipartStore implements MultipartStorage {
|
||||
throw new StoreException(400, "InvalidPart", "No valid parts supplied");
|
||||
MessageDigest sha = digest("SHA-256");
|
||||
List<Path> paths = new ArrayList<>();
|
||||
long total = 0; int last = 0;
|
||||
long total = 0;
|
||||
int last = 0;
|
||||
for (Part part : parts) {
|
||||
if (part.number() <= last || part.number() > 10000)
|
||||
throw new StoreException(400, "InvalidPartOrder", "Parts must be in ascending order");
|
||||
@@ -135,18 +155,26 @@ final class MultipartStore implements MultipartStorage {
|
||||
total += length;
|
||||
if (total > store.maxObject()) throw new StoreException(413, "EntityTooLarge", "Object exceeds the configured size limit");
|
||||
MessageDigest md5 = digest("MD5");
|
||||
java.util.zip.CRC32 crc32 = new java.util.zip.CRC32();
|
||||
try (var input = Files.newInputStream(file)) {
|
||||
byte[] buffer = new byte[65536]; int n;
|
||||
while ((n = input.read(buffer)) != -1) { sha.update(buffer, 0, n); md5.update(buffer, 0, n); }
|
||||
byte[] buffer = new byte[65536];
|
||||
int n;
|
||||
while ((n = input.read(buffer)) != -1) {
|
||||
sha.update(buffer, 0, n);
|
||||
md5.update(buffer, 0, n);
|
||||
crc32.update(buffer, 0, n);
|
||||
}
|
||||
}
|
||||
if (!SigV4.hex(md5.digest()).equals(part.etag().replace("\"", "")))
|
||||
throw new StoreException(400, "InvalidPart", "Part ETag mismatch");
|
||||
part.verifyCrc32(crc32.getValue());
|
||||
paths.add(file);
|
||||
}
|
||||
ObjectStorage.Metadata result;
|
||||
try (InputStream input = new PartsInput(paths)) {
|
||||
Upload upload = readUpload(dir);
|
||||
result = store.put(bucket, key, input, total, SigV4.hex(sha.digest()), null, false,
|
||||
readUpload(dir).contentType());
|
||||
upload.contentType(), upload.userMetadata(), upload.tags(), Map::of, upload.acl());
|
||||
}
|
||||
remove(dir);
|
||||
return result;
|
||||
@@ -156,6 +184,48 @@ final class MultipartStore implements MultipartStorage {
|
||||
remove(upload(id, bucket, key));
|
||||
}
|
||||
|
||||
@Override public synchronized PartPage listParts(String id, String bucket, String key,
|
||||
int marker, int maxParts) throws IOException {
|
||||
Path dir = upload(id, bucket, key);
|
||||
List<PartInfo> parts = new ArrayList<>();
|
||||
boolean truncated = false;
|
||||
try (var files = Files.list(dir)) {
|
||||
for (Path file : files.filter(path -> path.getFileName().toString().matches("part-[0-9]{5}"))
|
||||
.sorted().toList()) {
|
||||
int number = Integer.parseInt(file.getFileName().toString().substring(5));
|
||||
if (number <= marker) continue;
|
||||
if (parts.size() == maxParts) {
|
||||
truncated = true;
|
||||
break;
|
||||
}
|
||||
MessageDigest md5 = digest("MD5");
|
||||
try (InputStream input = Files.newInputStream(file)) {
|
||||
byte[] buffer = new byte[65536];
|
||||
int count;
|
||||
while ((count = input.read(buffer)) != -1) md5.update(buffer, 0, count);
|
||||
}
|
||||
parts.add(new PartInfo(number, Files.size(file), SigV4.hex(md5.digest()),
|
||||
Files.getLastModifiedTime(file).toMillis()));
|
||||
}
|
||||
}
|
||||
int next = parts.isEmpty() ? marker : parts.getLast().number();
|
||||
return new PartPage(parts, next, truncated);
|
||||
}
|
||||
|
||||
@Override public synchronized List<UploadInfo> listUploads(String bucket, String prefix) throws IOException {
|
||||
List<UploadInfo> uploads = new ArrayList<>();
|
||||
try (var dirs = Files.list(root)) {
|
||||
for (Path dir : dirs.filter(Files::isDirectory).toList()) {
|
||||
Upload upload = readUpload(dir);
|
||||
if (upload.bucket().equals(bucket) && upload.key().startsWith(prefix))
|
||||
uploads.add(new UploadInfo(dir.getFileName().toString(), upload.key(),
|
||||
Files.getLastModifiedTime(dir.resolve("manifest")).toMillis()));
|
||||
}
|
||||
}
|
||||
uploads.sort(Comparator.comparing(UploadInfo::key).thenComparing(UploadInfo::id));
|
||||
return uploads;
|
||||
}
|
||||
|
||||
private Path upload(String id, String bucket, String key) throws IOException {
|
||||
if (!id.matches("[0-9a-f-]{36}")) throw new StoreException(404, "NoSuchUpload", "Upload not found");
|
||||
Path dir = root.resolve(id);
|
||||
@@ -167,8 +237,14 @@ final class MultipartStore implements MultipartStorage {
|
||||
}
|
||||
private static Upload readUpload(Path dir) throws IOException {
|
||||
try (var input = new DataInputStream(Files.newInputStream(dir.resolve("manifest")))) {
|
||||
if (input.readInt() != MAGIC) throw new IOException("Invalid multipart upload manifest");
|
||||
Upload upload = new Upload(input.readUTF(), input.readUTF(), input.readUTF());
|
||||
int magic = input.readInt();
|
||||
if (magic != MAGIC && magic != MAGIC_V2 && magic != MAGIC_V3)
|
||||
throw new IOException("Invalid multipart upload manifest");
|
||||
String bucket = input.readUTF(), key = input.readUTF(), type = input.readUTF();
|
||||
Map<String, String> custom = magic != MAGIC ? ObjectAttributes.decode(input.readNBytes(input.readUnsignedShort())) : Map.of();
|
||||
Map<String, String> tags = magic != MAGIC ? ObjectAttributes.decode(input.readNBytes(input.readUnsignedShort())) : Map.of();
|
||||
Map<String, String> acl = magic == MAGIC_V3 ? ObjectAttributes.decode(input.readNBytes(input.readUnsignedShort())) : Map.of();
|
||||
Upload upload = new Upload(bucket, key, type, custom, tags, acl);
|
||||
if (input.read() != -1) throw new IOException("Invalid multipart upload manifest");
|
||||
return upload;
|
||||
}
|
||||
@@ -209,7 +285,8 @@ final class MultipartStore implements MultipartStorage {
|
||||
}
|
||||
int n = current.read(buffer, offset, length);
|
||||
if (n >= 0) return n;
|
||||
current.close(); current = null;
|
||||
current.close();
|
||||
current = null;
|
||||
}
|
||||
}
|
||||
@Override public void close() throws IOException { if (current != null) current.close(); }
|
||||
|
||||
@@ -9,22 +9,33 @@ import java.net.http.HttpResponse;
|
||||
import java.security.MessageDigest;
|
||||
import java.time.Duration;
|
||||
import java.util.HashSet;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
final class NodeClient {
|
||||
record Node(UUID id, UUID hostId, URI url) {}
|
||||
record StoredSegment(UUID id, long modified) {}
|
||||
|
||||
private static final HttpClient IDENTITY_HTTP = HttpClient.newBuilder()
|
||||
.connectTimeout(Duration.ofSeconds(2)).build();
|
||||
private static HttpClient identityHttp;
|
||||
private final List<Node> nodes;
|
||||
private final String token;
|
||||
private final String repairToken;
|
||||
private final HttpClient http = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(3)).build();
|
||||
private final HttpClient http;
|
||||
private final ConcurrentHashMap<UUID, Long> unreadableUntil = new ConcurrentHashMap<>();
|
||||
private final ConcurrentHashMap<UUID, Long> healthyUntil = new ConcurrentHashMap<>();
|
||||
private static final long READ_RETRY_NANOS = TimeUnit.SECONDS.toNanos(5);
|
||||
private static final long HEALTH_FRESH_NANOS = TimeUnit.SECONDS.toNanos(3);
|
||||
|
||||
NodeClient(List<Node> nodes, String token, String repairToken) {
|
||||
NodeClient(List<Node> nodes, String token, String repairToken) throws IOException {
|
||||
this(nodes, token, repairToken, ClusterTls.client(System.getenv(), Duration.ofSeconds(3)));
|
||||
}
|
||||
|
||||
NodeClient(List<Node> nodes, String token, String repairToken, HttpClient http) {
|
||||
if (nodes.isEmpty() || nodes.stream().map(Node::id).distinct().count() != nodes.size() ||
|
||||
nodes.stream().map(Node::url).distinct().count() != nodes.size())
|
||||
throw new IllegalArgumentException("Cluster node IDs and URLs must be unique");
|
||||
@@ -37,13 +48,17 @@ final class NodeClient {
|
||||
this.nodes = List.copyOf(nodes);
|
||||
this.token = token;
|
||||
this.repairToken = repairToken;
|
||||
this.http = java.util.Objects.requireNonNull(http);
|
||||
}
|
||||
|
||||
int count() { return nodes.size(); }
|
||||
List<Node> nodes() { return nodes; }
|
||||
Node node(int index) { return nodes.get(index); }
|
||||
boolean repairTokenUnavailable() { return repairToken == null || repairToken.length() < 32; }
|
||||
int index(UUID id) {
|
||||
for (int i = 0; i < nodes.size(); i++) if (nodes.get(i).id().equals(id)) return i;
|
||||
for (int i = 0; i < nodes.size(); i++) {
|
||||
if (nodes.get(i).id().equals(id)) return i;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
UUID faultDomain(int index, boolean testNodeDomains) {
|
||||
@@ -52,12 +67,16 @@ final class NodeClient {
|
||||
}
|
||||
|
||||
static NodeIdentity probe(URI url, String token) throws IOException {
|
||||
return probe(url, token, identityHttp());
|
||||
}
|
||||
|
||||
static NodeIdentity probe(URI url, String token, HttpClient http) throws IOException {
|
||||
validateUrl(url);
|
||||
if (token == null || token.length() < 32) throw new IllegalArgumentException("Invalid cluster token");
|
||||
HttpRequest request = HttpRequest.newBuilder(url.resolve("/identity"))
|
||||
.timeout(Duration.ofSeconds(2)).header("X-Cluster-Token", token).GET().build();
|
||||
try {
|
||||
HttpResponse<InputStream> response = IDENTITY_HTTP.send(request, HttpResponse.BodyHandlers.ofInputStream());
|
||||
HttpResponse<InputStream> response = http.send(request, HttpResponse.BodyHandlers.ofInputStream());
|
||||
try (InputStream body = response.body()) {
|
||||
if (response.statusCode() != 200) throw new IOException("Node identity request failed: " + response.statusCode());
|
||||
byte[] bytes = body.readNBytes(128);
|
||||
@@ -74,28 +93,70 @@ final class NodeClient {
|
||||
}
|
||||
}
|
||||
|
||||
static NodeIdentity probeIfAvailable(URI url, String token) {
|
||||
try { return probe(url, token); }
|
||||
catch (IOException offline) { return null; }
|
||||
}
|
||||
|
||||
private static NodeIdentity probeIfAvailable(URI url, String token, HttpClient http) {
|
||||
try { return probe(url, token, http); }
|
||||
catch (IOException offline) { return null; }
|
||||
}
|
||||
|
||||
private static synchronized HttpClient identityHttp() throws IOException {
|
||||
if (identityHttp == null)
|
||||
identityHttp = ClusterTls.client(System.getenv(), Duration.ofSeconds(2));
|
||||
return identityHttp;
|
||||
}
|
||||
|
||||
static void validateUrl(URI url) {
|
||||
if (url == null || !"http".equals(url.getScheme()) || url.getHost() == null ||
|
||||
String trustStore = System.getenv("CLUSTER_TLS_TRUSTSTORE");
|
||||
validateUrl(url, trustStore != null && !trustStore.isBlank());
|
||||
}
|
||||
|
||||
static void validateUrl(URI url, boolean requireHttps) {
|
||||
if (url == null || !("http".equals(url.getScheme()) || "https".equals(url.getScheme())) ||
|
||||
url.getHost() == null ||
|
||||
url.getPort() < 1 || url.getRawUserInfo() != null ||
|
||||
(url.getRawPath() != null && !url.getRawPath().isEmpty()) ||
|
||||
url.getRawQuery() != null || url.getRawFragment() != null)
|
||||
throw new IllegalArgumentException("Invalid private storage node URL");
|
||||
if (requireHttps && !"https".equals(url.getScheme()))
|
||||
throw new IllegalArgumentException("Cluster TLS truststore requires HTTPS node URLs");
|
||||
}
|
||||
|
||||
boolean availableHostsAtLeast(int required, boolean testNodeDomains) {
|
||||
Set<UUID> healthy = new HashSet<>();
|
||||
for (int i = 0; i < nodes.size(); i++) {
|
||||
Node node = nodes.get(i);
|
||||
try {
|
||||
NodeIdentity actual = probe(node.url(), token);
|
||||
if (actual.nodeId().equals(node.id()) && actual.hostId().equals(node.hostId()))
|
||||
healthy.add(faultDomain(i, testNodeDomains));
|
||||
if (healthy.size() >= required) return true;
|
||||
} catch (IOException error) { }
|
||||
NodeIdentity actual = probeIfAvailable(node.url(), token, http);
|
||||
if (actual == null || !actual.nodeId().equals(node.id()) || !actual.hostId().equals(node.hostId())) {
|
||||
markUnreadable(node);
|
||||
continue;
|
||||
}
|
||||
unreadableUntil.remove(node.id());
|
||||
healthyUntil.put(node.id(), System.nanoTime() + HEALTH_FRESH_NANOS);
|
||||
healthy.add(faultDomain(i, testNodeDomains));
|
||||
if (healthy.size() >= required) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private void markUnreadable(Node node) {
|
||||
healthyUntil.remove(node.id());
|
||||
unreadableUntil.put(node.id(), System.nanoTime() + READ_RETRY_NANOS);
|
||||
}
|
||||
|
||||
private boolean unreadable(Node node) {
|
||||
Long until = unreadableUntil.get(node.id());
|
||||
return until != null && System.nanoTime() - until < 0;
|
||||
}
|
||||
|
||||
private boolean recentlyHealthy(Node node) {
|
||||
Long until = healthyUntil.get(node.id());
|
||||
return until != null && System.nanoTime() - until < 0;
|
||||
}
|
||||
|
||||
void put(int index, UUID id, byte[] data, byte[] sha256) throws IOException {
|
||||
put(index, id, data, sha256, false);
|
||||
}
|
||||
@@ -123,20 +184,94 @@ final class NodeClient {
|
||||
byte[] get(int index, UUID id, int length, byte[] sha256) throws IOException {
|
||||
if (length < 1 || length > ClusterNode.MAX_SEGMENT) throw new IOException("Invalid segment length");
|
||||
Node node = nodes.get(index);
|
||||
if (unreadable(node)) throw new IOException("Storage node is temporarily unreachable");
|
||||
if (!recentlyHealthy(node)) {
|
||||
NodeIdentity actual = probeIfAvailable(node.url(), token, http);
|
||||
if (actual == null || !actual.nodeId().equals(node.id()) || !actual.hostId().equals(node.hostId())) {
|
||||
markUnreadable(node);
|
||||
throw new IOException("Storage node is temporarily unreachable");
|
||||
}
|
||||
healthyUntil.put(node.id(), System.nanoTime() + HEALTH_FRESH_NANOS);
|
||||
}
|
||||
HttpRequest request = HttpRequest.newBuilder(node.url().resolve("/segments/" + id))
|
||||
.timeout(Duration.ofSeconds(30)).header("X-Cluster-Token", token)
|
||||
.header("X-Cluster-Expected-Node", node.id().toString()).GET().build();
|
||||
HttpResponse<InputStream> response;
|
||||
try { response = send(request, HttpResponse.BodyHandlers.ofInputStream()); }
|
||||
catch (IOException error) {
|
||||
markUnreadable(node);
|
||||
throw error;
|
||||
}
|
||||
if (response.statusCode() != 200) {
|
||||
response.body().close();
|
||||
throw new IOException("Node " + node.id() + " has no verified copy of segment " + id);
|
||||
}
|
||||
byte[] bytes;
|
||||
try (InputStream body = response.body()) { bytes = body.readNBytes(length + 1); }
|
||||
catch (IOException error) {
|
||||
markUnreadable(node);
|
||||
throw error;
|
||||
}
|
||||
if (bytes.length != length || !MessageDigest.isEqual(SigV4.hash(bytes), sha256))
|
||||
throw new IOException("Node " + node.id() + " has no verified copy of segment " + id);
|
||||
unreadableUntil.remove(node.id());
|
||||
healthyUntil.put(node.id(), System.nanoTime() + HEALTH_FRESH_NANOS);
|
||||
return bytes;
|
||||
}
|
||||
|
||||
List<StoredSegment> inventory(int index, String shard, UUID after) throws IOException {
|
||||
if (repairToken == null || repairToken.length() < 32)
|
||||
throw new IOException("Repair authority is not available to this process");
|
||||
Node node = nodes.get(index);
|
||||
String path = "/segments?shard=" + shard + (after == null ? "" : "&after=" + after);
|
||||
HttpRequest request = HttpRequest.newBuilder(node.url().resolve(path))
|
||||
.timeout(Duration.ofSeconds(30)).header("X-Cluster-Token", token)
|
||||
.header("X-Cluster-Expected-Node", node.id().toString())
|
||||
.header("X-Cluster-Repair-Token", repairToken).GET().build();
|
||||
HttpResponse<InputStream> response = send(request, HttpResponse.BodyHandlers.ofInputStream());
|
||||
try (InputStream body = response.body()) {
|
||||
if (response.statusCode() != 200)
|
||||
throw new IOException("Node " + node.id() + " has no verified copy of segment " + id);
|
||||
byte[] bytes = body.readNBytes(length + 1);
|
||||
if (bytes.length != length || !MessageDigest.isEqual(SigV4.hash(bytes), sha256))
|
||||
throw new IOException("Node " + node.id() + " has no verified copy of segment " + id);
|
||||
return bytes;
|
||||
if (response.statusCode() != 200) throw new IOException("Node inventory failed: " + response.statusCode());
|
||||
byte[] bytes = body.readNBytes(70001);
|
||||
if (bytes.length > 70000) throw new IOException("Node inventory response is too large");
|
||||
List<StoredSegment> result = new ArrayList<>();
|
||||
String last = after == null ? "" : after.toString();
|
||||
for (String line : new String(bytes, java.nio.charset.StandardCharsets.US_ASCII).split("\n")) {
|
||||
if (line.isEmpty()) continue;
|
||||
String[] fields = line.split(" ", -1);
|
||||
if (fields.length != 2) throw new IOException("Invalid node inventory response");
|
||||
try {
|
||||
UUID id = UUID.fromString(fields[0]);
|
||||
if (!id.toString().equals(fields[0]) || !fields[0].startsWith(shard) ||
|
||||
fields[0].compareTo(last) <= 0)
|
||||
throw new IOException("Invalid node inventory cursor");
|
||||
result.add(new StoredSegment(id, Long.parseLong(fields[1])));
|
||||
last = fields[0];
|
||||
} catch (IllegalArgumentException error) {
|
||||
throw new IOException("Invalid node inventory response", error);
|
||||
}
|
||||
}
|
||||
if (result.size() > 1000) throw new IOException("Node inventory page is too large");
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
boolean deleteOrphan(int index, StoredSegment segment, long minimumAgeMillis) throws IOException {
|
||||
if (repairToken == null || repairToken.length() < 32)
|
||||
throw new IOException("Repair authority is not available to this process");
|
||||
Node node = nodes.get(index);
|
||||
HttpRequest request = HttpRequest.newBuilder(node.url().resolve("/segments/" + segment.id()))
|
||||
.timeout(Duration.ofSeconds(30)).header("X-Cluster-Token", token)
|
||||
.header("X-Cluster-Expected-Node", node.id().toString())
|
||||
.header("X-Cluster-Repair-Token", repairToken)
|
||||
.header("X-Cluster-Expected-Mtime", Long.toString(segment.modified()))
|
||||
.header("X-Cluster-Gc-Min-Age-Millis", Long.toString(minimumAgeMillis))
|
||||
.DELETE().build();
|
||||
HttpResponse<Void> response = send(request, HttpResponse.BodyHandlers.discarding());
|
||||
if (response.statusCode() == 204) return true;
|
||||
if (response.statusCode() == 404 || response.statusCode() == 409) return false;
|
||||
throw new IOException("Node refused orphan deletion: " + response.statusCode());
|
||||
}
|
||||
|
||||
private <T> HttpResponse<T> send(HttpRequest request, HttpResponse.BodyHandler<T> handler) throws IOException {
|
||||
try { return http.send(request, handler); }
|
||||
catch (InterruptedException error) {
|
||||
|
||||
@@ -52,7 +52,8 @@ final class NodeRegistry {
|
||||
connection.commit();
|
||||
return new NodeClient.Node(identity.nodeId(), identity.hostId(), url);
|
||||
} catch (SQLException | IOException error) {
|
||||
try { connection.rollback(); } catch (SQLException rollback) { error.addSuppressed(rollback); }
|
||||
try { connection.rollback(); }
|
||||
catch (SQLException rollback) { error.addSuppressed(rollback); }
|
||||
if (error instanceof IOException io) throw io;
|
||||
throw new IOException("Node registration failed", error);
|
||||
} finally {
|
||||
@@ -69,61 +70,16 @@ final class NodeRegistry {
|
||||
try (Statement statement = connection.createStatement()) {
|
||||
statement.execute("SELECT pg_advisory_xact_lock(6834071092781)");
|
||||
}
|
||||
Map<String, NodeClient.Node> stored = new HashMap<>();
|
||||
try (Statement statement = connection.createStatement();
|
||||
ResultSet result = statement.executeQuery("SELECT node_id, host_id, endpoint FROM cluster_nodes WHERE state <> 'retired'")) {
|
||||
while (result.next()) {
|
||||
URI url = URI.create(result.getString(3));
|
||||
stored.put(url.toString(), new NodeClient.Node((UUID) result.getObject(1),
|
||||
(UUID) result.getObject(2), url));
|
||||
}
|
||||
}
|
||||
if (stored.isEmpty()) {
|
||||
try (Statement statement = connection.createStatement();
|
||||
ResultSet result = statement.executeQuery("SELECT EXISTS (SELECT 1 FROM cluster_segments)")) {
|
||||
result.next();
|
||||
if (result.getBoolean(1)) throw new IOException("Existing segments have no registered node identities");
|
||||
}
|
||||
for (URI url : urls) {
|
||||
NodeIdentity identity = NodeClient.probe(url, token);
|
||||
try (PreparedStatement insert = connection.prepareStatement(
|
||||
"INSERT INTO cluster_nodes (node_id, host_id, endpoint, state) VALUES (?, ?, ?, 'active')")) {
|
||||
insert.setObject(1, identity.nodeId());
|
||||
insert.setObject(2, identity.hostId());
|
||||
insert.setString(3, url.toString());
|
||||
insert.executeUpdate();
|
||||
}
|
||||
stored.put(url.toString(), new NodeClient.Node(identity.nodeId(), identity.hostId(), url));
|
||||
}
|
||||
}
|
||||
List<NodeClient.Node> configured = new ArrayList<>();
|
||||
Set<UUID> configuredIds = new HashSet<>();
|
||||
for (URI url : urls) {
|
||||
NodeClient.Node node = stored.get(url.toString());
|
||||
if (node == null) throw new IOException("Unregistered storage node URL: " + url);
|
||||
NodeIdentity actual = null;
|
||||
try {
|
||||
actual = NodeClient.probe(url, token);
|
||||
} catch (IOException offline) { }
|
||||
if (actual != null && (!actual.nodeId().equals(node.id()) || !actual.hostId().equals(node.hostId())))
|
||||
throw new IOException("Storage node identity changed at " + url);
|
||||
configured.add(node);
|
||||
configuredIds.add(node.id());
|
||||
}
|
||||
try (Statement statement = connection.createStatement();
|
||||
ResultSet result = statement.executeQuery(
|
||||
"SELECT DISTINCT unnest(s.replica_ids) FROM cluster_segments s JOIN cluster_objects o ON o.generation=s.generation")) {
|
||||
while (result.next()) {
|
||||
UUID id = (UUID) result.getObject(1);
|
||||
if (!configuredIds.contains(id))
|
||||
throw new IOException("A live segment refers to a node missing from CLUSTER_NODES: " + id);
|
||||
}
|
||||
}
|
||||
Map<String, NodeClient.Node> stored = registeredNodes(connection);
|
||||
if (stored.isEmpty()) registerInitialNodes(connection, urls, token, stored);
|
||||
List<NodeClient.Node> configured = configuredNodes(urls, token, stored);
|
||||
ensureLiveReplicasConfigured(connection, configured);
|
||||
NodeClient nodes = new NodeClient(configured, token, repairToken);
|
||||
connection.commit();
|
||||
return nodes;
|
||||
} catch (SQLException | IOException | RuntimeException error) {
|
||||
try { connection.rollback(); } catch (SQLException rollback) { error.addSuppressed(rollback); }
|
||||
try { connection.rollback(); }
|
||||
catch (SQLException rollback) { error.addSuppressed(rollback); }
|
||||
if (error instanceof IOException io) throw io;
|
||||
if (error instanceof SQLException sql) throw new IOException("Node registry check failed", sql);
|
||||
throw (RuntimeException) error;
|
||||
@@ -132,4 +88,66 @@ final class NodeRegistry {
|
||||
catch (SQLException error) { throw new IOException("Could not restore metadata connection", error); }
|
||||
}
|
||||
}
|
||||
|
||||
private static Map<String, NodeClient.Node> registeredNodes(Connection connection) throws SQLException {
|
||||
Map<String, NodeClient.Node> stored = new HashMap<>();
|
||||
try (Statement statement = connection.createStatement();
|
||||
ResultSet result = statement.executeQuery("SELECT node_id, host_id, endpoint FROM cluster_nodes WHERE state <> 'retired'")) {
|
||||
while (result.next()) {
|
||||
URI url = URI.create(result.getString(3));
|
||||
stored.put(url.toString(), new NodeClient.Node((UUID) result.getObject(1),
|
||||
(UUID) result.getObject(2), url));
|
||||
}
|
||||
}
|
||||
return stored;
|
||||
}
|
||||
|
||||
private static void registerInitialNodes(Connection connection, List<URI> urls, String token,
|
||||
Map<String, NodeClient.Node> stored) throws SQLException, IOException {
|
||||
try (Statement statement = connection.createStatement();
|
||||
ResultSet result = statement.executeQuery("SELECT EXISTS (SELECT 1 FROM cluster_segments)")) {
|
||||
result.next();
|
||||
if (result.getBoolean(1)) throw new IOException("Existing segments have no registered node identities");
|
||||
}
|
||||
for (URI url : urls) {
|
||||
NodeIdentity identity = NodeClient.probe(url, token);
|
||||
try (PreparedStatement insert = connection.prepareStatement(
|
||||
"INSERT INTO cluster_nodes (node_id, host_id, endpoint, state) VALUES (?, ?, ?, 'active')")) {
|
||||
insert.setObject(1, identity.nodeId());
|
||||
insert.setObject(2, identity.hostId());
|
||||
insert.setString(3, url.toString());
|
||||
insert.executeUpdate();
|
||||
}
|
||||
stored.put(url.toString(), new NodeClient.Node(identity.nodeId(), identity.hostId(), url));
|
||||
}
|
||||
}
|
||||
|
||||
private static List<NodeClient.Node> configuredNodes(List<URI> urls, String token,
|
||||
Map<String, NodeClient.Node> stored) throws IOException {
|
||||
List<NodeClient.Node> configured = new ArrayList<>();
|
||||
for (URI url : urls) {
|
||||
NodeClient.Node node = stored.get(url.toString());
|
||||
if (node == null) throw new IOException("Unregistered storage node URL: " + url);
|
||||
NodeIdentity actual = NodeClient.probeIfAvailable(url, token);
|
||||
if (actual != null && (!actual.nodeId().equals(node.id()) || !actual.hostId().equals(node.hostId())))
|
||||
throw new IOException("Storage node identity changed at " + url);
|
||||
configured.add(node);
|
||||
}
|
||||
return configured;
|
||||
}
|
||||
|
||||
private static void ensureLiveReplicasConfigured(Connection connection, List<NodeClient.Node> configured)
|
||||
throws SQLException, IOException {
|
||||
Set<UUID> configuredIds = new HashSet<>();
|
||||
for (NodeClient.Node node : configured) configuredIds.add(node.id());
|
||||
try (Statement statement = connection.createStatement();
|
||||
ResultSet result = statement.executeQuery(
|
||||
"SELECT DISTINCT unnest(s.replica_ids) FROM cluster_segments s JOIN cluster_objects o ON o.generation=s.generation")) {
|
||||
while (result.next()) {
|
||||
UUID id = (UUID) result.getObject(1);
|
||||
if (!configuredIds.contains(id))
|
||||
throw new IOException("A live segment refers to a node missing from CLUSTER_NODES: " + id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import com.sun.net.httpserver.Headers;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.DataInputStream;
|
||||
import java.io.DataOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
|
||||
final class ObjectAttributes {
|
||||
private ObjectAttributes() {}
|
||||
|
||||
static Map<String, String> userMetadata(Headers headers) {
|
||||
Map<String, String> values = new TreeMap<>();
|
||||
int total = 0;
|
||||
for (String name : headers.keySet()) {
|
||||
if (!name.toLowerCase(java.util.Locale.ROOT).startsWith("x-amz-meta-")) continue;
|
||||
String key = name.substring(11).toLowerCase(java.util.Locale.ROOT);
|
||||
if (!key.matches("[a-z0-9][a-z0-9._-]{0,127}"))
|
||||
throw new StoreException(400, "InvalidArgument", "Invalid user metadata key");
|
||||
String value = SigV4.single(headers, name);
|
||||
if (value == null || !value.chars().allMatch(c -> c >= 32 && c <= 126))
|
||||
throw new StoreException(400, "InvalidArgument", "Invalid user metadata value");
|
||||
total += key.getBytes(StandardCharsets.UTF_8).length + value.getBytes(StandardCharsets.UTF_8).length;
|
||||
values.put(key, value);
|
||||
}
|
||||
if (total > 2048) throw new StoreException(400, "MetadataTooLarge", "User metadata exceeds 2 KiB");
|
||||
return Map.copyOf(values);
|
||||
}
|
||||
|
||||
static Map<String, String> tagsHeader(String raw) {
|
||||
if (raw == null) return Map.of();
|
||||
Map<String, String> tags = new TreeMap<>();
|
||||
if (raw.isEmpty()) return tags;
|
||||
for (String pair : raw.split("&", -1)) {
|
||||
String[] parts = pair.split("=", 2);
|
||||
if (parts.length != 2) throw new StoreException(400, "InvalidTag", "Invalid tagging header");
|
||||
String key = SigV4.decode(parts[0]);
|
||||
String value = SigV4.decode(parts[1]);
|
||||
if (tags.put(key, value) != null) throw new StoreException(400, "InvalidTag", "Duplicate tag key");
|
||||
}
|
||||
validateTags(tags);
|
||||
return Map.copyOf(tags);
|
||||
}
|
||||
|
||||
static void validateTags(Map<String, String> tags) {
|
||||
if (tags.size() > 10) throw new StoreException(400, "InvalidTag", "Too many object tags");
|
||||
for (var entry : tags.entrySet()) {
|
||||
if (entry.getKey().isEmpty() || entry.getKey().length() > 128 ||
|
||||
entry.getValue().length() > 256 ||
|
||||
!xmlText(entry.getKey()) || !xmlText(entry.getValue()))
|
||||
throw new StoreException(400, "InvalidTag", "Invalid tag key or value");
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean xmlText(String value) {
|
||||
for (int i = 0; i < value.length();) {
|
||||
int point = value.codePointAt(i);
|
||||
if (point < 32 || point > 0x10ffff || point >= 0xd800 && point <= 0xdfff ||
|
||||
point >= 0xfffe && point <= 0xffff) return false;
|
||||
i += Character.charCount(point);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
static byte[] encode(Map<String, String> values, int limit) {
|
||||
try {
|
||||
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
|
||||
DataOutputStream output = new DataOutputStream(bytes);
|
||||
output.writeShort(values.size());
|
||||
for (var entry : new TreeMap<>(values).entrySet()) {
|
||||
byte[] key = entry.getKey().getBytes(StandardCharsets.UTF_8);
|
||||
byte[] value = entry.getValue().getBytes(StandardCharsets.UTF_8);
|
||||
output.writeShort(key.length);
|
||||
output.writeShort(value.length);
|
||||
output.write(key);
|
||||
output.write(value);
|
||||
}
|
||||
if (bytes.size() > limit) throw new StoreException(400, "InvalidArgument", "Object attributes are too large");
|
||||
return bytes.toByteArray();
|
||||
} catch (IOException error) { throw new IllegalStateException(error); }
|
||||
}
|
||||
|
||||
static Map<String, String> decode(byte[] bytes) throws IOException {
|
||||
if (bytes == null || bytes.length == 0) return Map.of();
|
||||
try (DataInputStream input = new DataInputStream(new ByteArrayInputStream(bytes))) {
|
||||
int count = input.readUnsignedShort();
|
||||
if (count > 128) throw new IOException("Invalid object attributes");
|
||||
Map<String, String> values = new TreeMap<>();
|
||||
for (int i = 0; i < count; i++) {
|
||||
int keyLength = input.readUnsignedShort(), valueLength = input.readUnsignedShort();
|
||||
String key = decodeUtf8(input.readNBytes(keyLength), keyLength);
|
||||
String value = decodeUtf8(input.readNBytes(valueLength), valueLength);
|
||||
if (values.put(key, value) != null) throw new IOException("Duplicate object attribute");
|
||||
}
|
||||
if (input.available() != 0) throw new IOException("Trailing object attributes");
|
||||
return Map.copyOf(values);
|
||||
}
|
||||
}
|
||||
|
||||
private static String decodeUtf8(byte[] bytes, int length) throws IOException {
|
||||
if (bytes.length != length) throw new IOException("Truncated object attributes");
|
||||
try {
|
||||
return StandardCharsets.UTF_8.newDecoder()
|
||||
.onMalformedInput(java.nio.charset.CodingErrorAction.REPORT)
|
||||
.decode(java.nio.ByteBuffer.wrap(bytes)).toString();
|
||||
} catch (java.nio.charset.CharacterCodingException error) {
|
||||
throw new IOException("Invalid object attributes", error);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,346 @@
|
||||
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")) {
|
||||
access.requireObject(bucketName, key, metadata, principal, Acl.READ_ACP,
|
||||
versionId == null ? "s3:GetObjectAcl" : "s3:GetObjectVersionAcl");
|
||||
S3Request.requireEmptyBody(exchange, hash);
|
||||
S3Xml.sendXml(exchange, 200, Acl.xml(
|
||||
store.bucket(bucketName).ownership() == ObjectStorage.ObjectOwnership.BUCKET_OWNER_ENFORCED
|
||||
? Map.of() : metadata.acl(), owner));
|
||||
} else {
|
||||
if (store.bucket(bucketName).ownership() == ObjectStorage.ObjectOwnership.BUCKET_OWNER_ENFORCED)
|
||||
throw new StoreException(400, "AccessControlListNotSupported", "ACLs are disabled for this bucket");
|
||||
if (!owner.equals(principal) &&
|
||||
(metadata.versionId() == null || metadata.versionId().equals("null")))
|
||||
throw new StoreException(403, "AccessDenied", "Access denied");
|
||||
access.requireObject(bucketName, key, metadata, principal, Acl.WRITE_ACP,
|
||||
versionId == null ? "s3:PutObjectAcl" : "s3:PutObjectVersionAcl");
|
||||
Map<String, String> acl;
|
||||
if (exchange.getRequestHeaders().containsKey("x-amz-acl") ||
|
||||
exchange.getRequestHeaders().keySet().stream().anyMatch(
|
||||
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());
|
||||
}
|
||||
BucketSecurity.checkAcl(store.bucket(bucketName), exchange.getRequestHeaders(), acl, true);
|
||||
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 copy = exchange.getRequestHeaders().containsKey("x-amz-copy-source");
|
||||
boolean versionRequest = (method.equals("GET") || method.equals("HEAD") || method.equals("DELETE")) &&
|
||||
query.containsKey("versionId") && (query.size() == 1 || query.size() == 2 && query.containsKey("x-id"));
|
||||
if (versionRequest && query.containsKey("x-id") &&
|
||||
!(method.equals("GET") ? "GetObject" : method.equals("HEAD") ? "HeadObject" : "DeleteObject")
|
||||
.equals(query.get("x-id"))) S3Request.unsupported("Version query operation");
|
||||
boolean directUploadQuery = method.equals("PUT") && !copy &&
|
||||
(query.get("x-id") == null || query.get("x-id").equals("PutObject")) &&
|
||||
query.keySet().stream().allMatch(name -> name.equals("x-id") ||
|
||||
name.equals("x-amz-sdk-checksum-algorithm") ||
|
||||
name.startsWith("x-amz-checksum-") && name.equals(name.toLowerCase(Locale.ROOT)));
|
||||
if (!multipartRequest && !versionRequest && !query.isEmpty() && !directUploadQuery && !(query.size() == 1 &&
|
||||
("PutObject".equals(query.get("x-id")) || "CopyObject".equals(query.get("x-id")) ||
|
||||
"GetObject".equals(query.get("x-id")) ||
|
||||
"HeadObject".equals(query.get("x-id")) || "DeleteObject".equals(query.get("x-id")))))
|
||||
S3Request.unsupported("Query operation");
|
||||
S3Request.validateObjectHeaders(exchange.getRequestHeaders());
|
||||
if (multipartRequest) {
|
||||
if (method.equals("GET")) access.requireOwner(principal);
|
||||
else access.requireWrite(bucketName, key, principal,
|
||||
method.equals("DELETE") ? "s3:AbortMultipartUpload" : "s3:PutObject");
|
||||
multipartHandler.handleMultipart(exchange, method, query, key, verified, bucketName);
|
||||
return;
|
||||
}
|
||||
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.requireWrite(bucketName, key, principal, "s3:PutObject");
|
||||
if (copy) copyObject(exchange, key, bucketName, principal);
|
||||
else putObject(exchange, key, verified, bucketName, query);
|
||||
}
|
||||
case "GET", "HEAD" -> readObject(exchange, key, bucketName, query.get("versionId"), principal);
|
||||
case "DELETE" -> {
|
||||
access.requireWrite(bucketName, key, principal,
|
||||
query.get("versionId") == null ? "s3:DeleteObject" : "s3:DeleteObjectVersion");
|
||||
deleteObject(exchange, key, bucketName, query.get("versionId"));
|
||||
}
|
||||
default -> S3Request.unsupported("HTTP method");
|
||||
}
|
||||
}
|
||||
|
||||
private void putObject(HttpExchange exchange, String key, SigV4.Verified verified,
|
||||
String bucketName, Map<String, String> query) throws IOException {
|
||||
var headers = exchange.getRequestHeaders();
|
||||
String length = SigV4.single(headers, "content-length"), condition = SigV4.single(headers, "if-none-match");
|
||||
if (condition != null && !condition.equals("*")) S3Request.unsupported("Write condition");
|
||||
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 = S3Request.uploadChecksums(headers, query);
|
||||
AwsChunkedInputStream chunked = verified.streaming() ? S3Request.chunkedBody(exchange, verified) : null;
|
||||
if (chunked != null) bytes = S3Request.decodedLength(headers);
|
||||
else if (headers.containsKey("x-amz-decoded-content-length") || headers.containsKey("x-amz-trailer"))
|
||||
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());
|
||||
BucketSecurity.checkAcl(store.bucket(bucketName), headers, acl, false);
|
||||
if (!acl.isEmpty() && !owner.equals(verified.principal()))
|
||||
access.requireBucket(bucketName, verified.principal(), Acl.WRITE_ACP);
|
||||
ObjectStorage.Metadata data = store.put(bucketName, key,
|
||||
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");
|
||||
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();
|
||||
access.requireObject(sourceBucket, sourceKey, sourceMetadata, principal, Acl.READ,
|
||||
sourceVersion == null ? "s3:GetObject" : "s3:GetObjectVersion");
|
||||
if (sourceMetadata.versionId() != null)
|
||||
exchange.getResponseHeaders().set("x-amz-copy-source-version-id", sourceMetadata.versionId());
|
||||
String type = "REPLACE".equals(directive) ? S3Request.contentType(headers) : sourceMetadata.contentType();
|
||||
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());
|
||||
BucketSecurity.checkAcl(store.bucket(bucketName), headers, acl, false);
|
||||
if (!acl.isEmpty() && !owner.equals(principal))
|
||||
access.requireBucket(bucketName, principal, Acl.WRITE_ACP);
|
||||
var copied = store.put(bucketName, key, object.stream(), sourceMetadata.length(),
|
||||
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>"" +
|
||||
copied.etag() + ""</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();
|
||||
access.requireObject(bucketName, key, meta, principal, Acl.READ,
|
||||
versionId == null ? "s3:GetObject" : "s3:GetObjectVersion");
|
||||
String etag = "\"" + meta.etag() + "\"";
|
||||
String noneMatch = SigV4.single(headers, "if-none-match");
|
||||
if (noneMatch != null && (noneMatch.equals("*") ||
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,11 +3,60 @@ package cloud.lunarsky.store;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/** Storage operations shared by the local and cluster gateways. */
|
||||
interface ObjectStorage extends AutoCloseable {
|
||||
enum VersioningState { NEVER, ENABLED, SUSPENDED }
|
||||
enum ObjectOwnership { BUCKET_OWNER_ENFORCED, BUCKET_OWNER_PREFERRED, OBJECT_WRITER }
|
||||
record PublicAccessBlock(boolean blockPublicAcls, boolean ignorePublicAcls,
|
||||
boolean blockPublicPolicy, boolean restrictPublicBuckets) {
|
||||
static PublicAccessBlock secure() { return new PublicAccessBlock(true, true, true, true); }
|
||||
static PublicAccessBlock open() { return new PublicAccessBlock(false, false, false, false); }
|
||||
}
|
||||
record Limits(long maxObjectBytes, long maxTotalBytes) {}
|
||||
record Bucket(String name, long created, VersioningState versioning, Map<String, String> acl,
|
||||
ObjectOwnership ownership, PublicAccessBlock publicAccessBlock, String policy) {
|
||||
Bucket(String name, long created) {
|
||||
this(name, created, VersioningState.NEVER, Map.of(),
|
||||
ObjectOwnership.BUCKET_OWNER_ENFORCED, PublicAccessBlock.secure(), null);
|
||||
}
|
||||
Bucket(String name, long created, VersioningState versioning, Map<String, String> acl) {
|
||||
this(name, created, versioning, acl,
|
||||
ObjectOwnership.OBJECT_WRITER, PublicAccessBlock.open(), null);
|
||||
}
|
||||
Bucket(String name, long created, VersioningState versioning) {
|
||||
this(name, created, versioning, Map.of());
|
||||
}
|
||||
}
|
||||
record Metadata(long length, long modified, String etag, byte[] sha256,
|
||||
String bucket, String key, String contentType) {}
|
||||
String bucket, String key, String contentType,
|
||||
Map<String, String> userMetadata, Map<String, String> tags,
|
||||
String versionId, Map<String, String> checksums, Map<String, String> acl) {
|
||||
Metadata(long length, long modified, String etag, byte[] sha256,
|
||||
String bucket, String key, String contentType,
|
||||
Map<String, String> userMetadata, Map<String, String> tags,
|
||||
String versionId, Map<String, String> checksums) {
|
||||
this(length, modified, etag, sha256, bucket, key, contentType,
|
||||
userMetadata, tags, versionId, checksums, Map.of());
|
||||
}
|
||||
Metadata(long length, long modified, String etag, byte[] sha256,
|
||||
String bucket, String key, String contentType,
|
||||
Map<String, String> userMetadata, Map<String, String> tags,
|
||||
String versionId) {
|
||||
this(length, modified, etag, sha256, bucket, key, contentType,
|
||||
userMetadata, tags, versionId, Map.of());
|
||||
}
|
||||
Metadata(long length, long modified, String etag, byte[] sha256,
|
||||
String bucket, String key, String contentType,
|
||||
Map<String, String> userMetadata, Map<String, String> tags) {
|
||||
this(length, modified, etag, sha256, bucket, key, contentType, userMetadata, tags, null);
|
||||
}
|
||||
Metadata(long length, long modified, String etag, byte[] sha256,
|
||||
String bucket, String key, String contentType) {
|
||||
this(length, modified, etag, sha256, bucket, key, contentType, Map.of(), Map.of(), null);
|
||||
}
|
||||
}
|
||||
record OpenObject(Metadata metadata, InputStream stream) implements AutoCloseable {
|
||||
public void close() throws IOException { stream.close(); }
|
||||
}
|
||||
@@ -15,12 +64,75 @@ interface ObjectStorage extends AutoCloseable {
|
||||
record ListPage(List<ListedObject> objects, List<String> prefixes, String nextKey, boolean truncated) {
|
||||
int keyCount() { return objects.size() + prefixes.size(); }
|
||||
}
|
||||
record VersionEntry(String key, String versionId, long modified, boolean deleteMarker,
|
||||
boolean latest, Metadata metadata) {}
|
||||
record VersionPage(List<VersionEntry> entries, String nextKey, String nextVersionId,
|
||||
boolean truncated) {}
|
||||
record DeleteResult(String versionId, boolean deleteMarker) {}
|
||||
|
||||
Metadata put(String bucket, String key, InputStream input, long length, String expectedHash,
|
||||
String checksum, boolean createOnly, String contentType) throws IOException;
|
||||
String checksum, boolean createOnly, String contentType,
|
||||
Map<String, String> userMetadata, Map<String, String> tags,
|
||||
java.util.function.Supplier<Map<String, String>> checksums,
|
||||
Map<String, String> acl) throws IOException;
|
||||
default Metadata put(String bucket, String key, InputStream input, long length, String expectedHash,
|
||||
String checksum, boolean createOnly, String contentType,
|
||||
Map<String, String> userMetadata, Map<String, String> tags,
|
||||
java.util.function.Supplier<Map<String, String>> checksums) throws IOException {
|
||||
return put(bucket, key, input, length, expectedHash, checksum, createOnly, contentType,
|
||||
userMetadata, tags, checksums, Map.of());
|
||||
}
|
||||
default Metadata put(String bucket, String key, InputStream input, long length, String expectedHash,
|
||||
String checksum, boolean createOnly, String contentType,
|
||||
Map<String, String> userMetadata, Map<String, String> tags) throws IOException {
|
||||
return put(bucket, key, input, length, expectedHash, checksum, createOnly, contentType,
|
||||
userMetadata, tags, Map::of);
|
||||
}
|
||||
default Metadata put(String bucket, String key, InputStream input, long length, String expectedHash,
|
||||
String checksum, boolean createOnly, String contentType) throws IOException {
|
||||
return put(bucket, key, input, length, expectedHash, checksum, createOnly, contentType, Map.of(), Map.of());
|
||||
}
|
||||
OpenObject open(String bucket, String key) throws IOException;
|
||||
default OpenObject open(String bucket, String key, String versionId) throws IOException {
|
||||
if (versionId == null) return open(bucket, key);
|
||||
throw new StoreException(501, "NotImplemented", "Object versioning is unavailable");
|
||||
}
|
||||
Map<String, String> tags(String bucket, String key) throws IOException;
|
||||
default Map<String, String> tags(String bucket, String key, String versionId) throws IOException {
|
||||
if (versionId == null) return tags(bucket, key);
|
||||
throw new StoreException(501, "NotImplemented", "Versioned tagging is unavailable");
|
||||
}
|
||||
void setTags(String bucket, String key, Map<String, String> tags) throws IOException;
|
||||
default void setTags(String bucket, String key, String versionId,
|
||||
Map<String, String> tags) throws IOException {
|
||||
if (versionId == null) setTags(bucket, key, tags);
|
||||
else throw new StoreException(501, "NotImplemented", "Versioned tagging is unavailable");
|
||||
}
|
||||
void delete(String bucket, String key) throws IOException;
|
||||
default DeleteResult delete(String bucket, String key, String versionId) throws IOException {
|
||||
if (versionId != null) throw new StoreException(501, "NotImplemented", "Object versioning is unavailable");
|
||||
delete(bucket, key);
|
||||
return new DeleteResult(null, false);
|
||||
}
|
||||
default void setVersioning(String bucket, VersioningState state) throws IOException {
|
||||
throw new StoreException(501, "NotImplemented", "Object versioning is unavailable");
|
||||
}
|
||||
default VersionPage listVersions(String bucket, String prefix, String keyMarker,
|
||||
String versionMarker, int maxKeys) throws IOException {
|
||||
throw new StoreException(501, "NotImplemented", "Object versioning is unavailable");
|
||||
}
|
||||
ListPage list(String bucket, String prefix, String delimiter, int maxKeys, String after) throws IOException;
|
||||
void ensureBucket(String bucket) throws IOException;
|
||||
Bucket bucket(String bucket) throws IOException;
|
||||
List<Bucket> buckets() throws IOException;
|
||||
void createBucket(String bucket) throws IOException;
|
||||
void deleteBucket(String bucket) throws IOException;
|
||||
void setBucketAcl(String bucket, Map<String, String> acl) throws IOException;
|
||||
void setBucketOwnership(String bucket, ObjectOwnership ownership) throws IOException;
|
||||
void setPublicAccessBlock(String bucket, PublicAccessBlock block) throws IOException;
|
||||
void setBucketPolicy(String bucket, String policy) throws IOException;
|
||||
void setObjectAcl(String bucket, String key, String versionId, Map<String, String> acl) throws IOException;
|
||||
Limits limits();
|
||||
default boolean ready() { return true; }
|
||||
void close() throws IOException;
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
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 sessions = SessionCredentials.fromEnvironment(env, identities.keySet());
|
||||
var allIdentities = new java.util.HashSet<>(identities.keySet());
|
||||
allIdentities.addAll(sessions.keySet());
|
||||
var app = new Main(store, multipart, new SigV4(identities, sessions,
|
||||
access, region, Clock.systemUTC()), bucket, ClientLimits.fromEnvironment(env),
|
||||
positiveInt(env, "MAX_IN_FLIGHT_REQUESTS", 16, 1024),
|
||||
env.getOrDefault("S3_VIRTUAL_HOST_SUFFIX", ""), BrowserCors.fromEnvironment(env),
|
||||
KeyScopes.fromEnvironment(env, access, allIdentities),
|
||||
new RequestMetrics(env.get("METRICS_BEARER_TOKEN")),
|
||||
IdentityPolicies.fromEnvironment(env, access, allIdentities),
|
||||
publicEndpoint(env));
|
||||
int port = Integer.parseInt(env.getOrDefault("PORT", "9000"));
|
||||
var server = HttpServer.create(mode.equals("cluster")
|
||||
? new InetSocketAddress(env.getOrDefault("BIND_ADDRESS", "127.0.0.1"), port)
|
||||
: 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;
|
||||
}
|
||||
|
||||
static URI publicEndpoint(Map<String, String> env) {
|
||||
String configured = env.get("S3_PUBLIC_ENDPOINT");
|
||||
if (configured == null || configured.isBlank()) return null;
|
||||
URI uri;
|
||||
try { uri = URI.create(configured); }
|
||||
catch (IllegalArgumentException error) {
|
||||
throw new IllegalArgumentException("Invalid S3_PUBLIC_ENDPOINT", error);
|
||||
}
|
||||
if (!"http".equals(uri.getScheme()) && !"https".equals(uri.getScheme()) ||
|
||||
uri.getHost() == null || uri.getUserInfo() != null || uri.getRawQuery() != null ||
|
||||
uri.getRawFragment() != null ||
|
||||
!(uri.getRawPath().isEmpty() || uri.getRawPath().equals("/")))
|
||||
throw new IllegalArgumentException("S3_PUBLIC_ENDPOINT must be an HTTP(S) origin");
|
||||
return URI.create(configured.endsWith("/") ? configured.substring(0, configured.length() - 1) : configured);
|
||||
}
|
||||
private static void printStartup(DiskStore store, MultipartStorage multipart,
|
||||
String bucket, String region, int port) {
|
||||
System.out.println(" *");
|
||||
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";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
final class S3Access {
|
||||
private final ObjectStorage store;
|
||||
private final String owner;
|
||||
private final java.util.Map<String, BucketPolicy> identityPolicies;
|
||||
private final ConcurrentHashMap<String, CachedPolicy> policies = new ConcurrentHashMap<>();
|
||||
private record CachedPolicy(String source, BucketPolicy parsed) { }
|
||||
|
||||
S3Access(ObjectStorage store, String owner) {
|
||||
this(store, owner, java.util.Map.of());
|
||||
}
|
||||
|
||||
S3Access(ObjectStorage store, String owner, java.util.Map<String, BucketPolicy> identityPolicies) {
|
||||
this.store = store;
|
||||
this.owner = owner;
|
||||
this.identityPolicies = java.util.Map.copyOf(identityPolicies);
|
||||
}
|
||||
|
||||
String owner() {
|
||||
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 {
|
||||
var current = store.bucket(bucket);
|
||||
String action = permission == Acl.READ ? "s3:ListBucket" :
|
||||
permission == Acl.READ_ACP ? "s3:GetBucketAcl" :
|
||||
permission == Acl.WRITE_ACP ? "s3:PutBucketAcl" : "s3:PutObject";
|
||||
require(current, current.acl(), principal, permission, action, null);
|
||||
}
|
||||
|
||||
void requireWrite(String bucket, String key, String principal, String action) throws IOException {
|
||||
var current = store.bucket(bucket);
|
||||
require(current, current.acl(), principal, Acl.WRITE, action, key);
|
||||
}
|
||||
|
||||
void requireObject(String bucket, String key, ObjectStorage.Metadata metadata,
|
||||
String principal, int permission, String action) throws IOException {
|
||||
require(store.bucket(bucket), metadata.acl(), principal, permission, action, key);
|
||||
}
|
||||
|
||||
private void require(ObjectStorage.Bucket bucket, java.util.Map<String, String> acl,
|
||||
String principal, int permission, String action, String key) {
|
||||
String resource = "arn:aws:s3:::" + bucket.name() + (key == null ? "" : "/" + key);
|
||||
BucketPolicy policy = policy(bucket);
|
||||
int decision = policy.decide(principal, action, resource);
|
||||
int identityDecision = principal == null ? 0 :
|
||||
identityPolicies.getOrDefault(principal, BucketPolicy.empty()).decide(principal, action, resource);
|
||||
if (decision < 0 || identityDecision < 0 ||
|
||||
!BucketSecurity.allowsAcl(bucket, acl, principal, owner, permission) &&
|
||||
identityDecision <= 0 &&
|
||||
!(decision > 0 && (principal != null || !bucket.publicAccessBlock().restrictPublicBuckets() ||
|
||||
!policy.publicAllow())))
|
||||
throw new StoreException(403, "AccessDenied", "Access denied");
|
||||
}
|
||||
|
||||
private BucketPolicy policy(ObjectStorage.Bucket bucket) {
|
||||
String source = bucket.policy();
|
||||
if (source == null) return BucketPolicy.empty();
|
||||
CachedPolicy cached = policies.get(bucket.name());
|
||||
if (cached != null && cached.source().equals(source)) return cached.parsed();
|
||||
BucketPolicy parsed = BucketPolicy.parse(source, bucket.name());
|
||||
policies.put(bucket.name(), new CachedPolicy(source, parsed));
|
||||
return parsed;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import com.sun.net.httpserver.HttpExchange;
|
||||
import com.sun.net.httpserver.Headers;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
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-security-token",
|
||||
"x-amz-sdk-checksum-algorithm", "x-amz-user-agent", "x-amz-copy-source",
|
||||
"x-amz-metadata-directive", "x-amz-tagging", "x-amz-tagging-directive",
|
||||
"x-amz-decoded-content-length", "x-amz-trailer", "x-amz-checksum-mode",
|
||||
"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 UploadChecksums uploadChecksums(Headers headers, Map<String, String> query) {
|
||||
if (query.keySet().stream().noneMatch(name -> name.startsWith("x-amz-checksum-") ||
|
||||
name.equals("x-amz-sdk-checksum-algorithm"))) return UploadChecksums.from(headers);
|
||||
Headers combined = new Headers();
|
||||
headers.forEach((name, values) -> combined.put(name, java.util.List.copyOf(values)));
|
||||
query.forEach((name, value) -> {
|
||||
if (!name.startsWith("x-amz-checksum-") && !name.equals("x-amz-sdk-checksum-algorithm")) return;
|
||||
if (combined.containsKey(name))
|
||||
throw new StoreException(400, "InvalidRequest", "Duplicate checksum in query and header");
|
||||
combined.set(name, value);
|
||||
});
|
||||
return UploadChecksums.from(combined);
|
||||
}
|
||||
static String contentType(com.sun.net.httpserver.Headers headers) {
|
||||
String value = SigV4.single(headers, "content-type");
|
||||
if (value == null) return "application/octet-stream";
|
||||
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"); }
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
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, checksumCrc32 = null;
|
||||
var fields = element.getChildNodes();
|
||||
for (int j = 0; j < fields.getLength(); j++) {
|
||||
if (!(fields.item(j) instanceof org.w3c.dom.Element field)) continue;
|
||||
if (field.getTagName().equals("PartNumber") && number == null)
|
||||
number = field.getTextContent().trim();
|
||||
else if (field.getTagName().equals("ETag") && etag == null)
|
||||
etag = field.getTextContent().trim();
|
||||
else if (field.getTagName().equals("ChecksumCRC32") && checksumCrc32 == null)
|
||||
checksumCrc32 = field.getTextContent().trim();
|
||||
else throw new IllegalArgumentException();
|
||||
}
|
||||
if (number == null || etag == null || !etag.matches("\"?[0-9a-f]{32}\"?"))
|
||||
throw new IllegalArgumentException();
|
||||
if (checksumCrc32 != null && java.util.Base64.getDecoder().decode(checksumCrc32).length != 4)
|
||||
throw new IllegalArgumentException();
|
||||
parts.add(new MultipartStorage.Part(Integer.parseInt(number), etag, checksumCrc32));
|
||||
if (parts.size() > 10000) throw new IllegalArgumentException();
|
||||
}
|
||||
return parts;
|
||||
} 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>"")
|
||||
.append(meta.etag()).append(""</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("&", "&").replace("<", "<").replace(">", ">").replace("\"", """);
|
||||
}
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -21,7 +21,7 @@ final class SchemaMigrator {
|
||||
result.next();
|
||||
version = result.getInt(1);
|
||||
}
|
||||
if (version > 2) throw new IOException("Metadata schema is newer than this ObjectStore build");
|
||||
if (version > 11) throw new IOException("Metadata schema is newer than this ObjectStore build");
|
||||
if (version < 1) {
|
||||
statement.execute("CREATE TABLE IF NOT EXISTS cluster_usage (bucket text PRIMARY KEY, used_bytes bigint NOT NULL CHECK (used_bytes >= 0))");
|
||||
statement.execute("CREATE TABLE IF NOT EXISTS cluster_objects (bucket text NOT NULL, object_key text COLLATE \"C\" NOT NULL, generation uuid NOT NULL, length bigint NOT NULL, modified bigint NOT NULL, etag text NOT NULL, sha256 bytea NOT NULL, content_type text NOT NULL, PRIMARY KEY (bucket, object_key))");
|
||||
@@ -37,12 +37,92 @@ final class SchemaMigrator {
|
||||
statement.execute("CREATE TABLE IF NOT EXISTS cluster_format (singleton integer PRIMARY KEY CHECK (singleton=1), version integer NOT NULL)");
|
||||
statement.execute("INSERT INTO cluster_schema_migrations VALUES (2)");
|
||||
}
|
||||
if (version < 3) {
|
||||
statement.execute("CREATE TABLE cluster_uploads (upload_id uuid PRIMARY KEY, bucket text NOT NULL, object_key text COLLATE \"C\" NOT NULL, content_type text NOT NULL, created_at bigint NOT NULL)");
|
||||
statement.execute("CREATE TABLE cluster_upload_parts (upload_id uuid NOT NULL REFERENCES cluster_uploads(upload_id) ON DELETE CASCADE, part_number integer NOT NULL CHECK (part_number BETWEEN 1 AND 10000), length bigint NOT NULL CHECK (length >= 0), etag text NOT NULL, modified bigint NOT NULL, PRIMARY KEY (upload_id, part_number))");
|
||||
statement.execute("CREATE TABLE cluster_upload_segments (upload_id uuid NOT NULL, part_number integer NOT NULL, ordinal integer NOT NULL, segment_id uuid NOT NULL, length integer NOT NULL, sha256 bytea NOT NULL, replica_ids uuid[] NOT NULL, placement_version bigint NOT NULL DEFAULT 0, PRIMARY KEY (upload_id, part_number, ordinal), FOREIGN KEY (upload_id, part_number) REFERENCES cluster_upload_parts(upload_id, part_number) ON DELETE CASCADE)");
|
||||
statement.execute("INSERT INTO cluster_schema_migrations VALUES (3)");
|
||||
}
|
||||
if (version < 4) {
|
||||
statement.execute("CREATE TABLE cluster_gc_candidates (node_id uuid NOT NULL, segment_id uuid NOT NULL, observed_mtime bigint NOT NULL, first_seen bigint NOT NULL, PRIMARY KEY (node_id, segment_id))");
|
||||
statement.execute("INSERT INTO cluster_schema_migrations VALUES (4)");
|
||||
}
|
||||
if (version < 5) {
|
||||
statement.execute("ALTER TABLE cluster_objects ADD COLUMN user_metadata bytea");
|
||||
statement.execute("ALTER TABLE cluster_objects ADD COLUMN tags bytea");
|
||||
statement.execute("ALTER TABLE cluster_uploads ADD COLUMN user_metadata bytea");
|
||||
statement.execute("ALTER TABLE cluster_uploads ADD COLUMN tags bytea");
|
||||
statement.execute("INSERT INTO cluster_schema_migrations VALUES (5)");
|
||||
}
|
||||
if (version < 6) {
|
||||
statement.execute("CREATE TABLE cluster_buckets (name text PRIMARY KEY, created_at bigint NOT NULL)");
|
||||
statement.execute("INSERT INTO cluster_buckets SELECT DISTINCT bucket, " +
|
||||
"CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS bigint) FROM cluster_usage");
|
||||
statement.execute("INSERT INTO cluster_schema_migrations VALUES (6)");
|
||||
}
|
||||
if (version < 7) {
|
||||
statement.execute("ALTER TABLE cluster_buckets ADD COLUMN versioning_state text NOT NULL " +
|
||||
"DEFAULT 'NEVER' CHECK (versioning_state IN ('NEVER', 'ENABLED', 'SUSPENDED'))");
|
||||
statement.execute("INSERT INTO cluster_schema_migrations VALUES (7)");
|
||||
}
|
||||
if (version < 8) {
|
||||
statement.execute("CREATE TABLE cluster_object_versions (sequence bigint GENERATED ALWAYS AS IDENTITY, " +
|
||||
"bucket text NOT NULL, object_key text COLLATE \"C\" NOT NULL, version_id text NOT NULL, " +
|
||||
"delete_marker boolean NOT NULL, generation uuid, length bigint, modified bigint NOT NULL, " +
|
||||
"etag text, sha256 bytea, content_type text, user_metadata bytea, tags bytea, " +
|
||||
"PRIMARY KEY (bucket, object_key, version_id), " +
|
||||
"CHECK (delete_marker = (generation IS NULL)))");
|
||||
statement.execute("CREATE INDEX cluster_versions_order ON cluster_object_versions " +
|
||||
"(bucket, object_key, sequence DESC)");
|
||||
statement.execute("CREATE TABLE cluster_object_heads (bucket text NOT NULL, " +
|
||||
"object_key text COLLATE \"C\" NOT NULL, version_id text NOT NULL, " +
|
||||
"PRIMARY KEY (bucket, object_key), " +
|
||||
"FOREIGN KEY (bucket, object_key, version_id) REFERENCES cluster_object_versions " +
|
||||
"(bucket, object_key, version_id) DEFERRABLE INITIALLY DEFERRED)");
|
||||
statement.execute("INSERT INTO cluster_object_versions " +
|
||||
"(bucket, object_key, version_id, delete_marker, generation, length, modified, etag, " +
|
||||
"sha256, content_type, user_metadata, tags) " +
|
||||
"SELECT bucket, object_key, 'null', false, generation, length, modified, etag, sha256, " +
|
||||
"content_type, user_metadata, tags FROM cluster_objects");
|
||||
statement.execute("INSERT INTO cluster_object_heads " +
|
||||
"SELECT bucket, object_key, 'null' FROM cluster_objects");
|
||||
statement.execute("INSERT INTO cluster_schema_migrations VALUES (8)");
|
||||
}
|
||||
if (version < 9) {
|
||||
statement.execute("ALTER TABLE cluster_object_versions ADD COLUMN checksum_metadata bytea");
|
||||
statement.execute("INSERT INTO cluster_schema_migrations VALUES (9)");
|
||||
}
|
||||
if (version < 10) {
|
||||
statement.execute("ALTER TABLE cluster_buckets ADD COLUMN acl bytea");
|
||||
statement.execute("ALTER TABLE cluster_object_versions ADD COLUMN acl bytea");
|
||||
statement.execute("ALTER TABLE cluster_uploads ADD COLUMN acl bytea");
|
||||
statement.execute("INSERT INTO cluster_schema_migrations VALUES (10)");
|
||||
}
|
||||
if (version < 11) {
|
||||
statement.execute("ALTER TABLE cluster_buckets ADD COLUMN object_ownership text NOT NULL " +
|
||||
"DEFAULT 'OBJECT_WRITER' CHECK (object_ownership IN " +
|
||||
"('BUCKET_OWNER_ENFORCED', 'BUCKET_OWNER_PREFERRED', 'OBJECT_WRITER'))");
|
||||
statement.execute("ALTER TABLE cluster_buckets ADD COLUMN block_public_acls boolean NOT NULL DEFAULT false");
|
||||
statement.execute("ALTER TABLE cluster_buckets ADD COLUMN ignore_public_acls boolean NOT NULL DEFAULT false");
|
||||
statement.execute("ALTER TABLE cluster_buckets ADD COLUMN block_public_policy boolean NOT NULL DEFAULT false");
|
||||
statement.execute("ALTER TABLE cluster_buckets ADD COLUMN restrict_public_buckets boolean NOT NULL DEFAULT false");
|
||||
statement.execute("ALTER TABLE cluster_buckets ADD COLUMN bucket_policy text");
|
||||
statement.execute("INSERT INTO cluster_schema_migrations VALUES (11)");
|
||||
}
|
||||
statement.execute("INSERT INTO cluster_format SELECT 1, CASE WHEN EXISTS (SELECT 1 FROM cluster_segments WHERE replica_ids IS NULL) THEN 1 ELSE 2 END WHERE NOT EXISTS (SELECT 1 FROM cluster_format)");
|
||||
}
|
||||
try (PreparedStatement insert = connection.prepareStatement("INSERT INTO cluster_usage VALUES (?, 0) ON CONFLICT DO NOTHING")) {
|
||||
insert.setString(1, bucket);
|
||||
insert.executeUpdate();
|
||||
}
|
||||
try (PreparedStatement insert = connection.prepareStatement(
|
||||
"INSERT INTO cluster_buckets (name, created_at, object_ownership, block_public_acls, " +
|
||||
"ignore_public_acls, block_public_policy, restrict_public_buckets) " +
|
||||
"VALUES (?, ?, 'BUCKET_OWNER_ENFORCED', true, true, true, true) ON CONFLICT DO NOTHING")) {
|
||||
insert.setString(1, bucket);
|
||||
insert.setLong(2, System.currentTimeMillis());
|
||||
insert.executeUpdate();
|
||||
}
|
||||
int format;
|
||||
try (Statement statement = connection.createStatement();
|
||||
ResultSet result = statement.executeQuery("SELECT version FROM cluster_format WHERE singleton=1")) {
|
||||
@@ -60,7 +140,8 @@ final class SchemaMigrator {
|
||||
connection.commit();
|
||||
return format;
|
||||
} catch (SQLException | IOException error) {
|
||||
try { connection.rollback(); } catch (SQLException rollback) { error.addSuppressed(rollback); }
|
||||
try { connection.rollback(); }
|
||||
catch (SQLException rollback) { error.addSuppressed(rollback); }
|
||||
if (error instanceof IOException io) throw io;
|
||||
throw new IOException("Metadata schema migration failed", error);
|
||||
} finally {
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Instant;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
final class SessionCredentials {
|
||||
record Session(String secret, String token, Instant expires) { }
|
||||
|
||||
private SessionCredentials() { }
|
||||
|
||||
static Map<String, Session> fromEnvironment(Map<String, String> env, java.util.Set<String> permanent)
|
||||
throws IOException {
|
||||
String file = env.get("S3_SESSION_CREDENTIALS_FILE");
|
||||
if (file == null || file.isBlank()) return Map.of();
|
||||
var lines = Files.readAllLines(Path.of(file), StandardCharsets.UTF_8);
|
||||
if (lines.size() > 256) throw new IllegalArgumentException("Too many session credentials");
|
||||
Map<String, Session> sessions = new HashMap<>();
|
||||
for (String line : lines) {
|
||||
if (line.isBlank() || line.startsWith("#")) continue;
|
||||
String[] fields = line.split("\\t", -1);
|
||||
if (fields.length != 4 || !fields[0].matches("[A-Za-z0-9]{16,128}") ||
|
||||
permanent.contains(fields[0]) || fields[1].length() < 32 ||
|
||||
fields[2].length() < 32 || fields[2].length() > 2048 ||
|
||||
fields[2].indexOf('\n') >= 0 || fields[2].indexOf('\r') >= 0)
|
||||
throw new IllegalArgumentException("Invalid session credential entry");
|
||||
Instant expires;
|
||||
try { expires = Instant.ofEpochSecond(Long.parseLong(fields[3])); }
|
||||
catch (RuntimeException error) { throw new IllegalArgumentException("Invalid session expiry", error); }
|
||||
if (sessions.putIfAbsent(fields[0], new Session(fields[1], fields[2], expires)) != null)
|
||||
throw new IllegalArgumentException("Duplicate session credential");
|
||||
}
|
||||
return Map.copyOf(sessions);
|
||||
}
|
||||
}
|
||||
@@ -12,48 +12,226 @@ import java.time.format.DateTimeFormatter;
|
||||
import java.util.Arrays;
|
||||
import java.util.HexFormat;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.TreeMap;
|
||||
import java.util.regex.Pattern;
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
|
||||
final class SigV4 {
|
||||
record Verified(String payload, String applicationQuery, byte[] signingKey,
|
||||
String date, String scope, String signature, String principal) {
|
||||
Verified(String payload, String applicationQuery, byte[] signingKey,
|
||||
String date, String scope, String signature) {
|
||||
this(payload, applicationQuery, signingKey, date, scope, signature, null);
|
||||
}
|
||||
boolean streaming() { return payload.startsWith("STREAMING-AWS4-HMAC-SHA256-PAYLOAD"); }
|
||||
}
|
||||
private static final DateTimeFormatter DATE = DateTimeFormatter.ofPattern("uuuuMMdd'T'HHmmss'Z'").withZone(ZoneOffset.UTC);
|
||||
private static final Pattern HEX = Pattern.compile("[0-9a-f]{64}");
|
||||
private final String accessKey, secretKey, region;
|
||||
private final Map<String, String> identities;
|
||||
private final Map<String, SessionCredentials.Session> sessions;
|
||||
private final String root;
|
||||
private final String region;
|
||||
private final Clock clock;
|
||||
|
||||
SigV4(String accessKey, String secretKey, String region, Clock clock) {
|
||||
this.accessKey = accessKey; this.secretKey = secretKey; this.region = region; this.clock = clock;
|
||||
this(Map.of(accessKey, secretKey), accessKey, region, clock);
|
||||
}
|
||||
|
||||
SigV4(Map<String, String> identities, String root, String region, Clock clock) {
|
||||
this(identities, Map.of(), root, region, clock);
|
||||
}
|
||||
|
||||
SigV4(Map<String, String> identities, Map<String, SessionCredentials.Session> sessions,
|
||||
String root, String region, Clock clock) {
|
||||
this.identities = Map.copyOf(identities);
|
||||
this.sessions = Map.copyOf(sessions);
|
||||
if (!this.identities.containsKey(root)) throw new IllegalArgumentException("Missing root identity");
|
||||
if (this.sessions.keySet().stream().anyMatch(this.identities::containsKey))
|
||||
throw new IllegalArgumentException("Session and permanent keys overlap");
|
||||
this.root = root;
|
||||
this.region = region;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
String root() { return root; }
|
||||
Set<String> identities() {
|
||||
var all = new java.util.HashSet<>(identities.keySet());
|
||||
all.addAll(sessions.keySet());
|
||||
return Set.copyOf(all);
|
||||
}
|
||||
|
||||
String verify(String method, URI uri, Headers headers) {
|
||||
return verifyRequest(method, uri, headers).payload();
|
||||
}
|
||||
|
||||
Verified verifyRequest(String method, URI uri, Headers headers) {
|
||||
if (hasPresignedQuery(uri.getRawQuery())) return verifyPresigned(method, uri, headers);
|
||||
Map<String, String> fields = authorizationFields(headers);
|
||||
String[] credential = credentialScope(fields.get("Credential"));
|
||||
validateSession(credential[0], single(headers, "x-amz-security-token"));
|
||||
String date = signingDate(headers, credential[1]);
|
||||
String payload = payloadHash(headers);
|
||||
String signedHeaders = fields.get("SignedHeaders");
|
||||
String canonicalHeaders = canonicalHeaders(headers, signedHeaders,
|
||||
Set.of("host", "x-amz-date", "x-amz-content-sha256"));
|
||||
String canonical = method + "\n" + encode(decode(uri.getRawPath()), true) + "\n"
|
||||
+ canonicalQuery(uri.getRawQuery()) + "\n" + canonicalHeaders + "\n" + signedHeaders + "\n" + payload;
|
||||
String scope = String.join("/", Arrays.copyOfRange(credential, 1, 5));
|
||||
String toSign = "AWS4-HMAC-SHA256\n" + date + "\n" + scope + "\n" + hex(hash(canonical.getBytes(StandardCharsets.UTF_8)));
|
||||
byte[] signingKey = signingKey(secret(credential[0]), credential[1], region);
|
||||
String signature = fields.get("Signature");
|
||||
if (!HEX.matcher(signature).matches() || !MessageDigest.isEqual(hmac(signingKey, toSign), HexFormat.of().parseHex(signature))) denied("Signature mismatch");
|
||||
return new Verified(payload, uri.getRawQuery(), signingKey, date, scope, signature, credential[0]);
|
||||
}
|
||||
|
||||
private Verified verifyPresigned(String method, URI uri, Headers headers) {
|
||||
if (headers.containsKey("authorization")) denied("Use one authentication method");
|
||||
PresignedQuery query = presignedQuery(uri.getRawQuery());
|
||||
Map<String, String> fields = query.fields();
|
||||
Set<String> expected = Set.of("X-Amz-Algorithm", "X-Amz-Credential", "X-Amz-Date",
|
||||
"X-Amz-Expires", "X-Amz-SignedHeaders", "X-Amz-Signature");
|
||||
Set<String> allowed = new java.util.HashSet<>(expected);
|
||||
allowed.add("X-Amz-Security-Token");
|
||||
allowed.add("X-Amz-Content-Sha256");
|
||||
if (!fields.keySet().containsAll(expected) || !allowed.containsAll(fields.keySet()) ||
|
||||
fields.containsKey("X-Amz-Content-Sha256") &&
|
||||
!"UNSIGNED-PAYLOAD".equals(fields.get("X-Amz-Content-Sha256")) ||
|
||||
!"AWS4-HMAC-SHA256".equals(fields.get("X-Amz-Algorithm")))
|
||||
denied("Invalid presigned parameters");
|
||||
String[] credential = credentialScope(fields.get("X-Amz-Credential"));
|
||||
if (headers.containsKey("x-amz-security-token")) denied("Presigned session token must be in the query");
|
||||
validateSession(credential[0], fields.get("X-Amz-Security-Token"));
|
||||
String date = fields.get("X-Amz-Date");
|
||||
validatePresignedTime(date, credential[1], fields.get("X-Amz-Expires"));
|
||||
String signedHeaders = fields.get("X-Amz-SignedHeaders");
|
||||
String canonicalHeaders = canonicalHeaders(headers, signedHeaders, Set.of("host"));
|
||||
String scope = String.join("/", Arrays.copyOfRange(credential, 1, 5));
|
||||
String canonical = method + "\n" + encode(decode(uri.getRawPath()), true) + "\n"
|
||||
+ canonicalQuery(query.signed()) + "\n" + canonicalHeaders + "\n"
|
||||
+ signedHeaders + "\nUNSIGNED-PAYLOAD";
|
||||
String toSign = "AWS4-HMAC-SHA256\n" + date + "\n" + scope + "\n"
|
||||
+ hex(hash(canonical.getBytes(StandardCharsets.UTF_8)));
|
||||
String signature = fields.get("X-Amz-Signature");
|
||||
byte[] key = signingKey(secret(credential[0]), credential[1], region);
|
||||
if (!HEX.matcher(signature).matches() ||
|
||||
!MessageDigest.isEqual(hmac(key, toSign), HexFormat.of().parseHex(signature)))
|
||||
denied("Signature mismatch");
|
||||
return new Verified("UNSIGNED-PAYLOAD", query.application(), key, date, scope, signature, credential[0]);
|
||||
}
|
||||
|
||||
private static PresignedQuery presignedQuery(String rawQuery) {
|
||||
Map<String, String> fields = new TreeMap<>();
|
||||
StringBuilder application = new StringBuilder();
|
||||
StringBuilder signed = new StringBuilder();
|
||||
for (String part : rawQuery.split("&", -1)) {
|
||||
String[] pair = part.split("=", 2);
|
||||
String name = decode(pair[0]);
|
||||
String value = decode(pair.length == 2 ? pair[1] : "");
|
||||
if (name.startsWith("X-Amz-")) {
|
||||
if (fields.put(name, value) != null) denied("Duplicate presigned parameter");
|
||||
if (!name.equals("X-Amz-Signature")) appendQuery(signed, part);
|
||||
} else {
|
||||
appendQuery(application, part);
|
||||
appendQuery(signed, part);
|
||||
}
|
||||
}
|
||||
return new PresignedQuery(fields, application.toString(), signed.toString());
|
||||
}
|
||||
|
||||
private void validatePresignedTime(String date, String scopeDate, String rawExpires) {
|
||||
if (!date.matches("[0-9]{8}T[0-9]{6}Z") || !date.startsWith(scopeDate))
|
||||
denied("Invalid signing date");
|
||||
long expires;
|
||||
try {
|
||||
expires = Long.parseLong(rawExpires);
|
||||
} catch (NumberFormatException error) {
|
||||
denied("Invalid presigned expiry");
|
||||
return;
|
||||
}
|
||||
if (expires < 1 || expires > 604800) denied("Invalid presigned expiry");
|
||||
try {
|
||||
Instant start = Instant.from(DATE.parse(date));
|
||||
Instant now = clock.instant();
|
||||
if (now.isBefore(start.minus(Duration.ofMinutes(5))) || now.isAfter(start.plusSeconds(expires)))
|
||||
denied("Presigned URL has expired or is not yet valid");
|
||||
} catch (java.time.DateTimeException error) { denied("Invalid signing date"); }
|
||||
}
|
||||
|
||||
private record PresignedQuery(Map<String, String> fields, String application, String signed) { }
|
||||
|
||||
private static boolean hasPresignedQuery(String raw) {
|
||||
return raw != null && (raw.startsWith("X-Amz-Algorithm=") || raw.contains("&X-Amz-Algorithm="));
|
||||
}
|
||||
|
||||
private static void appendQuery(StringBuilder target, String part) {
|
||||
if (!target.isEmpty()) target.append('&');
|
||||
target.append(part);
|
||||
}
|
||||
|
||||
private static Map<String, String> authorizationFields(Headers headers) {
|
||||
String authorization = single(headers, "authorization");
|
||||
if (authorization == null || !authorization.startsWith("AWS4-HMAC-SHA256 ")) denied("Signed requests are required");
|
||||
Map<String,String> fields = new TreeMap<>();
|
||||
Map<String, String> fields = new TreeMap<>();
|
||||
for (String part : authorization.substring(17).split(",")) {
|
||||
String[] pair = part.trim().split("=", 2);
|
||||
if (pair.length != 2 || fields.put(pair[0], pair[1]) != null) denied("Invalid authorization header");
|
||||
}
|
||||
if (!fields.keySet().equals(java.util.Set.of("Credential", "SignedHeaders", "Signature"))) denied("Invalid authorization fields");
|
||||
String[] credential = fields.get("Credential").split("/", -1);
|
||||
if (credential.length != 5 || !credential[0].equals(accessKey) || !credential[2].equals(region)
|
||||
return fields;
|
||||
}
|
||||
|
||||
private String[] credentialScope(String value) {
|
||||
String[] credential = value.split("/", -1);
|
||||
if (credential.length != 5 || !(identities.containsKey(credential[0]) || sessions.containsKey(credential[0])) || !credential[2].equals(region)
|
||||
|| !credential[3].equals("s3") || !credential[4].equals("aws4_request")) denied("Invalid credential scope");
|
||||
String date = single(headers, "x-amz-date"), payload = single(headers, "x-amz-content-sha256");
|
||||
if (date == null || !credential[1].matches("[0-9]{8}") || !date.matches("[0-9]{8}T[0-9]{6}Z") || !date.startsWith(credential[1])) denied("Invalid signing date");
|
||||
return credential;
|
||||
}
|
||||
|
||||
private String secret(String accessKey) {
|
||||
String secret = identities.get(accessKey);
|
||||
if (secret == null && sessions.containsKey(accessKey)) secret = sessions.get(accessKey).secret();
|
||||
if (secret == null) denied("Invalid credential scope");
|
||||
return secret;
|
||||
}
|
||||
|
||||
private void validateSession(String accessKey, String token) {
|
||||
SessionCredentials.Session session = sessions.get(accessKey);
|
||||
if (session == null) {
|
||||
if (token != null) denied("Unexpected session token");
|
||||
return;
|
||||
}
|
||||
if (token == null || !MessageDigest.isEqual(token.getBytes(StandardCharsets.UTF_8),
|
||||
session.token().getBytes(StandardCharsets.UTF_8)) || !clock.instant().isBefore(session.expires()))
|
||||
denied("Invalid or expired session token");
|
||||
}
|
||||
|
||||
private String signingDate(Headers headers, String credentialDate) {
|
||||
String date = single(headers, "x-amz-date");
|
||||
if (date == null || !credentialDate.matches("[0-9]{8}") || !date.matches("[0-9]{8}T[0-9]{6}Z") || !date.startsWith(credentialDate)) denied("Invalid signing date");
|
||||
try {
|
||||
Instant signed = Instant.from(DATE.parse(date));
|
||||
if (Duration.between(signed, clock.instant()).abs().compareTo(Duration.ofMinutes(5)) > 0)
|
||||
throw new StoreException(403, "RequestTimeTooSkewed", "Request timestamp is outside the permitted window");
|
||||
} catch (java.time.DateTimeException e) { denied("Invalid signing date"); }
|
||||
if (payload == null || !HEX.matcher(payload).matches())
|
||||
throw new StoreException(400, "NotImplemented", "A hexadecimal SHA-256 payload hash is required; unsigned and chunk-signed payloads are unsupported");
|
||||
if (headers.containsKey("x-amz-security-token")) denied("Temporary credentials are unsupported");
|
||||
String signedHeaders = fields.get("SignedHeaders");
|
||||
return date;
|
||||
}
|
||||
|
||||
private static String payloadHash(Headers headers) {
|
||||
String payload = single(headers, "x-amz-content-sha256");
|
||||
if (payload == null || !(HEX.matcher(payload).matches() ||
|
||||
payload.equals("STREAMING-AWS4-HMAC-SHA256-PAYLOAD") ||
|
||||
payload.equals("STREAMING-AWS4-HMAC-SHA256-PAYLOAD-TRAILER")))
|
||||
throw new StoreException(400, "NotImplemented", "Unsupported SHA-256 payload mode");
|
||||
return payload;
|
||||
}
|
||||
|
||||
private static String canonicalHeaders(Headers headers, String signedHeaders, Set<String> required) {
|
||||
String[] names = signedHeaders.split(";", -1);
|
||||
if (names.length > 32 || !signedHeaders.equals(String.join(";", Arrays.stream(names).distinct().sorted().toList()))) denied("Signed headers must be unique and sorted");
|
||||
var namesSet = java.util.Set.copyOf(Arrays.asList(names));
|
||||
if (!namesSet.containsAll(java.util.Set.of("host", "x-amz-date", "x-amz-content-sha256"))) denied("Missing signed headers");
|
||||
if (!namesSet.containsAll(required)) denied("Missing signed headers");
|
||||
for (String key : headers.keySet()) {
|
||||
String lower = key.toLowerCase(java.util.Locale.ROOT);
|
||||
if (lower.startsWith("x-amz-") && !namesSet.contains(lower)) denied("Unsigned Amazon header");
|
||||
@@ -66,14 +244,7 @@ final class SigV4 {
|
||||
if (value == null) denied("Missing signed header");
|
||||
canonicalHeaders.append(name).append(':').append(value.trim().replaceAll("[\\t ]+", " ")).append('\n');
|
||||
}
|
||||
String canonical = method + "\n" + encode(decode(uri.getRawPath()), true) + "\n"
|
||||
+ canonicalQuery(uri.getRawQuery()) + "\n" + canonicalHeaders + "\n" + signedHeaders + "\n" + payload;
|
||||
String scope = String.join("/", Arrays.copyOfRange(credential, 1, 5));
|
||||
String toSign = "AWS4-HMAC-SHA256\n" + date + "\n" + scope + "\n" + hex(hash(canonical.getBytes(StandardCharsets.UTF_8)));
|
||||
byte[] signingKey = signingKey(secretKey, credential[1], region);
|
||||
String signature = fields.get("Signature");
|
||||
if (!HEX.matcher(signature).matches() || !MessageDigest.isEqual(hmac(signingKey, toSign), HexFormat.of().parseHex(signature))) denied("Signature mismatch");
|
||||
return payload;
|
||||
return canonicalHeaders.toString();
|
||||
}
|
||||
|
||||
static String single(Headers headers, String name) {
|
||||
@@ -85,17 +256,25 @@ final class SigV4 {
|
||||
|
||||
static String decode(String value) {
|
||||
try {
|
||||
var bytes=new java.io.ByteArrayOutputStream();
|
||||
for(int i=0;i<value.length();){
|
||||
if(value.charAt(i)=='%'){
|
||||
if(i+2>=value.length())throw new IllegalArgumentException();
|
||||
int hi=Character.digit(value.charAt(i+1),16),lo=Character.digit(value.charAt(i+2),16);
|
||||
if(hi<0||lo<0)throw new IllegalArgumentException();
|
||||
bytes.write((hi<<4)|lo);i+=3;
|
||||
}else{int point=value.codePointAt(i);bytes.writeBytes(new String(Character.toChars(point)).getBytes(StandardCharsets.UTF_8));i+=Character.charCount(point);}
|
||||
var bytes = new java.io.ByteArrayOutputStream();
|
||||
for (int i = 0; i < value.length();) {
|
||||
if (value.charAt(i) == '%') {
|
||||
if (i + 2 >= value.length()) throw new IllegalArgumentException();
|
||||
int hi = Character.digit(value.charAt(i + 1), 16);
|
||||
int lo = Character.digit(value.charAt(i + 2), 16);
|
||||
if (hi < 0 || lo < 0) throw new IllegalArgumentException();
|
||||
bytes.write((hi << 4) | lo);
|
||||
i += 3;
|
||||
} else {
|
||||
int point = value.codePointAt(i);
|
||||
bytes.writeBytes(new String(Character.toChars(point)).getBytes(StandardCharsets.UTF_8));
|
||||
i += Character.charCount(point);
|
||||
}
|
||||
}
|
||||
return StandardCharsets.UTF_8.newDecoder().onMalformedInput(java.nio.charset.CodingErrorAction.REPORT).decode(java.nio.ByteBuffer.wrap(bytes.toByteArray())).toString();
|
||||
}catch(IllegalArgumentException|java.nio.charset.CharacterCodingException e){throw new StoreException(400,"InvalidURI","Malformed URI encoding");}
|
||||
} catch (IllegalArgumentException | java.nio.charset.CharacterCodingException e) {
|
||||
throw new StoreException(400, "InvalidURI", "Malformed URI encoding");
|
||||
}
|
||||
}
|
||||
|
||||
static String encode(String value, boolean keepSlash) {
|
||||
@@ -120,10 +299,17 @@ final class SigV4 {
|
||||
return hmac(hmac(hmac(hmac(("AWS4"+secret).getBytes(StandardCharsets.UTF_8),date),region),"s3"),"aws4_request");
|
||||
}
|
||||
static byte[] hmac(byte[] key, String text) {
|
||||
try { Mac mac=Mac.getInstance("HmacSHA256");mac.init(new SecretKeySpec(key,"HmacSHA256"));return mac.doFinal(text.getBytes(StandardCharsets.UTF_8)); }
|
||||
try {
|
||||
Mac mac = Mac.getInstance("HmacSHA256");
|
||||
mac.init(new SecretKeySpec(key, "HmacSHA256"));
|
||||
return mac.doFinal(text.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
catch (java.security.GeneralSecurityException e) { throw new IllegalStateException(e); }
|
||||
}
|
||||
static byte[] hash(byte[] data) { try {return MessageDigest.getInstance("SHA-256").digest(data);}catch(java.security.NoSuchAlgorithmException e){throw new IllegalStateException(e);} }
|
||||
static byte[] hash(byte[] data) {
|
||||
try { return MessageDigest.getInstance("SHA-256").digest(data); }
|
||||
catch (java.security.NoSuchAlgorithmException e) { throw new IllegalStateException(e); }
|
||||
}
|
||||
static String hex(byte[] data) { return HexFormat.of().formatHex(data); }
|
||||
private static void denied(String message) { throw new StoreException(403,"AccessDenied",message); }
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
final class StorageLimits {
|
||||
private StorageLimits() {}
|
||||
|
||||
static ObjectStorage.Limits fromEnvironment(Map<String, String> environment) {
|
||||
try {
|
||||
long maxObject = Long.parseLong(environment.getOrDefault("MAX_OBJECT_BYTES", "134217728"));
|
||||
long maxTotal = Long.parseLong(environment.getOrDefault("MAX_TOTAL_BYTES", "2147483648"));
|
||||
if (maxObject < 1 || maxObject > 1073741824L || maxTotal < maxObject)
|
||||
throw new NumberFormatException();
|
||||
return new ObjectStorage.Limits(maxObject, maxTotal);
|
||||
} catch (NumberFormatException error) {
|
||||
throw new IllegalArgumentException("Invalid storage size limits", error);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,9 @@ package cloud.lunarsky.store;
|
||||
final class StoreException extends RuntimeException {
|
||||
final int status;
|
||||
final String code;
|
||||
final String versionId;
|
||||
final long modified;
|
||||
final boolean deleteMarker;
|
||||
StoreException(int status, String code, String message) {
|
||||
this(status, code, message, null);
|
||||
}
|
||||
@@ -10,5 +13,20 @@ final class StoreException extends RuntimeException {
|
||||
super(message, cause);
|
||||
this.status = status;
|
||||
this.code = code;
|
||||
this.versionId = null;
|
||||
this.modified = -1;
|
||||
this.deleteMarker = false;
|
||||
}
|
||||
private StoreException(int status, String code, String message, String versionId, long modified) {
|
||||
super(message);
|
||||
this.status = status;
|
||||
this.code = code;
|
||||
this.versionId = versionId;
|
||||
this.modified = modified;
|
||||
this.deleteMarker = true;
|
||||
}
|
||||
static StoreException deletedVersion(String versionId, long modified, boolean explicit) {
|
||||
return new StoreException(explicit ? 405 : 404, explicit ? "MethodNotAllowed" : "NoSuchKey",
|
||||
"Object is deleted", versionId, modified);
|
||||
}
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.util.List;
|
||||
|
||||
final class UnavailableMultipart implements MultipartStorage {
|
||||
private StoreException unavailable() {
|
||||
return new StoreException(501, "NotImplemented", "Multipart uploads are unavailable in the local cluster prototype");
|
||||
}
|
||||
@Override public String create(String bucket, String key, String contentType) { throw unavailable(); }
|
||||
@Override public String putPart(String id, String bucket, String key, int number, InputStream input,
|
||||
long length, String expectedHash, String checksum) { throw unavailable(); }
|
||||
@Override public ObjectStorage.Metadata complete(String id, String bucket, String key, List<Part> parts) { throw unavailable(); }
|
||||
@Override public void abort(String id, String bucket, String key) { throw unavailable(); }
|
||||
@Override public int activeUploads() { return 0; }
|
||||
@Override public long stagedBytes() { return 0; }
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import com.sun.net.httpserver.Headers;
|
||||
import java.io.FilterInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.Base64;
|
||||
import java.util.Locale;
|
||||
import java.util.zip.CRC32;
|
||||
import java.util.zip.CRC32C;
|
||||
import java.util.zip.Checksum;
|
||||
|
||||
final class UploadChecksums {
|
||||
private record Algorithm(String name, String header, int length) {}
|
||||
|
||||
private final byte[] contentMd5;
|
||||
private final Algorithm algorithm;
|
||||
private final byte[] expected;
|
||||
private final String encoded;
|
||||
|
||||
private UploadChecksums(byte[] contentMd5, Algorithm algorithm, byte[] expected, String encoded) {
|
||||
this.contentMd5 = contentMd5;
|
||||
this.algorithm = algorithm;
|
||||
this.expected = expected;
|
||||
this.encoded = encoded;
|
||||
}
|
||||
|
||||
static UploadChecksums from(Headers headers) {
|
||||
String md5 = SigV4.single(headers, "content-md5");
|
||||
byte[] contentMd5 = md5 == null ? null : decode(md5, 16);
|
||||
Algorithm algorithm = null;
|
||||
String encoded = null;
|
||||
for (String name : headers.keySet()) {
|
||||
String lower = name.toLowerCase(Locale.ROOT);
|
||||
if (!lower.startsWith("x-amz-checksum-")) continue;
|
||||
if (algorithm != null)
|
||||
throw new StoreException(400, "InvalidRequest", "Supply one checksum algorithm");
|
||||
algorithm = algorithm(lower);
|
||||
encoded = SigV4.single(headers, name);
|
||||
}
|
||||
String selected = SigV4.single(headers, "x-amz-sdk-checksum-algorithm");
|
||||
if (selected != null) {
|
||||
String trailer = SigV4.single(headers, "x-amz-trailer");
|
||||
if (algorithm == null && trailer != null) {
|
||||
Algorithm declared = algorithm(trailer);
|
||||
if (!selected.equals(declared.name()))
|
||||
throw new StoreException(400, "InvalidRequest", "Checksum algorithm and trailer must match");
|
||||
} else if (algorithm == null || !selected.equals(algorithm.name())) {
|
||||
throw new StoreException(400, "InvalidRequest", "Checksum algorithm and value must match");
|
||||
}
|
||||
}
|
||||
byte[] expected = algorithm == null ? null : decode(encoded, algorithm.length());
|
||||
return new UploadChecksums(contentMd5, algorithm, expected, encoded);
|
||||
}
|
||||
|
||||
private static Algorithm algorithm(String header) {
|
||||
return switch (header) {
|
||||
case "x-amz-checksum-crc32" -> new Algorithm("CRC32", header, 4);
|
||||
case "x-amz-checksum-crc32c" -> new Algorithm("CRC32C", header, 4);
|
||||
case "x-amz-checksum-crc64nvme" -> new Algorithm("CRC64NVME", header, 8);
|
||||
case "x-amz-checksum-xxhash64" -> new Algorithm("XXHASH64", header, 8);
|
||||
case "x-amz-checksum-xxhash3" -> new Algorithm("XXHASH3", header, 8);
|
||||
case "x-amz-checksum-xxhash128" -> new Algorithm("XXHASH128", header, 16);
|
||||
case "x-amz-checksum-sha1" -> new Algorithm("SHA1", header, 20);
|
||||
case "x-amz-checksum-sha256" -> new Algorithm("SHA256", header, 32);
|
||||
case "x-amz-checksum-sha512" -> new Algorithm("SHA512", header, 64);
|
||||
case "x-amz-checksum-md5" -> new Algorithm("MD5", header, 16);
|
||||
default -> throw new StoreException(501, "NotImplemented", "Checksum algorithm is unsupported");
|
||||
};
|
||||
}
|
||||
|
||||
private static byte[] decode(String value, int length) {
|
||||
try {
|
||||
byte[] decoded = Base64.getDecoder().decode(value);
|
||||
if (decoded.length == length) return decoded;
|
||||
} catch (IllegalArgumentException ignored) { }
|
||||
throw new StoreException(400, "InvalidDigest", "Invalid checksum encoding or length");
|
||||
}
|
||||
|
||||
String sha256() {
|
||||
return algorithm != null && algorithm.name().equals("SHA256") ? encoded : null;
|
||||
}
|
||||
|
||||
java.util.Map<String, String> metadata() {
|
||||
return algorithm == null ? java.util.Map.of() : java.util.Map.of(algorithm.header(), encoded);
|
||||
}
|
||||
|
||||
void response(Headers headers) {
|
||||
if (algorithm != null) headers.set(algorithm.header(), encoded);
|
||||
}
|
||||
|
||||
InputStream verifying(InputStream input) {
|
||||
if (contentMd5 == null && (algorithm == null || algorithm.name().equals("SHA256"))) return input;
|
||||
return new VerifiedInput(input);
|
||||
}
|
||||
|
||||
private final class VerifiedInput extends FilterInputStream {
|
||||
private final MessageDigest md5 = contentMd5 != null ||
|
||||
(algorithm != null && algorithm.name().equals("MD5")) ? digest("MD5") : null;
|
||||
private final MessageDigest hash = algorithm == null ? null : switch (algorithm.name()) {
|
||||
case "SHA1" -> digest("SHA-1");
|
||||
case "SHA512" -> digest("SHA-512");
|
||||
default -> null;
|
||||
};
|
||||
private final Checksum crc = algorithm == null ? null : switch (algorithm.name()) {
|
||||
case "CRC32" -> new CRC32();
|
||||
case "CRC32C" -> new CRC32C();
|
||||
case "CRC64NVME" -> new Crc64Nvme();
|
||||
default -> null;
|
||||
};
|
||||
private final XxHashes xxhash = algorithm != null && algorithm.name().startsWith("XXHASH")
|
||||
? new XxHashes(algorithm.name()) : null;
|
||||
private boolean checked;
|
||||
|
||||
private VerifiedInput(InputStream input) { super(input); }
|
||||
|
||||
@Override public int read() throws IOException {
|
||||
int value = in.read();
|
||||
if (value < 0) verify();
|
||||
else update(new byte[]{(byte) value}, 0, 1);
|
||||
return value;
|
||||
}
|
||||
|
||||
@Override public int read(byte[] bytes, int offset, int length) throws IOException {
|
||||
int count = in.read(bytes, offset, length);
|
||||
if (count < 0) verify();
|
||||
else if (count > 0) update(bytes, offset, count);
|
||||
return count;
|
||||
}
|
||||
|
||||
private void update(byte[] bytes, int offset, int length) {
|
||||
if (md5 != null) md5.update(bytes, offset, length);
|
||||
if (hash != null) hash.update(bytes, offset, length);
|
||||
if (crc != null) crc.update(bytes, offset, length);
|
||||
if (xxhash != null) xxhash.update(bytes, offset, length);
|
||||
}
|
||||
|
||||
private void verify() {
|
||||
if (checked) return;
|
||||
checked = true;
|
||||
byte[] actualMd5 = md5 == null ? null : md5.digest();
|
||||
if (contentMd5 != null && !MessageDigest.isEqual(contentMd5, actualMd5))
|
||||
throw new StoreException(400, "BadDigest", "Content-MD5 mismatch");
|
||||
if (algorithm == null || algorithm.name().equals("SHA256")) return;
|
||||
byte[] actual;
|
||||
if (crc != null) {
|
||||
long value = crc.getValue();
|
||||
actual = new byte[algorithm.length()];
|
||||
for (int i = actual.length - 1; i >= 0; i--) {
|
||||
actual[i] = (byte) value;
|
||||
value >>>= 8;
|
||||
}
|
||||
} else if (algorithm.name().equals("MD5")) actual = actualMd5;
|
||||
else if (xxhash != null) actual = xxhash.digest();
|
||||
else actual = hash.digest();
|
||||
if (!MessageDigest.isEqual(expected, actual))
|
||||
throw new StoreException(400, "BadDigest", algorithm.name() + " checksum mismatch");
|
||||
}
|
||||
}
|
||||
|
||||
private static MessageDigest digest(String algorithm) {
|
||||
try { return MessageDigest.getInstance(algorithm); }
|
||||
catch (NoSuchAlgorithmException error) { throw new IllegalStateException(error); }
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
final class Version {
|
||||
static final String VALUE = "0.0.2";
|
||||
static final String VALUE = "0.1.0";
|
||||
|
||||
private Version() {}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import com.dynatrace.hash4j.hashing.HashStream64;
|
||||
import com.dynatrace.hash4j.hashing.HashStream128;
|
||||
import com.dynatrace.hash4j.hashing.Hashing;
|
||||
import java.nio.ByteBuffer;
|
||||
|
||||
final class XxHashes {
|
||||
private final HashStream64 stream;
|
||||
|
||||
XxHashes(String algorithm) {
|
||||
stream = switch (algorithm) {
|
||||
case "XXHASH64" -> Hashing.xxh64().hashStream();
|
||||
case "XXHASH3" -> Hashing.xxh3_64().hashStream();
|
||||
case "XXHASH128" -> Hashing.xxh3_128().hashStream();
|
||||
default -> throw new IllegalArgumentException(algorithm);
|
||||
};
|
||||
}
|
||||
|
||||
void update(byte[] bytes, int offset, int length) {
|
||||
stream.putBytes(bytes, offset, length);
|
||||
}
|
||||
|
||||
byte[] digest() {
|
||||
if (stream instanceof HashStream128 wide) {
|
||||
var value = wide.get();
|
||||
return ByteBuffer.allocate(16).putLong(value.getMostSignificantBits())
|
||||
.putLong(value.getLeastSignificantBits()).array();
|
||||
}
|
||||
return ByteBuffer.allocate(8).putLong(stream.getAsLong()).array();
|
||||
}
|
||||
}
|
||||
@@ -44,6 +44,21 @@ public final class CliTest {
|
||||
int status = Cli.run(new String[]{"verify"}, root, new PrintStream(output), new PrintStream(output));
|
||||
if (status != 1 || !output.toString().contains("Object checksum mismatch"))
|
||||
throw new AssertionError("CLI missed corrupted payload");
|
||||
Path versionRoot = root.resolve("versioned");
|
||||
try (var store = new DiskStore(versionRoot, 100, 1000)) {
|
||||
store.createBucket("versioned-bucket");
|
||||
store.setVersioning("versioned-bucket", ObjectStorage.VersioningState.ENABLED);
|
||||
for (byte[] body : new byte[][]{"first".getBytes(StandardCharsets.UTF_8),
|
||||
"second".getBytes(StandardCharsets.UTF_8)}) {
|
||||
store.put("versioned-bucket", "example", new ByteArrayInputStream(body), body.length,
|
||||
SigV4.hex(SigV4.hash(body)), null, false, "text/plain");
|
||||
}
|
||||
output.reset();
|
||||
status = Cli.run(new String[]{"verify"}, versionRoot,
|
||||
new PrintStream(output), new PrintStream(output));
|
||||
if (status != 0 || !output.toString().contains("verified_objects=2"))
|
||||
throw new AssertionError("CLI did not inspect retained versions");
|
||||
}
|
||||
System.out.println("CLI tests passed: version, live status, verification, corruption exit code");
|
||||
} finally {
|
||||
try (var paths = Files.walk(root)) {
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
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.concurrent.Executors;
|
||||
|
||||
public final class ClientLimitsTest {
|
||||
private static final String ACCESS = "TESTACCESSKEY123";
|
||||
private static final String SECRET = "test-secret-key-that-is-at-least-32-characters";
|
||||
|
||||
private static HttpResponse<String> get(HttpClient client, String base, String path, String ip) throws Exception {
|
||||
var request = HttpRequest.newBuilder(URI.create(base + path));
|
||||
if (ip != null) request.header("X-Real-IP", ip);
|
||||
return client.send(request.GET().build(), HttpResponse.BodyHandlers.ofString());
|
||||
}
|
||||
|
||||
private static void status(int wanted, HttpResponse<?> response) {
|
||||
if (response.statusCode() != wanted)
|
||||
throw new AssertionError("Expected " + wanted + ", got " + response.statusCode() + ": " + response.body());
|
||||
}
|
||||
|
||||
private static void exercise(Map<String, String> configuration, boolean trusted) throws Exception {
|
||||
Path root = Files.createTempDirectory("client-limits-test-");
|
||||
var executor = Executors.newVirtualThreadPerTaskExecutor();
|
||||
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 16);
|
||||
DiskStore store = new DiskStore(root, 1024, 4096);
|
||||
try {
|
||||
var app = new Main(store, new MultipartStore(store),
|
||||
new SigV4(Map.of(ACCESS, SECRET), ACCESS, "us-east-1", Clock.systemUTC()),
|
||||
"objects", ClientLimits.fromEnvironment(configuration));
|
||||
server.setExecutor(executor);
|
||||
server.createContext("/", app::handle);
|
||||
server.start();
|
||||
String base = "http://127.0.0.1:" + server.getAddress().getPort();
|
||||
HttpClient client = HttpClient.newHttpClient();
|
||||
if (trusted) {
|
||||
status(200, get(client, base, "/health", null));
|
||||
status(400, get(client, base, "/ready", null));
|
||||
status(400, get(client, base, "/objects/example", null));
|
||||
status(400, get(client, base, "/health", "not-an-ip"));
|
||||
status(400, client.send(HttpRequest.newBuilder(URI.create(base + "/health"))
|
||||
.header("X-Real-IP", "192.0.2.1")
|
||||
.header("X-Real-IP", "192.0.2.2")
|
||||
.GET().build(), HttpResponse.BodyHandlers.ofString()));
|
||||
status(200, get(client, base, "/health", "192.0.2.1"));
|
||||
var limited = get(client, base, "/health", "192.0.2.1");
|
||||
status(503, limited);
|
||||
if (!"1".equals(limited.headers().firstValue("Retry-After").orElse(null)))
|
||||
throw new AssertionError("SlowDown response lacks Retry-After");
|
||||
status(200, get(client, base, "/health", "192.0.2.2"));
|
||||
} else if (configuration.containsKey("PUBLIC_BYTES_PER_SECOND")) {
|
||||
long start = System.nanoTime();
|
||||
byte[] upload = new byte[128];
|
||||
status(200, client.send(HttpTest.signedUri(URI.create(base + "/objects/bandwidth"),
|
||||
"PUT", upload, Map.of()), HttpResponse.BodyHandlers.ofString()));
|
||||
if (System.nanoTime() - start < 800_000_000L)
|
||||
throw new AssertionError("Upload bytes were not paced");
|
||||
start = System.nanoTime();
|
||||
status(200, get(client, base, "/health", "192.0.2.1"));
|
||||
status(200, get(client, base, "/health", "192.0.2.1"));
|
||||
if (System.nanoTime() - start < 250_000_000L)
|
||||
throw new AssertionError("Responses were not paced by the shared byte budget");
|
||||
} else {
|
||||
status(200, get(client, base, "/health", "192.0.2.1"));
|
||||
status(503, get(client, base, "/health", "192.0.2.2"));
|
||||
}
|
||||
} finally {
|
||||
server.stop(0);
|
||||
executor.close();
|
||||
store.close();
|
||||
try (var paths = Files.walk(root)) {
|
||||
for (Path path : paths.sorted(Comparator.reverseOrder()).toList()) Files.delete(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
var disabled = ClientLimits.fromEnvironment(Map.of());
|
||||
if (disabled == null) throw new AssertionError("Disabled configuration missing");
|
||||
try { ClientLimits.fromEnvironment(Map.of("PUBLIC_TRUSTED_PROXY_IPS", "127.0.0.1"));
|
||||
throw new AssertionError("Proxy trust accepted without limits");
|
||||
} catch (IllegalArgumentException expected) { }
|
||||
exercise(Map.of("PUBLIC_REQUESTS_PER_SECOND", "1", "PUBLIC_REQUEST_BURST", "1",
|
||||
"PUBLIC_TRUSTED_PROXY_IPS", "127.0.0.1"), true);
|
||||
exercise(Map.of("PUBLIC_REQUESTS_PER_SECOND", "1", "PUBLIC_REQUEST_BURST", "1"), false);
|
||||
exercise(Map.of("PUBLIC_BYTES_PER_SECOND", "64", "PUBLIC_BYTE_BURST", "64"), false);
|
||||
System.out.println("Client limit tests passed");
|
||||
}
|
||||
}
|
||||
@@ -3,8 +3,14 @@ package cloud.lunarsky.store;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.Arrays;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.HashSet;
|
||||
import java.util.UUID;
|
||||
|
||||
public final class ClusterIntegrationTest {
|
||||
private static final String KEY = "cluster-test/survivor";
|
||||
@@ -21,7 +27,9 @@ public final class ClusterIntegrationTest {
|
||||
switch (args[0]) {
|
||||
case "basic" -> {
|
||||
byte[] large = new byte[ClusterNode.MAX_SEGMENT + 37];
|
||||
for (int i = 0; i < large.length; i++) large[i] = (byte) (i * 31);
|
||||
for (int i = 0; i < large.length; i++) {
|
||||
large[i] = (byte) (i * 31);
|
||||
}
|
||||
String largeKey = "cluster-test/large";
|
||||
put(store, bucket, largeKey, large, false);
|
||||
try (var opened = store.open(bucket, largeKey)) {
|
||||
@@ -39,7 +47,10 @@ public final class ClusterIntegrationTest {
|
||||
"Overwrite was not visible");
|
||||
}
|
||||
store.delete(bucket, largeKey);
|
||||
try { store.open(bucket, largeKey); throw new AssertionError("Deleted object remained visible"); }
|
||||
try {
|
||||
store.open(bucket, largeKey);
|
||||
throw new AssertionError("Deleted object remained visible");
|
||||
}
|
||||
catch (StoreException error) { require(error.status == 404, "Wrong missing-object status"); }
|
||||
put(store, bucket, KEY, stable, false);
|
||||
require(store.ready(), "Healthy cluster is not ready");
|
||||
@@ -57,13 +68,70 @@ public final class ClusterIntegrationTest {
|
||||
}
|
||||
System.out.println("Cluster degraded test passed");
|
||||
}
|
||||
case "multipart-stage" -> {
|
||||
String key = "cluster-test/multipart";
|
||||
String id = store.create(bucket, key, "text/plain");
|
||||
byte[] first = "hello ".getBytes(StandardCharsets.UTF_8);
|
||||
byte[] second = "world".getBytes(StandardCharsets.UTF_8);
|
||||
putPart(store, id, bucket, key, 1, "old".getBytes(StandardCharsets.UTF_8));
|
||||
putPart(store, id, bucket, key, 1, first);
|
||||
putPart(store, id, bucket, key, 2, second);
|
||||
require(store.activeUploads() == 1, "Upload was not retained");
|
||||
require(store.stagedBytes() == first.length + second.length, "Replaced part was counted twice");
|
||||
require(store.listUploads(bucket, key).size() == 1, "Upload listing missed the staged upload");
|
||||
var firstPage = store.listParts(id, bucket, key, 0, 1);
|
||||
require(firstPage.truncated() && firstPage.parts().size() == 1 && firstPage.nextMarker() == 1,
|
||||
"Part listing did not paginate");
|
||||
require(store.listParts(id, bucket, key, 1, 1).parts().getFirst().number() == 2,
|
||||
"Part marker skipped the second part");
|
||||
try {
|
||||
store.open(bucket, key);
|
||||
throw new AssertionError("Incomplete upload became visible");
|
||||
} catch (StoreException error) { require(error.status == 404, "Wrong incomplete-upload status"); }
|
||||
System.out.println("Cluster multipart parts staged and listed");
|
||||
}
|
||||
case "multipart-complete" -> {
|
||||
String key = "cluster-test/multipart";
|
||||
var uploads = store.listUploads(bucket, key);
|
||||
require(uploads.size() == 1, "Upload did not survive gateway restart");
|
||||
String id = uploads.getFirst().id();
|
||||
var listed = store.listParts(id, bucket, key, 0, 1000).parts();
|
||||
require(listed.size() == 2, "Staged parts were lost");
|
||||
try {
|
||||
store.complete(id, bucket, key, List.of(new MultipartStorage.Part(1, "0".repeat(32))));
|
||||
throw new AssertionError("Wrong part ETag was accepted");
|
||||
} catch (StoreException error) { require(error.status == 400, "Wrong ETag rejection status"); }
|
||||
var completed = store.complete(id, bucket, key, List.of(
|
||||
new MultipartStorage.Part(1, listed.get(0).etag()),
|
||||
new MultipartStorage.Part(2, listed.get(1).etag())));
|
||||
byte[] expected = "hello world".getBytes(StandardCharsets.UTF_8);
|
||||
require(completed.length() == expected.length && completed.contentType().equals("text/plain"),
|
||||
"Completed object metadata is wrong");
|
||||
MessageDigest digest = MessageDigest.getInstance("MD5");
|
||||
digest.update(HexFormat.of().parseHex(listed.get(0).etag()));
|
||||
digest.update(HexFormat.of().parseHex(listed.get(1).etag()));
|
||||
require(completed.etag().equals(HexFormat.of().formatHex(digest.digest()) + "-2"),
|
||||
"Multipart ETag is wrong");
|
||||
try (var opened = store.open(bucket, key)) {
|
||||
require(Arrays.equals(opened.stream().readAllBytes(), expected), "Completed multipart body is wrong");
|
||||
}
|
||||
require(store.activeUploads() == 0 && store.stagedBytes() == 0, "Completed parts still count as staged");
|
||||
String aborted = store.create(bucket, "cluster-test/aborted", "text/plain");
|
||||
putPart(store, aborted, bucket, "cluster-test/aborted", 1, expected);
|
||||
store.abort(aborted, bucket, "cluster-test/aborted");
|
||||
require(store.activeUploads() == 0 && store.stagedBytes() == 0, "Aborted parts still count as staged");
|
||||
System.out.println("Cluster multipart completion survived restart and node loss");
|
||||
}
|
||||
case "quorum-lost" -> {
|
||||
require(!store.ready(), "One available node must not be ready");
|
||||
try {
|
||||
put(store, bucket, "cluster-test/rejected", new byte[]{1}, false);
|
||||
throw new AssertionError("Write succeeded with only one node");
|
||||
} catch (StoreException error) { require(error.status == 503, "Wrong unavailable status"); }
|
||||
try { store.open(bucket, "cluster-test/rejected"); throw new AssertionError("Failed write became visible"); }
|
||||
try {
|
||||
store.open(bucket, "cluster-test/rejected");
|
||||
throw new AssertionError("Failed write became visible");
|
||||
}
|
||||
catch (StoreException error) { require(error.status == 404, "Partial object became visible"); }
|
||||
System.out.println("Cluster quorum-loss test passed");
|
||||
}
|
||||
@@ -82,13 +150,18 @@ public final class ClusterIntegrationTest {
|
||||
var executor = java.util.concurrent.Executors.newFixedThreadPool(2);
|
||||
try {
|
||||
var a = executor.submit(() -> {
|
||||
start.await(); put(store, bucket, key, first, false); return null;
|
||||
start.await();
|
||||
put(store, bucket, key, first, false);
|
||||
return null;
|
||||
});
|
||||
var b = executor.submit(() -> {
|
||||
start.await(); put(store, bucket, key, second, false); return null;
|
||||
start.await();
|
||||
put(store, bucket, key, second, false);
|
||||
return null;
|
||||
});
|
||||
start.countDown();
|
||||
a.get(); b.get();
|
||||
a.get();
|
||||
b.get();
|
||||
try (var opened = store.open(bucket, key)) {
|
||||
byte[] actual = opened.stream().readAllBytes();
|
||||
require(Arrays.equals(actual, first) || Arrays.equals(actual, second),
|
||||
@@ -130,6 +203,42 @@ public final class ClusterIntegrationTest {
|
||||
}
|
||||
System.out.println("Joined node accepted new placements while previous objects stayed readable");
|
||||
}
|
||||
case "verify-expanded" -> {
|
||||
for (int i = 0; i < 32; i++) {
|
||||
try (var opened = store.open(bucket, "cluster-test/expanded-" + i)) {
|
||||
require(("expanded object " + i).equals(new String(opened.stream().readAllBytes(),
|
||||
StandardCharsets.UTF_8)), "Expanded object was lost during maintenance");
|
||||
}
|
||||
}
|
||||
System.out.println("Expanded objects survived repair and cleanup");
|
||||
}
|
||||
case "balanced" -> {
|
||||
try (var connection = java.sql.DriverManager.getConnection(env.get("POSTGRES_JDBC_URL"),
|
||||
env.get("POSTGRES_USER"), env.get("POSTGRES_PASSWORD"))) {
|
||||
NodeClient nodes = NodeRegistry.load(connection,
|
||||
Arrays.stream(urls).map(URI::create).toList(), env.get("CLUSTER_TOKEN"), null);
|
||||
int checked = 0;
|
||||
try (var query = connection.createStatement();
|
||||
var result = query.executeQuery("SELECT s.segment_id, s.replica_ids FROM cluster_segments s " +
|
||||
"JOIN cluster_objects o ON o.generation=s.generation")) {
|
||||
while (result.next()) {
|
||||
UUID segment = (UUID) result.getObject(1);
|
||||
Set<UUID> preferred = new HashSet<>();
|
||||
Set<UUID> hosts = new HashSet<>();
|
||||
for (int index : PlacementPolicy.candidates(segment, nodes, true)) {
|
||||
if (hosts.add(nodes.faultDomain(index, true))) preferred.add(nodes.node(index).id());
|
||||
if (preferred.size() == 3) break;
|
||||
}
|
||||
Set<UUID> actual = new HashSet<>();
|
||||
for (Object id : (Object[]) result.getArray(2).getArray()) actual.add((UUID) id);
|
||||
require(actual.equals(preferred), "Segment did not move to preferred hosts");
|
||||
checked++;
|
||||
}
|
||||
}
|
||||
require(checked > 0, "No live segments were checked for placement");
|
||||
}
|
||||
System.out.println("Existing segments balanced across preferred hosts");
|
||||
}
|
||||
default -> throw new IllegalArgumentException("Unknown test phase");
|
||||
}
|
||||
}
|
||||
@@ -138,6 +247,11 @@ public final class ClusterIntegrationTest {
|
||||
store.put(bucket, key, new ByteArrayInputStream(data), data.length, SigV4.hex(SigV4.hash(data)),
|
||||
null, createOnly, "application/octet-stream");
|
||||
}
|
||||
private static void putPart(ClusterStore store, String id, String bucket, String key, int number, byte[] data)
|
||||
throws Exception {
|
||||
store.putPart(id, bucket, key, number, new ByteArrayInputStream(data), data.length,
|
||||
SigV4.hex(SigV4.hash(data)), null);
|
||||
}
|
||||
private static void require(boolean condition, String message) {
|
||||
if (!condition) throw new AssertionError(message);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.URI;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.sql.DriverManager;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
public final class ClusterMetadataTest {
|
||||
public static void main(String[] args) throws Exception {
|
||||
Map<String, String> env = System.getenv();
|
||||
String token = "metadata-test-cluster-token-0123456789";
|
||||
String repairToken = "metadata-test-repair-token-0123456789";
|
||||
Path root = Files.createTempDirectory("objectstore-metadata-test-");
|
||||
try (ClusterNode first = new ClusterNode(root.resolve("first"), token, repairToken, UUID.randomUUID());
|
||||
ClusterNode second = new ClusterNode(root.resolve("second"), token, repairToken, UUID.randomUUID())) {
|
||||
HttpServer firstServer = server(first);
|
||||
HttpServer secondServer = server(second);
|
||||
try {
|
||||
List<URI> nodes = List.of(url(firstServer), url(secondServer));
|
||||
try (ClusterStore store = new ClusterStore(env.get("POSTGRES_JDBC_URL"),
|
||||
env.get("POSTGRES_USER"), env.get("POSTGRES_PASSWORD"), "objects",
|
||||
nodes, token, repairToken, 1024 * 1024, 16 * 1024 * 1024, false)) {
|
||||
require(store.ready(), "Writable primary was not selected from the multi-host URL");
|
||||
try (var admin = DriverManager.getConnection(env.get("POSTGRES_ADMIN_JDBC_URL"),
|
||||
env.get("POSTGRES_USER"), env.get("POSTGRES_PASSWORD"));
|
||||
var statement = admin.createStatement()) {
|
||||
statement.execute("ALTER DATABASE objectstore_test SET default_transaction_read_only=on");
|
||||
try {
|
||||
require(!store.ready(), "Read-only metadata was reported ready");
|
||||
} finally {
|
||||
statement.execute("ALTER DATABASE objectstore_test RESET default_transaction_read_only");
|
||||
}
|
||||
}
|
||||
require(store.ready(), "Writable metadata did not recover after read-only mode ended");
|
||||
}
|
||||
} finally {
|
||||
firstServer.stop(0);
|
||||
secondServer.stop(0);
|
||||
}
|
||||
}
|
||||
System.out.println("Metadata routing tests passed: second JDBC host and writable readiness");
|
||||
}
|
||||
|
||||
private static HttpServer server(ClusterNode node) throws Exception {
|
||||
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
|
||||
server.createContext("/", node::handle);
|
||||
server.start();
|
||||
return server;
|
||||
}
|
||||
|
||||
private static URI url(HttpServer server) {
|
||||
return URI.create("http://127.0.0.1:" + server.getAddress().getPort());
|
||||
}
|
||||
|
||||
private static void require(boolean condition, String message) {
|
||||
if (!condition) throw new AssertionError(message);
|
||||
}
|
||||
}
|
||||
Loaded 100 of 113 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user