Add shared cluster credentials and readiness CI
ObjectStore CI / build (push) Successful in 10m22s

This commit is contained in:
admin committed 2026-11-16 03:41:32 +01:00
1 parent b724a21a0d
commit d73fa2c435
45 files changed
+2733 -226

No files matched your search

+71
View File
@@ -0,0 +1,71 @@
name: ObjectStore CI
on:
push:
workflow_dispatch:
permissions:
code: read
jobs:
build:
runs-on: objectstore-ci
timeout-minutes: 60
env:
COMPOSE_PARALLEL_LIMIT: '1'
CARGO_BUILD_JOBS: '1'
CARGO_PROFILE_DEV_DEBUG: '0'
CARGO_PROFILE_TEST_DEBUG: '0'
JAVA_TOOL_OPTIONS: -Xmx384m -XX:ActiveProcessorCount=2
steps:
- name: Check out source
uses: https://github.com/actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803
with:
persist-credentials: false
- name: Install Java 21
uses: https://github.com/actions/setup-java@d1374f8ac74474200d16ef8ecee22c7ae7a51880
with:
distribution: temurin
java-version: '21'
- name: Java service and client tests
run: sh scripts/test.sh
- name: Packaging and test runner checks
run: |
python3 client/scripts/test-packaging.py
python3 scripts/test-readiness.py
node test/admin-workspace.test.cjs
- name: Install Rust
uses: https://github.com/dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca
with:
toolchain: '1.99.1'
- name: Rust client tests
run: cargo test --locked --manifest-path rust-client/Cargo.toml
- name: Build Docker image
run: docker build -t objectstore-test:ci .
- name: Cluster metadata tests
run: sh scripts/test-metadata.sh
env:
OBJECTSTORE_TEST_IMAGE: objectstore-test:ci
- name: Crash and restore tests
run: python3 scripts/test-recovery.py --image objectstore-test:ci --output out/recovery-ci
- name: Metadata failover tests
run: python3 scripts/test-ha.py --image objectstore-test:ci --output out/ha-ci.json
- name: Package Java client
run: bash client/scripts/build-maven-repo.sh
- name: Save Java packages
uses: https://github.com/actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02
with:
name: objectstore-java-client
path: client/dist/maven-repo/
if-no-files-found: error
retention-days: 14
- name: Save test reports
if: always()
uses: https://github.com/actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02
with:
name: readiness-reports
path: |
out/ha-ci.json
out/recovery-ci/**/*.json
if-no-files-found: warn
retention-days: 14
+20 -1
View File
@@ -3,6 +3,7 @@ name: Tests
on:
push:
pull_request:
workflow_dispatch:
permissions:
contents: read
@@ -10,6 +11,7 @@ permissions:
jobs:
java:
runs-on: ubuntu-latest
timeout-minutes: 25
steps:
- uses: actions/checkout@v7
- uses: actions/setup-java@v6
@@ -17,4 +19,21 @@ jobs:
distribution: temurin
java-version: '21'
- run: sh scripts/test.sh
- run: docker build .
- run: python3 client/scripts/test-packaging.py
- run: python3 scripts/test-readiness.py
- run: node test/admin-workspace.test.cjs
- run: docker build -t objectstore-test:ci .
- run: sh scripts/test-metadata.sh
env:
OBJECTSTORE_TEST_IMAGE: objectstore-test:ci
- run: python3 scripts/test-recovery.py --image objectstore-test:ci --output out/recovery-ci
- run: python3 scripts/test-ha.py --image objectstore-test:ci --output out/ha-ci.json
- uses: actions/upload-artifact@v7
if: always()
with:
name: readiness-reports
path: |
out/ha-ci.json
out/recovery-ci/**/*.json
if-no-files-found: ignore
retention-days: 14
+2
View File
@@ -1,5 +1,6 @@
FROM eclipse-temurin:21-jdk-alpine AS build
WORKDIR /src
ENV JAVA_TOOL_OPTIONS="-Xmx384m -XX:ActiveProcessorCount=2"
RUN wget -q -O /tmp/postgresql.jar https://jdbc.postgresql.org/download/postgresql-42.7.14.jar && \
echo '73914527305a40cce504b0d3d90b23caf565136912d607ae8ae7c5895512332c /tmp/postgresql.jar' | sha256sum -c -
COPY src ./src
@@ -9,6 +10,7 @@ COPY lib/hash4j-0.30.0.jar /tmp/hash4j.jar
RUN echo 'd3224b113ea835ce3452097747e5209ec760cf443dbed770d6ba68a0d480178f /tmp/hash4j.jar' | sha256sum -c -
RUN mkdir /out && javac --release 21 --add-modules jdk.httpserver,java.net.http -cp /tmp/hash4j.jar -d /out src/cloud/lunarsky/store/*.java test/cloud/lunarsky/store/*.java
RUN java --add-modules jdk.httpserver -cp /out:/tmp/hash4j.jar cloud.lunarsky.store.StoreTest
RUN java -Xmx32m --add-modules jdk.httpserver,java.net.http -cp /out:/tmp/hash4j.jar cloud.lunarsky.store.LargeObjectTest
RUN java --add-modules jdk.httpserver -cp /out:/tmp/hash4j.jar cloud.lunarsky.store.DiskBucketNamesTest
RUN java --add-modules jdk.httpserver -cp /out:/tmp/hash4j.jar cloud.lunarsky.store.ConditionalEditTest
RUN java -cp /out:/tmp/hash4j.jar cloud.lunarsky.store.ClusterRepairCliTest
+14 -6
View File
@@ -61,7 +61,7 @@ Run `sh scripts/test.sh` with JDK 21 to test from source. See [TESTS.md](TESTS.m
`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.
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 64 GiB (`68719476736` bytes); `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.
@@ -75,7 +75,7 @@ Audit & access shows the last 100 admin events and S3 request counts by authenti
Bulk jobs can export a CSV inventory, copy between buckets, set one tag, or delete current objects under a prefix. One job runs at a time per gateway, with at most 10,000 objects per job. Copy uses create-only writes, so existing destination keys are reported as errors rather than overwritten. Delete follows the bucket's versioning rules; it may create delete markers. Cancellation takes effect between objects. Progress and a CSV result report are available in the console, but job history and reports are held in bounded memory and disappear on restart. Narrow the prefix before running a large or destructive job, and use the report to inspect partial failures.
The Cluster page appears in both modes; disk mode explains that no cluster is configured. In cluster mode it shows a diagram of the metadata primary and up to 64 storage nodes. Node probes run concurrently with a 2-second timeout and the result is cached for 15 seconds. Repair progress is written to the metadata database at most every 256 segments or five seconds. A running report older than five minutes is marked as possibly interrupted. Per-node verified replica counts are saved after a completed pass. Counts describe that pass, not a live replica inventory. The cluster maintenance service still performs repair separately; opening the page does not start it. Schema version 14 stores this status.
The Cluster page appears in both modes; disk mode explains that no cluster is configured. In cluster mode it shows a diagram of the metadata primary and up to 64 storage nodes. Node probes run concurrently with a 2-second timeout and the result is cached for 15 seconds. Repair progress is written to the metadata database at most every 256 segments or five seconds. A running report older than five minutes is marked as possibly interrupted. Per-node verified replica counts are saved after a completed pass. Counts describe that pass, not a live replica inventory. The cluster maintenance service still performs repair separately; opening the page does not start it. Schema migration 14 introduced this status.
Renaming a populated bucket keeps its objects, versions, tags, ACLs, and active multipart uploads, but the old URL and presigned links stop working. In disk mode the stored data keeps a stable internal name; include `bucket-names.txt` with the data volume in backups. In cluster mode the metadata rename is one database transaction and can briefly pause requests. Move or remove console-managed scoped keys first. Update external key scopes, policies, clients, and `S3_BUCKET` if it names the renamed bucket before restarting.
@@ -99,7 +99,13 @@ chmod 644 secrets/managed-master
docker compose -f compose.yaml -f compose.admin.yaml -f compose.credentials.yaml up -d --build
```
The master key is mounted read-only; the encrypted key database is stored in the `object-data` volume. Back up **both** the data volume and `secrets/managed-master`. Losing the master key makes managed S3 credentials unrecoverable. A key is scoped to one bucket and optional prefix, with separate read, write, and list permissions. Its secret appears once when created. The console can change its scope or permissions, disable it, or delete it; disabling or deleting rejects new signed requests. Existing keys configured in `.env` or credential files still need manual management. This local key manager currently supports disk mode only; the cluster requires externally managed identities, because gateways do not share this credential database.
The master key is mounted read-only; the encrypted key database is stored in the `object-data` volume. Back up **both** the data volume and `secrets/managed-master`. Losing the master key makes managed S3 credentials unrecoverable. A key is scoped to one bucket and optional prefix, with separate read, write, and list permissions. Its secret appears once when created. The console can change its scope or permissions, disable it, or delete it; disabling or deleting rejects new signed requests. Existing keys configured in `.env` or credential files still need manual management.
Cluster gateways instead share an AES-GCM-encrypted credential registry in PostgreSQL (schema 15). Add `compose.cluster.credentials.yaml` to your cluster Compose command and mount the **same** master file on every gateway. The cluster overlay only supplies this mount; configure the separate admin listener and its password as described above. Upgrade all gateways together: older builds do not understand this registry and refuse schema 15 on startup. Take a metadata backup before upgrading; rollback requires restoring a compatible backup.
Back up the cluster metadata and keep a separate secure copy of the master key. Replacing the master file is not key rotation: the wrong key prevents startup. There is no automatic import from the disk-mode registry. After restoring older metadata, stop and restart all gateways together and reconcile keys revoked since the backup before accepting traffic.
Each request signed with a managed key checks the writable primary's registry revision. Its signature, policy, and scope checks use one immutable snapshot. Disabling or deleting a key rejects subsequent requests across gateways; already admitted requests can finish. Unavailable, read-only, or backward-moving credential metadata fails closed. Configured static keys, session keys, and anonymous requests avoid this extra registry query. Registry updates are transactional; bucket rename/delete is blocked while any managed key references that bucket, including disabled keys. The limit remains 64 managed keys, with bucket/prefix and read/write/list scope; this is not full IAM. Admin branding, activity, and audit files remain local to each gateway.
The admin Compose overlay maps host port 9001 to a separate admin-only listener, bound to loopback by default. Admin paths return 404 on the S3 port; S3 paths return 404 on the admin port. The console accepts only loopback Host values by default, including if a 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.
@@ -160,7 +166,7 @@ CLUSTER_TLS_DIR=/private/objectstore-certs docker compose --env-file /path/to/cl
The files must be readable by container UID 10001 without making private keys or passwords world-readable. Add HTTPS URLs for additional nodes when expanding the cluster.
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.
This secures node traffic only. The base local cluster uses one PostgreSQL instance; the separate [metadata HA drill](tests/ha/README.md) exercises automatic failover with Patroni. 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
@@ -172,6 +178,8 @@ jdbc:postgresql://db-a:5432,db-b:5432/objectstore?targetServerType=primary&conne
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.
The [Patroni reference and failover drill](tests/ha/README.md) supplies a reproducible local setup with three metadata members, three etcd voters, and strict synchronous replication. It verifies primary loss, automatic promotion without restarting the gateway, old-primary rejoin, and refusal to acknowledge writes without synchronous replicas or after DCS quorum loss. Run it with `python3 scripts/test-ha.py --output out/ha-report.json`. Its test credentials, unencrypted internal network, and disabled watchdog are deliberately limited to disposable local tests. Separate-machine operation requires TLS, host fencing, durable storage, and independent recovery testing.
## Migrating a local cluster
For an existing **local** three-node cluster that stores replicas by URL position:
@@ -204,7 +212,7 @@ The maintenance service is opt-in. It repairs missing or corrupt replicas and re
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.
`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` supports 1 byte through 64 GiB; `MAX_TOTAL_BYTES` must be at least that value. Payloads stream through fixed buffers (64 KiB at the gateway and 8 MiB cluster segments), but cluster manifests remain in memory. The ceiling limits manifest size; this is not support for every S3 object size. Cluster uploads also stage a full object in the gateway temporary directory before replication. Allow temporary disk space for concurrent uploads, and allow space for staged multipart parts plus the completed copy in disk mode. Raising a quota does not reserve physical disk space.
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.
@@ -216,6 +224,6 @@ ObjectStore uses the socket peer as the client IP and ignores forwarded-IP heade
Enable these limits only on a deliberately public endpoint. They also apply to direct localhost storage calls to that same endpoint; leave them disabled for the local-only setup or run a separate local-only instance if local storage calls must be exempt. A direct loopback `/health` probe without a forwarded-IP header remains exempt. The byte limit is aggregate ingress plus egress for each IP, and several users behind one NAT share it. If a proxy buffers complete uploads before forwarding them, the upload byte limit controls proxy-to-ObjectStore traffic, not the client's initial upload speed; disable request buffering when end-to-end upload pacing is required. It is a fairness control, not a defense against connection floods before the Java handler runs. Put an internet-facing proxy or firewall in front of the gateway for TLS, connection limits, request timeouts, and buffering controls. Do not expose storage nodes or PostgreSQL publicly.
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 default local cluster still uses plaintext node and PostgreSQL connections. The optional TLS overlay secures node traffic; PostgreSQL TLS and HA remain separately operated components. A disposable Patroni HA reference is included, but 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.
+20 -6
View File
@@ -4,13 +4,15 @@
Small S3-compatible object storage for LunarSky.
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/)
Source: [GitHub](https://github.com/LunarSkyOSS/ObjectStore) · [Gitea mirror](https://git.lunarsky.cloud/admin/ObjectStore)
Current source docs: [Operations](OPERATIONS.md) · [Java client](client/README.md) · [Rust client](rust-client/README.md) · [Tests](TESTS.md)
**Development software. Do not use it for production data.** It is provided as is, without warranty, under the [MIT License](LICENSE).
[![Stage: development](assets/badge-stage.svg)](OPERATIONS.md#limits-and-safety) [![License: MIT](assets/badge-license.svg)](LICENSE) [![Runtime: Java 21](assets/badge-java.svg)](Dockerfile) [![S3 API: partial support](assets/badge-api.svg)](#s3-api-support-checklist) [![CodeFactor](https://www.codefactor.io/repository/github/lunarskyoss/objectstore/badge)](https://www.codefactor.io/repository/github/lunarskyoss/objectstore)
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.
The hosted [v0.0.8 docs](https://docs.lunarsky.cloud/objectstore/v0.0.8/) describe an older release. Use the source docs above for this checkout's behavior and limitations.
## Capability checklist
@@ -23,7 +25,9 @@ ObjectStore creates the default bucket at startup. All buckets share one capacit
- ✅ 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
- ✅ Shared encrypted managed credentials across cluster gateways
- ✅ Disposable [metadata failover and recovery tests](TESTS.md#metadata-high-availability-drill)
- ⬜ Production multi-server validation across independent machines
Legacy single-node objects remain readable but stay out of listings until overwritten because their keys were not stored.
@@ -80,7 +84,7 @@ Port 9000 binds to localhost. Data stays in the `object-data` Docker volume. `do
The optional [local admin console](OPERATIONS.md#local-admin-console) manages buckets, ACLs, policies, scoped keys, bulk jobs, access checks, and live performance. It has its own password and is disabled in the base Compose stack.
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.
The standalone defaults are 128 MiB per object and 2 GiB total. Set `MAX_OBJECT_BYTES` (up to 64 GiB) and `MAX_TOTAL_BYTES` in `.env` to change them. The total must be at least the object limit. Incomplete multipart uploads consume space until aborted.
## Operations
@@ -88,7 +92,17 @@ The [operations guide](OPERATIONS.md) covers encrypted mounts, access keys and A
## Java client
The [JDK-only Java client](client/README.md) works with ObjectStore and other S3-compatible endpoints. Version 0.0.8 is available from `https://repo.lunarsky.cloud/` without an account. Add that URL as a Maven repository, then use `cloud.lunarsky:objectstore-client:0.0.8`.
The [JDK-only Java client](client/README.md) works with ObjectStore and other S3-compatible endpoints. Build the current source with JDK 21 or newer:
```sh
bash client/scripts/build-maven-repo.sh
```
This creates the client JAR, Javadocs, and a local Maven repository under `client/dist/`, using the checkout's version. It does not publish anything.
### Older published package (0.0.8)
Version 0.0.8 is available from `https://repo.lunarsky.cloud/` without an account. The following examples install that older release, not the current source:
Gradle (Kotlin DSL):
@@ -119,7 +133,7 @@ Maven (`pom.xml`):
</dependencies>
```
See [client installation and examples](https://docs.lunarsky.cloud/objectstore/v0.0.8/client/install). The [AWT image manager](client/examples/README.md) is a small desktop example.
See [current client usage and limits](client/README.md). The [AWT image manager](client/examples/README.md) is a small desktop example.
## Rust client
+67 -4
View File
@@ -4,6 +4,14 @@ ObjectStore is development software. Do not use it for production data. It is pr
Run the commands below from the repository root.
## Gitea CI
`.gitea/workflows/ci.yml` runs Java and Rust client tests, packaging checks, the
Docker build, and metadata/recovery/failover tests sequentially on the
`objectstore-ci` runner. It runs on pushes and manual dispatch, not public fork
pull requests. Java packages and JSON test reports are saved as build artifacts
for 14 days. CI does not publish releases or overwrite package registries.
## Source tests
Requires JDK 21. No Docker service is needed.
@@ -17,6 +25,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. |
| `LargeObjectTest` | Configured large-object boundaries, bounded streaming buffers, truncated oversized PUT and multipart bodies, and sparse-file reads, ranges, restart, and deletion above 2 GiB with a small heap. Sparse files exercise offsets without writing gigabytes of payload. |
| `DiskBucketNamesTest` | Renaming a populated bucket while retaining versions, policies, and multipart uploads across restarts; default-bucket startup, deletion recovery, and old-name rejection. |
| `ConditionalEditTest` | Atomic editor saves, concurrent uploads, changed ACLs/tags, versioning changes, and renamed buckets. |
| `ClusterRepairCliTest` | Repair CLI entrypoint and argument validation. |
@@ -42,11 +51,65 @@ The local installer was also checked with a disposable Compose project and separ
The encrypted Compose overlays can be checked with `docker compose config` without starting the stack. This verifies their bind mounts and startup settings, not that a host filesystem is actually encrypted. `scripts/prepare-encrypted-storage.sh` must also verify an active dm-crypt-backed mount. A complete deployment drill must unlock it, prepare directories, start with the overlay, write data, restart, restore from backup, and confirm that the stack refuses to start while the mount is unavailable. Do not point that drill at existing data.
Run `python3 client/scripts/test-packaging.py` to build the Java client twice and verify source-derived versions, embedded license notices, Maven metadata, checksums, and rejection of mislabeled versions. This does not publish artifacts.
Run `node test/admin-workspace.test.cjs` with Node.js to check that a late access-check response cannot replace a newer page after navigation. This test uses a small DOM harness and does not require a browser.
## Bounded workloads and recovery checks
Requires Python 3.9 or newer. Run `python3 scripts/test-readiness.py` for the runner's own checks: byte caps, corrupt/missing objects, ownership protection, cleanup isolation, and incomplete-manifest rejection.
`scripts/readiness.py` creates a uniquely named test bucket. It repeatedly uploads an object, checks its SHA-256 on download, checks HEAD, and deletes three out of every four objects. Retained objects allow a separate integrity check after a restart or restore. Existing buckets are not selected. Set `S3_ACCESS_KEY` and `S3_SECRET_KEY` in the environment for a **test service**, then run:
```sh
python3 scripts/readiness.py run \
--endpoint http://127.0.0.1:9000 --output out/readiness-short \
--duration 30 --concurrency 4 --size 4096 \
--max-write-bytes 16777216 --max-objects 4096
python3 scripts/readiness.py verify --manifest out/readiness-short/manifest.json
python3 scripts/readiness.py cleanup --manifest out/readiness-short/manifest.json
```
The output directory must be new. `report.json` records the exact settings, duration, stop reason, per-operation successes and failures, status counts, payload throughput, and latency histograms. Percentiles are upper bounds from bins no wider than 10%; they include failed attempts. These numbers describe the tested machine and workload, not a service-wide performance guarantee. The write budget counts attempted workload payload, including failed PUTs; the 32-byte ownership marker, filesystem metadata, replicas, and backups consume additional bytes. The runner also caps concurrency at 32, object size at 1 MiB, total attempted payload at 1 GiB, and object count at 100,000. Verification and cleanup stop after ten failed requests and exit nonzero.
A paced soak uses the same runner, for example:
```sh
python3 scripts/readiness.py run \
--endpoint http://127.0.0.1:9000 --output out/readiness-soak \
--duration 1800 --writes-per-second 2 --concurrency 2 \
--max-write-bytes 67108864 --max-objects 16384
```
The run stops when its duration, byte budget, or object budget is reached. A 30-minute run at two 4-KiB writes per second attempts about 14 MiB of payload. Budget exhaustion is reported explicitly; a short run is not a completed long soak. Use HTTPS for non-loopback endpoints. Credentials never go into the report or manifest.
For a service interruption, add `--retain-all` to avoid ambiguous unacknowledged deletes. Keep the runner alive on a separate machine while interrupting only the disposable test service. Verification requires a completed manifest and checks every retained acknowledged PUT; failed PUTs may or may not have reached the service. The manifest is saved when the runner completes, so killing the runner itself cannot establish durability. `verify --endpoint https://restored.example` checks a separately restored service against that same manifest. `cleanup` checks the ownership marker and deletes only keys recorded by that run; it refuses to remove a bucket containing unrelated objects. Versioning should remain disabled on the disposable test bucket.
An automated **single-machine** crash and cold-restore drill creates its own labelled containers, fresh volumes, credentials, and random loopback ports:
```sh
docker build -t objectstore-readiness:local .
python3 scripts/test-recovery.py --image objectstore-readiness:local \
--output out/recovery-check
```
The drill first verifies twenty retained objects, then sends a ten-second workload capped at 2 MiB of attempted payload, kills only its own service container, restarts it, and verifies acknowledged data. It then stops the source, exports its volume, restores into a separate empty volume, starts a second service, and verifies the same data, including the twenty objects acknowledged before the crash. Its `summary.json` records the image digest, snapshot digest, outcome, and cleanup status. Containers and volumes are removed by exact ownership label; reports and the small snapshot remain in the specified directory. It never restarts a host or uses an existing service. This is a local cold-volume restore, not a live multi-host or off-site backup test.
## Disposable metadata routing test
Run `sh scripts/test-metadata.sh` with Docker Compose. It creates a separate, temporary PostgreSQL container and two in-process storage nodes. The test connects through a two-host JDBC URL whose first host is unavailable, checks writable readiness, then makes the test database read-only and verifies that readiness drops. The script removes its test containers and temporary database afterward. It does not promote a standby or test automatic failover.
Run `sh scripts/test-metadata.sh` with Docker Compose. It creates a separate, temporary PostgreSQL container and two in-process storage nodes. The test connects through a two-host JDBC URL whose first host is unavailable, checks writable readiness, then makes the test database read-only and verifies that readiness drops. The script removes its test containers and temporary database afterward. It also tests shared encrypted credentials through two HTTP gateways, scoped access, cross-gateway revocation, immutable request snapshots, concurrent edits, stale-read and revision-rollback rejection, and bucket rename/delete guards. It does not promote a standby; the separate drill below covers that. Set `OBJECTSTORE_TEST_IMAGE` to an image already built from this checkout to avoid rebuilding.
## Metadata high availability drill
With Docker Compose and Python installed, run:
```sh
python3 scripts/test-ha.py --output out/ha-report.json
```
Use `--image objectstore-test:local` to reuse a freshly built image. The drill creates an isolated Patroni/PostgreSQL cluster with three etcd voters, two storage nodes, and one gateway. It checks automatic promotion after primary termination, reconnection without restarting the gateway, old-primary rejoin, refusal to acknowledge writes without synchronous replicas, and recovery after losing DCS quorum. SHA-256 verification covers objects acknowledged before and after failover. Cleanup removes only the uniquely named test project and its volumes; failure to clean up fails the run.
This runs on one physical machine. It does not prove fencing, independent failure domains, or network-partition behavior across real hosts. The [HA reference](tests/ha/README.md) explains its test-only credentials, plaintext internal connections, disabled watchdog, and deployment requirements. Run it separately from other builds or drills on a memory-constrained machine. CI runs the build, metadata, recovery, and HA checks sequentially and retains JSON reports.
## Disposable Docker cluster tests
@@ -73,7 +136,7 @@ If port 9001 is occupied, set `CLUSTER_HOST_PORT` to the same free port in both
The Docker suite checks signed capability discovery and S3 operations, bucket creation and deletion, metadata and tags, public-read ACLs and anonymous access, copies, upload checksums, multi-segment objects, concurrent overwrites, multipart staging and listings, versioned reads and delete markers, versioned multipart completion, completion after a gateway restart and node loss, reads and writes with a node stopped, refusal to write without a storage quorum, restart recovery, corrupt-replica repair including staged parts, metadata unavailability, read-only metadata readiness rejection, and placement on a newly joined node. It then checks rebalance to the fourth node, automatic repair, garbage collection dry run and delayed deletion, and a metadata backup restored to a separate PostgreSQL instance while the original database is stopped. A two-host JDBC URL selects that restored writable database. Historical regular and multipart versions are checked after repair and cleanup. It also checks that containers labeled as one physical host cannot satisfy the normal host quorum. Its local-only override permits the remaining phases to use containers as separate test domains.
`ClusterMigrationTest` is a separate legacy-format fixture and is **not** run by either test script. Do not run its `create` phase against a populated metadata database. The migration procedure is in the [README](README.md#migrating-a-local-cluster).
`ClusterMigrationTest` is a separate legacy-format fixture and is **not** run by either test script. Do not run its `create` phase against a populated metadata database. The migration procedure is in the [README](OPERATIONS.md#migrating-a-local-cluster).
`ClusterBucketRenameTest` is another standalone test for a fresh, disposable PostgreSQL database. It checks the transaction, metadata tables, duplicate-name rollback, restart, and refusal to recreate a renamed default bucket. Never point it at an existing metadata database.
@@ -87,6 +150,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. `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.
- The local HA drill tests automatic metadata failover with disposable containers. The suite does not prove an off-site backup restore, prolonged production load, or full AWS S3 compatibility. `scripts/test.sh` checks scoped keys, CORS, and metrics. A separate local cold-snapshot drill restored one object into fresh single-node and cluster Compose projects and confirmed its bytes; the single-node restore also refused a nonempty destination. This does not test a multi-host restore. The Rust client passed live local upload/download and presigned GET/PUT smoke tests, but is not covered by the Java test script.
See [Limits and safety](README.md#limits-and-safety) before evaluating any multi-server deployment.
See [Limits and safety](OPERATIONS.md#limits-and-safety) before evaluating any multi-server deployment.
+17 -7
View File
@@ -6,20 +6,30 @@ A small, synchronous S3-compatible client built with the JDK alone. It uses path
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).
This file and the generated Javadocs describe the current source. The hosted
[installation examples](https://docs.lunarsky.cloud/objectstore/v0.0.8/client/install)
and Maven package `cloud.lunarsky:objectstore-client:0.0.8` at
`https://repo.lunarsky.cloud/` are an older release. Build this checkout for the
current client; building locally does not publish a release.
```sh
bash client/scripts/test.sh
bash client/scripts/build.sh
python3 client/scripts/test-packaging.py
```
Run these commands from the ObjectStore repository root. The second command writes `client/dist/objectstore-client.jar` and `client/dist/javadoc/`.
Run these commands from the ObjectStore repository root. The build writes `client/dist/objectstore-client.jar` and `client/dist/javadoc/`, replacing stale classes and documentation. The JAR includes the MIT license and an `Implementation-Version` matching the service's `Version.java`. The optional packaging test requires Python 3 and builds twice in a temporary directory.
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/`.
To assemble a local Maven repository, run:
```sh
bash client/scripts/build-maven-repo.sh
```
It derives the version from this checkout and writes the JAR, POM, sources,
Javadocs, metadata, and checksums under `client/dist/maven-repo/`. An optional
version argument must match the source; the script refuses to label current code
as another release. To build an older release, check out its source tag first.
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.
+15 -15
View File
@@ -1,26 +1,23 @@
#!/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
version="$(bash scripts/version.sh "$@")"
bash scripts/build.sh "$version"
artifact_root="dist/maven-repo/cloud/lunarsky/objectstore-client"
version_dir="$artifact_root/$version"
mkdir -p "$version_dir"
mkdir -p "$artifact_root"
staging="$(mktemp -d "$artifact_root/.packaging-XXXXXX")"
trap 'rm -rf "$staging"' EXIT
base="objectstore-client-$version"
cp dist/objectstore-client.jar "$version_dir/$base.jar"
jar --create --file "$version_dir/$base-sources.jar" \
cp dist/objectstore-client.jar "$staging/$base.jar"
jar --create --file "$staging/$base-sources.jar" --manifest dist/MANIFEST.MF \
-C src/main/java . -C dist/classes META-INF/LICENSE
jar --create --file "$version_dir/$base-javadoc.jar" \
jar --create --file "$staging/$base-javadoc.jar" --manifest dist/MANIFEST.MF \
-C dist/javadoc . -C dist/classes META-INF/LICENSE
cat > "$version_dir/$base.pom" <<EOF
cat > "$staging/$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"
@@ -48,7 +45,10 @@ cat > "$version_dir/$base.pom" <<EOF
</project>
EOF
mapfile -t versions < <(find "$artifact_root" -mindepth 1 -maxdepth 1 -type d -printf '%f\n' | sort -V)
rm -rf "$version_dir"
mv "$staging" "$version_dir"
mapfile -t versions < <(find "$artifact_root" -mindepth 1 -maxdepth 1 -type d -printf '%f\n' |
grep -E '^[0-9]+\.[0-9]+\.[0-9]+([.-][A-Za-z0-9]+)*$' | sort -V)
latest="${versions[${#versions[@]}-1]}"
{
printf '%s\n' '<?xml version="1.0" encoding="UTF-8"?>' '<metadata>'
@@ -58,8 +58,8 @@ latest="${versions[${#versions[@]}-1]}"
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
for file in "$version_dir/$base.jar" "$version_dir/$base-sources.jar" \
"$version_dir/$base-javadoc.jar" "$version_dir/$base.pom" "$artifact_root/maven-metadata.xml"; do
md5sum "$file" | cut -d ' ' -f 1 > "$file.md5"
sha1sum "$file" | cut -d ' ' -f 1 > "$file.sha1"
sha256sum "$file" | cut -d ' ' -f 1 > "$file.sha256"
+16 -8
View File
@@ -1,13 +1,21 @@
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")/.."
rm -rf dist/classes
mkdir -p dist/classes
version="$(bash scripts/version.sh "$@")"
build_dir="$(mktemp -d)"
trap 'rm -rf "$build_dir"' EXIT
mkdir -p "$build_dir/classes/META-INF"
find src/main/java -name '*.java' -print0 |
xargs -0 javac --release 21 -d dist/classes
mkdir -p dist/classes/META-INF
cp ../LICENSE dist/classes/META-INF/LICENSE
jar --create --file dist/objectstore-client.jar -C dist/classes .
javadoc --release 21 -quiet -Xdoclint:reference,syntax,html -d dist/javadoc \
xargs -0 javac --release 21 -d "$build_dir/classes"
cp ../LICENSE "$build_dir/classes/META-INF/LICENSE"
printf 'Manifest-Version: 1.0\nImplementation-Title: ObjectStore Java client\nImplementation-Version: %s\n\n' \
"$version" > "$build_dir/MANIFEST.MF"
jar --create --file "$build_dir/objectstore-client.jar" --manifest "$build_dir/MANIFEST.MF" \
-C "$build_dir/classes" .
javadoc --release 21 -quiet -Xdoclint:reference,syntax,html -d "$build_dir/javadoc" \
$(find src/main/java -name '*.java' -print)
echo "Built dist/objectstore-client.jar"
mkdir -p dist
rm -rf dist/classes dist/javadoc
mv "$build_dir/classes" "$build_dir/javadoc" "$build_dir/MANIFEST.MF" \
"$build_dir/objectstore-client.jar" dist/
echo "Built dist/objectstore-client.jar ($version)"
+101
View File
@@ -0,0 +1,101 @@
#!/usr/bin/env python3
import hashlib
import re
import shutil
import subprocess
import tempfile
import xml.etree.ElementTree as ET
import zipfile
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
def run(root, *command, success=True):
result = subprocess.run(command, cwd=root, capture_output=True, text=True, timeout=120)
if (result.returncode == 0) != success:
raise AssertionError(f"Unexpected exit {result.returncode}: {command}\n"
f"{result.stdout}\n{result.stderr}")
return result
def check_archives(root, version):
dist = root / "client/dist"
artifact = dist / "maven-repo/cloud/lunarsky/objectstore-client"
version_dir = artifact / version
base = f"objectstore-client-{version}"
license_text = (root / "LICENSE").read_bytes()
for suffix in ("", "-sources", "-javadoc"):
with zipfile.ZipFile(version_dir / f"{base}{suffix}.jar") as archive:
manifest = archive.read("META-INF/MANIFEST.MF").decode()
assert f"Implementation-Version: {version}\r\n" in manifest
assert archive.read("META-INF/LICENSE") == license_text
assert not any("Stale" in name for name in archive.namelist())
namespace = {"m": "http://maven.apache.org/POM/4.0.0"}
pom = ET.parse(version_dir / f"{base}.pom")
assert pom.findtext("m:version", namespaces=namespace) == version
metadata = ET.parse(artifact / "maven-metadata.xml")
assert metadata.findtext("versioning/latest") == version
assert metadata.findtext("versioning/release") == version
assert [item.text for item in metadata.findall("versioning/versions/version")] == [version]
assert not (dist / "classes/Stale.class").exists()
assert not (dist / "javadoc/Stale.html").exists()
assert len(list(version_dir.iterdir())) == 16
for primary in list(version_dir.glob("*.jar")) + list(version_dir.glob("*.pom")) + [
artifact / "maven-metadata.xml"]:
for algorithm in ("md5", "sha1", "sha256"):
digest = hashlib.new(algorithm, primary.read_bytes()).hexdigest()
assert Path(str(primary) + "." + algorithm).read_text().strip() == digest
return version_dir
def verify_runtime_version(root, version):
probe = root / "VersionCheck.java"
probe.write_text("""import cloud.lunarsky.objectstore.client.ObjectStorageClient;
class VersionCheck {
public static void main(String[] args) {
String version = ObjectStorageClient.class.getPackage().getImplementationVersion();
if (!args[0].equals(version)) throw new AssertionError(version);
}
}
""")
jar = "client/dist/objectstore-client.jar"
run(root, "javac", "--release", "21", "-cp", jar, str(probe))
run(root, "java", "-cp", f"{jar}:{root}", "VersionCheck", version)
def exercise(root):
source_version = (root / "src/cloud/lunarsky/store/Version.java").read_text()
version = re.search(r'String VALUE = "([^"]+)"', source_version)[1]
for script in ("build.sh", "build-maven-repo.sh"):
result = run(root, "bash", f"client/scripts/{script}", "999.999.999", success=False)
assert "does not match source version" in result.stderr
assert not (root / "client/dist").exists()
for file in ("classes/Stale.class", "javadoc/Stale.html"):
target = root / "client/dist" / file
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text("stale")
run(root, "bash", "client/scripts/build-maven-repo.sh")
version_dir = check_archives(root, version)
(version_dir / "old.jar.sha1.sha1").write_text("stale checksum")
run(root, "bash", "client/scripts/build-maven-repo.sh", version)
check_archives(root, version)
verify_runtime_version(root, version)
print(f"Java {version} packaging tests passed: source version, manifests, licenses, clean rebuild, checksums")
def main():
with tempfile.TemporaryDirectory(prefix="objectstore-packaging-") as directory:
root = Path(directory)
for folder in ("client/src/main/java", "client/scripts"):
shutil.copytree(ROOT / folder, root / folder)
target = root / "src/cloud/lunarsky/store"
target.mkdir(parents=True)
shutil.copy(ROOT / "src/cloud/lunarsky/store/Version.java", target)
shutil.copy(ROOT / "LICENSE", root)
exercise(root)
if __name__ == "__main__":
main()
+19
View File
@@ -0,0 +1,19 @@
#!/usr/bin/env bash
set -euo pipefail
if (( $# > 1 )); then
echo "usage: version.sh [VERSION]" >&2
exit 1
fi
version_file="$(dirname "$0")/../../src/cloud/lunarsky/store/Version.java"
version="$(sed -nE 's/^[[:space:]]*static final String VALUE = "([^"]+)";[[:space:]]*$/\1/p' "$version_file")"
if [[ ! "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+([.-][A-Za-z0-9]+)*$ ]]; then
echo "Cannot determine the source version from Version.java" >&2
exit 1
fi
if [[ -n "${1:-}" && "$1" != "$version" ]]; then
echo "Requested version $1 does not match source version $version; build from the matching source tag" >&2
exit 1
fi
printf '%s\n' "$version"
+6
View File
@@ -0,0 +1,6 @@
services:
gateway:
environment:
S3_MANAGED_KEYS_MASTER_FILE: /run/secrets/objectstore_managed_master
volumes:
- ./secrets/managed-master:/run/secrets/objectstore_managed_master:ro
+201
View File
@@ -0,0 +1,201 @@
#!/usr/bin/env python3
import argparse
import concurrent.futures
import hashlib
import json
import threading
import time
import uuid
from datetime import datetime, timezone
from pathlib import Path
from readiness_support import Client, Metrics, check_empty_except_marker, check_owner, read_manifest, request_checked, write_json
class Budget:
def __init__(self, duration, max_bytes, max_objects, size, rate):
self.deadline = time.monotonic() + duration
self.max_objects = min(max_objects, max_bytes // size)
self.rate = rate
self.started = time.monotonic()
self.count = 0
self.lock = threading.Lock()
self.reason = "duration"
def next(self):
with self.lock:
if time.monotonic() >= self.deadline:
return None
if self.count >= self.max_objects:
self.reason = "write_budget"
return None
index = self.count
wait = max(0, self.started + index / self.rate - time.monotonic()) if self.rate else 0
if time.monotonic() + wait >= self.deadline:
return None
self.count += 1
if wait:
time.sleep(wait)
return index
def new_manifest(args):
identifier = uuid.uuid4().hex
return {"format": 1, "id": identifier, "bucket": "readiness-" + identifier,
"endpoint": args.endpoint, "region": args.region, "objects": {},
"created_at": datetime.now(timezone.utc).isoformat(),
"complete": False, "retain_all": args.retain_all}
def run(args):
output = Path(args.output)
output.mkdir(mode=0o700, parents=True, exist_ok=False)
manifest = new_manifest(args)
client = Client(args.endpoint, args.region, args.timeout)
metrics = Metrics()
lock = threading.Lock()
started = time.monotonic()
try:
status, _, _ = client.request("HEAD", manifest["bucket"])
if status != 404:
raise ValueError("new test bucket was not absent; refusing to proceed")
if client.request("PUT", manifest["bucket"])[0] != 200:
raise ValueError("could not create a dedicated test bucket")
write_json(output / "manifest.json", manifest)
marker = manifest["id"].encode()
if client.request("PUT", manifest["bucket"], ".readiness-owner", marker)[0] != 200:
raise ValueError("could not write the test ownership marker")
budget = Budget(args.duration, args.max_write_bytes, args.max_objects, args.size, args.writes_per_second)
def worker():
while (index := budget.next()) is not None:
key = f"objects/{index}"
body = hashlib.shake_256((manifest["id"] + key).encode()).digest(args.size)
digest = hashlib.sha256(body).hexdigest()
entry = {"size": args.size, "sha256": digest, "acknowledged": False, "deleted": False}
with lock:
manifest["objects"][key] = entry
if not request_checked(client, metrics, "PUT", manifest["bucket"], key, body, {200}):
continue
entry["acknowledged"] = True
request_checked(client, metrics, "GET", manifest["bucket"], key, b"", {200}, digest)
request_checked(client, metrics, "HEAD", manifest["bucket"], key, b"", {200})
if not args.retain_all and index % 4 != 0:
entry["delete_attempted"] = True
entry["deleted"] = request_checked(client, metrics, "DELETE", manifest["bucket"], key, b"", {204})
with concurrent.futures.ThreadPoolExecutor(max_workers=args.concurrency) as pool:
futures = [pool.submit(worker) for _ in range(args.concurrency)]
for future in futures:
future.result()
manifest["complete"] = True
duration = time.monotonic() - started
report = metrics.report(duration)
report.update({"seconds": round(duration, 3), "stop_reason": budget.reason,
"bucket": manifest["bucket"], "config": vars(args),
"attempted_write_bytes": len(manifest["objects"]) * args.size,
"acknowledged_objects_retained": sum(entry["acknowledged"] and not entry.get("delete_attempted")
for entry in manifest["objects"].values())})
write_json(output / "report.json", report)
print(json.dumps(report, indent=2))
return 1 if any(value["failed"] for value in report["operations"].values()) else 0
finally:
write_json(output / "manifest.json", manifest)
client.close()
def verify_objects(client, metrics, manifest):
if not manifest["complete"]:
raise ValueError("workload manifest is incomplete; acknowledged-data verification is unavailable")
retained = sum(entry["acknowledged"] and not entry.get("delete_attempted")
for entry in manifest["objects"].values())
if not retained:
raise ValueError("manifest has no retained acknowledged objects to verify")
failures = 0
for key, entry in manifest["objects"].items():
success = True
if entry["acknowledged"] and not entry.get("delete_attempted"):
success = request_checked(client, metrics, "GET", manifest["bucket"], key, b"", {200}, entry["sha256"])
elif entry["deleted"]:
success = request_checked(client, metrics, "GET", manifest["bucket"], key, b"", {404})
failures += not success
if failures >= 10:
return True
return False
def cleanup_objects(client, metrics, manifest):
failures = 0
for key in manifest["objects"]:
failures += not request_checked(client, metrics, "DELETE", manifest["bucket"], key, b"", {204})
if failures >= 10:
return True
if failures:
return False
check_empty_except_marker(client, manifest)
removed = request_checked(client, metrics, "DELETE", manifest["bucket"], ".readiness-owner", b"", {204})
if removed and not request_checked(client, metrics, "DELETE", manifest["bucket"], None, b"", {204}):
request_checked(client, metrics, "PUT", manifest["bucket"], ".readiness-owner", manifest["id"].encode(), {200})
return False
def check_or_cleanup(args):
manifest = read_manifest(args.manifest)
client = Client(args.endpoint or manifest["endpoint"], manifest["region"], args.timeout)
metrics = Metrics()
started = time.monotonic()
try:
check_owner(client, manifest)
action = verify_objects if args.command == "verify" else cleanup_objects
stopped_early = action(client, metrics, manifest)
report = metrics.report(time.monotonic() - started)
report.update({"command": args.command, "bucket": manifest["bucket"],
"manifest_complete": manifest["complete"], "stopped_after_ten_failures": stopped_early})
if args.report:
write_json(args.report, report)
print(json.dumps(report, indent=2))
return 1 if any(value["failed"] for value in report["operations"].values()) else 0
finally:
client.close()
def arguments():
parser = argparse.ArgumentParser(description="Bounded mixed S3 workload and acknowledged-data verification")
subparsers = parser.add_subparsers(dest="command", required=True)
workload = subparsers.add_parser("run")
workload.add_argument("--endpoint", default="http://127.0.0.1:9000")
workload.add_argument("--region", default="us-east-1")
workload.add_argument("--output", required=True, help="new directory for reports and the ownership manifest")
workload.add_argument("--duration", type=float, default=30)
workload.add_argument("--size", type=int, default=4096)
workload.add_argument("--concurrency", type=int, default=4)
workload.add_argument("--writes-per-second", type=float, default=0, help="global PUT rate; 0 means unpaced")
workload.add_argument("--max-write-bytes", type=int, default=64 * 1024 * 1024)
workload.add_argument("--max-objects", type=int, default=4096)
workload.add_argument("--retain-all", action="store_true", help="skip deletes, for interruption/recovery tests")
for command in ("verify", "cleanup"):
action = subparsers.add_parser(command)
action.add_argument("--manifest", required=True)
action.add_argument("--endpoint", help="override only for a separately restored test service")
action.add_argument("--report")
for subparser in (workload, *[subparsers.choices[name] for name in ("verify", "cleanup")]):
subparser.add_argument("--timeout", type=float, default=10)
args = parser.parse_args()
if not .1 <= args.timeout <= 60:
parser.error("timeout must be 0.1–60 seconds")
if args.command == "run":
if not 1 <= args.duration <= 86400 or not 1 <= args.concurrency <= 32:
parser.error("duration must be 1–86400 seconds; concurrency must be 1–32")
if not 1 <= args.size <= 1048576 or not args.size <= args.max_write_bytes <= 1073741824:
parser.error("size must be 1–1048576 bytes; write budget must be at least size and at most 1 GiB")
if not 1 <= args.max_objects <= 100000 or not 0 <= args.writes_per_second <= 10000:
parser.error("max objects must be 1–100000; write rate must be 0–10000")
return args
if __name__ == "__main__":
try:
options = arguments()
raise SystemExit(run(options) if options.command == "run" else check_or_cleanup(options))
except (OSError, ValueError, KeyError) as error:
raise SystemExit(f"Readiness check failed: {error}") from error
+217
View File
@@ -0,0 +1,217 @@
import hashlib
import hmac
import http.client
import json
import math
import os
import threading
import time
import xml.etree.ElementTree as ET
from datetime import datetime, timezone
from pathlib import Path
from urllib.parse import quote, urlsplit
def endpoint_origin(value):
endpoint = urlsplit(value)
if (endpoint.scheme not in ("http", "https") or not endpoint.hostname
or endpoint.username or endpoint.password or endpoint.query or endpoint.fragment
or endpoint.path not in ("", "/")):
raise ValueError("endpoint must be an HTTP(S) origin without credentials")
if endpoint.scheme == "http" and endpoint.hostname not in ("localhost", "127.0.0.1", "::1"):
raise ValueError("use HTTPS outside localhost")
return endpoint
def signed_headers(method, path, body, host, access, secret, region, query=""):
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"
canonical = (f"{method}\n{path}\n{query}\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()
return {
"Host": host, "x-amz-content-sha256": digest, "x-amz-date": now,
"Authorization": (f"AWS4-HMAC-SHA256 Credential={access}/{scope},"
f"SignedHeaders={names},Signature={signature}"),
}
class Client:
def __init__(self, endpoint, region, timeout=10):
self.endpoint = endpoint_origin(endpoint)
self.region = region
self.timeout = timeout
self.access = os.environ["S3_ACCESS_KEY"]
self.secret = os.environ["S3_SECRET_KEY"]
self.local = threading.local()
self.connections = set()
self.lock = threading.Lock()
def request(self, method, bucket, key=None, body=b"", limit=1048576, query=None):
path = "/" + quote(bucket, safe="")
if key is not None:
path += "/" + quote(key, safe="/~")
encoded_query = "&".join(quote(name, safe="~") + "=" + quote(value, safe="~")
for name, value in sorted((query or {}).items()))
connection = self.connection()
headers = signed_headers(method, path, body, self.endpoint.netloc,
self.access, self.secret, self.region, encoded_query)
try:
connection.request(method, path + ("?" + encoded_query if encoded_query else ""), body, headers)
response = connection.getresponse()
data = response.read(limit + 1)
if len(data) > limit:
raise ValueError("response exceeded the test response limit")
return response.status, dict(response.getheaders()), data
except Exception:
connection.close()
self.local.connection = None
with self.lock:
self.connections.discard(connection)
raise
def connection(self):
connection = getattr(self.local, "connection", None)
if connection is None:
cls = http.client.HTTPSConnection if self.endpoint.scheme == "https" else http.client.HTTPConnection
connection = cls(self.endpoint.hostname, self.endpoint.port, timeout=self.timeout)
self.local.connection = connection
with self.lock:
self.connections.add(connection)
return connection
def close(self):
for connection in self.connections:
connection.close()
class Metrics:
def __init__(self):
self.lock = threading.Lock()
self.operations = {}
self.errors = []
def record(self, operation, seconds, success, status, sent, received, error=None):
with self.lock:
stats = self.operations.setdefault(operation, {
"attempts": 0, "succeeded": 0, "failed": 0, "seconds": 0,
"request_payload_bytes": 0, "response_payload_bytes": 0,
"successful_request_payload_bytes": 0, "successful_response_payload_bytes": 0,
"status_counts": {}, "histogram": {},
})
stats["attempts"] += 1
stats["succeeded" if success else "failed"] += 1
stats["seconds"] += seconds
stats["request_payload_bytes"] += sent
stats["response_payload_bytes"] += received
if success:
stats["successful_request_payload_bytes"] += sent
stats["successful_response_payload_bytes"] += received
code = str(status) if status is not None else "transport"
stats["status_counts"][code] = stats["status_counts"].get(code, 0) + 1
bucket = math.ceil(math.log(max(seconds * 1000, .001), 1.1))
stats["histogram"][bucket] = stats["histogram"].get(bucket, 0) + 1
if error and len(self.errors) < 20:
self.errors.append({"operation": operation, "error": error})
def report(self, duration):
output = {}
for operation, stats in self.operations.items():
item = {key: value for key, value in stats.items() if key not in ("histogram", "seconds")}
item["successful_requests_per_second"] = round(stats["succeeded"] / max(duration, .001), 3)
item["successful_upload_mib_per_second"] = round(stats["successful_request_payload_bytes"] / max(duration, .001) / 1048576, 3)
item["successful_download_mib_per_second"] = round(stats["successful_response_payload_bytes"] / max(duration, .001) / 1048576, 3)
item["mean_ms"] = round(stats["seconds"] * 1000 / stats["attempts"], 3)
for label, fraction in (("p50_ms_upper", .5), ("p95_ms_upper", .95), ("p99_ms_upper", .99)):
target = math.ceil(stats["attempts"] * fraction)
seen = 0
for bucket, count in sorted(stats["histogram"].items()):
seen += count
if seen >= target:
item[label] = round(1.1 ** bucket, 3)
break
output[operation] = item
return {"operations": output, "error_samples": self.errors,
"latency_note": "All attempts; percentile histogram upper bounds have at most 10% bin width."}
def request_checked(client, metrics, method, bucket, key, body, expected, digest=None):
started = time.perf_counter()
status = None
received = 0
error = None
try:
status, headers, data = client.request(method, bucket, key, body)
received = len(data)
if status not in expected:
error = f"HTTP {status}"
elif digest is not None and hashlib.sha256(data).hexdigest() != digest:
error = "response checksum mismatch"
return error is None
except Exception as failure:
error = type(failure).__name__
return False
finally:
metrics.record(method, time.perf_counter() - started, error is None,
status, len(body), received, error)
def write_json(path, value):
path = Path(path)
temporary = path.with_name(path.name + ".tmp")
with open(temporary, "w", encoding="utf-8", opener=lambda p, flags: os.open(p, flags, 0o600)) as output:
json.dump(value, output, indent=2, sort_keys=True)
output.write("\n")
output.flush()
os.fsync(output.fileno())
os.replace(temporary, path)
def read_manifest(path):
path = Path(path)
if path.stat().st_size > 32 * 1024 * 1024:
raise ValueError("manifest is too large")
value = json.loads(path.read_text())
identifier = value["id"]
if (value.get("format") != 1 or len(identifier) != 32
or any(char not in "0123456789abcdef" for char in identifier)
or value["bucket"] != "readiness-" + identifier):
raise ValueError("invalid test ownership manifest")
if len(value["objects"]) > 100000:
raise ValueError("too many manifest objects")
for key, entry in value["objects"].items():
if not key.startswith("objects/") or not key[8:].isdigit():
raise ValueError("invalid test object key")
if not 1 <= entry["size"] <= 1048576:
raise ValueError("invalid test object size")
if len(entry["sha256"]) != 64:
raise ValueError("invalid test object checksum")
endpoint_origin(value["endpoint"])
return value
def check_owner(client, manifest):
status, _, body = client.request("GET", manifest["bucket"], ".readiness-owner")
if status != 200 or body != manifest["id"].encode():
raise ValueError("test ownership marker mismatch; refusing to access or delete objects")
def check_empty_except_marker(client, manifest):
status, _, body = client.request("GET", manifest["bucket"], query={"list-type": "2", "max-keys": "2"})
if status != 200:
raise ValueError("could not verify test bucket contents before removal")
try:
root = ET.fromstring(body)
except ET.ParseError as error:
raise ValueError("invalid bucket listing; refusing to remove marker") from error
keys = [element.text for element in root.findall("{*}Contents/{*}Key")]
truncated = root.findtext("{*}IsTruncated")
if root.tag.rsplit("}", 1)[-1] != "ListBucketResult" or keys != [".readiness-owner"] or truncated != "false":
raise ValueError("bucket has unlisted objects; preserving bucket and ownership marker")
+217
View File
@@ -0,0 +1,217 @@
#!/usr/bin/env python3
"""Disposable Patroni failover test; never attaches to an existing cluster."""
import argparse
import hashlib
import http.client
import json
import os
from pathlib import Path
import subprocess
import sys
import time
import uuid
from readiness_support import signed_headers
ROOT = Path(__file__).resolve().parent.parent
DATABASES = ("db-a", "db-b", "db-c")
ETCD = ("etcd-a", "etcd-b", "etcd-c")
ACCESS = "HaTestAccessKey0001"
SECRET = "ha-test-s3-secret-01234567890123456789"
def wait_for(check, description, timeout=150):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
result = check()
if result:
return result
time.sleep(1)
raise RuntimeError(f"Timed out waiting for {description}")
class Drill:
def __init__(self, image):
self.project = "objectstore-ha-" + uuid.uuid4().hex[:12]
self.image = image or self.project + ":local"
self.environment = dict(os.environ, OBJECTSTORE_HA_IMAGE=self.image, COMPOSE_PARALLEL_LIMIT="1")
self.host = None
self.writes = {}
def compose(self, *arguments, check=True):
return subprocess.run(
["docker", "compose", "--env-file", "/dev/null", "-p", self.project, "-f", "tests/ha/compose.yaml", *arguments],
cwd=ROOT, env=self.environment, capture_output=True, text=True, check=check,
timeout=15 if arguments[0] == "exec" else 600 if arguments[0] == "build" or "--build" in arguments else 90,
)
def cluster(self, observer):
program = ("import json,urllib.request; "
"print(urllib.request.urlopen('http://127.0.0.1:8008/cluster',timeout=3).read().decode())")
try:
result = self.compose("exec", "-T", observer, "python3", "-c", program, check=False)
except subprocess.TimeoutExpired:
return []
if result.returncode:
return []
try:
return json.loads(result.stdout).get("members", [])
except ValueError:
return []
def primary(self, observer, excluded=None, count=3):
members = self.cluster(observer)
healthy = [item for item in members if item.get("state") in ("running", "streaming")]
leaders = [item["name"] for item in healthy if item.get("role") == "leader"]
synchronous = any(item.get("role") in ("sync_standby", "quorum_standby") for item in healthy)
if len(healthy) >= count and len(leaders) == 1 and synchronous and leaders[0] != excluded:
return leaders[0]
return None
def request(self, method, path, body=b"", timeout=12):
connection = http.client.HTTPConnection(self.host, timeout=timeout)
try:
headers = signed_headers(method, path, body, self.host, ACCESS, SECRET, "us-east-1")
connection.request(method, path, body, headers)
response = connection.getresponse()
return response.status, response.read()
finally:
connection.close()
def ready(self):
try:
return self.request("GET", "/ready")[0] == 200
except (OSError, http.client.HTTPException):
return False
def seed(self, prefix):
for index in range(12):
path = f"/ha-test/{prefix}/{index}"
body = hashlib.shake_256(path.encode()).digest(4096)
status, _ = self.request("PUT", path, body)
if status != 200:
raise AssertionError(f"Write returned {status}: {path}")
self.writes[path] = hashlib.sha256(body).hexdigest()
def verify(self):
for path, digest in self.writes.items():
status, body = self.request("GET", path)
if status != 200 or hashlib.sha256(body).hexdigest() != digest:
raise AssertionError(f"Acknowledged object changed or disappeared: {path}")
def start(self, build):
if build:
subprocess.run(["docker", "build", "-t", self.image, "."], cwd=ROOT, check=True)
print("Starting isolated metadata HA cluster", flush=True)
self.compose("build", "db-a")
self.compose("up", "-d", "--no-build", *ETCD, *DATABASES, "node-a", "node-b")
leader = wait_for(lambda: self.primary("db-c"), "three PostgreSQL members and synchronous standby")
self.compose("up", "-d", "gateway")
self.host = self.compose("port", "gateway", "9000").stdout.strip()
if not self.host.startswith("127.0.0.1:") or "\n" in self.host:
raise RuntimeError("Gateway port was not published on loopback")
wait_for(self.ready, "ObjectStore readiness")
return leader
def failover(self, leader):
observer = next(name for name in DATABASES if name != leader)
print(f"Killing disposable primary {leader}", flush=True)
before = time.monotonic()
self.compose("kill", "-s", "SIGKILL", leader)
new_leader = wait_for(lambda: self.primary(observer, excluded=leader, count=2), "automatic promotion")
wait_for(self.ready, "gateway reconnection without restart")
elapsed = time.monotonic() - before
self.verify()
self.seed("after-promotion")
self.compose("start", leader)
wait_for(lambda: self.primary(observer), "old primary to rejoin")
self.verify()
return new_leader, elapsed
def quorum_healthy(self):
try:
result = self.compose("exec", "-T", "etcd-a", "etcdctl",
"--endpoints=http://etcd-a:2379,http://etcd-b:2379,http://etcd-c:2379",
"--command-timeout=3s", "endpoint", "health", check=False)
return result.returncode == 0
except subprocess.TimeoutExpired:
return False
def lose_quorum(self, observer):
print("Removing disposable DCS majority", flush=True)
self.compose("stop", "etcd-b", "etcd-c")
wait_for(lambda: not self.ready(), "gateway to refuse readiness", timeout=70)
try:
status, _ = self.request("PUT", "/ha-test/uncertain-during-quorum-loss", b"uncertain")
if status == 200:
raise AssertionError("Write was acknowledged after metadata quorum was lost")
except (OSError, http.client.HTTPException):
pass
self.compose("start", "etcd-b", "etcd-c")
wait_for(self.quorum_healthy, "all coordination members to recover")
wait_for(lambda: self.primary(observer), "metadata quorum recovery")
wait_for(self.ready, "gateway recovery")
self.verify()
self.seed("after-quorum-recovery")
def lose_standbys(self, leader):
replicas = [name for name in DATABASES if name != leader]
print("Removing disposable synchronous replicas", flush=True)
self.compose("kill", "-s", "SIGKILL", *replicas)
try:
status, _ = self.request("PUT", "/ha-test/uncertain-without-standby", b"uncertain")
if status == 200:
raise AssertionError("Write was acknowledged without a synchronous standby")
except (OSError, http.client.HTTPException):
pass
self.compose("start", *replicas)
wait_for(lambda: self.primary(leader), "synchronous replicas to return")
wait_for(self.ready, "gateway recovery after standby loss")
self.verify()
def run(self, build):
try:
leader = self.start(build)
self.seed("before-failover")
new_leader, elapsed = self.failover(leader)
self.lose_standbys(new_leader)
self.lose_quorum(new_leader)
self.verify()
return {"passed": True, "acknowledged_objects_verified": len(self.writes),
"failover_seconds": round(elapsed, 3), "gateway_restarted": False,
"physical_hosts": 1, "dcs_quorum_recovery": True,
"no_standby_write_refusal": True}
except Exception:
logs = self.compose("logs", "--tail", "35", check=False)
print(logs.stdout, file=sys.stderr)
raise
finally:
self.compose("down", "-v", "--remove-orphans")
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--image", help="Existing ObjectStore image; otherwise build this checkout")
parser.add_argument("--output", type=Path, help="Write a JSON test report")
args = parser.parse_args()
if args.output and args.output.exists():
parser.error("Report already exists")
try:
report = Drill(args.image).run(build=not args.image)
except Exception as error:
report = {"passed": False, "error": str(error)}
if args.output:
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(json.dumps(report, indent=2) + "\n")
raise
rendered = json.dumps(report, indent=2) + "\n"
if args.output:
args.output.parent.mkdir(parents=True, exist_ok=True)
with args.output.open("x") as output:
output.write(rendered)
print(rendered, end="")
if __name__ == "__main__":
main()
+5 -1
View File
@@ -4,4 +4,8 @@ cd "$(dirname "$0")/.."
project="objectstore-metadata-test-$$"
compose() { docker compose -p "$project" -f tests/metadata/compose.yaml "$@"; }
trap 'compose down -v --remove-orphans >/dev/null 2>&1 || true' EXIT
compose up --build --abort-on-container-exit --exit-code-from check check
if [ -n "${OBJECTSTORE_TEST_IMAGE:-}" ]; then
compose up --no-build --abort-on-container-exit --exit-code-from check check
else
compose up --build --abort-on-container-exit --exit-code-from check check
fi
+208
View File
@@ -0,0 +1,208 @@
#!/usr/bin/env python3
import argparse
import json
import tempfile
import threading
import unittest
import xml.etree.ElementTree as ET
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from unittest.mock import patch
from readiness import Budget, check_or_cleanup, run
from readiness_support import Metrics, endpoint_origin, read_manifest
class FakeStore(BaseHTTPRequestHandler):
objects = {}
bucket = None
corrupt = False
inject_on_marker_delete = False
def log_message(self, *args):
pass
def do_HEAD(self):
self.respond(200 if self.path in self.objects or self.path == self.bucket else 404)
def do_PUT(self):
data = self.rfile.read(int(self.headers.get("Content-Length", "0")))
if self.path.count("/") == 1:
type(self).bucket = self.path
else:
self.objects[self.path] = data
self.respond(200)
def do_GET(self):
if self.path.partition("?")[0] == self.bucket:
root = ET.Element("ListBucketResult")
ET.SubElement(root, "IsTruncated").text = "false"
for path in sorted(self.objects):
entry = ET.SubElement(root, "Contents")
ET.SubElement(entry, "Key").text = path[len(self.bucket) + 1:]
self.respond(200, ET.tostring(root))
return
data = self.objects.get(self.path)
if self.corrupt and "/objects/" in self.path and data is not None:
data = b"corrupt"
self.respond(200 if data is not None else 404, data or b"")
def do_DELETE(self):
if self.path == self.bucket:
if self.objects:
self.respond(409)
return
type(self).bucket = None
else:
self.objects.pop(self.path, None)
if self.inject_on_marker_delete and self.path.endswith("/.readiness-owner"):
self.objects[self.bucket + "/racing-object"] = b"preserve"
type(self).inject_on_marker_delete = False
self.respond(204)
def respond(self, status, body=b""):
self.send_response(status)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
class ReadinessTest(unittest.TestCase):
def setUp(self):
FakeStore.objects = {}
FakeStore.bucket = None
FakeStore.corrupt = False
FakeStore.inject_on_marker_delete = False
self.server = ThreadingHTTPServer(("127.0.0.1", 0), FakeStore)
self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)
self.thread.start()
self.temp = tempfile.TemporaryDirectory()
self.output = Path(self.temp.name) / "run"
self.endpoint = "http://127.0.0.1:" + str(self.server.server_port)
self.credentials = patch.dict("os.environ", {"S3_ACCESS_KEY": "test", "S3_SECRET_KEY": "test-secret"})
self.credentials.start()
def tearDown(self):
self.credentials.stop()
self.server.shutdown()
self.server.server_close()
self.thread.join()
self.temp.cleanup()
def workload(self, retain=False):
args = argparse.Namespace(command="run", output=str(self.output), endpoint=self.endpoint,
region="us-east-1", timeout=1, duration=2, max_write_bytes=4096,
max_objects=100, size=1024, concurrency=2, writes_per_second=0,
retain_all=retain)
with patch("builtins.print"):
return run(args)
def action(self, command):
args = argparse.Namespace(command=command, manifest=str(self.output / "manifest.json"),
endpoint=None, timeout=1, report=None)
with patch("builtins.print"):
return check_or_cleanup(args)
def test_budget_integrity_and_owned_cleanup(self):
self.assertEqual(self.workload(), 0)
report = json.loads((self.output / "report.json").read_text())
self.assertEqual(report["attempted_write_bytes"], 4096)
self.assertEqual(report["operations"]["PUT"]["succeeded"], 4)
self.assertEqual(report["operations"]["DELETE"]["succeeded"], 3)
self.assertEqual(self.action("verify"), 0)
self.assertEqual(self.action("cleanup"), 0)
self.assertEqual(FakeStore.objects, {})
def test_corruption_and_missing_acknowledged_object_fail(self):
self.assertEqual(self.workload(retain=True), 0)
FakeStore.corrupt = True
self.assertEqual(self.action("verify"), 1)
FakeStore.corrupt = False
key = next(key for key in FakeStore.objects if "/objects/" in key)
del FakeStore.objects[key]
self.assertEqual(self.action("verify"), 1)
def test_cleanup_refuses_wrong_marker(self):
self.workload()
marker = FakeStore.bucket + "/.readiness-owner"
FakeStore.objects[marker] = b"someone-else"
before = dict(FakeStore.objects)
with self.assertRaisesRegex(ValueError, "ownership marker"):
self.action("cleanup")
self.assertEqual(before, FakeStore.objects)
def test_cleanup_does_not_delete_unlisted_objects(self):
self.workload()
unknown = FakeStore.bucket + "/not-created-by-the-test"
FakeStore.objects[unknown] = b"preserve"
marker = FakeStore.objects[FakeStore.bucket + "/.readiness-owner"]
with self.assertRaisesRegex(ValueError, "unlisted objects"):
self.action("cleanup")
self.assertEqual(FakeStore.objects[unknown], b"preserve")
self.assertEqual(FakeStore.objects[FakeStore.bucket + "/.readiness-owner"], marker)
del FakeStore.objects[unknown]
self.assertEqual(self.action("cleanup"), 0)
def test_manifest_rejects_arbitrary_bucket(self):
self.workload()
path = self.output / "manifest.json"
manifest = json.loads(path.read_text())
manifest["bucket"] = "important-data"
path.write_text(json.dumps(manifest))
with self.assertRaisesRegex(ValueError, "ownership manifest"):
read_manifest(path)
def test_cleanup_restores_marker_if_bucket_changes(self):
self.workload()
marker = FakeStore.objects[FakeStore.bucket + "/.readiness-owner"]
FakeStore.inject_on_marker_delete = True
self.assertEqual(self.action("cleanup"), 1)
self.assertEqual(FakeStore.objects[FakeStore.bucket + "/.readiness-owner"], marker)
self.assertEqual(FakeStore.objects[FakeStore.bucket + "/racing-object"], b"preserve")
del FakeStore.objects[FakeStore.bucket + "/racing-object"]
self.assertEqual(self.action("cleanup"), 0)
def test_incomplete_manifest_cannot_claim_verification(self):
self.workload()
path = self.output / "manifest.json"
manifest = json.loads(path.read_text())
manifest["complete"] = False
path.write_text(json.dumps(manifest))
with self.assertRaisesRegex(ValueError, "incomplete"):
self.action("verify")
def test_maximum_manifest_can_be_reopened(self):
self.workload()
path = self.output / "manifest.json"
manifest = json.loads(path.read_text())
entry = next(iter(manifest["objects"].values()))
manifest["objects"] = {"objects/" + str(index): entry for index in range(100000)}
with path.open("w") as stream:
json.dump(manifest, stream, indent=2)
self.assertGreater(path.stat().st_size, 16 * 1024 * 1024)
self.assertEqual(len(read_manifest(path)["objects"]), 100000)
def test_transport_policy_and_histogram(self):
for endpoint in ("http://example.com", "http://user:pass@localhost", "https://example.com/path"):
with self.assertRaises(ValueError):
endpoint_origin(endpoint)
metrics = Metrics()
for _ in range(9):
metrics.record("PUT", .01, True, 200, 100, 0)
metrics.record("PUT", .1, False, 503, 100, 0, "HTTP 503")
report = metrics.report(2)["operations"]["PUT"]
self.assertEqual(report["failed"], 1)
self.assertEqual(report["successful_requests_per_second"], 4.5)
self.assertGreaterEqual(report["p95_ms_upper"], 100)
self.assertLess(report["p95_ms_upper"], 110)
def test_rate_reservation_does_not_consume_an_unstarted_write(self):
budget = Budget(1, 2048, 2, 1024, .1)
self.assertEqual(budget.next(), 0)
self.assertIsNone(budget.next())
self.assertEqual(budget.count, 1)
self.assertEqual(budget.reason, "duration")
if __name__ == "__main__":
unittest.main()
+230
View File
@@ -0,0 +1,230 @@
#!/usr/bin/env python3
import argparse
import hashlib
import json
import os
import secrets
import socket
import subprocess
import sys
import time
import urllib.request
import uuid
from pathlib import Path
from readiness_support import write_json
LABEL = "cloud.lunarsky.objectstore.readiness"
ROOT = Path(__file__).resolve().parent.parent
class Drill:
def __init__(self, image, output):
self.image = image
self.output = output
self.identifier = uuid.uuid4().hex
self.prefix = "objectstore-recovery-" + self.identifier
self.containers = []
self.volumes = []
self.environment = dict(os.environ, S3_ACCESS_KEY="Readiness" + secrets.token_hex(8),
S3_SECRET_KEY=secrets.token_hex(32))
def docker(self, *args, **kwargs):
return subprocess.run(["docker", *args], check=True, env=self.environment,
timeout=90, **kwargs)
def create_volume(self, suffix):
volume = self.prefix + "-" + suffix
self.docker("volume", "create", "--label", LABEL + "=" + self.identifier,
volume, stdout=subprocess.DEVNULL)
self.volumes.append(volume)
return volume
def start_service(self, suffix, volume):
name = self.prefix + "-" + suffix
self.containers.append(name)
with socket.socket() as reserved:
reserved.bind(("127.0.0.1", 0))
port = reserved.getsockname()[1]
self.docker("run", "-d", "--name", name, "--label", LABEL + "=" + self.identifier,
"--memory", "384m", "--cpus", "2", "--cap-drop", "ALL",
"--security-opt", "no-new-privileges:true", "--publish", f"127.0.0.1:{port}:9000",
"--mount", f"type=volume,src={volume},dst=/data",
"-e", "S3_ACCESS_KEY", "-e", "S3_SECRET_KEY", "-e", "S3_BUCKET=objects",
"-e", "MAX_TOTAL_BYTES=67108864", "-e", "MAX_OBJECT_BYTES=1048576",
"-e", "JAVA_TOOL_OPTIONS=-XX:+UseSerialGC -Xms32m -Xmx192m", self.image,
stdout=subprocess.DEVNULL)
endpoint = self.endpoint(name)
self.wait_ready(endpoint)
return name, endpoint
def endpoint(self, name):
mapping = self.docker("port", name, "9000/tcp", capture_output=True, text=True).stdout.strip()
if not mapping.startswith("127.0.0.1:") or "\n" in mapping:
raise ValueError("test container port must be loopback-only")
return "http://" + mapping
def wait_ready(self, endpoint):
deadline = time.monotonic() + 40
while time.monotonic() < deadline:
try:
with urllib.request.urlopen(endpoint + "/ready", timeout=1) as response:
if response.status == 200:
return
except OSError:
pass
time.sleep(.2)
raise RuntimeError("test service did not become ready")
def command(self, *args):
return [sys.executable, str(ROOT / "scripts/readiness.py"), *args]
def verify(self, manifest, endpoint, filename):
subprocess.run(self.command("verify", "--manifest", str(manifest), "--endpoint", endpoint,
"--report", str(self.output / filename)), env=self.environment,
check=True, timeout=120, stdout=subprocess.DEVNULL)
def baseline(self, endpoint):
workload = self.output / "baseline"
subprocess.run(self.command("run", "--endpoint", endpoint, "--output", str(workload),
"--duration", "3", "--writes-per-second", "20", "--max-write-bytes", "1048576"),
env=self.environment, check=True, timeout=30, stdout=subprocess.DEVNULL)
manifest = workload / "manifest.json"
self.verify(manifest, endpoint, "baseline-verification.json")
subprocess.run(self.command("cleanup", "--manifest", str(manifest)), env=self.environment,
check=True, timeout=30, stdout=subprocess.DEVNULL)
def seed_before_crash(self, endpoint):
workload = self.output / "before-crash"
subprocess.run(self.command("run", "--endpoint", endpoint, "--output", str(workload),
"--duration", "10", "--max-objects", "20", "--concurrency", "1",
"--max-write-bytes", "81920", "--retain-all"),
env=self.environment, check=True, timeout=30, stdout=subprocess.DEVNULL)
report = json.loads((workload / "report.json").read_text())
if report["acknowledged_objects_retained"] != 20:
raise RuntimeError("pre-crash seed did not acknowledge all twenty objects")
manifest = workload / "manifest.json"
self.verify(manifest, endpoint, "before-crash-verification.json")
return manifest
def workload_and_restart(self, container, endpoint):
workload = self.output / "workload"
command = self.command("run", "--endpoint", endpoint, "--output", str(workload),
"--duration", "10", "--max-write-bytes", "2097152", "--max-objects", "512",
"--size", "4096", "--concurrency", "2", "--writes-per-second", "30",
"--timeout", "1", "--retain-all")
with open(self.output / "workload.log", "w") as log:
process = subprocess.Popen(command, env=self.environment, stdout=log, stderr=subprocess.STDOUT)
try:
deadline = time.monotonic() + 5
while not (workload / "manifest.json").exists():
if process.poll() is not None or time.monotonic() >= deadline:
raise RuntimeError("workload did not initialize")
time.sleep(.1)
time.sleep(2)
self.docker("kill", "--signal", "KILL", container, stdout=subprocess.DEVNULL)
time.sleep(1)
self.docker("start", container, stdout=subprocess.DEVNULL)
if self.endpoint(container) != endpoint:
raise RuntimeError("test endpoint changed during restart")
self.wait_ready(endpoint)
result = process.wait(timeout=40)
if result != 1:
raise RuntimeError("interrupted workload did not report the expected request failures")
finally:
if process.poll() is None:
process.terminate()
try:
process.wait(timeout=10)
except subprocess.TimeoutExpired:
process.kill()
process.wait(timeout=10)
report = json.loads((workload / "report.json").read_text())
if report["acknowledged_objects_retained"] < 10:
raise RuntimeError("too few acknowledged objects to validate recovery")
self.verify(workload / "manifest.json", endpoint, "restart-verification.json")
return workload / "manifest.json"
def archive_and_restore(self, source, target):
archive = self.output / "snapshot.tar"
export_name = self.prefix + "-export"
restore_name = self.prefix + "-import"
self.containers.extend((export_name, restore_name))
common = ["run", "--label", LABEL + "=" + self.identifier, "--network", "none", "--read-only",
"--security-opt", "no-new-privileges:true", "--user", "0"]
with open(archive, "xb") as stream:
self.docker(*common, "--name", export_name, "--mount", f"type=volume,src={source},dst=/snapshot,readonly",
"--entrypoint", "tar", self.image, "-C", "/snapshot", "-cf", "-", ".", stdout=stream)
digest = hashlib.sha256(archive.read_bytes()).hexdigest()
with open(archive, "rb") as stream:
self.docker(*common, "--name", restore_name, "--interactive", "--mount", f"type=volume,src={target},dst=/snapshot",
"--entrypoint", "sh", self.image, "-c",
'test -z "$(find /snapshot -mindepth 1 -print -quit)" && tar -C /snapshot -xpf -',
stdin=stream, stdout=subprocess.DEVNULL)
return {"sha256": digest, "bytes": archive.stat().st_size}
def cleanup(self):
failures = []
for kind, names in (("container", self.containers), ("volume", self.volumes)):
for name in names:
try:
info = subprocess.run(["docker", kind, "inspect", name], capture_output=True,
text=True, timeout=30)
if info.returncode and "No such" in info.stderr:
continue
info.check_returncode()
value = json.loads(info.stdout)[0]
labels = value.get("Config", {}).get("Labels", {}) if kind == "container" else value.get("Labels", {})
if labels.get(LABEL) != self.identifier:
raise ValueError("ownership label mismatch")
args = [kind, "rm", "-f", name] if kind == "container" else [kind, "rm", name]
self.docker(*args, stdout=subprocess.DEVNULL)
except (subprocess.SubprocessError, ValueError) as error:
failures.append(name + ": " + str(error))
if failures:
raise RuntimeError("Test resource cleanup failed: " + "; ".join(failures))
def run(self):
image_id = self.docker("image", "inspect", "--format", "{{.Id}}", self.image,
capture_output=True, text=True).stdout.strip()
summary = {"image": self.image, "image_id": image_id, "scope": "single-node local disposable Docker",
"physical_power_loss_tested": False, "offsite_restore_tested": False, "passed": False}
try:
source = self.create_volume("source-data")
target = self.create_volume("restore-data")
container, endpoint = self.start_service("source", source)
self.baseline(endpoint)
before_crash = self.seed_before_crash(endpoint)
manifest = self.workload_and_restart(container, endpoint)
self.verify(before_crash, endpoint, "pre-crash-restart-verification.json")
summary["pre_crash_acknowledged_objects_verified"] = 20
self.docker("stop", "--time", "15", container, stdout=subprocess.DEVNULL)
summary["snapshot"] = self.archive_and_restore(source, target)
_, restored = self.start_service("restored", target)
self.verify(manifest, restored, "restore-verification.json")
self.verify(before_crash, restored, "pre-crash-restore-verification.json")
summary["passed"] = True
finally:
try:
summary["resources_removed"] = False
self.cleanup()
summary["resources_removed"] = True
finally:
summary["passed"] = summary["passed"] and summary["resources_removed"]
write_json(self.output / "summary.json", summary)
print(json.dumps(summary, indent=2))
def main():
parser = argparse.ArgumentParser(description="Disposable container crash and cold-restore integrity drill")
parser.add_argument("--image", required=True, help="already-built local ObjectStore image")
parser.add_argument("--output", required=True, help="new directory; retained reports and snapshot use at most about 8 MiB")
args = parser.parse_args()
output = Path(args.output).resolve()
output.mkdir(mode=0o700, parents=True, exist_ok=False)
Drill(args.image, output).run()
if __name__ == "__main__":
main()
+1
View File
@@ -7,6 +7,7 @@ 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
java --add-modules jdk.httpserver -cp out/classes:lib/hash4j-0.30.0.jar cloud.lunarsky.store.StoreTest
java -Xmx32m --add-modules jdk.httpserver,java.net.http -cp out/classes:lib/hash4j-0.30.0.jar cloud.lunarsky.store.LargeObjectTest
java --add-modules jdk.httpserver -cp out/classes:lib/hash4j-0.30.0.jar cloud.lunarsky.store.DiskBucketNamesTest
java --add-modules jdk.httpserver -cp out/classes:lib/hash4j-0.30.0.jar cloud.lunarsky.store.ConditionalEditTest
java -cp out/classes:lib/hash4j-0.30.0.jar cloud.lunarsky.store.ClusterRepairCliTest
+18 -5
View File
@@ -353,9 +353,9 @@ final class AdminConsole {
private void auditPage(HttpExchange exchange, String origin) throws IOException {
Session session = requireSession(exchange, "GET");
if (session == null) return;
operations.read(() -> {
operations.read(() -> withCredentials(() -> {
send(exchange, 200, AdminOperationsPages.auditPage(identities, diagnostics, audit, session.csrf(), null, Map.of()), "text/html; charset=utf-8");
});
}));
}
private void jobsPage(HttpExchange exchange, String origin) throws IOException {
@@ -401,9 +401,9 @@ final class AdminConsole {
private void credentialsPage(HttpExchange exchange, String origin) throws IOException {
Session session = requireSession(exchange, "GET");
if (session == null) return;
operations.read(() -> {
operations.read(() -> withCredentials(() -> {
send(exchange, 200, AdminSettingsPages.credentialsPage(managedCredentials, store, session.csrf(), null), "text/html; charset=utf-8");
});
}));
}
private void download(HttpExchange exchange, String origin) throws IOException {
@@ -481,7 +481,11 @@ final class AdminConsole {
return;
}
String action = path.substring((PATH + "/action/").length());
StoreOperations.Action apply = () -> applyAction(exchange, session, action, form);
StoreOperations.Action apply = () -> {
if (Set.of("branding-name", "branding-reset", "default-theme").contains(action))
applyAction(exchange, session, action, form);
else withCredentials(() -> applyAction(exchange, session, action, form));
};
try {
if (action.equals("rename-bucket") || action.equals("delete-bucket")) {
operations.write(apply);
@@ -494,6 +498,15 @@ final class AdminConsole {
}
}
private void withCredentials(StoreOperations.Action action) throws IOException {
ManagedCredentials managed = managedCredentials;
if (managed == null) action.run();
else managed.withSnapshot(() -> {
refreshCredentials.run();
action.run();
});
}
private void applyAction(HttpExchange exchange, Session session, String action,
Map<String, String> form) throws IOException {
String peer = exchange.getRemoteAddress().getAddress().getHostAddress();
@@ -0,0 +1,108 @@
package cloud.lunarsky.store;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
final class ClusterCredentialStore implements ManagedCredentialStore {
private final ClusterMonitor.Connections connections;
ClusterCredentialStore(ClusterMonitor.Connections connections) {
this.connections = connections;
}
@Override public boolean shared() { return true; }
@Override public State read(long knownRevision) throws IOException {
try (Connection connection = connections.open();
PreparedStatement query = connection.prepareStatement(
"SELECT revision, CASE WHEN revision <> ? THEN encrypted END, " +
"NOT pg_is_in_recovery() AND current_setting('transaction_read_only') = 'off' " +
"FROM cluster_managed_credentials WHERE singleton=1")) {
query.setQueryTimeout(5);
query.setLong(1, knownRevision);
try (ResultSet rows = query.executeQuery()) {
if (!rows.next()) {
if (knownRevision >= 0) throw new IOException("Managed credential state is missing");
return new State(0, null);
}
if (!rows.getBoolean(3)) throw new IOException("Managed credentials require writable primary metadata");
return new State(rows.getLong(1), rows.getBytes(2));
}
} catch (SQLException error) {
throw unavailable(error);
}
}
@Override public State update(Change change) throws IOException {
try (Connection connection = connections.open()) {
connection.setAutoCommit(false);
try {
State current = lock(connection);
Mutation changed = change.apply(current);
replaceBuckets(connection, changed.buckets());
byte[] encrypted = changed.encrypted();
long revision = Math.addExact(current.revision(), 1);
try (PreparedStatement update = connection.prepareStatement(
"INSERT INTO cluster_managed_credentials (singleton, revision, encrypted) " +
"VALUES (1, ?, ?) ON CONFLICT (singleton) DO UPDATE " +
"SET revision=EXCLUDED.revision, encrypted=EXCLUDED.encrypted")) {
update.setLong(1, revision);
update.setBytes(2, encrypted);
update.executeUpdate();
}
connection.commit();
return new State(revision, encrypted);
} catch (SQLException | IOException | RuntimeException error) {
try { connection.rollback(); }
catch (SQLException rollback) { error.addSuppressed(rollback); }
throw error;
}
} catch (SQLException error) {
throw unavailable(error);
}
}
private static State lock(Connection connection) throws SQLException {
try (var statement = connection.createStatement()) {
statement.execute("SET LOCAL lock_timeout = '5s'");
statement.execute("SELECT pg_advisory_xact_lock(6834071092784)");
statement.execute("SELECT pg_advisory_xact_lock(6834071092785)");
try (ResultSet rows = statement.executeQuery(
"SELECT revision, encrypted FROM cluster_managed_credentials WHERE singleton=1 FOR UPDATE")) {
return rows.next() ? new State(rows.getLong(1), rows.getBytes(2)) : new State(0, null);
}
}
}
private static void replaceBuckets(Connection connection, java.util.Set<String> buckets) throws SQLException {
try (var statement = connection.createStatement()) {
statement.executeUpdate("DELETE FROM cluster_managed_credential_buckets");
}
try (PreparedStatement insert = connection.prepareStatement(
"INSERT INTO cluster_managed_credential_buckets SELECT name FROM cluster_buckets WHERE name=?")) {
for (String bucket : buckets) {
insert.setString(1, bucket);
if (insert.executeUpdate() != 1)
throw new StoreException(404, "NoSuchBucket", "Scoped credential bucket does not exist");
}
}
}
static void requireUnscopedBucket(Connection connection, String bucket) throws SQLException {
try (PreparedStatement query = connection.prepareStatement(
"SELECT 1 FROM cluster_managed_credential_buckets WHERE bucket=?")) {
query.setString(1, bucket);
try (ResultSet rows = query.executeQuery()) {
if (rows.next()) throw new StoreException(409, "BucketHasScopedKeys",
"Move or remove scoped access keys before renaming or deleting this bucket");
}
}
}
private static IOException unavailable(SQLException error) {
return new IOException("Managed credential metadata unavailable", error);
}
}
@@ -68,6 +68,8 @@ final class ClusterStore implements ObjectStorage, MultipartStorage {
private Connection connect() throws SQLException { return DriverManager.getConnection(jdbcUrl, user, password); }
ManagedCredentialStore managedCredentialStore() { return new ClusterCredentialStore(this::connect); }
@Override public Limits limits() { return new Limits(maxObject, maxTotal); }
@Override public void ensureBucket(String bucket) throws IOException {
@@ -244,6 +246,7 @@ final class ClusterStore implements ObjectStorage, MultipartStorage {
connection.setAutoCommit(false);
try {
lockUsage(connection, name);
ClusterCredentialStore.requireUnscopedBucket(connection, name);
try (PreparedStatement check = connection.prepareStatement(
"SELECT EXISTS (SELECT 1 FROM cluster_object_versions WHERE bucket=?) OR EXISTS " +
"(SELECT 1 FROM cluster_uploads WHERE bucket=?)")) {
@@ -288,6 +291,7 @@ final class ClusterStore implements ObjectStorage, MultipartStorage {
"cluster_uploads IN ACCESS EXCLUSIVE MODE");
}
lockUsage(connection, oldName);
ClusterCredentialStore.requireUnscopedBucket(connection, oldName);
try (PreparedStatement check = connection.prepareStatement(
"SELECT EXISTS (SELECT 1 FROM cluster_buckets WHERE name=?)")) {
check.setString(1, newName);
@@ -0,0 +1,59 @@
package cloud.lunarsky.store;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.SecureRandom;
import java.util.Arrays;
import javax.crypto.Cipher;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
final class CredentialCipher {
static final int MAX_BYTES = 65536;
private static final byte[] MAGIC = { 'O', 'S', 'K', '1' };
private static final SecureRandom RANDOM = new SecureRandom();
private final SecretKeySpec master;
CredentialCipher(byte[] master) {
this.master = new SecretKeySpec(master, "AES");
Arrays.fill(master, (byte) 0);
}
byte[] decrypt(byte[] bytes) throws IOException {
if (bytes == null) return new byte[0];
if (bytes.length < MAGIC.length + 12 + 16 || bytes.length > MAX_BYTES ||
!Arrays.equals(MAGIC, Arrays.copyOf(bytes, MAGIC.length)))
throw new IOException("Invalid managed credential store");
byte[] nonce = Arrays.copyOfRange(bytes, MAGIC.length, MAGIC.length + 12);
try {
Cipher cipher = cipher(Cipher.DECRYPT_MODE, nonce);
return cipher.doFinal(bytes, MAGIC.length + 12, bytes.length - MAGIC.length - 12);
} catch (GeneralSecurityException error) {
throw new IOException("Managed credential store could not be decrypted", error);
}
}
byte[] encrypt(byte[] plain) throws IOException {
byte[] nonce = new byte[12];
RANDOM.nextBytes(nonce);
try {
byte[] encrypted = cipher(Cipher.ENCRYPT_MODE, nonce).doFinal(plain);
byte[] result = new byte[MAGIC.length + nonce.length + encrypted.length];
System.arraycopy(MAGIC, 0, result, 0, MAGIC.length);
System.arraycopy(nonce, 0, result, MAGIC.length, nonce.length);
System.arraycopy(encrypted, 0, result, MAGIC.length + nonce.length, encrypted.length);
return result;
} catch (GeneralSecurityException error) {
throw new IOException("Could not encrypt managed credentials", error);
} finally {
Arrays.fill(plain, (byte) 0);
}
}
private Cipher cipher(int mode, byte[] nonce) throws GeneralSecurityException {
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
cipher.init(mode, master, new GCMParameterSpec(128, nonce));
cipher.updateAAD(MAGIC);
return cipher;
}
}
@@ -0,0 +1,54 @@
package cloud.lunarsky.store;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
final class CredentialCodec {
private CredentialCodec() { }
static Map<String, ManagedCredentials.Key> decode(byte[] plain, Set<String> reserved)
throws IOException {
try {
Map<String, ManagedCredentials.Key> loaded = new HashMap<>();
for (String line : new String(plain, StandardCharsets.UTF_8).split("\n")) {
if (line.isEmpty()) continue;
ManagedCredentials.Key key = entry(line, reserved);
if (loaded.size() >= 64 || loaded.putIfAbsent(key.id(), key) != null)
throw new IOException("Invalid managed credential entry");
}
return Map.copyOf(loaded);
} finally {
Arrays.fill(plain, (byte) 0);
}
}
private static ManagedCredentials.Key entry(String line, Set<String> reserved) throws IOException {
String[] fields = line.split("\t", -1);
if (fields.length != 6 || !fields[0].matches("[A-Za-z0-9]{16,128}") ||
fields[1].length() < 32 || !Set.of("true", "false").contains(fields[5]) ||
reserved.contains(fields[0]))
throw new IOException("Invalid managed credential entry");
try {
Set<String> actions = Set.of(fields[4].split(","));
ManagedCredentials.validateScope(fields[2], fields[3], actions);
return new ManagedCredentials.Key(fields[0], fields[1], fields[2], fields[3],
actions, Boolean.parseBoolean(fields[5]));
} catch (IllegalArgumentException | StoreException error) {
throw new IOException("Invalid managed credential entry", error);
}
}
static byte[] encode(Map<String, ManagedCredentials.Key> keys) {
StringBuilder contents = new StringBuilder();
keys.values().stream().sorted(java.util.Comparator.comparing(ManagedCredentials.Key::id))
.forEach(key -> contents.append(key.id()).append('\t').append(key.secret()).append('\t')
.append(key.bucket()).append('\t').append(key.prefix()).append('\t')
.append(String.join(",", key.actions().stream().sorted().toList())).append('\t')
.append(key.enabled()).append('\n'));
return contents.toString().getBytes(StandardCharsets.UTF_8);
}
}
@@ -0,0 +1,51 @@
package cloud.lunarsky.store;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
final class DiskCredentialStore implements ManagedCredentialStore {
private final Path path;
private long revision;
DiskCredentialStore(Path path) { this.path = path; }
@Override public boolean shared() { return false; }
@Override public State read(long knownRevision) throws IOException {
return new State(revision, knownRevision == revision ? null : load());
}
@Override public State update(Change change) throws IOException {
byte[] encrypted = change.apply(new State(revision, load())).encrypted();
Files.createDirectories(path.getParent());
Path temporary = Files.createTempFile(path.getParent(), "managed-credentials-", ".tmp");
try {
Files.setPosixFilePermissions(temporary,
java.nio.file.attribute.PosixFilePermissions.fromString("rw-------"));
try (FileChannel channel = FileChannel.open(temporary, StandardOpenOption.WRITE)) {
ByteBuffer buffer = ByteBuffer.wrap(encrypted);
while (buffer.hasRemaining()) channel.write(buffer);
channel.force(true);
}
Files.move(temporary, path, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
try (FileChannel directory = FileChannel.open(path.getParent(), StandardOpenOption.READ)) {
directory.force(true);
}
} finally {
Files.deleteIfExists(temporary);
}
return new State(++revision, encrypted);
}
private byte[] load() throws IOException {
if (!Files.exists(path)) return null;
if (Files.size(path) > CredentialCipher.MAX_BYTES)
throw new IOException("Invalid managed credential store");
return Files.readAllBytes(path);
}
}
+10 -2
View File
@@ -134,6 +134,8 @@ public final class Main {
void setManagedCredentials(ManagedCredentials managedCredentials) {
this.managedCredentials = managedCredentials;
access.setManagedCredentials(managedCredentials);
authentication.setManagedCredentials(managedCredentials);
refreshManagedCredentials();
if (adminConsole != null)
adminConsole.setManagedCredentials(managedCredentials, this::refreshManagedCredentials);
@@ -142,8 +144,6 @@ public final class Main {
private synchronized void refreshManagedCredentials() {
ManagedCredentials managed = managedCredentials;
if (managed == null) return;
access.setManagedPolicies(managed.policies());
authentication.setManagedIdentities(managed.identities());
if (adminConsole != null) adminConsole.setIdentities(authentication.identities());
}
@@ -229,6 +229,14 @@ public final class Main {
}
private void dispatch(HttpExchange exchange, RequestContext context) throws IOException {
ManagedCredentials managed = managedCredentials;
if (managed == null || anonymousRead(exchange) ||
authentication.usesConfiguredIdentity(exchange.getRequestURI(), exchange.getRequestHeaders()))
dispatchAuthenticated(exchange, context);
else managed.withSnapshot(() -> dispatchAuthenticated(exchange, context));
}
private void dispatchAuthenticated(HttpExchange exchange, RequestContext context) throws IOException {
SigV4.Verified verified = verifyRequest(exchange);
context.principal = verified.principal();
String path = SigV4.decode(exchange.getRequestURI().getRawPath());
@@ -0,0 +1,18 @@
package cloud.lunarsky.store;
import java.io.IOException;
interface ManagedCredentialStore {
record State(long revision, byte[] encrypted) { }
record Mutation(byte[] encrypted, java.util.Set<String> buckets) { }
@FunctionalInterface
interface Change {
Mutation apply(State previous) throws IOException;
}
State read(long knownRevision) throws IOException;
State update(Change change) throws IOException;
boolean shared();
}
+111 -139
View File
@@ -2,14 +2,8 @@ package cloud.lunarsky.store;
import com.sun.net.httpserver.Headers;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.security.GeneralSecurityException;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Base64;
@@ -18,36 +12,41 @@ import java.util.HexFormat;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.crypto.Cipher;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
final class ManagedCredentials {
record Key(String id, String secret, String bucket, String prefix,
Set<String> actions, boolean enabled) { }
private static final byte[] MAGIC = { 'O', 'S', 'K', '1' };
private static final SecureRandom RANDOM = new SecureRandom();
private static final Set<String> ACTIONS = Set.of("read", "write", "list");
private final Path path;
private final SecretKeySpec master;
private record Snapshot(long revision, Map<String, Key> keys,
Map<String, String> identities, Map<String, BucketPolicy> policies) { }
private final ManagedCredentialStore storage;
private final CredentialCipher cipher;
private final Set<String> reserved;
private volatile Map<String, Key> keys;
private final ThreadLocal<Snapshot> request = new ThreadLocal<>();
private volatile Snapshot snapshot;
private ManagedCredentials(Path path, byte[] master, Set<String> reserved) throws IOException {
this.path = path;
this.master = new SecretKeySpec(master, "AES");
ManagedCredentials(ManagedCredentialStore storage, byte[] master, Set<String> reserved)
throws IOException {
this.storage = storage;
this.cipher = new CredentialCipher(master);
this.reserved = Set.copyOf(reserved);
java.util.Arrays.fill(master, (byte) 0);
this.keys = load();
ManagedCredentialStore.State state = storage.read(-1);
if (state.encrypted() == null && storage.shared())
state = storage.update(existing -> {
Map<String, Key> keys = CredentialCodec.decode(cipher.decrypt(existing.encrypted()), reserved);
byte[] encrypted = existing.encrypted() == null ?
cipher.encrypt(CredentialCodec.encode(keys)) : existing.encrypted();
return new ManagedCredentialStore.Mutation(encrypted, buckets(keys));
});
snapshot = decode(state);
}
static ManagedCredentials fromEnvironment(Map<String, String> env, ObjectStorage store,
Set<String> reserved) throws IOException {
String configured = env.get("S3_MANAGED_KEYS_MASTER_FILE");
if (configured == null || configured.isBlank()) return null;
if (!(store instanceof DiskStore))
throw new IllegalArgumentException("Managed credentials require disk mode");
byte[] master;
try {
master = HexFormat.of().parseHex(Files.readString(Path.of(configured)).trim());
@@ -56,20 +55,53 @@ final class ManagedCredentials {
}
if (master.length != 32)
throw new IllegalArgumentException("Managed credentials master key must contain 32 bytes");
return new ManagedCredentials(Path.of(env.getOrDefault("DATA_DIR", "/data"))
.resolve("managed-credentials.bin"), master, reserved);
ManagedCredentialStore storage = store instanceof ClusterStore cluster ?
cluster.managedCredentialStore() : new DiskCredentialStore(
Path.of(env.getOrDefault("DATA_DIR", "/data")).resolve("managed-credentials.bin"));
return new ManagedCredentials(storage, master, reserved);
}
List<Key> list() { return keys.values().stream().sorted(java.util.Comparator.comparing(Key::id)).toList(); }
boolean contains(String principal) { return principal != null && keys.containsKey(principal); }
List<Key> list() { return current().keys().values().stream().sorted(java.util.Comparator.comparing(Key::id)).toList(); }
boolean contains(String principal) { return principal != null && current().keys().containsKey(principal); }
Map<String, String> identities() { return current().identities(); }
Map<String, BucketPolicy> policies() { return current().policies(); }
Map<String, String> identities() {
Map<String, String> active = new HashMap<>();
keys.values().stream().filter(Key::enabled).forEach(key -> active.put(key.id(), key.secret()));
return Map.copyOf(active);
void withSnapshot(StoreOperations.Action action) throws IOException {
Snapshot previous = request.get();
request.set(refresh());
try { action.run(); }
finally {
if (previous == null) request.remove();
else request.set(previous);
}
}
Map<String, BucketPolicy> policies() {
private Snapshot refresh() throws IOException {
Snapshot known = snapshot;
if (!storage.shared()) return known;
ManagedCredentialStore.State state = storage.read(known.revision());
if (state.revision() < known.revision())
throw new IOException("Managed credential metadata moved backwards; restore a current backup before restarting");
Snapshot loaded = state.revision() == known.revision() ? known : decode(state);
synchronized (this) {
if (loaded.revision() > snapshot.revision()) snapshot = loaded;
return snapshot;
}
}
private Snapshot current() {
Snapshot pinned = request.get();
return pinned == null ? snapshot : pinned;
}
private Snapshot decode(ManagedCredentialStore.State state) throws IOException {
Map<String, Key> keys = CredentialCodec.decode(cipher.decrypt(state.encrypted()), reserved);
Map<String, String> identities = new HashMap<>();
keys.values().stream().filter(Key::enabled).forEach(key -> identities.put(key.id(), key.secret()));
return new Snapshot(state.revision(), keys, Map.copyOf(identities), policies(keys));
}
private static Map<String, BucketPolicy> policies(Map<String, Key> keys) {
Map<String, BucketPolicy> active = new HashMap<>();
for (Key key : keys.values()) {
if (!key.enabled()) continue;
@@ -106,35 +138,35 @@ final class ManagedCredentials {
}
synchronized Key create(String bucket, String prefix, Set<String> actions) throws IOException {
if (keys.size() >= 64) invalid("Too many managed access keys");
validateScope(bucket, prefix, actions);
byte[] random = new byte[24];
String id;
do {
Key[] created = new Key[1];
mutate(keys -> {
if (keys.size() >= 64) invalid("Too many managed access keys");
byte[] random = new byte[24];
String id;
do {
RANDOM.nextBytes(random);
id = HexFormat.of().withUpperCase().formatHex(random, 0, 16);
} while (reserved.contains(id) || keys.containsKey(id));
RANDOM.nextBytes(random);
id = HexFormat.of().withUpperCase().formatHex(random, 0, 16);
} while (reserved.contains(id) || keys.containsKey(id));
RANDOM.nextBytes(random);
String secret = Base64.getUrlEncoder().withoutPadding().encodeToString(random) +
Base64.getUrlEncoder().withoutPadding().encodeToString(randomToken());
Key key = new Key(id, secret, bucket, prefix, Set.copyOf(actions), true);
Map<String, Key> updated = new HashMap<>(keys);
updated.put(id, key);
persist(updated);
keys = Map.copyOf(updated);
return key;
String secret = Base64.getUrlEncoder().withoutPadding().encodeToString(random) +
Base64.getUrlEncoder().withoutPadding().encodeToString(randomToken());
Key key = new Key(id, secret, bucket, prefix, Set.copyOf(actions), true);
keys.put(id, key);
created[0] = key;
});
return created[0];
}
synchronized void update(String id, String bucket, String prefix, Set<String> actions) throws IOException {
Key old = key(id);
validateScope(bucket, prefix, actions);
Map<String, Key> updated = new HashMap<>(keys);
updated.put(id, new Key(id, old.secret(), bucket, prefix, Set.copyOf(actions), old.enabled()));
persist(updated);
keys = Map.copyOf(updated);
mutate(keys -> {
Key old = key(keys, id);
keys.put(id, new Key(id, old.secret(), bucket, prefix, Set.copyOf(actions), old.enabled()));
});
}
private static void validateScope(String bucket, String prefix, Set<String> actions) {
static void validateScope(String bucket, String prefix, Set<String> actions) {
if (bucket == null || prefix == null || actions == null ||
!bucket.matches("[a-z0-9][a-z0-9-]{1,61}[a-z0-9]") ||
prefix.length() > 256 || !prefix.matches("[A-Za-z0-9/_-]*") ||
@@ -143,19 +175,35 @@ final class ManagedCredentials {
}
synchronized void setEnabled(String id, boolean enabled) throws IOException {
Key old = key(id);
Map<String, Key> updated = new HashMap<>(keys);
updated.put(id, new Key(id, old.secret(), old.bucket(), old.prefix(), old.actions(), enabled));
persist(updated);
keys = Map.copyOf(updated);
mutate(keys -> {
Key old = key(keys, id);
keys.put(id, new Key(id, old.secret(), old.bucket(), old.prefix(), old.actions(), enabled));
});
}
synchronized void remove(String id) throws IOException {
key(id);
Map<String, Key> updated = new HashMap<>(keys);
updated.remove(id);
persist(updated);
keys = Map.copyOf(updated);
mutate(keys -> {
key(keys, id);
keys.remove(id);
});
}
private void mutate(java.util.function.Consumer<Map<String, Key>> change) throws IOException {
ManagedCredentialStore.State state = storage.update(previous -> {
if (storage.shared() && previous.revision() < snapshot.revision())
throw new IOException("Managed credential metadata moved backwards");
Map<String, Key> updated = new HashMap<>(
CredentialCodec.decode(cipher.decrypt(previous.encrypted()), reserved));
change.accept(updated);
return new ManagedCredentialStore.Mutation(
cipher.encrypt(CredentialCodec.encode(updated)), buckets(updated));
});
snapshot = decode(state);
if (request.get() != null) request.set(snapshot);
}
private static Set<String> buckets(Map<String, Key> keys) {
return keys.values().stream().map(Key::bucket).collect(java.util.stream.Collectors.toUnmodifiableSet());
}
void checkBucket(String principal, String bucket, String method, Map<String, String> query) {
@@ -189,90 +237,14 @@ final class ManagedCredentials {
}
}
private Key key(String id) {
private Key key(String id) { return key(current().keys(), id); }
private static Key key(Map<String, Key> keys, String id) {
Key key = keys.get(id);
if (key == null) throw new StoreException(404, "NoSuchKey", "Access key not found");
return key;
}
private Map<String, Key> load() throws IOException {
if (!Files.exists(path)) return Map.of();
byte[] bytes = Files.readAllBytes(path);
if (bytes.length < MAGIC.length + 12 + 16 || bytes.length > 65536 ||
!java.util.Arrays.equals(MAGIC, java.util.Arrays.copyOf(bytes, MAGIC.length)))
throw new IOException("Invalid managed credential store");
byte[] nonce = java.util.Arrays.copyOfRange(bytes, MAGIC.length, MAGIC.length + 12);
byte[] plain;
try {
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, master, new GCMParameterSpec(128, nonce));
cipher.updateAAD(MAGIC);
plain = cipher.doFinal(bytes, MAGIC.length + 12, bytes.length - MAGIC.length - 12);
} catch (GeneralSecurityException error) {
throw new IOException("Managed credential store could not be decrypted", error);
}
Map<String, Key> loaded = new HashMap<>();
for (String line : new String(plain, StandardCharsets.UTF_8).split("\n")) {
if (line.isEmpty()) continue;
String[] fields = line.split("\t", -1);
if (fields.length != 6 || !fields[0].matches("[A-Za-z0-9]{16,128}") ||
fields[1].length() < 32 || !fields[2].matches("[a-z0-9][a-z0-9-]{1,61}[a-z0-9]") ||
!fields[3].matches("[A-Za-z0-9/_-]*") || fields[3].length() > 256 ||
!Set.of("true", "false").contains(fields[5]) || reserved.contains(fields[0]))
throw new IOException("Invalid managed credential entry");
Set<String> actions;
try { actions = Set.of(fields[4].split(",")); }
catch (IllegalArgumentException error) { throw new IOException("Invalid managed credential entry", error); }
if (actions.isEmpty() || !ACTIONS.containsAll(actions) || loaded.size() >= 64 ||
loaded.putIfAbsent(fields[0], new Key(fields[0], fields[1], fields[2], fields[3],
actions, Boolean.parseBoolean(fields[5]))) != null)
throw new IOException("Invalid managed credential entry");
}
java.util.Arrays.fill(plain, (byte) 0);
return Map.copyOf(loaded);
}
private void persist(Map<String, Key> updated) throws IOException {
StringBuilder contents = new StringBuilder();
updated.values().stream().sorted(java.util.Comparator.comparing(Key::id)).forEach(key ->
contents.append(key.id()).append('\t').append(key.secret()).append('\t')
.append(key.bucket()).append('\t').append(key.prefix()).append('\t')
.append(String.join(",", key.actions().stream().sorted().toList())).append('\t')
.append(key.enabled()).append('\n'));
byte[] nonce = randomToken();
byte[] encrypted;
try {
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, master, new GCMParameterSpec(128, nonce));
cipher.updateAAD(MAGIC);
encrypted = cipher.doFinal(contents.toString().getBytes(StandardCharsets.UTF_8));
} catch (GeneralSecurityException error) {
throw new IOException("Could not encrypt managed credentials", error);
}
Files.createDirectories(path.getParent());
Path temporary = Files.createTempFile(path.getParent(), "managed-credentials-", ".tmp");
try {
Files.setPosixFilePermissions(temporary, java.nio.file.attribute.PosixFilePermissions.fromString("rw-------"));
try (FileChannel channel = FileChannel.open(temporary, StandardOpenOption.WRITE)) {
writeAll(channel, MAGIC);
writeAll(channel, nonce);
writeAll(channel, encrypted);
channel.force(true);
}
Files.move(temporary, path, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
try (FileChannel directory = FileChannel.open(path.getParent(), StandardOpenOption.READ)) {
directory.force(true);
}
} finally {
Files.deleteIfExists(temporary);
}
}
private static void writeAll(FileChannel channel, byte[] bytes) throws IOException {
ByteBuffer buffer = ByteBuffer.wrap(bytes);
while (buffer.hasRemaining()) channel.write(buffer);
}
private static byte[] randomToken() {
byte[] nonce = new byte[12];
RANDOM.nextBytes(nonce);
+3 -2
View File
@@ -106,7 +106,7 @@ final class MultipartStore implements MultipartStorage {
if (length > store.maxObject()) throw new StoreException(413, "EntityTooLarge", "Part exceeds the object limit");
Path dir = upload(id, bucket, key), target = part(dir, number);
long previous = Files.exists(target) ? Files.size(target) : 0;
if (staged - previous + length > store.maxTotal())
if (length > store.maxTotal() - (staged - previous))
throw new StoreException(507, "InsufficientStorage", "Multipart staging limit reached");
Path pending = Files.createTempFile(store.root().resolve("pending"), "part-", ".part");
try {
@@ -152,8 +152,9 @@ final class MultipartStore implements MultipartStorage {
Path file = part(dir, part.number());
if (!Files.isRegularFile(file)) throw new StoreException(400, "InvalidPart", "Missing part");
long length = Files.size(file);
if (length > store.maxObject() - total)
throw new StoreException(413, "EntityTooLarge", "Object exceeds the configured size limit");
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)) {
+11 -10
View File
@@ -8,7 +8,7 @@ final class S3Access {
private final ObjectStorage store;
private final String owner;
private final java.util.Map<String, BucketPolicy> configuredIdentityPolicies;
private volatile java.util.Map<String, BucketPolicy> identityPolicies;
private volatile ManagedCredentials managedCredentials;
private final ConcurrentHashMap<String, CachedPolicy> policies = new ConcurrentHashMap<>();
private record CachedPolicy(String source, BucketPolicy parsed) { }
@@ -20,15 +20,17 @@ final class S3Access {
this.store = store;
this.owner = owner;
this.configuredIdentityPolicies = java.util.Map.copyOf(identityPolicies);
this.identityPolicies = configuredIdentityPolicies;
}
synchronized void setManagedPolicies(java.util.Map<String, BucketPolicy> managed) {
var combined = new java.util.HashMap<>(configuredIdentityPolicies);
for (var entry : managed.entrySet())
if (combined.putIfAbsent(entry.getKey(), entry.getValue()) != null)
throw new IllegalArgumentException("Managed policy conflicts with a configured identity");
identityPolicies = java.util.Map.copyOf(combined);
void setManagedCredentials(ManagedCredentials managed) { managedCredentials = managed; }
private BucketPolicy identityPolicy(String principal) {
if (principal == null) return BucketPolicy.empty();
BucketPolicy configured = configuredIdentityPolicies.get(principal);
if (configured != null) return configured;
ManagedCredentials managed = managedCredentials;
return managed == null ? BucketPolicy.empty() :
managed.policies().getOrDefault(principal, BucketPolicy.empty());
}
String owner() {
@@ -83,8 +85,7 @@ final class S3Access {
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);
int identityDecision = identityPolicy(principal).decide(principal, action, resource);
if (decision < 0) return new Decision(false, "Explicit bucket policy deny");
if (identityDecision < 0) return new Decision(false, "Explicit identity policy deny");
if (BucketSecurity.allowsAcl(bucket, acl, principal, owner, permission))
+9 -1
View File
@@ -21,7 +21,7 @@ final class SchemaMigrator {
result.next();
version = result.getInt(1);
}
if (version > 14) throw new IOException("Metadata schema is newer than this ObjectStore build");
if (version > 15) 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))");
@@ -129,6 +129,14 @@ final class SchemaMigrator {
"finished_at bigint NOT NULL)");
statement.execute("INSERT INTO cluster_schema_migrations VALUES (14)");
}
if (version < 15) {
statement.execute("CREATE TABLE cluster_managed_credentials (singleton integer PRIMARY KEY " +
"CHECK (singleton=1), revision bigint NOT NULL CHECK (revision > 0), " +
"encrypted bytea NOT NULL CHECK (octet_length(encrypted) BETWEEN 32 AND 65536))");
statement.execute("CREATE TABLE cluster_managed_credential_buckets " +
"(bucket text PRIMARY KEY REFERENCES cluster_buckets(name))");
statement.execute("INSERT INTO cluster_schema_migrations VALUES (15)");
}
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 check = connection.prepareStatement(
+25 -13
View File
@@ -30,7 +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> configuredIdentities;
private volatile Map<String, String> identities;
private volatile ManagedCredentials managedCredentials;
private final Map<String, SessionCredentials.Session> sessions;
private final String root;
private final String region;
@@ -47,10 +47,9 @@ final class SigV4 {
SigV4(Map<String, String> identities, Map<String, SessionCredentials.Session> sessions,
String root, String region, Clock clock) {
this.configuredIdentities = Map.copyOf(identities);
this.identities = configuredIdentities;
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))
if (!configuredIdentities.containsKey(root)) throw new IllegalArgumentException("Missing root identity");
if (this.sessions.keySet().stream().anyMatch(configuredIdentities::containsKey))
throw new IllegalArgumentException("Session and permanent keys overlap");
this.root = root;
this.region = region;
@@ -62,19 +61,32 @@ final class SigV4 {
return principal != null &&
(configuredIdentities.containsKey(principal) || sessions.containsKey(principal));
}
synchronized void setManagedIdentities(Map<String, String> managed) {
Map<String, String> combined = new java.util.HashMap<>(configuredIdentities);
for (var entry : managed.entrySet())
if (combined.putIfAbsent(entry.getKey(), entry.getValue()) != null || sessions.containsKey(entry.getKey()))
throw new IllegalArgumentException("Managed access key conflicts with a configured identity");
identities = Map.copyOf(combined);
boolean usesConfiguredIdentity(URI uri, Headers headers) {
String credential = hasPresignedQuery(uri.getRawQuery()) ?
presignedQuery(uri.getRawQuery()).fields().get("X-Amz-Credential") :
authorizationFields(headers).get("Credential");
if (credential == null) denied("Missing credential scope");
return configuredIdentity(credential.split("/", -1)[0]);
}
void setManagedCredentials(ManagedCredentials managed) { managedCredentials = managed; }
Set<String> identities() {
var all = new java.util.HashSet<>(identities.keySet());
var all = new java.util.HashSet<>(configuredIdentities.keySet());
all.addAll(sessions.keySet());
ManagedCredentials managed = managedCredentials;
if (managed != null) all.addAll(managed.identities().keySet());
return Set.copyOf(all);
}
private String identitySecret(String accessKey) {
String secret = configuredIdentities.get(accessKey);
if (secret == null && managedCredentials != null)
secret = managedCredentials.identities().get(accessKey);
return secret;
}
String verify(String method, URI uri, Headers headers) {
return verifyRequest(method, uri, headers).payload();
}
@@ -197,13 +209,13 @@ final class SigV4 {
private String[] credentialScope(String value) {
String[] credential = value.split("/", -1);
if (credential.length != 5 || !(identities.containsKey(credential[0]) || sessions.containsKey(credential[0])) || !credential[2].equals(region)
if (credential.length != 5 || !(identitySecret(credential[0]) != null || 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);
String secret = identitySecret(accessKey);
if (secret == null && sessions.containsKey(accessKey)) secret = sessions.get(accessKey).secret();
if (secret == null) denied("Invalid credential scope");
return secret;
+4 -2
View File
@@ -3,17 +3,19 @@ package cloud.lunarsky.store;
import java.util.Map;
final class StorageLimits {
static final long MAX_OBJECT_BYTES = 64L * 1024 * 1024 * 1024;
private StorageLimits() {}
static ObjectStorage.Limits fromEnvironment(Map<String, String> environment) {
try {
long maxObject = Long.parseLong(environment.getOrDefault("MAX_OBJECT_BYTES", "134217728"));
long maxTotal = Long.parseLong(environment.getOrDefault("MAX_TOTAL_BYTES", "2147483648"));
if (maxObject < 1 || maxObject > 1073741824L || maxTotal < maxObject)
if (maxObject < 1 || maxObject > MAX_OBJECT_BYTES || maxTotal < maxObject)
throw new NumberFormatException();
return new ObjectStorage.Limits(maxObject, maxTotal);
} catch (NumberFormatException error) {
throw new IllegalArgumentException("Invalid storage size limits", error);
throw new IllegalArgumentException("MAX_OBJECT_BYTES must be between 1 and " +
MAX_OBJECT_BYTES + "; MAX_TOTAL_BYTES must be at least MAX_OBJECT_BYTES", error);
}
}
}
@@ -17,12 +17,17 @@ public final class AdminOperationsTest {
}
private static AdminBulkJobs.Snapshot await(AdminBulkJobs jobs, String id) throws Exception {
for (int retry = 0; retry < 200; retry++) {
long deadline = System.nanoTime() + java.util.concurrent.TimeUnit.SECONDS.toNanos(60);
while (System.nanoTime() < deadline) {
AdminBulkJobs.Snapshot snapshot = jobs.get(id);
if (snapshot.finished() != 0) return snapshot;
Thread.sleep(25);
}
throw new AssertionError("Bulk job did not finish");
jobs.cancel(id);
long cancellationDeadline = System.nanoTime() + java.util.concurrent.TimeUnit.SECONDS.toNanos(30);
while (jobs.get(id).finished() == 0 && System.nanoTime() < cancellationDeadline)
Thread.sleep(25);
throw new AssertionError("Bulk job did not finish: " + jobs.get(id));
}
private static void copySafety(DiskStore store) throws Exception {
@@ -0,0 +1,295 @@
package cloud.lunarsky.store;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.sql.DriverManager;
import java.time.Clock;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
final class ClusterCredentialsTest {
private static final String ROOT = "TESTACCESSKEY123";
private static final String ROOT_SECRET = "test-secret-key-that-is-at-least-32-characters";
private static final byte[] MASTER = new byte[32];
private static final byte[] CONTENT = "credential replication test".getBytes(StandardCharsets.UTF_8);
static void run(ClusterStore store, Map<String, String> env) throws Exception {
ManagedCredentials first = credentials(store);
ManagedCredentials second = credentials(store);
ManagedCredentials.Key key = first.create("objects", "images/", Set.of("read", "write", "list"));
verifyPersistence(store, env, key);
verifySnapshot(first, second, key);
verifyHttp(store, first, second, key, env);
verifyConcurrentUpdates(store, first, second);
verifyLateRefresh(store);
verifyRollbackRefusal(store, env);
verifyBucketGuards(store);
System.out.println("Shared credential tests passed: encryption, snapshots, two gateways, revocation, concurrent updates");
}
private static ManagedCredentials credentials(ClusterStore store) throws IOException {
return new ManagedCredentials(store.managedCredentialStore(), MASTER.clone(), Set.of(ROOT));
}
private static void verifyPersistence(ClusterStore store, Map<String, String> env,
ManagedCredentials.Key key) throws Exception {
require(credentials(store).identities().get(key.id()).equals(key.secret()), "Secret did not survive restart");
try (var connection = connect(env); var statement = connection.createStatement();
var rows = statement.executeQuery("SELECT encrypted FROM cluster_managed_credentials")) {
require(rows.next(), "Shared credential state was not written");
require(!new String(rows.getBytes(1), StandardCharsets.ISO_8859_1).contains(key.secret()),
"Shared secret stored in cleartext");
}
byte[] wrong = MASTER.clone();
wrong[0] = 1;
try {
new ManagedCredentials(store.managedCredentialStore(), wrong, Set.of(ROOT));
throw new AssertionError("Wrong master key was accepted");
} catch (IOException expected) {
require(expected.getMessage().contains("decrypted"), "Wrong master key returned unrelated error");
}
try {
new ManagedCredentials(store.managedCredentialStore(), MASTER.clone(), Set.of(ROOT, key.id()));
throw new AssertionError("Configured identity collision was accepted");
} catch (IOException expected) { }
var file = Files.createTempFile("credential-test-master-", ".key");
try {
Files.writeString(file, "00".repeat(32));
ManagedCredentials configured = ManagedCredentials.fromEnvironment(
Map.of("S3_MANAGED_KEYS_MASTER_FILE", file.toString()), store, Set.of(ROOT));
require(configured.identities().containsKey(key.id()), "Cluster environment setup did not use metadata");
} finally {
Files.deleteIfExists(file);
}
}
private static void verifySnapshot(ManagedCredentials first, ManagedCredentials second,
ManagedCredentials.Key key) throws Exception {
second.withSnapshot(() -> {
first.update(key.id(), "objects", "other/", Set.of("write"));
second.checkObject(key.id(), "objects", "images/cat", "GET", Map.of(), new Headers());
require(second.policies().get(key.id()).decide(key.id(), "s3:GetObject",
"arn:aws:s3:::objects/images/cat") > 0, "In-flight request mixed policy revisions");
});
second.withSnapshot(() -> {
try {
second.checkObject(key.id(), "objects", "images/cat", "GET", Map.of(), new Headers());
throw new AssertionError("New request used stale scope");
} catch (StoreException expected) {
require(expected.status == 403, "Wrong scope rejection status");
}
});
first.update(key.id(), "objects", "images/", Set.of("read", "write", "list"));
}
private static void verifyHttp(ClusterStore store, ManagedCredentials first, ManagedCredentials second,
ManagedCredentials.Key key, Map<String, String> env) throws Exception {
HttpServer gatewayA = gateway(store, first);
HttpServer gatewayB = gateway(store, second);
try (HttpClient client = HttpClient.newHttpClient()) {
status(client, gatewayB, key, "PUT", "/objects/images/cat", 200);
status(client, gatewayA, key, "GET", "/objects/images/cat", 200);
status(client, gatewayB, key, "PUT", "/objects/outside/cat", 403);
status(client, gatewayB, key, "GET", "/objects?list-type=2&prefix=images%2F", 200);
status(client, gatewayB, key, "GET", "/objects?list-type=2", 403);
first.setEnabled(key.id(), false);
status(client, gatewayB, key, "GET", "/objects/images/cat", 403);
second.setEnabled(key.id(), true);
status(client, gatewayA, key, "GET", "/objects/images/cat", 200);
first.update(key.id(), "objects", "other/", Set.of("read", "write"));
status(client, gatewayB, key, "GET", "/objects/images/cat", 403);
status(client, gatewayB, key, "PUT", "/objects/other/cat", 200);
verifyReadOnlyRefusal(client, gatewayB, key, env);
first.remove(key.id());
status(client, gatewayB, key, "GET", "/objects/other/cat", 403);
var root = new ManagedCredentials.Key(ROOT, ROOT_SECRET, "", "", Set.of(), true);
status(client, gatewayB, root, "GET", "/objects/images/cat", 200);
} finally {
gatewayA.stop(0);
gatewayB.stop(0);
}
}
private static void verifyReadOnlyRefusal(HttpClient client, HttpServer server,
ManagedCredentials.Key key, Map<String, String> env) throws Exception {
try (var connection = DriverManager.getConnection(env.get("POSTGRES_ADMIN_JDBC_URL"),
env.get("POSTGRES_USER"), env.get("POSTGRES_PASSWORD"));
var statement = connection.createStatement()) {
statement.execute("ALTER DATABASE objectstore_test SET default_transaction_read_only=on");
try {
status(client, server, key, "GET", "/objects/other/cat", 500);
var root = new ManagedCredentials.Key(ROOT, ROOT_SECRET, "", "", Set.of(), true);
status(client, server, root, "GET", "/_objectstore/capabilities", 200);
} finally {
statement.execute("ALTER DATABASE objectstore_test RESET default_transaction_read_only");
}
}
status(client, server, key, "GET", "/objects/other/cat", 200);
}
private static void verifyConcurrentUpdates(ClusterStore store, ManagedCredentials first,
ManagedCredentials second) throws Exception {
try (var executor = Executors.newFixedThreadPool(4)) {
List<Callable<ManagedCredentials.Key>> operations = new ArrayList<>();
for (int i = 0; i < 12; i++) {
ManagedCredentials gateway = i % 2 == 0 ? first : second;
operations.add(() -> gateway.create("objects", "parallel/", Set.of("read")));
}
var results = executor.invokeAll(operations);
var restored = credentials(store);
require(restored.list().size() == 12, "Concurrent creates lost credentials");
for (var result : results)
require(restored.contains(result.get().id()), "Concurrent create was overwritten");
}
var key = credentials(store).list().getFirst();
first.remove(key.id());
try {
second.update(key.id(), "objects", "", Set.of("read"));
throw new AssertionError("Stale update resurrected deleted key");
} catch (StoreException expected) {
require(expected.status == 404, "Wrong stale-update rejection");
}
require(credentials(store).list().size() == 11, "Failed update changed shared state");
}
private static HttpServer gateway(ClusterStore store, ManagedCredentials managed) throws Exception {
SigV4 auth = new SigV4(ROOT, ROOT_SECRET, "us-east-1", Clock.systemUTC());
Main main = new Main(store, store, auth, "objects");
main.setManagedCredentials(managed);
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
server.createContext("/", main::handle);
server.start();
return server;
}
private static void verifyLateRefresh(ClusterStore store) throws Exception {
var delayed = new DelayedReadStore(store.managedCredentialStore());
var managed = new ManagedCredentials(delayed, MASTER.clone(), Set.of(ROOT));
var key = managed.create("objects", "race/", Set.of("read"));
try (var executor = Executors.newSingleThreadExecutor()) {
delayed.delay = true;
var reading = executor.submit(() -> {
managed.withSnapshot(() -> require(!managed.identities().containsKey(key.id()),
"Late metadata read replaced a newer revocation"));
return null;
});
require(delayed.read.await(5, TimeUnit.SECONDS), "Metadata read did not reach barrier");
try { managed.setEnabled(key.id(), false); }
finally { delayed.resume.countDown(); }
reading.get(5, TimeUnit.SECONDS);
}
managed.withSnapshot(() -> require(!managed.identities().containsKey(key.id()),
"Late read left stale credential cache"));
}
private static void verifyRollbackRefusal(ClusterStore store, Map<String, String> env) throws Exception {
var managed = credentials(store);
long originalRevision;
try (var connection = connect(env); var statement = connection.createStatement();
var rows = statement.executeQuery("SELECT revision FROM cluster_managed_credentials")) {
rows.next();
originalRevision = rows.getLong(1);
}
try (var connection = connect(env); var statement = connection.createStatement()) {
statement.executeUpdate("UPDATE cluster_managed_credentials SET revision=revision-1");
try {
managed.withSnapshot(() -> { throw new AssertionError("Rolled-back metadata was trusted"); });
throw new AssertionError("Credential revision regression was accepted");
} catch (IOException expected) {
require(expected.getMessage().contains("backwards"), "Wrong revision regression error");
}
try {
managed.create("objects", "rollback/", Set.of("read"));
throw new AssertionError("Mutation overwrote rolled-back credential metadata");
} catch (IOException expected) {
require(expected.getMessage().contains("backwards"), "Wrong mutation regression error");
} finally {
statement.executeUpdate("UPDATE cluster_managed_credentials SET revision=" + originalRevision);
}
}
}
private static void verifyBucketGuards(ClusterStore store) throws Exception {
store.createBucket("credential-source");
var managed = credentials(store);
var key = managed.create("credential-source", "", Set.of("read"));
for (String operation : List.of("rename", "delete")) {
try {
if (operation.equals("rename")) store.renameBucket("credential-source", "credential-target");
else store.deleteBucket("credential-source");
throw new AssertionError("Scoped bucket " + operation + " was accepted");
} catch (StoreException expected) {
require(expected.code.equals("BucketHasScopedKeys"), "Wrong scoped bucket rejection");
}
}
managed.remove(key.id());
store.renameBucket("credential-source", "credential-target");
try {
managed.create("credential-source", "", Set.of("read"));
throw new AssertionError("Credential was bound to a renamed-away bucket");
} catch (StoreException expected) {
require(expected.status == 404, "Wrong missing bucket rejection");
}
store.deleteBucket("credential-target");
}
private static final class DelayedReadStore implements ManagedCredentialStore {
private final ManagedCredentialStore delegate;
private final CountDownLatch read = new CountDownLatch(1);
private final CountDownLatch resume = new CountDownLatch(1);
private volatile boolean delay;
DelayedReadStore(ManagedCredentialStore delegate) { this.delegate = delegate; }
@Override public boolean shared() { return true; }
@Override public State update(Change change) throws IOException { return delegate.update(change); }
@Override public State read(long knownRevision) throws IOException {
State state = delegate.read(knownRevision);
if (delay) {
delay = false;
read.countDown();
try {
if (!resume.await(10, TimeUnit.SECONDS)) throw new IOException("Timed out waiting for mutation");
} catch (InterruptedException error) {
Thread.currentThread().interrupt();
throw new IOException("Metadata test interrupted", error);
}
}
return state;
}
}
private static void status(HttpClient client, HttpServer server, ManagedCredentials.Key key,
String method, String path, int expected) throws Exception {
URI uri = URI.create("http://127.0.0.1:" + server.getAddress().getPort() + path);
byte[] body = method.equals("PUT") ? CONTENT : new byte[0];
var response = client.send(HttpTest.signedUriAs(uri, method, body, Map.of(), key.id(), key.secret()),
HttpResponse.BodyHandlers.ofByteArray());
require(response.statusCode() == expected, "Expected " + expected + " for " + method + " " + path +
"; got " + response.statusCode());
if (method.equals("GET") && expected == 200 && path.startsWith("/objects/") && !path.contains("?"))
require(Arrays.equals(response.body(), CONTENT), "Object content changed");
}
private static java.sql.Connection connect(Map<String, String> env) throws Exception {
return DriverManager.getConnection(env.get("POSTGRES_JDBC_URL"),
env.get("POSTGRES_USER"), env.get("POSTGRES_PASSWORD"));
}
private static void require(boolean condition, String message) {
if (!condition) throw new AssertionError(message);
}
}
@@ -37,6 +37,7 @@ public final class ClusterMetadataTest {
}
}
require(store.ready(), "Writable metadata did not recover after read-only mode ended");
ClusterCredentialsTest.run(store, env);
}
} finally {
firstServer.stop(0);
@@ -0,0 +1,207 @@
package cloud.lunarsky.store;
import com.sun.net.httpserver.HttpServer;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpResponse;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.time.Clock;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Map;
import java.util.concurrent.Executors;
public final class LargeObjectTest {
private static final long LARGE_LENGTH = 3L * 1024 * 1024 * 1024 + 17;
private static final byte[] TAIL = "last bytes past the integer boundary".getBytes(
java.nio.charset.StandardCharsets.US_ASCII);
public static void main(String[] args) throws Exception {
configuration();
Path root = Files.createTempDirectory("large-object-test-");
try {
boundedUploads(root.resolve("uploads"));
sparseReads(root.resolve("sparse"));
} finally {
try (var files = Files.walk(root)) {
for (Path file : files.sorted(Comparator.reverseOrder()).toList()) Files.delete(file);
}
}
System.out.println("Large object limits, bounded uploads and sparse range tests passed");
}
private static void configuration() {
var defaults = StorageLimits.fromEnvironment(Map.of());
check(defaults.maxObjectBytes() == 134217728L, "Object default changed");
check(defaults.maxTotalBytes() == 2147483648L, "Total default changed");
long maximum = StorageLimits.MAX_OBJECT_BYTES;
check(limits(maximum, maximum).maxObjectBytes() == maximum, "64 GiB ceiling rejected");
check(limits(LARGE_LENGTH, Long.MAX_VALUE).maxObjectBytes() == LARGE_LENGTH,
"Object size was narrowed to an integer");
invalidLimits(0, maximum);
invalidLimits(-1, maximum);
invalidLimits(maximum + 1, maximum + 1);
invalidLimits(maximum, maximum - 1);
invalidLimits(1, -1);
try {
StorageLimits.fromEnvironment(Map.of("MAX_OBJECT_BYTES", "not-a-size"));
throw new AssertionError("Non-numeric limit accepted");
} catch (IllegalArgumentException expected) {
check(expected.getMessage().contains("MAX_OBJECT_BYTES"), "Missing setting in error");
}
}
private static ObjectStorage.Limits limits(long object, long total) {
return StorageLimits.fromEnvironment(Map.of("MAX_OBJECT_BYTES", Long.toString(object),
"MAX_TOTAL_BYTES", Long.toString(total)));
}
private static void invalidLimits(long object, long total) {
try {
limits(object, total);
throw new AssertionError("Invalid storage limits accepted");
} catch (IllegalArgumentException expected) { }
}
private static void boundedUploads(Path root) throws Exception {
try (var store = new DiskStore(root, StorageLimits.MAX_OBJECT_BYTES,
StorageLimits.MAX_OBJECT_BYTES * 2)) {
store.ensureBucket("objects");
int length = 8 * 1024 * 1024 + 17;
var body = new BoundedInput(length);
var metadata = store.put("objects", "stream", body, length, null, null, false,
"application/octet-stream");
check(metadata.length() == length && body.remaining == 0, "Upload truncated");
try (var opened = store.open("objects", "stream")) {
check(opened.stream().transferTo(java.io.OutputStream.nullOutputStream()) == length,
"Streamed download truncated");
}
StoreTest.fails(400, () -> store.put("objects", "incomplete", new BoundedInput(17),
LARGE_LENGTH, null, null, false, "application/octet-stream"));
StoreTest.fails(413, () -> store.put("objects", "too-large", unreadable(),
StorageLimits.MAX_OBJECT_BYTES + 1, null, null, false, "application/octet-stream"));
multipartBoundaries(store);
check(store.usedBytes() == length, "Failed upload changed accounted bytes");
try (var pending = Files.list(root.resolve("pending"))) {
check(pending.findAny().isEmpty(), "Failed upload left a staged file");
}
}
}
private static void multipartBoundaries(DiskStore store) throws Exception {
var multipart = new MultipartStore(store);
String id = multipart.create("objects", "multipart", "application/octet-stream",
Map.of(), Map.of(), Map.of());
StoreTest.fails(400, () -> multipart.putPart(id, "objects", "multipart", 1,
new BoundedInput(17), LARGE_LENGTH, null, null));
StoreTest.fails(413, () -> multipart.putPart(id, "objects", "multipart", 1,
unreadable(), StorageLimits.MAX_OBJECT_BYTES + 1, null, null));
check(multipart.stagedBytes() == 0, "Failed part changed accounted bytes");
multipart.abort(id, "objects", "multipart");
}
private static InputStream unreadable() {
return new InputStream() {
@Override public int read() { throw new AssertionError("Rejected payload was read"); }
};
}
private static final class BoundedInput extends InputStream {
private long remaining;
BoundedInput(long remaining) { this.remaining = remaining; }
@Override public int read() {
if (remaining == 0) return -1;
remaining--;
return 71;
}
@Override public int read(byte[] bytes, int offset, int length) {
check(bytes.length <= 65536, "Upload allocated a payload-sized buffer");
if (length == 0) return 0;
if (remaining == 0) return -1;
int count = (int) Math.min(length, remaining);
Arrays.fill(bytes, offset, offset + count, (byte) 71);
remaining -= count;
return count;
}
}
private static void sparseReads(Path root) throws Exception {
sparseFixture(root);
try (var store = new DiskStore(root, StorageLimits.MAX_OBJECT_BYTES,
StorageLimits.MAX_OBJECT_BYTES * 2)) {
check(store.usedBytes() == LARGE_LENGTH, "Restart truncated the object length");
var executor = Executors.newVirtualThreadPerTaskExecutor();
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 8);
try (HttpClient client = HttpClient.newHttpClient()) {
var app = new Main(store, new SigV4("TESTACCESSKEY123",
"test-secret-key-that-is-at-least-32-characters", "us-east-1", Clock.systemUTC()),
"objects");
server.setExecutor(executor);
server.createContext("/", app::handle);
server.start();
URI uri = URI.create("http://127.0.0.1:" + server.getAddress().getPort() + "/objects/sparse");
readRequests(client, uri);
} finally {
server.stop(0);
executor.close();
}
store.delete("objects", "sparse");
check(store.usedBytes() == 0, "Deleting a large object left accounted bytes");
}
}
private static void readRequests(HttpClient client, URI uri) throws Exception {
var head = client.send(HttpTest.signedUri(uri, "HEAD", new byte[0], Map.of()),
HttpResponse.BodyHandlers.ofByteArray());
check(head.statusCode() == 200, "Large object HEAD failed");
check(head.headers().firstValueAsLong("Content-Length").orElse(-1) == LARGE_LENGTH,
"HEAD narrowed Content-Length");
String start = Long.toString(LARGE_LENGTH - TAIL.length);
for (String range : new String[] {"bytes=" + start + "-", "bytes=-" + TAIL.length}) {
var response = client.send(HttpTest.signedUri(uri, "GET", new byte[0], Map.of("range", range)),
HttpResponse.BodyHandlers.ofByteArray());
check(response.statusCode() == 206 && Arrays.equals(response.body(), TAIL),
"Range beyond 2 GiB returned incorrect data");
check(response.headers().firstValue("Content-Range").orElse("").equals(
"bytes " + start + "-" + (LARGE_LENGTH - 1) + "/" + LARGE_LENGTH),
"Range metadata narrowed the object length");
}
}
/** Builds a sparse length fixture; it does not write or hash gigabytes of data. */
private static void sparseFixture(Path root) throws Exception {
try (var store = new DiskStore(root, StorageLimits.MAX_OBJECT_BYTES,
StorageLimits.MAX_OBJECT_BYTES * 2)) {
store.ensureBucket("objects");
store.put("objects", "sparse", new ByteArrayInputStream(TAIL), TAIL.length, null, null,
false, "application/octet-stream");
}
Path record;
try (var files = Files.walk(root.resolve("objects"))) {
record = files.filter(Files::isRegularFile).findFirst().orElseThrow();
}
long headerLength = Files.size(record) - TAIL.length;
try (FileChannel file = FileChannel.open(record, StandardOpenOption.WRITE)) {
write(file, ByteBuffer.allocate(Long.BYTES).putLong(LARGE_LENGTH).flip(), Long.BYTES);
write(file, ByteBuffer.wrap(TAIL), headerLength + LARGE_LENGTH - TAIL.length);
}
}
private static void write(FileChannel file, ByteBuffer bytes, long position) throws Exception {
while (bytes.hasRemaining()) position += file.write(bytes, position);
}
private static void check(boolean condition, String message) {
if (!condition) throw new AssertionError(message);
}
}
@@ -22,6 +22,7 @@ public final class NodeHttpTest {
public static void main(String[] args) throws Exception {
try (HttpClient client = HttpClient.newBuilder().version(HttpClient.Version.HTTP_1_1).build()) {
warmUp(client);
stalledBody(client, false);
stalledBody(client, true);
oversizedBody(client);
@@ -32,6 +33,22 @@ public final class NodeHttpTest {
System.out.println("Node HTTP tests passed: total deadlines, cancellation, bounded responses, interruption");
}
private static void warmUp(HttpClient client) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
server.createContext("/", exchange -> {
exchange.sendResponseHeaders(204, -1);
exchange.close();
});
server.start();
try {
URI uri = URI.create("http://127.0.0.1:" + server.getAddress().getPort());
HttpRequest request = HttpRequest.newBuilder(uri).timeout(Duration.ofSeconds(10)).GET().build();
require(NodeHttp.bytes(client, request, 0).statusCode() == 204, "HTTP client warm-up failed");
} finally {
server.stop(0);
}
}
private static void stalledBody(HttpClient client, boolean discard) throws Exception {
try (StalledResponse server = new StalledResponse(1)) {
HttpRequest request = HttpRequest.newBuilder(server.uri()).timeout(Duration.ofMillis(500)).GET().build();
+9
View File
@@ -0,0 +1,9 @@
FROM postgres:17-alpine
RUN apk add --no-cache python3 py3-pip py3-psycopg2 && \
python3 -m venv --system-site-packages /opt/patroni && \
/opt/patroni/bin/pip install --no-cache-dir 'patroni[etcd3]==4.1.5'
COPY patroni.yaml /etc/patroni.yaml
COPY bootstrap.sh /usr/local/bin/bootstrap-objectstore
RUN chmod 755 /usr/local/bin/bootstrap-objectstore
USER postgres
ENTRYPOINT ["/opt/patroni/bin/patroni", "/etc/patroni.yaml"]
+74
View File
@@ -0,0 +1,74 @@
# Metadata failover drill
This isolated test runs three PostgreSQL members under Patroni, three etcd voters,
two storage nodes, and one ObjectStore gateway. It tests automatic metadata
promotion and gateway reconnection. All containers run on one machine, so it
does not establish physical fault isolation or production readiness.
Requires Docker Compose, Python 3, and about 2 GiB of available Docker memory.
PostgreSQL and etcd use disposable volumes that survive container restarts. Only the gateway
has a published port, allocated on loopback. The script generates a unique
Compose project and removes its containers and volumes on exit. It never uses
the repository's `.env` or an existing deployment.
```sh
python3 scripts/test-ha.py --output out/ha-report.json
```
To reuse an image built from this checkout, add `--image IMAGE`. The report path
must not already exist. Keep reports outside Git if they contain local details.
The test:
1. Waits for a primary and synchronous standby, then writes small signed objects.
2. Kills the primary container without stopping the gateway.
3. Waits for Patroni promotion, reads every acknowledged object, and writes more.
4. Restarts the old primary and checks that it rejoins the cluster.
5. Kills both standbys and checks that strict replication stops acknowledging writes.
6. Restores them, then stops two etcd voters and checks that readiness and writes fail.
7. Restores quorum and verifies acknowledged objects again.
The database uses synchronous replication with `synchronous_mode_strict: true`.
Losing the eligible synchronous replicas can stop writes; availability must not
silently take priority over the configured durability policy. Requests interrupted
by a failure have uncertain outcomes and are not counted as acknowledged.
See [Patroni replication modes](https://patroni.readthedocs.io/en/latest/replication_modes.html).
## Operating metadata HA on separate machines
Use the tested configuration as a behavior reference, not deployment credentials.
The fixture has public test passwords, private-network plaintext traffic, and no
hardware watchdog. Never expose its database, etcd, or Patroni APIs.
For a separately operated HA deployment:
1. Place the three PostgreSQL members and etcd majority across independent machines.
Give each member durable storage and unique credentials. Keep ObjectStore's
database role separate from PostgreSQL superuser and replication roles.
2. Configure TLS and authentication for etcd peer/client traffic and Patroni's
management API. Enable PostgreSQL TLS with hostname verification on every client.
3. Enable Patroni synchronous mode, strict mode, and at least one synchronous
standby. Keep PostgreSQL `synchronous_commit=on`; do not override it in the
ObjectStore database or role settings.
4. Configure and test host fencing. Patroni's required watchdog mode refuses
promotion if its watchdog is unavailable. A stalled controller must not leave
an old primary accepting writes after its lease expires. The local fixture
intentionally cannot reboot the machine. See
[Patroni watchdog requirements](https://patroni.readthedocs.io/en/latest/watchdog.html).
5. Give each gateway and maintenance process a primary-only JDBC URL:
```text
jdbc:postgresql://db-a:5432,db-b:5432,db-c:5432/objectstore?targetServerType=primary&connectTimeout=3&socketTimeout=10&hostRecheckSeconds=1&sslmode=verify-full&sslrootcert=/certs/metadata-ca.pem
```
6. Back up PostgreSQL and storage independently of this cluster. Rehearse restore
into fresh infrastructure; replication does not protect against deletion or
an administrative mistake. Recover the managed-credential encryption key with
the metadata backup when managed credentials are enabled.
7. Repeat the drill on those machines, including network partitions and fencing,
before directing important data to them. Monitor replication lag, quorum,
disk space, backup age, and restore results.
ObjectStore reconnects to the elected primary; Patroni controls promotion and
demotion. Do not promote a database by hand while its former primary can still
accept traffic. Do not force promotion of a stale replica to make a test pass.
+6
View File
@@ -0,0 +1,6 @@
#!/bin/sh
set -eu
psql "$1" -v ON_ERROR_STOP=1 -c \
"CREATE ROLE objectstore LOGIN PASSWORD 'ha-test-database-password'"
psql "$1" -v ON_ERROR_STOP=1 -c \
'CREATE DATABASE objectstore OWNER objectstore'
+128
View File
@@ -0,0 +1,128 @@
x-etcd: &etcd
image: quay.io/coreos/etcd:v3.6.5
entrypoint: /usr/local/bin/etcd
mem_limit: 128m
volumes:
- /etcd-data
security_opt:
- no-new-privileges:true
x-etcd-env: &etcd-env
ETCD_DATA_DIR: /etcd-data
ETCD_LISTEN_CLIENT_URLS: http://0.0.0.0:2379
ETCD_LISTEN_PEER_URLS: http://0.0.0.0:2380
ETCD_INITIAL_CLUSTER: etcd-a=http://etcd-a:2380,etcd-b=http://etcd-b:2380,etcd-c=http://etcd-c:2380
ETCD_INITIAL_CLUSTER_TOKEN: objectstore-disposable-ha-test
ETCD_INITIAL_CLUSTER_STATE: new
ETCD_QUOTA_BACKEND_BYTES: "33554432"
ETCD_MAX_WALS: "2"
ETCD_MAX_SNAPSHOTS: "2"
ETCD_LOG_LEVEL: warn
x-postgres: &postgres
image: objectstore-ha-postgres:local
build: .
mem_limit: 256m
volumes:
- /var/lib/postgresql/data
security_opt:
- no-new-privileges:true
depends_on:
- etcd-a
- etcd-b
- etcd-c
x-node: &node
image: ${OBJECTSTORE_HA_IMAGE:-objectstore-ha-test:local}
entrypoint: [java, -Xmx96m, --add-modules, "jdk.httpserver,java.net.http", -cp, /app:/app/postgresql.jar:/app/hash4j.jar, cloud.lunarsky.store.ClusterNode]
mem_limit: 160m
environment:
CLUSTER_TOKEN: ha-test-cluster-token-012345678901234567
CLUSTER_REPAIR_TOKEN: ha-test-repair-token-012345678901234567
CLUSTER_HOST_ID: 82ae31fb-522e-40c6-ac78-aa1c003f9a18
DATA_DIR: /data
NODE_BIND: 0.0.0.0
volumes:
- /data
healthcheck:
test: ["CMD", "wget", "-qO-", "http://127.0.0.1:9100/health"]
interval: 2s
timeout: 2s
retries: 30
services:
etcd-a:
<<: *etcd
environment:
<<: *etcd-env
ETCD_NAME: etcd-a
ETCD_ADVERTISE_CLIENT_URLS: http://etcd-a:2379
ETCD_INITIAL_ADVERTISE_PEER_URLS: http://etcd-a:2380
etcd-b:
<<: *etcd
environment:
<<: *etcd-env
ETCD_NAME: etcd-b
ETCD_ADVERTISE_CLIENT_URLS: http://etcd-b:2379
ETCD_INITIAL_ADVERTISE_PEER_URLS: http://etcd-b:2380
etcd-c:
<<: *etcd
environment:
<<: *etcd-env
ETCD_NAME: etcd-c
ETCD_ADVERTISE_CLIENT_URLS: http://etcd-c:2379
ETCD_INITIAL_ADVERTISE_PEER_URLS: http://etcd-c:2380
db-a:
<<: *postgres
environment:
PATRONI_NAME: db-a
PATRONI_POSTGRESQL_CONNECT_ADDRESS: db-a:5432
PATRONI_RESTAPI_CONNECT_ADDRESS: db-a:8008
db-b:
<<: *postgres
environment:
PATRONI_NAME: db-b
PATRONI_POSTGRESQL_CONNECT_ADDRESS: db-b:5432
PATRONI_RESTAPI_CONNECT_ADDRESS: db-b:8008
db-c:
<<: *postgres
environment:
PATRONI_NAME: db-c
PATRONI_POSTGRESQL_CONNECT_ADDRESS: db-c:5432
PATRONI_RESTAPI_CONNECT_ADDRESS: db-c:8008
node-a:
<<: *node
node-b:
<<: *node
gateway:
image: ${OBJECTSTORE_HA_IMAGE:-objectstore-ha-test:local}
mem_limit: 256m
environment:
STORE_MODE: cluster
CLUSTER_LOCAL_DEV: "true"
CLUSTER_TEST_NODE_DOMAINS: "true"
CLUSTER_NODES: http://node-a:9100,http://node-b:9100
CLUSTER_TOKEN: ha-test-cluster-token-012345678901234567
POSTGRES_JDBC_URL: jdbc:postgresql://db-a:5432,db-b:5432,db-c:5432/objectstore?targetServerType=primary&connectTimeout=1&socketTimeout=5&hostRecheckSeconds=0
POSTGRES_USER: objectstore
POSTGRES_PASSWORD: ha-test-database-password
S3_ACCESS_KEY: HaTestAccessKey0001
S3_SECRET_KEY: ha-test-s3-secret-01234567890123456789
S3_BUCKET: ha-test
MAX_OBJECT_BYTES: "1048576"
MAX_TOTAL_BYTES: "16777216"
BIND_ADDRESS: 0.0.0.0
ports:
- "127.0.0.1::9000"
networks:
- default
- client
depends_on:
node-a:
condition: service_healthy
node-b:
condition: service_healthy
networks:
default:
internal: true
client: {}
+54
View File
@@ -0,0 +1,54 @@
scope: objectstore-ha-test
namespace: /objectstore-test/
restapi:
listen: 0.0.0.0:8008
authentication:
username: operator
password: ha-test-rest-password
etcd3:
hosts: etcd-a:2379,etcd-b:2379,etcd-c:2379
bootstrap:
dcs:
ttl: 20
loop_wait: 2
retry_timeout: 3
primary_start_timeout: 0
primary_stop_timeout: 5
synchronous_mode: true
synchronous_mode_strict: true
synchronous_node_count: 1
failsafe_mode: false
postgresql:
use_pg_rewind: true
parameters:
synchronous_commit: "on"
password_encryption: scram-sha-256
shared_buffers: 32MB
max_connections: 64
max_wal_size: 128MB
min_wal_size: 32MB
wal_keep_size: 64MB
max_slot_wal_keep_size: 128MB
initdb:
- encoding: UTF8
- data-checksums
post_bootstrap: /usr/local/bin/bootstrap-objectstore
postgresql:
listen: 0.0.0.0:5432
data_dir: /var/lib/postgresql/data/pgdata
pgpass: /tmp/pgpass
basebackup:
checkpoint: fast
authentication:
superuser:
username: postgres
password: ha-test-superuser-password
replication:
username: replicator
password: ha-test-replication-password
pg_hba:
- local all all trust
- host replication replicator all scram-sha-256
- host all all all scram-sha-256
watchdog:
mode: "off"
+2 -1
View File
@@ -17,9 +17,10 @@ services:
check:
build:
context: ../..
image: lunarsky-objectstore:metadata-test
image: ${OBJECTSTORE_TEST_IMAGE:-lunarsky-objectstore:metadata-test}
entrypoint: ["java", "--add-modules", "jdk.httpserver,java.net.http", "-cp", "/app:/app/postgresql.jar:/app/hash4j.jar", "cloud.lunarsky.store.ClusterMetadataTest"]
environment:
JAVA_TOOL_OPTIONS: -Xmx192m -XX:ActiveProcessorCount=2
POSTGRES_JDBC_URL: jdbc:postgresql://127.0.0.2:5432,metadata:5432/objectstore_test?connectTimeout=1&socketTimeout=10&targetServerType=primary&hostRecheckSeconds=0
POSTGRES_ADMIN_JDBC_URL: jdbc:postgresql://metadata:5432/postgres?connectTimeout=3&socketTimeout=10
POSTGRES_USER: objectstore_test
+1 -1
View File
@@ -47,4 +47,4 @@ Stop the node container on machine A and repeat the rejection and read checks us
For a manual metadata recovery drill, take a custom-format `pg_dump` after the last acknowledged write and verify it with `pg_restore --list`. Copy the dump to machine B and restore it into a fresh PostgreSQL volume there. Stop the original gateway and metadata container on machine A. Start a separate gateway against the restored database, then verify the journal. Finally stop the storage node on machine A and verify again: this forces reads to use both the restored metadata and the replica on machine B. Keep the backup and its credentials private.
Passing this drill does not prove every crash point, disk-controller write behavior, long-term bit-rot resistance, automatic metadata failover, or production readiness. The cluster still requires a manual metadata restore.
Passing this drill does not prove every crash point, disk-controller write behavior, long-term bit-rot resistance, automatic metadata failover, or production readiness. This drill uses manual metadata restore. The separate [local HA drill](../ha/README.md) tests automatic promotion with Patroni; it does not replace validation across physical machines.