Compare commits
5
Commits
a4f55a5bde
..
v0.1.1
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
240c278621 | ||
|
|
bd6bb52dc7 | ||
|
|
35bd1d5703 | ||
|
|
0cf5c11202 | ||
|
|
31eb4d092e |
No files matched your search
@@ -4,12 +4,21 @@ CLUSTER_TOKEN=
|
||||
CLUSTER_REPAIR_TOKEN=
|
||||
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=
|
||||
+13
-4
@@ -1,9 +1,14 @@
|
||||
# Copy to .env and replace both empty values with random credentials.
|
||||
# The Compose file refuses to start without them.
|
||||
S3_ACCESS_KEY=[Replace_with_your_S3_Access_Key]
|
||||
S3_SECRET_KEY=[Replace_with_your_S3_Secret_Key]
|
||||
# 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
|
||||
@@ -16,6 +21,10 @@ 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,8 +1,10 @@
|
||||
out/
|
||||
rust-client/target/
|
||||
.env
|
||||
.env.cluster
|
||||
*.local.env
|
||||
data/
|
||||
secrets/
|
||||
*.log
|
||||
__pycache__/
|
||||
*.pyc
|
||||
|
||||
+8
-2
@@ -4,6 +4,7 @@ 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
|
||||
COPY admin-ui ./admin-ui
|
||||
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
|
||||
@@ -11,19 +12,24 @@ RUN java --add-modules jdk.httpserver -cp /out:/tmp/hash4j.jar cloud.lunarsky.st
|
||||
RUN java --add-modules jdk.httpserver -cp /out:/tmp/hash4j.jar cloud.lunarsky.store.ConcurrencyTest
|
||||
RUN java --add-modules jdk.httpserver,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.AdminConsoleTest
|
||||
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
|
||||
WORKDIR /app
|
||||
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 admin-ui /app/admin-ui
|
||||
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:/app/hash4j.jar", "cloud.lunarsky.store.Main"]
|
||||
ENTRYPOINT ["/usr/local/bin/objectstore-server"]
|
||||
+192
@@ -0,0 +1,192 @@
|
||||
# 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, in-flight requests, and S3 request and body-byte totals without bucket or user labels. Keep the token private. The Prometheus endpoint is disabled when the variable is empty.
|
||||
|
||||
### Local admin console
|
||||
|
||||
The admin console is a read-only status, bucket, and performance view at `http://127.0.0.1:9000/_objectstore/admin/`. It lists buckets, navigates object prefixes, and shows object metadata and bucket access settings. The object-size chart and counts cover only the current page of a listing. The performance view samples every three seconds while visible and graphs S3 request rate, inbound and outbound body bytes, process CPU, and memory. It also shows GC collections. Admin requests and health checks are excluded from those S3 rates, and chart history lives only in the browser tab. RSS is read from Linux when available; otherwise the memory card shows JVM heap plus non-heap usage. This view does not require the separate Prometheus token. It is disabled by default and uses a separate password, not an S3 access key. Its Biscuit widgets are bundled with the image under the MIT license in `admin-ui/LICENSE.Biscuit`. To enable it for the local Compose stack:
|
||||
|
||||
```sh
|
||||
mkdir -p secrets
|
||||
chmod 700 secrets
|
||||
umask 077
|
||||
openssl rand -base64 32 > secrets/admin-password
|
||||
chmod 644 secrets/admin-password
|
||||
docker compose -f compose.yaml -f compose.admin.yaml up -d --build
|
||||
```
|
||||
|
||||
Read the generated password from `secrets/admin-password` on the host to sign in. The directory is private to your host account, while the file is readable by the container's unprivileged user through a read-only mount. The file is ignored by Git. The password must be at least 16 bytes. Sessions expire after 30 minutes, and five failed logins from one peer pause further attempts for five minutes. A restart clears all sessions. Do not reuse the S3 secret.
|
||||
|
||||
The console accepts only loopback Host values by default, including if the S3 port is accidentally published on a wider interface. For access through a reverse proxy, set `ADMIN_UI_ORIGIN` to the exact external HTTPS origin, preserve its Host header, and terminate TLS at the proxy. HTTP access through a remote origin is not supported. The password is still required behind the loopback binding or proxy; neither is an authentication mechanism. The console does not grant access to S3 operations.
|
||||
|
||||
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,49 +4,28 @@
|
||||
|
||||
Small S3-compatible object storage for LunarSky.
|
||||
|
||||
Source: [GitHub](https://github.com/LunarSkyOSS/ObjectStore) · [Gitea mirror](https://git.lunarsky.cloud/admin/ObjectStore) · [Documentation](https://docs.lunarsky.cloud/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) [](https://www.codefactor.io/repository/github/lunarskyoss/objectstore)
|
||||
[](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)
|
||||
- [Encrypted storage](#encrypted-storage)
|
||||
- [Access keys and ACLs](#access-keys-and-acls)
|
||||
- [CLI and tests](#cli-and-tests)
|
||||
- [Capability discovery](#capability-discovery)
|
||||
- [Java client](#java-client)
|
||||
- [Local cluster prototype](#local-cluster-prototype)
|
||||
- [Node transport TLS](#node-transport-tls)
|
||||
- [Metadata primary routing](#metadata-primary-routing)
|
||||
- [Migrating a local cluster](#migrating-a-local-cluster)
|
||||
- [Adding a cluster node](#adding-a-cluster-node)
|
||||
- [Cluster maintenance and recovery](#cluster-maintenance-and-recovery)
|
||||
- [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 creates the configured default bucket at startup. Additional buckets share the configured capacity limit.
|
||||
ObjectStore creates the default bucket at startup. All buckets share one capacity limit.
|
||||
|
||||
- ✅ Persistent single-node storage with checksum verification
|
||||
- ✅ Optional dm-crypt-backed data mounts with startup guards
|
||||
- ✅ 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
|
||||
- ✅ Optional HTTPS between cluster processes and storage nodes
|
||||
- ✅ Opt-in automatic repair, rebalance, and guarded garbage collection in the local cluster
|
||||
- ✅ Metadata backup and tested restore to a separate local PostgreSQL instance
|
||||
- ✅ Manual [two-machine durability and metadata-restore drill](tests/two-host/README.md)
|
||||
- ✅ 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
|
||||
|
||||
@@ -56,22 +35,22 @@ New objects retain their content type and key. Objects written by the earlier si
|
||||
- ✅ Single-range GET and `ListObjectsV2` in both modes
|
||||
- ✅ SHA-256 payload verification and `x-amz-checksum-sha256` in both modes
|
||||
- ✅ `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`, `CompleteMultipartUpload`, and `AbortMultipartUpload` in both modes
|
||||
- ✅ `ListParts` and `ListMultipartUploads` in both modes
|
||||
- ✅ `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
|
||||
- ✅ Basic bucket and object ACL grants, public reads, and multiple access-key identities
|
||||
- ⬜ Full AWS ACL ownership controls, email grantees, and bucket policies
|
||||
- ✅ Bucket and object ACL grants, bucket policies, Object Ownership controls, and Block Public Access
|
||||
- ✅ Scoped identity policies and externally provisioned, expiring session credentials
|
||||
- ⬜ Full IAM, STS issuance, cross-account ACL ownership, and conditional policies
|
||||
|
||||
This is an S3 API subset, not full AWS S3 compatibility. Unsupported S3 operations and Amazon-specific headers are rejected.
|
||||
Buckets use the same three-to-63-character lowercase names as the configured default bucket. The default bucket cannot be deleted through the API. Bucket creation currently accepts the empty-body request used for the configured region. Tags do not control access.
|
||||
Versioning supports enabled and suspended states, historical object versions, null versions, and delete markers. Retained versions count toward the capacity limit. Deleting a specific version is permanent. Lifecycle expiration, MFA Delete, and `ListObjectVersions` delimiter grouping are not supported yet.
|
||||
User metadata values currently accept printable ASCII only; non-ASCII metadata header encoding is not yet supported.
|
||||
Checksums supplied with `PutObject` are validated before publication and retained across restarts, copies, and object versions. When no checksum is supplied, ObjectStore calculates and stores CRC64NVME, including for completed multipart uploads. Request `x-amz-checksum-mode: ENABLED` on `GetObject` or `HeadObject` to receive the stored checksum. `UploadPart` checksums are validated but are not yet returned by `ListParts` or combined into a multipart checksum; the completed object's CRC64NVME covers its full content. Presigned URLs use query Signature V4 with a maximum seven-day expiry. Streaming uploads support signed `aws-chunked` payloads and one signed checksum trailer. Temporary credentials and other streaming payload modes remain unsupported. Copies use the existing object size limit.
|
||||
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
|
||||
|
||||
@@ -85,147 +64,52 @@ curl http://127.0.0.1:9000/health
|
||||
|
||||
Port 9000 binds to localhost. Data stays in the `object-data` Docker volume. `docker compose down -v` deletes that volume.
|
||||
|
||||
The optional [local admin console](OPERATIONS.md#local-admin-console) has bucket and live performance views, its own password, and is disabled by default.
|
||||
|
||||
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.
|
||||
|
||||
## Encrypted storage
|
||||
## Operations
|
||||
|
||||
At-rest encryption is an **opt-in deployment setting** backed by a host-mounted dm-crypt/LUKS filesystem. ObjectStore does not encrypt bytes itself or store an encryption key in its environment. Prepare and unlock the LUKS filesystem outside Docker, then set `ENCRYPTED_STORAGE_ROOT` to its exact mount point and `ENCRYPTED_VOLUME_ID` to a stable 32-character lowercase hex identifier in your private environment file. Generate the identifier with `openssl rand -hex 16`; it is a mount guard, **not** a cryptographic key. Keep the LUKS recovery key separately from the data and backups.
|
||||
|
||||
With the encrypted filesystem mounted, prepare empty directories using `sh scripts/prepare-encrypted-storage.sh single /path/to/objectstore.env` or `sh scripts/prepare-encrypted-storage.sh cluster /path/to/cluster.env`. The script reads only the two encryption settings from that file; it does not execute it. It requires an active dm-crypt-backed mount at `ENCRYPTED_STORAGE_ROOT` and refuses to mark a nonempty directory. Run it with permission to create the directories and set container ownership. Enable the matching Compose override:
|
||||
|
||||
```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**, not both. The overrides bind encrypted directories for object data, cluster nodes, PostgreSQL, and cluster staging files. Each process checks a marker stored on its mounted directory before opening data; PostgreSQL checks before starting. If a mount is missing after reboot, the service refuses to start instead of silently creating a new plaintext store. Provision an unlock-and-mount service before starting Compose; a container restart cannot unlock LUKS. The preparation script checks the host mount, while the runtime marker is only a guard against an absent or wrong mount.
|
||||
|
||||
**Existing Docker volumes are not migrated automatically.** Stop the stack, take and verify a backup, prepare the empty encrypted directories, then copy the stopped volumes into their corresponding directories before starting with the override. For PostgreSQL, copy the existing data directory into `cluster/metadata/pgdata` because the encrypted override changes `PGDATA`. Verify the restored objects and database before retiring the original volumes. The cluster overlay places all local test containers on one encrypted host; a future multi-host deployment needs an encrypted data mount and key recovery plan on each host.
|
||||
|
||||
This covers the specified data and staging mounts, but not Docker logs, host swap, other temporary files, external backups, or a compromised running host. Encrypt those separately as appropriate, use TLS for network paths, restrict access, and test backup recovery. Encryption at rest is one security measure; enabling it does not by itself establish GDPR compliance.
|
||||
|
||||
## Access keys and ACLs
|
||||
|
||||
`S3_ACCESS_KEY` is the owner identity. Its secret is `S3_SECRET_KEY`. Additional keys are optional: place one `ACCESSKEY:secret` pair per line in a file mounted read-only inside the container, and set `S3_CREDENTIALS_FILE=/run/secrets/s3-credentials` in the environment file. Use a Compose override to mount an absolute host path at `/run/secrets/s3-credentials` for the `objectstore` service (or `gateway` in cluster mode). Each access key needs 16–128 alphanumeric characters and each secret at least 32 characters. A restart loads changes to that file. Keep it outside Git and protect it as a secret. Additional identities have no access until the owner grants it.
|
||||
|
||||
The owner can send `x-amz-acl: public-read` or signed `x-amz-grant-*` headers on bucket creation, object uploads, copies, and multipart initiation. `GET` and `PUT ?acl` support bucket and object ACLs; a PUT accepts either signed grant headers with an empty body or an XML `AccessControlPolicy`. A grantee ID is its configured access key. Supported permissions are `READ`, `WRITE`, `READ_ACP`, `WRITE_ACP`, and `FULL_CONTROL`. The `AllUsers` group is limited to `READ`; `AuthenticatedUsers` is also recognized. Anonymous reads work only where `AllUsers` has a read grant. Replacing an object starts with a private ACL unless the new upload supplies grants; older version ACLs remain attached to their versions.
|
||||
|
||||
This is a deliberately limited ACL subset. The configured owner owns every bucket and object. A `WRITE_ACP` grantee can change an object ACL only on a retained, non-null version; updates to current unversioned and null versions require the owner key. List-versions, multipart inspection, tagging, versioning controls, bucket creation/deletion, and the capability endpoint remain owner-only. There are no IAM policies, email grantees, Object Ownership modes, Block Public Access settings, or temporary credentials. Granting public bucket `READ` exposes object names through `ListObjectsV2`; granting public object `READ` exposes that object's bytes. Review those grants before exposing a gateway to the internet.
|
||||
|
||||
## 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
|
||||
|
||||
ObjectStore provides a signed `GET /_objectstore/capabilities` endpoint. Use the same header-based Signature V4 authentication as the S3 API. It returns JSON with `schemaVersion: 1`, the service and software version, storage mode, supported operation names, and configured limits. The endpoint does not disclose credentials or cluster topology. The response has `Cache-Control: no-store` because limits can change after a restart.
|
||||
|
||||
`operations` lists implemented API operations, not every AWS option for each operation or the caller's authorization to use them. `limits.maxObjectBytes` applies to a completed object and to each uploaded part; `limits.maxTotalBytes` is the logical storage limit; `limits.maxParts` is 10,000. Future schema version 1 responses may add fields. Clients should ignore unknown fields and treat unknown operation names as unsupported by their own implementation. This endpoint is an ObjectStore extension; a missing endpoint on another S3-compatible service does not prove that a feature is unavailable.
|
||||
|
||||
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.
|
||||
|
||||
The server includes [hash4j](https://github.com/dynatrace-oss/hash4j) for streaming XXHash checksums. Its Apache-2.0 license is included at [lib/LICENSE.hash4j](lib/LICENSE.hash4j).
|
||||
The [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.
|
||||
|
||||
## Java client
|
||||
|
||||
The [JDK-only Java client](client/README.md) works with ObjectStore and other S3-compatible endpoints. It supports object transfers, listing, multipart uploads, and read-only capability discovery. An [AWT image manager](client/examples/README.md) provides a small desktop example. Run `bash client/scripts/build.sh` to produce its JAR and Javadoc locally.
|
||||
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`.
|
||||
|
||||
## Local cluster prototype
|
||||
Gradle (Kotlin DSL):
|
||||
|
||||
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
|
||||
```kotlin
|
||||
repositories {
|
||||
maven { url = uri("https://repo.lunarsky.cloud/") }
|
||||
}
|
||||
dependencies {
|
||||
implementation("cloud.lunarsky:objectstore-client:0.0.8")
|
||||
}
|
||||
```
|
||||
|
||||
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.
|
||||
Maven (`pom.xml`):
|
||||
|
||||
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
|
||||
```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 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.
|
||||
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.
|
||||
|
||||
This secures node traffic only. The local cluster still lacks automatic PostgreSQL failover, database TLS configuration, encryption at rest, and production multi-server validation. Its HTTP S3 gateway remains bound to localhost; use a separate trusted proxy for external TLS. Do not treat the TLS overlay as a production deployment.
|
||||
## Rust client
|
||||
|
||||
## 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.
|
||||
|
||||
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, scoped credentials, and physical host verification remain absent. Garbage collection can remove data required by an older metadata backup, so its retention guard is essential. Host UUIDs are operator labels, not proof that machines have separate power, disks, or network paths. Keep `CLUSTER_LOCAL_DEV=true` limited to local tests.
|
||||
|
||||
The 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
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ The script compiles the source and test programs into `out/classes`, then runs:
|
||||
| Test | Checks |
|
||||
| --- | --- |
|
||||
| `StoreTest` | Signature V4 and signed-stream vectors, CRC64NVME and XXHash reference vectors, local writes and reads, quotas, restart persistence for objects, checksums, ACLs, attributes, buckets, and versions, multipart recovery, legacy reads, locking, and corruption rejection. |
|
||||
| `ConcurrencyTest` | Atomic local overwrites and consistent reads, listings, and deletes during concurrent access. |
|
||||
| `ConcurrencyTest` | Atomic local overwrites, consistent reads, listings and deletes, plus concurrent quota enforcement and restart recovery. |
|
||||
| `HttpTest` | Signed capability discovery, presigned URLs, streaming uploads and trailers, object and bucket operations, ACL grants with a second access key and public reads, copies, checksum persistence and rejection, ranges, listing, metadata, tags, multipart uploads, versioning, and signed virtual-hosted requests in single-node mode. |
|
||||
| `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. |
|
||||
@@ -69,6 +69,6 @@ The [manual two-machine drill](tests/two-host/README.md) uses machine A and mach
|
||||
|
||||
- Container stops are not physical power cuts or disk failures. The automated suite does not reboot a host or test every possible crash point.
|
||||
- The Compose nodes share one machine. Passing the local-only quorum override does not demonstrate durability across independent hosts, racks, or sites.
|
||||
- The suite does not test automatic metadata failover, an off-site backup restore, prolonged load, or full AWS S3 compatibility.
|
||||
- The suite does not test automatic metadata failover, an off-site backup restore, prolonged load, or full AWS S3 compatibility. `scripts/test.sh` checks scoped keys, CORS, and metrics. A separate local cold-snapshot drill restored one object into fresh single-node and cluster Compose projects and confirmed its bytes; the single-node restore also refused a nonempty destination. This does not test a multi-host restore. The Rust client passed live local upload/download and presigned GET/PUT smoke tests, but is not covered by the Java test script.
|
||||
|
||||
See [Limits and safety](README.md#limits-and-safety) before evaluating any multi-server deployment.
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 Biscuit contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
+12373
File diff suppressed because it is too large.
Load diff
Binary file not shown.
|
After Width: | Height: | Size: 697 KiB |
@@ -0,0 +1,153 @@
|
||||
(() => {
|
||||
const base = '/_objectstore/admin';
|
||||
const state = document.getElementById('perf-state');
|
||||
const charts = [
|
||||
['perf-requests-chart', [
|
||||
{ type: 'line', x: 'time', y: 'requests', name: 'Requests/s' },
|
||||
{ type: 'line', x: 'time', y: 'errors', name: 'Errors/s' }
|
||||
]],
|
||||
['perf-transfer-chart', [
|
||||
{ type: 'line', x: 'time', y: 'inbound', name: 'Inbound KiB/s' },
|
||||
{ type: 'line', x: 'time', y: 'outbound', name: 'Outbound KiB/s' }
|
||||
]],
|
||||
['perf-cpu-chart', [
|
||||
{ type: 'line', x: 'time', y: 'cpu', name: 'CPU %' }
|
||||
]],
|
||||
['perf-memory-chart', [
|
||||
{ type: 'line', x: 'time', y: 'memory', name: 'RSS MiB' },
|
||||
{ type: 'line', x: 'time', y: 'heap', name: 'Heap MiB' }
|
||||
]]
|
||||
].map(([id, series]) => {
|
||||
const chart = document.getElementById(id);
|
||||
chart.series = series;
|
||||
return chart;
|
||||
});
|
||||
const history = [];
|
||||
let previous = null;
|
||||
let polling = false;
|
||||
let memoryFallback = false;
|
||||
|
||||
function show(id, value) {
|
||||
document.getElementById(id).textContent = value;
|
||||
}
|
||||
|
||||
function bytes(value, suffix = '') {
|
||||
if (!Number.isFinite(value) || value < 0) return '—';
|
||||
const units = ['B', 'KiB', 'MiB', 'GiB', 'TiB'];
|
||||
let index = 0;
|
||||
while (value >= 1024 && index < units.length - 1) {
|
||||
value /= 1024;
|
||||
index++;
|
||||
}
|
||||
return (index === 0 ? Math.round(value) : value.toFixed(1)) + ' ' + units[index] + suffix;
|
||||
}
|
||||
|
||||
function rate(value) {
|
||||
return Number.isFinite(value) ? value.toFixed(value < 10 ? 2 : 1) : '—';
|
||||
}
|
||||
|
||||
function counterDelta(current, before, key) {
|
||||
return Math.max(0, current[key] - before[key]);
|
||||
}
|
||||
|
||||
function updateCharts() {
|
||||
document.querySelector('.perf-charts').hidden = history.length === 0;
|
||||
for (const chart of charts)
|
||||
chart.data = chart.id === 'perf-cpu-chart'
|
||||
? history.filter(point => point.cpu !== null) : history;
|
||||
}
|
||||
|
||||
async function poll() {
|
||||
if (polling || document.hidden) return;
|
||||
polling = true;
|
||||
const controller = new AbortController();
|
||||
const timeout = setTimeout(() => controller.abort(), 5000);
|
||||
try {
|
||||
const response = await fetch(base + '/performance.json', {
|
||||
cache: 'no-store', credentials: 'same-origin', signal: controller.signal
|
||||
});
|
||||
if (response.redirected) {
|
||||
location.assign(base + '/login');
|
||||
return;
|
||||
}
|
||||
if (!response.ok) throw new Error('Metrics unavailable');
|
||||
if (!response.headers.get('Content-Type')?.includes('application/json'))
|
||||
throw new Error('Unexpected metrics response');
|
||||
const sample = await response.json();
|
||||
const now = performance.now();
|
||||
const rss = sample.rssBytes >= 0 ? sample.rssBytes : sample.heapBytes + sample.nonHeapBytes;
|
||||
if (sample.rssBytes < 0 && !memoryFallback) {
|
||||
memoryFallback = true;
|
||||
document.querySelector('#perf-ram').previousElementSibling.textContent = 'JVM memory used';
|
||||
charts[3].series = [
|
||||
{ type: 'line', x: 'time', y: 'memory', name: 'JVM used MiB' },
|
||||
{ type: 'line', x: 'time', y: 'heap', name: 'Heap MiB' }
|
||||
];
|
||||
}
|
||||
show('perf-ram', bytes(rss));
|
||||
show('perf-gc', Number(sample.gcCount).toLocaleString());
|
||||
show('perf-inflight', Number(sample.inFlight).toLocaleString());
|
||||
if (previous && sample.requests < previous.sample.requests) {
|
||||
history.length = 0;
|
||||
updateCharts();
|
||||
}
|
||||
if (previous && sample.requests >= previous.sample.requests) {
|
||||
const seconds = (now - previous.at) / 1000;
|
||||
if (seconds > 0.1) {
|
||||
const requests = counterDelta(sample, previous.sample, 'requests');
|
||||
const errors = counterDelta(sample, previous.sample, 'failures4xx') +
|
||||
counterDelta(sample, previous.sample, 'failures5xx');
|
||||
const cpu = sample.cpuNanos >= 0 && previous.sample.cpuNanos >= 0
|
||||
? Math.max(0, Math.min(100,
|
||||
(sample.cpuNanos - previous.sample.cpuNanos) /
|
||||
(seconds * 1e9 * Math.max(1, sample.processors)) * 100))
|
||||
: null;
|
||||
const point = {
|
||||
time: new Date().toLocaleTimeString(),
|
||||
requests: requests / seconds,
|
||||
errors: errors / seconds,
|
||||
inbound: counterDelta(sample, previous.sample, 'inboundBytes') / seconds / 1024,
|
||||
outbound: counterDelta(sample, previous.sample, 'outboundBytes') / seconds / 1024,
|
||||
cpu,
|
||||
memory: rss / 1048576,
|
||||
heap: sample.heapBytes / 1048576,
|
||||
seconds
|
||||
};
|
||||
history.push(point);
|
||||
if (history.length > 60) history.shift();
|
||||
show('perf-rps', rate(point.requests));
|
||||
show('perf-latency', requests ?
|
||||
(counterDelta(sample, previous.sample, 'durationNanos') / requests / 1e6).toFixed(1) + ' ms' : '—');
|
||||
show('perf-inbound', bytes(point.inbound * 1024, '/s'));
|
||||
show('perf-outbound', bytes(point.outbound * 1024, '/s'));
|
||||
const cpuPoints = history.filter(entry => entry.cpu !== null);
|
||||
const cpuSeconds = cpuPoints.reduce((total, entry) => total + entry.seconds, 0);
|
||||
show('perf-cpu', cpuSeconds ?
|
||||
(cpuPoints.reduce((total, entry) => total + entry.cpu * entry.seconds, 0) /
|
||||
cpuSeconds).toFixed(1) + '%' : '—');
|
||||
updateCharts();
|
||||
}
|
||||
}
|
||||
previous = { sample, at: now };
|
||||
state.textContent = history.length ? 'Live · recent samples' : 'Collecting a second sample…';
|
||||
} catch {
|
||||
state.textContent = 'Connection lost · retrying';
|
||||
previous = null;
|
||||
} finally {
|
||||
clearTimeout(timeout);
|
||||
polling = false;
|
||||
}
|
||||
}
|
||||
|
||||
document.addEventListener('visibilitychange', () => {
|
||||
if (document.hidden) {
|
||||
previous = null;
|
||||
state.textContent = 'Paused while this tab is hidden';
|
||||
} else {
|
||||
state.textContent = 'Collecting a fresh sample…';
|
||||
poll();
|
||||
}
|
||||
});
|
||||
poll();
|
||||
setInterval(poll, 3000);
|
||||
})();
|
||||
+9
-1
@@ -4,7 +4,11 @@ A small, synchronous S3-compatible client built with the JDK alone. It uses path
|
||||
|
||||
## Build and test
|
||||
|
||||
Requires JDK 21 or newer. No Maven, Gradle, or third-party Java libraries are needed.
|
||||
Requires JDK 21 or newer. Building from source needs no Maven or Gradle, and the client has no third-party runtime dependencies.
|
||||
|
||||
For Maven or Gradle consumers, release 0.0.8 is published as
|
||||
`cloud.lunarsky:objectstore-client:0.0.8` at
|
||||
`https://repo.lunarsky.cloud/`. See the [installation examples](https://docs.lunarsky.cloud/objectstore/v0.0.8/client/install).
|
||||
|
||||
```sh
|
||||
bash client/scripts/test.sh
|
||||
@@ -13,6 +17,10 @@ bash client/scripts/build.sh
|
||||
|
||||
Run these commands from the ObjectStore repository root. The second command writes `client/dist/objectstore-client.jar` and `client/dist/javadoc/`.
|
||||
|
||||
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
|
||||
|
||||
@@ -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,8 @@
|
||||
services:
|
||||
objectstore:
|
||||
environment:
|
||||
ADMIN_UI_ENABLED: "true"
|
||||
ADMIN_UI_PASSWORD_FILE: /run/secrets/objectstore_admin
|
||||
ADMIN_UI_ORIGIN: ${ADMIN_UI_ORIGIN:-}
|
||||
volumes:
|
||||
- ./secrets/admin-password:/run/secrets/objectstore_admin:ro
|
||||
@@ -13,11 +13,19 @@ services:
|
||||
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}
|
||||
|
||||
@@ -4,16 +4,25 @@ 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}
|
||||
|
||||
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,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()
|
||||
@@ -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
|
||||
@@ -148,6 +148,15 @@ assert "ListParts" in capabilities["operations"], capabilities
|
||||
assert capabilities["limits"]["maxObjectBytes"] > 0, capabilities
|
||||
assert headers.get_content_type() == "application/json", headers
|
||||
|
||||
ownership = b"<OwnershipControls><Rule><ObjectOwnership>ObjectWriter</ObjectOwnership></Rule></OwnershipControls>"
|
||||
status, _, _ = request("PUT", f"/{bucket}?ownershipControls", ownership)
|
||||
assert status == 200, status
|
||||
public_access = (b"<PublicAccessBlockConfiguration><BlockPublicAcls>false</BlockPublicAcls>"
|
||||
b"<IgnorePublicAcls>false</IgnorePublicAcls><BlockPublicPolicy>false</BlockPublicPolicy>"
|
||||
b"<RestrictPublicBuckets>false</RestrictPublicBuckets></PublicAccessBlockConfiguration>")
|
||||
status, _, _ = request("PUT", f"/{bucket}?publicAccessBlock", public_access)
|
||||
assert status == 200, status
|
||||
|
||||
key = f"/{bucket}/cluster-test/http.txt"
|
||||
body = b"HTTP gateway integration test"
|
||||
status, _, _ = request("PUT", key, body)
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
test_dir=$(mktemp -d)
|
||||
trap 'rm -rf "$test_dir"' EXIT HUP INT TERM
|
||||
cat > "$test_dir/java" <<'EOF'
|
||||
#!/bin/sh
|
||||
printf '%s\n' "$@" > "$OBJECTSTORE_TEST_ARGS"
|
||||
EOF
|
||||
chmod +x "$test_dir/java"
|
||||
OBJECTSTORE_TEST_ARGS="$test_dir/args" PATH="$test_dir:$PATH" \
|
||||
OBJECTSTORE_REQUEST_TIMEOUT_SECONDS=300 OBJECTSTORE_RESPONSE_TIMEOUT_SECONDS=45 \
|
||||
sh scripts/start-server.sh
|
||||
grep -Fx -- '-Dsun.net.httpserver.maxReqTime=300' "$test_dir/args" >/dev/null
|
||||
grep -Fx -- '-Dsun.net.httpserver.maxRspTime=45' "$test_dir/args" >/dev/null
|
||||
if OBJECTSTORE_TEST_ARGS="$test_dir/args" PATH="$test_dir:$PATH" \
|
||||
OBJECTSTORE_REQUEST_TIMEOUT_SECONDS=86401 sh scripts/start-server.sh 2>/dev/null; then
|
||||
echo 'Oversized request timeout was accepted' >&2
|
||||
exit 1
|
||||
fi
|
||||
echo 'Server launcher timeout tests passed'
|
||||
@@ -1,6 +1,7 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
sh scripts/test-start-server.sh
|
||||
mkdir -p out/classes
|
||||
javac --release 21 --add-modules jdk.httpserver,java.net.http -cp lib/hash4j-0.30.0.jar -d out/classes \
|
||||
src/cloud/lunarsky/store/*.java test/cloud/lunarsky/store/*.java
|
||||
@@ -8,6 +9,8 @@ java --add-modules jdk.httpserver -cp out/classes:lib/hash4j-0.30.0.jar cloud.lu
|
||||
java --add-modules jdk.httpserver -cp out/classes:lib/hash4j-0.30.0.jar cloud.lunarsky.store.ConcurrencyTest
|
||||
java --add-modules jdk.httpserver,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.AdminConsoleTest
|
||||
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
|
||||
|
||||
@@ -65,6 +65,8 @@ final class Acl {
|
||||
principal = entry.substring(4, entry.length() - 1);
|
||||
else if (entry.startsWith("uri=\"") && entry.endsWith("\""))
|
||||
principal = entry.substring(5, entry.length() - 1);
|
||||
else if (entry.startsWith("emailAddress=\""))
|
||||
throw new StoreException(405, "MethodNotAllowed", "Email ACL grantees are no longer supported");
|
||||
else throw new StoreException(400, "InvalidArgument", "Invalid ACL grant");
|
||||
if (!identities.contains(principal) && !principal.equals(ALL_USERS) &&
|
||||
!principal.equals(AUTHENTICATED_USERS))
|
||||
@@ -122,6 +124,8 @@ final class Acl {
|
||||
String principal = switch (type) {
|
||||
case "CanonicalUser" -> text(grantee, "ID");
|
||||
case "Group" -> text(grantee, "URI");
|
||||
case "AmazonCustomerByEmail" -> throw new StoreException(405, "MethodNotAllowed",
|
||||
"Email ACL grantees are no longer supported");
|
||||
default -> throw new IllegalArgumentException();
|
||||
};
|
||||
Integer permission = PERMISSIONS.get(text(grant, "Permission"));
|
||||
@@ -130,7 +134,8 @@ final class Acl {
|
||||
}
|
||||
grants.remove(owner);
|
||||
return validate(encoded(grants), identities);
|
||||
} catch (Exception error) {
|
||||
} catch (StoreException error) { throw error; }
|
||||
catch (Exception error) {
|
||||
throw new StoreException(400, "MalformedACLError", "Invalid access control policy");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,334 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URLDecoder;
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
final class AdminBrowser {
|
||||
private static final int PAGE_SIZE = 50;
|
||||
private static final DateTimeFormatter TIME = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm 'UTC'")
|
||||
.withZone(ZoneOffset.UTC);
|
||||
|
||||
private AdminBrowser() { }
|
||||
|
||||
static String index(ObjectStorage store, String rawQuery, String csrf) throws IOException {
|
||||
Map<String, String> query = query(rawQuery, Set.of("filter", "after"));
|
||||
String filter = query.getOrDefault("filter", "").trim();
|
||||
String after = query.get("after");
|
||||
if (filter.length() > 256 || after != null && after.length() > 255)
|
||||
throw invalidQuery();
|
||||
List<ObjectStorage.Bucket> matches = store.buckets().stream()
|
||||
.filter(bucket -> bucket.name().toLowerCase(Locale.ROOT).contains(filter.toLowerCase(Locale.ROOT)))
|
||||
.sorted(Comparator.comparing(ObjectStorage.Bucket::name)).toList();
|
||||
List<ObjectStorage.Bucket> page = matches.stream()
|
||||
.filter(bucket -> after == null || bucket.name().compareTo(after) > 0)
|
||||
.limit(PAGE_SIZE + 1).toList();
|
||||
boolean next = page.size() > PAGE_SIZE;
|
||||
if (next) page = page.subList(0, PAGE_SIZE);
|
||||
|
||||
StringBuilder html = new StringBuilder(AdminConsole.consoleHeader(csrf));
|
||||
html.append("<nav class=crumbs aria-label=Breadcrumb><a href='")
|
||||
.append(AdminConsole.PATH).append("/overview'>Overview</a><span>/</span><span>Buckets</span></nav>")
|
||||
.append("<div class=intro><div><h2>Buckets</h2><p>")
|
||||
.append(matches.size()).append(" matching buckets · read-only</p></div></div>")
|
||||
.append("<div class=toolbar><form method=get action='").append(AdminConsole.PATH)
|
||||
.append("/buckets'><div class=field><label for=bucket-filter>Find a bucket</label>")
|
||||
.append("<input id=bucket-filter name=filter value='").append(AdminConsole.escape(filter))
|
||||
.append("' placeholder='Bucket name'></div><button type=submit>Search</button></form>")
|
||||
.append("<a class=button-link href='").append(AdminConsole.PATH)
|
||||
.append("/overview'>Overview</a></div>");
|
||||
if (page.isEmpty()) {
|
||||
html.append("<div class='table-wrap empty'>No buckets match this search.</div>");
|
||||
} else {
|
||||
html.append("<div class=table-wrap><table><thead><tr><th>Bucket</th><th>Versioning</th>")
|
||||
.append("<th>Ownership</th><th>Created</th></tr></thead><tbody>");
|
||||
for (ObjectStorage.Bucket bucket : page) {
|
||||
html.append("<tr><td class=name-cell><a href='")
|
||||
.append(bucketUrl(bucket.name(), "", null)).append("'>")
|
||||
.append(AdminConsole.escape(bucket.name())).append("</a></td><td>")
|
||||
.append(versioning(bucket.versioning())).append("</td><td>")
|
||||
.append(ownership(bucket.ownership())).append("</td><td>")
|
||||
.append(time(bucket.created())).append("</td></tr>");
|
||||
}
|
||||
html.append("</tbody></table></div>");
|
||||
}
|
||||
if (after != null || next) {
|
||||
html.append("<nav class=pagination aria-label='Bucket pages'><a class=button-link href='")
|
||||
.append(indexUrl(filter, null)).append("'>First page</a>");
|
||||
if (next) html.append("<a class=button-link href='")
|
||||
.append(indexUrl(filter, page.getLast().name())).append("'>Next page →</a>");
|
||||
html.append("</nav>");
|
||||
}
|
||||
return html.toString();
|
||||
}
|
||||
|
||||
static String bucket(ObjectStorage store, String rawQuery, String csrf) throws IOException {
|
||||
Map<String, String> query = query(rawQuery, Set.of("name", "prefix", "after"));
|
||||
String name = required(query, "name", 255);
|
||||
String prefix = query.getOrDefault("prefix", "");
|
||||
String after = query.get("after");
|
||||
if (prefix.length() > 1024 || after != null && after.length() > 1024)
|
||||
throw invalidQuery();
|
||||
ObjectStorage.Bucket bucket = store.bucket(name);
|
||||
ObjectStorage.ListPage page = store.list(name, prefix, "/", PAGE_SIZE, after);
|
||||
long visibleBytes = page.objects().stream().mapToLong(entry -> entry.metadata().length()).sum();
|
||||
|
||||
StringBuilder html = new StringBuilder(AdminConsole.consoleHeader(csrf));
|
||||
html.append(breadcrumbs(name, prefix));
|
||||
html.append("<div class=intro><div><h2>").append(AdminConsole.escape(name))
|
||||
.append("</h2><p>Browse prefixes and inspect object metadata.</p></div>")
|
||||
.append("<biscuit-badgeview theme=dark variant=accent>Read-only</biscuit-badgeview></div>")
|
||||
.append("<div class=grid><biscuit-cardview><small>Entries on this page</small><strong>")
|
||||
.append(page.keyCount()).append("</strong></biscuit-cardview>")
|
||||
.append("<biscuit-cardview><small>Object bytes on this page</small><strong>")
|
||||
.append(AdminConsole.formatBytes(visibleBytes)).append("</strong></biscuit-cardview>")
|
||||
.append("<biscuit-cardview><small>Versioning</small><strong>")
|
||||
.append(versioning(bucket.versioning())).append("</strong></biscuit-cardview></div>")
|
||||
.append("<section class=buckets id=objects><h2>Objects</h2>")
|
||||
.append("<p>Showing up to ").append(PAGE_SIZE)
|
||||
.append(" entries in this prefix. Counts and chart data describe this page only.</p>")
|
||||
.append("<div class=toolbar><form method=get action='").append(AdminConsole.PATH)
|
||||
.append("/bucket'><input type=hidden name=name value='").append(AdminConsole.escape(name))
|
||||
.append("'><div class=field><label for=prefix>Prefix</label>")
|
||||
.append("<input id=prefix name=prefix value='").append(AdminConsole.escape(prefix))
|
||||
.append("' placeholder='e.g. images/2026/'></div><button type=submit>Browse</button></form>")
|
||||
.append("<a class=button-link href='").append(AdminConsole.PATH)
|
||||
.append("/buckets'>All buckets</a></div>");
|
||||
if (page.keyCount() == 0) {
|
||||
html.append("<div class='table-wrap empty'>Nothing in this prefix.</div>");
|
||||
if (!prefix.isEmpty()) html.append("<nav class=pagination><a class=button-link href='")
|
||||
.append(bucketUrl(name, parentPrefix(prefix), null)).append("'>← Parent folder</a></nav>");
|
||||
} else {
|
||||
html.append("<div class=table-wrap><table><thead><tr><th>Name</th><th>Kind</th>")
|
||||
.append("<th>Size</th><th>Modified</th></tr></thead><tbody>");
|
||||
if (!prefix.isEmpty()) {
|
||||
html.append("<tr><td class=name-cell><a href='")
|
||||
.append(bucketUrl(name, parentPrefix(prefix), null))
|
||||
.append("'>../</a></td><td class=kind>Parent</td><td>—</td><td>—</td></tr>");
|
||||
}
|
||||
for (String folder : page.prefixes()) {
|
||||
html.append("<tr><td class=name-cell><a href='")
|
||||
.append(bucketUrl(name, folder, null)).append("'>▸ ")
|
||||
.append(AdminConsole.escape(folder.substring(prefix.length())))
|
||||
.append("</a></td><td class=kind>Folder</td><td>—</td><td>—</td></tr>");
|
||||
}
|
||||
for (ObjectStorage.ListedObject object : page.objects()) {
|
||||
ObjectStorage.Metadata meta = object.metadata();
|
||||
String label = object.key().substring(prefix.length());
|
||||
if (label.isEmpty()) label = "(folder marker)";
|
||||
html.append("<tr><td class=name-cell><a href='")
|
||||
.append(objectUrl(name, object.key())).append("'>")
|
||||
.append(AdminConsole.escape(label)).append("</a></td><td class=kind>Object</td><td>")
|
||||
.append(AdminConsole.formatBytes(meta.length())).append("</td><td>")
|
||||
.append(time(meta.modified())).append("</td></tr>");
|
||||
}
|
||||
html.append("</tbody></table></div>");
|
||||
}
|
||||
if (after != null || page.truncated()) {
|
||||
html.append("<nav class=pagination aria-label='Object pages'><a class=button-link href='")
|
||||
.append(bucketUrl(name, prefix, null)).append("'>First page</a>");
|
||||
if (page.truncated()) html.append("<a class=button-link href='")
|
||||
.append(bucketUrl(name, prefix, page.nextKey())).append("'>Next page →</a>");
|
||||
html.append("</nav>");
|
||||
}
|
||||
html.append("</section>");
|
||||
if (!page.objects().isEmpty()) {
|
||||
html.append("<section class=insight><biscuit-chartview type=bar theme=dark ")
|
||||
.append("name='Largest objects on this page' height=300>")
|
||||
.append("<biscuit-series type=bar x=label y=bytes name='Size in bytes'>");
|
||||
page.objects().stream().sorted(Comparator.comparingLong((ObjectStorage.ListedObject object) ->
|
||||
object.metadata().length()).reversed()).limit(10).forEach(object -> {
|
||||
String label = object.key().substring(prefix.length());
|
||||
if (label.length() > 24) label = label.substring(0, 23) + "…";
|
||||
html.append("<biscuit-point x='").append(AdminConsole.escape(label))
|
||||
.append("' y='").append(object.metadata().length()).append("'></biscuit-point>");
|
||||
});
|
||||
html.append("</biscuit-series></biscuit-chartview></section>");
|
||||
}
|
||||
html.append("<section class=buckets id=configuration><h2>Bucket settings</h2>")
|
||||
.append("<div class=detail-grid><div class=detail-card><h3>Access</h3>")
|
||||
.append(fact("Ownership", ownership(bucket.ownership())))
|
||||
.append(fact("Block public ACLs", yesNo(bucket.publicAccessBlock().blockPublicAcls())))
|
||||
.append(fact("Ignore public ACLs", yesNo(bucket.publicAccessBlock().ignorePublicAcls())))
|
||||
.append(fact("Block public policy", yesNo(bucket.publicAccessBlock().blockPublicPolicy())))
|
||||
.append(fact("Restrict public buckets", yesNo(bucket.publicAccessBlock().restrictPublicBuckets())))
|
||||
.append("</div><div class=detail-card><h3>Lifecycle</h3>")
|
||||
.append(fact("Created", time(bucket.created())))
|
||||
.append(fact("Versioning", versioning(bucket.versioning())))
|
||||
.append(fact("Policy", bucket.policy() == null ? "None" : "Configured"))
|
||||
.append("</div></div>");
|
||||
if (bucket.policy() != null)
|
||||
html.append("<details><summary>Bucket policy</summary><pre>")
|
||||
.append(AdminConsole.escape(bucket.policy())).append("</pre></details>");
|
||||
if (!bucket.acl().isEmpty())
|
||||
html.append(attributes("Bucket grants", bucket.acl()));
|
||||
html.append("</section>");
|
||||
return html.toString();
|
||||
}
|
||||
|
||||
static String object(ObjectStorage store, String rawQuery, String csrf) throws IOException {
|
||||
Map<String, String> query = query(rawQuery, Set.of("bucket", "key"));
|
||||
String bucketName = required(query, "bucket", 255);
|
||||
String key = required(query, "key", 1024);
|
||||
store.bucket(bucketName);
|
||||
ObjectStorage.Metadata meta;
|
||||
try (ObjectStorage.OpenObject opened = store.open(bucketName, key)) {
|
||||
meta = opened.metadata();
|
||||
}
|
||||
int slash = key.lastIndexOf('/');
|
||||
String prefix = slash < 0 ? "" : key.substring(0, slash + 1);
|
||||
StringBuilder html = new StringBuilder(AdminConsole.consoleHeader(csrf));
|
||||
html.append(breadcrumbs(bucketName, prefix))
|
||||
.append("<div class=intro><div><h2 class=name-cell>")
|
||||
.append(AdminConsole.escape(key.endsWith("/") ? "(folder marker)" : key.substring(prefix.length())))
|
||||
.append("</h2><p>Object metadata · content is not loaded in this view</p></div>")
|
||||
.append("<biscuit-badgeview theme=dark variant=accent>Object</biscuit-badgeview></div>")
|
||||
.append("<div class=grid><biscuit-cardview><small>Size</small><strong>")
|
||||
.append(AdminConsole.formatBytes(meta.length()))
|
||||
.append("</strong></biscuit-cardview><biscuit-cardview><small>Content type</small><strong>")
|
||||
.append(AdminConsole.escape(meta.contentType() == null ? "Unknown" : meta.contentType()))
|
||||
.append("</strong></biscuit-cardview><biscuit-cardview><small>Modified</small><strong>")
|
||||
.append(time(meta.modified())).append("</strong></biscuit-cardview></div>")
|
||||
.append("<div class=detail-grid><div class=detail-card><h3>Identity</h3>")
|
||||
.append(fact("Bucket", bucketName)).append(fact("Key", key))
|
||||
.append(fact("Version ID", meta.versionId() == null ? "Unversioned" : meta.versionId()))
|
||||
.append("</div><div class=detail-card><h3>Integrity</h3>")
|
||||
.append(fact("ETag", meta.etag() == null ? "—" : meta.etag()))
|
||||
.append(fact("SHA-256", meta.sha256() == null ? "—" :
|
||||
java.util.HexFormat.of().formatHex(meta.sha256())))
|
||||
.append("</div></div>")
|
||||
.append(attributes("User metadata", meta.userMetadata()))
|
||||
.append(attributes("Tags", meta.tags()))
|
||||
.append(attributes("Checksums", meta.checksums()))
|
||||
.append(attributes("ACL grants", meta.acl()));
|
||||
return html.toString();
|
||||
}
|
||||
|
||||
static String bucketUrl(String name, String prefix, String after) {
|
||||
StringBuilder url = new StringBuilder(AdminConsole.PATH + "/bucket?name=" + encoded(name));
|
||||
if (!prefix.isEmpty()) url.append("&prefix=").append(encoded(prefix));
|
||||
if (after != null) url.append("&after=").append(encoded(after));
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
private static String objectUrl(String bucket, String key) {
|
||||
return AdminConsole.PATH + "/object?bucket=" + encoded(bucket) + "&key=" + encoded(key);
|
||||
}
|
||||
|
||||
private static String indexUrl(String filter, String after) {
|
||||
StringBuilder url = new StringBuilder(AdminConsole.PATH + "/buckets?filter=" + encoded(filter));
|
||||
if (after != null) url.append("&after=").append(encoded(after));
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
private static String breadcrumbs(String bucket, String prefix) {
|
||||
StringBuilder html = new StringBuilder("<nav class=crumbs aria-label=Breadcrumb><a href='")
|
||||
.append(AdminConsole.PATH).append("/buckets'>Buckets</a><span>/</span>");
|
||||
if (prefix.isEmpty()) {
|
||||
html.append("<span>").append(AdminConsole.escape(bucket)).append("</span>");
|
||||
} else {
|
||||
html.append("<a href='").append(bucketUrl(bucket, "", null)).append("'>")
|
||||
.append(AdminConsole.escape(bucket)).append("</a>");
|
||||
int from = 0;
|
||||
while (from < prefix.length()) {
|
||||
int slash = prefix.indexOf('/', from);
|
||||
if (slash < 0) break;
|
||||
String current = prefix.substring(0, slash + 1);
|
||||
String label = prefix.substring(from, slash + 1);
|
||||
html.append("<span>/</span><a href='").append(bucketUrl(bucket, current, null))
|
||||
.append("'>").append(AdminConsole.escape(label)).append("</a>");
|
||||
from = slash + 1;
|
||||
}
|
||||
}
|
||||
return html.append("</nav>").toString();
|
||||
}
|
||||
|
||||
private static String parentPrefix(String prefix) {
|
||||
int last = prefix.lastIndexOf('/', prefix.length() - 2);
|
||||
return last < 0 ? "" : prefix.substring(0, last + 1);
|
||||
}
|
||||
|
||||
private static String attributes(String title, Map<String, String> values) {
|
||||
if (values == null || values.isEmpty()) return "";
|
||||
StringBuilder html = new StringBuilder("<details><summary>")
|
||||
.append(AdminConsole.escape(title)).append(" (" + values.size() + ")</summary>")
|
||||
.append("<div class=table-wrap><table><thead><tr><th>Name</th><th>Value</th></tr></thead><tbody>");
|
||||
values.entrySet().stream().sorted(Map.Entry.comparingByKey()).forEach(entry ->
|
||||
html.append("<tr><td class=name-cell>").append(AdminConsole.escape(entry.getKey()))
|
||||
.append("</td><td class=name-cell>").append(AdminConsole.escape(entry.getValue() == null ? "" : entry.getValue()))
|
||||
.append("</td></tr>"));
|
||||
return html.append("</tbody></table></div></details>").toString();
|
||||
}
|
||||
|
||||
private static String fact(String name, String value) {
|
||||
return "<div class=fact><span>" + AdminConsole.escape(name) + "</span><strong>" +
|
||||
AdminConsole.escape(value) + "</strong></div>";
|
||||
}
|
||||
|
||||
private static String versioning(ObjectStorage.VersioningState state) {
|
||||
return switch (state) {
|
||||
case NEVER -> "Off";
|
||||
case ENABLED -> "Enabled";
|
||||
case SUSPENDED -> "Suspended";
|
||||
};
|
||||
}
|
||||
|
||||
private static String ownership(ObjectStorage.ObjectOwnership value) {
|
||||
return switch (value) {
|
||||
case BUCKET_OWNER_ENFORCED -> "Owner enforced";
|
||||
case BUCKET_OWNER_PREFERRED -> "Owner preferred";
|
||||
case OBJECT_WRITER -> "Object writer";
|
||||
};
|
||||
}
|
||||
|
||||
private static String yesNo(boolean value) {
|
||||
return value ? "On" : "Off";
|
||||
}
|
||||
|
||||
private static String time(long epochMillis) {
|
||||
return TIME.format(Instant.ofEpochMilli(epochMillis));
|
||||
}
|
||||
|
||||
private static String encoded(String value) {
|
||||
return URLEncoder.encode(value, StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
private static String required(Map<String, String> values, String name, int limit) {
|
||||
String value = values.get(name);
|
||||
if (value == null || value.isEmpty() || value.length() > limit) throw invalidQuery();
|
||||
return value;
|
||||
}
|
||||
|
||||
private static Map<String, String> query(String raw, Set<String> allowed) {
|
||||
if (raw == null || raw.isEmpty()) return Map.of();
|
||||
if (raw.length() > 8192) throw invalidQuery();
|
||||
Map<String, String> values = new HashMap<>();
|
||||
try {
|
||||
for (String field : raw.split("&", -1)) {
|
||||
int equal = field.indexOf('=');
|
||||
if (equal < 0) throw invalidQuery();
|
||||
String name = URLDecoder.decode(field.substring(0, equal), StandardCharsets.UTF_8);
|
||||
String value = URLDecoder.decode(field.substring(equal + 1), StandardCharsets.UTF_8);
|
||||
if (!allowed.contains(name) || values.putIfAbsent(name, value) != null)
|
||||
throw invalidQuery();
|
||||
}
|
||||
} catch (IllegalArgumentException badEncoding) {
|
||||
throw invalidQuery();
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
private static StoreException invalidQuery() {
|
||||
return new StoreException(400, "InvalidArgument", "Invalid browser link or search");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,703 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import com.sun.net.httpserver.HttpExchange;
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.net.URLDecoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.SecureRandom;
|
||||
import java.time.Duration;
|
||||
import java.util.Base64;
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.List;
|
||||
|
||||
final class AdminConsole {
|
||||
static final String PATH = "/_objectstore/admin";
|
||||
private static final String STYLE = """
|
||||
:root { color-scheme: dark; }
|
||||
body { background: #14121d; color: #f4f0fa; font: 16px system-ui; margin: 0;
|
||||
padding: clamp(20px, 4vw, 48px); }
|
||||
main { max-width: 1080px; margin: 0 auto; }
|
||||
.login { min-height: calc(100dvh - 2 * clamp(20px, 4vw, 48px));
|
||||
display: grid; place-items: center; }
|
||||
.login-card { width: min(100%, 400px); box-sizing: border-box; padding: 34px;
|
||||
border: 1px solid #514663; border-radius: 18px; background: #211c2b;
|
||||
box-shadow: 0 24px 80px #08060d88; }
|
||||
.mark { display: grid; place-items: center; width: 48px; height: 48px; flex: none; }
|
||||
.mark img { width: 56px; height: 56px; max-width: none; }
|
||||
.login-brand { display: flex; align-items: center; gap: 12px; margin-bottom: 20px; }
|
||||
.login-brand strong { font-size: 1.1rem; }
|
||||
.login-card h1 { font-size: 1.75rem; }
|
||||
.login-card .muted { margin-bottom: 28px; line-height: 1.5; }
|
||||
h1 { margin: 0; font-size: 2rem; }
|
||||
header { display: flex; justify-content: space-between; align-items: center; gap: 16px;
|
||||
border-bottom: 1px solid #3e344e; padding-bottom: 22px; }
|
||||
.header-title { display: flex; align-items: center; gap: 14px; }
|
||||
.header-title h1 { font-size: 1.35rem; }
|
||||
.header-title small { margin-top: 3px; }
|
||||
.intro { display: flex; align-items: center; justify-content: space-between;
|
||||
gap: 16px; margin: 34px 0 18px; }
|
||||
.intro h2, .buckets h2 { margin: 0 0 6px; font-size: 1.3rem; }
|
||||
.intro p, .buckets p { margin: 0; color: #aaa2bb; }
|
||||
.muted, small { color: #aaa2bb; }
|
||||
.error { color: #ffafa9; }
|
||||
form { margin-top: 24px; }
|
||||
label { display: block; margin-bottom: 8px; }
|
||||
input, button { font: inherit; border: 1px solid #514663; border-radius: 8px;
|
||||
padding: 12px 14px; }
|
||||
input { display: block; width: min(100%, 360px); box-sizing: border-box;
|
||||
background: #211c2b; color: #fff; }
|
||||
input[type=hidden] { display: none; }
|
||||
.login input[type=password], .login button { width: 100%; }
|
||||
button { background: #b39add; color: #20172c; cursor: pointer; }
|
||||
form button { margin-top: 12px; }
|
||||
header form { margin: 0; }
|
||||
header button { background: #282232; color: #eee; }
|
||||
.grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
|
||||
gap: 14px; }
|
||||
biscuit-cardview { display: block; --biscuit-cardview-background: #211c2b;
|
||||
--biscuit-cardview-border: 1px solid #463a58;
|
||||
--biscuit-cardview-radius: 14px;
|
||||
--biscuit-cardview-padding: 22px;
|
||||
--biscuit-cardview-color: #f4f0fa; }
|
||||
biscuit-cardview:not(:defined) { background: #211c2b; border: 1px solid #463a58;
|
||||
border-radius: 14px; padding: 22px; }
|
||||
biscuit-cardview small { display: block; margin-bottom: 12px; }
|
||||
biscuit-cardview strong { display: block; font-size: 1.2rem; overflow-wrap: anywhere; }
|
||||
biscuit-badgeview:not(:defined) { display: inline-block; padding: 6px 10px;
|
||||
border-radius: 999px; background: #342844; color: #d9c6f5; font-size: .8rem; }
|
||||
.buckets { margin-top: 34px; }
|
||||
.table-wrap { overflow: auto; margin-top: 18px; border: 1px solid #463a58;
|
||||
border-radius: 14px; background: #211c2b; }
|
||||
table { width: 100%; border-collapse: collapse; text-align: left; }
|
||||
th, td { padding: 15px 18px; border-bottom: 1px solid #3b314b; white-space: nowrap; }
|
||||
tr:last-child td { border-bottom: 0; }
|
||||
th { color: #aaa2bb; font-size: .75rem; text-transform: uppercase; letter-spacing: .1em; }
|
||||
td { font-size: .93rem; }
|
||||
.empty { padding: 28px; color: #aaa2bb; }
|
||||
a { color: #c6a8f3; text-decoration: none; }
|
||||
a:hover { text-decoration: underline; }
|
||||
.crumbs { display: flex; flex-wrap: wrap; align-items: center; gap: 8px;
|
||||
color: #aaa2bb; font-size: .9rem; margin: 30px 0 12px; }
|
||||
.crumbs span { overflow-wrap: anywhere; }
|
||||
.toolbar { display: flex; flex-wrap: wrap; align-items: end; justify-content: space-between;
|
||||
gap: 16px; margin: 22px 0; }
|
||||
.toolbar form { display: flex; flex-wrap: wrap; align-items: end; gap: 8px; margin: 0; }
|
||||
.toolbar label { margin: 0; color: #aaa2bb; font-size: .85rem; }
|
||||
.toolbar input { min-width: min(280px, 100%); }
|
||||
.toolbar button { margin: 0; }
|
||||
.toolbar .field { display: grid; gap: 6px; }
|
||||
.button-link { display: inline-flex; align-items: center; justify-content: center;
|
||||
border: 1px solid #514663; border-radius: 8px; padding: 12px 14px;
|
||||
color: #f4f0fa; background: #282232; }
|
||||
.button-link:hover { background: #342a42; text-decoration: none; }
|
||||
.name-cell { max-width: 420px; white-space: normal; overflow-wrap: anywhere; }
|
||||
.kind { color: #aaa2bb; font-size: .8rem; }
|
||||
.pagination { display: flex; gap: 12px; align-items: center; margin-top: 18px; }
|
||||
.detail-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
|
||||
gap: 14px; margin-top: 22px; }
|
||||
.detail-card { border: 1px solid #463a58; border-radius: 14px; background: #211c2b;
|
||||
padding: 22px; min-width: 0; }
|
||||
.detail-card h3 { margin: 0 0 16px; font-size: 1rem; }
|
||||
.fact { display: flex; align-items: baseline; justify-content: space-between;
|
||||
gap: 16px; padding: 9px 0; border-top: 1px solid #3b314b; }
|
||||
.fact span { color: #aaa2bb; }
|
||||
.fact strong { text-align: right; overflow-wrap: anywhere; }
|
||||
.insight { margin-top: 26px; }
|
||||
.console-nav { display: flex; flex-wrap: wrap; gap: 8px; padding: 12px 0;
|
||||
border-bottom: 1px solid #3e344e; }
|
||||
.console-nav a { padding: 8px 12px; border-radius: 8px; color: #cfc5df; }
|
||||
.console-nav a:hover { background: #282232; text-decoration: none; }
|
||||
.perf-grid { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr));
|
||||
gap: 14px; margin-top: 24px; }
|
||||
.perf-grid biscuit-cardview strong { font-variant-numeric: tabular-nums; }
|
||||
.perf-charts { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 16px; margin-top: 24px; }
|
||||
.perf-charts[hidden] { display: none; }
|
||||
.perf-status { color: #aaa2bb; margin-top: 12px; min-height: 24px; }
|
||||
.perf-note { color: #aaa2bb; font-size: .9rem; line-height: 1.5; }
|
||||
biscuit-chartview { --biscuit-chart-surface: #211c2b;
|
||||
--biscuit-chart-color: #f4f0fa;
|
||||
--biscuit-chart-muted: #aaa2bb;
|
||||
--biscuit-chart-border: #463a58;
|
||||
--biscuit-chart-accent: #b39add; }
|
||||
details { margin-top: 22px; padding: 18px 22px; border: 1px solid #463a58;
|
||||
border-radius: 14px; background: #211c2b; }
|
||||
summary { cursor: pointer; font-weight: 600; }
|
||||
pre { overflow-wrap: anywhere; white-space: pre-wrap; }
|
||||
@media (max-width: 820px) { .perf-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
|
||||
@media (max-width: 520px) {
|
||||
.login-card { padding: 26px; }
|
||||
.intro { align-items: start; }
|
||||
.grid > :last-child:nth-child(odd) { grid-column: 1 / -1; }
|
||||
.grid biscuit-cardview { --biscuit-cardview-padding: 16px; }
|
||||
.perf-grid biscuit-cardview { --biscuit-cardview-padding: 16px; }
|
||||
.perf-grid biscuit-cardview small { margin-bottom: 8px; }
|
||||
.perf-charts { grid-template-columns: minmax(0, 1fr); }
|
||||
}
|
||||
""";
|
||||
private static final long SESSION_MILLIS = Duration.ofMinutes(30).toMillis();
|
||||
private static final long ATTEMPT_WINDOW_MILLIS = Duration.ofMinutes(5).toMillis();
|
||||
private static final int MAX_SESSIONS = 128;
|
||||
private static final int MAX_CLIENTS = 1024;
|
||||
private final ObjectStorage store;
|
||||
private final byte[] passwordHash;
|
||||
private final URI publicOrigin;
|
||||
private final String biscuitScript;
|
||||
private final String performanceScript;
|
||||
private final byte[] logo;
|
||||
private volatile RequestMetrics metrics;
|
||||
private final SecureRandom random = new SecureRandom();
|
||||
private final LinkedHashMap<String, Session> sessions = new LinkedHashMap<>();
|
||||
private final LinkedHashMap<String, Long> loginTokens = new LinkedHashMap<>();
|
||||
private final LinkedHashMap<String, Attempt> attempts = new LinkedHashMap<>();
|
||||
|
||||
private record Attempt(long started, int failures) { }
|
||||
private record Session(long expires, String csrf) { }
|
||||
|
||||
private AdminConsole(ObjectStorage store, byte[] passwordHash, URI publicOrigin,
|
||||
String biscuitScript, String performanceScript, byte[] logo) {
|
||||
this.store = store;
|
||||
this.passwordHash = passwordHash;
|
||||
this.publicOrigin = publicOrigin;
|
||||
this.biscuitScript = biscuitScript;
|
||||
this.performanceScript = performanceScript;
|
||||
this.logo = logo;
|
||||
}
|
||||
|
||||
void setMetrics(RequestMetrics metrics) { this.metrics = metrics; }
|
||||
|
||||
static AdminConsole fromEnvironment(Map<String, String> env, ObjectStorage store) throws IOException {
|
||||
String enabled = env.getOrDefault("ADMIN_UI_ENABLED", "false");
|
||||
if (enabled.equals("false")) return null;
|
||||
if (!enabled.equals("true")) throw new IllegalArgumentException("Invalid ADMIN_UI_ENABLED");
|
||||
String file = env.get("ADMIN_UI_PASSWORD_FILE");
|
||||
if (file == null || file.isBlank())
|
||||
throw new IllegalArgumentException("ADMIN_UI_PASSWORD_FILE is required when the admin UI is enabled");
|
||||
byte[] password = Files.readAllBytes(Path.of(file));
|
||||
int length = password.length;
|
||||
if (length > 0 && password[length - 1] == '\n') length--;
|
||||
if (length > 0 && password[length - 1] == '\r') length--;
|
||||
if (length < 16 || length > 1024)
|
||||
throw new IllegalArgumentException("Admin password must contain 16 to 1024 bytes");
|
||||
for (int i = 0; i < length; i++) {
|
||||
if (password[i] == '\n' || password[i] == '\r' || password[i] == 0)
|
||||
throw new IllegalArgumentException("Admin password must be a single line");
|
||||
}
|
||||
byte[] trimmed = java.util.Arrays.copyOf(password, length);
|
||||
byte[] hash = SigV4.hash(trimmed);
|
||||
java.util.Arrays.fill(trimmed, (byte) 0);
|
||||
java.util.Arrays.fill(password, (byte) 0);
|
||||
String configured = env.get("ADMIN_UI_ORIGIN");
|
||||
URI origin = null;
|
||||
if (configured != null && !configured.isBlank()) {
|
||||
try { origin = URI.create(configured); }
|
||||
catch (IllegalArgumentException error) {
|
||||
throw new IllegalArgumentException("Invalid ADMIN_UI_ORIGIN", error);
|
||||
}
|
||||
if (!"https".equals(origin.getScheme()) || origin.getHost() == null ||
|
||||
origin.getUserInfo() != null || origin.getRawQuery() != null || origin.getRawFragment() != null ||
|
||||
!(origin.getRawPath().isEmpty() || origin.getRawPath().equals("/")))
|
||||
throw new IllegalArgumentException("ADMIN_UI_ORIGIN must be an HTTPS origin");
|
||||
origin = URI.create(origin.toString().replaceFirst("/$", ""));
|
||||
}
|
||||
return new AdminConsole(store, hash, origin,
|
||||
Files.readString(Path.of("admin-ui/biscuit.js")),
|
||||
Files.readString(Path.of("admin-ui/performance.js")),
|
||||
Files.readAllBytes(Path.of("admin-ui/objectstore-logo.png")));
|
||||
}
|
||||
|
||||
void handle(HttpExchange exchange) throws IOException {
|
||||
securityHeaders(exchange);
|
||||
String origin = requestOrigin(exchange);
|
||||
if (origin == null) {
|
||||
send(exchange, 403, page("<h1>Admin console unavailable</h1>" +
|
||||
"<p>Open the local console at <code>http://127.0.0.1:<port>" + PATH +
|
||||
"/login</code>, or use the configured HTTPS origin.</p>"), "text/html; charset=utf-8");
|
||||
return;
|
||||
}
|
||||
String path = exchange.getRequestURI().getRawPath();
|
||||
String method = exchange.getRequestMethod();
|
||||
if (path.equals(PATH) || path.equals(PATH + "/")) {
|
||||
if (!method.equals("GET")) {
|
||||
methodNotAllowed(exchange, "GET");
|
||||
return;
|
||||
}
|
||||
if (session(exchange) != null) redirect(exchange, PATH + "/overview");
|
||||
else redirect(exchange, PATH + "/login");
|
||||
return;
|
||||
}
|
||||
if (path.equals(PATH + "/login")) {
|
||||
if (method.equals("GET")) {
|
||||
send(exchange, 200, loginPage("", issueLoginToken()), "text/html; charset=utf-8");
|
||||
return;
|
||||
}
|
||||
if (method.equals("POST")) {
|
||||
login(exchange);
|
||||
return;
|
||||
}
|
||||
methodNotAllowed(exchange, "GET, POST");
|
||||
return;
|
||||
}
|
||||
if (path.equals(PATH + "/style.css")) {
|
||||
if (!method.equals("GET")) {
|
||||
methodNotAllowed(exchange, "GET");
|
||||
return;
|
||||
}
|
||||
send(exchange, 200, STYLE, "text/css; charset=utf-8");
|
||||
return;
|
||||
}
|
||||
if (path.equals(PATH + "/logo.png")) {
|
||||
if (!method.equals("GET")) {
|
||||
methodNotAllowed(exchange, "GET");
|
||||
return;
|
||||
}
|
||||
exchange.getResponseHeaders().set("Content-Type", "image/png");
|
||||
exchange.sendResponseHeaders(200, logo.length);
|
||||
exchange.getResponseBody().write(logo);
|
||||
return;
|
||||
}
|
||||
if (path.equals(PATH + "/biscuit.js")) {
|
||||
if (!method.equals("GET")) {
|
||||
methodNotAllowed(exchange, "GET");
|
||||
return;
|
||||
}
|
||||
if (session(exchange) == null) {
|
||||
redirect(exchange, PATH + "/login");
|
||||
return;
|
||||
}
|
||||
send(exchange, 200, biscuitScript, "text/javascript; charset=utf-8");
|
||||
return;
|
||||
}
|
||||
if (path.equals(PATH + "/performance.js")) {
|
||||
if (!method.equals("GET")) {
|
||||
methodNotAllowed(exchange, "GET");
|
||||
return;
|
||||
}
|
||||
if (session(exchange) == null) {
|
||||
redirect(exchange, PATH + "/login");
|
||||
return;
|
||||
}
|
||||
send(exchange, 200, performanceScript, "text/javascript; charset=utf-8");
|
||||
return;
|
||||
}
|
||||
if (path.equals(PATH + "/performance.json")) {
|
||||
if (!method.equals("GET")) {
|
||||
methodNotAllowed(exchange, "GET");
|
||||
return;
|
||||
}
|
||||
if (session(exchange) == null) {
|
||||
redirect(exchange, PATH + "/login");
|
||||
return;
|
||||
}
|
||||
if (metrics == null) {
|
||||
send(exchange, 503, "Metrics unavailable", "text/plain; charset=utf-8");
|
||||
return;
|
||||
}
|
||||
send(exchange, 200, AdminPerformance.snapshot(metrics), "application/json; charset=utf-8");
|
||||
return;
|
||||
}
|
||||
if (path.equals(PATH + "/logout")) {
|
||||
if (!method.equals("POST")) {
|
||||
methodNotAllowed(exchange, "POST");
|
||||
return;
|
||||
}
|
||||
Session session = session(exchange);
|
||||
Map<String, String> form = readForm(exchange);
|
||||
if (session == null || !MessageDigest.isEqual(session.csrf().getBytes(StandardCharsets.US_ASCII),
|
||||
form.getOrDefault("csrf", "").getBytes(StandardCharsets.US_ASCII))) {
|
||||
send(exchange, 403, "Invalid sign-out request", "text/plain; charset=utf-8");
|
||||
return;
|
||||
}
|
||||
String token = sessionCookie(exchange);
|
||||
synchronized (this) {
|
||||
sessions.remove(token);
|
||||
}
|
||||
exchange.getResponseHeaders().add("Set-Cookie", cookie("", 0));
|
||||
redirect(exchange, PATH + "/login");
|
||||
return;
|
||||
}
|
||||
if (path.equals(PATH + "/overview")) {
|
||||
if (!method.equals("GET")) {
|
||||
methodNotAllowed(exchange, "GET");
|
||||
return;
|
||||
}
|
||||
Session session = session(exchange);
|
||||
if (session == null) {
|
||||
redirect(exchange, PATH + "/login");
|
||||
return;
|
||||
}
|
||||
ObjectStorage.Limits limits = store.limits();
|
||||
String mode = store instanceof ClusterStore ? "Cluster" : "Disk";
|
||||
String status = store.ready() ? "Ready" : "Unavailable";
|
||||
List<ObjectStorage.Bucket> buckets;
|
||||
boolean bucketListAvailable;
|
||||
try {
|
||||
buckets = store.buckets();
|
||||
bucketListAvailable = true;
|
||||
} catch (IOException unavailable) {
|
||||
buckets = List.of();
|
||||
bucketListAvailable = false;
|
||||
}
|
||||
send(exchange, 200, overviewPage(mode, status, limits.maxObjectBytes(), limits.maxTotalBytes(),
|
||||
buckets, bucketListAvailable, session.csrf()),
|
||||
"text/html; charset=utf-8");
|
||||
return;
|
||||
}
|
||||
if (path.equals(PATH + "/performance")) {
|
||||
if (!method.equals("GET")) {
|
||||
methodNotAllowed(exchange, "GET");
|
||||
return;
|
||||
}
|
||||
Session session = session(exchange);
|
||||
if (session == null) {
|
||||
redirect(exchange, PATH + "/login");
|
||||
return;
|
||||
}
|
||||
send(exchange, 200, performancePage(session.csrf()), "text/html; charset=utf-8");
|
||||
return;
|
||||
}
|
||||
if (path.equals(PATH + "/buckets") || path.equals(PATH + "/bucket") ||
|
||||
path.equals(PATH + "/object")) {
|
||||
if (!method.equals("GET")) {
|
||||
methodNotAllowed(exchange, "GET");
|
||||
return;
|
||||
}
|
||||
Session session = session(exchange);
|
||||
if (session == null) {
|
||||
redirect(exchange, PATH + "/login");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
String body = path.equals(PATH + "/buckets") ?
|
||||
AdminBrowser.index(store, exchange.getRequestURI().getRawQuery(), session.csrf()) :
|
||||
path.equals(PATH + "/bucket") ?
|
||||
AdminBrowser.bucket(store, exchange.getRequestURI().getRawQuery(), session.csrf()) :
|
||||
AdminBrowser.object(store, exchange.getRequestURI().getRawQuery(), session.csrf());
|
||||
send(exchange, 200, page(body, true), "text/html; charset=utf-8");
|
||||
} catch (StoreException error) {
|
||||
send(exchange, error.status, page(consoleHeader(session.csrf()) +
|
||||
"<div class=crumbs><a href='" + PATH + "/buckets'>Buckets</a></div>" +
|
||||
"<h2>Could not open this view</h2><p class=muted>" + escape(error.getMessage()) + "</p>"),
|
||||
"text/html; charset=utf-8");
|
||||
} catch (IOException unavailable) {
|
||||
send(exchange, 503, page(consoleHeader(session.csrf()) +
|
||||
"<h2>Storage unavailable</h2><p class=muted>Try again when the service is ready.</p>"),
|
||||
"text/html; charset=utf-8");
|
||||
}
|
||||
return;
|
||||
}
|
||||
send(exchange, 404, "Not found", "text/plain; charset=utf-8");
|
||||
}
|
||||
|
||||
private void login(HttpExchange exchange) throws IOException {
|
||||
Map<String, String> form = readForm(exchange);
|
||||
if (!consumeLoginToken(form.get("csrf"))) {
|
||||
send(exchange, 403, loginPage("Sign-in expired. Reload the page and try again.", issueLoginToken()),
|
||||
"text/html; charset=utf-8");
|
||||
return;
|
||||
}
|
||||
String password = form.get("password");
|
||||
String client = exchange.getRemoteAddress().getAddress().getHostAddress();
|
||||
if (throttled(client)) {
|
||||
exchange.getResponseHeaders().set("Retry-After", "300");
|
||||
send(exchange, 429, loginPage("Too many attempts. Try again in five minutes.", issueLoginToken()),
|
||||
"text/html; charset=utf-8");
|
||||
return;
|
||||
}
|
||||
byte[] candidate = SigV4.hash((password == null ? "" : password).getBytes(StandardCharsets.UTF_8));
|
||||
if (!MessageDigest.isEqual(candidate, passwordHash)) {
|
||||
failed(client);
|
||||
send(exchange, 401, loginPage("Invalid password", issueLoginToken()), "text/html; charset=utf-8");
|
||||
return;
|
||||
}
|
||||
String token = randomToken();
|
||||
synchronized (this) {
|
||||
attempts.remove(client);
|
||||
long now = System.currentTimeMillis();
|
||||
sessions.entrySet().removeIf(entry -> entry.getValue().expires() <= now);
|
||||
if (sessions.size() >= MAX_SESSIONS) sessions.remove(sessions.keySet().iterator().next());
|
||||
sessions.put(token, new Session(now + SESSION_MILLIS, randomToken()));
|
||||
}
|
||||
exchange.getResponseHeaders().add("Set-Cookie", cookie(token, 1800));
|
||||
redirect(exchange, PATH + "/overview");
|
||||
}
|
||||
|
||||
private static Map<String, String> readForm(HttpExchange exchange) throws IOException {
|
||||
String contentType = exchange.getRequestHeaders().getFirst("Content-Type");
|
||||
if (contentType == null || !contentType.split(";", 2)[0].trim()
|
||||
.equalsIgnoreCase("application/x-www-form-urlencoded")) {
|
||||
throw new StoreException(415, "InvalidRequest", "Expected a form submission");
|
||||
}
|
||||
byte[] body = exchange.getRequestBody().readNBytes(4097);
|
||||
if (body.length > 4096) {
|
||||
throw new StoreException(413, "InvalidRequest", "Form is too large");
|
||||
}
|
||||
Map<String, String> values = new java.util.HashMap<>();
|
||||
try {
|
||||
for (String field : new String(body, StandardCharsets.UTF_8).split("&", -1)) {
|
||||
int split = field.indexOf('=');
|
||||
if (split < 0) continue;
|
||||
String key = URLDecoder.decode(field.substring(0, split), StandardCharsets.UTF_8);
|
||||
String value = URLDecoder.decode(field.substring(split + 1), StandardCharsets.UTF_8);
|
||||
if (values.putIfAbsent(key, value) != null)
|
||||
throw new IllegalArgumentException("Duplicate form field");
|
||||
}
|
||||
} catch (IllegalArgumentException error) {
|
||||
throw new StoreException(400, "InvalidRequest", "Invalid form submission");
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
private synchronized String issueLoginToken() {
|
||||
long now = System.currentTimeMillis();
|
||||
loginTokens.entrySet().removeIf(entry -> entry.getValue() <= now);
|
||||
if (loginTokens.size() >= MAX_SESSIONS) loginTokens.remove(loginTokens.keySet().iterator().next());
|
||||
String token = randomToken();
|
||||
loginTokens.put(token, now + Duration.ofMinutes(10).toMillis());
|
||||
return token;
|
||||
}
|
||||
|
||||
private synchronized boolean consumeLoginToken(String token) {
|
||||
if (token == null || !token.matches("[A-Za-z0-9_-]{43}")) return false;
|
||||
Long until = loginTokens.remove(token);
|
||||
return until != null && until > System.currentTimeMillis();
|
||||
}
|
||||
|
||||
private String randomToken() {
|
||||
byte[] value = new byte[32];
|
||||
random.nextBytes(value);
|
||||
return Base64.getUrlEncoder().withoutPadding().encodeToString(value);
|
||||
}
|
||||
|
||||
private synchronized boolean throttled(String client) {
|
||||
Attempt attempt = attempts.get(client);
|
||||
return attempt != null && System.currentTimeMillis() - attempt.started < ATTEMPT_WINDOW_MILLIS &&
|
||||
attempt.failures >= 5;
|
||||
}
|
||||
|
||||
private synchronized void failed(String client) {
|
||||
long now = System.currentTimeMillis();
|
||||
Attempt attempt = attempts.get(client);
|
||||
if (attempt == null || now - attempt.started >= ATTEMPT_WINDOW_MILLIS)
|
||||
attempts.put(client, new Attempt(now, 1));
|
||||
else attempts.put(client, new Attempt(attempt.started, attempt.failures + 1));
|
||||
if (attempts.size() > MAX_CLIENTS) {
|
||||
Iterator<String> oldest = attempts.keySet().iterator();
|
||||
oldest.next();
|
||||
oldest.remove();
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized Session session(HttpExchange exchange) {
|
||||
String token = sessionCookie(exchange);
|
||||
Session session = sessions.get(token);
|
||||
if (session == null) return null;
|
||||
if (session.expires() > System.currentTimeMillis()) return session;
|
||||
sessions.remove(token);
|
||||
return null;
|
||||
}
|
||||
|
||||
private String sessionCookie(HttpExchange exchange) {
|
||||
String header = exchange.getRequestHeaders().getFirst("Cookie");
|
||||
if (header == null || header.length() > 8192) return "";
|
||||
String name = publicOrigin == null ? "objectstore_admin=" : "__Host-objectstore_admin=";
|
||||
for (String field : header.split(";")) {
|
||||
String value = field.trim();
|
||||
if (value.startsWith(name) && value.substring(name.length()).matches("[A-Za-z0-9_-]{43}"))
|
||||
return value.substring(name.length());
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
private String cookie(String token, int seconds) {
|
||||
String name = publicOrigin == null ? "objectstore_admin" : "__Host-objectstore_admin";
|
||||
String path = publicOrigin == null ? PATH : "/";
|
||||
return name + "=" + token + "; Path=" + path + "; HttpOnly; SameSite=Strict; Max-Age=" + seconds +
|
||||
(publicOrigin == null ? "" : "; Secure");
|
||||
}
|
||||
|
||||
private String requestOrigin(HttpExchange exchange) {
|
||||
String host = exchange.getRequestHeaders().getFirst("Host");
|
||||
if (host == null || exchange.getRequestHeaders().get("Host").size() != 1) return null;
|
||||
if (publicOrigin != null)
|
||||
return host.equalsIgnoreCase(publicOrigin.getRawAuthority()) ? publicOrigin.toString() : null;
|
||||
if (!host.matches("(?i)(localhost|127\\.0\\.0\\.1|\\[::1\\])(?::[0-9]{1,5})?")) return null;
|
||||
return "http://" + host.toLowerCase(java.util.Locale.ROOT);
|
||||
}
|
||||
|
||||
private static void securityHeaders(HttpExchange exchange) {
|
||||
exchange.getResponseHeaders().set("Cache-Control", "no-store");
|
||||
exchange.getResponseHeaders().set("Content-Security-Policy",
|
||||
"default-src 'none'; style-src 'self'; style-src-elem 'self' 'unsafe-inline'; " +
|
||||
"style-src-attr 'none'; script-src 'self'; img-src 'self'; connect-src 'self'; form-action 'self'; " +
|
||||
"frame-ancestors 'none'; base-uri 'none'");
|
||||
exchange.getResponseHeaders().set("Referrer-Policy", "no-referrer");
|
||||
exchange.getResponseHeaders().set("X-Frame-Options", "DENY");
|
||||
exchange.getResponseHeaders().set("X-Content-Type-Options", "nosniff");
|
||||
}
|
||||
|
||||
private static void methodNotAllowed(HttpExchange exchange, String methods) throws IOException {
|
||||
exchange.getResponseHeaders().set("Allow", methods);
|
||||
send(exchange, 405, "Method not allowed", "text/plain; charset=utf-8");
|
||||
}
|
||||
|
||||
private static void redirect(HttpExchange exchange, String path) throws IOException {
|
||||
exchange.getResponseHeaders().set("Location", path);
|
||||
exchange.sendResponseHeaders(303, -1);
|
||||
}
|
||||
|
||||
private static void send(HttpExchange exchange, int status, String body, String contentType) throws IOException {
|
||||
byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
|
||||
exchange.getResponseHeaders().set("Content-Type", contentType);
|
||||
exchange.sendResponseHeaders(status, bytes.length);
|
||||
exchange.getResponseBody().write(bytes);
|
||||
}
|
||||
|
||||
private static String loginPage(String error, String csrf) {
|
||||
return page("<div class=login><div class=login-card><div class=login-brand>" +
|
||||
logoMark() + "<strong>ObjectStore</strong></div><h1>Admin console</h1>" +
|
||||
"<p class=muted>Sign in to view this service.</p>" +
|
||||
(error.isEmpty() ? "" : "<p role=alert class=error>" + error + "</p>") +
|
||||
"<form method=post action='" + PATH + "/login'>" +
|
||||
"<input type=hidden name=csrf value='" + csrf + "'>" +
|
||||
"<label for=password>Admin password</label><input id=password name=password type=password " +
|
||||
"autocomplete=current-password required autofocus><button type=submit>Sign in</button>" +
|
||||
"</form></div></div>");
|
||||
}
|
||||
|
||||
private static String overviewPage(String mode, String status, long maxObject, long maxTotal,
|
||||
List<ObjectStorage.Bucket> buckets, boolean bucketListAvailable,
|
||||
String csrf) {
|
||||
StringBuilder content = new StringBuilder(consoleHeader(csrf) +
|
||||
"<div class=intro><div><h2>Overview</h2><p>Service status and configured limits</p></div>" +
|
||||
"<biscuit-badgeview theme=dark variant='" + (status.equals("Ready") ? "success" : "danger") + "'>" +
|
||||
status + "</biscuit-badgeview></div>" +
|
||||
"<div class=grid><biscuit-cardview><small>Storage mode</small><strong>" + mode +
|
||||
"</strong></biscuit-cardview><biscuit-cardview><small>Buckets</small><strong>" +
|
||||
(bucketListAvailable ? buckets.size() : "Unavailable") +
|
||||
"</strong></biscuit-cardview><biscuit-cardview><small>Maximum object</small><strong>" +
|
||||
formatBytes(maxObject) + "</strong></biscuit-cardview><biscuit-cardview>" +
|
||||
"<small>Total storage limit</small><strong>" + formatBytes(maxTotal) +
|
||||
"</strong></biscuit-cardview></div><section class=buckets><h2>Buckets</h2>" +
|
||||
"<p>Read-only view of the first 25 buckets. <a href='" + PATH +
|
||||
"/buckets'>Browse all buckets</a></p>");
|
||||
if (!bucketListAvailable || buckets.isEmpty()) {
|
||||
content.append("<div class='table-wrap empty'>")
|
||||
.append(bucketListAvailable ? "No buckets yet." : "Bucket list unavailable.")
|
||||
.append("</div>");
|
||||
} else {
|
||||
content.append("<div class=table-wrap><table><thead><tr><th>Bucket</th><th>Versioning</th>" +
|
||||
"<th>Ownership</th></tr></thead><tbody>");
|
||||
for (ObjectStorage.Bucket bucket : buckets.stream().limit(25).toList()) {
|
||||
String versioning = bucket.versioning() == ObjectStorage.VersioningState.NEVER ?
|
||||
"Off" : bucket.versioning().name().toLowerCase(java.util.Locale.ROOT);
|
||||
String ownership = switch (bucket.ownership()) {
|
||||
case BUCKET_OWNER_ENFORCED -> "Owner enforced";
|
||||
case BUCKET_OWNER_PREFERRED -> "Owner preferred";
|
||||
case OBJECT_WRITER -> "Object writer";
|
||||
};
|
||||
content.append("<tr><td><a href='").append(AdminBrowser.bucketUrl(bucket.name(), "", null))
|
||||
.append("'>").append(escape(bucket.name())).append("</a></td><td>")
|
||||
.append(versioning).append("</td><td>").append(ownership).append("</td></tr>");
|
||||
}
|
||||
content.append("</tbody></table></div>");
|
||||
}
|
||||
content.append("</section>");
|
||||
return page(content.toString(), true);
|
||||
}
|
||||
|
||||
private static String performancePage(String csrf) {
|
||||
StringBuilder content = new StringBuilder(consoleHeader(csrf));
|
||||
content.append("<div class=intro><div><h2>Performance</h2>")
|
||||
.append("<p>Live S3 traffic and process health</p></div>")
|
||||
.append("<biscuit-badgeview theme=dark variant=accent>Live</biscuit-badgeview></div>")
|
||||
.append("<p class=perf-note>Sampled every 3 seconds while this tab is visible. ")
|
||||
.append("Traffic excludes admin pages and health checks. Charts keep only the last 60 samples ")
|
||||
.append("in this browser tab.</p><p id=perf-state class=perf-status role=status>Collecting samples…</p>")
|
||||
.append("<div class=perf-grid>")
|
||||
.append(perfCard("Requests / second", "perf-rps"))
|
||||
.append(perfCard("Average latency", "perf-latency"))
|
||||
.append(perfCard("Inbound / second", "perf-inbound"))
|
||||
.append(perfCard("Outbound / second", "perf-outbound"))
|
||||
.append(perfCard("Average CPU · recent", "perf-cpu"))
|
||||
.append(perfCard("Process RAM (RSS)", "perf-ram"))
|
||||
.append(perfCard("GC collections", "perf-gc"))
|
||||
.append(perfCard("In flight", "perf-inflight"))
|
||||
.append("</div><div class=perf-charts hidden>")
|
||||
.append("<biscuit-chartview id=perf-requests-chart theme=dark type=line ")
|
||||
.append("name='Requests / second' height=250 max-rows=60></biscuit-chartview>")
|
||||
.append("<biscuit-chartview id=perf-transfer-chart theme=dark type=line ")
|
||||
.append("name='Transfer / second' height=250 max-rows=60></biscuit-chartview>")
|
||||
.append("<biscuit-chartview id=perf-cpu-chart theme=dark type=line ")
|
||||
.append("name='Process CPU' height=250 max-rows=60></biscuit-chartview>")
|
||||
.append("<biscuit-chartview id=perf-memory-chart theme=dark type=line ")
|
||||
.append("name='Process memory' height=250 max-rows=60></biscuit-chartview>")
|
||||
.append("</div><p class=perf-note>Inbound and outbound measure HTTP body bytes, including ")
|
||||
.append("S3 metadata responses. CPU is the process share of available cores. ")
|
||||
.append("GC counts reset when the service restarts.</p>");
|
||||
return page(content.toString(), true, true);
|
||||
}
|
||||
|
||||
private static String perfCard(String label, String id) {
|
||||
return "<biscuit-cardview><small>" + label + "</small><strong id='" + id +
|
||||
"'>—</strong></biscuit-cardview>";
|
||||
}
|
||||
|
||||
private static String page(String content) {
|
||||
return page(content, false);
|
||||
}
|
||||
|
||||
static String page(String content, boolean widgets) {
|
||||
return page(content, widgets, false);
|
||||
}
|
||||
|
||||
private static String page(String content, boolean widgets, boolean performance) {
|
||||
return "<!doctype html><html lang=en><head><meta charset=utf-8>" +
|
||||
"<meta name=viewport content='width=device-width,initial-scale=1'><title>ObjectStore admin</title>" +
|
||||
"<link rel=stylesheet href='" + PATH + "/style.css'>" +
|
||||
(widgets ? "<script defer src='" + PATH + "/biscuit.js'></script>" : "") +
|
||||
(performance ? "<script defer src='" + PATH + "/performance.js'></script>" : "") +
|
||||
"</head><body><main>" +
|
||||
content + "</main></body></html>";
|
||||
}
|
||||
|
||||
static String consoleHeader(String csrf) {
|
||||
return "<header><div class=header-title>" + logoMark() +
|
||||
"<div><h1>ObjectStore</h1><small>Admin console · v" + Version.VALUE +
|
||||
"</small></div></div><form method=post action='" + PATH +
|
||||
"/logout'><input type=hidden name=csrf value='" + csrf +
|
||||
"'><button type=submit>Sign out</button></form></header>" +
|
||||
"<nav class=console-nav aria-label='Admin sections'><a href='" + PATH +
|
||||
"/overview'>Overview</a><a href='" + PATH + "/buckets'>Buckets</a>" +
|
||||
"<a href='" + PATH + "/performance'>Performance</a></nav>";
|
||||
}
|
||||
|
||||
private static String logoMark() {
|
||||
return "<span class=mark aria-hidden=true><img src='" + PATH +
|
||||
"/logo.png' alt='' width=56 height=56></span>";
|
||||
}
|
||||
|
||||
static String escape(String value) {
|
||||
return value.replace("&", "&").replace("<", "<").replace(">", ">")
|
||||
.replace("\"", """).replace("'", "'");
|
||||
}
|
||||
|
||||
static String formatBytes(long bytes) {
|
||||
if (bytes == Long.MAX_VALUE) return "Unlimited";
|
||||
if (bytes < 1024) return bytes + " B";
|
||||
String[] units = { "KiB", "MiB", "GiB", "TiB", "PiB", "EiB" };
|
||||
double value = bytes;
|
||||
int unit = -1;
|
||||
do {
|
||||
value /= 1024;
|
||||
unit++;
|
||||
} while (value >= 1024 && unit < units.length - 1);
|
||||
return String.format(java.util.Locale.ROOT, "%.1f %s", value, units[unit]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.lang.management.GarbageCollectorMXBean;
|
||||
import java.lang.management.ManagementFactory;
|
||||
import java.lang.management.MemoryMXBean;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
|
||||
final class AdminPerformance {
|
||||
private static final MemoryMXBean MEMORY = ManagementFactory.getMemoryMXBean();
|
||||
private static final List<GarbageCollectorMXBean> COLLECTORS =
|
||||
ManagementFactory.getGarbageCollectorMXBeans();
|
||||
private static final ProcessHandle PROCESS = ProcessHandle.current();
|
||||
private static final Path STATUS = Path.of("/proc/self/status");
|
||||
|
||||
private AdminPerformance() { }
|
||||
|
||||
static String snapshot(RequestMetrics metrics) {
|
||||
RequestMetrics.DataSnapshot traffic = metrics.dataSnapshot();
|
||||
long gcCount = 0;
|
||||
long gcMillis = 0;
|
||||
for (GarbageCollectorMXBean collector : COLLECTORS) {
|
||||
gcCount += Math.max(0, collector.getCollectionCount());
|
||||
gcMillis += Math.max(0, collector.getCollectionTime());
|
||||
}
|
||||
long cpuNanos = PROCESS.info().totalCpuDuration().map(Duration::toNanos).orElse(-1L);
|
||||
return "{\"requests\":" + traffic.requests() +
|
||||
",\"failures4xx\":" + traffic.failures4xx() +
|
||||
",\"failures5xx\":" + traffic.failures5xx() +
|
||||
",\"durationNanos\":" + traffic.durationNanos() +
|
||||
",\"inboundBytes\":" + traffic.inboundBytes() +
|
||||
",\"outboundBytes\":" + traffic.outboundBytes() +
|
||||
",\"inFlight\":" + traffic.inFlight() +
|
||||
",\"cpuNanos\":" + cpuNanos +
|
||||
",\"processors\":" + Runtime.getRuntime().availableProcessors() +
|
||||
",\"rssBytes\":" + rssBytes() +
|
||||
",\"heapBytes\":" + MEMORY.getHeapMemoryUsage().getUsed() +
|
||||
",\"nonHeapBytes\":" + MEMORY.getNonHeapMemoryUsage().getUsed() +
|
||||
",\"gcCount\":" + gcCount +
|
||||
",\"gcMillis\":" + gcMillis + "}";
|
||||
}
|
||||
|
||||
private static long rssBytes() {
|
||||
if (!Files.isReadable(STATUS)) return -1;
|
||||
try (var lines = Files.lines(STATUS)) {
|
||||
String line = lines.filter(value -> value.startsWith("VmRSS:"))
|
||||
.findFirst().orElse("");
|
||||
if (line.isEmpty()) return -1;
|
||||
String value = line.substring("VmRSS:".length()).trim();
|
||||
return Math.multiplyExact(Long.parseLong(value.split("\\s+", 2)[0]), 1024);
|
||||
} catch (IOException | NumberFormatException | ArithmeticException unavailable) {
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -127,7 +127,7 @@ final class AwsChunkedInputStream extends FilterInputStream {
|
||||
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}"))
|
||||
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" +
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
@@ -78,12 +78,16 @@ final class ClusterStore implements ObjectStorage, MultipartStorage {
|
||||
|
||||
@Override public Bucket bucket(String name) throws IOException {
|
||||
try (Connection connection = connect(); PreparedStatement query = connection.prepareStatement(
|
||||
"SELECT created_at, versioning_state, acl FROM cluster_buckets WHERE name=?")) {
|
||||
"SELECT created_at, versioning_state, acl, object_ownership, block_public_acls, " +
|
||||
"ignore_public_acls, block_public_policy, restrict_public_buckets, bucket_policy " +
|
||||
"FROM cluster_buckets WHERE name=?")) {
|
||||
query.setString(1, name);
|
||||
try (ResultSet result = query.executeQuery()) {
|
||||
if (!result.next()) throw new StoreException(404, "NoSuchBucket", "Bucket not found");
|
||||
return new Bucket(name, result.getLong(1), VersioningState.valueOf(result.getString(2)),
|
||||
ObjectAttributes.decode(result.getBytes(3)));
|
||||
ObjectAttributes.decode(result.getBytes(3)), ObjectOwnership.valueOf(result.getString(4)),
|
||||
new PublicAccessBlock(result.getBoolean(5), result.getBoolean(6),
|
||||
result.getBoolean(7), result.getBoolean(8)), result.getString(9));
|
||||
}
|
||||
} catch (SQLException error) { throw databaseError(error); }
|
||||
}
|
||||
@@ -91,9 +95,14 @@ final class ClusterStore implements ObjectStorage, MultipartStorage {
|
||||
@Override public List<Bucket> buckets() throws IOException {
|
||||
List<Bucket> result = new ArrayList<>();
|
||||
try (Connection connection = connect(); var query = connection.createStatement();
|
||||
ResultSet rows = query.executeQuery("SELECT name, created_at, versioning_state, acl FROM cluster_buckets ORDER BY name")) {
|
||||
ResultSet rows = query.executeQuery("SELECT name, created_at, versioning_state, acl, " +
|
||||
"object_ownership, block_public_acls, ignore_public_acls, block_public_policy, " +
|
||||
"restrict_public_buckets, bucket_policy FROM cluster_buckets ORDER BY name")) {
|
||||
while (rows.next()) result.add(new Bucket(rows.getString(1), rows.getLong(2),
|
||||
VersioningState.valueOf(rows.getString(3)), ObjectAttributes.decode(rows.getBytes(4))));
|
||||
VersioningState.valueOf(rows.getString(3)), ObjectAttributes.decode(rows.getBytes(4)),
|
||||
ObjectOwnership.valueOf(rows.getString(5)),
|
||||
new PublicAccessBlock(rows.getBoolean(6), rows.getBoolean(7),
|
||||
rows.getBoolean(8), rows.getBoolean(9)), rows.getString(10)));
|
||||
return result;
|
||||
} catch (SQLException error) { throw databaseError(error); }
|
||||
}
|
||||
@@ -133,6 +142,38 @@ final class ClusterStore implements ObjectStorage, MultipartStorage {
|
||||
} catch (SQLException error) { throw databaseError(error); }
|
||||
}
|
||||
|
||||
@Override public void setBucketOwnership(String bucket, ObjectOwnership ownership) throws IOException {
|
||||
updateBucketAccess(bucket, "object_ownership", ownership.name());
|
||||
}
|
||||
|
||||
@Override public void setPublicAccessBlock(String bucket, PublicAccessBlock block) throws IOException {
|
||||
try (Connection connection = connect(); PreparedStatement update = connection.prepareStatement(
|
||||
"UPDATE cluster_buckets SET block_public_acls=?, ignore_public_acls=?, " +
|
||||
"block_public_policy=?, restrict_public_buckets=? WHERE name=?")) {
|
||||
update.setBoolean(1, block.blockPublicAcls());
|
||||
update.setBoolean(2, block.ignorePublicAcls());
|
||||
update.setBoolean(3, block.blockPublicPolicy());
|
||||
update.setBoolean(4, block.restrictPublicBuckets());
|
||||
update.setString(5, bucket);
|
||||
if (update.executeUpdate() == 0)
|
||||
throw new StoreException(404, "NoSuchBucket", "Bucket not found");
|
||||
} catch (SQLException error) { throw databaseError(error); }
|
||||
}
|
||||
|
||||
@Override public void setBucketPolicy(String bucket, String policy) throws IOException {
|
||||
updateBucketAccess(bucket, "bucket_policy", policy);
|
||||
}
|
||||
|
||||
private void updateBucketAccess(String bucket, String column, String value) throws IOException {
|
||||
try (Connection connection = connect(); PreparedStatement update = connection.prepareStatement(
|
||||
"UPDATE cluster_buckets SET " + column + "=? WHERE name=?")) {
|
||||
update.setString(1, value);
|
||||
update.setString(2, bucket);
|
||||
if (update.executeUpdate() == 0)
|
||||
throw new StoreException(404, "NoSuchBucket", "Bucket not found");
|
||||
} catch (SQLException error) { throw databaseError(error); }
|
||||
}
|
||||
|
||||
private static VersioningState versioningState(Connection connection, String bucket) throws SQLException {
|
||||
try (PreparedStatement query = connection.prepareStatement(
|
||||
"SELECT versioning_state FROM cluster_buckets WHERE name=? FOR UPDATE")) {
|
||||
@@ -171,7 +212,9 @@ final class ClusterStore implements ObjectStorage, MultipartStorage {
|
||||
throw new StoreException(400, "TooManyBuckets", "Bucket limit reached");
|
||||
}
|
||||
try (PreparedStatement insert = connection.prepareStatement(
|
||||
"INSERT INTO cluster_buckets (name, created_at) VALUES (?, ?) ON CONFLICT DO NOTHING")) {
|
||||
"INSERT INTO cluster_buckets (name, created_at, object_ownership, block_public_acls, " +
|
||||
"ignore_public_acls, block_public_policy, restrict_public_buckets) " +
|
||||
"VALUES (?, ?, 'BUCKET_OWNER_ENFORCED', true, true, true, true) ON CONFLICT DO NOTHING")) {
|
||||
insert.setString(1, name);
|
||||
insert.setLong(2, Instant.now().toEpochMilli());
|
||||
if (insert.executeUpdate() == 0)
|
||||
@@ -599,17 +642,20 @@ final class ClusterStore implements ObjectStorage, MultipartStorage {
|
||||
throw new StoreException(413, "EntityTooLarge", "Object exceeds the configured size limit");
|
||||
total += part.length();
|
||||
MessageDigest partHash = digest("MD5");
|
||||
java.util.zip.CRC32 partCrc32 = new java.util.zip.CRC32();
|
||||
for (Segment segment : part.segments()) {
|
||||
byte[] bytes = readableSegment(segment);
|
||||
if (bytes == null) throw new StoreException(503, "SlowDown", "A part has no verified replica");
|
||||
fullHash.update(bytes);
|
||||
crc64.update(bytes, 0, bytes.length);
|
||||
partHash.update(bytes);
|
||||
partCrc32.update(bytes, 0, bytes.length);
|
||||
selected.add(segment);
|
||||
}
|
||||
byte[] md5 = partHash.digest();
|
||||
if (!part.etag().equals(HexFormat.of().formatHex(md5)))
|
||||
throw new StoreException(503, "SlowDown", "A part failed integrity verification");
|
||||
requested.verifyCrc32(partCrc32.getValue());
|
||||
etagHash.update(md5);
|
||||
}
|
||||
long replaced = state == VersioningState.ENABLED ? 0 : nullVersionLength(connection, bucket, key);
|
||||
|
||||
@@ -32,6 +32,7 @@ final class DiskStore implements ObjectStorage {
|
||||
private static final int BUCKET_MAGIC = 0x4c534243;
|
||||
private static final int BUCKET_MAGIC_V2 = 0x4c534244;
|
||||
private static final int BUCKET_MAGIC_V3 = 0x4c534245;
|
||||
private static final int BUCKET_MAGIC_V4 = 0x4c534246;
|
||||
private static final int VERSION_MAGIC = 0x4c53564d;
|
||||
private final Path root, objects, temporary, catalog, versions;
|
||||
private final FileChannel lockChannel;
|
||||
@@ -41,7 +42,9 @@ final class DiskStore implements ObjectStorage {
|
||||
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) {}
|
||||
@@ -92,7 +95,8 @@ final class DiskStore implements ObjectStorage {
|
||||
if (Files.exists(catalog)) {
|
||||
try (DataInputStream input = new DataInputStream(Files.newInputStream(catalog))) {
|
||||
int magic = input.readInt();
|
||||
if (magic != BUCKET_MAGIC && magic != BUCKET_MAGIC_V2 && magic != BUCKET_MAGIC_V3)
|
||||
if (magic != BUCKET_MAGIC && magic != BUCKET_MAGIC_V2 &&
|
||||
magic != BUCKET_MAGIC_V3 && magic != BUCKET_MAGIC_V4)
|
||||
throw new IOException("Invalid bucket catalog");
|
||||
int count = input.readInt();
|
||||
if (count < 0 || count > 1000) throw new IOException("Invalid bucket catalog");
|
||||
@@ -100,20 +104,35 @@ final class DiskStore implements ObjectStorage {
|
||||
String name = input.readUTF();
|
||||
long created = input.readLong();
|
||||
VersioningState state = VersioningState.NEVER;
|
||||
if (magic == BUCKET_MAGIC_V2 || magic == BUCKET_MAGIC_V3) {
|
||||
if (magic != BUCKET_MAGIC) {
|
||||
int ordinal = input.readUnsignedByte();
|
||||
if (ordinal >= VersioningState.values().length)
|
||||
throw new IOException("Invalid bucket versioning state");
|
||||
state = VersioningState.values()[ordinal];
|
||||
}
|
||||
Map<String, String> acl = Map.of();
|
||||
if (magic == BUCKET_MAGIC_V3) {
|
||||
if (magic == BUCKET_MAGIC_V3 || magic == BUCKET_MAGIC_V4) {
|
||||
int size = input.readUnsignedShort();
|
||||
if (size > ACL_AREA) throw new IOException("Invalid bucket ACL");
|
||||
acl = ObjectAttributes.decode(input.readNBytes(size));
|
||||
}
|
||||
ObjectOwnership ownership = ObjectOwnership.OBJECT_WRITER;
|
||||
PublicAccessBlock block = PublicAccessBlock.open();
|
||||
String policy = null;
|
||||
if (magic == BUCKET_MAGIC_V4) {
|
||||
int ordinal = input.readUnsignedByte();
|
||||
int flags = input.readUnsignedByte();
|
||||
if (ordinal >= ObjectOwnership.values().length || (flags & ~15) != 0)
|
||||
throw new IOException("Invalid bucket access settings");
|
||||
ownership = ObjectOwnership.values()[ordinal];
|
||||
block = new PublicAccessBlock((flags & 1) != 0, (flags & 2) != 0,
|
||||
(flags & 4) != 0, (flags & 8) != 0);
|
||||
policy = input.readUTF();
|
||||
if (policy.isEmpty()) policy = null;
|
||||
}
|
||||
if (!validBucket(name) || created < 0 ||
|
||||
buckets.put(name, new Bucket(name, created, state, acl)) != null)
|
||||
buckets.put(name, new Bucket(name, created, state, acl,
|
||||
ownership, block, policy)) != null)
|
||||
throw new IOException("Invalid bucket catalog");
|
||||
}
|
||||
if (input.read() != -1) throw new IOException("Invalid bucket catalog");
|
||||
@@ -174,6 +193,7 @@ final class DiskStore implements ObjectStorage {
|
||||
|
||||
@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") &&
|
||||
@@ -209,7 +229,7 @@ final class DiskStore implements ObjectStorage {
|
||||
Path pending = Files.createTempFile(temporary, "buckets-", ".part");
|
||||
try {
|
||||
try (DataOutputStream output = new DataOutputStream(Files.newOutputStream(pending))) {
|
||||
output.writeInt(BUCKET_MAGIC_V3);
|
||||
output.writeInt(BUCKET_MAGIC_V4);
|
||||
output.writeInt(next.size());
|
||||
for (Bucket entry : next.values()) {
|
||||
output.writeUTF(entry.name());
|
||||
@@ -218,6 +238,13 @@ final class DiskStore implements ObjectStorage {
|
||||
byte[] acl = ObjectAttributes.encode(entry.acl(), ACL_AREA);
|
||||
output.writeShort(acl.length);
|
||||
output.write(acl);
|
||||
output.writeByte(entry.ownership().ordinal());
|
||||
PublicAccessBlock block = entry.publicAccessBlock();
|
||||
output.writeByte((block.blockPublicAcls() ? 1 : 0) |
|
||||
(block.ignorePublicAcls() ? 2 : 0) |
|
||||
(block.blockPublicPolicy() ? 4 : 0) |
|
||||
(block.restrictPublicBuckets() ? 8 : 0));
|
||||
output.writeUTF(entry.policy() == null ? "" : entry.policy());
|
||||
}
|
||||
}
|
||||
try (FileChannel channel = FileChannel.open(pending, StandardOpenOption.WRITE)) { channel.force(true); }
|
||||
@@ -227,13 +254,15 @@ final class DiskStore implements ObjectStorage {
|
||||
}
|
||||
|
||||
@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()));
|
||||
next.put(name, new Bucket(name, old.created(), state, old.acl(),
|
||||
old.ownership(), old.publicAccessBlock(), old.policy()));
|
||||
saveBuckets(next);
|
||||
buckets.clear();
|
||||
buckets.putAll(next);
|
||||
@@ -242,13 +271,52 @@ final class DiskStore implements ObjectStorage {
|
||||
@Override public synchronized void setBucketAcl(String name, Map<String, String> acl) throws IOException {
|
||||
Bucket old = bucket(name);
|
||||
NavigableMap<String, Bucket> next = new TreeMap<>(buckets);
|
||||
next.put(name, new Bucket(name, old.created(), old.versioning(), Map.copyOf(acl)));
|
||||
next.put(name, new Bucket(name, old.created(), old.versioning(), Map.copyOf(acl),
|
||||
old.ownership(), old.publicAccessBlock(), old.policy()));
|
||||
saveBuckets(next);
|
||||
buckets.clear();
|
||||
buckets.putAll(next);
|
||||
}
|
||||
|
||||
@Override public synchronized void setBucketOwnership(String name, ObjectOwnership ownership)
|
||||
throws IOException {
|
||||
Bucket old = bucket(name);
|
||||
updateBucket(new Bucket(name, old.created(), old.versioning(), old.acl(),
|
||||
ownership, old.publicAccessBlock(), old.policy()));
|
||||
}
|
||||
|
||||
@Override public synchronized void setPublicAccessBlock(String name, PublicAccessBlock block)
|
||||
throws IOException {
|
||||
Bucket old = bucket(name);
|
||||
updateBucket(new Bucket(name, old.created(), old.versioning(), old.acl(),
|
||||
old.ownership(), block, old.policy()));
|
||||
}
|
||||
|
||||
@Override public synchronized void setBucketPolicy(String name, String policy)
|
||||
throws IOException {
|
||||
Bucket old = bucket(name);
|
||||
updateBucket(new Bucket(name, old.created(), old.versioning(), old.acl(),
|
||||
old.ownership(), old.publicAccessBlock(), policy));
|
||||
}
|
||||
|
||||
private void updateBucket(Bucket bucket) throws IOException {
|
||||
NavigableMap<String, Bucket> next = new TreeMap<>(buckets);
|
||||
next.put(bucket.name(), bucket);
|
||||
saveBuckets(next);
|
||||
buckets.clear();
|
||||
buckets.putAll(next);
|
||||
}
|
||||
|
||||
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);
|
||||
@@ -505,17 +573,36 @@ final class DiskStore implements ObjectStorage {
|
||||
legacy = old.key() == null;
|
||||
}
|
||||
}
|
||||
long additional = Math.max(0, metadata.length() - previous);
|
||||
synchronized (this) {
|
||||
if (Files.exists(catalog) && !buckets.containsKey(metadata.bucket()))
|
||||
Bucket configured = buckets.get(metadata.bucket());
|
||||
if (configured != null && configured.versioning() != VersioningState.NEVER)
|
||||
return installVersionedPending(destination, pending, metadata, createOnly,
|
||||
configured.versioning());
|
||||
if (Files.exists(catalog) && configured == null)
|
||||
throw new StoreException(404, "NoSuchBucket", "Bucket not found");
|
||||
if (used - previous + metadata.length() > maxTotal)
|
||||
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);
|
||||
syncDirectory(destination.getParent());
|
||||
}
|
||||
reservedBytes -= additional;
|
||||
publishingByBucket.compute(metadata.bucket(), (bucket, count) -> count == 1 ? null : count - 1);
|
||||
notifyAll();
|
||||
}
|
||||
}
|
||||
return metadata;
|
||||
}
|
||||
@@ -542,7 +629,7 @@ final class DiskStore implements ObjectStorage {
|
||||
}
|
||||
}
|
||||
}
|
||||
if (maxTotal - (used - replaced) < metadata.length())
|
||||
if (maxTotal - (used - replaced) - reservedBytes < metadata.length())
|
||||
throw new StoreException(507, "InsufficientStorage", "Store capacity limit reached");
|
||||
Path target = versionPath(bucket, key, storageId);
|
||||
Files.createDirectories(target.getParent());
|
||||
|
||||
@@ -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"));
|
||||
}
|
||||
}
|
||||
+114
-1139
File diff suppressed because it is too large.
Load diff
@@ -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());
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,16 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
interface MultipartStorage {
|
||||
record Part(int number, String etag) {}
|
||||
record Part(int number, String etag, String checksumCrc32) {
|
||||
Part(int number, String etag) { this(number, etag, null); }
|
||||
|
||||
void verifyCrc32(long value) {
|
||||
if (checksumCrc32 == null) return;
|
||||
byte[] bytes = java.nio.ByteBuffer.allocate(4).putInt((int) value).array();
|
||||
if (!checksumCrc32.equals(java.util.Base64.getEncoder().encodeToString(bytes)))
|
||||
throw new StoreException(400, "BadDigest", "Part CRC32 checksum mismatch");
|
||||
}
|
||||
}
|
||||
record PartInfo(int number, long length, String etag, long modified) {}
|
||||
record PartPage(List<PartInfo> parts, int nextMarker, boolean truncated) {}
|
||||
record UploadInfo(String id, String key, long created) {}
|
||||
|
||||
@@ -155,16 +155,19 @@ final class MultipartStore implements MultipartStorage {
|
||||
total += length;
|
||||
if (total > store.maxObject()) throw new StoreException(413, "EntityTooLarge", "Object exceeds the configured size limit");
|
||||
MessageDigest md5 = digest("MD5");
|
||||
java.util.zip.CRC32 crc32 = new java.util.zip.CRC32();
|
||||
try (var input = Files.newInputStream(file)) {
|
||||
byte[] buffer = new byte[65536];
|
||||
int n;
|
||||
while ((n = input.read(buffer)) != -1) {
|
||||
sha.update(buffer, 0, n);
|
||||
md5.update(buffer, 0, n);
|
||||
crc32.update(buffer, 0, n);
|
||||
}
|
||||
}
|
||||
if (!SigV4.hex(md5.digest()).equals(part.etag().replace("\"", "")))
|
||||
throw new StoreException(400, "InvalidPart", "Part ETag mismatch");
|
||||
part.verifyCrc32(crc32.getValue());
|
||||
paths.add(file);
|
||||
}
|
||||
ObjectStorage.Metadata result;
|
||||
|
||||
@@ -0,0 +1,353 @@
|
||||
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");
|
||||
if (query.containsKey("x-amz-acl")) {
|
||||
if (!method.equals("PUT") || copy || !"private".equals(query.get("x-amz-acl")))
|
||||
throw new StoreException(400, "InvalidArgument", "Unsupported ACL query value");
|
||||
if (exchange.getRequestHeaders().containsKey("x-amz-acl"))
|
||||
throw new StoreException(400, "InvalidRequest", "Supply ACL once");
|
||||
}
|
||||
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-acl") ||
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,9 +8,23 @@ import java.util.Map;
|
||||
/** Storage operations shared by the local and cluster gateways. */
|
||||
interface ObjectStorage extends AutoCloseable {
|
||||
enum VersioningState { NEVER, ENABLED, SUSPENDED }
|
||||
enum ObjectOwnership { BUCKET_OWNER_ENFORCED, BUCKET_OWNER_PREFERRED, OBJECT_WRITER }
|
||||
record PublicAccessBlock(boolean blockPublicAcls, boolean ignorePublicAcls,
|
||||
boolean blockPublicPolicy, boolean restrictPublicBuckets) {
|
||||
static PublicAccessBlock secure() { return new PublicAccessBlock(true, true, true, true); }
|
||||
static PublicAccessBlock open() { return new PublicAccessBlock(false, false, false, false); }
|
||||
}
|
||||
record Limits(long maxObjectBytes, long maxTotalBytes) {}
|
||||
record Bucket(String name, long created, VersioningState versioning, Map<String, String> acl) {
|
||||
Bucket(String name, long created) { this(name, created, VersioningState.NEVER, Map.of()); }
|
||||
record Bucket(String name, long created, VersioningState versioning, Map<String, String> acl,
|
||||
ObjectOwnership ownership, PublicAccessBlock publicAccessBlock, String policy) {
|
||||
Bucket(String name, long created) {
|
||||
this(name, created, VersioningState.NEVER, Map.of(),
|
||||
ObjectOwnership.BUCKET_OWNER_ENFORCED, PublicAccessBlock.secure(), null);
|
||||
}
|
||||
Bucket(String name, long created, VersioningState versioning, Map<String, String> acl) {
|
||||
this(name, created, versioning, acl,
|
||||
ObjectOwnership.OBJECT_WRITER, PublicAccessBlock.open(), null);
|
||||
}
|
||||
Bucket(String name, long created, VersioningState versioning) {
|
||||
this(name, created, versioning, Map.of());
|
||||
}
|
||||
@@ -114,6 +128,9 @@ interface ObjectStorage extends AutoCloseable {
|
||||
void createBucket(String bucket) throws IOException;
|
||||
void deleteBucket(String bucket) throws IOException;
|
||||
void setBucketAcl(String bucket, Map<String, String> acl) throws IOException;
|
||||
void setBucketOwnership(String bucket, ObjectOwnership ownership) throws IOException;
|
||||
void setPublicAccessBlock(String bucket, PublicAccessBlock block) throws IOException;
|
||||
void setBucketPolicy(String bucket, String policy) throws IOException;
|
||||
void setObjectAcl(String bucket, String key, String versionId, Map<String, String> acl) throws IOException;
|
||||
Limits limits();
|
||||
default boolean ready() { return true; }
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
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));
|
||||
app.setAdminConsole(AdminConsole.fromEnvironment(env, store));
|
||||
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,75 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.concurrent.atomic.LongAdder;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
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();
|
||||
private final LongAdder dataRequests = new LongAdder();
|
||||
private final LongAdder dataFailures4xx = new LongAdder();
|
||||
private final LongAdder dataFailures5xx = new LongAdder();
|
||||
private final LongAdder dataDurationNanos = new LongAdder();
|
||||
private final LongAdder inboundBytes = new LongAdder();
|
||||
private final LongAdder outboundBytes = new LongAdder();
|
||||
private final AtomicInteger dataInFlight = new AtomicInteger();
|
||||
|
||||
record DataSnapshot(long requests, long failures4xx, long failures5xx,
|
||||
long durationNanos, long inboundBytes, long outboundBytes, int inFlight) { }
|
||||
|
||||
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));
|
||||
}
|
||||
|
||||
void dataStarted() { dataInFlight.incrementAndGet(); }
|
||||
|
||||
void dataFinished(int status, long elapsedNanos, long inbound, long outbound) {
|
||||
dataRequests.increment();
|
||||
if (status >= 500) dataFailures5xx.increment();
|
||||
else if (status >= 400) dataFailures4xx.increment();
|
||||
dataDurationNanos.add(Math.max(0, elapsedNanos));
|
||||
inboundBytes.add(Math.max(0, inbound));
|
||||
outboundBytes.add(Math.max(0, outbound));
|
||||
dataInFlight.decrementAndGet();
|
||||
}
|
||||
|
||||
DataSnapshot dataSnapshot() {
|
||||
return new DataSnapshot(dataRequests.sum(), dataFailures4xx.sum(),
|
||||
dataFailures5xx.sum(), dataDurationNanos.sum(), inboundBytes.sum(),
|
||||
outboundBytes.sum(), dataInFlight.get());
|
||||
}
|
||||
|
||||
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# TYPE objectstore_data_requests_total counter\nobjectstore_data_requests_total " + dataRequests.sum() +
|
||||
"\n# TYPE objectstore_ingress_bytes_total counter\nobjectstore_ingress_bytes_total " + inboundBytes.sum() +
|
||||
"\n# TYPE objectstore_egress_bytes_total counter\nobjectstore_egress_bytes_total " + outboundBytes.sum() + "\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 > 10) throw new IOException("Metadata schema is newer than this ObjectStore build");
|
||||
if (version > 11) throw new IOException("Metadata schema is newer than this ObjectStore build");
|
||||
if (version < 1) {
|
||||
statement.execute("CREATE TABLE IF NOT EXISTS cluster_usage (bucket text PRIMARY KEY, used_bytes bigint NOT NULL CHECK (used_bytes >= 0))");
|
||||
statement.execute("CREATE TABLE IF NOT EXISTS cluster_objects (bucket text NOT NULL, object_key text COLLATE \"C\" NOT NULL, generation uuid NOT NULL, length bigint NOT NULL, modified bigint NOT NULL, etag text NOT NULL, sha256 bytea NOT NULL, content_type text NOT NULL, PRIMARY KEY (bucket, object_key))");
|
||||
@@ -98,6 +98,17 @@ final class SchemaMigrator {
|
||||
statement.execute("ALTER TABLE cluster_uploads ADD COLUMN acl bytea");
|
||||
statement.execute("INSERT INTO cluster_schema_migrations VALUES (10)");
|
||||
}
|
||||
if (version < 11) {
|
||||
statement.execute("ALTER TABLE cluster_buckets ADD COLUMN object_ownership text NOT NULL " +
|
||||
"DEFAULT 'OBJECT_WRITER' CHECK (object_ownership IN " +
|
||||
"('BUCKET_OWNER_ENFORCED', 'BUCKET_OWNER_PREFERRED', 'OBJECT_WRITER'))");
|
||||
statement.execute("ALTER TABLE cluster_buckets ADD COLUMN block_public_acls boolean NOT NULL DEFAULT false");
|
||||
statement.execute("ALTER TABLE cluster_buckets ADD COLUMN ignore_public_acls boolean NOT NULL DEFAULT false");
|
||||
statement.execute("ALTER TABLE cluster_buckets ADD COLUMN block_public_policy boolean NOT NULL DEFAULT false");
|
||||
statement.execute("ALTER TABLE cluster_buckets ADD COLUMN restrict_public_buckets boolean NOT NULL DEFAULT false");
|
||||
statement.execute("ALTER TABLE cluster_buckets ADD COLUMN bucket_policy text");
|
||||
statement.execute("INSERT INTO cluster_schema_migrations VALUES (11)");
|
||||
}
|
||||
statement.execute("INSERT INTO cluster_format SELECT 1, CASE WHEN EXISTS (SELECT 1 FROM cluster_segments WHERE replica_ids IS NULL) THEN 1 ELSE 2 END WHERE NOT EXISTS (SELECT 1 FROM cluster_format)");
|
||||
}
|
||||
try (PreparedStatement insert = connection.prepareStatement("INSERT INTO cluster_usage VALUES (?, 0) ON CONFLICT DO NOTHING")) {
|
||||
@@ -105,7 +116,9 @@ final class SchemaMigrator {
|
||||
insert.executeUpdate();
|
||||
}
|
||||
try (PreparedStatement insert = connection.prepareStatement(
|
||||
"INSERT INTO cluster_buckets (name, created_at) VALUES (?, ?) ON CONFLICT DO NOTHING")) {
|
||||
"INSERT INTO cluster_buckets (name, created_at, object_ownership, block_public_acls, " +
|
||||
"ignore_public_acls, block_public_policy, restrict_public_buckets) " +
|
||||
"VALUES (?, ?, 'BUCKET_OWNER_ENFORCED', true, true, true, true) ON CONFLICT DO NOTHING")) {
|
||||
insert.setString(1, bucket);
|
||||
insert.setLong(2, System.currentTimeMillis());
|
||||
insert.executeUpdate();
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Instant;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
final class SessionCredentials {
|
||||
record Session(String secret, String token, Instant expires) { }
|
||||
|
||||
private SessionCredentials() { }
|
||||
|
||||
static Map<String, Session> fromEnvironment(Map<String, String> env, java.util.Set<String> permanent)
|
||||
throws IOException {
|
||||
String file = env.get("S3_SESSION_CREDENTIALS_FILE");
|
||||
if (file == null || file.isBlank()) return Map.of();
|
||||
var lines = Files.readAllLines(Path.of(file), StandardCharsets.UTF_8);
|
||||
if (lines.size() > 256) throw new IllegalArgumentException("Too many session credentials");
|
||||
Map<String, Session> sessions = new HashMap<>();
|
||||
for (String line : lines) {
|
||||
if (line.isBlank() || line.startsWith("#")) continue;
|
||||
String[] fields = line.split("\\t", -1);
|
||||
if (fields.length != 4 || !fields[0].matches("[A-Za-z0-9]{16,128}") ||
|
||||
permanent.contains(fields[0]) || fields[1].length() < 32 ||
|
||||
fields[2].length() < 32 || fields[2].length() > 2048 ||
|
||||
fields[2].indexOf('\n') >= 0 || fields[2].indexOf('\r') >= 0)
|
||||
throw new IllegalArgumentException("Invalid session credential entry");
|
||||
Instant expires;
|
||||
try { expires = Instant.ofEpochSecond(Long.parseLong(fields[3])); }
|
||||
catch (RuntimeException error) { throw new IllegalArgumentException("Invalid session expiry", error); }
|
||||
if (sessions.putIfAbsent(fields[0], new Session(fields[1], fields[2], expires)) != null)
|
||||
throw new IllegalArgumentException("Duplicate session credential");
|
||||
}
|
||||
return Map.copyOf(sessions);
|
||||
}
|
||||
}
|
||||
@@ -30,6 +30,7 @@ final class SigV4 {
|
||||
private static final DateTimeFormatter DATE = DateTimeFormatter.ofPattern("uuuuMMdd'T'HHmmss'Z'").withZone(ZoneOffset.UTC);
|
||||
private static final Pattern HEX = Pattern.compile("[0-9a-f]{64}");
|
||||
private final Map<String, String> identities;
|
||||
private final Map<String, SessionCredentials.Session> sessions;
|
||||
private final String root;
|
||||
private final String region;
|
||||
private final Clock clock;
|
||||
@@ -39,15 +40,27 @@ final class SigV4 {
|
||||
}
|
||||
|
||||
SigV4(Map<String, String> identities, String root, String region, Clock clock) {
|
||||
this(identities, Map.of(), root, region, clock);
|
||||
}
|
||||
|
||||
SigV4(Map<String, String> identities, Map<String, SessionCredentials.Session> sessions,
|
||||
String root, String region, Clock clock) {
|
||||
this.identities = Map.copyOf(identities);
|
||||
this.sessions = Map.copyOf(sessions);
|
||||
if (!this.identities.containsKey(root)) throw new IllegalArgumentException("Missing root identity");
|
||||
if (this.sessions.keySet().stream().anyMatch(this.identities::containsKey))
|
||||
throw new IllegalArgumentException("Session and permanent keys overlap");
|
||||
this.root = root;
|
||||
this.region = region;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
String root() { return root; }
|
||||
Set<String> identities() { return identities.keySet(); }
|
||||
Set<String> identities() {
|
||||
var all = new java.util.HashSet<>(identities.keySet());
|
||||
all.addAll(sessions.keySet());
|
||||
return Set.copyOf(all);
|
||||
}
|
||||
|
||||
String verify(String method, URI uri, Headers headers) {
|
||||
return verifyRequest(method, uri, headers).payload();
|
||||
@@ -57,6 +70,7 @@ final class SigV4 {
|
||||
if (hasPresignedQuery(uri.getRawQuery())) return verifyPresigned(method, uri, headers);
|
||||
Map<String, String> fields = authorizationFields(headers);
|
||||
String[] credential = credentialScope(fields.get("Credential"));
|
||||
validateSession(credential[0], single(headers, "x-amz-security-token"));
|
||||
String date = signingDate(headers, credential[1]);
|
||||
String payload = payloadHash(headers);
|
||||
String signedHeaders = fields.get("SignedHeaders");
|
||||
@@ -76,11 +90,19 @@ final class SigV4 {
|
||||
if (headers.containsKey("authorization")) denied("Use one authentication method");
|
||||
PresignedQuery query = presignedQuery(uri.getRawQuery());
|
||||
Map<String, String> fields = query.fields();
|
||||
if (!fields.keySet().equals(Set.of("X-Amz-Algorithm", "X-Amz-Credential", "X-Amz-Date",
|
||||
"X-Amz-Expires", "X-Amz-SignedHeaders", "X-Amz-Signature")) ||
|
||||
Set<String> expected = Set.of("X-Amz-Algorithm", "X-Amz-Credential", "X-Amz-Date",
|
||||
"X-Amz-Expires", "X-Amz-SignedHeaders", "X-Amz-Signature");
|
||||
Set<String> allowed = new java.util.HashSet<>(expected);
|
||||
allowed.add("X-Amz-Security-Token");
|
||||
allowed.add("X-Amz-Content-Sha256");
|
||||
if (!fields.keySet().containsAll(expected) || !allowed.containsAll(fields.keySet()) ||
|
||||
fields.containsKey("X-Amz-Content-Sha256") &&
|
||||
!"UNSIGNED-PAYLOAD".equals(fields.get("X-Amz-Content-Sha256")) ||
|
||||
!"AWS4-HMAC-SHA256".equals(fields.get("X-Amz-Algorithm")))
|
||||
denied("Invalid presigned parameters");
|
||||
String[] credential = credentialScope(fields.get("X-Amz-Credential"));
|
||||
if (headers.containsKey("x-amz-security-token")) denied("Presigned session token must be in the query");
|
||||
validateSession(credential[0], fields.get("X-Amz-Security-Token"));
|
||||
String date = fields.get("X-Amz-Date");
|
||||
validatePresignedTime(date, credential[1], fields.get("X-Amz-Expires"));
|
||||
String signedHeaders = fields.get("X-Amz-SignedHeaders");
|
||||
@@ -162,17 +184,29 @@ final class SigV4 {
|
||||
|
||||
private String[] credentialScope(String value) {
|
||||
String[] credential = value.split("/", -1);
|
||||
if (credential.length != 5 || !identities.containsKey(credential[0]) || !credential[2].equals(region)
|
||||
if (credential.length != 5 || !(identities.containsKey(credential[0]) || sessions.containsKey(credential[0])) || !credential[2].equals(region)
|
||||
|| !credential[3].equals("s3") || !credential[4].equals("aws4_request")) denied("Invalid credential scope");
|
||||
return credential;
|
||||
}
|
||||
|
||||
private String secret(String accessKey) {
|
||||
String secret = identities.get(accessKey);
|
||||
if (secret == null && sessions.containsKey(accessKey)) secret = sessions.get(accessKey).secret();
|
||||
if (secret == null) denied("Invalid credential scope");
|
||||
return secret;
|
||||
}
|
||||
|
||||
private void validateSession(String accessKey, String token) {
|
||||
SessionCredentials.Session session = sessions.get(accessKey);
|
||||
if (session == null) {
|
||||
if (token != null) denied("Unexpected session token");
|
||||
return;
|
||||
}
|
||||
if (token == null || !MessageDigest.isEqual(token.getBytes(StandardCharsets.UTF_8),
|
||||
session.token().getBytes(StandardCharsets.UTF_8)) || !clock.instant().isBefore(session.expires()))
|
||||
denied("Invalid or expired session token");
|
||||
}
|
||||
|
||||
private String signingDate(Headers headers, String credentialDate) {
|
||||
String date = single(headers, "x-amz-date");
|
||||
if (date == null || !credentialDate.matches("[0-9]{8}") || !date.matches("[0-9]{8}T[0-9]{6}Z") || !date.startsWith(credentialDate)) denied("Invalid signing date");
|
||||
@@ -190,7 +224,6 @@ final class SigV4 {
|
||||
payload.equals("STREAMING-AWS4-HMAC-SHA256-PAYLOAD") ||
|
||||
payload.equals("STREAMING-AWS4-HMAC-SHA256-PAYLOAD-TRAILER")))
|
||||
throw new StoreException(400, "NotImplemented", "Unsupported SHA-256 payload mode");
|
||||
if (headers.containsKey("x-amz-security-token")) denied("Temporary credentials are unsupported");
|
||||
return payload;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import com.sun.net.httpserver.HttpExchange;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
|
||||
final class TrafficMeter {
|
||||
private long inbound;
|
||||
private long outbound;
|
||||
|
||||
private TrafficMeter() { }
|
||||
|
||||
static TrafficMeter attach(HttpExchange exchange) {
|
||||
TrafficMeter meter = new TrafficMeter();
|
||||
InputStream input = exchange.getRequestBody();
|
||||
OutputStream output = exchange.getResponseBody();
|
||||
exchange.setStreams(meter.input(input), meter.output(output));
|
||||
return meter;
|
||||
}
|
||||
|
||||
long inbound() { return inbound; }
|
||||
long outbound() { return outbound; }
|
||||
|
||||
private InputStream input(InputStream source) {
|
||||
return new InputStream() {
|
||||
@Override public int read() throws IOException {
|
||||
int value = source.read();
|
||||
if (value >= 0) inbound++;
|
||||
return value;
|
||||
}
|
||||
|
||||
@Override public int read(byte[] buffer, int offset, int length) throws IOException {
|
||||
int count = source.read(buffer, offset, length);
|
||||
if (count > 0) inbound += count;
|
||||
return count;
|
||||
}
|
||||
|
||||
@Override public long skip(long count) throws IOException {
|
||||
long skipped = source.skip(count);
|
||||
inbound += skipped;
|
||||
return skipped;
|
||||
}
|
||||
|
||||
@Override public int available() throws IOException { return source.available(); }
|
||||
@Override public void close() throws IOException { source.close(); }
|
||||
};
|
||||
}
|
||||
|
||||
private OutputStream output(OutputStream destination) {
|
||||
return new OutputStream() {
|
||||
@Override public void write(int value) throws IOException {
|
||||
destination.write(value);
|
||||
outbound++;
|
||||
}
|
||||
|
||||
@Override public void write(byte[] buffer, int offset, int length) throws IOException {
|
||||
destination.write(buffer, offset, length);
|
||||
outbound += length;
|
||||
}
|
||||
|
||||
@Override public void flush() throws IOException { destination.flush(); }
|
||||
@Override public void close() throws IOException { destination.close(); }
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
final class Version {
|
||||
static final String VALUE = "0.0.8";
|
||||
static final String VALUE = "0.1.1";
|
||||
|
||||
private Version() {}
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.Socket;
|
||||
import java.net.URI;
|
||||
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.time.Clock;
|
||||
import java.util.Comparator;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
public final class AdminConsoleTest {
|
||||
private static final String PASSWORD = "a-very-long-test-admin-password";
|
||||
|
||||
private static void status(int wanted, HttpResponse<?> response) {
|
||||
if (response.statusCode() != wanted)
|
||||
throw new AssertionError("Expected " + wanted + ", got " + response.statusCode() + ": " + response.body());
|
||||
}
|
||||
|
||||
private static HttpRequest.Builder request(String base, String path) {
|
||||
return HttpRequest.newBuilder(URI.create(base + AdminConsole.PATH + path));
|
||||
}
|
||||
|
||||
private static HttpResponse<String> post(HttpClient client, String base, String path,
|
||||
String password, String csrf, String origin, String cookie) throws Exception {
|
||||
var builder = request(base, path).header("Content-Type", "application/x-www-form-urlencoded");
|
||||
if (origin != null) builder.header("Origin", origin);
|
||||
if (cookie != null) builder.header("Cookie", cookie);
|
||||
return client.send(builder.POST(HttpRequest.BodyPublishers.ofString(
|
||||
"password=" + java.net.URLEncoder.encode(password, StandardCharsets.UTF_8) +
|
||||
"&csrf=" + java.net.URLEncoder.encode(csrf, StandardCharsets.UTF_8))).build(),
|
||||
HttpResponse.BodyHandlers.ofString());
|
||||
}
|
||||
|
||||
private static String csrf(String page) {
|
||||
var match = java.util.regex.Pattern.compile("name=csrf value='([A-Za-z0-9_-]{43})'").matcher(page);
|
||||
if (!match.find()) throw new AssertionError("CSRF token missing from page");
|
||||
return match.group(1);
|
||||
}
|
||||
|
||||
private static String loginToken(HttpClient client, String base) throws Exception {
|
||||
return csrf(client.send(request(base, "/login").GET().build(),
|
||||
HttpResponse.BodyHandlers.ofString()).body());
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
Path root = Files.createTempDirectory("admin-console-test-");
|
||||
Path passwordFile = root.resolve("password");
|
||||
Files.writeString(passwordFile, PASSWORD + "\n");
|
||||
DiskStore store = new DiskStore(root.resolve("data"), 1024, 4096);
|
||||
store.ensureBucket("photos");
|
||||
byte[] image = "small preview".getBytes(StandardCharsets.UTF_8);
|
||||
store.put("photos", "images/cat.txt", new ByteArrayInputStream(image), image.length,
|
||||
SigV4.hex(SigV4.hash(image)), null, true, "text/plain");
|
||||
var executor = Executors.newVirtualThreadPerTaskExecutor();
|
||||
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 16);
|
||||
try {
|
||||
if (AdminConsole.fromEnvironment(Map.of(), store) != null)
|
||||
throw new AssertionError("Admin console enabled without configuration");
|
||||
try {
|
||||
AdminConsole.fromEnvironment(Map.of("ADMIN_UI_ENABLED", "true"), store);
|
||||
throw new AssertionError("Admin console enabled without password file");
|
||||
} catch (IllegalArgumentException expected) { }
|
||||
try {
|
||||
AdminConsole.fromEnvironment(Map.of("ADMIN_UI_ENABLED", "true",
|
||||
"ADMIN_UI_PASSWORD_FILE", passwordFile.toString(),
|
||||
"ADMIN_UI_ORIGIN", "http://public.example"), store);
|
||||
throw new AssertionError("Admin console accepted a remote HTTP origin");
|
||||
} catch (IllegalArgumentException expected) { }
|
||||
AdminConsole console = AdminConsole.fromEnvironment(Map.of(
|
||||
"ADMIN_UI_ENABLED", "true", "ADMIN_UI_PASSWORD_FILE", passwordFile.toString()), store);
|
||||
var app = new Main(store, new MultipartStore(store),
|
||||
new SigV4("TESTACCESSKEY123", "test-secret-key-that-is-at-least-32-characters",
|
||||
"us-east-1", Clock.systemUTC()), "objects");
|
||||
app.setAdminConsole(console);
|
||||
server.setExecutor(executor);
|
||||
server.createContext("/", app::handle);
|
||||
server.start();
|
||||
String base = "http://127.0.0.1:" + server.getAddress().getPort();
|
||||
HttpClient client = HttpClient.newHttpClient();
|
||||
try (Socket socket = new Socket("127.0.0.1", server.getAddress().getPort())) {
|
||||
socket.getOutputStream().write(("GET " + AdminConsole.PATH + "/login HTTP/1.1\r\n" +
|
||||
"Host: public.example\r\nConnection: close\r\n\r\n").getBytes(StandardCharsets.US_ASCII));
|
||||
String response = new String(socket.getInputStream().readAllBytes(), StandardCharsets.UTF_8);
|
||||
if (!response.startsWith("HTTP/1.1 403"))
|
||||
throw new AssertionError("Public Host header reached the admin console");
|
||||
}
|
||||
status(303, client.send(request(base, "/overview").GET().build(),
|
||||
HttpResponse.BodyHandlers.ofString()));
|
||||
for (String path : new String[] { "/performance", "/performance.json", "/performance.js",
|
||||
"/buckets", "/bucket?name=photos",
|
||||
"/object?bucket=photos&key=images%2Fcat.txt" }) {
|
||||
status(303, client.send(request(base, path).GET().build(),
|
||||
HttpResponse.BodyHandlers.ofString()));
|
||||
}
|
||||
var loginPage = client.send(request(base, "/login").GET().build(),
|
||||
HttpResponse.BodyHandlers.ofString());
|
||||
status(200, loginPage);
|
||||
if (!loginPage.body().contains("Admin password") ||
|
||||
!loginPage.body().contains("/_objectstore/admin/logo.png") ||
|
||||
!loginPage.headers().firstValue("Cache-Control").orElse("").equals("no-store"))
|
||||
throw new AssertionError("Login page or cache control missing");
|
||||
String policy = loginPage.headers().firstValue("Content-Security-Policy").orElse("");
|
||||
if (!policy.contains("style-src 'self'") || !policy.contains("img-src 'self'"))
|
||||
throw new AssertionError("Admin console content policy missing");
|
||||
var logo = client.send(request(base, "/logo.png").GET().build(),
|
||||
HttpResponse.BodyHandlers.ofByteArray());
|
||||
status(200, logo);
|
||||
if (!logo.headers().firstValue("Content-Type").orElse("").equals("image/png") ||
|
||||
logo.body().length < 8 || logo.body()[0] != (byte) 0x89 ||
|
||||
logo.body()[1] != 'P' || logo.body()[2] != 'N' || logo.body()[3] != 'G')
|
||||
throw new AssertionError("ObjectStore icon is unavailable");
|
||||
var style = client.send(request(base, "/style.css").GET().build(),
|
||||
HttpResponse.BodyHandlers.ofString());
|
||||
status(200, style);
|
||||
if (!style.body().contains("color-scheme: dark") ||
|
||||
!style.body().contains("--biscuit-chart-surface: #211c2b"))
|
||||
throw new AssertionError("Dark chart styles missing");
|
||||
status(303, client.send(request(base, "/biscuit.js").GET().build(),
|
||||
HttpResponse.BodyHandlers.discarding()));
|
||||
status(403, post(client, base, "/login", PASSWORD, "invalid", null, null));
|
||||
status(401, post(client, base, "/login", "incorrect", loginToken(client, base), null, null));
|
||||
var login = post(client, base, "/login", PASSWORD, loginToken(client, base), null, null);
|
||||
status(303, login);
|
||||
String cookie = login.headers().firstValue("Set-Cookie").orElseThrow().split(";", 2)[0];
|
||||
if (!login.headers().firstValue("Set-Cookie").orElseThrow().contains("HttpOnly; SameSite=Strict"))
|
||||
throw new AssertionError("Session cookie protections missing");
|
||||
var overview = client.send(request(base, "/overview").header("Cookie", cookie).GET().build(),
|
||||
HttpResponse.BodyHandlers.ofString());
|
||||
status(200, overview);
|
||||
if (!overview.body().contains("Storage mode") ||
|
||||
!overview.body().contains("biscuit-cardview") || !overview.body().contains("photos") ||
|
||||
!overview.body().contains("/performance") ||
|
||||
!overview.body().contains("/_objectstore/admin/logo.png"))
|
||||
throw new AssertionError("Authenticated overview missing");
|
||||
var performance = client.send(request(base, "/performance").header("Cookie", cookie).GET().build(),
|
||||
HttpResponse.BodyHandlers.ofString());
|
||||
status(200, performance);
|
||||
if (!performance.headers().firstValue("Content-Security-Policy").orElse("")
|
||||
.contains("connect-src 'self'"))
|
||||
throw new AssertionError("Performance polling is blocked by content policy");
|
||||
if (!performance.body().contains("perf-transfer-chart") ||
|
||||
!performance.body().contains("Process RAM") ||
|
||||
!performance.body().contains("performance.js"))
|
||||
throw new AssertionError("Performance view missing");
|
||||
if (performance.body().split("theme=dark type=line", -1).length != 5)
|
||||
throw new AssertionError("Performance charts must use Biscuit's dark renderer");
|
||||
status(200, client.send(request(base, "/performance.js").header("Cookie", cookie).GET().build(),
|
||||
HttpResponse.BodyHandlers.ofString()));
|
||||
for (int poll = 0; poll < 2; poll++) {
|
||||
var sample = client.send(request(base, "/performance.json")
|
||||
.header("Cookie", cookie).GET().build(), HttpResponse.BodyHandlers.ofString());
|
||||
status(200, sample);
|
||||
if (!sample.body().contains("\"requests\":0") ||
|
||||
!sample.body().contains("\"gcCount\":") ||
|
||||
!sample.body().contains("\"heapBytes\":"))
|
||||
throw new AssertionError("Admin polling was counted as S3 traffic or system data is missing");
|
||||
}
|
||||
var bucketIndex = client.send(request(base, "/buckets").header("Cookie", cookie).GET().build(),
|
||||
HttpResponse.BodyHandlers.ofString());
|
||||
status(200, bucketIndex);
|
||||
if (!bucketIndex.body().contains("/bucket?name=photos"))
|
||||
throw new AssertionError("Bucket index did not link to photos");
|
||||
var bucket = client.send(request(base, "/bucket?name=photos").header("Cookie", cookie).GET().build(),
|
||||
HttpResponse.BodyHandlers.ofString());
|
||||
status(200, bucket);
|
||||
if (!bucket.body().contains("images/") || !bucket.body().contains("Bucket settings"))
|
||||
throw new AssertionError("Bucket folder or settings missing");
|
||||
var folder = client.send(request(base, "/bucket?name=photos&prefix=images%2F")
|
||||
.header("Cookie", cookie).GET().build(), HttpResponse.BodyHandlers.ofString());
|
||||
status(200, folder);
|
||||
if (!folder.body().contains("cat.txt") || !folder.body().contains("biscuit-chartview") ||
|
||||
!folder.body().contains("theme=dark") ||
|
||||
!folder.body().contains("this page only"))
|
||||
throw new AssertionError("Folder listing or bounded chart missing");
|
||||
var object = client.send(request(base, "/object?bucket=photos&key=images%2Fcat.txt")
|
||||
.header("Cookie", cookie).GET().build(), HttpResponse.BodyHandlers.ofString());
|
||||
status(200, object);
|
||||
if (!object.body().contains("Content type") || !object.body().contains("text/plain") ||
|
||||
!object.body().contains("SHA-256"))
|
||||
throw new AssertionError("Object metadata missing");
|
||||
status(400, client.send(request(base, "/bucket?name=photos&name=other")
|
||||
.header("Cookie", cookie).GET().build(), HttpResponse.BodyHandlers.ofString()));
|
||||
var reflected = client.send(request(base, "/buckets?filter=%3Cscript%3E")
|
||||
.header("Cookie", cookie).GET().build(), HttpResponse.BodyHandlers.ofString());
|
||||
status(200, reflected);
|
||||
if (reflected.body().contains("value='<script>'") ||
|
||||
!reflected.body().contains("<script>"))
|
||||
throw new AssertionError("Bucket search was not escaped");
|
||||
status(200, client.send(request(base, "/biscuit.js").header("Cookie", cookie).GET().build(),
|
||||
HttpResponse.BodyHandlers.discarding()));
|
||||
status(403, post(client, base, "/logout", "", "invalid", null, cookie));
|
||||
status(200, client.send(request(base, "/overview").header("Cookie", cookie).GET().build(),
|
||||
HttpResponse.BodyHandlers.ofString()));
|
||||
status(303, post(client, base, "/logout", "", csrf(overview.body()), null, cookie));
|
||||
status(303, client.send(request(base, "/overview").header("Cookie", cookie).GET().build(),
|
||||
HttpResponse.BodyHandlers.ofString()));
|
||||
for (int i = 0; i < 5; i++) {
|
||||
status(401, post(client, base, "/login", "incorrect", loginToken(client, base), null, null));
|
||||
}
|
||||
status(429, post(client, base, "/login", PASSWORD, loginToken(client, base), null, null));
|
||||
System.out.println("Admin console tests passed");
|
||||
} 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,14 +3,68 @@ package cloud.lunarsky.store;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
public final class ConcurrencyTest {
|
||||
private static void parallelCapacity() throws Exception {
|
||||
Path root = Files.createTempDirectory("store-parallel-capacity-");
|
||||
byte[] body = new byte[4096];
|
||||
Set<String> saved = new HashSet<>();
|
||||
try {
|
||||
try (var store = new DiskStore(root, body.length, 8L * body.length);
|
||||
var workers = Executors.newFixedThreadPool(16)) {
|
||||
CountDownLatch start = new CountDownLatch(1);
|
||||
List<Future<String>> writes = new ArrayList<>();
|
||||
for (int i = 0; i < 16; i++) {
|
||||
String key = "parallel-" + i;
|
||||
writes.add(workers.submit(() -> {
|
||||
start.await();
|
||||
try {
|
||||
store.put("test", key, new ByteArrayInputStream(body), body.length,
|
||||
SigV4.hex(SigV4.hash(body)), null, true, "application/octet-stream");
|
||||
return key;
|
||||
} catch (StoreException error) {
|
||||
if (error.status != 507) throw error;
|
||||
return null;
|
||||
}
|
||||
}));
|
||||
}
|
||||
start.countDown();
|
||||
for (Future<String> write : writes) {
|
||||
String key = write.get();
|
||||
if (key != null) saved.add(key);
|
||||
}
|
||||
if (saved.size() != 8 || store.usedBytes() != 8L * body.length ||
|
||||
store.list("test", "", "", 100, null).objects().size() != 8)
|
||||
throw new AssertionError("Concurrent writes exceeded capacity or lost an acknowledgement");
|
||||
}
|
||||
try (var restarted = new DiskStore(root, body.length, 8L * body.length)) {
|
||||
if (restarted.usedBytes() != 8L * body.length ||
|
||||
restarted.list("test", "", "", 100, null).objects().size() != 8)
|
||||
throw new AssertionError("Concurrent writes were not recovered after restart");
|
||||
for (String key : saved) {
|
||||
try (var object = restarted.open("test", key)) {
|
||||
if (!Arrays.equals(object.stream().readAllBytes(), body))
|
||||
throw new AssertionError("Recovered object differs from acknowledged write");
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
try (var paths = Files.walk(root)) {
|
||||
for (Path path : paths.sorted(Comparator.reverseOrder()).toList()) Files.delete(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static ObjectStorage.Metadata put(DiskStore store, byte[] body) throws Exception {
|
||||
return store.put("test", "shared", new ByteArrayInputStream(body), body.length,
|
||||
SigV4.hex(SigV4.hash(body)), null, false, "application/octet-stream");
|
||||
@@ -78,11 +132,12 @@ public final class ConcurrencyTest {
|
||||
} catch (StoreException expected) {
|
||||
if (expected.status != 404) throw expected;
|
||||
}
|
||||
System.out.println("Concurrent storage tests passed: atomic overwrite, read and listing after acknowledgement, delete");
|
||||
} finally {
|
||||
try (var paths = Files.walk(root)) {
|
||||
for (Path path : paths.sorted(Comparator.reverseOrder()).toList()) Files.delete(path);
|
||||
}
|
||||
}
|
||||
parallelCapacity();
|
||||
System.out.println("Concurrent storage tests passed: atomic overwrite, read and listing after acknowledgement, delete, parallel quota and restart");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,278 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Clock;
|
||||
import java.util.Comparator;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
public final class FeatureTest {
|
||||
private static final String OWNER = "TESTACCESSKEY123";
|
||||
private static final String LIMITED = "LIMITEDACCESS1234";
|
||||
private static final String OWNER_SECRET = "test-secret-key-that-is-at-least-32-characters";
|
||||
private static final String LIMITED_SECRET = "limited-secret-key-that-is-at-least-32-characters";
|
||||
private static final String SESSION = "SESSIONACCESS1234";
|
||||
private static final String SESSION_SECRET = "session-secret-key-that-is-at-least-32-characters";
|
||||
private static final String SESSION_TOKEN = "session-token-that-is-at-least-32-characters";
|
||||
|
||||
private static void status(int expected, HttpResponse<?> response) {
|
||||
if (response.statusCode() != expected)
|
||||
throw new AssertionError("Expected " + expected + ", got " + response.statusCode() + ": " + response.body());
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
Path root = Files.createTempDirectory("objectstore-feature-test-");
|
||||
Path sessionFile = root.resolve("sessions");
|
||||
Files.writeString(sessionFile, SESSION + "\t" + SESSION_SECRET + "\t" + SESSION_TOKEN +
|
||||
"\t" + java.time.Instant.now().plusSeconds(3600).getEpochSecond() + "\n");
|
||||
var sessions = SessionCredentials.fromEnvironment(
|
||||
Map.of("S3_SESSION_CREDENTIALS_FILE", sessionFile.toString()), Set.of(OWNER, LIMITED));
|
||||
if (!sessions.containsKey(SESSION)) throw new AssertionError("Session credentials not loaded");
|
||||
Path identityDir = Files.createDirectory(root.resolve("identity-policies"));
|
||||
Files.writeString(identityDir.resolve(LIMITED + ".json"),
|
||||
"{\"Version\":\"2012-10-17\",\"Statement\":[" +
|
||||
statement("Deny", null, "s3:PutObject", "arn:aws:s3:::photos/users/one/blocked") + "," +
|
||||
statement("Allow", null, "s3:GetObject", "arn:aws:s3:::photos/users/one/self_readable") + "," +
|
||||
statement("Allow", null, "s3:PutObject", "arn:aws:s3:::secure/users/one/*") + "," +
|
||||
statement("Allow", null, "s3:GetObject", "arn:aws:s3:::secure/users/one/*") + "]}");
|
||||
Files.writeString(identityDir.resolve(SESSION + ".json"), policy("Allow", null,
|
||||
"s3:GetObject", "arn:aws:s3:::photos/users/one/allowed"));
|
||||
var identityPolicies = IdentityPolicies.fromEnvironment(
|
||||
Map.of("S3_IDENTITY_POLICIES_DIR", identityDir.toString()), OWNER,
|
||||
Set.of(OWNER, LIMITED, SESSION));
|
||||
Path policy = root.resolve("scopes");
|
||||
Files.writeString(policy, LIMITED + "\tphotos\tusers/one/\tread,write,list\n" +
|
||||
LIMITED + "\tsecure\tusers/one/\tread,write\n" +
|
||||
SESSION + "\tphotos\tusers/one/\tread\n");
|
||||
KeyScopes scopes = KeyScopes.fromEnvironment(Map.of("S3_KEY_SCOPES_FILE", policy.toString()),
|
||||
OWNER, Set.of(OWNER, LIMITED, SESSION));
|
||||
scopes.require(LIMITED, "write", "photos", "users/one/image.jpg");
|
||||
scopes.checkBucket(LIMITED, "photos", "GET", Map.of("list-type", "2", "prefix", "users/one/"));
|
||||
denied(() -> scopes.require(LIMITED, "read", "photos", "users/two/image.jpg"));
|
||||
denied(() -> scopes.checkBucket(LIMITED, "photos", "GET", Map.of("list-type", "2")));
|
||||
denied(() -> scopes.checkBucket(LIMITED, "photos", "GET", Map.of("list-type", "2", "prefix", "users/")));
|
||||
denied(() -> scopes.checkObject(LIMITED, "photos", "users/one/copy.jpg", "PUT", Map.of(),
|
||||
headers("x-amz-copy-source", "/photos/users/two/private.jpg")));
|
||||
denied(() -> scopes.checkObject(LIMITED, "photos", "users/one/file", "PUT", Map.of(),
|
||||
headers("x-amz-acl", "public-read")));
|
||||
var cors = BrowserCors.fromEnvironment(Map.of("CORS_ALLOWED_ORIGINS", "https://dashboard.example"));
|
||||
var metrics = new RequestMetrics("metrics-test-token-at-least-32-characters");
|
||||
var executor = Executors.newVirtualThreadPerTaskExecutor();
|
||||
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 16);
|
||||
DiskStore store = new DiskStore(root.resolve("data"), 1024, 4096);
|
||||
try {
|
||||
Main app = new Main(store, new MultipartStore(store),
|
||||
new SigV4(Map.of(OWNER, OWNER_SECRET, LIMITED, LIMITED_SECRET), sessions, OWNER,
|
||||
"us-east-1", Clock.systemUTC()),
|
||||
"photos", ClientLimits.disabled(), 16, "", cors, scopes, metrics, identityPolicies);
|
||||
store.setBucketOwnership("photos", ObjectStorage.ObjectOwnership.OBJECT_WRITER);
|
||||
store.setPublicAccessBlock("photos", ObjectStorage.PublicAccessBlock.open());
|
||||
server.setExecutor(executor);
|
||||
server.createContext("/", app::handle);
|
||||
server.start();
|
||||
String base = "http://127.0.0.1:" + server.getAddress().getPort();
|
||||
HttpClient client = HttpClient.newHttpClient();
|
||||
status(204, client.send(HttpRequest.newBuilder(URI.create(base + "/photos/file"))
|
||||
.header("Origin", "https://dashboard.example")
|
||||
.header("Access-Control-Request-Method", "PUT")
|
||||
.header("Access-Control-Request-Headers", "content-type,x-amz-date")
|
||||
.method("OPTIONS", HttpRequest.BodyPublishers.noBody()).build(),
|
||||
HttpResponse.BodyHandlers.ofString()));
|
||||
status(403, client.send(HttpRequest.newBuilder(URI.create(base + "/photos/file"))
|
||||
.header("Origin", "https://other.example")
|
||||
.header("Access-Control-Request-Method", "PUT")
|
||||
.method("OPTIONS", HttpRequest.BodyPublishers.noBody()).build(),
|
||||
HttpResponse.BodyHandlers.ofString()));
|
||||
var health = client.send(HttpRequest.newBuilder(URI.create(base + "/health"))
|
||||
.header("Origin", "https://dashboard.example").GET().build(),
|
||||
HttpResponse.BodyHandlers.ofString());
|
||||
status(200, health);
|
||||
if (!"https://dashboard.example".equals(health.headers().firstValue("Access-Control-Allow-Origin").orElse(null)))
|
||||
throw new AssertionError("Allowed origin missing from response");
|
||||
status(401, client.send(HttpRequest.newBuilder(URI.create(base + "/metrics")).GET().build(),
|
||||
HttpResponse.BodyHandlers.ofString()));
|
||||
var snapshot = client.send(HttpRequest.newBuilder(URI.create(base + "/metrics"))
|
||||
.header("Authorization", "Bearer metrics-test-token-at-least-32-characters").GET().build(),
|
||||
HttpResponse.BodyHandlers.ofString());
|
||||
status(200, snapshot);
|
||||
if (!snapshot.body().contains("objectstore_requests_total 4"))
|
||||
throw new AssertionError("Metrics did not count requests: " + snapshot.body());
|
||||
status(200, client.send(HttpTest.signedUri(URI.create(base + "/photos?acl"),
|
||||
"PUT", new byte[0], Map.of("x-amz-grant-full-control", "id=\"" + LIMITED + "\"")),
|
||||
HttpResponse.BodyHandlers.ofString()));
|
||||
status(405, client.send(HttpTest.signedUri(URI.create(base + "/photos?acl"),
|
||||
"PUT", new byte[0], Map.of("x-amz-grant-read", "emailAddress=\"example@example.test\"")),
|
||||
HttpResponse.BodyHandlers.ofString()));
|
||||
byte[] content = "allowed".getBytes(java.nio.charset.StandardCharsets.UTF_8);
|
||||
status(200, client.send(HttpTest.signedUriAs(URI.create(base + "/photos/users/one/allowed"),
|
||||
"PUT", content, Map.of(), LIMITED, LIMITED_SECRET), HttpResponse.BodyHandlers.ofString()));
|
||||
URI ownReadable = URI.create(base + "/photos/users/one/self_readable");
|
||||
var trafficBefore = metrics.dataSnapshot();
|
||||
status(200, client.send(HttpTest.signedUriAs(ownReadable,
|
||||
"PUT", content, Map.of(), LIMITED, LIMITED_SECRET), HttpResponse.BodyHandlers.ofString()));
|
||||
status(200, client.send(HttpTest.signedUriAs(ownReadable,
|
||||
"GET", new byte[0], Map.of(), LIMITED, LIMITED_SECRET), HttpResponse.BodyHandlers.ofString()));
|
||||
var trafficAfter = metrics.dataSnapshot();
|
||||
if (trafficAfter.requests() - trafficBefore.requests() != 2 ||
|
||||
trafficAfter.inboundBytes() - trafficBefore.inboundBytes() < content.length ||
|
||||
trafficAfter.outboundBytes() - trafficBefore.outboundBytes() < content.length ||
|
||||
trafficAfter.inFlight() != 0)
|
||||
throw new AssertionError("S3 traffic meter missed upload or download body bytes");
|
||||
status(403, client.send(HttpTest.signedUriAs(URI.create(base + "/photos/users/one/allowed"),
|
||||
"GET", new byte[0], Map.of(), LIMITED, LIMITED_SECRET), HttpResponse.BodyHandlers.ofString()));
|
||||
status(403, client.send(HttpTest.signedUriAs(URI.create(base + "/photos/users/one/blocked"),
|
||||
"PUT", content, Map.of(), LIMITED, LIMITED_SECRET), HttpResponse.BodyHandlers.ofString()));
|
||||
status(403, client.send(HttpTest.signedUriAs(URI.create(base + "/photos/users/two/denied"),
|
||||
"PUT", content, Map.of(), LIMITED, LIMITED_SECRET), HttpResponse.BodyHandlers.ofString()));
|
||||
status(200, client.send(HttpTest.signedUriAs(URI.create(base + "/photos?list-type=2&prefix=users%2Fone%2F"),
|
||||
"GET", new byte[0], Map.of(), LIMITED, LIMITED_SECRET), HttpResponse.BodyHandlers.ofString()));
|
||||
status(403, client.send(HttpTest.signedUriAs(URI.create(base + "/photos?list-type=2"),
|
||||
"GET", new byte[0], Map.of(), LIMITED, LIMITED_SECRET), HttpResponse.BodyHandlers.ofString()));
|
||||
status(403, client.send(HttpTest.signedUriAs(URI.create(base + "/photos/users/one/allowed?acl"),
|
||||
"GET", new byte[0], Map.of(), LIMITED, LIMITED_SECRET), HttpResponse.BodyHandlers.ofString()));
|
||||
status(200, client.send(HttpTest.signedUri(URI.create(base + "/photos/users/one/allowed?acl"),
|
||||
"PUT", new byte[0], Map.of("x-amz-acl", "public-read")),
|
||||
HttpResponse.BodyHandlers.ofString()));
|
||||
status(200, client.send(HttpRequest.newBuilder(
|
||||
URI.create(base + "/photos/users/one/allowed")).GET().build(),
|
||||
HttpResponse.BodyHandlers.ofString()));
|
||||
store.setPublicAccessBlock("photos", ObjectStorage.PublicAccessBlock.secure());
|
||||
status(403, client.send(HttpRequest.newBuilder(
|
||||
URI.create(base + "/photos/users/one/allowed")).GET().build(),
|
||||
HttpResponse.BodyHandlers.ofString()));
|
||||
status(403, client.send(HttpTest.signedUri(URI.create(base + "/photos/users/one/public"),
|
||||
"PUT", content, Map.of("x-amz-acl", "public-read")),
|
||||
HttpResponse.BodyHandlers.ofString()));
|
||||
store.createBucket("secure");
|
||||
var secure = store.bucket("secure");
|
||||
if (secure.ownership() != ObjectStorage.ObjectOwnership.BUCKET_OWNER_ENFORCED ||
|
||||
!secure.publicAccessBlock().blockPublicAcls() ||
|
||||
!secure.publicAccessBlock().ignorePublicAcls() ||
|
||||
!secure.publicAccessBlock().blockPublicPolicy() ||
|
||||
!secure.publicAccessBlock().restrictPublicBuckets())
|
||||
throw new AssertionError("New bucket did not default to private access");
|
||||
URI scopedObject = URI.create(base + "/secure/users/one/photo.jpg");
|
||||
status(200, client.send(HttpTest.signedUriAs(scopedObject,
|
||||
"PUT", content, Map.of(), LIMITED, LIMITED_SECRET), HttpResponse.BodyHandlers.ofString()));
|
||||
status(200, client.send(HttpTest.signedUriAs(scopedObject,
|
||||
"GET", new byte[0], Map.of(), LIMITED, LIMITED_SECRET), HttpResponse.BodyHandlers.ofString()));
|
||||
status(403, client.send(HttpTest.signedUriAs(URI.create(base + "/secure/users/two/photo.jpg"),
|
||||
"GET", new byte[0], Map.of(), LIMITED, LIMITED_SECRET), HttpResponse.BodyHandlers.ofString()));
|
||||
status(400, client.send(HttpTest.signedUri(URI.create(base + "/secure/item"),
|
||||
"PUT", content, Map.of("x-amz-acl", "public-read")),
|
||||
HttpResponse.BodyHandlers.ofString()));
|
||||
URI ownership = URI.create(base + "/photos?ownershipControls");
|
||||
byte[] enforced = ("<OwnershipControls><Rule><ObjectOwnership>BucketOwnerEnforced" +
|
||||
"</ObjectOwnership></Rule></OwnershipControls>")
|
||||
.getBytes(java.nio.charset.StandardCharsets.UTF_8);
|
||||
status(200, client.send(HttpTest.signedUri(ownership, "PUT", enforced, Map.of()),
|
||||
HttpResponse.BodyHandlers.ofString()));
|
||||
status(403, client.send(HttpTest.signedUriAs(URI.create(base + "/photos/users/one/allowed"),
|
||||
"GET", new byte[0], Map.of(), LIMITED, LIMITED_SECRET), HttpResponse.BodyHandlers.ofString()));
|
||||
URI bucketPolicy = URI.create(base + "/photos?policy");
|
||||
String allow = policy("Allow", LIMITED, "s3:GetObject", "arn:aws:s3:::photos/users/one/*");
|
||||
status(204, client.send(HttpTest.signedUri(bucketPolicy, "PUT", allow.getBytes(), Map.of()),
|
||||
HttpResponse.BodyHandlers.ofString()));
|
||||
status(200, client.send(HttpTest.signedUriAs(URI.create(base + "/photos/users/one/allowed"),
|
||||
"GET", new byte[0], Map.of(), LIMITED, LIMITED_SECRET), HttpResponse.BodyHandlers.ofString()));
|
||||
String deny = "{\"Version\":\"2012-10-17\",\"Statement\":[" +
|
||||
statement("Allow", LIMITED, "s3:GetObject", "arn:aws:s3:::photos/users/one/*") + "," +
|
||||
statement("Deny", "*", "s3:GetObject", "arn:aws:s3:::photos/users/one/allowed") + "]}";
|
||||
status(204, client.send(HttpTest.signedUri(bucketPolicy, "PUT", deny.getBytes(), Map.of()),
|
||||
HttpResponse.BodyHandlers.ofString()));
|
||||
status(403, client.send(HttpTest.signedUriAs(URI.create(base + "/photos/users/one/allowed"),
|
||||
"GET", new byte[0], Map.of(), LIMITED, LIMITED_SECRET), HttpResponse.BodyHandlers.ofString()));
|
||||
status(403, client.send(HttpTest.signedUri(URI.create(base + "/photos/users/one/allowed"),
|
||||
"GET", new byte[0], Map.of()), HttpResponse.BodyHandlers.ofString()));
|
||||
String publicPolicy = policy("Allow", "*", "s3:GetObject", "arn:aws:s3:::photos/users/one/*");
|
||||
status(403, client.send(HttpTest.signedUri(bucketPolicy, "PUT", publicPolicy.getBytes(), Map.of()),
|
||||
HttpResponse.BodyHandlers.ofString()));
|
||||
byte[] block = ("<PublicAccessBlockConfiguration><BlockPublicAcls>true</BlockPublicAcls>" +
|
||||
"<IgnorePublicAcls>true</IgnorePublicAcls><BlockPublicPolicy>false</BlockPublicPolicy>" +
|
||||
"<RestrictPublicBuckets>true</RestrictPublicBuckets></PublicAccessBlockConfiguration>").getBytes();
|
||||
status(200, client.send(HttpTest.signedUri(URI.create(base + "/photos?publicAccessBlock"),
|
||||
"PUT", block, Map.of()), HttpResponse.BodyHandlers.ofString()));
|
||||
status(204, client.send(HttpTest.signedUri(bucketPolicy, "PUT", publicPolicy.getBytes(), Map.of()),
|
||||
HttpResponse.BodyHandlers.ofString()));
|
||||
status(403, client.send(HttpRequest.newBuilder(
|
||||
URI.create(base + "/photos/users/one/allowed")).GET().build(),
|
||||
HttpResponse.BodyHandlers.ofString()));
|
||||
status(200, client.send(HttpTest.signedUri(bucketPolicy, "GET", new byte[0], Map.of()),
|
||||
HttpResponse.BodyHandlers.ofString()));
|
||||
String sessionPolicy = policy("Allow", LIMITED, "s3:GetObject",
|
||||
"arn:aws:s3:::photos/users/one/*");
|
||||
status(204, client.send(HttpTest.signedUri(bucketPolicy, "PUT", sessionPolicy.getBytes(), Map.of()),
|
||||
HttpResponse.BodyHandlers.ofString()));
|
||||
URI sessionObject = URI.create(base + "/photos/users/one/allowed");
|
||||
status(200, client.send(HttpTest.signedUriAs(sessionObject, "GET", new byte[0],
|
||||
Map.of("x-amz-security-token", SESSION_TOKEN), SESSION, SESSION_SECRET),
|
||||
HttpResponse.BodyHandlers.ofString()));
|
||||
status(403, client.send(HttpTest.signedUriAs(sessionObject, "GET", new byte[0],
|
||||
Map.of(), SESSION, SESSION_SECRET), HttpResponse.BodyHandlers.ofString()));
|
||||
status(403, client.send(HttpTest.signedUriAs(sessionObject, "GET", new byte[0],
|
||||
Map.of("x-amz-security-token", SESSION_TOKEN + "wrong"), SESSION, SESSION_SECRET),
|
||||
HttpResponse.BodyHandlers.ofString()));
|
||||
status(403, client.send(HttpTest.signedUriAs(sessionObject, "PUT", content,
|
||||
Map.of("x-amz-security-token", SESSION_TOKEN), SESSION, SESSION_SECRET),
|
||||
HttpResponse.BodyHandlers.ofString()));
|
||||
status(200, client.send(HttpRequest.newBuilder(HttpTest.presignedUriAs(sessionObject, "GET", 60,
|
||||
SESSION, SESSION_SECRET, SESSION_TOKEN)).GET().build(), HttpResponse.BodyHandlers.ofString()));
|
||||
status(403, client.send(HttpRequest.newBuilder(HttpTest.presignedUriAs(sessionObject, "GET", 60,
|
||||
SESSION, SESSION_SECRET, null)).GET().build(), HttpResponse.BodyHandlers.ofString()));
|
||||
status(403, client.send(HttpTest.signedUriAs(sessionObject, "GET", new byte[0],
|
||||
Map.of("x-amz-security-token", SESSION_TOKEN), OWNER, OWNER_SECRET),
|
||||
HttpResponse.BodyHandlers.ofString()));
|
||||
var expired = new SigV4(Map.of(OWNER, OWNER_SECRET), Map.of(SESSION,
|
||||
new SessionCredentials.Session(SESSION_SECRET, SESSION_TOKEN,
|
||||
java.time.Instant.now().minusSeconds(1))), OWNER, "us-east-1", Clock.systemUTC());
|
||||
var signed = HttpTest.signedUriAs(sessionObject, "GET", new byte[0],
|
||||
Map.of("x-amz-security-token", SESSION_TOKEN), SESSION, SESSION_SECRET);
|
||||
var signedHeaders = new com.sun.net.httpserver.Headers();
|
||||
signed.headers().map().forEach(signedHeaders::put);
|
||||
signedHeaders.set("host", sessionObject.getAuthority());
|
||||
denied(() -> expired.verifyRequest("GET", sessionObject, signedHeaders));
|
||||
} finally {
|
||||
server.stop(0);
|
||||
executor.close();
|
||||
store.close();
|
||||
try (var files = Files.walk(root)) {
|
||||
for (Path path : files.sorted(Comparator.reverseOrder()).toList()) Files.delete(path);
|
||||
}
|
||||
}
|
||||
System.out.println("Feature tests passed: scoped keys, CORS, metrics, bucket policy and public access");
|
||||
}
|
||||
|
||||
private static String policy(String effect, String principal, String action, String resource) {
|
||||
return "{\"Version\":\"2012-10-17\",\"Statement\":[" +
|
||||
statement(effect, principal, action, resource) + "]}";
|
||||
}
|
||||
|
||||
private static String statement(String effect, String principal, String action, String resource) {
|
||||
return "{\"Effect\":\"" + effect + "\"," +
|
||||
(principal == null ? "" : "\"Principal\":\"" + principal + "\",") +
|
||||
"\"Action\":\"" + action + "\",\"Resource\":\"" + resource + "\"}";
|
||||
}
|
||||
|
||||
private static com.sun.net.httpserver.Headers headers(String name, String value) {
|
||||
var headers = new com.sun.net.httpserver.Headers();
|
||||
headers.set(name, value);
|
||||
return headers;
|
||||
}
|
||||
|
||||
private static void denied(Runnable action) {
|
||||
try { action.run(); }
|
||||
catch (StoreException error) {
|
||||
if (error.status == 403) return;
|
||||
throw new AssertionError("Wrong denial", error);
|
||||
}
|
||||
throw new AssertionError("Expected access denial");
|
||||
}
|
||||
}
|
||||
@@ -39,7 +39,7 @@ public final class HttpTest {
|
||||
return signedUriAs(uri, method, body, extra, ACCESS, SECRET);
|
||||
}
|
||||
|
||||
private static HttpRequest signedUriAs(URI uri, String method, byte[] body, Map<String, String> extra,
|
||||
static HttpRequest signedUriAs(URI uri, String method, byte[] body, Map<String, String> extra,
|
||||
String access, String secret) {
|
||||
String host = uri.getAuthority();
|
||||
String date = DATE.format(Instant.now());
|
||||
@@ -71,17 +71,35 @@ public final class HttpTest {
|
||||
}
|
||||
|
||||
private static URI presignedUri(URI uri, String method, int expires) {
|
||||
return presignedUriAs(uri, method, expires, ACCESS, SECRET, null);
|
||||
}
|
||||
|
||||
static URI presignedUriAs(URI uri, String method, int expires, String access, String secret,
|
||||
String token) {
|
||||
return presignedUriAs(uri, method, expires, access, secret, token, false);
|
||||
}
|
||||
|
||||
private static URI presignedUriAs(URI uri, String method, int expires, String access, String secret,
|
||||
String token, boolean sdkContentHash) {
|
||||
return presignedUriAs(uri, method, expires, access, secret, token, sdkContentHash, "");
|
||||
}
|
||||
|
||||
private static URI presignedUriAs(URI uri, String method, int expires, String access, String secret,
|
||||
String token, boolean sdkContentHash, String applicationQuery) {
|
||||
String date = DATE.format(Instant.now());
|
||||
String scope = date.substring(0, 8) + "/" + REGION + "/s3/aws4_request";
|
||||
String query = "X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=" +
|
||||
SigV4.encode(ACCESS + "/" + scope, false) + "&X-Amz-Date=" + date +
|
||||
SigV4.encode(access + "/" + scope, false) + "&X-Amz-Date=" + date +
|
||||
"&X-Amz-Expires=" + expires + "&X-Amz-SignedHeaders=host";
|
||||
if (token != null) query += "&X-Amz-Security-Token=" + SigV4.encode(token, false);
|
||||
if (sdkContentHash) query += "&X-Amz-Content-Sha256=UNSIGNED-PAYLOAD";
|
||||
if (!applicationQuery.isEmpty()) query += "&" + applicationQuery;
|
||||
String canonical = method + "\n" + uri.getRawPath() + "\n" +
|
||||
SigV4.canonicalQuery(query) + "\nhost:" + uri.getAuthority() +
|
||||
"\n\nhost\nUNSIGNED-PAYLOAD";
|
||||
String toSign = "AWS4-HMAC-SHA256\n" + date + "\n" + scope + "\n" +
|
||||
SigV4.hex(SigV4.hash(canonical.getBytes(StandardCharsets.UTF_8)));
|
||||
String signature = SigV4.hex(SigV4.hmac(SigV4.signingKey(SECRET,
|
||||
String signature = SigV4.hex(SigV4.hmac(SigV4.signingKey(secret,
|
||||
date.substring(0, 8), REGION), toSign));
|
||||
return URI.create(uri + "?" + query + "&X-Amz-Signature=" + signature);
|
||||
}
|
||||
@@ -96,6 +114,53 @@ public final class HttpTest {
|
||||
HttpResponse.BodyHandlers.ofByteArray());
|
||||
status(200, read);
|
||||
if (!java.util.Arrays.equals(body, read.body())) throw new AssertionError("Presigned object mismatch");
|
||||
URI sdkObject = URI.create(base + "/objects/sdk-v3-presigned");
|
||||
URI sdkPut = presignedUriAs(sdkObject, "PUT", 60, ACCESS, SECRET, null, true);
|
||||
status(200, client.send(HttpRequest.newBuilder(sdkPut)
|
||||
.PUT(HttpRequest.BodyPublishers.ofByteArray(body)).build(), HttpResponse.BodyHandlers.ofByteArray()));
|
||||
URI sdkGet = presignedUriAs(sdkObject, "GET", 60, ACCESS, SECRET, null, true);
|
||||
status(200, client.send(HttpRequest.newBuilder(sdkGet).GET().build(),
|
||||
HttpResponse.BodyHandlers.ofByteArray()));
|
||||
URI privateObject = URI.create(base + "/objects/sdk-v3-private-acl");
|
||||
URI privatePut = presignedUriAs(privateObject, "PUT", 60, ACCESS, SECRET, null,
|
||||
true, "x-amz-acl=private&x-id=PutObject");
|
||||
status(200, client.send(HttpRequest.newBuilder(privatePut)
|
||||
.PUT(HttpRequest.BodyPublishers.ofByteArray(body)).build(),
|
||||
HttpResponse.BodyHandlers.ofByteArray()));
|
||||
var privateRead = client.send(HttpRequest.newBuilder(presignedUri(privateObject, "GET", 60))
|
||||
.GET().build(), HttpResponse.BodyHandlers.ofByteArray());
|
||||
status(200, privateRead);
|
||||
if (!java.util.Arrays.equals(body, privateRead.body()))
|
||||
throw new AssertionError("Private ACL query upload mismatch");
|
||||
status(403, client.send(HttpRequest.newBuilder(privateObject).GET().build(),
|
||||
HttpResponse.BodyHandlers.ofByteArray()));
|
||||
status(403, client.send(HttpRequest.newBuilder(URI.create(privatePut.toString().replace(
|
||||
"x-amz-acl=private", "x-amz-acl=public-read")))
|
||||
.PUT(HttpRequest.BodyPublishers.ofByteArray(body)).build(),
|
||||
HttpResponse.BodyHandlers.ofByteArray()));
|
||||
status(400, client.send(HttpRequest.newBuilder(presignedUriAs(privateObject, "PUT", 60,
|
||||
ACCESS, SECRET, null, true, "x-amz-acl=public-read&x-id=PutObject"))
|
||||
.PUT(HttpRequest.BodyPublishers.ofByteArray(body)).build(),
|
||||
HttpResponse.BodyHandlers.ofByteArray()));
|
||||
status(403, client.send(HttpRequest.newBuilder(privatePut).header("x-amz-acl", "private")
|
||||
.PUT(HttpRequest.BodyPublishers.ofByteArray(body)).build(),
|
||||
HttpResponse.BodyHandlers.ofByteArray()));
|
||||
status(204, client.send(HttpRequest.newBuilder(presignedUri(privateObject, "DELETE", 60))
|
||||
.DELETE().build(), HttpResponse.BodyHandlers.ofByteArray()));
|
||||
status(403, client.send(HttpRequest.newBuilder(URI.create(sdkGet.toString().replace(
|
||||
"X-Amz-Content-Sha256=UNSIGNED-PAYLOAD", "X-Amz-Content-Sha256=changed")))
|
||||
.GET().build(), HttpResponse.BodyHandlers.ofByteArray()));
|
||||
status(204, client.send(HttpRequest.newBuilder(presignedUriAs(sdkObject, "DELETE", 60,
|
||||
ACCESS, SECRET, null, true)).DELETE().build(), HttpResponse.BodyHandlers.ofByteArray()));
|
||||
URI checksumObject = URI.create(base + "/objects/sdk-v3-checksum");
|
||||
String checksumQuery = "x-amz-checksum-crc32=" +
|
||||
SigV4.encode(encodedChecksum("CRC32", body), false) +
|
||||
"&x-amz-sdk-checksum-algorithm=CRC32&x-id=PutObject";
|
||||
status(200, client.send(HttpRequest.newBuilder(presignedUriAs(checksumObject, "PUT", 60,
|
||||
ACCESS, SECRET, null, true, checksumQuery))
|
||||
.PUT(HttpRequest.BodyPublishers.ofByteArray(body)).build(), HttpResponse.BodyHandlers.ofByteArray()));
|
||||
status(204, client.send(HttpRequest.newBuilder(presignedUri(checksumObject, "DELETE", 60))
|
||||
.DELETE().build(), HttpResponse.BodyHandlers.ofByteArray()));
|
||||
URI tampered = URI.create(presignedUri(object, "GET", 60).toString().replace("presigned-test", "different"));
|
||||
status(403, client.send(HttpRequest.newBuilder(tampered).GET().build(),
|
||||
HttpResponse.BodyHandlers.ofByteArray()));
|
||||
@@ -104,6 +169,7 @@ public final class HttpTest {
|
||||
}
|
||||
|
||||
private static void testAcl(HttpClient client, String base) throws Exception {
|
||||
enableAcl(client, URI.create(base + "/objects"));
|
||||
byte[] body = "private object".getBytes(StandardCharsets.UTF_8);
|
||||
URI object = URI.create(base + "/objects/acl-test");
|
||||
URI objectAcl = URI.create(object + "?acl");
|
||||
@@ -166,6 +232,7 @@ public final class HttpTest {
|
||||
URI historyBucket = URI.create(base + "/acl-history");
|
||||
status(200, client.send(signedUri(historyBucket, "PUT", new byte[0], Map.of()),
|
||||
HttpResponse.BodyHandlers.ofByteArray()));
|
||||
enableAcl(client, historyBucket);
|
||||
byte[] versioning = "<VersioningConfiguration><Status>Enabled</Status></VersioningConfiguration>"
|
||||
.getBytes(StandardCharsets.UTF_8);
|
||||
status(200, client.send(signedUri(URI.create(historyBucket + "?versioning"),
|
||||
@@ -197,6 +264,19 @@ public final class HttpTest {
|
||||
HttpResponse.BodyHandlers.ofByteArray()));
|
||||
}
|
||||
|
||||
private static void enableAcl(HttpClient client, URI bucket) throws Exception {
|
||||
byte[] ownership = ("<OwnershipControls><Rule><ObjectOwnership>ObjectWriter</ObjectOwnership>" +
|
||||
"</Rule></OwnershipControls>").getBytes(StandardCharsets.UTF_8);
|
||||
status(200, client.send(signedUri(URI.create(bucket + "?ownershipControls"),
|
||||
"PUT", ownership, Map.of()), HttpResponse.BodyHandlers.ofByteArray()));
|
||||
byte[] publicAccess = ("<PublicAccessBlockConfiguration><BlockPublicAcls>false</BlockPublicAcls>" +
|
||||
"<IgnorePublicAcls>false</IgnorePublicAcls><BlockPublicPolicy>false</BlockPublicPolicy>" +
|
||||
"<RestrictPublicBuckets>false</RestrictPublicBuckets></PublicAccessBlockConfiguration>")
|
||||
.getBytes(StandardCharsets.UTF_8);
|
||||
status(200, client.send(signedUri(URI.create(bucket + "?publicAccessBlock"),
|
||||
"PUT", publicAccess, Map.of()), HttpResponse.BodyHandlers.ofByteArray()));
|
||||
}
|
||||
|
||||
private static void testStreaming(HttpClient client, String base) throws Exception {
|
||||
URI object = URI.create(base + "/objects/streaming-test");
|
||||
byte[] body = "verified streaming payload".getBytes(StandardCharsets.UTF_8);
|
||||
@@ -274,7 +354,7 @@ public final class HttpTest {
|
||||
String trailerToSign = "AWS4-HMAC-SHA256-TRAILER\n" + date + "\n" + scope + "\n" +
|
||||
previous + "\n" + SigV4.hex(SigV4.hash((trailerName + ":" + checksum + "\n")
|
||||
.getBytes(StandardCharsets.UTF_8)));
|
||||
encoded.write(("x-amz-trailer-signature=" + SigV4.hex(SigV4.hmac(key, trailerToSign)) +
|
||||
encoded.write(("x-amz-trailer-signature:" + SigV4.hex(SigV4.hmac(key, trailerToSign)) +
|
||||
"\r\n\r\n").getBytes(StandardCharsets.US_ASCII));
|
||||
byte[] upload = encoded.toByteArray();
|
||||
HttpRequest.Builder request = HttpRequest.newBuilder(object)
|
||||
@@ -413,7 +493,8 @@ public final class HttpTest {
|
||||
"PUT", body, Map.of("content-type", "text/plain")), HttpResponse.BodyHandlers.ofByteArray()));
|
||||
String header = "/objects/" + SigV4.encode(source, true);
|
||||
var result = client.send(signedUri(URI.create(base + "/objects/" + target), "PUT",
|
||||
new byte[0], Map.of("x-amz-copy-source", header)), HttpResponse.BodyHandlers.ofString());
|
||||
new byte[0], Map.of("x-amz-copy-source", header,
|
||||
"content-type", "application/x-sdk-copy")), HttpResponse.BodyHandlers.ofString());
|
||||
if (result.statusCode() != 200 || !result.body().contains("<CopyObjectResult>") ||
|
||||
!result.body().contains("<ETag>""))
|
||||
throw new AssertionError("CopyObject failed: " + result.body());
|
||||
@@ -536,18 +617,32 @@ public final class HttpTest {
|
||||
}
|
||||
|
||||
private static void testMultipart(HttpClient client, String base) throws Exception {
|
||||
URI endpoint = ObjectStoreServer.publicEndpoint(Map.of("S3_PUBLIC_ENDPOINT", "https://s3.example.test/"));
|
||||
if (!"https://s3.example.test/objects/folder/a%20b.mp4".equals(
|
||||
MultipartHandler.objectLocation(endpoint, "127.0.0.1:9000", "http",
|
||||
"/objects/folder/a%20b.mp4", "objects", "folder/a b.mp4")))
|
||||
throw new AssertionError("Configured multipart location is incorrect");
|
||||
try {
|
||||
ObjectStoreServer.publicEndpoint(Map.of("S3_PUBLIC_ENDPOINT", "https://s3.example.test/subpath"));
|
||||
throw new AssertionError("Public endpoint with a path was accepted");
|
||||
} catch (IllegalArgumentException expected) { }
|
||||
String movie = "folder/video.mp4";
|
||||
URI initiate = URI.create(base + "/objects/" + movie + "?uploads=");
|
||||
var created = client.send(signedUri(initiate, "POST", new byte[0],
|
||||
Map.of("content-type", "video/mp4")), HttpResponse.BodyHandlers.ofString());
|
||||
Map.of("content-type", "video/mp4", "x-amz-checksum-algorithm", "CRC32")),
|
||||
HttpResponse.BodyHandlers.ofString());
|
||||
if (created.statusCode() != 200) throw new AssertionError("Multipart initiation failed: " + created.body());
|
||||
String upload = created.body().split("<UploadId>")[1].split("</UploadId>")[0];
|
||||
byte[] first = "hello ".getBytes(StandardCharsets.UTF_8);
|
||||
byte[] second = "world".getBytes(StandardCharsets.UTF_8);
|
||||
var partOne = client.send(signedUri(URI.create(base + "/objects/" + movie +
|
||||
"?partNumber=1&uploadId=" + upload), "PUT", first, Map.of()), HttpResponse.BodyHandlers.ofByteArray());
|
||||
"?partNumber=1&uploadId=" + upload), "PUT", first,
|
||||
Map.of("x-amz-checksum-crc32", encodedChecksum("CRC32", first),
|
||||
"x-amz-sdk-checksum-algorithm", "CRC32")), HttpResponse.BodyHandlers.ofByteArray());
|
||||
var partTwo = client.send(signedUri(URI.create(base + "/objects/" + movie +
|
||||
"?partNumber=2&uploadId=" + upload), "PUT", second, Map.of()), HttpResponse.BodyHandlers.ofByteArray());
|
||||
"?partNumber=2&uploadId=" + upload), "PUT", second,
|
||||
Map.of("x-amz-checksum-crc32", encodedChecksum("CRC32", second),
|
||||
"x-amz-sdk-checksum-algorithm", "CRC32")), HttpResponse.BodyHandlers.ofByteArray());
|
||||
status(200, partOne);
|
||||
status(200, partTwo);
|
||||
var rejectedPart = client.send(signedUri(URI.create(base + "/objects/" + movie +
|
||||
@@ -567,11 +662,20 @@ public final class HttpTest {
|
||||
throw new AssertionError("Multipart upload listing failed: " + uploads.body());
|
||||
String completion = "<CompleteMultipartUpload><Part><PartNumber>1</PartNumber><ETag>" +
|
||||
partOne.headers().firstValue("etag").orElseThrow() +
|
||||
"</ETag></Part><Part><PartNumber>2</PartNumber><ETag>" +
|
||||
"</ETag><ChecksumCRC32>" + encodedChecksum("CRC32", first) +
|
||||
"</ChecksumCRC32></Part><Part><PartNumber>2</PartNumber><ETag>" +
|
||||
partTwo.headers().firstValue("etag").orElseThrow() +
|
||||
"</ETag></Part></CompleteMultipartUpload>";
|
||||
status(200, client.send(signedUri(URI.create(base + "/objects/" + movie + "?uploadId=" + upload),
|
||||
"POST", completion.getBytes(StandardCharsets.UTF_8), Map.of()), HttpResponse.BodyHandlers.ofByteArray()));
|
||||
"</ETag><ChecksumCRC32>" + encodedChecksum("CRC32", second) +
|
||||
"</ChecksumCRC32></Part></CompleteMultipartUpload>";
|
||||
String mismatched = completion.replace(encodedChecksum("CRC32", first), "AAAAAA==");
|
||||
status(400, client.send(signedUri(URI.create(base + "/objects/" + movie + "?uploadId=" + upload),
|
||||
"POST", mismatched.getBytes(StandardCharsets.UTF_8), Map.of()),
|
||||
HttpResponse.BodyHandlers.ofString()));
|
||||
var completed = client.send(signedUri(URI.create(base + "/objects/" + movie + "?uploadId=" + upload),
|
||||
"POST", completion.getBytes(StandardCharsets.UTF_8), Map.of()), HttpResponse.BodyHandlers.ofString());
|
||||
status(200, completed);
|
||||
if (!completed.body().contains("<Location>" + base + "/objects/" + movie + "</Location>"))
|
||||
throw new AssertionError("Multipart completion omitted the object location: " + completed.body());
|
||||
var assembled = client.send(signed(base, "GET", movie, new byte[0]), HttpResponse.BodyHandlers.ofByteArray());
|
||||
status(200, assembled);
|
||||
if (!"hello world".equals(new String(assembled.body(), StandardCharsets.UTF_8)) ||
|
||||
|
||||
@@ -85,7 +85,7 @@ public final class StoreTest {
|
||||
withTrailer.write(body, 65536, 1024);
|
||||
withTrailer.write("\r\n0;chunk-signature=2ca2aba2005185cf7159c6277faf83795951dd77a3a99e6e65d5c9f85863f992\r\n".getBytes());
|
||||
withTrailer.write("x-amz-checksum-crc32c:sOO8/Q==\r\n".getBytes());
|
||||
withTrailer.write("x-amz-trailer-signature=d81f82fc3505edab99d459891051a732e8730629a2e4a59689829ca17fe2e435\r\n\r\n".getBytes());
|
||||
withTrailer.write("x-amz-trailer-signature:d81f82fc3505edab99d459891051a732e8730629a2e4a59689829ca17fe2e435\r\n\r\n".getBytes());
|
||||
var trailerAuthorization = new SigV4.Verified("STREAMING-AWS4-HMAC-SHA256-PAYLOAD-TRAILER",
|
||||
"", key, date, scope, "106e2a8a18243abcf37539882f36619c00e2dfc72633413f02d3b74544bfeb8e");
|
||||
try (var stream = new AwsChunkedInputStream(new ByteArrayInputStream(withTrailer.toByteArray()),
|
||||
@@ -295,6 +295,40 @@ public final class StoreTest {
|
||||
}
|
||||
}
|
||||
|
||||
private static void testBucketAccessUpgrade(Path root) throws Exception {
|
||||
Path data = Files.createDirectory(root.resolve("bucket-access-upgrade"));
|
||||
try (var output = new DataOutputStream(Files.newOutputStream(data.resolve("buckets.bin")))) {
|
||||
output.writeInt(0x4c534245);
|
||||
output.writeInt(1);
|
||||
output.writeUTF("legacy-bucket");
|
||||
output.writeLong(System.currentTimeMillis());
|
||||
output.writeByte(0);
|
||||
output.writeShort(0);
|
||||
}
|
||||
try (var store = new DiskStore(data, 8, 16)) {
|
||||
var legacy = store.bucket("legacy-bucket");
|
||||
if (legacy.ownership() != ObjectStorage.ObjectOwnership.OBJECT_WRITER ||
|
||||
legacy.publicAccessBlock().blockPublicAcls())
|
||||
throw new AssertionError("Existing bucket access changed during upgrade");
|
||||
store.createBucket("new-bucket");
|
||||
if (store.bucket("new-bucket").ownership() !=
|
||||
ObjectStorage.ObjectOwnership.BUCKET_OWNER_ENFORCED ||
|
||||
!store.bucket("new-bucket").publicAccessBlock().blockPublicPolicy())
|
||||
throw new AssertionError("New bucket did not use secure defaults");
|
||||
store.setBucketPolicy("legacy-bucket", "{\"Version\":\"2012-10-17\"," +
|
||||
"\"Statement\":{\"Effect\":\"Deny\",\"Principal\":\"*\"," +
|
||||
"\"Action\":\"s3:GetObject\",\"Resource\":\"arn:aws:s3:::legacy-bucket/*\"}}");
|
||||
}
|
||||
try (var store = new DiskStore(data, 8, 16)) {
|
||||
if (store.bucket("legacy-bucket").ownership() !=
|
||||
ObjectStorage.ObjectOwnership.OBJECT_WRITER ||
|
||||
store.bucket("legacy-bucket").policy() == null ||
|
||||
store.bucket("new-bucket").ownership() !=
|
||||
ObjectStorage.ObjectOwnership.BUCKET_OWNER_ENFORCED)
|
||||
throw new AssertionError("Bucket access settings were not durable");
|
||||
}
|
||||
}
|
||||
|
||||
private static void testAclPersistence(Path root) throws Exception {
|
||||
Path data = root.resolve("acl");
|
||||
Map<String, String> grant = Map.of("SECONDARYKEY1234", Integer.toString(Acl.READ));
|
||||
@@ -328,14 +362,14 @@ public final class StoreTest {
|
||||
private static void testAdditionalKeys(Path root) throws Exception {
|
||||
Path file = root.resolve("access-keys");
|
||||
Files.writeString(file, "SECONDARYKEY1234:secondary-secret-key-that-is-at-least-32-characters\n");
|
||||
Map<String, String> keys = Main.identities(
|
||||
Map<String, String> keys = ObjectStoreServer.identities(
|
||||
Map.of("S3_CREDENTIALS_FILE", file.toString()),
|
||||
"TESTACCESSKEY123", "test-secret-key-that-is-at-least-32-characters");
|
||||
if (keys.size() != 2 || !keys.containsKey("SECONDARYKEY1234"))
|
||||
throw new AssertionError("Additional access key was not loaded");
|
||||
Files.writeString(file, "TESTACCESSKEY123:duplicate-root-secret-that-is-at-least-32-characters\n");
|
||||
try {
|
||||
Main.identities(Map.of("S3_CREDENTIALS_FILE", file.toString()),
|
||||
ObjectStoreServer.identities(Map.of("S3_CREDENTIALS_FILE", file.toString()),
|
||||
"TESTACCESSKEY123", "test-secret-key-that-is-at-least-32-characters");
|
||||
throw new AssertionError("Duplicate root key was accepted");
|
||||
} catch (IllegalArgumentException expected) { }
|
||||
@@ -423,6 +457,7 @@ public final class StoreTest {
|
||||
testAttributesRestart(root);
|
||||
testV3Record(root);
|
||||
testBucketRestart(root);
|
||||
testBucketAccessUpgrade(root);
|
||||
testAclPersistence(root);
|
||||
testAdditionalKeys(root);
|
||||
testVersioning(root);
|
||||
|
||||
Reference in new issue
Block a user