Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d73fa2c435 | ||
|
|
b724a21a0d | ||
|
|
3c739deb09 | ||
|
|
5304dfc047 | ||
|
|
fbec6694df | ||
|
|
240c278621 | ||
|
|
bd6bb52dc7 | ||
|
|
35bd1d5703 |
No files matched your search
@@ -6,6 +6,8 @@ POSTGRES_PASSWORD=[PG_Pass]
|
||||
S3_BUCKET=objects
|
||||
S3_CREDENTIALS_FILE=
|
||||
S3_KEY_SCOPES_FILE=
|
||||
S3_SESSION_CREDENTIALS_FILE=
|
||||
S3_IDENTITY_POLICIES_DIR=
|
||||
METRICS_BEARER_TOKEN=
|
||||
CLUSTER_HOST_PORT=9001
|
||||
MAX_OBJECT_BYTES=134217728
|
||||
@@ -16,6 +18,7 @@ OBJECTSTORE_RESPONSE_TIMEOUT_SECONDS=0
|
||||
CORS_ALLOWED_ORIGINS=
|
||||
HTTP_BACKLOG=64
|
||||
S3_VIRTUAL_HOST_SUFFIX=
|
||||
S3_PUBLIC_ENDPOINT=
|
||||
# For compose.cluster.encrypted.yaml only; provision and mount LUKS before setting these.
|
||||
ENCRYPTED_STORAGE_ROOT=
|
||||
ENCRYPTED_VOLUME_ID=
|
||||
@@ -6,8 +6,15 @@ S3_BUCKET=objects
|
||||
S3_REGION=us-east-1
|
||||
S3_CREDENTIALS_FILE=
|
||||
S3_KEY_SCOPES_FILE=
|
||||
S3_SESSION_CREDENTIALS_FILE=
|
||||
S3_IDENTITY_POLICIES_DIR=
|
||||
METRICS_BEARER_TOKEN=
|
||||
HOST_PORT=9000
|
||||
# Optional admin overlay: keep the default loopback bind, or use a VPN interface IP.
|
||||
ADMIN_UI_BIND_IP=127.0.0.1
|
||||
ADMIN_UI_HOST_PORT=9001
|
||||
ADMIN_UI_PRIVATE_ORIGIN=
|
||||
# Managed access keys require compose.credentials.yaml and a separate master key.
|
||||
MAX_OBJECT_BYTES=134217728
|
||||
MAX_TOTAL_BYTES=2147483648
|
||||
PUBLIC_REQUESTS_PER_SECOND=0
|
||||
@@ -19,6 +26,7 @@ PUBLIC_TRUSTED_PROXY_IPS=
|
||||
MAX_IN_FLIGHT_REQUESTS=16
|
||||
HTTP_BACKLOG=64
|
||||
S3_VIRTUAL_HOST_SUFFIX=
|
||||
S3_PUBLIC_ENDPOINT=
|
||||
CORS_ALLOWED_ORIGINS=
|
||||
OBJECTSTORE_REQUEST_TIMEOUT_SECONDS=0
|
||||
OBJECTSTORE_RESPONSE_TIMEOUT_SECONDS=0
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -4,6 +4,7 @@ rust-client/target/
|
||||
.env.cluster
|
||||
*.local.env
|
||||
data/
|
||||
secrets/
|
||||
*.log
|
||||
__pycache__/
|
||||
*.pyc
|
||||
|
||||
@@ -1,31 +1,46 @@
|
||||
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
|
||||
COPY test ./test
|
||||
COPY admin-ui ./admin-ui
|
||||
COPY lib/hash4j-0.30.0.jar /tmp/hash4j.jar
|
||||
RUN echo 'd3224b113ea835ce3452097747e5209ec760cf443dbed770d6ba68a0d480178f /tmp/hash4j.jar' | sha256sum -c -
|
||||
RUN mkdir /out && javac --release 21 --add-modules jdk.httpserver,java.net.http -cp /tmp/hash4j.jar -d /out src/cloud/lunarsky/store/*.java test/cloud/lunarsky/store/*.java
|
||||
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
|
||||
RUN java --add-modules jdk.httpserver -cp /out:/tmp/hash4j.jar cloud.lunarsky.store.ConcurrencyTest
|
||||
RUN java --add-modules jdk.httpserver,java.net.http -cp /out:/tmp/hash4j.jar cloud.lunarsky.store.HttpTest
|
||||
RUN java --add-modules jdk.httpserver,java.net.http -cp /out:/tmp/hash4j.jar cloud.lunarsky.store.ClientLimitsTest
|
||||
RUN java --add-modules jdk.httpserver,java.net.http -cp /out:/tmp/hash4j.jar cloud.lunarsky.store.AdminConsoleTest
|
||||
RUN java --add-modules jdk.httpserver,java.net.http -cp /out:/tmp/hash4j.jar cloud.lunarsky.store.RequestCoordinationTest
|
||||
RUN java -cp /out:/tmp/hash4j.jar cloud.lunarsky.store.RequestDiagnosticsTest
|
||||
RUN java -cp /out:/tmp/hash4j.jar cloud.lunarsky.store.BucketActivityTest
|
||||
RUN java --add-modules jdk.httpserver -cp /out:/tmp/hash4j.jar cloud.lunarsky.store.AdminOperationsTest
|
||||
RUN java --add-modules jdk.httpserver -cp /out:/tmp/hash4j.jar cloud.lunarsky.store.AdminBulkJobsTest
|
||||
RUN java --add-modules jdk.httpserver,java.net.http -cp /out:/tmp/hash4j.jar cloud.lunarsky.store.FeatureTest
|
||||
RUN java -cp /out:/tmp/hash4j.jar cloud.lunarsky.store.EncryptedVolumeTest
|
||||
RUN java --add-modules jdk.httpserver,java.net.http -cp /out:/tmp/hash4j.jar cloud.lunarsky.store.NodeHttpTest
|
||||
RUN java --add-modules jdk.httpserver,java.net.http -cp /out:/tmp/hash4j.jar cloud.lunarsky.store.ClusterNodeTest
|
||||
RUN java --add-modules jdk.httpserver,java.net.http -cp /out:/tmp/hash4j.jar cloud.lunarsky.store.ClusterTlsTest
|
||||
RUN java -cp /out:/tmp/hash4j.jar cloud.lunarsky.store.CliTest
|
||||
|
||||
FROM eclipse-temurin:21-jre-alpine
|
||||
WORKDIR /app
|
||||
RUN addgroup -g 10001 store && adduser -D -u 10001 -G store store && mkdir /data && chown store:store /data
|
||||
COPY --from=build /out /app
|
||||
COPY --from=build /tmp/postgresql.jar /app/postgresql.jar
|
||||
COPY --from=build /tmp/hash4j.jar /app/hash4j.jar
|
||||
COPY lib/LICENSE.hash4j /app/LICENSE.hash4j
|
||||
COPY admin-ui /app/admin-ui
|
||||
COPY scripts/objectstore /usr/local/bin/objectstore
|
||||
COPY scripts/start-server.sh /usr/local/bin/objectstore-server
|
||||
RUN chmod 755 /usr/local/bin/objectstore /usr/local/bin/objectstore-server
|
||||
USER store
|
||||
EXPOSE 9000
|
||||
EXPOSE 9000 9001
|
||||
ENTRYPOINT ["/usr/local/bin/objectstore-server"]
|
||||
@@ -23,11 +23,19 @@ This does not cover Docker logs, swap, other temporary files, external backups,
|
||||
|
||||
`S3_ACCESS_KEY` and `S3_SECRET_KEY` define the owner. For additional identities, put one `ACCESSKEY:secret` pair per line in a private file and mount it read-only at `/run/secrets/s3-credentials` on `objectstore` (or `gateway` in cluster mode). Set `S3_CREDENTIALS_FILE` to that path. Keys need 16–128 alphanumeric characters; secrets need at least 32 characters. Changes load on restart. Additional identities have no access until granted it.
|
||||
|
||||
The owner can set `x-amz-acl: public-read` or signed `x-amz-grant-*` headers on bucket creation, uploads, copies, and multipart initiation. Use `GET ?acl` to read bucket or object grants; `PUT ?acl` accepts signed grant headers or an XML `AccessControlPolicy`. A grantee ID is its access key. Permissions are `READ`, `WRITE`, `READ_ACP`, `WRITE_ACP`, and `FULL_CONTROL`; `AllUsers` can only read, and `AuthenticatedUsers` is recognized. Anonymous reads require an `AllUsers` grant. Overwriting an object resets its ACL to private unless new grants are supplied; retained versions keep their ACLs.
|
||||
New buckets default to `BucketOwnerEnforced` and all four Block Public Access flags enabled. Existing buckets retain their prior ACL behavior on upgrade. The owner can inspect or change settings with `GET`/`PUT ?ownershipControls` and `GET`/`PUT ?publicAccessBlock`; changing a legacy bucket to owner-enforced immediately stops its ACL grants from authorizing requests. Public ACL writes are blocked when `BlockPublicAcls` is enabled, and existing public ACL grants are ignored when `IgnorePublicAcls` is enabled. `GET`/`PUT`/`DELETE ?policy` manages a bucket policy. `BlockPublicPolicy` rejects new policies that allow a wildcard principal; `RestrictPublicBuckets` prevents anonymous access through such a policy.
|
||||
|
||||
For a narrower additional key, mount a second private file and set `S3_KEY_SCOPES_FILE` to its container path. Each non-comment line has four **tab-separated** fields: access key, bucket, key prefix, and comma-separated actions (`read`, `write`, `list`). For example, `UPLOADKEY12345678<TAB>media<TAB>users/42/<TAB>read,write,list`. The file must name an identity in `S3_CREDENTIALS_FILE`; the owner key is always unrestricted. Once the scope file is enabled, an additional key with no scope is denied. A list request must include a prefix inside the granted prefix. Copy requires read permission on the source and write permission on the destination. Restricted keys cannot change ACLs or manage buckets. Existing S3 ACL checks still apply, so the bucket must also grant the key the corresponding permissions. Restart the service after editing either file.
|
||||
On a bucket with ACLs enabled, the owner can set `x-amz-acl: public-read` or signed `x-amz-grant-*` headers on bucket creation, uploads, copies, and multipart initiation. Use `GET ?acl` to read bucket or object grants; `PUT ?acl` accepts signed grant headers or an XML `AccessControlPolicy`. A grantee ID is its access key. Permissions are `READ`, `WRITE`, `READ_ACP`, `WRITE_ACP`, and `FULL_CONTROL`; `AllUsers` can only read, and `AuthenticatedUsers` is recognized. Anonymous reads require an `AllUsers` grant or an allowed bucket policy. Overwriting an object resets its ACL to private unless new grants are supplied; retained versions keep their ACLs. Email grantees return `405 MethodNotAllowed`, matching AWS's removal of that grant type.
|
||||
|
||||
The configured owner owns every bucket and object. A `WRITE_ACP` grantee can change an ACL only on a retained, non-null version; current unversioned and null versions require the owner key. Version lists, multipart inspection, tags, versioning controls, bucket creation/deletion, and capabilities remain owner-only. IAM policies, email grantees, Object Ownership, Block Public Access, and temporary credentials are unsupported. Public bucket `READ` exposes names; public object `READ` exposes bytes. Review grants before exposing a gateway.
|
||||
For a narrower additional key, mount a second private file and set `S3_KEY_SCOPES_FILE` to its container path. Each non-comment line has four **tab-separated** fields: access key, bucket, key prefix, and comma-separated actions (`read`, `write`, `list`). For example, `UPLOADKEY12345678<TAB>media<TAB>users/42/<TAB>read,write,list`. The file may name a permanent or session identity; the owner key is always unrestricted. Once the scope file is enabled, an additional key with no scope is denied. A list request must include a prefix inside the granted prefix. Copy requires read permission on the source and write permission on the destination. Restricted keys cannot change ACLs or manage buckets. A scope is a ceiling: the bucket ACL, bucket policy, or identity policy must also grant access. Restart the service after editing the files.
|
||||
|
||||
To use identity policies, mount a private directory and set `S3_IDENTITY_POLICIES_DIR` to its container path. Put one `<ACCESSKEY>.json` file per identity. The supported JSON subset uses `Version: "2012-10-17"` and `Statement` entries with `Effect`, `Action`, and `Resource`; it accepts S3 action wildcards and bucket/object ARNs. The bucket-policy form also requires `Principal`, using `*`, an access key, or `{ "AWS": "ACCESSKEY" }`. Policies govern object reads, writes, deletes, copies, ACLs, bucket listing, and multipart writes or aborts. Explicit denies win. `Condition`, `NotAction`, `NotResource`, `NotPrincipal`, and IAM roles are rejected rather than silently ignored. Files load on restart; protect the directory like credentials.
|
||||
|
||||
For a restricted key to upload **and read** files in a new owner-enforced bucket, give it both a `read,write` key scope for its prefix and an identity policy allowing `s3:PutObject` and `s3:GetObject` on that prefix. For example, a scope of `UPLOADKEY12345678<TAB>media<TAB>users/42/<TAB>read,write` pairs with `UPLOADKEY12345678.json` containing `{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["s3:PutObject","s3:GetObject"],"Resource":"arn:aws:s3:::media/users/42/*"}]}`. A scope alone is only a ceiling, and ObjectStore does not infer ownership from the uploader's key. Assign a distinct prefix per key when keys must not read each other's files.
|
||||
|
||||
For externally issued sessions, mount a private file and set `S3_SESSION_CREDENTIALS_FILE` to its container path. Each line is four **tab-separated** fields: session access key, secret, security token, and Unix expiry time in seconds. Session keys use the same 16–128 alphanumeric format as permanent keys; secrets and tokens need at least 32 characters. Signed requests must sign and send `x-amz-security-token`; presigned URLs must include signed `X-Amz-Security-Token`. Expired or mismatched tokens are denied on every request. ObjectStore does not issue or refresh sessions: provision and rotate the file outside the service, then restart. A session has no access until an ACL, bucket policy, or identity policy grants it; a configured key scope can narrow it further.
|
||||
|
||||
The configured owner owns every bucket and object. `BucketOwnerPreferred` and `ObjectWriter` are accepted as ACL-enabled modes, but there is one ObjectStore account, so cross-account object ownership is not modeled. A `WRITE_ACP` grantee can change an ACL only on a retained, non-null version; current unversioned and null versions require the owner key. Version lists, multipart inspection, tags, versioning controls, bucket creation/deletion, and capabilities remain owner-only. These policy features cover common object and bucket access, not full AWS IAM or STS. Public bucket `READ` exposes names; public object `READ` exposes bytes. Review grants before exposing a gateway.
|
||||
|
||||
## CLI and tests
|
||||
|
||||
@@ -53,9 +61,61 @@ 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, and in-flight requests without bucket or user labels. Keep the token private. Metrics are disabled when the variable is empty.
|
||||
Set `METRICS_BEARER_TOKEN` to a random value of at least 32 characters to enable `GET /metrics` in Prometheus text format. Scrape with `Authorization: Bearer <token>` over a private network or HTTPS. The endpoint reports counts by response class, total request time, in-flight requests, and S3 request and body-byte totals without bucket or user labels. Keep the token private. The Prometheus endpoint is disabled when the variable is empty.
|
||||
|
||||
### Local admin console
|
||||
|
||||
The admin console is at `http://127.0.0.1:9001/_objectstore/admin/`. It lists buckets, navigates object prefixes and retained versions, and shows object metadata. An administrator can upload and download files, edit UTF-8 text objects up to 32 KiB in versioned buckets, create and rename buckets, delete empty buckets, edit versioning, Object Ownership, Block Public Access, bucket policies, ACL grants, and object tags, and delete objects or individual versions. Uploads create new objects by default; replacing an object requires bucket versioning so the old version remains available. Public grants and policies require typing the bucket name; version deletion requires the full key and version ID. The object-size chart and counts cover only the current page of a listing. The performance view receives one sample per second while visible and graphs S3 request rate, inbound and outbound body bytes, process CPU, memory, and GC collections. Admin requests and health checks are excluded from S3 rates; chart history lives only in the browser tab. RSS is read from Linux when available; otherwise the memory card shows JVM heap plus non-heap usage. This view does not require the separate Prometheus token. It is disabled by default and uses a separate password, not an S3 access key. Its Biscuit widgets are bundled with the image under the MIT license in `admin-ui/LICENSE.Biscuit`. To enable only the console for an existing local Compose stack:
|
||||
|
||||
The Health & recovery page shows readiness, disk quota use, object count, and available filesystem space in disk mode. It does not infer backup health: backup and restore status remain **Not reported** until a separate verified reporting integration exists. The Diagnostics page keeps five one-minute request windows in memory and shows bounded latency estimates and the most recent 64 errors. Error records contain status, operation, bucket name, and request ID, but no object key or credential. Its 1 MiB connection probe measures only the browser-to-admin-listener path. These in-memory diagnostics reset on restart and are per gateway in cluster mode.
|
||||
|
||||
Audit & access shows the last 100 admin events and S3 request counts by authenticated key. Admin events are appended and synced to `admin-audit.tsv` under `ADMIN_UI_STATE_DIR` (default `DATA_DIR`), with one 4 MiB rotated file. Include both audit files in backups; the event trail is bounded and is not a substitute for a central audit system. Key counters reset on gateway restart and do not retain secrets or object keys. The access checker uses the live key scope, identity policy, bucket policy, and ACL rules for a current object. It does not check a historical version or perform the requested S3 operation.
|
||||
|
||||
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 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.
|
||||
|
||||
```sh
|
||||
mkdir -p secrets
|
||||
chmod 700 secrets
|
||||
umask 077
|
||||
openssl rand -base64 32 > secrets/admin-password
|
||||
chmod 644 secrets/admin-password
|
||||
docker compose -f compose.yaml -f compose.admin.yaml up -d --build
|
||||
```
|
||||
|
||||
Read the generated password from `secrets/admin-password` on the host to sign in. The directory is private to your host account, while the file is readable by the container's unprivileged user through a read-only mount. The file is ignored by Git. The password must be at least 16 bytes. Sessions expire after 30 minutes, and five failed logins from one peer pause further attempts for five minutes. A restart clears all sessions. Do not reuse the S3 secret.
|
||||
|
||||
To manage additional scoped S3 keys in the console, provision a separate 256-bit master key and add the credentials overlay:
|
||||
|
||||
```sh
|
||||
umask 077
|
||||
openssl rand -hex 32 > secrets/managed-master
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
For a private VPN interface, set `ADMIN_UI_BIND_IP` to that interface's private IPv4 address and `ADMIN_UI_PRIVATE_ORIGIN` to `http://<that-address>:9001`. The origin must use an RFC 1918 IPv4 address and an explicit port; the console then accepts only that Host value. The VPN must encrypt traffic and restrict who can reach the port. Do not publish this HTTP port on the public internet. The password is still required, and the admin listener does not accept S3 operations.
|
||||
|
||||
The admin display name, icon, and global default theme are shared across browsers and survive restarts in `/data/admin-branding.txt`; include that file in volume backups. Set `ADMIN_UI_BRANDING_FILE` to a persistent path when the admin process has no `/data` volume. The global default is Deep dark until changed in Settings. A personal Biscuit theme choice is stored in the browser and takes precedence; selecting "Use server default" clears that choice.
|
||||
|
||||
For cluster gateways with an admin console, mount a persistent directory at `ADMIN_UI_STATE_DIR` for branding, activity, and audit files. The local cluster Compose stack provides `/data`; its encrypted overlay maps that directory to the encrypted host volume. Keep this gateway state with the metadata backup.
|
||||
|
||||
Each bucket's Activity tab shows successful S3 reads and writes observed by this gateway over the last 365 UTC days. Counters are held in memory during requests and saved to `bucket-activity.tsv` in `ADMIN_UI_STATE_DIR` (default `DATA_DIR`) once per minute and at clean shutdown. Include that file in backups if you want to keep the chart after a restore. A sudden power loss can lose up to a minute of chart counts; object data is unaffected. Cluster gateways keep separate per-node activity files, so this is not a cluster-wide total.
|
||||
|
||||
For a bounded local write baseline, run `python3 scripts/benchmark-writes.py --requests 100 --concurrency 8 --size 4096` with `S3_ACCESS_KEY` and `S3_SECRET_KEY` in the environment. It writes under a unique `benchmark/` prefix and deletes successful objects afterward. Results depend on CPU, disks, network, connection reuse, and durability settings; a laptop number does not predict another server. Run a mixed upload/download workload before changing concurrency or public limits.
|
||||
|
||||
@@ -106,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
|
||||
|
||||
@@ -118,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:
|
||||
@@ -150,16 +212,18 @@ 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.
|
||||
|
||||
Set `S3_PUBLIC_ENDPOINT` to the external HTTP(S) origin, such as `https://s3.example.com`, when a TLS reverse proxy fronts ObjectStore. Multipart completion uses it to return a path-style `Location` URL. Without it, the response uses the request's signed `Host` and direct connection scheme, which may be `http` behind a TLS proxy. The value must be an origin without a path, query, user info, or fragment.
|
||||
|
||||
For example, to start with 100 requests per second and 16 MiB/s combined upload and download per IP, set `PUBLIC_REQUESTS_PER_SECOND=100` and `PUBLIC_BYTES_PER_SECOND=16777216`. Both start with a one-second burst. Adjust these numbers after measuring the actual workload; do not copy them as a universal production policy.
|
||||
|
||||
ObjectStore uses the socket peer as the client IP and ignores forwarded-IP headers by default. If a reverse proxy sits between external clients and ObjectStore, set `PUBLIC_TRUSTED_PROXY_IPS` to the exact IP address that ObjectStore sees for that proxy and configure the proxy to **replace** `X-Real-IP` with its actual client IP. A request from that trusted peer without exactly one valid numeric `X-Real-IP` is rejected. Do not trust an address reachable by arbitrary clients, and preserve the original `Host` header for Signature V4. In Docker, the proxy's address as seen by the container may be a bridge address rather than `127.0.0.1`. If proxy trust is not configured, all clients behind that proxy share its budget; this is safe from header spoofing but may throttle them together.
|
||||
|
||||
Enable these limits only on a deliberately public endpoint. They also apply to direct localhost storage calls to that same endpoint; leave them disabled for the local-only setup or run a separate local-only instance if local storage calls must be exempt. A direct loopback `/health` probe without a forwarded-IP header remains exempt. The byte limit is aggregate ingress plus egress for each IP, and several users behind one NAT share it. If a proxy buffers complete uploads before forwarding them, the upload byte limit controls proxy-to-ObjectStore traffic, not the client's initial upload speed; disable request buffering when end-to-end upload pacing is required. It is a fairness control, not a defense against connection floods before the Java handler runs. Put an internet-facing proxy or firewall in front of the gateway for TLS, connection limits, request timeouts, and buffering controls. Do not expose storage nodes or PostgreSQL publicly.
|
||||
|
||||
The default local cluster still uses plaintext node and PostgreSQL connections. The optional TLS overlay secures node traffic, but PostgreSQL TLS, automatic metadata failover, IAM policies, and physical host verification remain absent. The key-scope file limits additional signed identities; it is not an IAM replacement. Garbage collection can remove data required by an older metadata backup, so its retention guard is essential. Host UUIDs are operator labels, not proof that machines have separate power, disks, or network paths. Keep `CLUSTER_LOCAL_DEV=true` limited to local tests.
|
||||
The default local cluster still uses plaintext node and PostgreSQL connections. The optional TLS overlay secures node traffic; 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.
|
||||
@@ -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).
|
||||
|
||||
[](OPERATIONS.md#limits-and-safety) [](LICENSE) [](Dockerfile) [](#s3-api-support-checklist) [](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.
|
||||
|
||||
@@ -42,18 +46,33 @@ Legacy single-node objects remain readable but stay out of listings until overwr
|
||||
- ✅ User metadata on object and multipart uploads; object tags on upload, copy, and the tagging subresource
|
||||
- ✅ CRC64NVME and XXHash checksums, checksum trailers, and persisted object checksum metadata
|
||||
- ✅ Bucket versioning with retained versions, delete markers, and version-specific reads, copies, deletes, and tags in both modes
|
||||
- ✅ Basic bucket and object ACL grants, public reads, and multiple access-key identities
|
||||
- ⬜ Full AWS ACL ownership controls, email grantees, and bucket policies
|
||||
- ✅ Bucket and object ACL grants, bucket policies, Object Ownership controls, and Block Public Access
|
||||
- ✅ Scoped identity policies and externally provisioned, expiring session credentials
|
||||
- ⬜ Full IAM, STS issuance, cross-account ACL ownership, and conditional policies
|
||||
|
||||
This is an S3 subset. Unsupported operations and Amazon-specific headers are rejected. Bucket names use three to 63 lowercase letters, digits, or hyphens; the default bucket cannot be deleted. Bucket creation accepts an empty body for the configured region. Tags do not control access.
|
||||
|
||||
Versioning supports enabled and suspended states. Old versions and delete markers count toward capacity; deleting a specific version is permanent. Lifecycle expiration, MFA Delete, and `ListObjectVersions` delimiter grouping are unsupported. User metadata accepts printable ASCII only.
|
||||
|
||||
`PutObject` checksums are validated and retained; without one, ObjectStore stores CRC64NVME, including for completed multipart uploads. Request `x-amz-checksum-mode: ENABLED` on GET or HEAD to receive it. `UploadPart` checksums are validated but are not returned by `ListParts` or combined into a multipart checksum. Presigned URLs expire within seven days. Signed `aws-chunked` uploads support one checksum trailer; temporary credentials and other streaming modes are unsupported. Copies obey the object size limit.
|
||||
`PutObject` checksums are validated and retained; without one, ObjectStore stores CRC64NVME, including for completed multipart uploads. Request `x-amz-checksum-mode: ENABLED` on GET or HEAD to receive it. `UploadPart` checksums are validated but are not returned by `ListParts` or combined into a multipart checksum. Presigned URLs expire within seven days. Signed `aws-chunked` uploads support one checksum trailer; other streaming modes are unsupported. Copies obey the object size limit.
|
||||
|
||||
## Single-node setup
|
||||
|
||||
Requires Docker Compose. Copy `.env.example` to `.env`, then set `S3_ACCESS_KEY` and `S3_SECRET_KEY` to unique values. The access key must be at least 16 alphanumeric characters; the secret must be at least 32 characters.
|
||||
Requires Docker Compose and OpenSSL. From a fresh checkout, one command creates local credentials, enables the loopback-only admin console, and starts the service:
|
||||
|
||||
```sh
|
||||
bash scripts/install.sh
|
||||
```
|
||||
|
||||
For a new machine, clone and install in one shell line:
|
||||
|
||||
```sh
|
||||
git clone https://github.com/LunarSkyOSS/ObjectStore.git objectstore && cd objectstore && bash scripts/install.sh
|
||||
```
|
||||
|
||||
The installer supports the stock single-node Compose stack and keeps existing `.env`, secrets, and Docker data volumes on reruns. It refuses encrypted storage, existing data bind mounts, and extra Compose overlays; update those deployments using their original Compose command. Credentials are in `.env` and `secrets/admin-password`; keep `secrets/managed-master` for recovery. Review [admin access and key management](OPERATIONS.md#local-admin-console) before binding the console to a VPN interface.
|
||||
|
||||
For manual setup, copy `.env.example` to `.env`, then set `S3_ACCESS_KEY` and `S3_SECRET_KEY` to unique values. The access key must be at least 16 alphanumeric characters; the secret must be at least 32 characters.
|
||||
|
||||
```sh
|
||||
cp .env.example .env
|
||||
@@ -63,7 +82,9 @@ curl http://127.0.0.1:9000/health
|
||||
|
||||
Port 9000 binds to localhost. Data stays in the `object-data` Docker volume. `docker compose down -v` deletes that volume.
|
||||
|
||||
The 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 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` (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
|
||||
|
||||
@@ -71,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):
|
||||
|
||||
@@ -102,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
|
||||
|
||||
|
||||
@@ -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,22 +25,91 @@ 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. |
|
||||
| `RequestCoordinationTest` | Authentication before rename locking, bounded rename waits, isolated request diagnostics, and key revocation during a request. |
|
||||
| `ConcurrencyTest` | Atomic local overwrites, consistent reads, listings and deletes, plus concurrent quota enforcement and restart recovery. |
|
||||
| `HttpTest` | Signed capability discovery, presigned URLs, streaming uploads and trailers, object and bucket operations, ACL grants with a second access key and public reads, copies, checksum persistence and rejection, ranges, listing, metadata, tags, multipart uploads, versioning, and signed virtual-hosted requests in single-node mode. |
|
||||
| `ClientLimitsTest` | Disabled defaults, trusted-proxy address validation, ignored untrusted headers, per-IP request refusal, and paced response bytes. |
|
||||
| `AdminConsoleTest` | Admin sign-in, CSRF and origin checks, bucket and object changes, public-access confirmations, live metrics, encrypted managed-key persistence, scoped reads and listings, and key revocation. |
|
||||
| `AdminOperationsTest` | Persisted admin events, effective access checks, stale editor conflicts, and paged copy, tag, inventory, and delete jobs; private copy ACLs, checksum verification, and tag validation. |
|
||||
| `AdminBulkJobsTest` | Exact job limits, truncated and stalled pagination, cancellation, and bounded per-object error reports. |
|
||||
| `EncryptedVolumeTest` | Marker acceptance and refusal when the configured encrypted directory is missing, mismatched, or a symlink. |
|
||||
| `NodeHttpTest` | Total node response deadlines, stalled-body cancellation, response-size limits, and interruption. |
|
||||
| `ClusterNodeTest` | Node identity and locking, authenticated segment transfers, checksum rejection, repair authorization, inventory and guarded deletion, and restart cleanup. |
|
||||
| `ClusterTlsTest` | HTTPS node identity and segment roundtrip with a trusted certificate, plus rejection of untrusted and wrong-host certificates. |
|
||||
| `CliTest` | Version, status, verification, and a nonzero result for corrupt data. |
|
||||
| `ClientTest` and `MultipartClientTest` | Java client request signing, capability discovery, error handling, and multipart operations. |
|
||||
|
||||
The script also checks installer safety with a fake Docker command: unsupported storage setups must be refused before changing credentials or containers.
|
||||
|
||||
The script exits nonzero on failure. The test programs use temporary local directories and loopback HTTP or HTTPS ports; they do not use an existing ObjectStore volume. `ClusterTlsTest` uses the JDK's `keytool` to create disposable test certificates.
|
||||
|
||||
The local installer was also checked with a disposable Compose project and separate ports: it generated credentials, started a healthy container, served the S3 health and admin login endpoints, and reran without replacing the data volume. That smoke test does not exercise a remote VPN or production reverse proxy.
|
||||
|
||||
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
|
||||
|
||||
@@ -59,7 +136,11 @@ 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.
|
||||
|
||||
`ClusterMaintenanceTest` also requires a fresh, disposable PostgreSQL database and the PostgreSQL JDBC driver. It creates three temporary local storage nodes and checks rename contention, multipart totals across buckets, replica repair and reporting, and conflicting edits through two independent gateways.
|
||||
|
||||
## Two-machine durability drill
|
||||
|
||||
@@ -69,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.
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 Biscuit contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,373 @@
|
||||
:root { color-scheme: dark; }
|
||||
body { background: #14121d; color: #f4f0fa; font: 16px system-ui; margin: 0;
|
||||
padding: clamp(20px, 4vw, 48px); }
|
||||
main { max-width: 1080px; margin: 0 auto; }
|
||||
.login { min-height: calc(100dvh - 2 * clamp(20px, 4vw, 48px));
|
||||
display: grid; place-items: center; }
|
||||
.login-card { width: min(100%, 400px); box-sizing: border-box; padding: 34px;
|
||||
border: 1px solid #514663; border-radius: 18px; background: #211c2b;
|
||||
box-shadow: 0 24px 80px #08060d88; }
|
||||
.mark { display: grid; place-items: center; width: 48px; height: 48px; flex: none; }
|
||||
.mark img { width: 56px; height: 56px; max-width: none; }
|
||||
.login-brand { display: flex; align-items: center; gap: 12px; margin-bottom: 20px; }
|
||||
.login-brand strong { font-size: 1.1rem; }
|
||||
.login-card h1 { font-size: 1.75rem; }
|
||||
.login-card .muted { margin-bottom: 28px; line-height: 1.5; }
|
||||
h1 { margin: 0; font-size: 2rem; }
|
||||
header { display: flex; justify-content: space-between; align-items: center; gap: 16px;
|
||||
border-bottom: 1px solid #3e344e; padding-bottom: 22px; }
|
||||
.header-title { display: flex; align-items: center; gap: 14px; }
|
||||
.header-title h1 { font-size: 1.35rem; }
|
||||
.header-title small { margin-top: 3px; }
|
||||
.intro { display: flex; align-items: center; justify-content: space-between;
|
||||
gap: 16px; margin: 34px 0 18px; }
|
||||
.intro h2, .buckets h2 { margin: 0 0 6px; font-size: 1.3rem; }
|
||||
.intro p, .buckets p { margin: 0; color: #aaa2bb; }
|
||||
.muted, small { color: #aaa2bb; }
|
||||
.error { color: #ffafa9; }
|
||||
form { margin-top: 24px; }
|
||||
label { display: block; margin-bottom: 8px; }
|
||||
[hidden] { display: none !important; }
|
||||
input, select, textarea, button { font: inherit; border: 1px solid #514663; border-radius: 8px;
|
||||
padding: 12px 14px; }
|
||||
input, select, textarea { display: block; box-sizing: border-box;
|
||||
background: #211c2b; color: #fff; }
|
||||
input { width: min(100%, 360px); }
|
||||
textarea { width: 100%; resize: vertical; font: .9rem ui-monospace, monospace; }
|
||||
input[type=hidden] { display: none; }
|
||||
.login input[type=password], .login button { width: 100%; }
|
||||
button { background: #b39add; color: #20172c; cursor: pointer; }
|
||||
form button { margin-top: 12px; }
|
||||
header form { margin: 0; }
|
||||
header button { background: #282232; color: #eee; }
|
||||
.grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
|
||||
gap: 14px; }
|
||||
biscuit-cardview { display: block; --biscuit-cardview-background: #211c2b;
|
||||
--biscuit-cardview-border: 1px solid #463a58;
|
||||
--biscuit-cardview-radius: 14px;
|
||||
--biscuit-cardview-padding: 22px;
|
||||
--biscuit-cardview-color: #f4f0fa; }
|
||||
biscuit-cardview:not(:defined) { background: #211c2b; border: 1px solid #463a58;
|
||||
border-radius: 14px; padding: 22px; }
|
||||
biscuit-cardview small { display: block; margin-bottom: 12px; }
|
||||
biscuit-cardview strong { display: block; font-size: 1.2rem; overflow-wrap: anywhere; }
|
||||
biscuit-badgeview:not(:defined) { display: inline-block; padding: 6px 10px;
|
||||
border-radius: 999px; background: #342844; color: #d9c6f5; font-size: .8rem; }
|
||||
.bucket-badges { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }
|
||||
.buckets { margin-top: 34px; }
|
||||
.table-wrap { overflow: auto; margin-top: 18px; border: 1px solid #463a58;
|
||||
border-radius: 14px; background: #211c2b; }
|
||||
table { width: 100%; border-collapse: collapse; text-align: left; }
|
||||
th, td { padding: 15px 18px; border-bottom: 1px solid #3b314b; white-space: nowrap; }
|
||||
tr:last-child td { border-bottom: 0; }
|
||||
th { color: #aaa2bb; font-size: .75rem; text-transform: uppercase; letter-spacing: .1em; }
|
||||
td { font-size: .93rem; }
|
||||
.empty { padding: 28px; color: #aaa2bb; }
|
||||
a { color: #c6a8f3; text-decoration: none; }
|
||||
a:hover { text-decoration: underline; }
|
||||
.crumbs { display: flex; flex-wrap: wrap; align-items: center; gap: 8px;
|
||||
color: #aaa2bb; font-size: .9rem; margin: 30px 0 12px; }
|
||||
.crumbs span { overflow-wrap: anywhere; }
|
||||
.toolbar { display: flex; flex-wrap: wrap; align-items: end; justify-content: space-between;
|
||||
gap: 16px; margin: 22px 0; }
|
||||
.toolbar form { display: flex; flex-wrap: wrap; align-items: end; gap: 8px; margin: 0; }
|
||||
.toolbar label { margin: 0; color: #aaa2bb; font-size: .85rem; }
|
||||
.toolbar input { min-width: min(280px, 100%); }
|
||||
.toolbar button { margin: 0; }
|
||||
.toolbar .field { display: grid; gap: 6px; }
|
||||
.button-link { display: inline-flex; align-items: center; justify-content: center;
|
||||
border: 1px solid #514663; border-radius: 8px; padding: 12px 14px;
|
||||
color: #f4f0fa; background: #282232; }
|
||||
.button-link:hover { background: #342a42; text-decoration: none; }
|
||||
.action-icon { width: 16px; height: 16px; margin-right: 7px; vertical-align: -3px;
|
||||
filter: brightness(0) invert(.86); }
|
||||
button .action-icon { filter: brightness(0); }
|
||||
.danger-zone button .action-icon { filter: brightness(0) invert(1); }
|
||||
.name-cell { max-width: 420px; white-space: normal; overflow-wrap: anywhere; }
|
||||
.kind { color: #aaa2bb; font-size: .8rem; }
|
||||
.pagination { display: flex; gap: 12px; align-items: center; margin-top: 18px; }
|
||||
.detail-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
|
||||
gap: 14px; margin-top: 22px; }
|
||||
.detail-card { border: 1px solid #463a58; border-radius: 14px; background: #211c2b;
|
||||
padding: 22px; min-width: 0; }
|
||||
.detail-card h3 { margin: 0 0 16px; font-size: 1rem; }
|
||||
.settings-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(270px, 1fr)); gap: 14px; }
|
||||
.settings-form { border: 1px solid #463a58; border-radius: 14px; background: #211c2b;
|
||||
padding: 20px; margin-top: 16px; min-width: 0; }
|
||||
.settings-form h3 { margin: 0 0 12px; }
|
||||
.settings-form p { margin: 0 0 12px; }
|
||||
.settings-form select { max-width: 100%; }
|
||||
.settings-form input:not([type=hidden]), .settings-form select { margin: 8px 0; }
|
||||
.primary-action { font-weight: 700; white-space: nowrap; }
|
||||
.intro:has(.primary-action) { flex-wrap: wrap; }
|
||||
.dialog-form { border: 0; background: transparent; padding: 0; margin: 0; }
|
||||
.dialog-form input { width: 100%; }
|
||||
.dialog-form small { display: block; line-height: 1.4; }
|
||||
.bucket-wizard-form { width: min(580px, calc(100vw - 64px)); max-height: min(72vh, 650px);
|
||||
overflow-y: auto; }
|
||||
.bucket-wizard-form biscuit-formstep:not([hidden]) { display: grid; gap: 10px;
|
||||
padding: 12px 0; }
|
||||
.bucket-wizard-form .check input { width: auto; }
|
||||
.bucket-wizard-form .check[hidden] { display: none; }
|
||||
.dialog-actions { display: flex; justify-content: flex-end; gap: 8px; margin-top: 20px; }
|
||||
.dialog-actions button { margin: 0; }
|
||||
.dialog-actions button:first-child { background: #342b42; color: #f4f0fa; }
|
||||
.bucket-renamer { display: block; margin-top: 20px; }
|
||||
.bucket-renamer:not(:defined) { border: 1px solid #514663; border-radius: 10px; }
|
||||
.bucket-renamer .rename-form { margin: 0; border: 0; background: transparent; padding: 0; }
|
||||
.rename-warning { border-left: 3px solid #b39add; padding: 10px 14px;
|
||||
background: #2a2338; line-height: 1.5; }
|
||||
.rename-form input { width: min(100%, 380px); }
|
||||
.form-row { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }
|
||||
.form-row button { margin: 0; }
|
||||
.check-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 10px; }
|
||||
.check { display: flex; align-items: center; gap: 8px; margin: 0; }
|
||||
.check input { width: auto; margin: 0; }
|
||||
.danger-zone { border-color: #8b4756; }
|
||||
.danger-zone button { background: #aa6070; color: #fff; }
|
||||
.fact { display: flex; align-items: baseline; justify-content: space-between;
|
||||
gap: 16px; padding: 9px 0; border-top: 1px solid #3b314b; }
|
||||
.fact span { color: #aaa2bb; }
|
||||
.fact strong { text-align: right; overflow-wrap: anywhere; }
|
||||
.insight { margin-top: 26px; }
|
||||
biscuit-tablayout { display: block; margin-top: 22px;
|
||||
--biscuit-tablayout-panel-padding: 20px 22px 24px; }
|
||||
biscuit-tablayout biscuit-tab > :first-child { margin-top: 0; }
|
||||
biscuit-tablayout .activity-panel { border: 0; background: transparent; padding: 0; }
|
||||
.activity-panel { border: 1px solid #463a58; border-radius: 14px;
|
||||
background: #211c2b; padding: 20px; overflow-x: auto; }
|
||||
.activity-panel h2 { margin-top: 0; }
|
||||
.activity-summary { display: flex; align-items: baseline; flex-wrap: wrap;
|
||||
gap: 8px 16px; margin: 16px 0; }
|
||||
.activity-summary strong { font-size: 1.4rem; }
|
||||
.activity-panel biscuit-activity-chart { display: block; max-width: 100%; }
|
||||
.activity-panel > .muted { margin-bottom: 0; }
|
||||
.cluster-topology { display: grid; gap: 18px; margin: 24px 0; }
|
||||
.cluster-core { justify-self: center; min-width: min(100%, 280px); text-align: center;
|
||||
border: 1px solid #79659b; border-radius: 14px; background: #2a2338; padding: 18px; }
|
||||
.cluster-connect { width: 1px; height: 26px; background: #79659b; justify-self: center; }
|
||||
.cluster-nodes { display: grid; grid-template-columns: repeat(auto-fit, minmax(210px, 1fr)); gap: 12px; }
|
||||
.cluster-node { border: 1px solid #50445e; border-radius: 12px; padding: 16px; background: #211c2b; }
|
||||
.cluster-node[data-state=offline] { border-color: #a45c6a; }
|
||||
.cluster-node strong { display: block; margin-bottom: 6px; }
|
||||
.cluster-node code { display: block; overflow-wrap: anywhere; font-size: .8rem; }
|
||||
.console-nav { display: flex; flex-wrap: wrap; gap: 8px; padding: 12px 0;
|
||||
border-bottom: 1px solid #3e344e; }
|
||||
.console-nav a { padding: 8px 12px; border-radius: 8px; color: #cfc5df; }
|
||||
.console-nav a:hover { background: #282232; text-decoration: none; }
|
||||
.perf-grid { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr));
|
||||
gap: 14px; margin-top: 24px; }
|
||||
.perf-grid biscuit-cardview strong { font-variant-numeric: tabular-nums; }
|
||||
.perf-charts { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 16px; margin-top: 24px; }
|
||||
.perf-charts[hidden] { display: none; }
|
||||
.perf-status-row { display: flex; align-items: center; gap: 8px;
|
||||
min-height: 24px; margin-top: 12px; }
|
||||
.perf-status { color: #aaa2bb; margin: 0; }
|
||||
#perf-loader[hidden], #perf-loader::part(label) { display: none; }
|
||||
.perf-note { color: #aaa2bb; font-size: .9rem; line-height: 1.5; }
|
||||
biscuit-chartview { --biscuit-chart-surface: #211c2b;
|
||||
--biscuit-chart-color: #f4f0fa;
|
||||
--biscuit-chart-muted: #aaa2bb;
|
||||
--biscuit-chart-border: #463a58;
|
||||
--biscuit-chart-accent: #b39add; }
|
||||
details { margin-top: 22px; padding: 18px 22px; border: 1px solid #463a58;
|
||||
border-radius: 14px; background: #211c2b; }
|
||||
summary { cursor: pointer; font-weight: 600; }
|
||||
pre { overflow-wrap: anywhere; white-space: pre-wrap; }
|
||||
@media (max-width: 820px) { .perf-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
|
||||
@media (max-width: 520px) {
|
||||
.login-card { padding: 26px; }
|
||||
.intro { align-items: start; }
|
||||
.grid > :last-child:nth-child(odd) { grid-column: 1 / -1; }
|
||||
.grid biscuit-cardview { --biscuit-cardview-padding: 16px; }
|
||||
.perf-grid biscuit-cardview { --biscuit-cardview-padding: 16px; }
|
||||
.perf-grid biscuit-cardview small { margin-bottom: 8px; }
|
||||
.perf-charts { grid-template-columns: minmax(0, 1fr); }
|
||||
}
|
||||
.workspace-body { padding: 0; background: #14121d; }
|
||||
.workspace-body > main { max-width: none; margin: 0; }
|
||||
.app-shell { display: grid; grid-template-columns: 248px minmax(0, 1fr);
|
||||
min-height: 100dvh; }
|
||||
biscuit-sidebarview { --biscuit-sidebarview-width: 248px;
|
||||
--biscuit-sidebarview-background: #191623;
|
||||
--biscuit-sidebarview-color: #e6deef;
|
||||
--biscuit-sidebarview-divider: 1px solid #393044;
|
||||
--biscuit-sidebarview-hover-background: #292332;
|
||||
--biscuit-sidebarview-active-background: #372947;
|
||||
--biscuit-sidebarview-active-color: #e3caff;
|
||||
--biscuit-sidebarview-padding: 16px 12px; }
|
||||
biscuit-sidebarview:not(:defined) { display: flex; flex-direction: column;
|
||||
box-sizing: border-box; padding: 16px 12px; background: #191623;
|
||||
border-right: 1px solid #393044; }
|
||||
@media (min-width: 721px) { biscuit-sidebarview::part(header) { display: none; } }
|
||||
.sidebar-brand { display: flex; align-items: center; gap: 11px;
|
||||
padding: 4px 8px 18px; border-bottom: 1px solid #393044; margin-bottom: 16px; }
|
||||
.sidebar-brand .mark { width: 40px; height: 40px; }
|
||||
.sidebar-brand .mark img { width: 42px; height: 42px; }
|
||||
.sidebar-brand strong { display: block; font-size: 1.02rem; }
|
||||
.sidebar-brand small { display: block; margin-top: 2px; font-size: .68rem;
|
||||
letter-spacing: .12em; }
|
||||
.sidebar-group { margin: 14px 12px 5px; color: #8e829c;
|
||||
font-size: .69rem; font-weight: 700; letter-spacing: .12em; }
|
||||
.sidebar-link { display: flex; align-items: center; gap: 12px; min-height: 41px;
|
||||
padding: 8px 12px; border-radius: 8px; color: #d3cbdc; }
|
||||
.sidebar-link img { opacity: .82; flex: none; filter: brightness(0) invert(.86); }
|
||||
.sidebar-link[aria-current=page] { background: #372947; color: #eedaff; }
|
||||
biscuit-sidebarview:not(:defined) .sidebar-link:hover { background: #292332;
|
||||
text-decoration: none; }
|
||||
.workspace { min-width: 0; display: flex; flex-direction: column; }
|
||||
.loader-skeletons { display: grid; gap: 8px; margin-top: 12px; }
|
||||
@keyframes admin-spin { to { transform: rotate(360deg); } }
|
||||
.navigation-error { padding: 12px 16px; margin: 0 0 18px;
|
||||
border: 1px solid #b65b61; border-radius: 9px; color: #ffd3d0;
|
||||
background: #3a252f; }
|
||||
.settings-form[data-busy] button, .upload-form[data-busy] button { opacity: .7; }
|
||||
.settings-form[data-busy] button::before, .upload-form[data-busy] button::before {
|
||||
content: ''; display: inline-block; width: 12px; height: 12px;
|
||||
margin-right: 9px; vertical-align: -1px; border: 2px solid #6c538b;
|
||||
border-top-color: #20172c; border-radius: 50%;
|
||||
animation: admin-spin .85s linear infinite; }
|
||||
.upload-progress { display: block; width: 100%; height: 8px; margin-top: 10px;
|
||||
accent-color: #b39add; }
|
||||
.upload-progress[hidden] { display: none; }
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.settings-form[data-busy] button::before,
|
||||
.upload-form[data-busy] button::before { animation-duration: 2.5s; }
|
||||
}
|
||||
biscuit-navbarview { --biscuit-navbarview-background: #1b1823;
|
||||
--biscuit-navbarview-color: #f4f0fa;
|
||||
--biscuit-navbarview-bottom-border: 1px solid #393044;
|
||||
--biscuit-navbarview-padding: 9px 22px; }
|
||||
biscuit-navbarview:not(:defined) { display: flex; align-items: center;
|
||||
justify-content: space-between; min-height: 60px; padding: 0 22px;
|
||||
background: #1b1823; border-bottom: 1px solid #393044; }
|
||||
biscuit-navbarview:not(:defined)::before { content: 'ObjectStore admin'; font-weight: 700; }
|
||||
biscuit-navbarview form { margin: 0; }
|
||||
biscuit-navbarview button { padding: 8px 13px; background: #292332; color: #e6deef; }
|
||||
.mobile-nav-link { display: none; }
|
||||
.workspace-content { box-sizing: border-box; width: 100%; max-width: 1680px;
|
||||
margin: 0 auto; padding: 22px clamp(20px, 2.6vw, 46px) 56px; flex: 1; min-width: 0; }
|
||||
.workspace-content .crumbs { margin-top: 2px; }
|
||||
.workspace-content .intro { margin-top: 10px; }
|
||||
.workspace-content .grid { grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); }
|
||||
.workspace-content .settings-grid { grid-template-columns: repeat(auto-fit, minmax(330px, 1fr)); }
|
||||
.upload-form { margin: 18px 0; }
|
||||
.upload-fields { display: grid; grid-template-columns: minmax(230px, 1fr) minmax(230px, 2fr);
|
||||
gap: 16px; align-items: end; }
|
||||
.upload-fields input { width: 100%; min-width: 0; }
|
||||
.upload-fields input[type=file] { padding: 10px; }
|
||||
.upload-form .check { margin-top: 12px; }
|
||||
.upload-status { margin: 10px 0 0; color: #aaa2bb; font-size: .88rem; }
|
||||
.object-actions { margin: 18px 0 0; }
|
||||
biscuit-footerview { --biscuit-footerview-background: #191623;
|
||||
--biscuit-footerview-color: #d3cbdc;
|
||||
--biscuit-footerview-muted-color: #aaa2bb;
|
||||
--biscuit-footerview-top-border: 1px solid #393044;
|
||||
--biscuit-footerview-padding: 18px clamp(20px, 2.6vw, 46px); }
|
||||
biscuit-footerview:not(:defined) { display: block; padding: 18px 24px;
|
||||
background: #191623; border-top: 1px solid #393044; color: #aaa2bb; }
|
||||
.policy-editor, .text-editor { display: block; min-width: 0; margin-top: 12px;
|
||||
--biscuit-codeview-height: 300px;
|
||||
--biscuit-codeview-background: #17141f;
|
||||
--biscuit-codeview-color: #f4f0fa;
|
||||
--biscuit-codeview-border: 1px solid #514663;
|
||||
--biscuit-codeview-gutter-background: #211c2b;
|
||||
--biscuit-codeview-gutter-color: #9e92ae;
|
||||
--biscuit-codeview-focus-color: #b39add; }
|
||||
.text-editor { --biscuit-codeview-height: min(58vh, 600px); }
|
||||
.policy-editor:not(:defined), .text-editor:not(:defined) { display: none; }
|
||||
.code-fallback { display: block; }
|
||||
.code-form:not([data-enhanced]) biscuit-codeview { display: none; }
|
||||
.code-form[data-enhanced] .code-fallback { display: none; }
|
||||
.editor-section > .settings-form:not(.code-form) .text-fallback { display: none; }
|
||||
.editor-section > .settings-form:not(.code-form) biscuit-codeview:not(:defined) +
|
||||
.text-fallback { display: block; }
|
||||
.editor-diagnostics { margin: 10px 0; min-height: 22px; font-size: .88rem; }
|
||||
.editor-diagnostics[data-state=error] { color: #ffafa9; }
|
||||
.editor-diagnostics[data-state=ok] { color: #9cd8b2; }
|
||||
.editor-diagnostics[data-state=hint] { color: #aaa2bb; }
|
||||
.brand-preview { display: flex; align-items: center; gap: 12px;
|
||||
min-height: 68px; margin: 16px 0; padding: 12px; border: 1px solid #514663;
|
||||
border-radius: 10px; overflow-wrap: anywhere; }
|
||||
.brand-preview img { width: 52px; height: 52px; object-fit: contain; border-radius: 8px; }
|
||||
body[data-admin-theme=light] { background: #f5f2f9; color: #211a2b; }
|
||||
body[data-admin-theme=light] .workspace-body { background: #f5f2f9; }
|
||||
body[data-admin-theme=light] biscuit-sidebarview {
|
||||
--biscuit-sidebarview-background: #eae5f2;
|
||||
--biscuit-sidebarview-color: #241c30;
|
||||
--biscuit-sidebarview-divider: 1px solid #cabed9;
|
||||
--biscuit-sidebarview-hover-background: #ddd3e9;
|
||||
--biscuit-sidebarview-active-background: #d8c2f0;
|
||||
--biscuit-sidebarview-active-color: #341756; }
|
||||
body[data-admin-theme=light] biscuit-navbarview {
|
||||
--biscuit-navbarview-background: #eee9f5;
|
||||
--biscuit-navbarview-color: #211a2b;
|
||||
--biscuit-navbarview-bottom-border: 1px solid #cabed9; }
|
||||
body[data-admin-theme=light] biscuit-footerview {
|
||||
--biscuit-footerview-background: #eae5f2;
|
||||
--biscuit-footerview-color: #241c30;
|
||||
--biscuit-footerview-muted-color: #655871;
|
||||
--biscuit-footerview-top-border: 1px solid #cabed9; }
|
||||
body[data-admin-theme=light] biscuit-cardview {
|
||||
--biscuit-cardview-background: #fff;
|
||||
--biscuit-cardview-border: 1px solid #cabed9;
|
||||
--biscuit-cardview-color: #211a2b; }
|
||||
body[data-admin-theme=light] biscuit-chartview {
|
||||
--biscuit-chart-surface: #fff;
|
||||
--biscuit-chart-color: #211a2b;
|
||||
--biscuit-chart-muted: #655871;
|
||||
--biscuit-chart-border: #cabed9; }
|
||||
body[data-admin-theme=light] .settings-form,
|
||||
body[data-admin-theme=light] .detail-card,
|
||||
body[data-admin-theme=light] .table-wrap,
|
||||
body[data-admin-theme=light] details,
|
||||
body[data-admin-theme=light] .login-card { background: #fff; border-color: #cabed9; }
|
||||
body[data-admin-theme=light] input,
|
||||
body[data-admin-theme=light] select,
|
||||
body[data-admin-theme=light] textarea { background: #fff; color: #211a2b; border-color: #a798b8; }
|
||||
body[data-admin-theme=light] .muted,
|
||||
body[data-admin-theme=light] small,
|
||||
body[data-admin-theme=light] .intro p,
|
||||
body[data-admin-theme=light] .buckets p { color: #655871; }
|
||||
body[data-admin-theme=light] a { color: #653ca1; }
|
||||
body[data-admin-theme=light] .sidebar-link { color: #2b2238; }
|
||||
body[data-admin-theme=light] .rename-warning { background: #f0e9f7; }
|
||||
body[data-admin-theme=light] .activity-panel { background: #fff; border-color: #cabed9; }
|
||||
body[data-admin-theme=light] .button-link { background: #fff; color: #211a2b; }
|
||||
body[data-admin-theme=light] .policy-editor,
|
||||
body[data-admin-theme=light] .text-editor {
|
||||
--biscuit-codeview-background: #fff;
|
||||
--biscuit-codeview-color: #211a2b;
|
||||
--biscuit-codeview-gutter-background: #f0ebf5; }
|
||||
body[data-admin-theme=deep-dark] { background: #08080a; }
|
||||
body[data-admin-theme=deep-dark] .settings-form,
|
||||
body[data-admin-theme=deep-dark] .detail-card,
|
||||
body[data-admin-theme=deep-dark] .table-wrap,
|
||||
body[data-admin-theme=deep-dark] details { background: #101014; border-color: #4c4c55; }
|
||||
body[data-admin-theme=deep-dark] biscuit-cardview {
|
||||
--biscuit-cardview-background: #101014;
|
||||
--biscuit-cardview-border: 1px solid #4c4c55; }
|
||||
body[data-admin-theme=deep-dark] biscuit-chartview {
|
||||
--biscuit-chart-surface: #101014;
|
||||
--biscuit-chart-border: #4c4c55; }
|
||||
body[data-admin-theme=deep-dark] biscuit-sidebarview {
|
||||
--biscuit-sidebarview-background: #0d0d10;
|
||||
--biscuit-sidebarview-divider: 1px solid #4c4c55; }
|
||||
body[data-admin-theme=deep-dark] biscuit-navbarview {
|
||||
--biscuit-navbarview-background: #101014;
|
||||
--biscuit-navbarview-bottom-border: 1px solid #4c4c55; }
|
||||
body[data-admin-theme=deep-dark] biscuit-footerview {
|
||||
--biscuit-footerview-background: #0d0d10;
|
||||
--biscuit-footerview-top-border: 1px solid #4c4c55; }
|
||||
@media (max-width: 720px) {
|
||||
.app-shell { grid-template-columns: minmax(0, 1fr); }
|
||||
biscuit-sidebarview { display: none; }
|
||||
biscuit-navbarview { --biscuit-navbarview-padding: 9px 16px; }
|
||||
biscuit-navbarview::part(toggle) { order: -1; }
|
||||
.mobile-nav-link { display: inline-flex; align-items: center; gap: 8px; }
|
||||
.mobile-nav-link img { filter: brightness(0) invert(.86); }
|
||||
.workspace-content { padding: 18px 16px 40px; }
|
||||
biscuit-tablayout { --biscuit-tablayout-panel-padding: 16px; }
|
||||
.upload-fields { grid-template-columns: minmax(0, 1fr); }
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="1em" height="1em" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="8" cy="9" r="4.25"/><path d="m11.1 12.1 8.15 8.15M16.1 17.1l2-2m.6 4.6 2-2"/><circle cx="7.75" cy="8.75" r=".85" fill="currentColor" stroke="none"/></svg>
|
||||
|
After Width: | Height: | Size: 372 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="1em" height="1em" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3.5 19.5h17"/><path d="M5.5 16V11m4 5V6m4 10v-3m4 3V4"/><circle cx="5.5" cy="9" r="1" fill="currentColor" stroke="none"/><circle cx="9.5" cy="4" r="1" fill="currentColor" stroke="none"/><circle cx="13.5" cy="11" r="1" fill="currentColor" stroke="none"/><circle cx="17.5" cy="2" r="1" fill="currentColor" stroke="none"/></svg>
|
||||
|
After Width: | Height: | Size: 541 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="1em" height="1em" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><ellipse cx="12" cy="6.5" rx="8" ry="2.5"/><path d="M4 6.5 5.3 18c.2 1.8 3.1 3 6.7 3s6.5-1.2 6.7-3L20 6.5"/><path d="M7 17.2c1.2.6 3 .9 5 .9s3.8-.3 5-.9"/></svg>
|
||||
|
After Width: | Height: | Size: 367 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="1em" height="1em" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m9 5 7 7-7 7"/></svg>
|
||||
|
After Width: | Height: | Size: 236 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="1em" height="1em" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M6.5 2.75H15L19.25 7v12.5a1.75 1.75 0 0 1-1.75 1.75h-11a1.75 1.75 0 0 1-1.75-1.75v-15A1.75 1.75 0 0 1 6.5 2.75Z"/><path d="M15 2.75V7h4.25"/><path d="m10 11-2 2.5 2 2.5m4-5 2 2.5-2 2.5m-.5-5.5-2 6"/></svg>
|
||||
|
After Width: | Height: | Size: 420 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="1em" height="1em" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 3v13m-5-5 5 5 5-5"/><path d="M4 16v3a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-3"/></svg>
|
||||
|
After Width: | Height: | Size: 298 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="1em" height="1em" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 20h4.1L20 8.1a2.9 2.9 0 0 0-4.1-4.1L4 15.9Z"/><path d="m13.8 6.1 4.1 4.1M4 20l4.1-4.1"/></svg>
|
||||
|
After Width: | Height: | Size: 312 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="1em" height="1em" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M6.5 2.75H15L19.25 7v12.5a1.75 1.75 0 0 1-1.75 1.75h-11a1.75 1.75 0 0 1-1.75-1.75v-15A1.75 1.75 0 0 1 6.5 2.75Z"/><path d="M15 2.75V7h4.25"/><path d="M8 12h7M8 15.5h7"/></svg>
|
||||
|
After Width: | Height: | Size: 390 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="1em" height="1em" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M2.75 7.25A2.25 2.25 0 0 1 5 5h4.2l1.8 2h8A2.25 2.25 0 0 1 21.25 9.25v9A2.75 2.75 0 0 1 18.5 21h-13a2.75 2.75 0 0 1-2.75-2.75Z"/><path d="M2.75 9h18.5"/></svg>
|
||||
|
After Width: | Height: | Size: 374 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="1em" height="1em" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="3.5" width="7.5" height="7.5" rx="1.2"/><rect x="13.5" y="3.5" width="7.5" height="7.5" rx="1.2"/><rect x="3" y="14" width="7.5" height="7.5" rx="1.2"/><rect x="13.5" y="14" width="7.5" height="7.5" rx="1.2"/></svg>
|
||||
|
After Width: | Height: | Size: 436 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="1em" height="1em" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 4v16M4 12h16"/></svg>
|
||||
|
After Width: | Height: | Size: 240 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="1em" height="1em" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M20 10a8 8 0 0 0-14.4-4.4L3 8"/><path d="M3 3v5h5"/><path d="M4 14a8 8 0 0 0 14.4 4.4L21 16"/><path d="M21 21v-5h-5"/></svg>
|
||||
|
After Width: | Height: | Size: 339 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="1em" height="1em" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="10.75" cy="10.75" r="6.75"/><path d="m16 16 5 5"/></svg>
|
||||
|
After Width: | Height: | Size: 274 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="1em" height="1em" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 6h5m4 0h9M3 12h12m4 0h2M3 18h3m4 0h11"/><circle cx="10" cy="6" r="2"/><circle cx="17" cy="12" r="2"/><circle cx="8" cy="18" r="2"/></svg>
|
||||
|
After Width: | Height: | Size: 355 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="1em" height="1em" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 6.5h16M9 6.5V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2.5M6.5 6.5l.8 13a1.7 1.7 0 0 0 1.7 1.5h6a1.7 1.7 0 0 0 1.7-1.5l.8-13M10 10.5v6m4-6v6"/></svg>
|
||||
|
After Width: | Height: | Size: 357 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="1em" height="1em" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 16V3m-5 5 5-5 5 5"/><path d="M4 16v3a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-3"/></svg>
|
||||
|
After Width: | Height: | Size: 298 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="1em" height="1em" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3.25 10a9 9 0 1 1 .7 5.35M3.25 4.5V10h5.5"/><path d="M12 7v5l3.4 2"/></svg>
|
||||
|
After Width: | Height: | Size: 291 B |
|
After Width: | Height: | Size: 697 KiB |
@@ -0,0 +1,247 @@
|
||||
(() => {
|
||||
let cleanup = null;
|
||||
|
||||
function mount() {
|
||||
if (cleanup) cleanup();
|
||||
const base = '/_objectstore/admin';
|
||||
const state = document.getElementById('perf-state');
|
||||
if (!state) return;
|
||||
const loader = document.getElementById('perf-loader');
|
||||
let active = true;
|
||||
const charts = [
|
||||
['perf-requests-chart', [
|
||||
{ type: 'line', x: 'time', y: 'requests', name: 'Requests/s' },
|
||||
{ type: 'line', x: 'time', y: 'errors', name: 'Errors/s' }
|
||||
]],
|
||||
['perf-transfer-chart', [
|
||||
{ type: 'line', x: 'time', y: 'inbound', name: 'Inbound KiB/s' },
|
||||
{ type: 'line', x: 'time', y: 'outbound', name: 'Outbound KiB/s' }
|
||||
]],
|
||||
['perf-cpu-chart', [
|
||||
{ type: 'line', x: 'time', y: 'cpu', name: 'CPU %' }
|
||||
]],
|
||||
['perf-memory-chart', [
|
||||
{ type: 'line', x: 'time', y: 'memory', name: 'RSS MiB' },
|
||||
{ type: 'line', x: 'time', y: 'heap', name: 'Heap MiB' }
|
||||
]]
|
||||
].map(([id, series]) => {
|
||||
const chart = document.getElementById(id);
|
||||
chart.series = series;
|
||||
return chart;
|
||||
});
|
||||
const history = [];
|
||||
let previous = null;
|
||||
let stream = null;
|
||||
let fallback = null;
|
||||
let polling = false;
|
||||
let memoryFallback = false;
|
||||
|
||||
function show(id, value) {
|
||||
document.getElementById(id).textContent = value;
|
||||
}
|
||||
|
||||
function showState(message, status) {
|
||||
state.textContent = message;
|
||||
state.dataset.state = status;
|
||||
if (loader) loader.hidden = status !== 'loading';
|
||||
}
|
||||
|
||||
function bytes(value, suffix = '') {
|
||||
if (!Number.isFinite(value) || value < 0) return '—';
|
||||
const units = ['B', 'KiB', 'MiB', 'GiB', 'TiB'];
|
||||
let index = 0;
|
||||
while (value >= 1024 && index < units.length - 1) {
|
||||
value /= 1024;
|
||||
index++;
|
||||
}
|
||||
return (index === 0 ? Math.round(value) : value.toFixed(1)) + ' ' + units[index] + suffix;
|
||||
}
|
||||
|
||||
function rate(value) {
|
||||
return Number.isFinite(value) ? value.toFixed(value < 10 ? 2 : 1) : '—';
|
||||
}
|
||||
|
||||
function counterDelta(current, before, key) {
|
||||
return Math.max(0, current[key] - before[key]);
|
||||
}
|
||||
|
||||
function updateCharts() {
|
||||
document.querySelector('.perf-charts').hidden = history.length === 0;
|
||||
for (const chart of charts)
|
||||
chart.data = chart.id === 'perf-cpu-chart'
|
||||
? history.filter(point => point.cpu !== null) : history;
|
||||
}
|
||||
|
||||
function showMemory(sample) {
|
||||
const rss = sample.rssBytes >= 0 ? sample.rssBytes : sample.heapBytes + sample.nonHeapBytes;
|
||||
if (sample.rssBytes < 0 && !memoryFallback) {
|
||||
memoryFallback = true;
|
||||
document.querySelector('#perf-ram').previousElementSibling.textContent = 'JVM memory used';
|
||||
charts[3].series = [
|
||||
{ type: 'line', x: 'time', y: 'memory', name: 'JVM used MiB' },
|
||||
{ type: 'line', x: 'time', y: 'heap', name: 'Heap MiB' }
|
||||
];
|
||||
}
|
||||
show('perf-ram', bytes(rss));
|
||||
return rss;
|
||||
}
|
||||
|
||||
function cpuUsage(sample, before, seconds) {
|
||||
if (!(sample.cpuNanos >= 0 && before.cpuNanos >= 0)) return null;
|
||||
return Math.max(0, Math.min(100,
|
||||
(sample.cpuNanos - before.cpuNanos) /
|
||||
(seconds * 1e9 * Math.max(1, sample.processors)) * 100));
|
||||
}
|
||||
|
||||
function samplePoint(sample, before, seconds, rss) {
|
||||
const errors = counterDelta(sample, before, 'failures4xx') +
|
||||
counterDelta(sample, before, 'failures5xx');
|
||||
return {
|
||||
time: new Date().toLocaleTimeString(),
|
||||
requests: counterDelta(sample, before, 'requests') / seconds,
|
||||
errors: errors / seconds,
|
||||
inbound: counterDelta(sample, before, 'inboundBytes') / seconds / 1024,
|
||||
outbound: counterDelta(sample, before, 'outboundBytes') / seconds / 1024,
|
||||
cpu: cpuUsage(sample, before, seconds),
|
||||
memory: rss / 1048576,
|
||||
heap: sample.heapBytes / 1048576,
|
||||
seconds
|
||||
};
|
||||
}
|
||||
|
||||
function showCpuAverage() {
|
||||
const cpuPoints = history.filter(entry => entry.cpu !== null);
|
||||
const cpuSeconds = cpuPoints.reduce((total, entry) => total + entry.seconds, 0);
|
||||
show('perf-cpu', cpuSeconds ?
|
||||
(cpuPoints.reduce((total, entry) => total + entry.cpu * entry.seconds, 0) /
|
||||
cpuSeconds).toFixed(1) + '%' : '—');
|
||||
}
|
||||
|
||||
function showInterval(sample, before, point) {
|
||||
const requests = counterDelta(sample, before, 'requests');
|
||||
show('perf-rps', rate(point.requests));
|
||||
show('perf-latency', requests ?
|
||||
(counterDelta(sample, before, 'durationNanos') / requests / 1e6).toFixed(1) + ' ms' : '—');
|
||||
show('perf-inbound', bytes(point.inbound * 1024, '/s'));
|
||||
show('perf-outbound', bytes(point.outbound * 1024, '/s'));
|
||||
showCpuAverage();
|
||||
updateCharts();
|
||||
}
|
||||
|
||||
function recordSample(sample, now, rss) {
|
||||
if (!previous) return;
|
||||
const before = previous.sample;
|
||||
if (sample.requests < before.requests) {
|
||||
history.length = 0;
|
||||
updateCharts();
|
||||
}
|
||||
if (!(sample.requests >= before.requests)) return;
|
||||
const seconds = (now - previous.at) / 1000;
|
||||
if (!(seconds > 0.1)) return;
|
||||
const point = samplePoint(sample, before, seconds, rss);
|
||||
history.push(point);
|
||||
if (history.length > 60) history.shift();
|
||||
showInterval(sample, before, point);
|
||||
}
|
||||
|
||||
function accept(sample) {
|
||||
if (!active || document.hidden) return;
|
||||
try {
|
||||
const now = performance.now();
|
||||
const rss = showMemory(sample);
|
||||
show('perf-gc', Number(sample.gcCount).toLocaleString());
|
||||
show('perf-inflight', Number(sample.inFlight).toLocaleString());
|
||||
recordSample(sample, now, rss);
|
||||
previous = { sample, at: now };
|
||||
showState(history.length ? 'Live · one-second samples' :
|
||||
'Collecting a second sample…', history.length ? 'live' : 'loading');
|
||||
} catch {
|
||||
showState('Invalid metrics sample · retrying', 'error');
|
||||
previous = null;
|
||||
}
|
||||
}
|
||||
|
||||
async function pollFallback() {
|
||||
if (!active || document.hidden || polling) return;
|
||||
polling = true;
|
||||
const controller = new AbortController();
|
||||
const timeout = setTimeout(() => controller.abort(), 5000);
|
||||
try {
|
||||
const response = await fetch(base + '/performance.json', {
|
||||
cache: 'no-store', credentials: 'same-origin', signal: controller.signal
|
||||
});
|
||||
if (response.redirected) {
|
||||
location.assign(base + '/login');
|
||||
return;
|
||||
}
|
||||
if (!response.ok) throw new Error('Metrics unavailable');
|
||||
accept(await response.json());
|
||||
} catch {
|
||||
if (!active) return;
|
||||
showState('Connection lost · retrying', 'error');
|
||||
previous = null;
|
||||
} finally {
|
||||
clearTimeout(timeout);
|
||||
polling = false;
|
||||
}
|
||||
}
|
||||
|
||||
function connect() {
|
||||
if (!active || document.hidden) return;
|
||||
if (!window.EventSource) {
|
||||
if (!fallback) fallback = setInterval(pollFallback, 1000);
|
||||
pollFallback();
|
||||
return;
|
||||
}
|
||||
stream = new EventSource(base + '/performance.events');
|
||||
stream.onmessage = event => {
|
||||
try { accept(JSON.parse(event.data)); }
|
||||
catch { showState('Invalid metrics sample · retrying', 'error'); }
|
||||
};
|
||||
stream.onerror = () => {
|
||||
if (!active) return;
|
||||
previous = null;
|
||||
showState('Connection lost · retrying', 'error');
|
||||
fetch(base + '/performance.json', { credentials: 'same-origin', cache: 'no-store' })
|
||||
.then(response => { if (response.redirected) location.assign(base + '/login'); })
|
||||
.catch(() => {});
|
||||
};
|
||||
}
|
||||
|
||||
function disconnect() {
|
||||
stream?.close();
|
||||
stream = null;
|
||||
if (fallback) clearInterval(fallback);
|
||||
fallback = null;
|
||||
previous = null;
|
||||
}
|
||||
|
||||
const visibilityChanged = () => {
|
||||
if (!active) return;
|
||||
if (document.hidden) {
|
||||
disconnect();
|
||||
showState('Paused while this tab is hidden', 'paused');
|
||||
} else {
|
||||
showState('Collecting a fresh sample…', 'loading');
|
||||
connect();
|
||||
}
|
||||
};
|
||||
document.addEventListener('visibilitychange', visibilityChanged);
|
||||
connect();
|
||||
cleanup = () => {
|
||||
active = false;
|
||||
disconnect();
|
||||
document.removeEventListener('visibilitychange', visibilityChanged);
|
||||
};
|
||||
}
|
||||
|
||||
function unmount() {
|
||||
if (cleanup) cleanup();
|
||||
cleanup = null;
|
||||
}
|
||||
|
||||
window.ObjectStorePerformance = { mount, unmount };
|
||||
if (document.readyState === 'loading')
|
||||
document.addEventListener('DOMContentLoaded', mount, { once: true });
|
||||
else mount();
|
||||
})();
|
||||
@@ -0,0 +1,551 @@
|
||||
(() => {
|
||||
const base = "/_objectstore/admin";
|
||||
const pages = new Set(["overview", "buckets", "bucket", "object", "versions", "credentials", "performance", "diagnostics", "health", "audit", "jobs", "cluster", "settings"]);
|
||||
let pending = null;
|
||||
let loadingTimer = null;
|
||||
let performanceScript = null;
|
||||
const defaults = { theme: "deep-dark", brand: "ObjectStore admin", icon: base + "/logo.png" };
|
||||
const themes = ["auto", "light", "dark", "deep-dark"];
|
||||
let branding = { name: defaults.brand, icon: defaults.icon, defaultTheme: defaults.theme };
|
||||
|
||||
function saved(key, fallback) {
|
||||
try { return localStorage.getItem("objectstore-admin-" + key) || fallback; }
|
||||
catch { return fallback; }
|
||||
}
|
||||
|
||||
function save(key, value) {
|
||||
try { localStorage.setItem("objectstore-admin-" + key, value); return true; }
|
||||
catch { return false; }
|
||||
}
|
||||
|
||||
function clear(key) {
|
||||
try { localStorage.removeItem("objectstore-admin-" + key); return true; }
|
||||
catch { return false; }
|
||||
}
|
||||
|
||||
function preferences() {
|
||||
const stored = saved("theme", "");
|
||||
const personalTheme = themes.includes(stored) ? stored : "";
|
||||
return { personalTheme, theme: personalTheme || branding.defaultTheme };
|
||||
}
|
||||
|
||||
function applyPreferences() {
|
||||
const { theme, personalTheme } = preferences();
|
||||
const brand = branding.name;
|
||||
const icon = branding.icon;
|
||||
document.body.dataset.adminTheme = theme === "auto" ?
|
||||
(matchMedia("(prefers-color-scheme: light)").matches ? "light" : "dark") : theme;
|
||||
for (const widget of document.querySelectorAll("biscuit-sidebarview, biscuit-navbarview, " +
|
||||
"biscuit-footerview, biscuit-cardview, biscuit-badgeview, biscuit-chartview, " +
|
||||
"biscuit-activity-chart, biscuit-tablayout, biscuit-formwizardview, " +
|
||||
"biscuit-pageloaderview, biscuit-loadingindicator, biscuit-skeletonview, biscuit-paginationview, " +
|
||||
"biscuit-codeview, biscuit-dialogview, biscuit-accordionview, biscuit-toastview"))
|
||||
widget.setAttribute("theme", theme);
|
||||
document.querySelector("biscuit-navbarview")?.setAttribute("brand", brand);
|
||||
document.querySelector("biscuit-footerview")?.setAttribute("brand", brand);
|
||||
const sidebarName = document.querySelector(".sidebar-brand strong");
|
||||
if (sidebarName) sidebarName.textContent = brand;
|
||||
const loginName = document.querySelector(".login-brand strong");
|
||||
if (loginName) loginName.textContent = brand;
|
||||
const sidebarIcon = document.querySelector(".sidebar-brand .mark img");
|
||||
if (sidebarIcon) sidebarIcon.src = icon;
|
||||
const loginIcon = document.querySelector(".login-brand .mark img");
|
||||
if (loginIcon) loginIcon.src = icon;
|
||||
const themeInput = document.getElementById("admin-theme");
|
||||
if (themeInput) themeInput.value = personalTheme || "default";
|
||||
const globalThemeInput = document.getElementById("admin-global-theme");
|
||||
if (globalThemeInput && document.activeElement !== globalThemeInput)
|
||||
globalThemeInput.value = branding.defaultTheme;
|
||||
const brandInput = document.getElementById("admin-brand-text");
|
||||
if (brandInput && document.activeElement !== brandInput) brandInput.value = brand;
|
||||
const preview = document.getElementById("admin-brand-preview");
|
||||
if (preview) preview.src = icon;
|
||||
const previewText = document.getElementById("admin-brand-preview-text");
|
||||
if (previewText) previewText.textContent = brand;
|
||||
}
|
||||
|
||||
async function loadBranding() {
|
||||
try {
|
||||
const response = await fetch(base + "/branding.json", { cache: "no-store" });
|
||||
if (!response.ok) return;
|
||||
const next = await response.json();
|
||||
if (typeof next.name !== "string" || typeof next.icon !== "string" ||
|
||||
!next.icon.startsWith(base + "/")) return;
|
||||
branding = { name: next.name, icon: next.icon,
|
||||
defaultTheme: themes.includes(next.defaultTheme) ? next.defaultTheme : defaults.theme };
|
||||
applyPreferences();
|
||||
} catch { return; }
|
||||
}
|
||||
|
||||
function pageName(url) {
|
||||
if (url.origin !== location.origin || !url.pathname.startsWith(base + "/")) return null;
|
||||
const name = url.pathname.slice(base.length + 1);
|
||||
return pages.has(name) ? name : null;
|
||||
}
|
||||
|
||||
function updateNavigation() {
|
||||
const current = location.pathname.split("/").pop();
|
||||
const section = ["bucket", "object", "versions"].includes(current) ? "buckets" : current;
|
||||
for (const link of document.querySelectorAll(".sidebar-link, .mobile-nav-link")) {
|
||||
if (link.pathname.endsWith("/" + section)) link.setAttribute("aria-current", "page");
|
||||
else link.removeAttribute("aria-current");
|
||||
}
|
||||
}
|
||||
|
||||
function loading(active, label = "Loading page…") {
|
||||
clearTimeout(loadingTimer);
|
||||
const overlay = document.getElementById("page-loading");
|
||||
const content = document.querySelector(".workspace-content");
|
||||
if (!overlay || !content) return;
|
||||
if (active) {
|
||||
content.setAttribute("aria-busy", "true");
|
||||
overlay.setAttribute("message", label);
|
||||
loadingTimer = setTimeout(() => { overlay.show?.(); }, 140);
|
||||
} else {
|
||||
overlay.hide?.();
|
||||
content.removeAttribute("aria-busy");
|
||||
}
|
||||
}
|
||||
|
||||
function navigationError(message) {
|
||||
const content = document.querySelector(".workspace-content");
|
||||
let notice = content.querySelector(".navigation-error");
|
||||
if (!notice) {
|
||||
notice = document.createElement("p");
|
||||
notice.className = "navigation-error";
|
||||
notice.setAttribute("role", "alert");
|
||||
content.prepend(notice);
|
||||
}
|
||||
notice.textContent = message;
|
||||
const toast = document.getElementById("admin-toast");
|
||||
if (toast?.matches(":defined")) toast.show(message, { variant: "danger", duration: 6000 });
|
||||
}
|
||||
|
||||
async function mountPerformance() {
|
||||
if (location.pathname !== base + "/performance") return;
|
||||
if (window.ObjectStorePerformance) {
|
||||
window.ObjectStorePerformance.mount();
|
||||
return;
|
||||
}
|
||||
if (!performanceScript) {
|
||||
performanceScript = new Promise((resolve, reject) => {
|
||||
const script = document.createElement("script");
|
||||
script.src = base + "/performance.js";
|
||||
script.onload = resolve;
|
||||
script.onerror = reject;
|
||||
document.head.append(script);
|
||||
});
|
||||
}
|
||||
try { await performanceScript; }
|
||||
catch {
|
||||
performanceScript = null;
|
||||
navigationError("Live charts could not load. Reload this page to try again.");
|
||||
}
|
||||
}
|
||||
|
||||
async function navigate(input, mode = "push", options = {}) {
|
||||
const url = new URL(input, location.href);
|
||||
if (!pageName(url)) { location.assign(url.href); return; }
|
||||
if (mode === "push") history.replaceState({ scrollY: window.scrollY }, "", location.href);
|
||||
pending?.abort();
|
||||
const controller = new AbortController();
|
||||
pending = controller;
|
||||
loading(true, options.label);
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
credentials: "same-origin", cache: "no-store", signal: controller.signal
|
||||
});
|
||||
const destination = new URL(response.url);
|
||||
if (!pageName(destination)) { location.assign(destination.href); return; }
|
||||
if (!response.headers.get("Content-Type")?.startsWith("text/html"))
|
||||
throw new Error("The server returned an unexpected response.");
|
||||
const parsed = new DOMParser().parseFromString(await response.text(), "text/html");
|
||||
if (controller.signal.aborted) return;
|
||||
const next = parsed.querySelector(".workspace-content");
|
||||
if (!next) { location.assign(destination.href); return; }
|
||||
window.ObjectStorePerformance?.unmount();
|
||||
document.querySelector(".workspace-content").replaceWith(document.importNode(next, true));
|
||||
if (mode === "push") history.pushState({ scrollY: 0 }, "", destination.href);
|
||||
document.title = parsed.title || "ObjectStore admin";
|
||||
updateNavigation();
|
||||
mountContent(document.querySelector(".workspace-content"));
|
||||
window.scrollTo(0, mode === "pop" ? options.scrollY || 0 : 0);
|
||||
void mountPerformance();
|
||||
} catch (error) {
|
||||
if (error.name !== "AbortError")
|
||||
navigationError(error.message || "The page could not be loaded. Try again.");
|
||||
} finally {
|
||||
if (pending === controller) { pending = null; loading(false); }
|
||||
}
|
||||
}
|
||||
|
||||
if (globalThis.Biscuit?.registerCodeLanguage) {
|
||||
try {
|
||||
Biscuit.registerCodeLanguage("json", { rules: [
|
||||
{ type: "property", pattern: /"(?:\\.|[^"\\])*"(?=\s*:)/ },
|
||||
{ type: "string", pattern: /"(?:\\.|[^"\\])*"/ },
|
||||
{ type: "number", pattern: /-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?/ },
|
||||
{ type: "keyword", pattern: /\b(?:true|false|null)\b/ }
|
||||
] });
|
||||
} catch (error) {
|
||||
console.error("JSON highlighting unavailable", error);
|
||||
}
|
||||
}
|
||||
|
||||
function mountContent(root) {
|
||||
applyPreferences();
|
||||
const bulkForm = root.querySelector("form[action$='/bulk-start']");
|
||||
if (bulkForm) {
|
||||
const operation = bulkForm.elements.operation;
|
||||
const update = () => {
|
||||
for (const field of bulkForm.querySelectorAll("[data-bulk-only]")) {
|
||||
const visible = field.dataset.bulkOnly === operation.value;
|
||||
field.hidden = !visible;
|
||||
field.querySelector("input").required = visible &&
|
||||
["targetBucket", "tag", "confirm"].includes(field.querySelector("input").name);
|
||||
}
|
||||
};
|
||||
operation.addEventListener("change", update);
|
||||
update();
|
||||
}
|
||||
const liveJobs = [...root.querySelectorAll("[data-job-id]")]
|
||||
.filter(row => row.querySelector("form[action$='/bulk-cancel']"));
|
||||
if (liveJobs.length) {
|
||||
const poll = async () => {
|
||||
if (!root.isConnected) return;
|
||||
for (const row of liveJobs) {
|
||||
if (!row.querySelector("form[action$='/bulk-cancel']")) continue;
|
||||
try {
|
||||
const response = await fetch(base + "/jobs.json?id=" + row.dataset.jobId,
|
||||
{ cache: "no-store", signal: AbortSignal.timeout(10000) });
|
||||
if (!response.ok) continue;
|
||||
const job = await response.json();
|
||||
if (!root.isConnected) return;
|
||||
row.querySelector("[data-job-state]").textContent = job.state;
|
||||
row.querySelector("[data-job-counts]").textContent =
|
||||
`${job.processed} processed · ${job.succeeded} succeeded · ${job.failed} failed`;
|
||||
if (job.finished) {
|
||||
row.querySelector("form[action$='/bulk-cancel']")?.remove();
|
||||
}
|
||||
} catch { /* The next poll may succeed. */ }
|
||||
}
|
||||
if (root.isConnected && liveJobs.some(row => row.querySelector("form[action$='/bulk-cancel']")))
|
||||
setTimeout(poll, 1500);
|
||||
};
|
||||
setTimeout(poll, 1500);
|
||||
}
|
||||
root.querySelector("#diagnostic-probe")?.addEventListener("click", async event => {
|
||||
const button = event.currentTarget;
|
||||
const result = root.querySelector("#diagnostic-probe-result");
|
||||
button.disabled = true;
|
||||
result.textContent = "Measuring…";
|
||||
const started = performance.now();
|
||||
try {
|
||||
const response = await fetch(base + "/diagnostics/probe.bin", { cache: "no-store" });
|
||||
if (!response.ok || !response.body) throw new Error("Probe unavailable");
|
||||
const firstByte = performance.now();
|
||||
const reader = response.body.getReader();
|
||||
let bytes = 0;
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
bytes += value.byteLength;
|
||||
}
|
||||
const elapsed = performance.now() - started;
|
||||
result.textContent = `${Math.round(firstByte - started)} ms to headers · ` +
|
||||
`${Math.round(elapsed)} ms total · ${(bytes / 1048576 / (elapsed / 1000)).toFixed(1)} MiB/s`;
|
||||
} catch {
|
||||
result.textContent = "Probe failed. Check the connection and try again.";
|
||||
} finally {
|
||||
button.disabled = false;
|
||||
}
|
||||
});
|
||||
const bucketTabs = root.querySelector("biscuit-tablayout[aria-label='Bucket panels']");
|
||||
if (bucketTabs) {
|
||||
const selected = location.hash.slice(1);
|
||||
if (["objects", "activity", "settings"].includes(selected)) bucketTabs.value = selected;
|
||||
bucketTabs.addEventListener("change", () => {
|
||||
history.replaceState(history.state, "", location.pathname + location.search + "#" + bucketTabs.value);
|
||||
});
|
||||
}
|
||||
root.querySelector(".bucket-pagination")?.addEventListener("change", event => {
|
||||
const params = new URLSearchParams();
|
||||
const filter = event.currentTarget.dataset.filter;
|
||||
if (filter) params.set("filter", filter);
|
||||
params.set("page", String(event.detail.page));
|
||||
void navigate(base + "/buckets?" + params, "push", { label: "Loading buckets…" });
|
||||
});
|
||||
const wizard = root.querySelector("#create-bucket-wizard");
|
||||
if (wizard) {
|
||||
const form = wizard.closest("form");
|
||||
const accessChecks = [...form.querySelectorAll("[name=blockPublicAcls], [name=ignorePublicAcls], " +
|
||||
"[name=blockPublicPolicy], [name=restrictPublicBuckets]")];
|
||||
const ackRow = form.querySelector("#public-ack-row");
|
||||
const acknowledge = ackRow.querySelector("input");
|
||||
const review = form.querySelector("#bucket-wizard-review");
|
||||
const updateReview = () => {
|
||||
const name = form.elements.bucket.value || "this bucket";
|
||||
const versioning = form.elements.versioning.value === "enabled" ? "on" : "off";
|
||||
const ownership = form.elements.ownership.selectedOptions[0]?.textContent.split(" · ")[0];
|
||||
review.textContent = `Create ${name} with versioning ${versioning}, ${ownership}, and ` +
|
||||
(accessChecks.every(input => input.checked) ? "all public access controls on." :
|
||||
"some public access controls off.");
|
||||
};
|
||||
const updateAccess = () => {
|
||||
const relaxed = accessChecks.some(input => !input.checked);
|
||||
ackRow.hidden = !relaxed;
|
||||
acknowledge.required = relaxed;
|
||||
if (!relaxed) acknowledge.checked = false;
|
||||
updateReview();
|
||||
};
|
||||
accessChecks.forEach(input => input.addEventListener("change", updateAccess));
|
||||
wizard.addEventListener("stepchange", updateReview);
|
||||
form.addEventListener("submit", event => {
|
||||
if (wizard.currentStep < wizard.steps.length - 1) {
|
||||
event.preventDefault();
|
||||
wizard.next();
|
||||
}
|
||||
});
|
||||
wizard.closest("biscuit-dialogview")?.addEventListener("close", () => {
|
||||
form.reset();
|
||||
wizard.currentStep = 0;
|
||||
updateAccess();
|
||||
});
|
||||
updateAccess();
|
||||
}
|
||||
const themeInput = root.querySelector("#admin-theme");
|
||||
themeInput?.addEventListener("change", () => {
|
||||
if (themeInput.value === "default") clear("theme");
|
||||
else if (themes.includes(themeInput.value)) save("theme", themeInput.value);
|
||||
applyPreferences();
|
||||
});
|
||||
const iconInput = root.querySelector("#admin-brand-icon");
|
||||
iconInput?.addEventListener("change", async () => {
|
||||
const file = iconInput.files?.[0];
|
||||
if (!file) return;
|
||||
const status = root.querySelector("#admin-settings-status");
|
||||
if (!["image/png", "image/jpeg", "image/webp"].includes(file.type) || file.size > 131072) {
|
||||
status.textContent = "Choose a PNG, JPEG, or WebP image under 128 KiB.";
|
||||
return;
|
||||
}
|
||||
iconInput.disabled = true;
|
||||
status.textContent = "Uploading icon…";
|
||||
try {
|
||||
const response = await fetch(base + "/branding-icon/upload", {
|
||||
method: "POST", body: file, credentials: "same-origin",
|
||||
headers: { "Content-Type": file.type, "X-CSRF-Token": iconInput.dataset.csrf }
|
||||
});
|
||||
if (!response.ok) throw new Error(await response.text());
|
||||
await loadBranding();
|
||||
status.textContent = "Icon saved on this server.";
|
||||
} catch (error) {
|
||||
status.textContent = error.message || "Could not save the icon.";
|
||||
} finally {
|
||||
iconInput.disabled = false;
|
||||
}
|
||||
});
|
||||
for (const button of root.querySelectorAll("[data-open-dialog]")) {
|
||||
button.addEventListener("click", () => {
|
||||
const dialog = root.querySelector("#" + button.dataset.openDialog);
|
||||
dialog?.show?.();
|
||||
dialog?.querySelector("input:not([type=hidden])")?.focus();
|
||||
});
|
||||
}
|
||||
for (const button of root.querySelectorAll("[data-close-dialog]")) {
|
||||
button.addEventListener("click", () => button.closest("biscuit-dialogview")?.hide?.());
|
||||
}
|
||||
for (const form of root.querySelectorAll(".code-form")) {
|
||||
const editor = form.querySelector("biscuit-codeview");
|
||||
const fallback = form.querySelector("textarea.code-fallback");
|
||||
const diagnostics = form.querySelector(".editor-diagnostics");
|
||||
const field = fallback?.getAttribute("name");
|
||||
if (!editor || !fallback || !diagnostics || !field) continue;
|
||||
|
||||
const validate = () => {
|
||||
const value = editor.matches(":defined") ? editor.value : fallback.value;
|
||||
if (editor.getAttribute("language") === "json" && value.trim()) {
|
||||
try {
|
||||
JSON.parse(value);
|
||||
} catch (error) {
|
||||
diagnostics.dataset.state = "error";
|
||||
diagnostics.textContent = "JSON syntax: " + error.message;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (field === "content" && new TextEncoder().encode(value).length > 32768) {
|
||||
diagnostics.dataset.state = "error";
|
||||
diagnostics.textContent = "Text files are limited to 32 KiB in the admin editor.";
|
||||
return false;
|
||||
}
|
||||
diagnostics.dataset.state = "ok";
|
||||
diagnostics.textContent = field === "policy" ?
|
||||
"JSON syntax looks valid. Policy permissions are checked when saved." :
|
||||
"Ready to save as a new object version.";
|
||||
return true;
|
||||
};
|
||||
|
||||
customElements.whenDefined("biscuit-codeview").then(() => {
|
||||
if (!form.isConnected) return;
|
||||
editor.name = field;
|
||||
fallback.removeAttribute("name");
|
||||
fallback.hidden = true;
|
||||
form.dataset.enhanced = "";
|
||||
editor.addEventListener("input", validate);
|
||||
});
|
||||
fallback.addEventListener("input", validate);
|
||||
form.addEventListener("submit", (event) => {
|
||||
if (validate()) return;
|
||||
event.preventDefault();
|
||||
editor.shadowRoot?.querySelector("textarea")?.focus();
|
||||
});
|
||||
}
|
||||
|
||||
for (const form of root.querySelectorAll(".upload-form")) {
|
||||
const fileInput = form.elements.namedItem("file");
|
||||
const keyInput = form.elements.namedItem("key");
|
||||
const overwriteInput = form.elements.namedItem("overwrite");
|
||||
const button = form.querySelector("button[type=submit]");
|
||||
const status = form.querySelector(".upload-status");
|
||||
const prefix = form.dataset.prefix || "";
|
||||
const progress = document.createElement("progress");
|
||||
progress.className = "upload-progress";
|
||||
progress.max = 100;
|
||||
progress.hidden = true;
|
||||
progress.setAttribute("aria-label", "Upload progress");
|
||||
status.after(progress);
|
||||
fileInput.addEventListener("change", () => {
|
||||
if (fileInput.files[0] && (!keyInput.value || keyInput.value === prefix))
|
||||
keyInput.value = prefix + fileInput.files[0].name;
|
||||
});
|
||||
status.textContent = "Choose a file, then upload it to this bucket.";
|
||||
form.addEventListener("submit", (event) => {
|
||||
event.preventDefault();
|
||||
const file = fileInput.files[0];
|
||||
if (!file) return;
|
||||
const key = keyInput.value.trim();
|
||||
if (!key) {
|
||||
status.textContent = "Enter an object key.";
|
||||
return;
|
||||
}
|
||||
if (file.size > Number(form.dataset.maxBytes)) {
|
||||
status.textContent = "This file exceeds the configured object limit.";
|
||||
return;
|
||||
}
|
||||
const query = new URLSearchParams({ bucket: form.dataset.bucket, key });
|
||||
if (overwriteInput.checked) query.set("overwrite", "1");
|
||||
button.disabled = true;
|
||||
form.dataset.busy = "";
|
||||
progress.hidden = false;
|
||||
progress.removeAttribute("value");
|
||||
status.textContent = "Uploading…";
|
||||
const request = new XMLHttpRequest();
|
||||
request.open("POST", base + "/upload?" + query);
|
||||
request.withCredentials = true;
|
||||
request.setRequestHeader("Content-Type", file.type || "application/octet-stream");
|
||||
request.setRequestHeader("X-ObjectStore-CSRF", form.elements.namedItem("csrf").value);
|
||||
request.upload.onprogress = (event) => {
|
||||
if (!event.lengthComputable) return;
|
||||
const percent = Math.round(event.loaded / event.total * 100);
|
||||
progress.value = percent;
|
||||
status.textContent = "Uploading… " + percent + "%";
|
||||
};
|
||||
request.onload = () => {
|
||||
if (request.status === 201 && request.getResponseHeader("Location")) {
|
||||
status.textContent = "Upload complete. Opening object…";
|
||||
void navigate(request.getResponseHeader("Location"), "push").finally(() => {
|
||||
if (!form.isConnected) return;
|
||||
button.disabled = false;
|
||||
delete form.dataset.busy;
|
||||
progress.hidden = true;
|
||||
});
|
||||
return;
|
||||
}
|
||||
status.textContent = request.responseText || "Upload failed.";
|
||||
button.disabled = false;
|
||||
delete form.dataset.busy;
|
||||
progress.hidden = true;
|
||||
};
|
||||
request.onerror = () => {
|
||||
status.textContent = "Connection lost during upload. Check the object list before retrying.";
|
||||
button.disabled = false;
|
||||
delete form.dataset.busy;
|
||||
progress.hidden = true;
|
||||
};
|
||||
request.send(file);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
document.addEventListener("click", (event) => {
|
||||
if (event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey ||
|
||||
event.shiftKey || event.altKey) return;
|
||||
const link = event.composedPath().find(node => node instanceof HTMLAnchorElement && node.href);
|
||||
if (!link || link.hasAttribute("download") || link.target && link.target !== "_self") return;
|
||||
const url = new URL(link.href);
|
||||
if (!pageName(url) || url.hash && url.pathname === location.pathname &&
|
||||
url.search === location.search) return;
|
||||
event.preventDefault();
|
||||
void navigate(url);
|
||||
});
|
||||
|
||||
document.addEventListener("submit", (event) => {
|
||||
if (event.defaultPrevented) return;
|
||||
const form = event.target;
|
||||
if (!(form instanceof HTMLFormElement) || !form.closest(".workspace-content")) return;
|
||||
if (form.action.endsWith("/action/access-check")) {
|
||||
event.preventDefault();
|
||||
pending?.abort();
|
||||
const controller = new AbortController();
|
||||
pending = controller;
|
||||
loading(true, "Checking access…");
|
||||
void (async () => {
|
||||
try {
|
||||
const response = await fetch(form.action, {
|
||||
method: "POST", body: new URLSearchParams(new FormData(form)),
|
||||
credentials: "same-origin", cache: "no-store", signal: controller.signal
|
||||
});
|
||||
const destination = new URL(response.url);
|
||||
if (!pageName(destination)) { location.assign(destination.href); return; }
|
||||
if (!response.headers.get("Content-Type")?.startsWith("text/html"))
|
||||
throw new Error("The access check did not return a page.");
|
||||
const parsed = new DOMParser().parseFromString(await response.text(), "text/html");
|
||||
if (controller.signal.aborted || !form.isConnected) return;
|
||||
const next = parsed.querySelector(".workspace-content");
|
||||
if (!next) throw new Error("The access check could not be displayed.");
|
||||
window.ObjectStorePerformance?.unmount();
|
||||
document.querySelector(".workspace-content").replaceWith(document.importNode(next, true));
|
||||
history.replaceState(history.state, "", base + "/audit");
|
||||
mountContent(document.querySelector(".workspace-content"));
|
||||
if (!response.ok) navigationError("Access could not be checked. Review the details below.");
|
||||
} catch (error) {
|
||||
if (error.name !== "AbortError") navigationError(error.message || "Access check failed.");
|
||||
} finally {
|
||||
if (pending === controller) { pending = null; loading(false); }
|
||||
}
|
||||
})();
|
||||
return;
|
||||
}
|
||||
if (form.method.toUpperCase() === "GET" && pageName(new URL(form.action))) {
|
||||
event.preventDefault();
|
||||
const url = new URL(form.action);
|
||||
for (const [key, value] of new FormData(form)) url.searchParams.set(key, value);
|
||||
void navigate(url, "push", { label: "Opening results…" });
|
||||
} else if (form.method.toUpperCase() === "POST" && !form.classList.contains("upload-form")) {
|
||||
form.dataset.busy = "";
|
||||
loading(true, "Saving changes…");
|
||||
}
|
||||
});
|
||||
|
||||
applyPreferences();
|
||||
void loadBranding();
|
||||
matchMedia("(prefers-color-scheme: light)").addEventListener("change", applyPreferences);
|
||||
if (document.querySelector(".workspace-content")) {
|
||||
history.replaceState({ scrollY: window.scrollY }, "", location.href);
|
||||
window.addEventListener("popstate", (event) => {
|
||||
void navigate(location.href, "pop", { scrollY: event.state?.scrollY || 0 });
|
||||
});
|
||||
updateNavigation();
|
||||
mountContent(document.querySelector(".workspace-content"));
|
||||
loading(false);
|
||||
}
|
||||
})();
|
||||
@@ -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.
|
||||
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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)"
|
||||
@@ -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()
|
||||
@@ -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"
|
||||
@@ -0,0 +1,12 @@
|
||||
services:
|
||||
objectstore:
|
||||
environment:
|
||||
ADMIN_UI_ENABLED: "true"
|
||||
ADMIN_UI_PASSWORD_FILE: /run/secrets/objectstore_admin
|
||||
ADMIN_UI_ORIGIN: ${ADMIN_UI_ORIGIN:-}
|
||||
ADMIN_UI_PRIVATE_ORIGIN: ${ADMIN_UI_PRIVATE_ORIGIN:-}
|
||||
ADMIN_UI_BIND_ADDRESS: 0.0.0.0
|
||||
ports:
|
||||
- "${ADMIN_UI_BIND_IP:-127.0.0.1}:${ADMIN_UI_HOST_PORT:-9001}:9001"
|
||||
volumes:
|
||||
- ./secrets/admin-password:/run/secrets/objectstore_admin:ro
|
||||
@@ -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
|
||||
@@ -25,6 +25,11 @@ services:
|
||||
target: /tmp
|
||||
bind:
|
||||
create_host_path: false
|
||||
- type: bind
|
||||
source: ${ENCRYPTED_STORAGE_ROOT:?Set ENCRYPTED_STORAGE_ROOT}/cluster/gateway-admin
|
||||
target: /data
|
||||
bind:
|
||||
create_host_path: false
|
||||
|
||||
metadata:
|
||||
environment:
|
||||
|
||||
@@ -14,12 +14,15 @@ services:
|
||||
S3_REGION: ${S3_REGION:-us-east-1}
|
||||
S3_CREDENTIALS_FILE: ${S3_CREDENTIALS_FILE:-}
|
||||
S3_KEY_SCOPES_FILE: ${S3_KEY_SCOPES_FILE:-}
|
||||
S3_SESSION_CREDENTIALS_FILE: ${S3_SESSION_CREDENTIALS_FILE:-}
|
||||
S3_IDENTITY_POLICIES_DIR: ${S3_IDENTITY_POLICIES_DIR:-}
|
||||
METRICS_BEARER_TOKEN: ${METRICS_BEARER_TOKEN:-}
|
||||
MAX_OBJECT_BYTES: ${MAX_OBJECT_BYTES:-134217728}
|
||||
MAX_TOTAL_BYTES: ${MAX_TOTAL_BYTES:-2147483648}
|
||||
MAX_IN_FLIGHT_REQUESTS: ${MAX_IN_FLIGHT_REQUESTS:-16}
|
||||
HTTP_BACKLOG: ${HTTP_BACKLOG:-64}
|
||||
S3_VIRTUAL_HOST_SUFFIX: ${S3_VIRTUAL_HOST_SUFFIX:-}
|
||||
S3_PUBLIC_ENDPOINT: ${S3_PUBLIC_ENDPOINT:-}
|
||||
CORS_ALLOWED_ORIGINS: ${CORS_ALLOWED_ORIGINS:-}
|
||||
OBJECTSTORE_REQUEST_TIMEOUT_SECONDS: ${OBJECTSTORE_REQUEST_TIMEOUT_SECONDS:-0}
|
||||
OBJECTSTORE_RESPONSE_TIMEOUT_SECONDS: ${OBJECTSTORE_RESPONSE_TIMEOUT_SECONDS:-0}
|
||||
@@ -34,6 +37,9 @@ services:
|
||||
POSTGRES_JDBC_URL: ${POSTGRES_JDBC_URL:-jdbc:postgresql://metadata:5432/objectstore?connectTimeout=3&socketTimeout=10&targetServerType=primary}
|
||||
POSTGRES_USER: objectstore
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD}
|
||||
ADMIN_UI_STATE_DIR: /data
|
||||
volumes:
|
||||
- cluster-gateway-admin:/data
|
||||
ports:
|
||||
- "127.0.0.1:${CLUSTER_HOST_PORT:-9001}:9000"
|
||||
depends_on:
|
||||
@@ -201,6 +207,7 @@ services:
|
||||
- cluster-node-d:/data
|
||||
|
||||
volumes:
|
||||
cluster-gateway-admin:
|
||||
cluster-metadata:
|
||||
cluster-metadata-recovery:
|
||||
cluster-node-a:
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
services:
|
||||
objectstore:
|
||||
environment:
|
||||
S3_MANAGED_KEYS_MASTER_FILE: /run/secrets/objectstore_managed_master
|
||||
volumes:
|
||||
- ./secrets/managed-master:/run/secrets/objectstore_managed_master:ro
|
||||
@@ -13,12 +13,15 @@ services:
|
||||
S3_REGION: ${S3_REGION:-us-east-1}
|
||||
S3_CREDENTIALS_FILE: ${S3_CREDENTIALS_FILE:-}
|
||||
S3_KEY_SCOPES_FILE: ${S3_KEY_SCOPES_FILE:-}
|
||||
S3_SESSION_CREDENTIALS_FILE: ${S3_SESSION_CREDENTIALS_FILE:-}
|
||||
S3_IDENTITY_POLICIES_DIR: ${S3_IDENTITY_POLICIES_DIR:-}
|
||||
METRICS_BEARER_TOKEN: ${METRICS_BEARER_TOKEN:-}
|
||||
MAX_OBJECT_BYTES: ${MAX_OBJECT_BYTES:-134217728}
|
||||
MAX_TOTAL_BYTES: ${MAX_TOTAL_BYTES:-2147483648}
|
||||
MAX_IN_FLIGHT_REQUESTS: ${MAX_IN_FLIGHT_REQUESTS:-16}
|
||||
HTTP_BACKLOG: ${HTTP_BACKLOG:-64}
|
||||
S3_VIRTUAL_HOST_SUFFIX: ${S3_VIRTUAL_HOST_SUFFIX:-}
|
||||
S3_PUBLIC_ENDPOINT: ${S3_PUBLIC_ENDPOINT:-}
|
||||
CORS_ALLOWED_ORIGINS: ${CORS_ALLOWED_ORIGINS:-}
|
||||
PUBLIC_REQUESTS_PER_SECOND: ${PUBLIC_REQUESTS_PER_SECOND:-0}
|
||||
PUBLIC_REQUEST_BURST: ${PUBLIC_REQUEST_BURST:-}
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
for command in docker openssl; do
|
||||
if ! command -v "$command" >/dev/null 2>&1; then
|
||||
echo "Missing prerequisite: $command" >&2
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
if ! docker compose version >/dev/null 2>&1; then
|
||||
echo "Docker Compose is required" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
compose=(docker compose -f compose.yaml -f compose.admin.yaml -f compose.credentials.yaml)
|
||||
|
||||
refuse_custom_storage() {
|
||||
echo "This installer cannot safely reproduce the existing storage configuration." >&2
|
||||
echo "Update using your existing Docker Compose files and encryption overlays instead." >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
compose_read() {
|
||||
S3_ACCESS_KEY="${S3_ACCESS_KEY:-ObjectStoreInstallCheck}" \
|
||||
S3_SECRET_KEY="${S3_SECRET_KEY:-ObjectStoreInstallCheckReadOnlyCredentials}" \
|
||||
"${compose[@]}" "$@"
|
||||
}
|
||||
|
||||
custom_configuration=$(compose_read config --environment | awk -F= '
|
||||
$1 == "ENCRYPTED_STORAGE_ROOT" || $1 == "ENCRYPTED_VOLUME_ID" || $1 == "COMPOSE_FILE" {
|
||||
sub(/^[^=]*=/, ""); if (length($0)) print "configured"
|
||||
}')
|
||||
[ -z "$custom_configuration" ] || refuse_custom_storage
|
||||
existing=$(compose_read ps --all --quiet objectstore)
|
||||
for container in $existing; do
|
||||
data_type=$(docker inspect --format '{{range .Mounts}}{{if eq .Destination "/data"}}{{.Type}}{{end}}{{end}}' "$container")
|
||||
[ "$data_type" = volume ] || refuse_custom_storage
|
||||
configured_files=$(docker inspect --format '{{index .Config.Labels "com.docker.compose.project.config_files"}}' "$container")
|
||||
[ -n "$configured_files" ] || refuse_custom_storage
|
||||
IFS=',' read -r -a files <<< "$configured_files"
|
||||
for file in "${files[@]}"; do
|
||||
case "$file" in
|
||||
"$PWD/compose.yaml"|"$PWD/compose.admin.yaml"|"$PWD/compose.credentials.yaml") ;;
|
||||
*) refuse_custom_storage ;;
|
||||
esac
|
||||
done
|
||||
if [ ! -f secrets/managed-master ]; then
|
||||
managed=$(docker inspect --format '{{range .Config.Env}}{{println .}}{{end}}' "$container" |
|
||||
awk -F= '$1 == "S3_MANAGED_KEYS_MASTER_FILE" {sub(/^[^=]*=/, ""); if (length($0)) print "configured"}')
|
||||
if [ -n "$managed" ]; then
|
||||
echo "Managed credentials are already configured, but secrets/managed-master is missing." >&2
|
||||
echo "Restore the original master key from backup; refusing to generate a replacement." >&2
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
done
|
||||
if [ -n "$existing" ] && [ ! -f .env ]; then
|
||||
echo "An existing deployment was found, but .env is missing." >&2
|
||||
echo "Restore its original configuration; refusing to generate a replacement root key." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
umask 077
|
||||
if [ ! -e .env ]; then
|
||||
access="OS$(openssl rand -hex 12 | tr '[:lower:]' '[:upper:]')"
|
||||
secret="$(openssl rand -hex 32)"
|
||||
cat > .env <<EOF
|
||||
S3_ACCESS_KEY=$access
|
||||
S3_SECRET_KEY=$secret
|
||||
S3_BUCKET=objects
|
||||
S3_REGION=us-east-1
|
||||
ADMIN_UI_BIND_IP=127.0.0.1
|
||||
ADMIN_UI_HOST_PORT=9001
|
||||
EOF
|
||||
echo "Created .env with a new root S3 key"
|
||||
else
|
||||
echo "Keeping existing .env"
|
||||
fi
|
||||
mkdir -p secrets
|
||||
chmod 700 secrets
|
||||
if [ ! -e secrets/admin-password ]; then
|
||||
openssl rand -hex 32 > secrets/admin-password
|
||||
echo "Created secrets/admin-password"
|
||||
fi
|
||||
if [ ! -e secrets/managed-master ]; then
|
||||
openssl rand -hex 32 > secrets/managed-master
|
||||
echo "Created secrets/managed-master"
|
||||
fi
|
||||
chmod 644 secrets/admin-password secrets/managed-master
|
||||
|
||||
"${compose[@]}" up -d --build --wait
|
||||
echo "S3 listener: $("${compose[@]}" port objectstore 9000)"
|
||||
echo "Admin console: http://$("${compose[@]}" port objectstore 9001)/_objectstore/admin/login"
|
||||
echo "Credentials are in .env and secrets/admin-password; keep secrets/managed-master for recovery."
|
||||
@@ -4,7 +4,7 @@ set -eu
|
||||
mode=${1:-}
|
||||
case "$mode" in
|
||||
single) directories='single' ;;
|
||||
cluster) directories='cluster/gateway-staging cluster/metadata cluster/metadata-recovery cluster/repair-staging cluster/gc-staging cluster/maintenance-staging cluster/node-a cluster/node-b cluster/node-c cluster/node-d' ;;
|
||||
cluster) directories='cluster/gateway-staging cluster/gateway-admin cluster/metadata cluster/metadata-recovery cluster/repair-staging cluster/gc-staging cluster/maintenance-staging cluster/node-a cluster/node-b cluster/node-c cluster/node-d' ;;
|
||||
*) echo 'Usage: prepare-encrypted-storage.sh single|cluster [environment-file]' >&2; exit 2 ;;
|
||||
esac
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -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")
|
||||
@@ -15,7 +15,7 @@ for setting in request response; do
|
||||
[ "${#value}" -le 5 ] || { echo "$setting timeout exceeds one day" >&2; exit 1; }
|
||||
if [ "$value" -gt 0 ]; then
|
||||
[ "$value" -le 86400 ] || { echo "$setting timeout exceeds one day" >&2; exit 1; }
|
||||
set -- "$@" "-Dsun.net.httpserver.$property=$((value * 1000))"
|
||||
set -- "$@" "-Dsun.net.httpserver.$property=$value"
|
||||
fi
|
||||
done
|
||||
|
||||
|
||||
@@ -148,6 +148,15 @@ assert "ListParts" in capabilities["operations"], capabilities
|
||||
assert capabilities["limits"]["maxObjectBytes"] > 0, capabilities
|
||||
assert headers.get_content_type() == "application/json", headers
|
||||
|
||||
ownership = b"<OwnershipControls><Rule><ObjectOwnership>ObjectWriter</ObjectOwnership></Rule></OwnershipControls>"
|
||||
status, _, _ = request("PUT", f"/{bucket}?ownershipControls", ownership)
|
||||
assert status == 200, status
|
||||
public_access = (b"<PublicAccessBlockConfiguration><BlockPublicAcls>false</BlockPublicAcls>"
|
||||
b"<IgnorePublicAcls>false</IgnorePublicAcls><BlockPublicPolicy>false</BlockPublicPolicy>"
|
||||
b"<RestrictPublicBuckets>false</RestrictPublicBuckets></PublicAccessBlockConfiguration>")
|
||||
status, _, _ = request("PUT", f"/{bucket}?publicAccessBlock", public_access)
|
||||
assert status == 200, status
|
||||
|
||||
key = f"/{bucket}/cluster-test/http.txt"
|
||||
body = b"HTTP gateway integration test"
|
||||
status, _, _ = request("PUT", key, body)
|
||||
|
||||
@@ -0,0 +1,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()
|
||||
@@ -0,0 +1,94 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
root=$(mktemp -d)
|
||||
trap 'rm -rf "$root"' EXIT
|
||||
mkdir -p "$root/project/scripts" "$root/bin"
|
||||
cp "$(dirname "$0")/install.sh" "$root/project/scripts/install.sh"
|
||||
cat > "$root/bin/docker" <<'EOF'
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
printf '%s\n' "$*" >> "$INSTALL_TEST_CALLS"
|
||||
if [ "$1" = inspect ]; then
|
||||
if [[ "$3" == *Mounts* ]]; then printf '%s\n' "${INSTALL_TEST_MOUNT:-volume}";
|
||||
elif [[ "$3" == *Config.Env* ]]; then printf '%s\n' "${INSTALL_TEST_MANAGED:-}";
|
||||
else printf '%s\n' "${INSTALL_TEST_FILES:-$PWD/compose.yaml}"; fi
|
||||
exit 0
|
||||
fi
|
||||
case "$*" in
|
||||
'compose version') ;;
|
||||
*'config --environment') printf '%s\n' "${INSTALL_TEST_ENV:-}" ;;
|
||||
*'ps --all --quiet objectstore') printf '%s\n' "${INSTALL_TEST_CONTAINER:-}" ;;
|
||||
*'up -d --build --wait') touch "$INSTALL_TEST_MUTATION" ;;
|
||||
*'port objectstore 9000') echo 127.0.0.1:9000 ;;
|
||||
*'port objectstore 9001') echo 127.0.0.1:9001 ;;
|
||||
*) echo "Unexpected Docker command: $*" >&2; exit 2 ;;
|
||||
esac
|
||||
EOF
|
||||
cat > "$root/bin/openssl" <<'EOF'
|
||||
#!/usr/bin/env bash
|
||||
touch "$INSTALL_TEST_MUTATION"
|
||||
printf '%064d\n' 1
|
||||
EOF
|
||||
chmod +x "$root/bin/docker" "$root/bin/openssl"
|
||||
export PATH="$root/bin:$PATH"
|
||||
export INSTALL_TEST_CALLS="$root/calls" INSTALL_TEST_MUTATION="$root/mutated"
|
||||
|
||||
refused() {
|
||||
rm -f "$INSTALL_TEST_MUTATION" "$INSTALL_TEST_CALLS"
|
||||
if bash "$root/project/scripts/install.sh" > "$root/output" 2>&1; then
|
||||
echo "Installer accepted unsafe storage configuration" >&2
|
||||
exit 1
|
||||
fi
|
||||
test ! -e "$INSTALL_TEST_MUTATION"
|
||||
test ! -e "$root/project/.env"
|
||||
test ! -e "$root/project/secrets"
|
||||
grep -q 'existing Docker Compose files' "$root/output"
|
||||
}
|
||||
|
||||
export INSTALL_TEST_ENV='ENCRYPTED_STORAGE_ROOT=/encrypted/objectstore'
|
||||
refused
|
||||
export INSTALL_TEST_ENV='ENCRYPTED_VOLUME_ID=0123456789abcdef0123456789abcdef'
|
||||
refused
|
||||
export INSTALL_TEST_ENV='COMPOSE_FILE=compose.yaml:compose.encrypted.yaml'
|
||||
refused
|
||||
export INSTALL_TEST_ENV='' INSTALL_TEST_CONTAINER=existing-container INSTALL_TEST_MOUNT=bind
|
||||
refused
|
||||
export INSTALL_TEST_MOUNT=volume INSTALL_TEST_FILES="$root/project/compose.yaml,$root/project/custom.yaml"
|
||||
refused
|
||||
|
||||
export INSTALL_TEST_FILES="$root/project/compose.yaml"
|
||||
export INSTALL_TEST_ENV=$'ENCRYPTED_STORAGE_ROOT=\nENCRYPTED_VOLUME_ID='
|
||||
export INSTALL_TEST_MANAGED='S3_MANAGED_KEYS_MASTER_FILE=/run/secrets/objectstore_managed_master'
|
||||
if bash "$root/project/scripts/install.sh" > "$root/output" 2>&1; then
|
||||
echo 'Installer replaced the missing master key' >&2
|
||||
exit 1
|
||||
fi
|
||||
test ! -e "$INSTALL_TEST_MUTATION"
|
||||
test ! -e "$root/project/.env"
|
||||
test ! -e "$root/project/secrets"
|
||||
grep -q 'Restore the original master key' "$root/output"
|
||||
|
||||
export INSTALL_TEST_MANAGED=''
|
||||
if bash "$root/project/scripts/install.sh" > "$root/output" 2>&1; then
|
||||
echo 'Installer replaced the missing root configuration' >&2
|
||||
exit 1
|
||||
fi
|
||||
test ! -e "$INSTALL_TEST_MUTATION"
|
||||
test ! -e "$root/project/.env"
|
||||
test ! -e "$root/project/secrets"
|
||||
grep -q 'Restore its original configuration' "$root/output"
|
||||
|
||||
mkdir "$root/project/secrets"
|
||||
printf '# ENCRYPTED_STORAGE_ROOT=/old-comment\nENCRYPTED_STORAGE_ROOT=\n' > "$root/project/.env"
|
||||
printf 'existing-admin-password\n' > "$root/project/secrets/admin-password"
|
||||
printf '%064d\n' 2 > "$root/project/secrets/managed-master"
|
||||
cp "$root/project/.env" "$root/original.env"
|
||||
cp "$root/project/secrets/admin-password" "$root/original-password"
|
||||
cp "$root/project/secrets/managed-master" "$root/original-master"
|
||||
bash "$root/project/scripts/install.sh" > "$root/output" 2>&1
|
||||
test -e "$INSTALL_TEST_MUTATION"
|
||||
cmp "$root/project/.env" "$root/original.env"
|
||||
cmp "$root/project/secrets/admin-password" "$root/original-password"
|
||||
cmp "$root/project/secrets/managed-master" "$root/original-master"
|
||||
echo 'Installer safety tests passed'
|
||||
@@ -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
|
||||
@@ -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()
|
||||
@@ -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()
|
||||
@@ -0,0 +1,21 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
test_dir=$(mktemp -d)
|
||||
trap 'rm -rf "$test_dir"' EXIT HUP INT TERM
|
||||
cat > "$test_dir/java" <<'EOF'
|
||||
#!/bin/sh
|
||||
printf '%s\n' "$@" > "$OBJECTSTORE_TEST_ARGS"
|
||||
EOF
|
||||
chmod +x "$test_dir/java"
|
||||
OBJECTSTORE_TEST_ARGS="$test_dir/args" PATH="$test_dir:$PATH" \
|
||||
OBJECTSTORE_REQUEST_TIMEOUT_SECONDS=300 OBJECTSTORE_RESPONSE_TIMEOUT_SECONDS=45 \
|
||||
sh scripts/start-server.sh
|
||||
grep -Fx -- '-Dsun.net.httpserver.maxReqTime=300' "$test_dir/args" >/dev/null
|
||||
grep -Fx -- '-Dsun.net.httpserver.maxRspTime=45' "$test_dir/args" >/dev/null
|
||||
if OBJECTSTORE_TEST_ARGS="$test_dir/args" PATH="$test_dir:$PATH" \
|
||||
OBJECTSTORE_REQUEST_TIMEOUT_SECONDS=86401 sh scripts/start-server.sh 2>/dev/null; then
|
||||
echo 'Oversized request timeout was accepted' >&2
|
||||
exit 1
|
||||
fi
|
||||
echo 'Server launcher timeout tests passed'
|
||||
@@ -1,15 +1,28 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
sh scripts/test-start-server.sh
|
||||
bash scripts/test-install.sh
|
||||
mkdir -p out/classes
|
||||
javac --release 21 --add-modules jdk.httpserver,java.net.http -cp lib/hash4j-0.30.0.jar -d out/classes \
|
||||
src/cloud/lunarsky/store/*.java test/cloud/lunarsky/store/*.java
|
||||
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
|
||||
java --add-modules jdk.httpserver -cp out/classes:lib/hash4j-0.30.0.jar cloud.lunarsky.store.ConcurrencyTest
|
||||
java --add-modules jdk.httpserver,java.net.http -cp out/classes:lib/hash4j-0.30.0.jar cloud.lunarsky.store.HttpTest
|
||||
java --add-modules jdk.httpserver,java.net.http -cp out/classes:lib/hash4j-0.30.0.jar cloud.lunarsky.store.ClientLimitsTest
|
||||
java --add-modules jdk.httpserver,java.net.http -cp out/classes:lib/hash4j-0.30.0.jar cloud.lunarsky.store.AdminConsoleTest
|
||||
java --add-modules jdk.httpserver,java.net.http -cp out/classes:lib/hash4j-0.30.0.jar cloud.lunarsky.store.RequestCoordinationTest
|
||||
java -cp out/classes:lib/hash4j-0.30.0.jar cloud.lunarsky.store.RequestDiagnosticsTest
|
||||
java -cp out/classes:lib/hash4j-0.30.0.jar cloud.lunarsky.store.BucketActivityTest
|
||||
java --add-modules jdk.httpserver -cp out/classes:lib/hash4j-0.30.0.jar cloud.lunarsky.store.AdminOperationsTest
|
||||
java --add-modules jdk.httpserver -cp out/classes:lib/hash4j-0.30.0.jar cloud.lunarsky.store.AdminBulkJobsTest
|
||||
java --add-modules jdk.httpserver,java.net.http -cp out/classes:lib/hash4j-0.30.0.jar cloud.lunarsky.store.FeatureTest
|
||||
java -cp out/classes:lib/hash4j-0.30.0.jar cloud.lunarsky.store.EncryptedVolumeTest
|
||||
java --add-modules jdk.httpserver,java.net.http -cp out/classes:lib/hash4j-0.30.0.jar cloud.lunarsky.store.NodeHttpTest
|
||||
java --add-modules jdk.httpserver,java.net.http -cp out/classes:lib/hash4j-0.30.0.jar cloud.lunarsky.store.ClusterNodeTest
|
||||
java --add-modules jdk.httpserver,java.net.http -cp out/classes:lib/hash4j-0.30.0.jar cloud.lunarsky.store.ClusterTlsTest
|
||||
java -cp out/classes:lib/hash4j-0.30.0.jar cloud.lunarsky.store.CliTest
|
||||
|
||||
@@ -65,6 +65,8 @@ final class Acl {
|
||||
principal = entry.substring(4, entry.length() - 1);
|
||||
else if (entry.startsWith("uri=\"") && entry.endsWith("\""))
|
||||
principal = entry.substring(5, entry.length() - 1);
|
||||
else if (entry.startsWith("emailAddress=\""))
|
||||
throw new StoreException(405, "MethodNotAllowed", "Email ACL grantees are no longer supported");
|
||||
else throw new StoreException(400, "InvalidArgument", "Invalid ACL grant");
|
||||
if (!identities.contains(principal) && !principal.equals(ALL_USERS) &&
|
||||
!principal.equals(AUTHENTICATED_USERS))
|
||||
@@ -122,6 +124,8 @@ final class Acl {
|
||||
String principal = switch (type) {
|
||||
case "CanonicalUser" -> text(grantee, "ID");
|
||||
case "Group" -> text(grantee, "URI");
|
||||
case "AmazonCustomerByEmail" -> throw new StoreException(405, "MethodNotAllowed",
|
||||
"Email ACL grantees are no longer supported");
|
||||
default -> throw new IllegalArgumentException();
|
||||
};
|
||||
Integer permission = PERMISSIONS.get(text(grant, "Permission"));
|
||||
@@ -130,7 +134,8 @@ final class Acl {
|
||||
}
|
||||
grants.remove(owner);
|
||||
return validate(encoded(grants), identities);
|
||||
} catch (Exception error) {
|
||||
} catch (StoreException error) { throw error; }
|
||||
catch (Exception error) {
|
||||
throw new StoreException(400, "MalformedACLError", "Invalid access control policy");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import com.sun.net.httpserver.Headers;
|
||||
import java.io.IOException;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
final class AdminAccessCheck {
|
||||
record Result(boolean allowed, String stage, String explanation) { }
|
||||
|
||||
private final ObjectStorage store;
|
||||
private final S3Access access;
|
||||
private final KeyScopes scopes;
|
||||
private final Set<String> identities;
|
||||
private final ManagedCredentials managed;
|
||||
|
||||
AdminAccessCheck(ObjectStorage store, S3Access access, KeyScopes scopes,
|
||||
Set<String> identities, ManagedCredentials managed) {
|
||||
this.store = store;
|
||||
this.access = access;
|
||||
this.scopes = scopes;
|
||||
this.identities = identities;
|
||||
this.managed = managed;
|
||||
}
|
||||
|
||||
Result check(String principal, String operation, String bucket, String key) throws IOException {
|
||||
if (principal == null || !identities.contains(principal))
|
||||
return new Result(false, "Authentication", "Access key is unknown or disabled");
|
||||
validateRequest(operation, bucket, key);
|
||||
try {
|
||||
checkScope(principal, operation, bucket, key);
|
||||
} catch (StoreException denied) {
|
||||
if (denied.status != 403) throw denied;
|
||||
return new Result(false, "Key scope", "Key scope does not allow this bucket, prefix, or operation");
|
||||
}
|
||||
return inspectAccess(principal, operation, bucket, key);
|
||||
}
|
||||
|
||||
private static void validateRequest(String operation, String bucket, String key) {
|
||||
if (operation == null || !Set.of("list", "read", "write", "delete").contains(operation))
|
||||
throw new StoreException(400, "InvalidArgument", "Choose a supported operation");
|
||||
if (bucket == null || !bucket.matches("[a-z0-9][a-z0-9-]{1,61}[a-z0-9]"))
|
||||
throw new StoreException(400, "InvalidArgument", "Choose a valid bucket");
|
||||
if (key != null && key.getBytes(java.nio.charset.StandardCharsets.UTF_8).length > 1024)
|
||||
throw new StoreException(400, "InvalidArgument", "Object key or prefix is too long");
|
||||
if (!operation.equals("list") && (key == null || key.isEmpty() || key.length() > 1024))
|
||||
throw new StoreException(400, "InvalidArgument", "Enter an object key");
|
||||
}
|
||||
|
||||
private void checkScope(String principal, String operation, String bucket, String key) {
|
||||
if (operation.equals("list")) {
|
||||
Map<String, String> query = Map.of("list-type", "2", "prefix", key == null ? "" : key);
|
||||
if (managed != null && managed.contains(principal))
|
||||
managed.checkBucket(principal, bucket, "GET", query);
|
||||
else scopes.checkBucket(principal, bucket, "GET", query);
|
||||
return;
|
||||
}
|
||||
String method = switch (operation) {
|
||||
case "write" -> "PUT";
|
||||
case "delete" -> "DELETE";
|
||||
default -> "GET";
|
||||
};
|
||||
if (managed != null && managed.contains(principal))
|
||||
managed.checkObject(principal, bucket, key, method, Map.of(), new Headers());
|
||||
else scopes.checkObject(principal, bucket, key, method, Map.of(), new Headers());
|
||||
}
|
||||
|
||||
private Result inspectAccess(String principal, String operation, String bucket, String key)
|
||||
throws IOException {
|
||||
return switch (operation) {
|
||||
case "list" -> policyResult(access.inspectBucket(bucket, principal));
|
||||
case "read" -> inspectRead(principal, bucket, key);
|
||||
case "delete" -> policyResult(access.inspectWrite(bucket, key, principal, "s3:DeleteObject"));
|
||||
default -> policyResult(access.inspectWrite(bucket, key, principal, "s3:PutObject"));
|
||||
};
|
||||
}
|
||||
|
||||
private Result inspectRead(String principal, String bucket, String key) throws IOException {
|
||||
ObjectStorage.ListPage page = store.list(bucket, key, "", 1, null);
|
||||
if (page.objects().isEmpty() || !key.equals(page.objects().get(0).key()))
|
||||
return new Result(false, "Object", "Current object does not exist");
|
||||
return policyResult(access.inspectObject(bucket, key, page.objects().get(0).metadata(), principal));
|
||||
}
|
||||
|
||||
private static Result policyResult(S3Access.Decision decision) {
|
||||
return new Result(decision.allowed(), "Bucket and identity policy", decision.reason());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,240 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import com.sun.net.httpserver.Headers;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
final class AdminActions {
|
||||
private AdminActions() { }
|
||||
|
||||
static String apply(ObjectStorage store, String action, Map<String, String> form,
|
||||
Set<String> identities, ManagedCredentials managed) throws IOException {
|
||||
String bucket = required(form, "bucket", 63);
|
||||
return switch (action) {
|
||||
case "create-bucket" -> createBucket(store, bucket, form);
|
||||
case "rename-bucket" -> renameBucket(store, bucket, form, managed);
|
||||
case "delete-bucket" -> deleteBucket(store, bucket, form);
|
||||
default -> updateBucket(store, bucket, action, form, identities);
|
||||
};
|
||||
}
|
||||
|
||||
private static String createBucket(ObjectStorage store, String bucket, Map<String, String> form)
|
||||
throws IOException {
|
||||
boolean wizard = "wizard".equals(form.get("setup"));
|
||||
String versioning = form.getOrDefault("versioning", "off");
|
||||
if (wizard && !versioning.equals("off") && !versioning.equals("enabled"))
|
||||
invalid("Invalid initial versioning setting");
|
||||
ObjectStorage.ObjectOwnership ownership = wizard ?
|
||||
BucketSecurity.ownership(form.getOrDefault("ownership", "BucketOwnerEnforced")) :
|
||||
ObjectStorage.ObjectOwnership.BUCKET_OWNER_ENFORCED;
|
||||
ObjectStorage.PublicAccessBlock publicBlock = wizard ? publicAccessBlock(form) :
|
||||
ObjectStorage.PublicAccessBlock.secure();
|
||||
if (wizard && !publicBlock.equals(ObjectStorage.PublicAccessBlock.secure()) &&
|
||||
!"yes".equals(form.get("acknowledgePublic")))
|
||||
invalid("Confirm that relaxing public access controls may expose this bucket");
|
||||
store.createBucket(bucket);
|
||||
if (wizard) configureCreatedBucket(store, bucket, versioning, ownership, publicBlock);
|
||||
return AdminBrowser.bucketUrl(bucket, "", null);
|
||||
}
|
||||
|
||||
private static void configureCreatedBucket(ObjectStorage store, String bucket, String versioning,
|
||||
ObjectStorage.ObjectOwnership ownership, ObjectStorage.PublicAccessBlock publicBlock)
|
||||
throws IOException {
|
||||
if (versioning.equals("enabled"))
|
||||
store.setVersioning(bucket, ObjectStorage.VersioningState.ENABLED);
|
||||
if (ownership != ObjectStorage.ObjectOwnership.BUCKET_OWNER_ENFORCED)
|
||||
store.setBucketOwnership(bucket, ownership);
|
||||
if (!publicBlock.equals(ObjectStorage.PublicAccessBlock.secure()))
|
||||
store.setPublicAccessBlock(bucket, publicBlock);
|
||||
}
|
||||
|
||||
private static String renameBucket(ObjectStorage store, String bucket, Map<String, String> form,
|
||||
ManagedCredentials managed) throws IOException {
|
||||
confirm(form, bucket);
|
||||
String newName = required(form, "newName", 63);
|
||||
if (managed != null && managed.list().stream().anyMatch(key -> key.bucket().equals(bucket)))
|
||||
throw new StoreException(409, "BucketHasScopedKeys",
|
||||
"Move or remove scoped access keys for this bucket before renaming it");
|
||||
store.renameBucket(bucket, newName);
|
||||
return AdminBrowser.bucketUrl(newName, "", null);
|
||||
}
|
||||
|
||||
private static String deleteBucket(ObjectStorage store, String bucket, Map<String, String> form)
|
||||
throws IOException {
|
||||
confirm(form, bucket);
|
||||
store.deleteBucket(bucket);
|
||||
return AdminConsole.PATH + "/buckets";
|
||||
}
|
||||
|
||||
private static String updateBucket(ObjectStorage store, String bucket, String action,
|
||||
Map<String, String> form, Set<String> identities) throws IOException {
|
||||
ObjectStorage.Bucket current = store.bucket(bucket);
|
||||
switch (action) {
|
||||
case "delete-object" -> { return deleteObject(store, bucket, form); }
|
||||
case "versioning" -> setVersioning(store, bucket, form);
|
||||
case "ownership" -> setOwnership(store, bucket, form);
|
||||
case "public-access" -> setPublicAccess(store, bucket, current, form);
|
||||
case "policy" -> setPolicy(store, bucket, current, form);
|
||||
case "bucket-grant" -> setBucketGrant(store, bucket, current, form, identities);
|
||||
case "object-grant" -> { return setObjectGrant(store, bucket, current, form, identities); }
|
||||
case "object-tag" -> { return setObjectTag(store, bucket, form); }
|
||||
default -> invalid("Unknown admin action");
|
||||
}
|
||||
return AdminBrowser.bucketUrl(bucket, "", null) + "#settings";
|
||||
}
|
||||
|
||||
private static String deleteObject(ObjectStorage store, String bucket, Map<String, String> form)
|
||||
throws IOException {
|
||||
String key = required(form, "key", 1024);
|
||||
if (!key.equals(form.get("confirm"))) invalid("Type the object key to confirm");
|
||||
String version = version(form);
|
||||
if (version != null && !version.equals(form.get("confirmVersion")))
|
||||
invalid("Type the version ID to confirm permanent deletion");
|
||||
store.delete(bucket, key, version);
|
||||
return AdminBrowser.bucketUrl(bucket, key.contains("/") ?
|
||||
key.substring(0, key.lastIndexOf('/') + 1) : "", null);
|
||||
}
|
||||
|
||||
private static void setVersioning(ObjectStorage store, String bucket, Map<String, String> form)
|
||||
throws IOException {
|
||||
String state = required(form, "state", 16);
|
||||
if (!state.equals("ENABLED") && !state.equals("SUSPENDED")) invalid("Invalid versioning state");
|
||||
store.setVersioning(bucket, ObjectStorage.VersioningState.valueOf(state));
|
||||
}
|
||||
|
||||
private static void setOwnership(ObjectStorage store, String bucket, Map<String, String> form)
|
||||
throws IOException {
|
||||
confirm(form, bucket);
|
||||
String value = required(form, "ownership", 32);
|
||||
store.setBucketOwnership(bucket, BucketSecurity.ownership(value));
|
||||
}
|
||||
|
||||
private static void setPublicAccess(ObjectStorage store, String bucket, ObjectStorage.Bucket current,
|
||||
Map<String, String> form) throws IOException {
|
||||
ObjectStorage.PublicAccessBlock block = publicAccessBlock(form);
|
||||
ObjectStorage.PublicAccessBlock previous = current.publicAccessBlock();
|
||||
if (previous.blockPublicAcls() && !block.blockPublicAcls() ||
|
||||
previous.ignorePublicAcls() && !block.ignorePublicAcls() ||
|
||||
previous.blockPublicPolicy() && !block.blockPublicPolicy() ||
|
||||
previous.restrictPublicBuckets() && !block.restrictPublicBuckets()) confirm(form, bucket);
|
||||
store.setPublicAccessBlock(bucket, block);
|
||||
}
|
||||
|
||||
private static ObjectStorage.PublicAccessBlock publicAccessBlock(Map<String, String> form) {
|
||||
return new ObjectStorage.PublicAccessBlock(
|
||||
form.containsKey("blockPublicAcls"), form.containsKey("ignorePublicAcls"),
|
||||
form.containsKey("blockPublicPolicy"), form.containsKey("restrictPublicBuckets"));
|
||||
}
|
||||
|
||||
private static void setPolicy(ObjectStorage store, String bucket, ObjectStorage.Bucket current,
|
||||
Map<String, String> form) throws IOException {
|
||||
String policy = form.getOrDefault("policy", "").trim();
|
||||
if (policy.getBytes(StandardCharsets.UTF_8).length > 20480) invalid("Policy is too large");
|
||||
if (!policy.isEmpty()) {
|
||||
BucketPolicy parsed = BucketPolicy.parse(policy, bucket);
|
||||
if (current.publicAccessBlock().blockPublicPolicy() && parsed.publicAllow())
|
||||
throw new StoreException(403, "AccessDenied", "Public bucket policies are blocked");
|
||||
if (parsed.publicAllow()) confirm(form, bucket);
|
||||
}
|
||||
store.setBucketPolicy(bucket, policy.isEmpty() ? null : policy);
|
||||
}
|
||||
|
||||
private static void setBucketGrant(ObjectStorage store, String bucket, ObjectStorage.Bucket current,
|
||||
Map<String, String> form, Set<String> identities) throws IOException {
|
||||
Map<String, String> acl = updateGrants(current.acl(), form, identities);
|
||||
if (newPublicGrant(current.acl(), acl)) confirm(form, bucket);
|
||||
BucketSecurity.checkAcl(current, new Headers(), acl, true);
|
||||
store.setBucketAcl(bucket, acl);
|
||||
}
|
||||
|
||||
private static String setObjectGrant(ObjectStorage store, String bucket, ObjectStorage.Bucket current,
|
||||
Map<String, String> form, Set<String> identities) throws IOException {
|
||||
String key = required(form, "key", 1024);
|
||||
String version = version(form);
|
||||
ObjectStorage.Metadata metadata;
|
||||
try (ObjectStorage.OpenObject opened = store.open(bucket, key, version)) {
|
||||
metadata = opened.metadata();
|
||||
}
|
||||
Map<String, String> acl = updateGrants(metadata.acl(), form, identities);
|
||||
if (newPublicGrant(metadata.acl(), acl)) confirm(form, bucket);
|
||||
BucketSecurity.checkAcl(current, new Headers(), acl, true);
|
||||
store.setObjectAcl(bucket, key, version, acl);
|
||||
return objectUrl(bucket, key, version);
|
||||
}
|
||||
|
||||
private static String setObjectTag(ObjectStorage store, String bucket, Map<String, String> form)
|
||||
throws IOException {
|
||||
String key = required(form, "key", 1024);
|
||||
String tag = required(form, "tag", 128);
|
||||
String version = version(form);
|
||||
Map<String, String> tags = new HashMap<>(store.tags(bucket, key, version));
|
||||
if ("remove".equals(form.get("operation"))) tags.remove(tag);
|
||||
else if ("add".equals(form.get("operation"))) {
|
||||
String value = form.get("value");
|
||||
if (value == null || value.length() > 256) invalid("Invalid value");
|
||||
tags.put(tag, value);
|
||||
} else invalid("Invalid tag operation");
|
||||
ObjectAttributes.validateTags(tags);
|
||||
store.setTags(bucket, key, version, Map.copyOf(tags));
|
||||
return objectUrl(bucket, key, version);
|
||||
}
|
||||
|
||||
private static String version(Map<String, String> form) {
|
||||
String version = form.getOrDefault("version", "");
|
||||
if (version.length() > 256) invalid("Invalid object version");
|
||||
return version.isEmpty() ? null : version;
|
||||
}
|
||||
|
||||
private static String objectUrl(String bucket, String key, String version) {
|
||||
return AdminConsole.PATH + "/object?bucket=" + AdminBrowser.encoded(bucket) +
|
||||
"&key=" + AdminBrowser.encoded(key) +
|
||||
(version == null ? "" : "&version=" + AdminBrowser.encoded(version));
|
||||
}
|
||||
|
||||
private static Map<String, String> updateGrants(Map<String, String> current,
|
||||
Map<String, String> form, Set<String> identities) {
|
||||
String principal = required(form, "principal", 128);
|
||||
if (principal.equals("AllUsers")) principal = Acl.ALL_USERS;
|
||||
if (principal.equals("AuthenticatedUsers")) principal = Acl.AUTHENTICATED_USERS;
|
||||
Map<String, String> updated = new HashMap<>(current);
|
||||
if ("remove".equals(form.get("operation"))) updated.remove(principal);
|
||||
else if ("add".equals(form.get("operation"))) {
|
||||
int bits = switch (required(form, "permission", 16)) {
|
||||
case "READ" -> Acl.READ;
|
||||
case "WRITE" -> Acl.WRITE;
|
||||
case "READ_ACP" -> Acl.READ_ACP;
|
||||
case "WRITE_ACP" -> Acl.WRITE_ACP;
|
||||
case "FULL_CONTROL" -> Acl.FULL_CONTROL;
|
||||
default -> throw new StoreException(400, "InvalidArgument", "Invalid ACL permission");
|
||||
};
|
||||
int existing = Integer.parseInt(updated.getOrDefault(principal, "0"));
|
||||
updated.put(principal, Integer.toString(existing | bits));
|
||||
} else invalid("Invalid grant operation");
|
||||
return Acl.validate(updated, identities);
|
||||
}
|
||||
|
||||
private static boolean newPublicGrant(Map<String, String> before, Map<String, String> after) {
|
||||
return java.util.List.of(Acl.ALL_USERS, Acl.AUTHENTICATED_USERS).stream().anyMatch(
|
||||
principal -> !before.getOrDefault(principal, "0").equals(after.getOrDefault(principal, "0")) &&
|
||||
Integer.parseInt(after.getOrDefault(principal, "0")) != 0);
|
||||
}
|
||||
|
||||
private static String required(Map<String, String> form, String field, int maxLength) {
|
||||
String value = form.get(field);
|
||||
if (value == null || value.isBlank() || value.length() > maxLength || value.indexOf('\0') >= 0)
|
||||
throw new StoreException(400, "InvalidArgument", "Invalid " + field);
|
||||
return value;
|
||||
}
|
||||
|
||||
private static void confirm(Map<String, String> form, String bucket) {
|
||||
if (!bucket.equals(form.get("confirm")))
|
||||
throw new StoreException(400, "InvalidArgument", "Type the bucket name to confirm");
|
||||
}
|
||||
|
||||
private static void invalid(String message) {
|
||||
throw new StoreException(400, "InvalidArgument", message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import com.sun.net.httpserver.HttpExchange;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import static cloud.lunarsky.store.AdminConsole.PATH;
|
||||
import static cloud.lunarsky.store.AdminHttp.*;
|
||||
|
||||
final class AdminAssets {
|
||||
private record Asset(byte[] content, String type, boolean authenticated) { }
|
||||
|
||||
private final Map<String, Asset> assets;
|
||||
|
||||
AdminAssets() throws IOException {
|
||||
Map<String, Asset> loaded = new HashMap<>();
|
||||
add(loaded, "/style.css", "admin.css", "text/css", false);
|
||||
add(loaded, "/logo.png", "objectstore-logo.png", "image/png", false);
|
||||
add(loaded, "/workspace.js", "workspace.js", "text/javascript", false);
|
||||
add(loaded, "/biscuit.js", "biscuit.js", "text/javascript", true);
|
||||
add(loaded, "/performance.js", "performance.js", "text/javascript", true);
|
||||
for (String icon : AdminLayout.ICONS) {
|
||||
add(loaded, "/icons/" + icon + ".svg", "icons/" + icon + ".svg", "image/svg+xml", true);
|
||||
}
|
||||
assets = Map.copyOf(loaded);
|
||||
}
|
||||
|
||||
boolean handle(HttpExchange exchange, boolean signedIn) throws IOException {
|
||||
String path = exchange.getRequestURI().getRawPath();
|
||||
Asset asset = assets.get(path);
|
||||
boolean icon = path.startsWith(PATH + "/icons/") && path.endsWith(".svg");
|
||||
if (asset == null && !icon) return false;
|
||||
if (!exchange.getRequestMethod().equals("GET")) {
|
||||
methodNotAllowed(exchange, "GET");
|
||||
} else if ((icon || asset.authenticated()) && !signedIn) {
|
||||
redirect(exchange, PATH + "/login");
|
||||
} else if (asset == null) {
|
||||
send(exchange, 404, "Not found", "text/plain; charset=utf-8");
|
||||
} else {
|
||||
exchange.getResponseHeaders().set("Content-Type", asset.type());
|
||||
exchange.sendResponseHeaders(200, asset.content().length);
|
||||
exchange.getResponseBody().write(asset.content());
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static void add(Map<String, Asset> assets, String route, String file, String type,
|
||||
boolean authenticated) throws IOException {
|
||||
String contentType = type.equals("image/png") ? type : type + "; charset=" + StandardCharsets.UTF_8;
|
||||
assets.put(PATH + route, new Asset(Files.readAllBytes(Path.of("admin-ui", file)),
|
||||
contentType, authenticated));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
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.nio.file.attribute.PosixFilePermission;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
final class AdminAuditTrail {
|
||||
private static final long MAX_BYTES = 4L * 1024 * 1024;
|
||||
private final Path file;
|
||||
private final Path previous;
|
||||
|
||||
record Entry(long timeMillis, String action, String target, String result, String peer) { }
|
||||
|
||||
AdminAuditTrail(Path dataDirectory) throws IOException {
|
||||
Files.createDirectories(dataDirectory);
|
||||
file = dataDirectory.resolve("admin-audit.tsv");
|
||||
previous = dataDirectory.resolve("admin-audit.previous.tsv");
|
||||
if (!Files.exists(file)) Files.createFile(file);
|
||||
privateFile(file);
|
||||
}
|
||||
|
||||
synchronized void record(String action, String target, String result, String peer) throws IOException {
|
||||
String line = System.currentTimeMillis() + "\t" + safe(action, 48) + "\t" +
|
||||
safe(target, 256) + "\t" + safe(result, 48) + "\t" + safe(peer, 64) + "\n";
|
||||
byte[] bytes = line.getBytes(StandardCharsets.UTF_8);
|
||||
if (Files.size(file) + bytes.length > MAX_BYTES) {
|
||||
Files.move(file, previous, StandardCopyOption.REPLACE_EXISTING);
|
||||
Files.createFile(file);
|
||||
privateFile(previous);
|
||||
privateFile(file);
|
||||
}
|
||||
try (FileChannel channel = FileChannel.open(file, StandardOpenOption.WRITE, StandardOpenOption.APPEND)) {
|
||||
ByteBuffer buffer = ByteBuffer.wrap(bytes);
|
||||
while (buffer.hasRemaining()) channel.write(buffer);
|
||||
channel.force(true);
|
||||
}
|
||||
}
|
||||
|
||||
synchronized List<Entry> recent(int limit) throws IOException {
|
||||
int wanted = Math.min(200, Math.max(0, limit));
|
||||
List<Entry> found = new ArrayList<>();
|
||||
for (Path path : List.of(file, previous)) {
|
||||
if (!Files.exists(path)) continue;
|
||||
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
|
||||
for (int i = lines.size() - 1; i >= 0 && found.size() < wanted; i--) {
|
||||
String[] fields = lines.get(i).split("\t", -1);
|
||||
if (fields.length != 5) continue;
|
||||
try {
|
||||
found.add(new Entry(Long.parseLong(fields[0]), fields[1], fields[2],
|
||||
fields[3], fields[4]));
|
||||
} catch (NumberFormatException ignored) { }
|
||||
}
|
||||
if (found.size() >= wanted) break;
|
||||
}
|
||||
return List.copyOf(found);
|
||||
}
|
||||
|
||||
private static String safe(String input, int limit) {
|
||||
if (input == null) return "—";
|
||||
String value = input.replace('\t', ' ').replace('\n', ' ').replace('\r', ' ');
|
||||
return value.length() <= limit ? value : value.substring(0, limit);
|
||||
}
|
||||
|
||||
private static void privateFile(Path path) throws IOException {
|
||||
try {
|
||||
Files.setPosixFilePermissions(path, Set.of(PosixFilePermission.OWNER_READ,
|
||||
PosixFilePermission.OWNER_WRITE));
|
||||
} catch (UnsupportedOperationException ignored) { }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import com.sun.net.httpserver.HttpExchange;
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.SecureRandom;
|
||||
import java.time.Duration;
|
||||
import java.util.Base64;
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import static cloud.lunarsky.store.AdminConsole.PATH;
|
||||
|
||||
final class AdminAuthentication {
|
||||
private static final long SESSION_MILLIS = Duration.ofMinutes(30).toMillis();
|
||||
private static final long ATTEMPT_WINDOW_MILLIS = Duration.ofMinutes(5).toMillis();
|
||||
private static final int MAX_SESSIONS = 128;
|
||||
private static final int MAX_CLIENTS = 1024;
|
||||
private final byte[] passwordHash;
|
||||
private final URI publicOrigin;
|
||||
private final SecureRandom random = new SecureRandom();
|
||||
private final LinkedHashMap<String, Session> sessions = new LinkedHashMap<>();
|
||||
private final LinkedHashMap<String, Long> loginTokens = new LinkedHashMap<>();
|
||||
private final LinkedHashMap<String, Attempt> attempts = new LinkedHashMap<>();
|
||||
|
||||
private record Attempt(long started, int failures) { }
|
||||
record Session(long expires, String csrf) { }
|
||||
|
||||
private AdminAuthentication(byte[] passwordHash, URI publicOrigin) {
|
||||
this.passwordHash = passwordHash;
|
||||
this.publicOrigin = publicOrigin;
|
||||
}
|
||||
|
||||
static AdminAuthentication fromEnvironment(Map<String, String> env) throws IOException {
|
||||
return new AdminAuthentication(passwordHash(env.get("ADMIN_UI_PASSWORD_FILE")), configuredOrigin(env));
|
||||
}
|
||||
|
||||
private static byte[] passwordHash(String file) throws IOException {
|
||||
if (file == null || file.isBlank())
|
||||
throw new IllegalArgumentException("ADMIN_UI_PASSWORD_FILE is required when the admin UI is enabled");
|
||||
byte[] password = Files.readAllBytes(Path.of(file));
|
||||
int length = password.length;
|
||||
if (length > 0 && password[length - 1] == '\n') length--;
|
||||
if (length > 0 && password[length - 1] == '\r') length--;
|
||||
if (length < 16 || length > 1024)
|
||||
throw new IllegalArgumentException("Admin password must contain 16 to 1024 bytes");
|
||||
for (int i = 0; i < length; i++) {
|
||||
if (password[i] == '\n' || password[i] == '\r' || password[i] == 0)
|
||||
throw new IllegalArgumentException("Admin password must be a single line");
|
||||
}
|
||||
byte[] trimmed = java.util.Arrays.copyOf(password, length);
|
||||
byte[] hash = SigV4.hash(trimmed);
|
||||
java.util.Arrays.fill(trimmed, (byte) 0);
|
||||
java.util.Arrays.fill(password, (byte) 0);
|
||||
return hash;
|
||||
}
|
||||
|
||||
private static URI configuredOrigin(Map<String, String> env) {
|
||||
String privateOrigin = env.get("ADMIN_UI_PRIVATE_ORIGIN");
|
||||
String publicOrigin = env.get("ADMIN_UI_ORIGIN");
|
||||
if (privateOrigin != null && !privateOrigin.isBlank() &&
|
||||
publicOrigin != null && !publicOrigin.isBlank())
|
||||
throw new IllegalArgumentException("Configure only one admin UI origin");
|
||||
String configured = privateOrigin != null && !privateOrigin.isBlank() ? privateOrigin : publicOrigin;
|
||||
URI origin = null;
|
||||
if (configured != null && !configured.isBlank()) {
|
||||
try { origin = URI.create(configured); }
|
||||
catch (IllegalArgumentException error) {
|
||||
throw new IllegalArgumentException("Invalid ADMIN_UI_ORIGIN", error);
|
||||
}
|
||||
boolean privateHttp = privateOrigin != null && !privateOrigin.isBlank();
|
||||
if (!(privateHttp ? "http".equals(origin.getScheme()) &&
|
||||
privateIpv4(origin.getHost()) && origin.getPort() > 0 && origin.getPort() <= 65535 :
|
||||
"https".equals(origin.getScheme()) && origin.getHost() != null) ||
|
||||
origin.getUserInfo() != null || origin.getRawQuery() != null || origin.getRawFragment() != null ||
|
||||
!(origin.getRawPath().isEmpty() || origin.getRawPath().equals("/")))
|
||||
throw new IllegalArgumentException(privateHttp ?
|
||||
"ADMIN_UI_PRIVATE_ORIGIN must be an HTTP origin with a private IPv4 address and port" :
|
||||
"ADMIN_UI_ORIGIN must be an HTTPS origin");
|
||||
origin = URI.create(origin.toString().replaceFirst("/$", ""));
|
||||
}
|
||||
return origin;
|
||||
}
|
||||
|
||||
boolean matchesPassword(String password) {
|
||||
byte[] candidate = SigV4.hash((password == null ? "" : password).getBytes(StandardCharsets.UTF_8));
|
||||
return MessageDigest.isEqual(candidate, passwordHash);
|
||||
}
|
||||
|
||||
synchronized String signIn(String client) {
|
||||
String token = randomToken();
|
||||
attempts.remove(client);
|
||||
long now = System.currentTimeMillis();
|
||||
sessions.entrySet().removeIf(entry -> entry.getValue().expires() <= now);
|
||||
if (sessions.size() >= MAX_SESSIONS) sessions.remove(sessions.keySet().iterator().next());
|
||||
sessions.put(token, new Session(now + SESSION_MILLIS, randomToken()));
|
||||
return token;
|
||||
}
|
||||
|
||||
synchronized void signOut(HttpExchange exchange) {
|
||||
sessions.remove(sessionCookie(exchange));
|
||||
}
|
||||
|
||||
synchronized String issueLoginToken() {
|
||||
long now = System.currentTimeMillis();
|
||||
loginTokens.entrySet().removeIf(entry -> entry.getValue() <= now);
|
||||
if (loginTokens.size() >= MAX_SESSIONS) loginTokens.remove(loginTokens.keySet().iterator().next());
|
||||
String token = randomToken();
|
||||
loginTokens.put(token, now + Duration.ofMinutes(10).toMillis());
|
||||
return token;
|
||||
}
|
||||
|
||||
synchronized boolean consumeLoginToken(String token) {
|
||||
if (token == null || !token.matches("[A-Za-z0-9_-]{43}")) return false;
|
||||
Long until = loginTokens.remove(token);
|
||||
return until != null && until > System.currentTimeMillis();
|
||||
}
|
||||
|
||||
String randomToken() {
|
||||
byte[] value = new byte[32];
|
||||
random.nextBytes(value);
|
||||
return Base64.getUrlEncoder().withoutPadding().encodeToString(value);
|
||||
}
|
||||
|
||||
synchronized boolean throttled(String client) {
|
||||
Attempt attempt = attempts.get(client);
|
||||
return attempt != null && System.currentTimeMillis() - attempt.started < ATTEMPT_WINDOW_MILLIS &&
|
||||
attempt.failures >= 5;
|
||||
}
|
||||
|
||||
synchronized void failed(String client) {
|
||||
long now = System.currentTimeMillis();
|
||||
Attempt attempt = attempts.get(client);
|
||||
if (attempt == null || now - attempt.started >= ATTEMPT_WINDOW_MILLIS)
|
||||
attempts.put(client, new Attempt(now, 1));
|
||||
else attempts.put(client, new Attempt(attempt.started, attempt.failures + 1));
|
||||
if (attempts.size() > MAX_CLIENTS) {
|
||||
Iterator<String> oldest = attempts.keySet().iterator();
|
||||
oldest.next();
|
||||
oldest.remove();
|
||||
}
|
||||
}
|
||||
|
||||
synchronized Session session(HttpExchange exchange) {
|
||||
String token = sessionCookie(exchange);
|
||||
Session session = sessions.get(token);
|
||||
if (session == null) return null;
|
||||
if (session.expires() > System.currentTimeMillis()) return session;
|
||||
sessions.remove(token);
|
||||
return null;
|
||||
}
|
||||
|
||||
String sessionCookie(HttpExchange exchange) {
|
||||
String header = exchange.getRequestHeaders().getFirst("Cookie");
|
||||
if (header == null || header.length() > 8192) return "";
|
||||
String name = secureOrigin() ? "__Host-objectstore_admin=" : "objectstore_admin=";
|
||||
for (String field : header.split(";")) {
|
||||
String value = field.trim();
|
||||
if (value.startsWith(name) && value.substring(name.length()).matches("[A-Za-z0-9_-]{43}"))
|
||||
return value.substring(name.length());
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
String cookie(String token, int seconds) {
|
||||
String name = secureOrigin() ? "__Host-objectstore_admin" : "objectstore_admin";
|
||||
String path = secureOrigin() ? "/" : PATH;
|
||||
return name + "=" + token + "; Path=" + path + "; HttpOnly; SameSite=Strict; Max-Age=" + seconds +
|
||||
(secureOrigin() ? "; Secure" : "");
|
||||
}
|
||||
|
||||
boolean secureOrigin() {
|
||||
return publicOrigin != null && "https".equals(publicOrigin.getScheme());
|
||||
}
|
||||
|
||||
static boolean privateIpv4(String host) {
|
||||
if (host == null || !host.matches("[0-9]+(?:\\.[0-9]+){3}")) return false;
|
||||
String[] fields = host.split("\\.");
|
||||
int[] octets = new int[4];
|
||||
for (int i = 0; i < octets.length; i++) {
|
||||
if (fields[i].length() > 3 || (fields[i].length() > 1 && fields[i].startsWith("0"))) return false;
|
||||
octets[i] = Integer.parseInt(fields[i]);
|
||||
if (octets[i] > 255) return false;
|
||||
}
|
||||
return octets[0] == 10 ||
|
||||
(octets[0] == 172 && octets[1] >= 16 && octets[1] <= 31) ||
|
||||
(octets[0] == 192 && octets[1] == 168);
|
||||
}
|
||||
|
||||
String requestOrigin(HttpExchange exchange) {
|
||||
String host = exchange.getRequestHeaders().getFirst("Host");
|
||||
if (host == null || exchange.getRequestHeaders().get("Host").size() != 1) return null;
|
||||
if (publicOrigin != null)
|
||||
return host.equalsIgnoreCase(publicOrigin.getRawAuthority()) ? publicOrigin.toString() : null;
|
||||
if (!host.matches("(?i)(localhost|127\\.0\\.0\\.1|\\[::1\\])(?::[0-9]{1,5})?")) return null;
|
||||
return "http://" + host.toLowerCase(java.util.Locale.ROOT);
|
||||
}
|
||||
|
||||
static boolean adminOriginAllowed(HttpExchange exchange, String expected) {
|
||||
String submitted = exchange.getRequestHeaders().getFirst("Origin");
|
||||
if (submitted == null || submitted.equals(expected) || submitted.equals("null")) return true;
|
||||
return "same-origin".equals(exchange.getRequestHeaders().getFirst("Sec-Fetch-Site"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
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.util.Base64;
|
||||
|
||||
final class AdminBranding {
|
||||
static final String DEFAULT_NAME = "ObjectStore admin";
|
||||
static final String DEFAULT_THEME = "deep-dark";
|
||||
static final int MAX_ICON_BYTES = 128 * 1024;
|
||||
private static final int MAX_FILE_BYTES = 180 * 1024;
|
||||
private final Path file;
|
||||
private volatile State state;
|
||||
|
||||
record State(String name, String mime, byte[] icon, String defaultTheme) { }
|
||||
|
||||
AdminBranding(Path file) throws IOException {
|
||||
this.file = file.toAbsolutePath().normalize();
|
||||
State loaded = new State(DEFAULT_NAME, "", new byte[0], DEFAULT_THEME);
|
||||
try {
|
||||
if (Files.exists(this.file)) loaded = decode(Files.readAllBytes(this.file));
|
||||
} catch (IOException error) {
|
||||
System.err.println("Could not load admin branding; using defaults: " + error.getMessage());
|
||||
}
|
||||
this.state = loaded;
|
||||
}
|
||||
|
||||
State state() {
|
||||
State current = state;
|
||||
return new State(current.name(), current.mime(), current.icon().clone(), current.defaultTheme());
|
||||
}
|
||||
|
||||
synchronized void setName(String name) throws IOException {
|
||||
String value = name == null ? "" : name.trim();
|
||||
if (value.isEmpty() || value.length() > 40 || value.chars().anyMatch(Character::isISOControl))
|
||||
throw new StoreException(400, "InvalidArgument", "Use a display name of 1 to 40 characters");
|
||||
persist(new State(value, state.mime(), state.icon(), state.defaultTheme()));
|
||||
}
|
||||
|
||||
synchronized void setIcon(byte[] icon) throws IOException {
|
||||
if (icon.length == 0 || icon.length > MAX_ICON_BYTES)
|
||||
throw new StoreException(413, "InvalidArgument", "Icon must be at most 128 KiB");
|
||||
String mime = mime(icon);
|
||||
if (mime == null)
|
||||
throw new StoreException(415, "InvalidArgument", "Use a PNG, JPEG, or WebP icon");
|
||||
persist(new State(state.name(), mime, icon.clone(), state.defaultTheme()));
|
||||
}
|
||||
|
||||
synchronized void setDefaultTheme(String theme) throws IOException {
|
||||
if (!validTheme(theme))
|
||||
throw new StoreException(400, "InvalidArgument", "Choose a supported Biscuit theme");
|
||||
persist(new State(state.name(), state.mime(), state.icon(), theme));
|
||||
}
|
||||
|
||||
synchronized void reset() throws IOException {
|
||||
persist(new State(DEFAULT_NAME, "", new byte[0], state.defaultTheme()));
|
||||
}
|
||||
|
||||
String json() {
|
||||
State current = state;
|
||||
String name = current.name().replace("\\", "\\\\").replace("\"", "\\\"");
|
||||
return "{\"name\":\"" + name + "\",\"icon\":\"" +
|
||||
(current.icon().length == 0 ? AdminConsole.PATH + "/logo.png" :
|
||||
AdminConsole.PATH + "/branding-icon?v=" +
|
||||
Integer.toHexString(java.util.Arrays.hashCode(current.icon()))) +
|
||||
"\",\"defaultTheme\":\"" + current.defaultTheme() + "\"}";
|
||||
}
|
||||
|
||||
private void persist(State next) throws IOException {
|
||||
Path parent = file.getParent();
|
||||
Files.createDirectories(parent);
|
||||
Path temporary = Files.createTempFile(parent, "admin-branding-", ".part");
|
||||
try {
|
||||
byte[] bytes = ("ObjectStoreBranding 2\n" +
|
||||
Base64.getEncoder().encodeToString(next.name().getBytes(StandardCharsets.UTF_8)) + "\n" +
|
||||
next.mime() + "\n" + Base64.getEncoder().encodeToString(next.icon()) + "\n" +
|
||||
next.defaultTheme() + "\n")
|
||||
.getBytes(StandardCharsets.US_ASCII);
|
||||
try (FileChannel channel = FileChannel.open(temporary, StandardOpenOption.WRITE)) {
|
||||
ByteBuffer buffer = ByteBuffer.wrap(bytes);
|
||||
while (buffer.hasRemaining()) channel.write(buffer);
|
||||
channel.force(true);
|
||||
}
|
||||
Files.move(temporary, file, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
|
||||
try (FileChannel directory = FileChannel.open(parent, StandardOpenOption.READ)) {
|
||||
directory.force(true);
|
||||
}
|
||||
state = next;
|
||||
} finally { Files.deleteIfExists(temporary); }
|
||||
}
|
||||
|
||||
private static State decode(byte[] bytes) throws IOException {
|
||||
if (bytes.length > MAX_FILE_BYTES) throw new IOException("Admin branding file is too large");
|
||||
try {
|
||||
String[] lines = new String(bytes, StandardCharsets.US_ASCII).split("\\n", -1);
|
||||
boolean oldFormat = lines.length == 5 && lines[0].equals("ObjectStoreBranding 1") &&
|
||||
lines[4].isEmpty();
|
||||
boolean newFormat = lines.length == 6 && lines[0].equals("ObjectStoreBranding 2") &&
|
||||
lines[5].isEmpty();
|
||||
if (!oldFormat && !newFormat)
|
||||
throw new IllegalArgumentException();
|
||||
String name = new String(Base64.getDecoder().decode(lines[1]), StandardCharsets.UTF_8);
|
||||
byte[] icon = Base64.getDecoder().decode(lines[3]);
|
||||
if (name.isBlank() || name.length() > 40 || name.chars().anyMatch(Character::isISOControl) ||
|
||||
icon.length > MAX_ICON_BYTES ||
|
||||
!(icon.length == 0 && lines[2].isEmpty() || lines[2].equals(mime(icon))))
|
||||
throw new IllegalArgumentException();
|
||||
String theme = oldFormat ? DEFAULT_THEME : lines[4];
|
||||
if (!validTheme(theme)) throw new IllegalArgumentException();
|
||||
return new State(name, lines[2], icon, theme);
|
||||
} catch (IllegalArgumentException error) {
|
||||
throw new IOException("Invalid admin branding file", error);
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean validTheme(String theme) {
|
||||
return "auto".equals(theme) || "light".equals(theme) ||
|
||||
"dark".equals(theme) || "deep-dark".equals(theme);
|
||||
}
|
||||
|
||||
private static String mime(byte[] bytes) {
|
||||
if (bytes.length >= 8 && (bytes[0] & 255) == 137 && bytes[1] == 80 && bytes[2] == 78 &&
|
||||
bytes[3] == 71 && bytes[4] == 13 && bytes[5] == 10 && bytes[6] == 26 && bytes[7] == 10)
|
||||
return "image/png";
|
||||
if (bytes.length >= 3 && (bytes[0] & 255) == 255 && (bytes[1] & 255) == 216 &&
|
||||
(bytes[2] & 255) == 255) return "image/jpeg";
|
||||
if (bytes.length >= 12 && bytes[0] == 'R' && bytes[1] == 'I' && bytes[2] == 'F' &&
|
||||
bytes[3] == 'F' && bytes[8] == 'W' && bytes[9] == 'E' && bytes[10] == 'B' &&
|
||||
bytes[11] == 'P') return "image/webp";
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,327 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URLDecoder;
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import static cloud.lunarsky.store.AdminBrowserView.*;
|
||||
|
||||
final class AdminBrowser {
|
||||
private static final int PAGE_SIZE = 50;
|
||||
|
||||
private AdminBrowser() { }
|
||||
|
||||
record EditorDraft(String value, String error) { }
|
||||
|
||||
static String index(ObjectStorage store, String rawQuery, String csrf) throws IOException {
|
||||
Map<String, String> query = query(rawQuery, Set.of("filter", "after", "page"));
|
||||
String filter = query.getOrDefault("filter", "").trim();
|
||||
String after = query.get("after");
|
||||
String pageQuery = query.get("page");
|
||||
if (filter.length() > 256 || after != null && after.length() > 255)
|
||||
throw invalidQuery();
|
||||
if (after != null && pageQuery != null) throw invalidQuery();
|
||||
List<ObjectStorage.Bucket> matches = store.buckets().stream()
|
||||
.filter(bucket -> bucket.name().toLowerCase(Locale.ROOT).contains(filter.toLowerCase(Locale.ROOT)))
|
||||
.sorted(Comparator.comparing(ObjectStorage.Bucket::name)).toList();
|
||||
int pageNumber = 1;
|
||||
if (pageQuery != null) {
|
||||
try { pageNumber = Integer.parseInt(pageQuery); }
|
||||
catch (NumberFormatException error) { throw invalidQuery(); }
|
||||
if (pageNumber < 1 || pageNumber > Math.max(1, (matches.size() + PAGE_SIZE - 1) / PAGE_SIZE))
|
||||
throw invalidQuery();
|
||||
} else if (after != null) {
|
||||
pageNumber = 1 + (int) matches.stream()
|
||||
.filter(bucket -> bucket.name().compareTo(after) <= 0).count() / PAGE_SIZE;
|
||||
}
|
||||
int offset = (pageNumber - 1) * PAGE_SIZE;
|
||||
List<ObjectStorage.Bucket> page = after == null ?
|
||||
matches.stream().skip(offset).limit(PAGE_SIZE).toList() :
|
||||
matches.stream().filter(bucket -> bucket.name().compareTo(after) > 0)
|
||||
.limit(PAGE_SIZE).toList();
|
||||
|
||||
StringBuilder html = new StringBuilder(AdminConsole.consoleHeader(csrf));
|
||||
html.append("<nav class=crumbs aria-label=Breadcrumb><a href='")
|
||||
.append(AdminConsole.PATH).append("/overview'>Overview</a><span>/</span><span>Buckets</span></nav>")
|
||||
.append("<div class=intro><div><h2>Buckets</h2><p>")
|
||||
.append(matches.size()).append(" matching buckets</p></div>")
|
||||
.append("<button type=button class=primary-action data-open-dialog=create-bucket-dialog>")
|
||||
.append(AdminConsole.icon("plus")).append("New bucket</button></div>")
|
||||
.append("<div class=toolbar><form method=get action='").append(AdminConsole.PATH)
|
||||
.append("/buckets'><div class=field><label for=bucket-filter>Find a bucket</label>")
|
||||
.append("<input id=bucket-filter name=filter value='").append(AdminConsole.escape(filter))
|
||||
.append("' placeholder='Bucket name'></div><button type=submit>Search</button></form>")
|
||||
.append("<a class=button-link href='").append(AdminConsole.PATH)
|
||||
.append("/overview'>Overview</a></div>")
|
||||
.append(AdminBucketForms.create(csrf));
|
||||
if (page.isEmpty()) {
|
||||
html.append("<div class='table-wrap empty'>No buckets match this search.</div>");
|
||||
} else {
|
||||
html.append("<div class=table-wrap><table><thead><tr><th>Bucket</th><th>Versioning</th>")
|
||||
.append("<th>Access</th><th>Ownership</th><th>Created</th></tr></thead><tbody>");
|
||||
for (ObjectStorage.Bucket bucket : page) {
|
||||
html.append("<tr><td class=name-cell><a href='")
|
||||
.append(bucketUrl(bucket.name(), "", null)).append("'>")
|
||||
.append(AdminConsole.escape(bucket.name())).append("</a></td><td>")
|
||||
.append(versioningBadge(bucket.versioning())).append("</td><td>")
|
||||
.append(accessBadge(bucket)).append("</td><td>")
|
||||
.append(ownership(bucket.ownership())).append("</td><td>")
|
||||
.append(time(bucket.created())).append("</td></tr>");
|
||||
}
|
||||
html.append("</tbody></table></div>");
|
||||
}
|
||||
if (matches.size() > PAGE_SIZE)
|
||||
html.append("<biscuit-paginationview class=bucket-pagination theme=deep-dark page=")
|
||||
.append(pageNumber).append(" total=").append(matches.size())
|
||||
.append(" page-size=").append(PAGE_SIZE).append(" data-filter='")
|
||||
.append(AdminConsole.escape(filter)).append("'></biscuit-paginationview>");
|
||||
return html.toString();
|
||||
}
|
||||
|
||||
static String bucket(ObjectStorage store, String rawQuery, String csrf) throws IOException {
|
||||
return bucket(store, rawQuery, csrf, null);
|
||||
}
|
||||
|
||||
static String bucket(ObjectStorage store, String rawQuery, String csrf, EditorDraft policyDraft)
|
||||
throws IOException {
|
||||
return bucket(store, rawQuery, csrf, policyDraft, null);
|
||||
}
|
||||
|
||||
static String bucket(ObjectStorage store, String rawQuery, String csrf, EditorDraft policyDraft,
|
||||
BucketActivity activity) throws IOException {
|
||||
Map<String, String> query = query(rawQuery, Set.of("name", "prefix", "after"));
|
||||
String name = required(query, "name", 255);
|
||||
String prefix = query.getOrDefault("prefix", "");
|
||||
String after = query.get("after");
|
||||
if (prefix.length() > 1024 || after != null && after.length() > 1024)
|
||||
throw invalidQuery();
|
||||
ObjectStorage.Bucket bucket = store.bucket(name);
|
||||
ObjectStorage.ListPage page = store.list(name, prefix, "/", PAGE_SIZE, after);
|
||||
long visibleBytes = page.objects().stream().mapToLong(entry -> entry.metadata().length()).sum();
|
||||
|
||||
StringBuilder html = new StringBuilder(AdminConsole.consoleHeader(csrf));
|
||||
html.append(breadcrumbs(name, prefix));
|
||||
html.append("<div class=intro><div><h2>").append(AdminConsole.escape(name))
|
||||
.append("</h2><p>Browse prefixes and inspect object metadata.</p></div>")
|
||||
.append("<div class=bucket-badges>")
|
||||
.append(versioningBadge(bucket.versioning()))
|
||||
.append(accessBadge(bucket))
|
||||
.append("</div></div>")
|
||||
.append("<div class=grid><biscuit-cardview><small>Entries on this page</small><strong>")
|
||||
.append(page.keyCount()).append("</strong></biscuit-cardview>")
|
||||
.append("<biscuit-cardview><small>Object bytes on this page</small><strong>")
|
||||
.append(AdminConsole.formatBytes(visibleBytes)).append("</strong></biscuit-cardview>")
|
||||
.append("<biscuit-cardview><small>Versioning</small><strong>")
|
||||
.append(versioning(bucket.versioning())).append("</strong></biscuit-cardview></div>")
|
||||
.append("<biscuit-tablayout theme=deep-dark orientation=horizontal variant=underline ")
|
||||
.append("aria-label='Bucket panels' value='")
|
||||
.append(policyDraft == null ? "objects" : "settings").append("'>");
|
||||
objectsPanel(html, store.limits().maxObjectBytes(), name, prefix, after, page, csrf);
|
||||
html.append("<biscuit-tab label=Activity value=activity>")
|
||||
.append(activityPanel(name, activity));
|
||||
largestObjects(html, page, prefix);
|
||||
html.append("</biscuit-tab><biscuit-tab label=Settings value=settings>");
|
||||
bucketSummary(html, bucket);
|
||||
AdminBucketForms.settings(html, bucket, csrf, policyDraft);
|
||||
html.append("</biscuit-tab></biscuit-tablayout>");
|
||||
return html.toString();
|
||||
}
|
||||
|
||||
private static void objectsPanel(StringBuilder html, long maxObjectBytes, String name,
|
||||
String prefix, String after, ObjectStorage.ListPage page, String csrf) {
|
||||
html.append("<biscuit-tab label=Objects value=objects>")
|
||||
.append("<section class=buckets id=objects><h2>Objects</h2>")
|
||||
.append("<p>Showing up to ").append(PAGE_SIZE)
|
||||
.append(" entries in this prefix. Counts and chart data describe this page only.</p>")
|
||||
.append("<div class=toolbar><form method=get action='").append(AdminConsole.PATH)
|
||||
.append("/bucket'><input type=hidden name=name value='").append(AdminConsole.escape(name))
|
||||
.append("'><div class=field><label for=prefix>Prefix</label>")
|
||||
.append("<input id=prefix name=prefix value='").append(AdminConsole.escape(prefix))
|
||||
.append("' placeholder='e.g. images/2026/'></div><button type=submit>Browse</button></form>")
|
||||
.append("<a class=button-link href='").append(AdminConsole.PATH)
|
||||
.append("/buckets'>All buckets</a><a class=button-link href='")
|
||||
.append(versionsUrl(name, prefix, null, null)).append("'>")
|
||||
.append(AdminConsole.icon("version-history")).append("Versions</a></div>")
|
||||
.append("<form class='settings-form upload-form' data-bucket='")
|
||||
.append(AdminConsole.escape(name)).append("' data-prefix='")
|
||||
.append(AdminConsole.escape(prefix)).append("' data-max-bytes='")
|
||||
.append(maxObjectBytes).append("'>")
|
||||
.append("<input type=hidden name=csrf value='").append(csrf).append("'>")
|
||||
.append("<h3>Upload file</h3><div class=upload-fields><label>Choose file")
|
||||
.append("<input type=file name=file required></label><label>Object key")
|
||||
.append("<input name=key value='").append(AdminConsole.escape(prefix))
|
||||
.append("' required placeholder='Path and file name'></label></div>")
|
||||
.append("<label class=check><input type=checkbox name=overwrite>Replace existing object")
|
||||
.append(" <small>(requires versioning)</small></label>")
|
||||
.append("<button type=submit>").append(AdminConsole.icon("upload"))
|
||||
.append("Upload</button><p class=upload-status role=status>")
|
||||
.append("JavaScript is required for uploads. Maximum file size: ")
|
||||
.append(AdminConsole.formatBytes(maxObjectBytes))
|
||||
.append(".</p></form>");
|
||||
objectTable(html, name, prefix, page);
|
||||
if (after != null || page.truncated()) {
|
||||
html.append("<nav class=pagination aria-label='Object pages'><a class=button-link href='")
|
||||
.append(bucketUrl(name, prefix, null)).append("'>First page</a>");
|
||||
if (page.truncated()) html.append("<a class=button-link href='")
|
||||
.append(bucketUrl(name, prefix, page.nextKey())).append("'>Next page →</a>");
|
||||
html.append("</nav>");
|
||||
}
|
||||
html.append("</section></biscuit-tab>");
|
||||
}
|
||||
|
||||
private static void objectTable(StringBuilder html, String name, String prefix,
|
||||
ObjectStorage.ListPage page) {
|
||||
if (page.keyCount() == 0) {
|
||||
html.append("<div class='table-wrap empty'>Nothing in this prefix.</div>");
|
||||
if (!prefix.isEmpty()) html.append("<nav class=pagination><a class=button-link href='")
|
||||
.append(bucketUrl(name, parentPrefix(prefix), null)).append("'>← Parent folder</a></nav>");
|
||||
} else {
|
||||
html.append("<div class=table-wrap><table><thead><tr><th>Name</th><th>Kind</th>")
|
||||
.append("<th>Size</th><th>Modified</th><th>Actions</th></tr></thead><tbody>");
|
||||
if (!prefix.isEmpty()) {
|
||||
html.append("<tr><td class=name-cell><a href='")
|
||||
.append(bucketUrl(name, parentPrefix(prefix), null))
|
||||
.append("'>../</a></td><td class=kind>Parent</td><td>—</td><td>—</td><td>—</td></tr>");
|
||||
}
|
||||
for (String folder : page.prefixes()) {
|
||||
html.append("<tr><td class=name-cell><a href='")
|
||||
.append(bucketUrl(name, folder, null)).append("'>▸ ")
|
||||
.append(AdminConsole.escape(folder.substring(prefix.length())))
|
||||
.append("</a></td><td class=kind>Folder</td><td>—</td><td>—</td><td>—</td></tr>");
|
||||
}
|
||||
for (ObjectStorage.ListedObject object : page.objects()) {
|
||||
ObjectStorage.Metadata meta = object.metadata();
|
||||
String label = object.key().substring(prefix.length());
|
||||
if (label.isEmpty()) label = "(folder marker)";
|
||||
html.append("<tr><td class=name-cell><a href='")
|
||||
.append(objectUrl(name, object.key())).append("'>")
|
||||
.append(AdminConsole.escape(label)).append("</a></td><td class=kind>Object</td><td>")
|
||||
.append(AdminConsole.formatBytes(meta.length())).append("</td><td>")
|
||||
.append(time(meta.modified())).append("</td><td><a href='")
|
||||
.append(downloadUrl(name, object.key(), null))
|
||||
.append("'>").append(AdminConsole.icon("download"))
|
||||
.append("Download</a></td></tr>");
|
||||
}
|
||||
html.append("</tbody></table></div>");
|
||||
}
|
||||
}
|
||||
|
||||
private static void largestObjects(StringBuilder html, ObjectStorage.ListPage page, String prefix) {
|
||||
if (!page.objects().isEmpty()) {
|
||||
html.append("<section class=insight><biscuit-chartview type=bar theme=deep-dark ")
|
||||
.append("name='Largest objects on this page' height=300>")
|
||||
.append("<biscuit-series type=bar x=label y=bytes name='Size in bytes'>");
|
||||
page.objects().stream().sorted(Comparator.comparingLong((ObjectStorage.ListedObject object) ->
|
||||
object.metadata().length()).reversed()).limit(10).forEach(object -> {
|
||||
String label = object.key().substring(prefix.length());
|
||||
if (label.length() > 24) label = label.substring(0, 23) + "…";
|
||||
html.append("<biscuit-point x='").append(AdminConsole.escape(label))
|
||||
.append("' y='").append(object.metadata().length()).append("'></biscuit-point>");
|
||||
});
|
||||
html.append("</biscuit-series></biscuit-chartview></section>");
|
||||
}
|
||||
}
|
||||
|
||||
private static void bucketSummary(StringBuilder html, ObjectStorage.Bucket bucket) {
|
||||
html.append("<section class=buckets id=configuration><h2>Bucket settings</h2>")
|
||||
.append("<div class=detail-grid><div class=detail-card><h3>Access</h3>")
|
||||
.append(fact("Ownership", ownership(bucket.ownership())))
|
||||
.append(fact("Block public ACLs", yesNo(bucket.publicAccessBlock().blockPublicAcls())))
|
||||
.append(fact("Ignore public ACLs", yesNo(bucket.publicAccessBlock().ignorePublicAcls())))
|
||||
.append(fact("Block public policy", yesNo(bucket.publicAccessBlock().blockPublicPolicy())))
|
||||
.append(fact("Restrict public buckets", yesNo(bucket.publicAccessBlock().restrictPublicBuckets())))
|
||||
.append("</div><div class=detail-card><h3>Lifecycle</h3>")
|
||||
.append(fact("Created", time(bucket.created())))
|
||||
.append(fact("Versioning", versioning(bucket.versioning())))
|
||||
.append(fact("Policy", bucket.policy() == null ? "None" : "Configured"))
|
||||
.append("</div></div>");
|
||||
if (bucket.policy() != null)
|
||||
html.append("<details><summary>Bucket policy</summary><pre>")
|
||||
.append(AdminConsole.escape(bucket.policy())).append("</pre></details>");
|
||||
if (!bucket.acl().isEmpty())
|
||||
html.append(attributes("Bucket grants", bucket.acl()));
|
||||
html.append("</section>");
|
||||
}
|
||||
|
||||
private static String activityPanel(String bucket, BucketActivity activity) {
|
||||
if (activity == null)
|
||||
return "<section class=insight><h2>Daily activity</h2><p>Activity is unavailable.</p></section>";
|
||||
List<BucketActivity.Day> days = activity.days(bucket);
|
||||
long reads = days.stream().mapToLong(BucketActivity.Day::reads).sum();
|
||||
long writes = days.stream().mapToLong(BucketActivity.Day::writes).sum();
|
||||
StringBuilder html = new StringBuilder("<section class='insight activity-panel'><h2>Daily activity</h2>")
|
||||
.append("<p>Successful S3 requests observed by this server, in UTC. ")
|
||||
.append("The latest activity may take up to a minute to survive a sudden power loss.</p>")
|
||||
.append("<p class=activity-summary><strong>").append(reads + writes)
|
||||
.append(" requests</strong><span>").append(reads).append(" reads · ")
|
||||
.append(writes).append(" writes over 365 days</span></p>")
|
||||
.append("<biscuit-activity-chart theme=deep-dark name='Daily S3 requests' ")
|
||||
.append("calendar-range=rolling calendar-color='#9d73d5' ")
|
||||
.append("color-scale=steps gradient=subtle>")
|
||||
.append("<biscuit-series type=calendar x=date y=count name=Requests>");
|
||||
for (BucketActivity.Day day : days) {
|
||||
if (day.total() > 0)
|
||||
html.append("<biscuit-point x='").append(day.date()).append("' y='")
|
||||
.append(day.total()).append("'></biscuit-point>");
|
||||
}
|
||||
return html.append("</biscuit-series></biscuit-activity-chart>")
|
||||
.append("<p class=muted>Each square is one UTC day. Counts include reads and writes.</p></section>")
|
||||
.toString();
|
||||
}
|
||||
|
||||
static String object(ObjectStorage store, String rawQuery, String csrf) throws IOException {
|
||||
return AdminObjectPages.object(store, rawQuery, csrf, null);
|
||||
}
|
||||
|
||||
static String object(ObjectStorage store, String rawQuery, String csrf, EditorDraft contentDraft)
|
||||
throws IOException {
|
||||
return AdminObjectPages.object(store, rawQuery, csrf, contentDraft);
|
||||
}
|
||||
|
||||
static String versions(ObjectStorage store, String rawQuery, String csrf) throws IOException {
|
||||
return AdminObjectPages.versions(store, rawQuery, csrf);
|
||||
}
|
||||
|
||||
static String bucketUrl(String name, String prefix, String after) {
|
||||
return AdminBrowserView.bucketUrl(name, prefix, after);
|
||||
}
|
||||
|
||||
static String encoded(String value) {
|
||||
return URLEncoder.encode(value, StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
static String required(Map<String, String> values, String name, int limit) {
|
||||
String value = values.get(name);
|
||||
if (value == null || value.isEmpty() || value.length() > limit) throw invalidQuery();
|
||||
return value;
|
||||
}
|
||||
|
||||
static Map<String, String> query(String raw, Set<String> allowed) {
|
||||
if (raw == null || raw.isEmpty()) return Map.of();
|
||||
if (raw.length() > 8192) throw invalidQuery();
|
||||
Map<String, String> values = new HashMap<>();
|
||||
try {
|
||||
for (String field : raw.split("&", -1)) {
|
||||
int equal = field.indexOf('=');
|
||||
if (equal < 0) throw invalidQuery();
|
||||
String name = URLDecoder.decode(field.substring(0, equal), StandardCharsets.UTF_8);
|
||||
String value = URLDecoder.decode(field.substring(equal + 1), StandardCharsets.UTF_8);
|
||||
if (!allowed.contains(name) || values.putIfAbsent(name, value) != null)
|
||||
throw invalidQuery();
|
||||
}
|
||||
} catch (IllegalArgumentException badEncoding) {
|
||||
throw invalidQuery();
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
static StoreException invalidQuery() {
|
||||
return new StoreException(400, "InvalidArgument", "Invalid browser link or search");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.Map;
|
||||
import static cloud.lunarsky.store.AdminBrowser.encoded;
|
||||
|
||||
final class AdminBrowserView {
|
||||
private static final DateTimeFormatter TIME = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm 'UTC'")
|
||||
.withZone(ZoneOffset.UTC);
|
||||
|
||||
private AdminBrowserView() { }
|
||||
|
||||
static String bucketUrl(String name, String prefix, String after) {
|
||||
StringBuilder url = new StringBuilder(AdminConsole.PATH + "/bucket?name=" + encoded(name));
|
||||
if (!prefix.isEmpty()) url.append("&prefix=").append(encoded(prefix));
|
||||
if (after != null) url.append("&after=").append(encoded(after));
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
static String objectUrl(String bucket, String key) {
|
||||
return AdminConsole.PATH + "/object?bucket=" + encoded(bucket) + "&key=" + encoded(key);
|
||||
}
|
||||
|
||||
static String downloadUrl(String bucket, String key, String version) {
|
||||
return AdminConsole.PATH + "/download?bucket=" + encoded(bucket) +
|
||||
"&key=" + encoded(key) +
|
||||
(version == null ? "" : "&version=" + encoded(version));
|
||||
}
|
||||
|
||||
static String versionsUrl(String bucket, String prefix, String keyMarker, String versionMarker) {
|
||||
StringBuilder url = new StringBuilder(AdminConsole.PATH + "/versions?bucket=" + encoded(bucket));
|
||||
if (!prefix.isEmpty()) url.append("&prefix=").append(encoded(prefix));
|
||||
if (keyMarker != null) url.append("&keyMarker=").append(encoded(keyMarker));
|
||||
if (versionMarker != null) url.append("&versionMarker=").append(encoded(versionMarker));
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
static String breadcrumbs(String bucket, String prefix) {
|
||||
StringBuilder html = new StringBuilder("<nav class=crumbs aria-label=Breadcrumb><a href='")
|
||||
.append(AdminConsole.PATH).append("/buckets'>Buckets</a><span>/</span>");
|
||||
if (prefix.isEmpty()) {
|
||||
html.append("<span>").append(AdminConsole.escape(bucket)).append("</span>");
|
||||
} else {
|
||||
html.append("<a href='").append(bucketUrl(bucket, "", null)).append("'>")
|
||||
.append(AdminConsole.escape(bucket)).append("</a>");
|
||||
int from = 0;
|
||||
while (from < prefix.length()) {
|
||||
int slash = prefix.indexOf('/', from);
|
||||
if (slash < 0) break;
|
||||
String current = prefix.substring(0, slash + 1);
|
||||
String label = prefix.substring(from, slash + 1);
|
||||
html.append("<span>/</span><a href='").append(bucketUrl(bucket, current, null))
|
||||
.append("'>").append(AdminConsole.escape(label)).append("</a>");
|
||||
from = slash + 1;
|
||||
}
|
||||
}
|
||||
return html.append("</nav>").toString();
|
||||
}
|
||||
|
||||
static String parentPrefix(String prefix) {
|
||||
int last = prefix.lastIndexOf('/', prefix.length() - 2);
|
||||
return last < 0 ? "" : prefix.substring(0, last + 1);
|
||||
}
|
||||
|
||||
static String attributes(String title, Map<String, String> values) {
|
||||
if (values == null || values.isEmpty()) return "";
|
||||
StringBuilder html = new StringBuilder("<details><summary>")
|
||||
.append(AdminConsole.escape(title)).append(" (" + values.size() + ")</summary>")
|
||||
.append("<div class=table-wrap><table><thead><tr><th>Name</th><th>Value</th></tr></thead><tbody>");
|
||||
values.entrySet().stream().sorted(Map.Entry.comparingByKey()).forEach(entry ->
|
||||
html.append("<tr><td class=name-cell>").append(AdminConsole.escape(entry.getKey()))
|
||||
.append("</td><td class=name-cell>").append(AdminConsole.escape(entry.getValue() == null ? "" : entry.getValue()))
|
||||
.append("</td></tr>"));
|
||||
return html.append("</tbody></table></div></details>").toString();
|
||||
}
|
||||
|
||||
static String fact(String name, String value) {
|
||||
return "<div class=fact><span>" + AdminConsole.escape(name) + "</span><strong>" +
|
||||
AdminConsole.escape(value) + "</strong></div>";
|
||||
}
|
||||
|
||||
static String versioning(ObjectStorage.VersioningState state) {
|
||||
return switch (state) {
|
||||
case NEVER -> "Off";
|
||||
case ENABLED -> "Enabled";
|
||||
case SUSPENDED -> "Suspended";
|
||||
};
|
||||
}
|
||||
|
||||
static String versioningBadge(ObjectStorage.VersioningState state) {
|
||||
String variant = state == ObjectStorage.VersioningState.ENABLED ? "success" :
|
||||
state == ObjectStorage.VersioningState.SUSPENDED ? "warning" : "accent";
|
||||
return badge(variant, "Versioning " + versioning(state));
|
||||
}
|
||||
|
||||
static String accessBadge(ObjectStorage.Bucket bucket) {
|
||||
ObjectStorage.PublicAccessBlock block = bucket.publicAccessBlock();
|
||||
boolean blocked = block.blockPublicAcls() && block.ignorePublicAcls() &&
|
||||
block.blockPublicPolicy() && block.restrictPublicBuckets();
|
||||
return badge(blocked ? "success" : "warning",
|
||||
blocked ? "Public access blocked" : "Public controls relaxed");
|
||||
}
|
||||
|
||||
static String badge(String variant, String text) {
|
||||
return "<biscuit-badgeview theme=deep-dark variant=" + variant + " size=small>" +
|
||||
AdminConsole.escape(text) + "</biscuit-badgeview>";
|
||||
}
|
||||
|
||||
static String ownership(ObjectStorage.ObjectOwnership value) {
|
||||
return switch (value) {
|
||||
case BUCKET_OWNER_ENFORCED -> "Owner enforced";
|
||||
case BUCKET_OWNER_PREFERRED -> "Owner preferred";
|
||||
case OBJECT_WRITER -> "Object writer";
|
||||
};
|
||||
}
|
||||
|
||||
static String yesNo(boolean value) {
|
||||
return value ? "On" : "Off";
|
||||
}
|
||||
|
||||
static String time(long epochMillis) {
|
||||
return TIME.format(Instant.ofEpochMilli(epochMillis));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
final class AdminBucketForms {
|
||||
private AdminBucketForms() { }
|
||||
|
||||
static String create(String csrf) {
|
||||
StringBuilder html = new StringBuilder();
|
||||
html.append("<biscuit-dialogview id=create-bucket-dialog theme=deep-dark label='Create bucket'>")
|
||||
.append("<form class='settings-form dialog-form bucket-wizard-form' method=post action='")
|
||||
.append(AdminConsole.PATH)
|
||||
.append("/action/create-bucket'><input type=hidden name=csrf value='").append(csrf)
|
||||
.append("'><input type=hidden name=setup value=wizard>")
|
||||
.append("<biscuit-formwizardview id=create-bucket-wizard theme=deep-dark>")
|
||||
.append("<biscuit-formstep label=Name value=name>")
|
||||
.append("<label for=new-bucket>Bucket name</label>")
|
||||
.append("<input id=new-bucket name=bucket required minlength=3 maxlength=63 ")
|
||||
.append("pattern='[a-z0-9][a-z0-9-]*[a-z0-9]' placeholder='e.g. media-archive'>")
|
||||
.append("<small>Bucket URLs and presigned links use this name.</small>")
|
||||
.append("</biscuit-formstep><biscuit-formstep label=Storage value=storage>")
|
||||
.append("<label for=new-versioning>Versioning</label>")
|
||||
.append("<select id=new-versioning name=versioning><option value=off>Off</option>")
|
||||
.append("<option value=enabled>Enabled · retain old versions</option></select>")
|
||||
.append("<label for=new-ownership>Object ownership</label>")
|
||||
.append("<select id=new-ownership name=ownership>")
|
||||
.append("<option value=BucketOwnerEnforced>Bucket owner enforced · ACLs disabled</option>")
|
||||
.append("<option value=BucketOwnerPreferred>Bucket owner preferred</option>")
|
||||
.append("<option value=ObjectWriter>Object writer</option></select>")
|
||||
.append("</biscuit-formstep><biscuit-formstep label=Access value=access>")
|
||||
.append("<p>Block public access by default. Turn off only the controls you need.</p>")
|
||||
.append("<div class=check-grid>")
|
||||
.append("<label class=check><input type=checkbox name=blockPublicAcls checked>Block public ACLs</label>")
|
||||
.append("<label class=check><input type=checkbox name=ignorePublicAcls checked>Ignore public ACLs</label>")
|
||||
.append("<label class=check><input type=checkbox name=blockPublicPolicy checked>Block public policies</label>")
|
||||
.append("<label class=check><input type=checkbox name=restrictPublicBuckets checked>Restrict public buckets</label>")
|
||||
.append("</div><label class=check id=public-ack-row hidden>")
|
||||
.append("<input type=checkbox name=acknowledgePublic value=yes>")
|
||||
.append("I understand that relaxing these controls can expose data</label>")
|
||||
.append("</biscuit-formstep><biscuit-formstep label=Review value=review>")
|
||||
.append("<p id=bucket-wizard-review role=status></p>")
|
||||
.append("<small>Settings can be changed later in the bucket panel.</small>")
|
||||
.append("</biscuit-formstep></biscuit-formwizardview>")
|
||||
.append("<div class=dialog-actions><button type=button data-close-dialog>Cancel</button>")
|
||||
.append("</div></form></biscuit-dialogview>");
|
||||
return html.toString();
|
||||
}
|
||||
|
||||
static void settings(StringBuilder html, ObjectStorage.Bucket bucket, String csrf,
|
||||
AdminBrowser.EditorDraft policyDraft) {
|
||||
String name = bucket.name();
|
||||
html.append("<section class=buckets><h2>Manage bucket</h2>")
|
||||
.append("<p>Changes take effect immediately. Type the bucket name to confirm access changes.</p>")
|
||||
.append("<div class=settings-grid><form class=settings-form method=post action='")
|
||||
.append(AdminConsole.PATH).append("/action/versioning'>").append(hidden(csrf, name))
|
||||
.append("<h3>Versioning</h3><select name=state>")
|
||||
.append(option("ENABLED", bucket.versioning() == ObjectStorage.VersioningState.ENABLED))
|
||||
.append(option("SUSPENDED", bucket.versioning() == ObjectStorage.VersioningState.SUSPENDED))
|
||||
.append("</select><button>Save versioning</button></form>")
|
||||
.append("<form class=settings-form method=post action='").append(AdminConsole.PATH)
|
||||
.append("/action/ownership'>").append(hidden(csrf, name))
|
||||
.append("<h3>Object Ownership</h3><select name=ownership>")
|
||||
.append(option("BucketOwnerEnforced", bucket.ownership() ==
|
||||
ObjectStorage.ObjectOwnership.BUCKET_OWNER_ENFORCED))
|
||||
.append(option("BucketOwnerPreferred", bucket.ownership() ==
|
||||
ObjectStorage.ObjectOwnership.BUCKET_OWNER_PREFERRED))
|
||||
.append(option("ObjectWriter", bucket.ownership() ==
|
||||
ObjectStorage.ObjectOwnership.OBJECT_WRITER))
|
||||
.append("</select><input name=confirm placeholder='Type bucket name' required>")
|
||||
.append("<button>Save ownership</button></form></div>")
|
||||
.append("<form class=settings-form method=post action='").append(AdminConsole.PATH)
|
||||
.append("/action/public-access'>").append(hidden(csrf, name))
|
||||
.append("<h3>Block Public Access</h3><div class=check-grid>")
|
||||
.append(checkbox("blockPublicAcls", "Block new public ACLs", bucket.publicAccessBlock().blockPublicAcls()))
|
||||
.append(checkbox("ignorePublicAcls", "Ignore existing public ACLs", bucket.publicAccessBlock().ignorePublicAcls()))
|
||||
.append(checkbox("blockPublicPolicy", "Block public policies", bucket.publicAccessBlock().blockPublicPolicy()))
|
||||
.append(checkbox("restrictPublicBuckets", "Restrict public buckets", bucket.publicAccessBlock().restrictPublicBuckets()))
|
||||
.append("</div><input name=confirm placeholder='Type bucket name if reducing protection'>")
|
||||
.append("<button>Save public access</button></form>")
|
||||
.append("<form class='settings-form code-form' id=policy-editor method=post action='")
|
||||
.append(AdminConsole.PATH)
|
||||
.append("/action/policy'>").append(hidden(csrf, name))
|
||||
.append("<h3>Bucket policy</h3><p class=muted>Edit the policy JSON for this bucket.</p>")
|
||||
.append("<biscuit-codeview class=policy-editor id=policy-code language=json ")
|
||||
.append("aria-label='Bucket policy JSON' value='")
|
||||
.append(AdminConsole.escape(policyDraft == null ?
|
||||
bucket.policy() == null ? "" : bucket.policy() : policyDraft.value()))
|
||||
.append("'></biscuit-codeview><textarea class='code-fallback policy-fallback' ")
|
||||
.append("name=policy rows=9 spellcheck=false placeholder='No policy configured'>")
|
||||
.append(AdminConsole.escape(policyDraft == null ?
|
||||
bucket.policy() == null ? "" : bucket.policy() : policyDraft.value()))
|
||||
.append("</textarea><p class=editor-diagnostics data-editor=policy-code data-state=")
|
||||
.append(policyDraft == null ? "hint" : "error")
|
||||
.append(" role=status>")
|
||||
.append(AdminConsole.escape(policyDraft == null ? "JSON syntax is checked before saving." :
|
||||
policyDraft.error()))
|
||||
.append("</p><input name=confirm placeholder='Type bucket name for public policy'>")
|
||||
.append("<button>Save policy</button></form>");
|
||||
if (bucket.ownership() != ObjectStorage.ObjectOwnership.BUCKET_OWNER_ENFORCED)
|
||||
grantForm(html, "bucket-grant", name, null, null, csrf);
|
||||
else html.append("<p class=muted>ACL editing is disabled while Bucket owner enforced is active.</p>");
|
||||
html.append("<biscuit-accordionview theme=deep-dark class=bucket-renamer>")
|
||||
.append("<biscuit-accordionitem label='Rename bucket'>")
|
||||
.append("<form class='settings-form rename-form' method=post action='")
|
||||
.append(AdminConsole.PATH).append("/action/rename-bucket'>")
|
||||
.append(hidden(csrf, name))
|
||||
.append("<p class=rename-warning role=note><strong>Renaming changes the bucket URL.</strong> ")
|
||||
.append("Clients using the old name or presigned links will stop working. Update application ")
|
||||
.append("configuration and any external access policies. Stored objects, versions, and ")
|
||||
.append("multipart uploads remain in this bucket. Scoped access keys must be moved first. ")
|
||||
.append("If S3_BUCKET names this bucket, update it before restarting the service.</p>")
|
||||
.append("<label for=rename-target>New bucket name</label>")
|
||||
.append("<input id=rename-target name=newName required minlength=3 maxlength=63 ")
|
||||
.append("pattern='[a-z0-9][a-z0-9-]*[a-z0-9]' placeholder='New name'>")
|
||||
.append("<label for=rename-confirm>Type the current name to confirm</label>")
|
||||
.append("<input id=rename-confirm name=confirm required autocomplete=off>")
|
||||
.append("<button type=submit>Rename bucket</button></form>")
|
||||
.append("</biscuit-accordionitem></biscuit-accordionview>");
|
||||
html.append("<form class='settings-form danger-zone' method=post action='")
|
||||
.append(AdminConsole.PATH).append("/action/delete-bucket'>")
|
||||
.append(hidden(csrf, name)).append("<h3>Delete bucket</h3>")
|
||||
.append("<p>Only an empty bucket can be deleted. Type its name to confirm.</p>")
|
||||
.append("<div class=form-row><input name=confirm required placeholder='Type bucket name'>")
|
||||
.append("<button>Delete bucket</button></div></form></section>");
|
||||
}
|
||||
|
||||
static void grantForm(StringBuilder html, String action, String bucket,
|
||||
String key, String version, String csrf) {
|
||||
html.append("<form class=settings-form method=post action='").append(AdminConsole.PATH)
|
||||
.append("/action/").append(action).append("'>").append(hidden(csrf, bucket));
|
||||
if (key != null) html.append("<input type=hidden name=key value='")
|
||||
.append(AdminConsole.escape(key)).append("'>");
|
||||
if (version != null) html.append("<input type=hidden name=version value='")
|
||||
.append(AdminConsole.escape(version)).append("'>");
|
||||
html.append("<h3>ACL grants</h3><p class=muted>Use an access key ID, AllUsers, or AuthenticatedUsers.</p>")
|
||||
.append("<div class=form-row><input name=principal required placeholder='Grantee'>")
|
||||
.append("<select name=permission><option>READ</option><option>WRITE</option>")
|
||||
.append("<option>READ_ACP</option><option>WRITE_ACP</option>")
|
||||
.append("<option>FULL_CONTROL</option></select>")
|
||||
.append("<select name=operation><option value=add>Add grant</option>")
|
||||
.append("<option value=remove>Remove grantee</option></select>")
|
||||
.append("<input name=confirm placeholder='Bucket name for public grant'>")
|
||||
.append("<button>Save grant</button></div></form>");
|
||||
}
|
||||
|
||||
static String hidden(String csrf, String bucket) {
|
||||
return "<input type=hidden name=csrf value='" + csrf +
|
||||
"'><input type=hidden name=bucket value='" + AdminConsole.escape(bucket) + "'>";
|
||||
}
|
||||
|
||||
private static String option(String name, boolean selected) {
|
||||
return "<option" + (selected ? " selected" : "") + ">" + name + "</option>";
|
||||
}
|
||||
|
||||
private static String checkbox(String name, String label, boolean checked) {
|
||||
return "<label class=check><input type=checkbox name='" + name + "'" +
|
||||
(checked ? " checked" : "") + ">" + label + "</label>";
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.Base64;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
final class AdminBulkJobs {
|
||||
static final int MAX_ITEMS = 10_000;
|
||||
private static final int MAX_REPORT_CHARS = 2_000_000;
|
||||
record Spec(String operation, String bucket, String prefix, String targetBucket,
|
||||
String targetPrefix, String tag, String value) { }
|
||||
record Snapshot(String id, Spec spec, String state, int processed, int succeeded,
|
||||
int failed, boolean capped, boolean reportTruncated, long started, long finished) { }
|
||||
|
||||
static final class Job {
|
||||
final String id;
|
||||
final Spec spec;
|
||||
final long started = System.currentTimeMillis();
|
||||
final StringBuilder report = new StringBuilder("status,bucket,key,detail\n");
|
||||
volatile String state = "Running";
|
||||
volatile int processed, succeeded, failed;
|
||||
volatile boolean capped, cancel, reportTruncated;
|
||||
volatile long finished;
|
||||
|
||||
Job(String id, Spec spec) {
|
||||
this.id = id;
|
||||
this.spec = spec;
|
||||
}
|
||||
Snapshot snapshot() {
|
||||
return new Snapshot(id, spec, state, processed, succeeded, failed, capped,
|
||||
reportTruncated, started, finished);
|
||||
}
|
||||
}
|
||||
|
||||
private final ObjectStorage store;
|
||||
private final java.util.function.Consumer<Snapshot> onFinish;
|
||||
private final SecureRandom random = new SecureRandom();
|
||||
private final ArrayDeque<Job> history = new ArrayDeque<>();
|
||||
private volatile StoreOperations operations = new StoreOperations();
|
||||
private Job active;
|
||||
|
||||
AdminBulkJobs(ObjectStorage store) { this(store, ignored -> { }); }
|
||||
|
||||
AdminBulkJobs(ObjectStorage store, java.util.function.Consumer<Snapshot> onFinish) {
|
||||
this.store = store;
|
||||
this.onFinish = onFinish;
|
||||
}
|
||||
|
||||
void setOperations(StoreOperations operations) { this.operations = operations; }
|
||||
|
||||
synchronized boolean hasActiveJob() { return active != null && active.finished == 0; }
|
||||
|
||||
Snapshot start(Spec spec) throws IOException {
|
||||
return operations.readValue(() -> startJob(spec));
|
||||
}
|
||||
|
||||
private synchronized Snapshot startJob(Spec spec) throws IOException {
|
||||
if (hasActiveJob())
|
||||
throw new StoreException(409, "JobInProgress", "Wait for or cancel the current job");
|
||||
validate(spec);
|
||||
byte[] id = new byte[12];
|
||||
random.nextBytes(id);
|
||||
Job job = new Job(Base64.getUrlEncoder().withoutPadding().encodeToString(id), spec);
|
||||
active = job;
|
||||
history.addFirst(job);
|
||||
while (history.size() > 10) history.removeLast();
|
||||
Thread.ofVirtual().name("objectstore-admin-job").start(() -> run(job));
|
||||
return job.snapshot();
|
||||
}
|
||||
|
||||
synchronized List<Snapshot> list() {
|
||||
return history.stream().map(Job::snapshot).toList();
|
||||
}
|
||||
|
||||
synchronized Snapshot get(String id) {
|
||||
Job job = find(id);
|
||||
return job.snapshot();
|
||||
}
|
||||
|
||||
synchronized String report(String id) {
|
||||
Job job = find(id);
|
||||
synchronized (job.report) { return job.report.toString(); }
|
||||
}
|
||||
|
||||
synchronized void cancel(String id) {
|
||||
Job job = find(id);
|
||||
if (job.finished == 0) job.cancel = true;
|
||||
}
|
||||
|
||||
private Job find(String id) {
|
||||
return history.stream().filter(job -> job.id.equals(id)).findFirst()
|
||||
.orElseThrow(() -> new StoreException(404, "NoSuchJob", "Job not found"));
|
||||
}
|
||||
|
||||
private void validate(Spec spec) throws IOException {
|
||||
if (!List.of("inventory", "copy", "delete", "tag").contains(spec.operation()))
|
||||
throw new StoreException(400, "InvalidArgument", "Choose a supported bulk operation");
|
||||
store.bucket(spec.bucket());
|
||||
if (spec.prefix() == null || spec.prefix().getBytes(StandardCharsets.UTF_8).length > 1024)
|
||||
throw new StoreException(400, "InvalidArgument", "Invalid prefix");
|
||||
if (spec.operation().equals("copy")) {
|
||||
store.bucket(spec.targetBucket());
|
||||
if (spec.bucket().equals(spec.targetBucket()))
|
||||
throw new StoreException(400, "InvalidArgument", "Bulk copy requires a different destination bucket");
|
||||
if (spec.targetPrefix() == null || spec.targetPrefix().getBytes(StandardCharsets.UTF_8).length > 1024)
|
||||
throw new StoreException(400, "InvalidArgument", "Invalid destination prefix");
|
||||
}
|
||||
if (spec.operation().equals("tag") && (spec.tag() == null || spec.tag().isBlank() ||
|
||||
spec.tag().length() > 128 || spec.value() == null || spec.value().length() > 256))
|
||||
throw new StoreException(400, "InvalidArgument", "Invalid tag key or value");
|
||||
if (spec.operation().equals("tag"))
|
||||
ObjectAttributes.validateTags(Map.of(spec.tag(), spec.value()));
|
||||
}
|
||||
|
||||
private void run(Job job) {
|
||||
try {
|
||||
processPages(job);
|
||||
job.state = job.cancel ? "Cancelled" : job.capped ? "Capped" : "Completed";
|
||||
} catch (Exception error) {
|
||||
job.state = "Failed";
|
||||
append(job, "error", "", error.getClass().getSimpleName());
|
||||
} finally {
|
||||
job.finished = System.currentTimeMillis();
|
||||
onFinish.accept(job.snapshot());
|
||||
}
|
||||
}
|
||||
|
||||
private void processPages(Job job) throws IOException {
|
||||
String after = null;
|
||||
while (!job.cancel) {
|
||||
ObjectStorage.ListPage page = list(job, after);
|
||||
if (processPage(job, page) || !page.truncated()) return;
|
||||
if (page.nextKey() == null || page.nextKey().equals(after))
|
||||
throw new IOException("Storage listing did not advance");
|
||||
after = page.nextKey();
|
||||
}
|
||||
}
|
||||
|
||||
private boolean processPage(Job job, ObjectStorage.ListPage page) {
|
||||
int remaining = MAX_ITEMS - job.processed;
|
||||
for (ObjectStorage.ListedObject entry : page.objects()) {
|
||||
if (job.cancel || job.processed >= MAX_ITEMS) break;
|
||||
processEntry(job, entry);
|
||||
}
|
||||
if (job.processed < MAX_ITEMS) return false;
|
||||
job.capped = page.truncated() || page.objects().size() > remaining;
|
||||
return true;
|
||||
}
|
||||
|
||||
private void processEntry(Job job, ObjectStorage.ListedObject entry) {
|
||||
try {
|
||||
operations.read(() -> process(job.spec, entry));
|
||||
job.succeeded++;
|
||||
String detail = job.spec.operation().equals("inventory") ?
|
||||
"bytes=" + entry.metadata().length() + " etag=" + entry.metadata().etag() :
|
||||
job.spec.operation();
|
||||
append(job, "ok", entry.key(), detail);
|
||||
} catch (Exception error) {
|
||||
job.failed++;
|
||||
append(job, "error", entry.key(), errorDetail(error));
|
||||
}
|
||||
job.processed++;
|
||||
}
|
||||
|
||||
private static String errorDetail(Exception error) {
|
||||
String detail = error instanceof StoreException storeError ?
|
||||
storeError.code + ": " + storeError.getMessage() : error.getClass().getSimpleName();
|
||||
return detail.length() > 200 ? detail.substring(0, 200) : detail;
|
||||
}
|
||||
|
||||
private ObjectStorage.ListPage list(Job job, String after) throws IOException {
|
||||
return operations.readValue(() ->
|
||||
store.list(job.spec.bucket(), job.spec.prefix(), "", 100, after));
|
||||
}
|
||||
|
||||
private void process(Spec spec, ObjectStorage.ListedObject entry) throws IOException {
|
||||
String key = entry.key();
|
||||
switch (spec.operation()) {
|
||||
case "inventory" -> { }
|
||||
case "delete" -> store.delete(spec.bucket(), key);
|
||||
case "tag" -> {
|
||||
Map<String, String> tags = new HashMap<>(store.tags(spec.bucket(), key));
|
||||
tags.put(spec.tag(), spec.value());
|
||||
ObjectAttributes.validateTags(tags);
|
||||
store.setTags(spec.bucket(), key, Map.copyOf(tags));
|
||||
}
|
||||
case "copy" -> {
|
||||
try (ObjectStorage.OpenObject source = store.open(spec.bucket(), key)) {
|
||||
ObjectStorage.Metadata meta = source.metadata();
|
||||
String suffix = key.substring(spec.prefix().length());
|
||||
store.put(spec.targetBucket(), spec.targetPrefix() + suffix, source.stream(),
|
||||
meta.length(), SigV4.hex(meta.sha256()), null, true, meta.contentType(),
|
||||
meta.userMetadata(), meta.tags(), meta::checksums, Map.of());
|
||||
}
|
||||
}
|
||||
default -> throw new IllegalStateException();
|
||||
}
|
||||
}
|
||||
|
||||
private static void append(Job job, String status, String key, String detail) {
|
||||
synchronized (job.report) {
|
||||
if (job.report.length() >= MAX_REPORT_CHARS) {
|
||||
if (!job.reportTruncated) job.report.append("report-truncated,,,See job counters for totals\n");
|
||||
job.reportTruncated = true;
|
||||
return;
|
||||
}
|
||||
job.report.append(csv(status)).append(',').append(csv(job.spec.bucket())).append(',')
|
||||
.append(csv(key)).append(',').append(csv(detail)).append('\n');
|
||||
}
|
||||
}
|
||||
|
||||
private static String csv(String value) {
|
||||
String safe = value.replace("\r", " ").replace("\n", " ").replace("\t", " ");
|
||||
if (!safe.isEmpty() && "=+-@".indexOf(safe.charAt(0)) >= 0) safe = "'" + safe;
|
||||
return '"' + safe.replace("\"", "\"\"") + '"';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,812 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import com.sun.net.httpserver.HttpExchange;
|
||||
import cloud.lunarsky.store.AdminAuthentication.Session;
|
||||
import static cloud.lunarsky.store.AdminHttp.*;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Path;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.Map;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
final class AdminConsole {
|
||||
static final String PATH = "/_objectstore/admin";
|
||||
@FunctionalInterface
|
||||
private interface Route {
|
||||
void handle(AdminConsole console, HttpExchange exchange, String origin) throws IOException;
|
||||
}
|
||||
|
||||
private static final Map<String, Route> ROUTES = Map.ofEntries(
|
||||
Map.entry(PATH, AdminConsole::root),
|
||||
Map.entry(PATH + "/", AdminConsole::root),
|
||||
Map.entry(PATH + "/login", AdminConsole::loginRoute),
|
||||
Map.entry(PATH + "/branding.json", AdminConsole::branding),
|
||||
Map.entry(PATH + "/branding-icon", AdminConsole::brandingIcon),
|
||||
Map.entry(PATH + "/branding-icon/upload", AdminConsole::uploadBranding),
|
||||
Map.entry(PATH + "/performance.json", AdminConsole::performanceJson),
|
||||
Map.entry(PATH + "/diagnostics/probe.bin", AdminConsole::probe),
|
||||
Map.entry(PATH + "/performance.events", AdminConsole::performanceEvents),
|
||||
Map.entry(PATH + "/logout", AdminConsole::logout),
|
||||
Map.entry(PATH + "/overview", AdminConsole::overview),
|
||||
Map.entry(PATH + "/performance", AdminConsole::performancePage),
|
||||
Map.entry(PATH + "/health", AdminConsole::statusPage),
|
||||
Map.entry(PATH + "/diagnostics", AdminConsole::statusPage),
|
||||
Map.entry(PATH + "/audit", AdminConsole::auditPage),
|
||||
Map.entry(PATH + "/jobs", AdminConsole::jobsPage),
|
||||
Map.entry(PATH + "/cluster", AdminConsole::clusterPage),
|
||||
Map.entry(PATH + "/jobs.json", AdminConsole::jobReport),
|
||||
Map.entry(PATH + "/jobs.csv", AdminConsole::jobReport),
|
||||
Map.entry(PATH + "/credentials", AdminConsole::credentialsPage),
|
||||
Map.entry(PATH + "/download", AdminConsole::download),
|
||||
Map.entry(PATH + "/upload", AdminConsole::upload),
|
||||
Map.entry(PATH + "/buckets", AdminConsole::browse),
|
||||
Map.entry(PATH + "/bucket", AdminConsole::browse),
|
||||
Map.entry(PATH + "/versions", AdminConsole::browse),
|
||||
Map.entry(PATH + "/object", AdminConsole::browse),
|
||||
Map.entry(PATH + "/settings", AdminConsole::settings));
|
||||
|
||||
private final ObjectStorage store;
|
||||
private final AdminAuthentication authentication;
|
||||
private final AdminAssets assets;
|
||||
private final AdminBranding branding;
|
||||
private final AdminAuditTrail audit;
|
||||
private final AdminBulkJobs jobs;
|
||||
private volatile StoreOperations operations = new StoreOperations();
|
||||
@FunctionalInterface interface AccessCheck {
|
||||
AdminAccessCheck.Result check(String principal, String operation, String bucket, String key)
|
||||
throws IOException;
|
||||
}
|
||||
private volatile AccessCheck accessCheck;
|
||||
private volatile RequestMetrics metrics;
|
||||
private volatile RequestDiagnostics diagnostics;
|
||||
private volatile DiskStore diskStore;
|
||||
private volatile BucketActivity bucketActivity;
|
||||
private volatile Set<String> identities = Set.of();
|
||||
private volatile ManagedCredentials managedCredentials;
|
||||
private volatile Runnable refreshCredentials;
|
||||
private AdminConsole(ObjectStorage store, AdminAuthentication authentication,
|
||||
AdminAssets assets,
|
||||
AdminBranding branding, AdminAuditTrail audit) {
|
||||
this.store = store;
|
||||
this.authentication = authentication;
|
||||
this.assets = assets;
|
||||
this.branding = branding;
|
||||
this.audit = audit;
|
||||
this.jobs = new AdminBulkJobs(store, completed ->
|
||||
auditOutcome("bulk-" + completed.spec().operation(),
|
||||
completed.spec().bucket() + "/" + completed.spec().prefix(),
|
||||
"background", completed.state() + ":" + completed.succeeded() + ":" + completed.failed()));
|
||||
}
|
||||
|
||||
void setOperations(StoreOperations operations) {
|
||||
this.operations = operations;
|
||||
jobs.setOperations(operations);
|
||||
}
|
||||
|
||||
void setMetrics(RequestMetrics metrics) { this.metrics = metrics; }
|
||||
void setDiagnostics(RequestDiagnostics diagnostics) { this.diagnostics = diagnostics; }
|
||||
void setDiskStore(DiskStore diskStore) { this.diskStore = diskStore; }
|
||||
void setBucketActivity(BucketActivity bucketActivity) { this.bucketActivity = bucketActivity; }
|
||||
void setIdentities(Set<String> identities) { this.identities = Set.copyOf(identities); }
|
||||
void setManagedCredentials(ManagedCredentials managed, Runnable refresh) {
|
||||
this.managedCredentials = managed;
|
||||
this.refreshCredentials = refresh;
|
||||
}
|
||||
void setAccessCheck(AccessCheck check) { this.accessCheck = check; }
|
||||
|
||||
static AdminConsole fromEnvironment(Map<String, String> env, ObjectStorage store) throws IOException {
|
||||
String enabled = env.getOrDefault("ADMIN_UI_ENABLED", "false");
|
||||
if (enabled.equals("false")) return null;
|
||||
if (!enabled.equals("true")) throw new IllegalArgumentException("Invalid ADMIN_UI_ENABLED");
|
||||
AdminAuthentication authentication = AdminAuthentication.fromEnvironment(env);
|
||||
Path stateDirectory = Path.of(env.getOrDefault("ADMIN_UI_STATE_DIR",
|
||||
env.getOrDefault("DATA_DIR", "/data")));
|
||||
Path brandingFile = Path.of(env.getOrDefault("ADMIN_UI_BRANDING_FILE",
|
||||
stateDirectory.resolve("admin-branding.txt").toString()));
|
||||
return new AdminConsole(store, authentication,
|
||||
new AdminAssets(), new AdminBranding(brandingFile),
|
||||
new AdminAuditTrail(stateDirectory));
|
||||
}
|
||||
|
||||
void handle(HttpExchange exchange) throws IOException {
|
||||
securityHeaders(exchange);
|
||||
String origin = authentication.requestOrigin(exchange);
|
||||
if (origin == null) {
|
||||
send(exchange, 403, page("<h1>Admin console unavailable</h1>" +
|
||||
"<p>Open the local console at <code>http://127.0.0.1:<port>" + PATH +
|
||||
"/login</code>, or use the configured origin.</p>"), "text/html; charset=utf-8");
|
||||
return;
|
||||
}
|
||||
if (assets.handle(exchange, authentication.session(exchange) != null)) return;
|
||||
String path = exchange.getRequestURI().getRawPath();
|
||||
if (path.startsWith(PATH + "/action/")) {
|
||||
action(exchange, origin);
|
||||
return;
|
||||
}
|
||||
Route route = ROUTES.get(path);
|
||||
if (route == null) send(exchange, 404, "Not found", "text/plain; charset=utf-8");
|
||||
else route.handle(this, exchange, origin);
|
||||
}
|
||||
|
||||
private Session requireSession(HttpExchange exchange, String method) throws IOException {
|
||||
if (!exchange.getRequestMethod().equals(method)) {
|
||||
methodNotAllowed(exchange, method);
|
||||
return null;
|
||||
}
|
||||
Session session = authentication.session(exchange);
|
||||
if (session == null) redirect(exchange, PATH + "/login");
|
||||
return session;
|
||||
}
|
||||
|
||||
private void root(HttpExchange exchange, String origin) throws IOException {
|
||||
String method = exchange.getRequestMethod();
|
||||
if (!method.equals("GET")) {
|
||||
methodNotAllowed(exchange, "GET");
|
||||
return;
|
||||
}
|
||||
if (authentication.session(exchange) != null) redirect(exchange, PATH + "/overview");
|
||||
else redirect(exchange, PATH + "/login");
|
||||
}
|
||||
|
||||
private void loginRoute(HttpExchange exchange, String origin) throws IOException {
|
||||
String method = exchange.getRequestMethod();
|
||||
if (method.equals("GET")) {
|
||||
send(exchange, 200, loginPage("", authentication.issueLoginToken()), "text/html; charset=utf-8");
|
||||
return;
|
||||
}
|
||||
if (method.equals("POST")) {
|
||||
login(exchange);
|
||||
return;
|
||||
}
|
||||
methodNotAllowed(exchange, "GET, POST");
|
||||
}
|
||||
|
||||
private void branding(HttpExchange exchange, String origin) throws IOException {
|
||||
String method = exchange.getRequestMethod();
|
||||
if (!method.equals("GET")) {
|
||||
methodNotAllowed(exchange, "GET");
|
||||
return;
|
||||
}
|
||||
send(exchange, 200, branding.json(), "application/json; charset=utf-8");
|
||||
}
|
||||
|
||||
private void brandingIcon(HttpExchange exchange, String origin) throws IOException {
|
||||
String method = exchange.getRequestMethod();
|
||||
if (!method.equals("GET")) {
|
||||
methodNotAllowed(exchange, "GET");
|
||||
return;
|
||||
}
|
||||
AdminBranding.State current = branding.state();
|
||||
if (current.icon().length == 0) {
|
||||
redirect(exchange, PATH + "/logo.png");
|
||||
return;
|
||||
}
|
||||
exchange.getResponseHeaders().set("Content-Type", current.mime());
|
||||
exchange.sendResponseHeaders(200, current.icon().length);
|
||||
exchange.getResponseBody().write(current.icon());
|
||||
}
|
||||
|
||||
private void uploadBranding(HttpExchange exchange, String origin) throws IOException {
|
||||
String method = exchange.getRequestMethod();
|
||||
if (!method.equals("POST")) {
|
||||
methodNotAllowed(exchange, "POST");
|
||||
return;
|
||||
}
|
||||
Session current = authentication.session(exchange);
|
||||
if (current == null) {
|
||||
send(exchange, 401, "Sign in required", "text/plain; charset=utf-8");
|
||||
return;
|
||||
}
|
||||
String csrf = exchange.getRequestHeaders().getFirst("X-CSRF-Token");
|
||||
if (csrf == null || !MessageDigest.isEqual(current.csrf().getBytes(StandardCharsets.US_ASCII),
|
||||
csrf.getBytes(StandardCharsets.US_ASCII)) ||
|
||||
!AdminAuthentication.adminOriginAllowed(exchange, origin)) {
|
||||
send(exchange, 403, "Invalid admin request", "text/plain; charset=utf-8");
|
||||
return;
|
||||
}
|
||||
byte[] image = exchange.getRequestBody().readNBytes(AdminBranding.MAX_ICON_BYTES + 1);
|
||||
try {
|
||||
auditStart("branding-icon", "admin", exchange);
|
||||
branding.setIcon(image);
|
||||
auditOutcome("branding-icon", "admin",
|
||||
exchange.getRemoteAddress().getAddress().getHostAddress(), "succeeded");
|
||||
send(exchange, 200, branding.json(), "application/json; charset=utf-8");
|
||||
} catch (StoreException invalid) {
|
||||
auditOutcome("branding-icon", "admin",
|
||||
exchange.getRemoteAddress().getAddress().getHostAddress(), invalid.code);
|
||||
send(exchange, invalid.status, invalid.getMessage(), "text/plain; charset=utf-8");
|
||||
} catch (IOException error) {
|
||||
auditOutcome("branding-icon", "admin",
|
||||
exchange.getRemoteAddress().getAddress().getHostAddress(), "IOError");
|
||||
send(exchange, 503, "Icon could not be saved", "text/plain; charset=utf-8");
|
||||
}
|
||||
}
|
||||
|
||||
private void performanceJson(HttpExchange exchange, String origin) throws IOException {
|
||||
String method = exchange.getRequestMethod();
|
||||
if (!method.equals("GET")) {
|
||||
methodNotAllowed(exchange, "GET");
|
||||
return;
|
||||
}
|
||||
if (authentication.session(exchange) == null) {
|
||||
redirect(exchange, PATH + "/login");
|
||||
return;
|
||||
}
|
||||
if (metrics == null) {
|
||||
send(exchange, 503, "Metrics unavailable", "text/plain; charset=utf-8");
|
||||
return;
|
||||
}
|
||||
send(exchange, 200, AdminPerformance.snapshot(metrics), "application/json; charset=utf-8");
|
||||
}
|
||||
|
||||
private void probe(HttpExchange exchange, String origin) throws IOException {
|
||||
String method = exchange.getRequestMethod();
|
||||
if (!method.equals("GET")) {
|
||||
methodNotAllowed(exchange, "GET");
|
||||
return;
|
||||
}
|
||||
if (authentication.session(exchange) == null) {
|
||||
redirect(exchange, PATH + "/login");
|
||||
return;
|
||||
}
|
||||
byte[] block = new byte[16 * 1024];
|
||||
int remaining = 1024 * 1024;
|
||||
exchange.getResponseHeaders().set("Content-Type", "application/octet-stream");
|
||||
exchange.sendResponseHeaders(200, remaining);
|
||||
try (OutputStream output = exchange.getResponseBody()) {
|
||||
while (remaining > 0) {
|
||||
int length = Math.min(block.length, remaining);
|
||||
output.write(block, 0, length);
|
||||
remaining -= length;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void performanceEvents(HttpExchange exchange, String origin) throws IOException {
|
||||
String method = exchange.getRequestMethod();
|
||||
if (!method.equals("GET")) {
|
||||
methodNotAllowed(exchange, "GET");
|
||||
return;
|
||||
}
|
||||
if (authentication.session(exchange) == null) {
|
||||
redirect(exchange, PATH + "/login");
|
||||
return;
|
||||
}
|
||||
if (metrics == null) {
|
||||
send(exchange, 503, "Metrics unavailable", "text/plain; charset=utf-8");
|
||||
return;
|
||||
}
|
||||
exchange.getResponseHeaders().set("Content-Type", "text/event-stream; charset=utf-8");
|
||||
exchange.getResponseHeaders().set("X-Accel-Buffering", "no");
|
||||
exchange.sendResponseHeaders(200, 0);
|
||||
try (OutputStream output = exchange.getResponseBody()) {
|
||||
for (int sample = 0; sample < 1800 && authentication.session(exchange) != null; sample++) {
|
||||
output.write(("data: " + AdminPerformance.snapshot(metrics) + "\n\n")
|
||||
.getBytes(StandardCharsets.UTF_8));
|
||||
output.flush();
|
||||
Thread.sleep(1000);
|
||||
}
|
||||
} catch (InterruptedException interrupted) {
|
||||
Thread.currentThread().interrupt();
|
||||
} catch (IOException disconnected) { return; }
|
||||
}
|
||||
|
||||
private void logout(HttpExchange exchange, String origin) throws IOException {
|
||||
String method = exchange.getRequestMethod();
|
||||
if (!method.equals("POST")) {
|
||||
methodNotAllowed(exchange, "POST");
|
||||
return;
|
||||
}
|
||||
Session session = authentication.session(exchange);
|
||||
Map<String, String> form = readForm(exchange);
|
||||
if (session == null || !MessageDigest.isEqual(session.csrf().getBytes(StandardCharsets.US_ASCII),
|
||||
form.getOrDefault("csrf", "").getBytes(StandardCharsets.US_ASCII))) {
|
||||
send(exchange, 403, "Invalid sign-out request", "text/plain; charset=utf-8");
|
||||
return;
|
||||
}
|
||||
authentication.signOut(exchange);
|
||||
exchange.getResponseHeaders().add("Set-Cookie", authentication.cookie("", 0));
|
||||
redirect(exchange, PATH + "/login");
|
||||
}
|
||||
|
||||
private void overview(HttpExchange exchange, String origin) throws IOException {
|
||||
Session session = requireSession(exchange, "GET");
|
||||
if (session == null) return;
|
||||
operations.read(() -> {
|
||||
ObjectStorage.Limits limits = store.limits();
|
||||
String mode = store instanceof ClusterStore ? "Cluster" : "Disk";
|
||||
String status = store.ready() ? "Ready" : "Unavailable";
|
||||
List<ObjectStorage.Bucket> buckets;
|
||||
boolean bucketListAvailable;
|
||||
try {
|
||||
buckets = store.buckets();
|
||||
bucketListAvailable = true;
|
||||
} catch (IOException unavailable) {
|
||||
buckets = List.of();
|
||||
bucketListAvailable = false;
|
||||
}
|
||||
send(exchange, 200, AdminStatusPages.overviewPage(mode, status, limits.maxObjectBytes(), limits.maxTotalBytes(),
|
||||
buckets, bucketListAvailable, session.csrf()),
|
||||
"text/html; charset=utf-8");
|
||||
});
|
||||
}
|
||||
|
||||
private void performancePage(HttpExchange exchange, String origin) throws IOException {
|
||||
Session session = requireSession(exchange, "GET");
|
||||
if (session == null) return;
|
||||
send(exchange, 200, AdminStatusPages.performancePage(session.csrf()), "text/html; charset=utf-8");
|
||||
}
|
||||
|
||||
private void statusPage(HttpExchange exchange, String origin) throws IOException {
|
||||
String path = exchange.getRequestURI().getRawPath();
|
||||
Session session = requireSession(exchange, "GET");
|
||||
if (session == null) return;
|
||||
operations.read(() -> {
|
||||
send(exchange, 200, path.endsWith("/health") ? AdminStatusPages.healthPage(diskStore, store, session.csrf()) :
|
||||
AdminStatusPages.diagnosticsPage(diagnostics, session.csrf()), "text/html; charset=utf-8");
|
||||
});
|
||||
}
|
||||
|
||||
private void auditPage(HttpExchange exchange, String origin) throws IOException {
|
||||
Session session = requireSession(exchange, "GET");
|
||||
if (session == null) return;
|
||||
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 {
|
||||
Session session = requireSession(exchange, "GET");
|
||||
if (session == null) return;
|
||||
send(exchange, 200, AdminOperationsPages.jobsPage(jobs, session.csrf()), "text/html; charset=utf-8");
|
||||
}
|
||||
|
||||
private void clusterPage(HttpExchange exchange, String origin) throws IOException {
|
||||
Session session = requireSession(exchange, "GET");
|
||||
if (session == null) return;
|
||||
operations.read(() -> {
|
||||
send(exchange, 200, AdminOperationsPages.clusterPage(store, session.csrf()), "text/html; charset=utf-8");
|
||||
});
|
||||
}
|
||||
|
||||
private void jobReport(HttpExchange exchange, String origin) throws IOException {
|
||||
String method = exchange.getRequestMethod();
|
||||
String path = exchange.getRequestURI().getRawPath();
|
||||
if (!method.equals("GET")) {
|
||||
methodNotAllowed(exchange, "GET");
|
||||
return;
|
||||
}
|
||||
if (authentication.session(exchange) == null) {
|
||||
send(exchange, 401, "Sign in required", "text/plain; charset=utf-8");
|
||||
return;
|
||||
}
|
||||
String query = exchange.getRequestURI().getRawQuery();
|
||||
String id = query != null && query.matches("id=[A-Za-z0-9_-]{16}") ? query.substring(3) : "";
|
||||
try {
|
||||
if (path.endsWith(".json")) {
|
||||
AdminBulkJobs.Snapshot job = jobs.get(id);
|
||||
send(exchange, 200, AdminOperationsPages.jobJson(job), "application/json; charset=utf-8");
|
||||
} else {
|
||||
exchange.getResponseHeaders().set("Content-Disposition", "attachment; filename=objectstore-job.csv");
|
||||
send(exchange, 200, jobs.report(id), "text/csv; charset=utf-8");
|
||||
}
|
||||
} catch (StoreException error) {
|
||||
send(exchange, error.status, "Job not found", "text/plain; charset=utf-8");
|
||||
}
|
||||
}
|
||||
|
||||
private void credentialsPage(HttpExchange exchange, String origin) throws IOException {
|
||||
Session session = requireSession(exchange, "GET");
|
||||
if (session == null) return;
|
||||
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 {
|
||||
String method = exchange.getRequestMethod();
|
||||
if (!method.equals("GET")) {
|
||||
methodNotAllowed(exchange, "GET");
|
||||
return;
|
||||
}
|
||||
if (authentication.session(exchange) == null) {
|
||||
redirect(exchange, PATH + "/login");
|
||||
return;
|
||||
}
|
||||
operations.read(() -> {
|
||||
try { AdminFileTransfer.download(store, exchange); }
|
||||
catch (StoreException error) {
|
||||
if (exchange.getResponseCode() <= 0)
|
||||
send(exchange, error.status, error.getMessage(), "text/plain; charset=utf-8");
|
||||
} catch (IOException error) {
|
||||
if (exchange.getResponseCode() <= 0)
|
||||
send(exchange, 503, "Download failed; storage is unavailable", "text/plain; charset=utf-8");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void upload(HttpExchange exchange, String origin) throws IOException {
|
||||
String method = exchange.getRequestMethod();
|
||||
if (!method.equals("POST")) {
|
||||
methodNotAllowed(exchange, "POST");
|
||||
return;
|
||||
}
|
||||
Session session = authentication.session(exchange);
|
||||
if (session == null) {
|
||||
send(exchange, 401, "Sign in again before uploading", "text/plain; charset=utf-8");
|
||||
return;
|
||||
}
|
||||
String token = exchange.getRequestHeaders().getFirst("X-ObjectStore-CSRF");
|
||||
if (token == null || !MessageDigest.isEqual(session.csrf().getBytes(StandardCharsets.US_ASCII),
|
||||
token.getBytes(StandardCharsets.US_ASCII)) ||
|
||||
!AdminAuthentication.adminOriginAllowed(exchange, origin)) {
|
||||
send(exchange, 403, "Invalid upload request", "text/plain; charset=utf-8");
|
||||
return;
|
||||
}
|
||||
operations.read(() -> {
|
||||
try {
|
||||
auditStart("upload-object", "object", exchange);
|
||||
String destination = AdminFileTransfer.upload(store, exchange);
|
||||
auditOutcome("upload-object", destination,
|
||||
exchange.getRemoteAddress().getAddress().getHostAddress(), "succeeded");
|
||||
exchange.getResponseHeaders().set("Location", destination);
|
||||
send(exchange, 201, "Uploaded", "text/plain; charset=utf-8");
|
||||
} catch (StoreException error) {
|
||||
auditOutcome("upload-object", "object",
|
||||
exchange.getRemoteAddress().getAddress().getHostAddress(), error.code);
|
||||
send(exchange, error.status, error.getMessage(), "text/plain; charset=utf-8");
|
||||
} catch (IOException error) {
|
||||
auditOutcome("upload-object", "object",
|
||||
exchange.getRemoteAddress().getAddress().getHostAddress(), "IOError");
|
||||
send(exchange, 503, "Upload failed; storage is unavailable", "text/plain; charset=utf-8");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void action(HttpExchange exchange, String origin) throws IOException {
|
||||
String path = exchange.getRequestURI().getRawPath();
|
||||
Session session = requireSession(exchange, "POST");
|
||||
if (session == null) return;
|
||||
Map<String, String> form = readForm(exchange);
|
||||
if (!MessageDigest.isEqual(session.csrf().getBytes(StandardCharsets.US_ASCII),
|
||||
form.getOrDefault("csrf", "").getBytes(StandardCharsets.US_ASCII))) {
|
||||
send(exchange, 403, "Invalid admin request", "text/plain; charset=utf-8");
|
||||
return;
|
||||
}
|
||||
if (!AdminAuthentication.adminOriginAllowed(exchange, origin)) {
|
||||
send(exchange, 403, "Invalid origin", "text/plain; charset=utf-8");
|
||||
return;
|
||||
}
|
||||
String action = path.substring((PATH + "/action/").length());
|
||||
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);
|
||||
} else {
|
||||
operations.read(apply);
|
||||
}
|
||||
} catch (StoreException busy) {
|
||||
send(exchange, busy.status, actionErrorPage(action, form, session.csrf(), busy),
|
||||
"text/html; charset=utf-8");
|
||||
}
|
||||
}
|
||||
|
||||
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();
|
||||
String target = auditTarget(form);
|
||||
try {
|
||||
if ((action.equals("rename-bucket") || action.equals("delete-bucket")) && jobs.hasActiveJob())
|
||||
throw new StoreException(409, "OperationAborted", "Wait for or cancel the active bulk job before renaming or deleting a bucket");
|
||||
auditStart(action, target, exchange);
|
||||
switch (action) {
|
||||
case "access-check" -> checkAccess(exchange, session, action, form);
|
||||
case "bulk-start" -> startBulkJob(exchange, session, action, form);
|
||||
case "bulk-cancel" -> cancelBulkJob(exchange, session, action, form);
|
||||
case "branding-name" -> saveBrandingName(exchange, session, action, form);
|
||||
case "branding-reset" -> resetBranding(exchange, session, action, form);
|
||||
case "default-theme" -> saveTheme(exchange, session, action, form);
|
||||
case "create-key", "update-key", "enable-key", "disable-key", "delete-key" ->
|
||||
changeCredentials(exchange, session, action, form);
|
||||
default -> changeStorage(exchange, session, action, form);
|
||||
}
|
||||
} catch (StoreException error) {
|
||||
auditOutcome(action, target, peer, error.code);
|
||||
send(exchange, error.status, actionErrorPage(action, form, session.csrf(), error),
|
||||
"text/html; charset=utf-8");
|
||||
} catch (IOException error) {
|
||||
auditOutcome(action, target, peer, "IOError");
|
||||
send(exchange, 503, page(consoleHeader(session.csrf()) +
|
||||
"<h2>Storage unavailable</h2><p class=error>Change was not saved.</p>"),
|
||||
"text/html; charset=utf-8");
|
||||
}
|
||||
}
|
||||
|
||||
private void checkAccess(HttpExchange exchange, Session session, String action,
|
||||
Map<String, String> form) throws IOException {
|
||||
String peer = exchange.getRemoteAddress().getAddress().getHostAddress();
|
||||
String target = auditTarget(form);
|
||||
AccessCheck check = accessCheck;
|
||||
if (check == null) throw new StoreException(503, "ServiceUnavailable", "Access checker unavailable");
|
||||
AdminAccessCheck.Result result = check.check(form.get("principal"),
|
||||
form.get("operation"), form.get("bucket"), form.get("key"));
|
||||
auditOutcome(action, target, peer, result.allowed() ? "allowed" : "denied");
|
||||
send(exchange, 200, AdminOperationsPages.auditPage(identities, diagnostics, audit, session.csrf(), result, form), "text/html; charset=utf-8");
|
||||
}
|
||||
|
||||
private void startBulkJob(HttpExchange exchange, Session session, String action,
|
||||
Map<String, String> form) throws IOException {
|
||||
String peer = exchange.getRemoteAddress().getAddress().getHostAddress();
|
||||
String target = auditTarget(form);
|
||||
String operation = form.getOrDefault("operation", "");
|
||||
if (operation.equals("delete") && !form.getOrDefault("bucket", "").equals(form.get("confirm")))
|
||||
throw new StoreException(400, "InvalidArgument", "Type the source bucket to confirm deletion");
|
||||
AdminBulkJobs.Spec spec = new AdminBulkJobs.Spec(operation,
|
||||
form.getOrDefault("bucket", ""), form.getOrDefault("prefix", ""),
|
||||
form.getOrDefault("targetBucket", ""), form.getOrDefault("targetPrefix", ""),
|
||||
form.getOrDefault("tag", ""), form.getOrDefault("value", ""));
|
||||
AdminBulkJobs.Snapshot job = jobs.start(spec);
|
||||
auditOutcome(action, target, peer, "started:" + job.id());
|
||||
redirect(exchange, PATH + "/jobs");
|
||||
}
|
||||
|
||||
private void cancelBulkJob(HttpExchange exchange, Session session, String action,
|
||||
Map<String, String> form) throws IOException {
|
||||
String peer = exchange.getRemoteAddress().getAddress().getHostAddress();
|
||||
String target = auditTarget(form);
|
||||
jobs.cancel(form.getOrDefault("id", ""));
|
||||
auditOutcome(action, "job:" + form.getOrDefault("id", ""), peer, "requested");
|
||||
redirect(exchange, PATH + "/jobs");
|
||||
}
|
||||
|
||||
private void saveBrandingName(HttpExchange exchange, Session session, String action,
|
||||
Map<String, String> form) throws IOException {
|
||||
String peer = exchange.getRemoteAddress().getAddress().getHostAddress();
|
||||
String target = auditTarget(form);
|
||||
branding.setName(form.get("displayName"));
|
||||
auditOutcome(action, target, peer, "succeeded");
|
||||
redirect(exchange, PATH + "/settings");
|
||||
}
|
||||
|
||||
private void resetBranding(HttpExchange exchange, Session session, String action,
|
||||
Map<String, String> form) throws IOException {
|
||||
String peer = exchange.getRemoteAddress().getAddress().getHostAddress();
|
||||
String target = auditTarget(form);
|
||||
branding.reset();
|
||||
auditOutcome(action, target, peer, "succeeded");
|
||||
redirect(exchange, PATH + "/settings");
|
||||
}
|
||||
|
||||
private void saveTheme(HttpExchange exchange, Session session, String action,
|
||||
Map<String, String> form) throws IOException {
|
||||
String peer = exchange.getRemoteAddress().getAddress().getHostAddress();
|
||||
String target = auditTarget(form);
|
||||
branding.setDefaultTheme(form.get("defaultTheme"));
|
||||
auditOutcome(action, target, peer, "succeeded");
|
||||
redirect(exchange, PATH + "/settings");
|
||||
}
|
||||
|
||||
private void changeCredentials(HttpExchange exchange, Session session, String action,
|
||||
Map<String, String> form) throws IOException {
|
||||
String peer = exchange.getRemoteAddress().getAddress().getHostAddress();
|
||||
String target = auditTarget(form);
|
||||
ManagedCredentials managed = managedCredentials;
|
||||
if (managed == null)
|
||||
throw new StoreException(409, "InvalidRequest", "Managed keys are not configured");
|
||||
ManagedCredentials.Key created = null;
|
||||
if (action.equals("create-key")) {
|
||||
String bucket = form.getOrDefault("bucket", "");
|
||||
store.bucket(bucket);
|
||||
created = managed.create(bucket, form.getOrDefault("prefix", ""), keyPermissions(form));
|
||||
} else {
|
||||
String id = form.getOrDefault("id", "");
|
||||
if (!id.matches("[A-Z0-9]{32}") || !id.equals(form.get("confirm")))
|
||||
throw new StoreException(400, "InvalidArgument", "Type the access key ID to confirm");
|
||||
switch (action) {
|
||||
case "update-key" -> {
|
||||
String bucket = form.getOrDefault("bucket", "");
|
||||
store.bucket(bucket);
|
||||
managed.update(id, bucket, form.getOrDefault("prefix", ""), keyPermissions(form));
|
||||
}
|
||||
case "enable-key" -> managed.setEnabled(id, true);
|
||||
case "disable-key" -> managed.setEnabled(id, false);
|
||||
case "delete-key" -> managed.remove(id);
|
||||
default -> throw new IllegalStateException();
|
||||
}
|
||||
}
|
||||
refreshCredentials.run();
|
||||
auditOutcome(action, target, peer, "succeeded");
|
||||
System.out.println("ObjectStore admin action " + action + " from " +
|
||||
exchange.getRemoteAddress().getAddress().getHostAddress());
|
||||
if (created == null) redirect(exchange, PATH + "/credentials");
|
||||
else send(exchange, 200, AdminSettingsPages.credentialsPage(managedCredentials, store, session.csrf(), created),
|
||||
"text/html; charset=utf-8");
|
||||
}
|
||||
|
||||
private void changeStorage(HttpExchange exchange, Session session, String action,
|
||||
Map<String, String> form) throws IOException {
|
||||
String peer = exchange.getRemoteAddress().getAddress().getHostAddress();
|
||||
String target = auditTarget(form);
|
||||
String destination = action.equals("edit-object") ?
|
||||
AdminTextEditor.save(store, form) :
|
||||
AdminActions.apply(store, action, form, identities, managedCredentials);
|
||||
BucketActivity activity = bucketActivity;
|
||||
if (activity != null) {
|
||||
String bucket = form.get("bucket");
|
||||
if (action.equals("rename-bucket")) activity.rename(bucket, form.get("newName"));
|
||||
else if (action.equals("delete-bucket")) activity.remove(bucket);
|
||||
}
|
||||
System.out.println("ObjectStore admin action " + action + " from " +
|
||||
exchange.getRemoteAddress().getAddress().getHostAddress());
|
||||
auditOutcome(action, target, peer, "succeeded");
|
||||
redirect(exchange, destination);
|
||||
}
|
||||
|
||||
private void browse(HttpExchange exchange, String origin) throws IOException {
|
||||
String path = exchange.getRequestURI().getRawPath();
|
||||
Session session = requireSession(exchange, "GET");
|
||||
if (session == null) return;
|
||||
operations.read(() -> {
|
||||
try {
|
||||
String body = path.equals(PATH + "/buckets") ?
|
||||
AdminBrowser.index(store, exchange.getRequestURI().getRawQuery(), session.csrf()) :
|
||||
path.equals(PATH + "/bucket") ?
|
||||
AdminBrowser.bucket(store, exchange.getRequestURI().getRawQuery(), session.csrf(),
|
||||
null, bucketActivity) :
|
||||
path.equals(PATH + "/versions") ?
|
||||
AdminBrowser.versions(store, exchange.getRequestURI().getRawQuery(), session.csrf()) :
|
||||
AdminBrowser.object(store, exchange.getRequestURI().getRawQuery(), session.csrf());
|
||||
send(exchange, 200, page(body, true), "text/html; charset=utf-8");
|
||||
} catch (StoreException error) {
|
||||
send(exchange, error.status, page(consoleHeader(session.csrf()) +
|
||||
"<div class=crumbs><a href='" + PATH + "/buckets'>Buckets</a></div>" +
|
||||
"<h2>Could not open this view</h2><p class=muted>" + escape(error.getMessage()) + "</p>"),
|
||||
"text/html; charset=utf-8");
|
||||
} catch (IOException unavailable) {
|
||||
send(exchange, 503, page(consoleHeader(session.csrf()) +
|
||||
"<h2>Storage unavailable</h2><p class=muted>Try again when the service is ready.</p>"),
|
||||
"text/html; charset=utf-8");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void settings(HttpExchange exchange, String origin) throws IOException {
|
||||
String method = exchange.getRequestMethod();
|
||||
if (!method.equals("GET")) {
|
||||
methodNotAllowed(exchange, "GET");
|
||||
return;
|
||||
}
|
||||
Session session = authentication.session(exchange);
|
||||
if (session == null) redirect(exchange, PATH + "/login");
|
||||
else send(exchange, 200, page(AdminSettingsPages.settingsPage(session.csrf()), true), "text/html; charset=utf-8");
|
||||
}
|
||||
|
||||
private void login(HttpExchange exchange) throws IOException {
|
||||
Map<String, String> form = readForm(exchange);
|
||||
if (!authentication.consumeLoginToken(form.get("csrf"))) {
|
||||
send(exchange, 403, loginPage("Sign-in expired. Reload the page and try again.", authentication.issueLoginToken()),
|
||||
"text/html; charset=utf-8");
|
||||
return;
|
||||
}
|
||||
String password = form.get("password");
|
||||
String client = exchange.getRemoteAddress().getAddress().getHostAddress();
|
||||
if (authentication.throttled(client)) {
|
||||
auditOutcome("login", "admin", client, "throttled");
|
||||
exchange.getResponseHeaders().set("Retry-After", "300");
|
||||
send(exchange, 429, loginPage("Too many attempts. Try again in five minutes.", authentication.issueLoginToken()),
|
||||
"text/html; charset=utf-8");
|
||||
return;
|
||||
}
|
||||
if (!authentication.matchesPassword(password)) {
|
||||
authentication.failed(client);
|
||||
auditOutcome("login", "admin", client, "denied");
|
||||
send(exchange, 401, loginPage("Invalid password", authentication.issueLoginToken()), "text/html; charset=utf-8");
|
||||
return;
|
||||
}
|
||||
String token = authentication.signIn(client);
|
||||
exchange.getResponseHeaders().add("Set-Cookie", authentication.cookie(token, 1800));
|
||||
auditOutcome("login", "admin", client, "succeeded");
|
||||
redirect(exchange, PATH + "/overview");
|
||||
}
|
||||
|
||||
private String actionErrorPage(String action, Map<String, String> form, String csrf,
|
||||
StoreException error) {
|
||||
try {
|
||||
if (action.equals("policy") && form.containsKey("bucket")) {
|
||||
String query = "name=" + AdminBrowser.encoded(form.get("bucket"));
|
||||
return page(AdminBrowser.bucket(store, query, csrf,
|
||||
new AdminBrowser.EditorDraft(form.getOrDefault("policy", ""), error.getMessage()),
|
||||
bucketActivity), true);
|
||||
}
|
||||
if (action.equals("edit-object") && form.containsKey("bucket") && form.containsKey("key")) {
|
||||
String query = "bucket=" + AdminBrowser.encoded(form.get("bucket")) +
|
||||
"&key=" + AdminBrowser.encoded(form.get("key"));
|
||||
return page(AdminBrowser.object(store, query, csrf,
|
||||
new AdminBrowser.EditorDraft(form.getOrDefault("content", ""), error.getMessage())), true);
|
||||
}
|
||||
} catch (IOException | IllegalArgumentException | StoreException ignored) {
|
||||
}
|
||||
return page(consoleHeader(csrf) +
|
||||
"<h2>Change was not saved</h2><p class=error>" + escape(error.getMessage()) +
|
||||
"</p><p><a href='" + PATH + "/buckets'>Return to buckets</a> · " +
|
||||
"<a href='" + PATH + "/credentials'>Return to access keys</a></p>");
|
||||
}
|
||||
|
||||
private static String loginPage(String error, String csrf) {
|
||||
return page("<div class=login><div class=login-card><div class=login-brand>" +
|
||||
AdminLayout.logoMark() + "<strong>ObjectStore</strong></div><h1>Admin console</h1>" +
|
||||
"<p class=muted>Sign in to view this service.</p>" +
|
||||
(error.isEmpty() ? "" : "<p role=alert class=error>" + error + "</p>") +
|
||||
"<form method=post action='" + PATH + "/login'>" +
|
||||
"<input type=hidden name=csrf value='" + csrf + "'>" +
|
||||
"<label for=password>Admin password</label><input id=password name=password type=password " +
|
||||
"autocomplete=current-password required autofocus><button type=submit>Sign in</button>" +
|
||||
"</form></div></div>");
|
||||
}
|
||||
|
||||
private static String auditTarget(Map<String, String> form) {
|
||||
String bucket = form.getOrDefault("bucket", "");
|
||||
String key = form.getOrDefault("key", "");
|
||||
String id = form.getOrDefault("id", "");
|
||||
if (!id.isEmpty()) return "key:" + id;
|
||||
if (!bucket.isEmpty()) return key.isEmpty() ? bucket : bucket + "/" + key;
|
||||
return "admin";
|
||||
}
|
||||
|
||||
private void auditOutcome(String action, String target, String peer, String reason) {
|
||||
try { audit.record(action, target, reason, peer); }
|
||||
catch (IOException error) { System.err.println("Admin audit write failed: " + error.getMessage()); }
|
||||
}
|
||||
|
||||
private void auditStart(String action, String target, HttpExchange exchange) throws IOException {
|
||||
audit.record(action, target, "started",
|
||||
exchange.getRemoteAddress().getAddress().getHostAddress());
|
||||
}
|
||||
|
||||
private static Set<String> keyPermissions(Map<String, String> form) {
|
||||
Set<String> permissions = new java.util.HashSet<>();
|
||||
for (String permission : List.of("read", "write", "list"))
|
||||
if (form.containsKey(permission)) permissions.add(permission);
|
||||
return permissions;
|
||||
}
|
||||
|
||||
static String page(String content, boolean widgets) {
|
||||
return AdminLayout.page(content, widgets);
|
||||
}
|
||||
|
||||
private static String page(String content) {
|
||||
return AdminLayout.page(content);
|
||||
}
|
||||
|
||||
static String consoleHeader(String csrf) {
|
||||
return AdminLayout.consoleHeader(csrf);
|
||||
}
|
||||
|
||||
static String icon(String name) {
|
||||
return AdminLayout.icon(name);
|
||||
}
|
||||
|
||||
static String escape(String value) {
|
||||
return AdminLayout.escape(value);
|
||||
}
|
||||
|
||||
static String formatBytes(long bytes) {
|
||||
return AdminLayout.formatBytes(bytes);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import com.sun.net.httpserver.HttpExchange;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
final class AdminFileTransfer {
|
||||
private AdminFileTransfer() { }
|
||||
|
||||
static String upload(ObjectStorage store, HttpExchange exchange) throws IOException {
|
||||
Map<String, String> query = AdminBrowser.query(exchange.getRequestURI().getRawQuery(),
|
||||
Set.of("bucket", "key", "overwrite"));
|
||||
String bucket = required(query, "bucket", 63);
|
||||
String key = required(query, "key", 1024);
|
||||
boolean overwrite = "1".equals(query.get("overwrite"));
|
||||
if (query.containsKey("overwrite") && !overwrite)
|
||||
throw new StoreException(400, "InvalidArgument", "Invalid overwrite option");
|
||||
ObjectStorage.Bucket current = store.bucket(bucket);
|
||||
if (overwrite && current.versioning() != ObjectStorage.VersioningState.ENABLED)
|
||||
throw new StoreException(409, "InvalidBucketState", "Enable versioning before replacing an object");
|
||||
String lengthHeader = exchange.getRequestHeaders().getFirst("Content-Length");
|
||||
long length;
|
||||
try { length = Long.parseLong(lengthHeader); }
|
||||
catch (NumberFormatException | NullPointerException error) {
|
||||
throw new StoreException(411, "MissingContentLength", "Upload size is required");
|
||||
}
|
||||
if (length < 0 || length > store.limits().maxObjectBytes())
|
||||
throw new StoreException(413, "EntityTooLarge", "File exceeds the configured object limit");
|
||||
String type = exchange.getRequestHeaders().getFirst("Content-Type");
|
||||
if (type == null || type.isBlank()) type = "application/octet-stream";
|
||||
if (type.length() > 255 || type.chars().anyMatch(character -> character < 32 || character == 127))
|
||||
throw new StoreException(400, "InvalidArgument", "Invalid content type");
|
||||
store.put(bucket, key, exchange.getRequestBody(), length, null, null, !overwrite, type);
|
||||
return AdminConsole.PATH + "/object?bucket=" + AdminBrowser.encoded(bucket) +
|
||||
"&key=" + AdminBrowser.encoded(key);
|
||||
}
|
||||
|
||||
static void download(ObjectStorage store, HttpExchange exchange) throws IOException {
|
||||
Map<String, String> query = AdminBrowser.query(exchange.getRequestURI().getRawQuery(),
|
||||
Set.of("bucket", "key", "version"));
|
||||
String bucket = required(query, "bucket", 63);
|
||||
String key = required(query, "key", 1024);
|
||||
String version = query.get("version");
|
||||
if (version != null && (version.isEmpty() || version.length() > 256))
|
||||
throw new StoreException(400, "InvalidArgument", "Invalid object version");
|
||||
try (ObjectStorage.OpenObject opened = store.open(bucket, key, version)) {
|
||||
String filename = key.substring(key.lastIndexOf('/') + 1);
|
||||
if (filename.isEmpty()) filename = "object";
|
||||
String encoded = java.net.URLEncoder.encode(filename, StandardCharsets.UTF_8)
|
||||
.replace("+", "%20").replace("*", "%2A");
|
||||
exchange.getResponseHeaders().set("Content-Type", "application/octet-stream");
|
||||
exchange.getResponseHeaders().set("Content-Disposition",
|
||||
"attachment; filename=\"download\"; filename*=UTF-8''" + encoded);
|
||||
exchange.sendResponseHeaders(200, opened.metadata().length());
|
||||
opened.stream().transferTo(exchange.getResponseBody());
|
||||
}
|
||||
}
|
||||
|
||||
private static String required(Map<String, String> query, String name, int maxLength) {
|
||||
String value = query.get(name);
|
||||
if (value == null || value.isEmpty() || value.getBytes(StandardCharsets.UTF_8).length > maxLength)
|
||||
throw new StoreException(400, "InvalidArgument", "Invalid object path");
|
||||
return value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import com.sun.net.httpserver.HttpExchange;
|
||||
import java.io.IOException;
|
||||
import java.net.URLDecoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Map;
|
||||
|
||||
final class AdminHttp {
|
||||
private static final int MAX_FORM_BYTES = 128 * 1024;
|
||||
|
||||
private AdminHttp() { }
|
||||
|
||||
static Map<String, String> readForm(HttpExchange exchange) throws IOException {
|
||||
String contentType = exchange.getRequestHeaders().getFirst("Content-Type");
|
||||
if (contentType == null || !contentType.split(";", 2)[0].trim()
|
||||
.equalsIgnoreCase("application/x-www-form-urlencoded")) {
|
||||
throw new StoreException(415, "InvalidRequest", "Expected a form submission");
|
||||
}
|
||||
byte[] body = exchange.getRequestBody().readNBytes(MAX_FORM_BYTES + 1);
|
||||
if (body.length > MAX_FORM_BYTES) {
|
||||
throw new StoreException(413, "InvalidRequest", "Form is too large");
|
||||
}
|
||||
Map<String, String> values = new java.util.HashMap<>();
|
||||
try {
|
||||
for (String field : new String(body, StandardCharsets.UTF_8).split("&", -1)) {
|
||||
int split = field.indexOf('=');
|
||||
if (split < 0) continue;
|
||||
String key = URLDecoder.decode(field.substring(0, split), StandardCharsets.UTF_8);
|
||||
String value = URLDecoder.decode(field.substring(split + 1), StandardCharsets.UTF_8);
|
||||
if (values.putIfAbsent(key, value) != null)
|
||||
throw new IllegalArgumentException("Duplicate form field");
|
||||
}
|
||||
} catch (IllegalArgumentException error) {
|
||||
throw new StoreException(400, "InvalidRequest", "Invalid form submission");
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
static void securityHeaders(HttpExchange exchange) {
|
||||
exchange.getResponseHeaders().set("Cache-Control", "no-store");
|
||||
exchange.getResponseHeaders().set("Content-Security-Policy",
|
||||
"default-src 'none'; style-src 'self'; style-src-elem 'self' 'unsafe-inline'; " +
|
||||
"style-src-attr 'none'; script-src 'self'; img-src 'self' data:; connect-src 'self'; form-action 'self'; " +
|
||||
"frame-ancestors 'none'; base-uri 'none'");
|
||||
exchange.getResponseHeaders().set("Referrer-Policy", "no-referrer");
|
||||
exchange.getResponseHeaders().set("X-Frame-Options", "DENY");
|
||||
exchange.getResponseHeaders().set("X-Content-Type-Options", "nosniff");
|
||||
}
|
||||
|
||||
static void methodNotAllowed(HttpExchange exchange, String methods) throws IOException {
|
||||
exchange.getResponseHeaders().set("Allow", methods);
|
||||
send(exchange, 405, "Method not allowed", "text/plain; charset=utf-8");
|
||||
}
|
||||
|
||||
static void redirect(HttpExchange exchange, String path) throws IOException {
|
||||
exchange.getResponseHeaders().set("Location", path);
|
||||
exchange.sendResponseHeaders(303, -1);
|
||||
}
|
||||
|
||||
static void send(HttpExchange exchange, int status, String body, String contentType) throws IOException {
|
||||
byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
|
||||
exchange.getResponseHeaders().set("Content-Type", contentType);
|
||||
exchange.sendResponseHeaders(status, bytes.length);
|
||||
exchange.getResponseBody().write(bytes);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import java.util.Set;
|
||||
import static cloud.lunarsky.store.AdminConsole.PATH;
|
||||
|
||||
final class AdminLayout {
|
||||
static final Set<String> ICONS = Set.of("folder", "file", "refresh", "code-file",
|
||||
"search", "chevron-right", "objects", "bucket", "access-key", "activity", "sliders",
|
||||
"plus", "upload", "download", "version-history", "edit", "trash");
|
||||
|
||||
private AdminLayout() { }
|
||||
|
||||
static String page(String content) {
|
||||
return page(content, false);
|
||||
}
|
||||
|
||||
static String page(String content, boolean widgets) {
|
||||
return page(content, widgets, false);
|
||||
}
|
||||
|
||||
static String page(String content, boolean widgets, boolean performance) {
|
||||
boolean workspace = content.startsWith("<!--admin-shell-->");
|
||||
return "<!doctype html><html lang=en><head><meta charset=utf-8>" +
|
||||
"<meta name=viewport content='width=device-width,initial-scale=1'><title>ObjectStore admin</title>" +
|
||||
"<link rel=stylesheet href='" + PATH + "/style.css'>" +
|
||||
(widgets || workspace ? "<script defer src='" + PATH + "/biscuit.js'></script>" : "") +
|
||||
"<script defer src='" + PATH + "/workspace.js'></script>" +
|
||||
(performance ? "<script defer src='" + PATH + "/performance.js'></script>" : "") +
|
||||
"</head><body data-admin-theme=deep-dark" + (workspace ? " class=workspace-body" : "") + "><main>" +
|
||||
content + (workspace ? "</div><biscuit-toastview id=admin-toast theme=deep-dark></biscuit-toastview>" +
|
||||
"<biscuit-footerview theme=deep-dark brand='ObjectStore admin' " +
|
||||
"description='Private service controls' copyright='ObjectStore v" + Version.VALUE + "'>" +
|
||||
"<a href='https://lunarsky.cloud/objectstore/' data-footer-group=Resources>Documentation</a>" +
|
||||
"</biscuit-footerview></div></div>" : "") + "</main></body></html>";
|
||||
}
|
||||
|
||||
static String consoleHeader(String csrf) {
|
||||
return "<!--admin-shell--><div class=app-shell>" +
|
||||
"<biscuit-sidebarview theme=deep-dark label='Navigation' aria-label='Admin sections' sticky>" +
|
||||
"<div class=sidebar-brand>" + logoMark() +
|
||||
"<span><strong>ObjectStore</strong><small>ADMIN · v" + Version.VALUE + "</small></span></div>" +
|
||||
"<div class=sidebar-group>WORKSPACE</div>" +
|
||||
navLink("overview", "objects", "Overview") +
|
||||
navLink("buckets", "bucket", "Buckets") +
|
||||
"<div class=sidebar-group>OPERATIONS</div>" +
|
||||
navLink("credentials", "access-key", "Access keys") +
|
||||
navLink("performance", "activity", "Performance") +
|
||||
navLink("diagnostics", "search", "Diagnostics") +
|
||||
navLink("health", "refresh", "Health & recovery") +
|
||||
navLink("audit", "access-key", "Audit & access") +
|
||||
navLink("jobs", "refresh", "Bulk jobs") +
|
||||
navLink("cluster", "objects", "Cluster") +
|
||||
"<div class=sidebar-group>PREFERENCES</div>" +
|
||||
navLink("settings", "sliders", "Settings") +
|
||||
"</biscuit-sidebarview><div class=workspace>" +
|
||||
"<biscuit-pageloaderview id=page-loading mode=page theme=deep-dark open " +
|
||||
"message='Loading page…'><div class=loader-skeletons>" +
|
||||
"<biscuit-skeletonview width=220px height=18px></biscuit-skeletonview>" +
|
||||
"<biscuit-skeletonview width=160px height=12px></biscuit-skeletonview>" +
|
||||
"</div></biscuit-pageloaderview>" +
|
||||
"<biscuit-navbarview theme=deep-dark sticky brand='ObjectStore admin' brand-href='" + PATH +
|
||||
"/overview' aria-label='Admin toolbar'>" +
|
||||
mobileNavLink("overview", "objects", "Overview") +
|
||||
mobileNavLink("buckets", "bucket", "Buckets") +
|
||||
mobileNavLink("credentials", "access-key", "Access keys") +
|
||||
mobileNavLink("performance", "activity", "Performance") +
|
||||
mobileNavLink("diagnostics", "search", "Diagnostics") +
|
||||
mobileNavLink("health", "refresh", "Health & recovery") +
|
||||
mobileNavLink("audit", "access-key", "Audit & access") +
|
||||
mobileNavLink("jobs", "refresh", "Bulk jobs") +
|
||||
mobileNavLink("cluster", "objects", "Cluster") +
|
||||
mobileNavLink("settings", "sliders", "Settings") +
|
||||
"<form slot=actions method=post action='" + PATH +
|
||||
"/logout'><input type=hidden name=csrf value='" + csrf +
|
||||
"'><button type=submit>Sign out</button></form></biscuit-navbarview>" +
|
||||
"<div class=workspace-content>";
|
||||
}
|
||||
|
||||
static String navLink(String path, String icon, String label) {
|
||||
return "<a class=sidebar-link href='" + PATH + "/" + path + "'><img alt='' src='" + PATH +
|
||||
"/icons/" + icon + ".svg' width=18 height=18><span>" + label + "</span></a>";
|
||||
}
|
||||
|
||||
static String icon(String name) {
|
||||
if (!ICONS.contains(name)) throw new IllegalArgumentException("Unknown admin icon");
|
||||
return "<img class=action-icon src='" + PATH + "/icons/" + name +
|
||||
".svg' alt='' width=16 height=16>";
|
||||
}
|
||||
|
||||
static String mobileNavLink(String path, String icon, String label) {
|
||||
return "<a class=mobile-nav-link href='" + PATH + "/" + path +
|
||||
"'><img alt='' src='" + PATH + "/icons/" + icon +
|
||||
".svg' width=16 height=16>" + label + "</a>";
|
||||
}
|
||||
|
||||
static String logoMark() {
|
||||
return "<span class=mark aria-hidden=true><img src='" + PATH +
|
||||
"/logo.png' alt='' width=56 height=56></span>";
|
||||
}
|
||||
|
||||
static String escape(String value) {
|
||||
return value.replace("&", "&").replace("<", "<").replace(">", ">")
|
||||
.replace("\"", """).replace("'", "'");
|
||||
}
|
||||
|
||||
static String formatBytes(long bytes) {
|
||||
if (bytes == Long.MAX_VALUE) return "Unlimited";
|
||||
if (bytes < 1024) return bytes + " B";
|
||||
String[] units = { "KiB", "MiB", "GiB", "TiB", "PiB", "EiB" };
|
||||
double value = bytes;
|
||||
int unit = -1;
|
||||
do {
|
||||
value /= 1024;
|
||||
unit++;
|
||||
} while (value >= 1024 && unit < units.length - 1);
|
||||
return String.format(java.util.Locale.ROOT, "%.1f %s", value, units[unit]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import static cloud.lunarsky.store.AdminBrowser.*;
|
||||
import static cloud.lunarsky.store.AdminBrowserView.*;
|
||||
import static cloud.lunarsky.store.AdminBucketForms.*;
|
||||
|
||||
final class AdminObjectPages {
|
||||
private static final int PAGE_SIZE = 50;
|
||||
|
||||
private AdminObjectPages() { }
|
||||
|
||||
static String object(ObjectStorage store, String rawQuery, String csrf) throws IOException {
|
||||
return object(store, rawQuery, csrf, null);
|
||||
}
|
||||
|
||||
static String object(ObjectStorage store, String rawQuery, String csrf, AdminBrowser.EditorDraft contentDraft)
|
||||
throws IOException {
|
||||
Map<String, String> query = query(rawQuery, Set.of("bucket", "key", "version"));
|
||||
String bucketName = required(query, "bucket", 255);
|
||||
String key = required(query, "key", 1024);
|
||||
String version = query.get("version");
|
||||
if (version != null && (version.isEmpty() || version.length() > 256)) throw invalidQuery();
|
||||
ObjectStorage.Bucket bucket = store.bucket(bucketName);
|
||||
ObjectStorage.Metadata meta;
|
||||
String text = null;
|
||||
String previewError = null;
|
||||
try (ObjectStorage.OpenObject opened = store.open(bucketName, key, version)) {
|
||||
meta = opened.metadata();
|
||||
if (AdminTextEditor.supports(meta)) {
|
||||
try { text = AdminTextEditor.read(opened); }
|
||||
catch (StoreException error) { previewError = error.getMessage(); }
|
||||
}
|
||||
}
|
||||
int slash = key.lastIndexOf('/');
|
||||
String prefix = slash < 0 ? "" : key.substring(0, slash + 1);
|
||||
StringBuilder html = new StringBuilder(AdminConsole.consoleHeader(csrf));
|
||||
html.append(breadcrumbs(bucketName, prefix))
|
||||
.append("<div class=intro><div><h2 class=name-cell>")
|
||||
.append(AdminConsole.escape(key.endsWith("/") ? "(folder marker)" : key.substring(prefix.length())))
|
||||
.append("</h2><p>Inspect, download, or edit this object.</p></div>")
|
||||
.append("<biscuit-badgeview theme=deep-dark variant=accent>Object</biscuit-badgeview></div>")
|
||||
.append("<div class=grid><biscuit-cardview><small>Size</small><strong>")
|
||||
.append(AdminConsole.formatBytes(meta.length()))
|
||||
.append("</strong></biscuit-cardview><biscuit-cardview><small>Content type</small><strong>")
|
||||
.append(AdminConsole.escape(meta.contentType() == null ? "Unknown" : meta.contentType()))
|
||||
.append("</strong></biscuit-cardview><biscuit-cardview><small>Modified</small><strong>")
|
||||
.append(time(meta.modified())).append("</strong></biscuit-cardview></div>")
|
||||
.append("<p class=object-actions><a class=button-link href='")
|
||||
.append(downloadUrl(bucketName, key, version)).append("'>")
|
||||
.append(AdminConsole.icon("download")).append("Download file</a></p>")
|
||||
.append("<div class=detail-grid><div class=detail-card><h3>Identity</h3>")
|
||||
.append(fact("Bucket", bucketName)).append(fact("Key", key))
|
||||
.append(fact("Version ID", meta.versionId() == null ? "Unversioned" : meta.versionId()))
|
||||
.append("</div><div class=detail-card><h3>Integrity</h3>")
|
||||
.append(fact("ETag", meta.etag() == null ? "—" : meta.etag()))
|
||||
.append(fact("SHA-256", meta.sha256() == null ? "—" :
|
||||
java.util.HexFormat.of().formatHex(meta.sha256())))
|
||||
.append("</div></div>")
|
||||
.append(attributes("User metadata", meta.userMetadata()))
|
||||
.append(attributes("Tags", meta.tags()))
|
||||
.append(attributes("Checksums", meta.checksums()))
|
||||
.append(attributes("ACL grants", meta.acl()));
|
||||
if (text != null) {
|
||||
textEditor(html, bucket, meta, version, text, csrf, contentDraft);
|
||||
} else if (previewError != null) {
|
||||
html.append("<p class=muted>").append(AdminConsole.escape(previewError)).append("</p>");
|
||||
}
|
||||
if (bucket.ownership() != ObjectStorage.ObjectOwnership.BUCKET_OWNER_ENFORCED)
|
||||
grantForm(html, "object-grant", bucketName, key, version, csrf);
|
||||
objectActions(html, bucketName, key, version, csrf);
|
||||
return html.toString();
|
||||
}
|
||||
|
||||
private static void textEditor(StringBuilder html, ObjectStorage.Bucket bucket,
|
||||
ObjectStorage.Metadata meta, String version, String text,
|
||||
String csrf, AdminBrowser.EditorDraft draft) {
|
||||
boolean versioningEnabled = bucket.versioning() ==
|
||||
ObjectStorage.VersioningState.ENABLED;
|
||||
boolean editable = version == null && versioningEnabled &&
|
||||
meta.versionId() != null && meta.sha256() != null;
|
||||
String value = draft == null ? text : draft.value();
|
||||
html.append("<section class=editor-section id=text-editor><div class=intro><div><h2>Text object</h2>")
|
||||
.append("<p>").append(editable ? "Saving creates a new object version." :
|
||||
version != null ? "Older versions are read-only." :
|
||||
!versioningEnabled ? "Enable bucket versioning to edit this object safely." :
|
||||
"This object has no version or integrity token and is read-only here.")
|
||||
.append("</p></div><biscuit-badgeview theme=deep-dark variant=accent>")
|
||||
.append(AdminConsole.escape(AdminTextEditor.language(meta)))
|
||||
.append("</biscuit-badgeview></div>");
|
||||
if (editable) html.append("<form class='settings-form code-form' method=post action='")
|
||||
.append(AdminConsole.PATH).append("/action/edit-object'>")
|
||||
.append(hidden(csrf, bucket.name()))
|
||||
.append("<input type=hidden name=key value='").append(AdminConsole.escape(meta.key()))
|
||||
.append("'><input type=hidden name=originalVersion value='")
|
||||
.append(AdminConsole.escape(meta.versionId() == null ? "" : meta.versionId()))
|
||||
.append("'><input type=hidden name=originalSha256 value='")
|
||||
.append(meta.sha256() == null ? "" : SigV4.hex(meta.sha256())).append("'>");
|
||||
else html.append("<div class=settings-form>");
|
||||
html.append("<label for=object-code>Content</label><biscuit-codeview id=object-code ")
|
||||
.append("class=text-editor language='")
|
||||
.append(AdminConsole.escape(AdminTextEditor.language(meta)))
|
||||
.append("' aria-label='Object content'")
|
||||
.append(editable ? "" : " readonly")
|
||||
.append(" value='").append(AdminConsole.escape(value)).append("'></biscuit-codeview>")
|
||||
.append("<textarea class='code-fallback text-fallback' id=object-content rows=12 ")
|
||||
.append(editable ? "name=content" : "readonly")
|
||||
.append(">").append(AdminConsole.escape(value)).append("</textarea>")
|
||||
.append("<p class=editor-diagnostics data-editor=object-code data-state=")
|
||||
.append(draft == null ? "hint" : "error")
|
||||
.append(" role=status>")
|
||||
.append(AdminConsole.escape(draft == null ? "UTF-8 text · 32 KiB maximum" :
|
||||
draft.error())).append("</p>");
|
||||
if (editable) html.append("<button type=submit>")
|
||||
.append(AdminConsole.icon("edit")).append("Save new version</button></form>");
|
||||
else html.append("</div>");
|
||||
html.append("</section>");
|
||||
}
|
||||
|
||||
private static void objectActions(StringBuilder html, String bucketName, String key,
|
||||
String version, String csrf) {
|
||||
html.append("<section class=buckets><h2>Tags</h2>")
|
||||
.append("<form class=settings-form method=post action='").append(AdminConsole.PATH)
|
||||
.append("/action/object-tag'>").append(hidden(csrf, bucketName))
|
||||
.append("<input type=hidden name=key value='").append(AdminConsole.escape(key))
|
||||
.append("'>");
|
||||
if (version != null) html.append("<input type=hidden name=version value='")
|
||||
.append(AdminConsole.escape(version)).append("'>");
|
||||
html.append("<div class=form-row><input name=tag placeholder='Tag name' required maxlength=128>")
|
||||
.append("<input name=value placeholder='Value' maxlength=256>")
|
||||
.append("<select name=operation><option value=add>Save</option>")
|
||||
.append("<option value=remove>Remove</option></select><button>Apply tag</button></div></form></section>")
|
||||
.append("<form class='settings-form danger-zone' method=post action='")
|
||||
.append(AdminConsole.PATH).append("/action/delete-object'>")
|
||||
.append(hidden(csrf, bucketName))
|
||||
.append("<input type=hidden name=key value='").append(AdminConsole.escape(key)).append("'>");
|
||||
if (version != null) html.append("<input type=hidden name=version value='")
|
||||
.append(AdminConsole.escape(version)).append("'>");
|
||||
html.append("<h3>Delete object</h3><p>Type the full object key to confirm. ")
|
||||
.append(version == null ? "A versioned bucket may create a delete marker." :
|
||||
"This deletes the selected version permanently.")
|
||||
.append("</p><input name=confirm required placeholder='Full object key'>");
|
||||
if (version != null) html.append("<input name=confirmVersion required placeholder='Version ID'>");
|
||||
html.append("<button type=submit>").append(AdminConsole.icon("trash"))
|
||||
.append("Delete object</button></form>");
|
||||
}
|
||||
|
||||
static String versions(ObjectStorage store, String rawQuery, String csrf) throws IOException {
|
||||
Map<String, String> query = query(rawQuery, Set.of("bucket", "prefix", "keyMarker", "versionMarker"));
|
||||
String bucket = required(query, "bucket", 255);
|
||||
String prefix = query.getOrDefault("prefix", "");
|
||||
String keyMarker = query.get("keyMarker");
|
||||
String versionMarker = query.get("versionMarker");
|
||||
if (prefix.length() > 1024 || keyMarker != null && keyMarker.length() > 1024 ||
|
||||
versionMarker != null && (versionMarker.isEmpty() || versionMarker.length() > 256))
|
||||
throw invalidQuery();
|
||||
ObjectStorage.VersionPage page = store.listVersions(bucket, prefix, keyMarker, versionMarker, PAGE_SIZE);
|
||||
StringBuilder html = new StringBuilder(AdminConsole.consoleHeader(csrf));
|
||||
html.append(breadcrumbs(bucket, prefix))
|
||||
.append("<div class=intro><div><h2>Object versions</h2><p>Retained versions and delete markers")
|
||||
.append("</p></div></div><div class=toolbar><form method=get action='")
|
||||
.append(AdminConsole.PATH).append("/versions'><input type=hidden name=bucket value='")
|
||||
.append(AdminConsole.escape(bucket)).append("'><div class=field><label for=version-prefix>Prefix</label>")
|
||||
.append("<input id=version-prefix name=prefix value='").append(AdminConsole.escape(prefix))
|
||||
.append("' placeholder='e.g. images/'></div><button type=submit>Browse</button></form></div>");
|
||||
if (page.entries().isEmpty()) {
|
||||
html.append("<div class='table-wrap empty'>No versions in this prefix.</div>");
|
||||
} else {
|
||||
html.append("<div class=table-wrap><table><thead><tr><th>Key</th><th>Version</th>")
|
||||
.append("<th>State</th><th>Modified</th></tr></thead><tbody>");
|
||||
for (ObjectStorage.VersionEntry entry : page.entries()) {
|
||||
html.append("<tr><td class=name-cell>");
|
||||
if (entry.deleteMarker()) html.append(AdminConsole.escape(entry.key()));
|
||||
else html.append("<a href='").append(objectUrl(bucket, entry.key()))
|
||||
.append("&version=").append(encoded(entry.versionId())).append("'>")
|
||||
.append(AdminConsole.escape(entry.key())).append("</a>");
|
||||
html.append("</td><td class=name-cell><code>").append(AdminConsole.escape(entry.versionId()))
|
||||
.append("</code></td><td>").append(entry.deleteMarker() ? "Delete marker" : "Object")
|
||||
.append(entry.latest() ? " · latest" : "").append("</td><td>")
|
||||
.append(time(entry.modified())).append("</td></tr>");
|
||||
}
|
||||
html.append("</tbody></table></div>");
|
||||
}
|
||||
if (page.truncated()) html.append("<nav class=pagination><a class=button-link href='")
|
||||
.append(versionsUrl(bucket, prefix, page.nextKey(), page.nextVersionId()))
|
||||
.append("'>Next page →</a></nav>");
|
||||
return html.toString();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import static cloud.lunarsky.store.AdminConsole.PATH;
|
||||
import static cloud.lunarsky.store.AdminLayout.*;
|
||||
|
||||
final class AdminOperationsPages {
|
||||
private AdminOperationsPages() { }
|
||||
|
||||
static String auditPage(Set<String> identities, RequestDiagnostics diagnostics, AdminAuditTrail audit, String csrf, AdminAccessCheck.Result result,
|
||||
Map<String, String> form) throws IOException {
|
||||
StringBuilder content = new StringBuilder(consoleHeader(csrf) +
|
||||
"<div class=intro><div><h2>Audit & access</h2>" +
|
||||
"<p>Recent admin changes and effective key access</p></div></div>");
|
||||
content.append("<section class=insight><h3>Check access</h3>" +
|
||||
"<p class=muted>Checks key scope, bucket policy, identity policy, and ACL for the current object. " +
|
||||
"It does not make a request or change data.</p><form class=settings-form method=post action='")
|
||||
.append(PATH).append("/action/access-check'><input type=hidden name=csrf value='")
|
||||
.append(csrf).append("'><div class=settings-grid><label>Access key<select name=principal required>");
|
||||
for (String identity : identities.stream().sorted().toList()) {
|
||||
content.append("<option value='").append(escape(identity)).append("'")
|
||||
.append(identity.equals(form.get("principal")) ? " selected" : "")
|
||||
.append(">").append(escape(identity)).append("</option>");
|
||||
}
|
||||
content.append("</select></label><label>Operation<select name=operation>");
|
||||
for (String operation : List.of("list", "read", "write", "delete")) {
|
||||
content.append("<option value='").append(operation).append("'")
|
||||
.append(operation.equals(form.get("operation")) ? " selected" : "")
|
||||
.append(">").append(operation).append("</option>");
|
||||
}
|
||||
content.append("</select></label><label>Bucket<input name=bucket required maxlength=63 value='")
|
||||
.append(escape(form.getOrDefault("bucket", "")))
|
||||
.append("'></label><label>Object key or list prefix<input name=key maxlength=1024 value='")
|
||||
.append(escape(form.getOrDefault("key", "")))
|
||||
.append("'></label></div><button type=submit>Check access</button></form>");
|
||||
if (result != null) content.append("<div class=detail-card role=status><strong>")
|
||||
.append(result.allowed() ? "Allowed" : "Denied").append("</strong><p>")
|
||||
.append(escape(result.stage())).append(": ").append(escape(result.explanation()))
|
||||
.append("</p></div>");
|
||||
content.append("</section><section class=insight><h3>Key activity since restart</h3>" +
|
||||
"<p class=muted>Counts include authenticated S3 requests on this gateway. No secrets or object keys are logged.</p>");
|
||||
RequestDiagnostics current = diagnostics;
|
||||
List<RequestDiagnostics.KeyActivity> keys = current == null ? List.of() : current.keyActivity();
|
||||
if (keys.isEmpty()) content.append("<p class=muted>No key activity yet.</p>");
|
||||
else {
|
||||
content.append("<div class=table-wrap><table><thead><tr><th>Access key</th><th>Requests</th>" +
|
||||
"<th>Errors</th><th>Last seen (UTC)</th></tr></thead><tbody>");
|
||||
for (var key : keys) content.append("<tr><td><code>").append(escape(key.principal()))
|
||||
.append("</code></td><td>").append(key.requests()).append("</td><td>")
|
||||
.append(key.failures()).append("</td><td>")
|
||||
.append(java.time.Instant.ofEpochMilli(key.lastSeenMillis())).append("</td></tr>");
|
||||
content.append("</tbody></table></div>");
|
||||
}
|
||||
content.append("</section><section class=insight><h3>Admin event trail</h3>" +
|
||||
"<p class=muted>Last 100 events from this gateway, stored on the admin data volume. " +
|
||||
"Older events rotate out.</p>");
|
||||
List<AdminAuditTrail.Entry> entries = audit.recent(100);
|
||||
if (entries.isEmpty()) content.append("<p class=muted>No events yet.</p>");
|
||||
else {
|
||||
content.append("<div class=table-wrap><table><thead><tr><th>Time (UTC)</th><th>Action</th>" +
|
||||
"<th>Target</th><th>Result</th><th>Peer</th></tr></thead><tbody>");
|
||||
for (var entry : entries) content.append("<tr><td>")
|
||||
.append(java.time.Instant.ofEpochMilli(entry.timeMillis())).append("</td><td>")
|
||||
.append(escape(entry.action())).append("</td><td><code>")
|
||||
.append(escape(entry.target())).append("</code></td><td>")
|
||||
.append(escape(entry.result())).append("</td><td>")
|
||||
.append(escape(entry.peer())).append("</td></tr>");
|
||||
content.append("</tbody></table></div>");
|
||||
}
|
||||
return page(content.append("</section>").toString(), true);
|
||||
}
|
||||
|
||||
static String jobsPage(AdminBulkJobs jobs, String csrf) {
|
||||
StringBuilder content = new StringBuilder(consoleHeader(csrf) +
|
||||
"<div class=intro><div><h2>Bulk jobs</h2><p>Copy, delete, tag, or export an object inventory</p>" +
|
||||
"</div></div><p class=perf-note>One job at a time, up to " + AdminBulkJobs.MAX_ITEMS +
|
||||
" current objects per job. Jobs continue after leaving this page, but history and reports " +
|
||||
"reset when this gateway restarts. Cancellation takes effect between objects.</p>" +
|
||||
"<section class=insight><h3>Start a job</h3><form class=settings-form method=post action='" +
|
||||
PATH + "/action/bulk-start'><input type=hidden name=csrf value='" + csrf + "'>" +
|
||||
"<div class=settings-grid><label>Operation<select name=operation>" +
|
||||
"<option value=inventory>Export inventory</option><option value=copy>Copy</option>" +
|
||||
"<option value=tag>Set tag</option><option value=delete>Delete</option></select></label>" +
|
||||
"<label>Source bucket<input name=bucket required maxlength=63></label>" +
|
||||
"<label>Key prefix<input name=prefix maxlength=1024 placeholder='Optional'></label>" +
|
||||
"<label data-bulk-only=copy>Destination bucket<input name=targetBucket maxlength=63></label>" +
|
||||
"<label data-bulk-only=copy>Destination prefix<input name=targetPrefix maxlength=1024></label>" +
|
||||
"<label data-bulk-only=tag>Tag key<input name=tag maxlength=128></label>" +
|
||||
"<label data-bulk-only=tag>Tag value<input name=value maxlength=256></label>" +
|
||||
"<label data-bulk-only=delete>Confirm source bucket<input name=confirm maxlength=63></label>" +
|
||||
"</div><p class=muted>Copy uses create-only writes and reports destination conflicts. " +
|
||||
"Delete follows bucket versioning and may create delete markers. " +
|
||||
"Inventory reports current objects only.</p><button type=submit>Start job</button>" +
|
||||
"</form></section><section class=insight><h3>Recent jobs</h3>");
|
||||
List<AdminBulkJobs.Snapshot> recent = jobs.list();
|
||||
if (recent.isEmpty()) content.append("<p class=muted>No jobs started on this gateway.</p>");
|
||||
for (AdminBulkJobs.Snapshot job : recent) {
|
||||
content.append("<div class=detail-card data-job-id='").append(job.id()).append("'>")
|
||||
.append("<div class=fact><span><strong>").append(escape(job.spec().operation()))
|
||||
.append("</strong> · <code>").append(escape(job.spec().bucket())).append("/")
|
||||
.append(escape(job.spec().prefix())).append("</code></span><biscuit-badgeview " +
|
||||
"data-job-state theme=deep-dark>").append(escape(job.state()))
|
||||
.append("</biscuit-badgeview></div><p data-job-counts>")
|
||||
.append(job.processed()).append(" processed · ").append(job.succeeded())
|
||||
.append(" succeeded · ").append(job.failed()).append(" failed")
|
||||
.append("</p><div class=form-row><a href='").append(PATH)
|
||||
.append("/jobs.csv?id=").append(job.id()).append("'>Download CSV report</a>");
|
||||
if (job.finished() == 0) content.append("<form method=post action='").append(PATH)
|
||||
.append("/action/bulk-cancel'><input type=hidden name=csrf value='")
|
||||
.append(csrf).append("'><input type=hidden name=id value='")
|
||||
.append(job.id()).append("'><button type=submit>Cancel</button></form>");
|
||||
content.append("</div>");
|
||||
if (job.capped()) content.append("<p class=rename-warning>Stopped at the job limit. " +
|
||||
"Run another job with a narrower prefix for remaining objects.</p>");
|
||||
if (job.reportTruncated()) content.append("<p class=rename-warning>The CSV report reached its " +
|
||||
"size limit; counters include all processed objects.</p>");
|
||||
content.append("</div>");
|
||||
}
|
||||
return page(content.append("</section>").toString(), true);
|
||||
}
|
||||
|
||||
static String jobJson(AdminBulkJobs.Snapshot job) {
|
||||
return "{\"state\":\"" + job.state() + "\",\"processed\":" + job.processed() +
|
||||
",\"succeeded\":" + job.succeeded() + ",\"failed\":" + job.failed() +
|
||||
",\"finished\":" + job.finished() + ",\"capped\":" + job.capped() +
|
||||
",\"reportTruncated\":" + job.reportTruncated() + "}";
|
||||
}
|
||||
|
||||
static String clusterPage(ObjectStorage store, String csrf) {
|
||||
StringBuilder content = new StringBuilder(consoleHeader(csrf) +
|
||||
"<div class=intro><div><h2>Cluster</h2><p>Metadata and storage-node health</p></div></div>");
|
||||
if (!(store instanceof ClusterStore cluster)) {
|
||||
content.append("<section class=insight><p class=muted>This gateway runs in disk mode. " +
|
||||
"Cluster status appears here when cluster mode is enabled.</p></section>");
|
||||
return page(content.toString(), true);
|
||||
}
|
||||
ClusterStore.ClusterStatus status = cluster.status();
|
||||
appendClusterSummary(content, status);
|
||||
appendClusterTopology(content, status);
|
||||
appendRepairProgress(content, status.repair());
|
||||
return page(content.toString(), true);
|
||||
}
|
||||
|
||||
private static void appendClusterSummary(StringBuilder content, ClusterStore.ClusterStatus status) {
|
||||
long healthy = status.nodes().stream().filter(ClusterStore.NodeStatus::reachable).count();
|
||||
long hosts = status.nodes().stream().filter(ClusterStore.NodeStatus::reachable)
|
||||
.map(node -> node.node().hostId()).distinct().count();
|
||||
content.append("<p class=perf-note>Checked ")
|
||||
.append(java.time.Instant.ofEpochMilli(status.checkedAt()))
|
||||
.append(" UTC · Refresh for a new snapshot. Checks are cached for 15 seconds and probe at most " +
|
||||
"64 nodes. Node identity probes are bounded; this page does not scan object data.</p>")
|
||||
.append("<div class=grid><biscuit-cardview><small>Metadata primary</small><strong>")
|
||||
.append(status.metadataWritable() ? "Writable" : "Unavailable or read-only")
|
||||
.append("</strong></biscuit-cardview><biscuit-cardview><small>Reachable nodes</small><strong>")
|
||||
.append(healthy).append(" / ").append(status.nodes().size())
|
||||
.append("</strong></biscuit-cardview><biscuit-cardview><small>Reachable hosts</small><strong>")
|
||||
.append(hosts).append("</strong></biscuit-cardview></div>");
|
||||
}
|
||||
|
||||
private static void appendClusterTopology(StringBuilder content, ClusterStore.ClusterStatus status) {
|
||||
content.append("<section class=cluster-topology aria-label='Cluster topology'><div class=cluster-core>")
|
||||
.append("<strong>Metadata primary</strong><p>")
|
||||
.append(status.metadataWritable() ? "Writable" : "Unavailable or read-only")
|
||||
.append("</p></div><div class=cluster-connect aria-hidden=true></div><div class=cluster-nodes>");
|
||||
for (ClusterStore.NodeStatus node : status.nodes()) {
|
||||
content.append("<div class=cluster-node data-state=")
|
||||
.append(node.reachable() ? "online" : "offline")
|
||||
.append("><strong>").append(node.reachable() ? "● Online" : "● Offline")
|
||||
.append("</strong><code>Node ").append(node.node().id())
|
||||
.append("</code><code>Host ").append(node.node().hostId())
|
||||
.append("</code><code>").append(escape(node.node().url().toString()))
|
||||
.append("</code><small>Verified replicas at last repair: ")
|
||||
.append(!replicasMeasured(status) ?
|
||||
"Not measured" :
|
||||
Long.toString(status.verifiedReplicas().getOrDefault(node.node().id(), 0L)))
|
||||
.append("</small></div>");
|
||||
}
|
||||
content.append("</div></section>");
|
||||
content.append("<p class=muted>Host IDs show physical failure domains as configured by the operator. " +
|
||||
"Multiple nodes on one host do not provide host-level redundancy.</p>");
|
||||
if (status.omittedNodes() > 0) content.append("<p class=rename-warning>")
|
||||
.append(status.omittedNodes()).append(" additional nodes are not probed in this view.</p>");
|
||||
}
|
||||
|
||||
private static boolean replicasMeasured(ClusterStore.ClusterStatus status) {
|
||||
ClusterStore.RepairStatus repair = status.repair();
|
||||
if (repair == null || !repair.state().equals("completed")) return false;
|
||||
return repair.report().scanned() <= 0 || !status.verifiedReplicas().isEmpty();
|
||||
}
|
||||
|
||||
private static void appendRepairProgress(StringBuilder content, ClusterStore.RepairStatus repair) {
|
||||
content.append("<section class=insight><h3>Repair progress</h3>");
|
||||
if (repair == null) content.append("<p class=muted>No repair report has been recorded yet.</p>");
|
||||
else {
|
||||
appendRepairReport(content, repair);
|
||||
}
|
||||
content.append("<p class=muted>Repair is run by the separate cluster maintenance service. " +
|
||||
"This panel does not trigger repair or change placement.</p></section>");
|
||||
}
|
||||
|
||||
private static void appendRepairReport(StringBuilder content, ClusterStore.RepairStatus repair) {
|
||||
ClusterStore.RepairReport report = repair.report();
|
||||
content.append("<p><strong>").append(repairLabel(repair))
|
||||
.append("</strong> · Started ")
|
||||
.append(java.time.Instant.ofEpochMilli(repair.startedAt()))
|
||||
.append(" UTC · Last update ")
|
||||
.append(java.time.Instant.ofEpochMilli(repair.updatedAt()))
|
||||
.append(" UTC</p><p class=muted>These counts are from this repair pass, " +
|
||||
"not a live replica inventory.</p><div class=grid>")
|
||||
.append("<biscuit-cardview><small>Segments scanned</small><strong>")
|
||||
.append(report.scanned()).append("</strong></biscuit-cardview>")
|
||||
.append("<biscuit-cardview><small>Replicas restored</small><strong>")
|
||||
.append(report.restored()).append("</strong></biscuit-cardview>")
|
||||
.append("<biscuit-cardview><small>Under-replicated</small><strong>")
|
||||
.append(report.underReplicated()).append("</strong></biscuit-cardview>")
|
||||
.append("<biscuit-cardview><small>Unrecoverable</small><strong>")
|
||||
.append(report.unrecoverable()).append("</strong></biscuit-cardview></div>");
|
||||
}
|
||||
|
||||
private static String repairLabel(ClusterStore.RepairStatus repair) {
|
||||
if (repair.state().equals("running")) {
|
||||
return System.currentTimeMillis() - repair.updatedAt() > 300_000
|
||||
? "May be interrupted" : "Running";
|
||||
}
|
||||
return repair.state().equals("failed") ? "Failed" : "Completed";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.lang.management.GarbageCollectorMXBean;
|
||||
import java.lang.management.ManagementFactory;
|
||||
import java.lang.management.MemoryMXBean;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
|
||||
final class AdminPerformance {
|
||||
private static final MemoryMXBean MEMORY = ManagementFactory.getMemoryMXBean();
|
||||
private static final List<GarbageCollectorMXBean> COLLECTORS =
|
||||
ManagementFactory.getGarbageCollectorMXBeans();
|
||||
private static final ProcessHandle PROCESS = ProcessHandle.current();
|
||||
private static final Path STATUS = Path.of("/proc/self/status");
|
||||
|
||||
private AdminPerformance() { }
|
||||
|
||||
static String snapshot(RequestMetrics metrics) {
|
||||
RequestMetrics.DataSnapshot traffic = metrics.dataSnapshot();
|
||||
long gcCount = 0;
|
||||
long gcMillis = 0;
|
||||
for (GarbageCollectorMXBean collector : COLLECTORS) {
|
||||
gcCount += Math.max(0, collector.getCollectionCount());
|
||||
gcMillis += Math.max(0, collector.getCollectionTime());
|
||||
}
|
||||
long cpuNanos = PROCESS.info().totalCpuDuration().map(Duration::toNanos).orElse(-1L);
|
||||
return "{\"requests\":" + traffic.requests() +
|
||||
",\"failures4xx\":" + traffic.failures4xx() +
|
||||
",\"failures5xx\":" + traffic.failures5xx() +
|
||||
",\"durationNanos\":" + traffic.durationNanos() +
|
||||
",\"inboundBytes\":" + traffic.inboundBytes() +
|
||||
",\"outboundBytes\":" + traffic.outboundBytes() +
|
||||
",\"inFlight\":" + traffic.inFlight() +
|
||||
",\"cpuNanos\":" + cpuNanos +
|
||||
",\"processors\":" + Runtime.getRuntime().availableProcessors() +
|
||||
",\"rssBytes\":" + rssBytes() +
|
||||
",\"heapBytes\":" + MEMORY.getHeapMemoryUsage().getUsed() +
|
||||
",\"nonHeapBytes\":" + MEMORY.getNonHeapMemoryUsage().getUsed() +
|
||||
",\"gcCount\":" + gcCount +
|
||||
",\"gcMillis\":" + gcMillis + "}";
|
||||
}
|
||||
|
||||
private static long rssBytes() {
|
||||
if (!Files.isReadable(STATUS)) return -1;
|
||||
try (var lines = Files.lines(STATUS)) {
|
||||
String line = lines.filter(value -> value.startsWith("VmRSS:"))
|
||||
.findFirst().orElse("");
|
||||
if (line.isEmpty()) return -1;
|
||||
String value = line.substring("VmRSS:".length()).trim();
|
||||
return Math.multiplyExact(Long.parseLong(value.split("\\s+", 2)[0]), 1024);
|
||||
} catch (IOException | NumberFormatException | ArithmeticException unavailable) {
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
import static cloud.lunarsky.store.AdminConsole.PATH;
|
||||
import static cloud.lunarsky.store.AdminLayout.*;
|
||||
|
||||
final class AdminSettingsPages {
|
||||
private AdminSettingsPages() { }
|
||||
|
||||
static String credentialsPage(ManagedCredentials managedCredentials, ObjectStorage store, String csrf, ManagedCredentials.Key created) throws IOException {
|
||||
StringBuilder content = new StringBuilder(consoleHeader(csrf));
|
||||
content.append("<div class=intro><div><h2>Access keys</h2><p>Scoped S3 credentials for applications</p></div></div>");
|
||||
ManagedCredentials managed = managedCredentials;
|
||||
if (managed == null) {
|
||||
content.append("<p class=muted>Managed keys are disabled. Configure a separate master key file to enable them.</p>");
|
||||
return page(content.toString(), true);
|
||||
}
|
||||
if (created != null) {
|
||||
content.append("<section class=settings-form><h3>Save this secret now</h3>")
|
||||
.append("<p>The secret will not be displayed again.</p><div class=fact><span>Access key ID</span><strong><code>")
|
||||
.append(escape(created.id())).append("</code></strong></div>")
|
||||
.append("<div class=fact><span>Secret access key</span><strong><code>")
|
||||
.append(escape(created.secret())).append("</code></strong></div></section>");
|
||||
}
|
||||
content.append("<form class=settings-form method=post action='").append(PATH)
|
||||
.append("/action/create-key'><h3>Create scoped key</h3><p>Select one bucket and an optional key prefix.</p>")
|
||||
.append("<input type=hidden name=csrf value='").append(csrf).append("'>")
|
||||
.append("<label for=key-bucket>Bucket</label><select id=key-bucket name=bucket required>");
|
||||
for (ObjectStorage.Bucket bucket : store.buckets())
|
||||
content.append("<option value='").append(escape(bucket.name())).append("'>")
|
||||
.append(escape(bucket.name())).append("</option>");
|
||||
content.append("</select><label for=key-prefix>Key prefix</label>")
|
||||
.append("<input id=key-prefix name=prefix maxlength=256 placeholder='images/'>")
|
||||
.append("<div class=check-grid><label class=check><input type=checkbox name=read>Read</label>")
|
||||
.append("<label class=check><input type=checkbox name=write>Write</label>")
|
||||
.append("<label class=check><input type=checkbox name=list>List</label></div>")
|
||||
.append("<button type=submit>").append(icon("access-key"))
|
||||
.append("Create key</button></form>")
|
||||
.append("<section class=buckets><h2>Managed keys</h2><p>Disabling a key rejects new signed requests immediately.</p>");
|
||||
for (ManagedCredentials.Key key : managed.list()) {
|
||||
content.append("<div class=settings-form><h3><code>").append(escape(key.id()))
|
||||
.append("</code> <biscuit-badgeview theme=deep-dark variant=")
|
||||
.append(key.enabled() ? "success" : "warning").append(" size=small>")
|
||||
.append(key.enabled() ? "Active" : "Disabled")
|
||||
.append("</biscuit-badgeview></h3><p>")
|
||||
.append(escape(key.bucket())).append(" / ")
|
||||
.append(escape(key.prefix())).append(" · ")
|
||||
.append(escape(String.join(", ", key.actions().stream().sorted().toList())))
|
||||
.append("</p>")
|
||||
.append("<form method=post action='").append(PATH).append("/action/update-key'>")
|
||||
.append("<input type=hidden name=csrf value='").append(csrf).append("'>")
|
||||
.append("<input type=hidden name=id value='").append(key.id()).append("'>")
|
||||
.append("<label>Bucket<input name=bucket required value='").append(escape(key.bucket()))
|
||||
.append("'></label><label>Prefix<input name=prefix maxlength=256 value='")
|
||||
.append(escape(key.prefix())).append("'></label><div class=check-grid>");
|
||||
for (String permission : List.of("read", "write", "list"))
|
||||
content.append("<label class=check><input type=checkbox name=").append(permission)
|
||||
.append(key.actions().contains(permission) ? " checked" : "")
|
||||
.append(">").append(permission).append("</label>");
|
||||
content.append("</div><label>Type the access key ID to confirm changes")
|
||||
.append("<input name=confirm required autocomplete=off></label>")
|
||||
.append("<button type=submit>Save scope</button></form>")
|
||||
.append("<form method=post action='").append(PATH).append("/action/")
|
||||
.append(key.enabled() ? "disable-key" : "enable-key").append("'>")
|
||||
.append("<input type=hidden name=csrf value='").append(csrf).append("'>")
|
||||
.append("<input type=hidden name=id value='").append(key.id()).append("'>")
|
||||
.append("<label>Type the access key ID to confirm<input name=confirm required autocomplete=off></label>")
|
||||
.append("<button type=submit>").append(key.enabled() ? "Disable" : "Enable")
|
||||
.append("</button></form><form method=post action='").append(PATH)
|
||||
.append("/action/delete-key'><input type=hidden name=csrf value='").append(csrf)
|
||||
.append("'><input type=hidden name=id value='").append(key.id())
|
||||
.append("'><label>Type the access key ID to delete<input name=confirm required autocomplete=off></label>")
|
||||
.append("<button type=submit>Delete key</button></form></div>");
|
||||
}
|
||||
content.append("</section>");
|
||||
return page(content.toString(), true);
|
||||
}
|
||||
|
||||
static String settingsPage(String csrf) {
|
||||
return consoleHeader(csrf) +
|
||||
"<nav class=crumbs aria-label=Breadcrumb><a href='" + PATH +
|
||||
"/overview'>Overview</a><span>/</span><span>Settings</span></nav>" +
|
||||
"<div class=intro><div><h2>Appearance</h2>" +
|
||||
"<p>Choose a theme for this browser or set the default for all admins.</p></div></div>" +
|
||||
"<section class=settings-grid><div class=settings-form>" +
|
||||
"<h3>Theme</h3><label for=admin-theme>This browser</label>" +
|
||||
"<select id=admin-theme><option value=default>Use server default</option>" +
|
||||
"<option value=dark>Dark</option>" +
|
||||
"<option value=auto>Follow system</option>" +
|
||||
"<option value=light>Light</option>" +
|
||||
"<option value=deep-dark>Deep dark</option></select>" +
|
||||
"<p class=muted>Your choice is saved only in this browser.</p>" +
|
||||
"<form method=post action='" + PATH + "/action/default-theme'>" +
|
||||
"<input type=hidden name=csrf value='" + csrf + "'>" +
|
||||
"<label for=admin-global-theme>Global default</label>" +
|
||||
"<select id=admin-global-theme name=defaultTheme>" +
|
||||
"<option value=deep-dark>Deep dark</option>" +
|
||||
"<option value=dark>Dark</option>" +
|
||||
"<option value=light>Light</option>" +
|
||||
"<option value=auto>Follow system</option></select>" +
|
||||
"<button type=submit>Save global default</button></form>" +
|
||||
"<p class=muted>Used by browsers without a personal theme choice.</p></div>" +
|
||||
"<div class=settings-form><h3>Branding</h3>" +
|
||||
"<form method=post action='" + PATH + "/action/branding-name'>" +
|
||||
"<input type=hidden name=csrf value='" + csrf + "'>" +
|
||||
"<label for=admin-brand-text>Display name</label>" +
|
||||
"<input id=admin-brand-text name=displayName maxlength=40 required placeholder='ObjectStore admin'>" +
|
||||
"<button type=submit>Save name</button></form>" +
|
||||
"<label for=admin-brand-icon>Icon image</label>" +
|
||||
"<input id=admin-brand-icon type=file data-csrf='" + csrf +
|
||||
"' accept='image/png,image/jpeg,image/webp'>" +
|
||||
"<div class=brand-preview><img id=admin-brand-preview src='" + PATH +
|
||||
"/logo.png' alt='Current admin icon' width=52 height=52>" +
|
||||
"<span id=admin-brand-preview-text>ObjectStore admin</span></div>" +
|
||||
"<p class=muted>PNG, JPEG, or WebP, up to 128 KiB. Changes appear on every device.</p>" +
|
||||
"<form method=post action='" + PATH + "/action/branding-reset'>" +
|
||||
"<input type=hidden name=csrf value='" + csrf + "'>" +
|
||||
"<button id=admin-brand-reset type=submit>Reset branding</button></form>" +
|
||||
"<p id=admin-settings-status role=status></p></div></section>";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.FileStore;
|
||||
import java.util.List;
|
||||
import static cloud.lunarsky.store.AdminConsole.PATH;
|
||||
import static cloud.lunarsky.store.AdminLayout.*;
|
||||
|
||||
final class AdminStatusPages {
|
||||
private AdminStatusPages() { }
|
||||
|
||||
static String overviewPage(String mode, String status, long maxObject, long maxTotal,
|
||||
List<ObjectStorage.Bucket> buckets, boolean bucketListAvailable,
|
||||
String csrf) {
|
||||
StringBuilder content = new StringBuilder(consoleHeader(csrf) +
|
||||
"<div class=intro><div><h2>Overview</h2><p>Service status and configured limits</p></div>" +
|
||||
"<biscuit-badgeview theme=deep-dark variant='" + (status.equals("Ready") ? "success" : "danger") + "'>" +
|
||||
status + "</biscuit-badgeview></div>" +
|
||||
"<div class=grid><biscuit-cardview><small>Storage mode</small><strong>" + mode +
|
||||
"</strong></biscuit-cardview><biscuit-cardview><small>Buckets</small><strong>" +
|
||||
(bucketListAvailable ? buckets.size() : "Unavailable") +
|
||||
"</strong></biscuit-cardview><biscuit-cardview><small>Maximum object</small><strong>" +
|
||||
formatBytes(maxObject) + "</strong></biscuit-cardview><biscuit-cardview>" +
|
||||
"<small>Total storage limit</small><strong>" + formatBytes(maxTotal) +
|
||||
"</strong></biscuit-cardview></div><section class=buckets><h2>Buckets</h2>" +
|
||||
"<p>First 25 buckets. <a href='" + PATH +
|
||||
"/buckets'>Browse all buckets</a></p>");
|
||||
if (!bucketListAvailable || buckets.isEmpty()) {
|
||||
content.append("<div class='table-wrap empty'>")
|
||||
.append(bucketListAvailable ? "No buckets yet." : "Bucket list unavailable.")
|
||||
.append("</div>");
|
||||
} else {
|
||||
content.append("<div class=table-wrap><table><thead><tr><th>Bucket</th><th>Versioning</th>" +
|
||||
"<th>Ownership</th></tr></thead><tbody>");
|
||||
for (ObjectStorage.Bucket bucket : buckets.stream().limit(25).toList()) {
|
||||
String versioning = bucket.versioning() == ObjectStorage.VersioningState.NEVER ?
|
||||
"Off" : bucket.versioning().name().toLowerCase(java.util.Locale.ROOT);
|
||||
String ownership = switch (bucket.ownership()) {
|
||||
case BUCKET_OWNER_ENFORCED -> "Owner enforced";
|
||||
case BUCKET_OWNER_PREFERRED -> "Owner preferred";
|
||||
case OBJECT_WRITER -> "Object writer";
|
||||
};
|
||||
content.append("<tr><td><a href='").append(AdminBrowser.bucketUrl(bucket.name(), "", null))
|
||||
.append("'>").append(escape(bucket.name())).append("</a></td><td>")
|
||||
.append(versioning).append("</td><td>").append(ownership).append("</td></tr>");
|
||||
}
|
||||
content.append("</tbody></table></div>");
|
||||
}
|
||||
content.append("</section>");
|
||||
return page(content.toString(), true);
|
||||
}
|
||||
|
||||
static String performancePage(String csrf) {
|
||||
StringBuilder content = new StringBuilder(consoleHeader(csrf));
|
||||
content.append("<div class=intro><div><h2>Performance</h2>")
|
||||
.append("<p>Live S3 traffic and process health</p></div>")
|
||||
.append("<biscuit-badgeview theme=deep-dark variant=accent>Live</biscuit-badgeview></div>")
|
||||
.append("<p class=perf-note>Live samples arrive about once a second while this tab is visible. ")
|
||||
.append("Traffic excludes admin pages and health checks. Charts keep only the last 60 samples ")
|
||||
.append("in this browser tab.</p><div class=perf-status-row>")
|
||||
.append("<biscuit-loadingindicator id=perf-loader theme=deep-dark size=small ")
|
||||
.append("label='Loading performance metrics' aria-hidden=true></biscuit-loadingindicator>")
|
||||
.append("<p id=perf-state class=perf-status data-state=loading role=status>Collecting samples…</p></div>")
|
||||
.append("<div class=perf-grid>")
|
||||
.append(perfCard("Requests / second", "perf-rps"))
|
||||
.append(perfCard("Average latency", "perf-latency"))
|
||||
.append(perfCard("Inbound / second", "perf-inbound"))
|
||||
.append(perfCard("Outbound / second", "perf-outbound"))
|
||||
.append(perfCard("Average CPU · recent", "perf-cpu"))
|
||||
.append(perfCard("Process RAM (RSS)", "perf-ram"))
|
||||
.append(perfCard("GC collections", "perf-gc"))
|
||||
.append(perfCard("In flight", "perf-inflight"))
|
||||
.append("</div><div class=perf-charts hidden>")
|
||||
.append("<biscuit-chartview id=perf-requests-chart theme=deep-dark type=line ")
|
||||
.append("name='Requests / second' height=250 max-rows=60></biscuit-chartview>")
|
||||
.append("<biscuit-chartview id=perf-transfer-chart theme=deep-dark type=line ")
|
||||
.append("name='Transfer / second' height=250 max-rows=60></biscuit-chartview>")
|
||||
.append("<biscuit-chartview id=perf-cpu-chart theme=deep-dark type=line ")
|
||||
.append("name='Process CPU' height=250 max-rows=60></biscuit-chartview>")
|
||||
.append("<biscuit-chartview id=perf-memory-chart theme=deep-dark type=line ")
|
||||
.append("name='Process memory' height=250 max-rows=60></biscuit-chartview>")
|
||||
.append("</div><p class=perf-note>Inbound and outbound measure HTTP body bytes, including ")
|
||||
.append("S3 metadata responses. CPU is the process share of available cores. ")
|
||||
.append("GC counts reset when the service restarts.</p>");
|
||||
return page(content.toString(), true, true);
|
||||
}
|
||||
|
||||
static String healthPage(DiskStore diskStore, ObjectStorage store, String csrf) {
|
||||
boolean ready = store.ready();
|
||||
String mode = diskStore == null ? "Cluster" : "Disk";
|
||||
StringBuilder content = new StringBuilder(consoleHeader(csrf) +
|
||||
"<div class=intro><div><h2>Health & recovery</h2>" +
|
||||
"<p>Current service and storage state</p></div><biscuit-badgeview variant='" +
|
||||
(ready ? "success" : "danger") + "'>" + (ready ? "Ready" : "Unavailable") +
|
||||
"</biscuit-badgeview></div><div class=grid>" +
|
||||
"<biscuit-cardview><small>Storage mode</small><strong>" + mode +
|
||||
"</strong></biscuit-cardview>");
|
||||
if (diskStore != null) {
|
||||
long used = diskStore.usedBytes();
|
||||
long quota = store.limits().maxTotalBytes();
|
||||
content.append("<biscuit-cardview><small>Quota used</small><strong>")
|
||||
.append(formatBytes(used)).append(" / ").append(formatBytes(quota))
|
||||
.append("</strong></biscuit-cardview><biscuit-cardview><small>Current objects</small><strong>")
|
||||
.append(diskStore.objectCount()).append("</strong></biscuit-cardview>");
|
||||
try {
|
||||
FileStore volume = Files.getFileStore(diskStore.root());
|
||||
long free = volume.getUsableSpace();
|
||||
content.append("<biscuit-cardview><small>Filesystem available</small><strong>")
|
||||
.append(formatBytes(free)).append("</strong></biscuit-cardview>");
|
||||
if (free < Math.max(0, quota - used))
|
||||
content.append("<p class=rename-warning>Filesystem free space is below the remaining configured quota. " +
|
||||
"The volume can fill before the quota is reached.</p>");
|
||||
} catch (IOException unavailable) {
|
||||
content.append("<biscuit-cardview><small>Filesystem available</small><strong>Unavailable" +
|
||||
"</strong></biscuit-cardview>");
|
||||
}
|
||||
} else {
|
||||
content.append("<biscuit-cardview><small>Storage nodes</small><strong>Not measured here" +
|
||||
"</strong></biscuit-cardview>");
|
||||
}
|
||||
content.append("</div><section class=insight><div class=detail-card><h3>Recovery readiness</h3>" +
|
||||
"<div class=fact><span>Latest off-site backup</span><strong>Not reported</strong></div>" +
|
||||
"<div class=fact><span>Latest restore test</span><strong>Not reported</strong></div>" +
|
||||
"<p class=muted>ObjectStore cannot verify external backups or restores. Check your backup jobs " +
|
||||
"and perform a restore drill before relying on this service for important data.</p>" +
|
||||
"<a href='https://lunarsky.cloud/objectstore/v0.0.8/operations'>Recovery documentation</a>" +
|
||||
"</div></section>");
|
||||
return page(content.toString(), true);
|
||||
}
|
||||
|
||||
static String diagnosticsPage(RequestDiagnostics diagnostics, String csrf) {
|
||||
RequestDiagnostics current = diagnostics;
|
||||
RequestDiagnostics.Snapshot snapshot = current == null ? null : current.snapshot();
|
||||
StringBuilder content = new StringBuilder(consoleHeader(csrf) +
|
||||
"<div class=intro><div><h2>Request diagnostics</h2>" +
|
||||
"<p>Recent S3 requests on this gateway</p></div></div>" +
|
||||
"<p class=perf-note>Five-minute rolling window. Latency percentiles are histogram upper bounds. " +
|
||||
"Admin requests and health checks are excluded. Refresh to update.</p>");
|
||||
if (snapshot == null) {
|
||||
content.append("<p class=error>Request diagnostics are unavailable.</p>");
|
||||
} else {
|
||||
content.append("<div class=grid><biscuit-cardview><small>Requests</small><strong>")
|
||||
.append(snapshot.requests()).append("</strong></biscuit-cardview>")
|
||||
.append("<biscuit-cardview><small>4xx / 5xx</small><strong>")
|
||||
.append(snapshot.clientErrors()).append(" / ").append(snapshot.serverErrors())
|
||||
.append("</strong></biscuit-cardview>")
|
||||
.append("<biscuit-cardview><small>p50 / p95</small><strong>")
|
||||
.append(latencyLabel(snapshot.p50Millis())).append(" / ")
|
||||
.append(latencyLabel(snapshot.p95Millis())).append("</strong></biscuit-cardview>")
|
||||
.append("<biscuit-cardview><small>p99</small><strong>")
|
||||
.append(latencyLabel(snapshot.p99Millis())).append("</strong></biscuit-cardview></div>")
|
||||
.append("<section class=insight><h3>Recent errors</h3><p class=muted>Most recent 64 errors; " +
|
||||
"bucket names and request IDs only. Object keys and credentials are not retained.</p>");
|
||||
if (snapshot.recentFailures().isEmpty()) {
|
||||
content.append("<div class='table-wrap empty'>No errors in this window.</div>");
|
||||
} else {
|
||||
content.append("<div class=table-wrap><table><thead><tr><th>Time (UTC)</th><th>Status</th>" +
|
||||
"<th>Operation</th><th>Bucket</th><th>Request ID</th></tr></thead><tbody>");
|
||||
for (RequestDiagnostics.Failure failure : snapshot.recentFailures()) {
|
||||
content.append("<tr><td>").append(java.time.Instant.ofEpochMilli(failure.timeMillis()))
|
||||
.append("</td><td>").append(failure.status()).append("</td><td>")
|
||||
.append(escape(failure.operation())).append("</td><td>")
|
||||
.append(escape(failure.bucket())).append("</td><td><code>")
|
||||
.append(escape(failure.requestId())).append("</code></td></tr>");
|
||||
}
|
||||
content.append("</tbody></table></div>");
|
||||
}
|
||||
content.append("</section>");
|
||||
}
|
||||
content.append("<section class=insight><div class=detail-card><h3>Connection probe</h3>" +
|
||||
"<p class=muted>Download 1 MiB from the admin listener to measure browser-to-gateway timing. " +
|
||||
"This does not measure object reads, disks, or storage nodes.</p>" +
|
||||
"<button id=diagnostic-probe type=button>Run probe</button> " +
|
||||
"<span id=diagnostic-probe-result role=status></span></div></section>");
|
||||
return page(content.toString(), true);
|
||||
}
|
||||
|
||||
static String latencyLabel(long upperMillis) {
|
||||
return upperMillis < 0 ? ">10 s" : upperMillis + " ms";
|
||||
}
|
||||
|
||||
static String perfCard(String label, String id) {
|
||||
return "<biscuit-cardview><small>" + label + "</small><strong id='" + id +
|
||||
"'><biscuit-skeletonview width=72px height=22px></biscuit-skeletonview>" +
|
||||
"</strong></biscuit-cardview>";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.CharacterCodingException;
|
||||
import java.nio.charset.CodingErrorAction;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Arrays;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
|
||||
final class AdminTextEditor {
|
||||
static final int MAX_BYTES = 32 * 1024;
|
||||
|
||||
private AdminTextEditor() { }
|
||||
|
||||
static boolean supports(ObjectStorage.Metadata metadata) {
|
||||
if (metadata.length() > MAX_BYTES) return false;
|
||||
String type = metadata.contentType() == null ? "" :
|
||||
metadata.contentType().split(";", 2)[0].trim().toLowerCase(Locale.ROOT);
|
||||
if (type.startsWith("text/") || type.equals("application/json") ||
|
||||
type.equals("application/xml") || type.equals("application/javascript") ||
|
||||
type.equals("application/x-javascript") || type.equals("application/x-yaml")) return true;
|
||||
String key = metadata.key().toLowerCase(Locale.ROOT);
|
||||
return type.equals("application/octet-stream") &&
|
||||
(key.endsWith(".txt") || key.endsWith(".json") || key.endsWith(".xml") ||
|
||||
key.endsWith(".md") || key.endsWith(".html") || key.endsWith(".css") ||
|
||||
key.endsWith(".js") || key.endsWith(".java") || key.endsWith(".yaml") ||
|
||||
key.endsWith(".yml"));
|
||||
}
|
||||
|
||||
static String read(ObjectStorage.OpenObject opened) throws IOException {
|
||||
byte[] data = opened.stream().readNBytes(MAX_BYTES + 1);
|
||||
if (data.length > MAX_BYTES) throw new StoreException(413, "EntityTooLarge", "Text preview is too large");
|
||||
try {
|
||||
String text = StandardCharsets.UTF_8.newDecoder()
|
||||
.onMalformedInput(CodingErrorAction.REPORT)
|
||||
.onUnmappableCharacter(CodingErrorAction.REPORT)
|
||||
.decode(ByteBuffer.wrap(data)).toString();
|
||||
if (text.indexOf('\0') >= 0)
|
||||
throw new StoreException(415, "InvalidObjectState", "This object contains binary data");
|
||||
return text;
|
||||
} catch (CharacterCodingException error) {
|
||||
throw new StoreException(415, "InvalidObjectState", "This object is not UTF-8 text");
|
||||
}
|
||||
}
|
||||
|
||||
static String language(ObjectStorage.Metadata metadata) {
|
||||
String key = metadata.key().toLowerCase(Locale.ROOT);
|
||||
String type = metadata.contentType() == null ? "" : metadata.contentType().toLowerCase(Locale.ROOT);
|
||||
if (key.endsWith(".json") || type.contains("json")) return "json";
|
||||
if (key.endsWith(".html") || type.contains("html")) return "html";
|
||||
if (key.endsWith(".css") || type.contains("css")) return "css";
|
||||
if (key.endsWith(".js") || type.contains("javascript")) return "javascript";
|
||||
if (key.endsWith(".java")) return "java";
|
||||
return "plain";
|
||||
}
|
||||
|
||||
static String save(ObjectStorage store, Map<String, String> form) throws IOException {
|
||||
String bucket = form.getOrDefault("bucket", "");
|
||||
String key = form.getOrDefault("key", "");
|
||||
if (bucket.isEmpty() || bucket.length() > 63 || key.isEmpty() || key.length() > 1024)
|
||||
throw new StoreException(400, "InvalidArgument", "Invalid object path");
|
||||
if (store.bucket(bucket).versioning() != ObjectStorage.VersioningState.ENABLED)
|
||||
throw new StoreException(409, "InvalidBucketState", "Enable bucket versioning before editing objects");
|
||||
String value = form.getOrDefault("content", "");
|
||||
byte[] data = value.getBytes(StandardCharsets.UTF_8);
|
||||
if (data.length > MAX_BYTES)
|
||||
throw new StoreException(413, "EntityTooLarge", "Text files are limited to 32 KiB in the admin editor");
|
||||
ObjectStorage.Metadata metadata;
|
||||
try (ObjectStorage.OpenObject opened = store.open(bucket, key)) {
|
||||
metadata = opened.metadata();
|
||||
if (!supports(metadata))
|
||||
throw new StoreException(415, "InvalidObjectState", "Only small text objects can be edited");
|
||||
read(opened);
|
||||
}
|
||||
if (metadata.versionId() == null || !metadata.versionId().equals(form.get("originalVersion")) ||
|
||||
metadata.sha256() == null || !SigV4.hex(metadata.sha256()).equals(form.get("originalSha256")))
|
||||
throw new StoreException(409, "Conflict", "The object changed. Reload before saving your edit");
|
||||
try {
|
||||
store.replaceVersion(bucket, key, data, metadata);
|
||||
} catch (StoreException error) {
|
||||
if (error.status == 412)
|
||||
throw new StoreException(409, "Conflict", "The object changed. Reload before saving your edit");
|
||||
throw error;
|
||||
} finally {
|
||||
Arrays.fill(data, (byte) 0);
|
||||
}
|
||||
return AdminConsole.PATH + "/object?bucket=" + AdminBrowser.encoded(bucket) +
|
||||
"&key=" + AdminBrowser.encoded(key);
|
||||
}
|
||||
}
|
||||
@@ -103,7 +103,8 @@ final class AwsChunkedInputStream extends FilterInputStream {
|
||||
throw invalid("Invalid signed chunk header");
|
||||
try { chunkLeft = Long.parseUnsignedLong(size, 16); }
|
||||
catch (NumberFormatException error) { throw invalid("Invalid signed chunk size"); }
|
||||
if (chunkLeft > decodedLength - decoded) throw invalid("Signed chunks exceed decoded length");
|
||||
if (chunkLeft < 0 || chunkLeft > decodedLength - decoded)
|
||||
throw invalid("Signed chunks exceed decoded length");
|
||||
chunkHash.reset();
|
||||
if (chunkLeft == 0) finishPayload();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
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.time.LocalDate;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.LongAdder;
|
||||
|
||||
final class BucketActivity implements AutoCloseable {
|
||||
private static final int DAYS = 365;
|
||||
private final Path file;
|
||||
private final ConcurrentHashMap<Key, Counts> counts = new ConcurrentHashMap<>();
|
||||
private final AtomicBoolean dirty = new AtomicBoolean();
|
||||
private final ScheduledExecutorService writer = Executors.newSingleThreadScheduledExecutor(task -> {
|
||||
Thread thread = new Thread(task, "objectstore-bucket-activity");
|
||||
thread.setDaemon(true);
|
||||
return thread;
|
||||
});
|
||||
|
||||
record Day(LocalDate date, long reads, long writes) {
|
||||
long total() { return reads + writes; }
|
||||
}
|
||||
|
||||
private record Key(String bucket, long epochDay) { }
|
||||
|
||||
private static final class Counts {
|
||||
final LongAdder reads = new LongAdder();
|
||||
final LongAdder writes = new LongAdder();
|
||||
}
|
||||
|
||||
BucketActivity(Path file) {
|
||||
this.file = file.toAbsolutePath().normalize();
|
||||
try { load(); }
|
||||
catch (IOException | IllegalArgumentException error) {
|
||||
counts.clear();
|
||||
System.err.println("Could not load bucket activity: " + error.getMessage());
|
||||
}
|
||||
writer.scheduleWithFixedDelay(this::flushSafely, 60, 60, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
void record(String bucket, String method) {
|
||||
if (!validBucket(bucket)) return;
|
||||
if (!method.equals("GET") && !method.equals("HEAD") &&
|
||||
!method.equals("PUT") && !method.equals("POST") && !method.equals("DELETE")) return;
|
||||
long epochDay = Math.floorDiv(System.currentTimeMillis(), 86_400_000L);
|
||||
Counts day = counts.computeIfAbsent(new Key(bucket, epochDay),
|
||||
ignored -> new Counts());
|
||||
if (method.equals("GET") || method.equals("HEAD")) day.reads.increment();
|
||||
else day.writes.increment();
|
||||
dirty.set(true);
|
||||
}
|
||||
|
||||
List<Day> days(String bucket) {
|
||||
LocalDate today = LocalDate.now(ZoneOffset.UTC);
|
||||
LocalDate start = today.minusDays(DAYS - 1);
|
||||
List<Day> result = new ArrayList<>(DAYS);
|
||||
for (int offset = 0; offset < DAYS; offset++) {
|
||||
LocalDate date = start.plusDays(offset);
|
||||
Counts value = counts.get(new Key(bucket, date.toEpochDay()));
|
||||
result.add(new Day(date, value == null ? 0 : value.reads.sum(),
|
||||
value == null ? 0 : value.writes.sum()));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
synchronized void rename(String oldName, String newName) {
|
||||
if (oldName.equals(newName)) return;
|
||||
for (var entry : counts.entrySet()) {
|
||||
Key key = entry.getKey();
|
||||
if (!key.bucket.equals(oldName)) continue;
|
||||
Counts moved = counts.computeIfAbsent(new Key(newName, key.epochDay), ignored -> new Counts());
|
||||
moved.reads.add(entry.getValue().reads.sum());
|
||||
moved.writes.add(entry.getValue().writes.sum());
|
||||
counts.remove(key, entry.getValue());
|
||||
}
|
||||
dirty.set(true);
|
||||
}
|
||||
|
||||
synchronized void remove(String bucket) {
|
||||
counts.keySet().removeIf(key -> key.bucket.equals(bucket));
|
||||
dirty.set(true);
|
||||
}
|
||||
|
||||
private void load() throws IOException {
|
||||
if (!Files.exists(file)) return;
|
||||
if (Files.size(file) > 64L * 1024 * 1024)
|
||||
throw new IOException("Activity file is too large");
|
||||
List<String> lines = Files.readAllLines(file, StandardCharsets.UTF_8);
|
||||
if (lines.isEmpty() || !lines.getFirst().equals("ObjectStoreActivity 1"))
|
||||
throw new IOException("Invalid activity file header");
|
||||
LocalDate earliest = LocalDate.now(ZoneOffset.UTC).minusDays(DAYS - 1);
|
||||
for (int index = 1; index < lines.size(); index++) {
|
||||
String[] fields = lines.get(index).split("\\t", -1);
|
||||
if (fields.length != 4 || !validBucket(fields[0]))
|
||||
throw new IOException("Invalid activity record");
|
||||
try {
|
||||
LocalDate date = LocalDate.parse(fields[1]);
|
||||
long reads = Long.parseLong(fields[2]);
|
||||
long writes = Long.parseLong(fields[3]);
|
||||
if (reads < 0 || writes < 0) throw new NumberFormatException();
|
||||
if (date.isBefore(earliest) || date.isAfter(LocalDate.now(ZoneOffset.UTC))) continue;
|
||||
Counts value = counts.computeIfAbsent(new Key(fields[0], date.toEpochDay()),
|
||||
ignored -> new Counts());
|
||||
value.reads.add(reads);
|
||||
value.writes.add(writes);
|
||||
} catch (RuntimeException error) {
|
||||
throw new IOException("Invalid activity record", error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized void flushSafely() {
|
||||
if (!dirty.getAndSet(false)) return;
|
||||
try { flush(); }
|
||||
catch (IOException error) {
|
||||
dirty.set(true);
|
||||
System.err.println("Could not save bucket activity: " + error.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private void flush() throws IOException {
|
||||
LocalDate earliest = LocalDate.now(ZoneOffset.UTC).minusDays(DAYS - 1);
|
||||
counts.keySet().removeIf(key -> key.epochDay < earliest.toEpochDay());
|
||||
StringBuilder data = new StringBuilder("ObjectStoreActivity 1\n");
|
||||
counts.entrySet().stream().sorted((left, right) -> {
|
||||
int byBucket = left.getKey().bucket.compareTo(right.getKey().bucket);
|
||||
return byBucket == 0 ? Long.compare(left.getKey().epochDay, right.getKey().epochDay) : byBucket;
|
||||
}).forEach(entry -> data.append(entry.getKey().bucket).append('\t')
|
||||
.append(LocalDate.ofEpochDay(entry.getKey().epochDay)).append('\t')
|
||||
.append(entry.getValue().reads.sum())
|
||||
.append('\t').append(entry.getValue().writes.sum()).append('\n'));
|
||||
Path parent = file.getParent();
|
||||
Files.createDirectories(parent);
|
||||
Path temporary = Files.createTempFile(parent, "bucket-activity-", ".part");
|
||||
try {
|
||||
ByteBuffer bytes = StandardCharsets.UTF_8.encode(data.toString());
|
||||
try (FileChannel channel = FileChannel.open(temporary, StandardOpenOption.WRITE)) {
|
||||
while (bytes.hasRemaining()) channel.write(bytes);
|
||||
channel.force(true);
|
||||
}
|
||||
Files.move(temporary, file, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
|
||||
try (FileChannel directory = FileChannel.open(parent, StandardOpenOption.READ)) {
|
||||
directory.force(true);
|
||||
}
|
||||
} finally { Files.deleteIfExists(temporary); }
|
||||
}
|
||||
|
||||
private static boolean validBucket(String bucket) {
|
||||
if (bucket == null || bucket.length() < 3 || bucket.length() > 63 ||
|
||||
bucket.charAt(0) == '-' || bucket.charAt(bucket.length() - 1) == '-') return false;
|
||||
for (int index = 0; index < bucket.length(); index++) {
|
||||
char character = bucket.charAt(index);
|
||||
if (character != '-' && (character < 'a' || character > 'z') &&
|
||||
(character < '0' || character > '9')) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override public void close() {
|
||||
writer.shutdown();
|
||||
flushSafely();
|
||||
}
|
||||
}
|
||||
@@ -38,105 +38,254 @@ final class BucketHandler {
|
||||
}
|
||||
|
||||
void handleBucket(HttpExchange exchange, Map<String, String> query, String hash,
|
||||
String bucketName, String principal) throws IOException {
|
||||
String bucketName, String principal) throws IOException {
|
||||
String method = exchange.getRequestMethod();
|
||||
if (query.containsKey("acl") && query.get("acl").isEmpty() &&
|
||||
if (configurationRequest(query, "ownershipControls")) {
|
||||
access.requireOwner(principal);
|
||||
handleOwnership(exchange, hash, bucketName);
|
||||
} else if (configurationRequest(query, "publicAccessBlock")) {
|
||||
access.requireOwner(principal);
|
||||
handlePublicAccess(exchange, hash, bucketName);
|
||||
} else if (configurationRequest(query, "policy")) {
|
||||
access.requireOwner(principal);
|
||||
handlePolicy(exchange, hash, bucketName);
|
||||
} else if (aclRequest(query, method)) {
|
||||
handleAcl(exchange, hash, bucketName, principal);
|
||||
} else if (bucketRequest(query, method)) {
|
||||
handleBucketOperation(exchange, hash, bucketName, principal);
|
||||
} else {
|
||||
store.bucket(bucketName);
|
||||
handleExistingBucket(exchange, query, hash, bucketName, principal);
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean configurationRequest(Map<String, String> query, String configuration) {
|
||||
return query.size() >= 1 && query.size() <= 2 &&
|
||||
query.keySet().stream().allMatch(java.util.Set.of(configuration, "x-id")::contains) &&
|
||||
query.containsKey(configuration) && query.get(configuration).isEmpty();
|
||||
}
|
||||
|
||||
private static boolean aclRequest(Map<String, String> query, String method) {
|
||||
return query.containsKey("acl") && query.get("acl").isEmpty() &&
|
||||
query.keySet().stream().allMatch(java.util.Set.of("acl", "x-id")::contains) &&
|
||||
(!query.containsKey("x-id") ||
|
||||
query.get("x-id").equals(method.equals("GET") ? "GetBucketAcl" : "PutBucketAcl")) &&
|
||||
(method.equals("GET") || method.equals("PUT"))) {
|
||||
var current = store.bucket(bucketName);
|
||||
Acl.require(current.acl(), principal, owner,
|
||||
method.equals("GET") ? Acl.READ_ACP : Acl.WRITE_ACP);
|
||||
if (method.equals("GET")) {
|
||||
S3Request.requireEmptyBody(exchange, hash);
|
||||
S3Xml.sendXml(exchange, 200, Acl.xml(current.acl(), owner));
|
||||
} else {
|
||||
if (exchange.getRequestHeaders().containsKey("x-amz-acl") ||
|
||||
exchange.getRequestHeaders().keySet().stream().anyMatch(
|
||||
name -> name.toLowerCase(Locale.ROOT).startsWith("x-amz-grant-"))) {
|
||||
S3Request.requireEmptyBody(exchange, hash);
|
||||
S3Request.verifyContentMd5(exchange.getRequestHeaders(), new byte[0]);
|
||||
store.setBucketAcl(bucketName, Acl.fromHeaders(exchange.getRequestHeaders(),
|
||||
authentication.identities()));
|
||||
} else {
|
||||
byte[] body = S3Request.signedBody(exchange, hash, 65536);
|
||||
S3Request.verifyContentMd5(exchange.getRequestHeaders(), body);
|
||||
store.setBucketAcl(bucketName, Acl.fromXml(body,
|
||||
owner, authentication.identities()));
|
||||
}
|
||||
exchange.sendResponseHeaders(200, -1);
|
||||
}
|
||||
return;
|
||||
}
|
||||
String bucketOperation = switch (method) {
|
||||
(method.equals("GET") || method.equals("PUT"));
|
||||
}
|
||||
|
||||
private static boolean bucketRequest(Map<String, String> query, String method) {
|
||||
String operation = switch (method) {
|
||||
case "PUT" -> "CreateBucket";
|
||||
case "HEAD" -> "HeadBucket";
|
||||
case "DELETE" -> "DeleteBucket";
|
||||
default -> null;
|
||||
};
|
||||
if (bucketOperation != null && (query.isEmpty() ||
|
||||
query.size() == 1 && bucketOperation.equals(query.get("x-id")))) {
|
||||
S3Request.requireEmptyBody(exchange, hash);
|
||||
switch (method) {
|
||||
case "PUT" -> {
|
||||
access.requireOwner(principal);
|
||||
Map<String, String> acl = Acl.fromHeaders(exchange.getRequestHeaders(),
|
||||
authentication.identities());
|
||||
store.createBucket(bucketName);
|
||||
if (!acl.isEmpty()) store.setBucketAcl(bucketName, acl);
|
||||
exchange.getResponseHeaders().set("Location", "/" + bucketName);
|
||||
exchange.sendResponseHeaders(200, -1);
|
||||
}
|
||||
case "HEAD" -> {
|
||||
access.requireBucket(bucketName, principal, Acl.READ);
|
||||
exchange.sendResponseHeaders(200, -1);
|
||||
}
|
||||
case "DELETE" -> {
|
||||
access.requireOwner(principal);
|
||||
if (bucketName.equals(bucket))
|
||||
throw new StoreException(409, "BucketNotEmpty", "The configured default bucket cannot be deleted");
|
||||
synchronized (multipart) {
|
||||
if (!multipart.listUploads(bucketName, "").isEmpty())
|
||||
throw new StoreException(409, "BucketNotEmpty", "Bucket has active uploads");
|
||||
store.deleteBucket(bucketName);
|
||||
}
|
||||
exchange.sendResponseHeaders(204, -1);
|
||||
}
|
||||
return operation != null && (query.isEmpty() ||
|
||||
query.size() == 1 && operation.equals(query.get("x-id")));
|
||||
}
|
||||
|
||||
private void handleOwnership(HttpExchange exchange, String hash, String bucketName) throws IOException {
|
||||
switch (exchange.getRequestMethod()) {
|
||||
case "GET" -> {
|
||||
S3Request.requireEmptyBody(exchange, hash);
|
||||
S3Xml.sendXml(exchange, 200, BucketSecurity.ownershipXml(store.bucket(bucketName).ownership()));
|
||||
}
|
||||
return;
|
||||
case "PUT" -> {
|
||||
byte[] body = S3Request.signedBody(exchange, hash, 65536);
|
||||
S3Request.verifyContentMd5(exchange.getRequestHeaders(), body);
|
||||
store.setBucketOwnership(bucketName, BucketSecurity.parseOwnership(body));
|
||||
exchange.sendResponseHeaders(200, -1);
|
||||
}
|
||||
case "DELETE" -> {
|
||||
S3Request.requireEmptyBody(exchange, hash);
|
||||
store.setBucketOwnership(bucketName, ObjectStorage.ObjectOwnership.OBJECT_WRITER);
|
||||
exchange.sendResponseHeaders(204, -1);
|
||||
}
|
||||
default -> S3Request.unsupported("Ownership controls operation");
|
||||
}
|
||||
store.bucket(bucketName);
|
||||
String versioningOperation = method.equals("GET") ? "GetBucketVersioning" :
|
||||
method.equals("PUT") ? "PutBucketVersioning" : null;
|
||||
if (query.containsKey("versioning") && query.get("versioning").isEmpty() &&
|
||||
(query.size() == 1 || query.size() == 2 && versioningOperation != null &&
|
||||
versioningOperation.equals(query.get("x-id")))) {
|
||||
}
|
||||
|
||||
private void handlePublicAccess(HttpExchange exchange, String hash, String bucketName) throws IOException {
|
||||
switch (exchange.getRequestMethod()) {
|
||||
case "GET" -> {
|
||||
S3Request.requireEmptyBody(exchange, hash);
|
||||
S3Xml.sendXml(exchange, 200, BucketSecurity.publicAccessXml(
|
||||
store.bucket(bucketName).publicAccessBlock()));
|
||||
}
|
||||
case "PUT" -> {
|
||||
byte[] body = S3Request.signedBody(exchange, hash, 65536);
|
||||
S3Request.verifyContentMd5(exchange.getRequestHeaders(), body);
|
||||
store.setPublicAccessBlock(bucketName, BucketSecurity.parsePublicAccess(body));
|
||||
exchange.sendResponseHeaders(200, -1);
|
||||
}
|
||||
case "DELETE" -> {
|
||||
S3Request.requireEmptyBody(exchange, hash);
|
||||
store.setPublicAccessBlock(bucketName, ObjectStorage.PublicAccessBlock.open());
|
||||
exchange.sendResponseHeaders(204, -1);
|
||||
}
|
||||
default -> S3Request.unsupported("Public access block operation");
|
||||
}
|
||||
}
|
||||
|
||||
private void handlePolicy(HttpExchange exchange, String hash, String bucketName) throws IOException {
|
||||
var current = store.bucket(bucketName);
|
||||
switch (exchange.getRequestMethod()) {
|
||||
case "GET" -> {
|
||||
S3Request.requireEmptyBody(exchange, hash);
|
||||
if (current.policy() == null)
|
||||
throw new StoreException(404, "NoSuchBucketPolicy", "Bucket has no policy");
|
||||
byte[] body = current.policy().getBytes(StandardCharsets.UTF_8);
|
||||
exchange.getResponseHeaders().set("Content-Type", "application/json");
|
||||
exchange.sendResponseHeaders(200, body.length);
|
||||
exchange.getResponseBody().write(body);
|
||||
}
|
||||
case "PUT" -> {
|
||||
byte[] body = S3Request.signedBody(exchange, hash, 20480);
|
||||
S3Request.verifyContentMd5(exchange.getRequestHeaders(), body);
|
||||
String policy = new String(body, StandardCharsets.UTF_8);
|
||||
BucketPolicy parsed = BucketPolicy.parse(policy, bucketName);
|
||||
if (current.publicAccessBlock().blockPublicPolicy() && parsed.publicAllow())
|
||||
throw new StoreException(403, "AccessDenied", "Public bucket policies are blocked");
|
||||
store.setBucketPolicy(bucketName, policy);
|
||||
exchange.sendResponseHeaders(204, -1);
|
||||
}
|
||||
case "DELETE" -> {
|
||||
S3Request.requireEmptyBody(exchange, hash);
|
||||
store.setBucketPolicy(bucketName, null);
|
||||
exchange.sendResponseHeaders(204, -1);
|
||||
}
|
||||
default -> S3Request.unsupported("Bucket policy operation");
|
||||
}
|
||||
}
|
||||
|
||||
private void handleAcl(HttpExchange exchange, String hash, String bucketName, String principal) throws IOException {
|
||||
var current = store.bucket(bucketName);
|
||||
boolean get = exchange.getRequestMethod().equals("GET");
|
||||
access.requireBucket(bucketName, principal, get ? Acl.READ_ACP : Acl.WRITE_ACP);
|
||||
if (get) {
|
||||
S3Request.requireEmptyBody(exchange, hash);
|
||||
S3Xml.sendXml(exchange, 200, Acl.xml(
|
||||
current.ownership() == ObjectStorage.ObjectOwnership.BUCKET_OWNER_ENFORCED
|
||||
? Map.of() : current.acl(), owner));
|
||||
} else {
|
||||
if (current.ownership() == ObjectStorage.ObjectOwnership.BUCKET_OWNER_ENFORCED)
|
||||
throw new StoreException(400, "AccessControlListNotSupported", "ACLs are disabled for this bucket");
|
||||
Map<String, String> acl = readAcl(exchange, hash);
|
||||
BucketSecurity.checkAcl(current, exchange.getRequestHeaders(), acl, true);
|
||||
store.setBucketAcl(bucketName, acl);
|
||||
exchange.sendResponseHeaders(200, -1);
|
||||
}
|
||||
}
|
||||
|
||||
private Map<String, String> readAcl(HttpExchange exchange, String hash) throws IOException {
|
||||
if (exchange.getRequestHeaders().containsKey("x-amz-acl") ||
|
||||
exchange.getRequestHeaders().keySet().stream().anyMatch(
|
||||
name -> name.toLowerCase(Locale.ROOT).startsWith("x-amz-grant-"))) {
|
||||
S3Request.requireEmptyBody(exchange, hash);
|
||||
S3Request.verifyContentMd5(exchange.getRequestHeaders(), new byte[0]);
|
||||
return Acl.fromHeaders(exchange.getRequestHeaders(), authentication.identities());
|
||||
}
|
||||
byte[] body = S3Request.signedBody(exchange, hash, 65536);
|
||||
S3Request.verifyContentMd5(exchange.getRequestHeaders(), body);
|
||||
return Acl.fromXml(body, owner, authentication.identities());
|
||||
}
|
||||
|
||||
private void handleBucketOperation(HttpExchange exchange, String hash,
|
||||
String bucketName, String principal) throws IOException {
|
||||
S3Request.requireEmptyBody(exchange, hash);
|
||||
switch (exchange.getRequestMethod()) {
|
||||
case "PUT" -> {
|
||||
access.requireOwner(principal);
|
||||
createBucket(exchange, bucketName);
|
||||
}
|
||||
case "HEAD" -> {
|
||||
access.requireBucket(bucketName, principal, Acl.READ);
|
||||
exchange.sendResponseHeaders(200, -1);
|
||||
}
|
||||
case "DELETE" -> {
|
||||
access.requireOwner(principal);
|
||||
deleteBucket(exchange, bucketName);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void createBucket(HttpExchange exchange, String bucketName) throws IOException {
|
||||
String requestedOwnership = SigV4.single(exchange.getRequestHeaders(), "x-amz-object-ownership");
|
||||
ObjectStorage.ObjectOwnership ownership = requestedOwnership == null
|
||||
? ObjectStorage.ObjectOwnership.BUCKET_OWNER_ENFORCED
|
||||
: BucketSecurity.ownership(requestedOwnership);
|
||||
Map<String, String> acl = Acl.fromHeaders(exchange.getRequestHeaders(), authentication.identities());
|
||||
BucketSecurity.checkAcl(new ObjectStorage.Bucket(bucketName, 0,
|
||||
ObjectStorage.VersioningState.NEVER, Map.of(), ownership,
|
||||
ObjectStorage.PublicAccessBlock.secure(), null),
|
||||
exchange.getRequestHeaders(), acl, false);
|
||||
store.createBucket(bucketName);
|
||||
if (requestedOwnership != null && ownership != ObjectStorage.ObjectOwnership.BUCKET_OWNER_ENFORCED)
|
||||
store.setBucketOwnership(bucketName, ownership);
|
||||
if (!acl.isEmpty()) store.setBucketAcl(bucketName, acl);
|
||||
exchange.getResponseHeaders().set("Location", "/" + bucketName);
|
||||
exchange.sendResponseHeaders(200, -1);
|
||||
}
|
||||
|
||||
private void deleteBucket(HttpExchange exchange, String bucketName) throws IOException {
|
||||
if (bucketName.equals(bucket))
|
||||
throw new StoreException(409, "BucketNotEmpty", "The configured default bucket cannot be deleted");
|
||||
synchronized (multipart) {
|
||||
if (!multipart.listUploads(bucketName, "").isEmpty())
|
||||
throw new StoreException(409, "BucketNotEmpty", "Bucket has active uploads");
|
||||
store.deleteBucket(bucketName);
|
||||
}
|
||||
exchange.sendResponseHeaders(204, -1);
|
||||
}
|
||||
|
||||
private void handleExistingBucket(HttpExchange exchange, Map<String, String> query, String hash,
|
||||
String bucketName, String principal) throws IOException {
|
||||
String method = exchange.getRequestMethod();
|
||||
if (versioningRequest(query, method)) {
|
||||
access.requireOwner(principal);
|
||||
handleVersioning(exchange, hash, bucketName);
|
||||
return;
|
||||
}
|
||||
if (method.equals("GET") && query.containsKey("versions") && query.get("versions").isEmpty()) {
|
||||
} else if (method.equals("GET") && query.containsKey("versions") && query.get("versions").isEmpty()) {
|
||||
access.requireOwner(principal);
|
||||
if (!query.keySet().stream().allMatch(java.util.Set.of("versions", "prefix", "key-marker",
|
||||
"version-id-marker", "max-keys", "encoding-type", "x-id")::contains) ||
|
||||
query.containsKey("x-id") && !"ListObjectVersions".equals(query.get("x-id")))
|
||||
S3Request.unsupported("Version listing option");
|
||||
S3Request.requireEmptyBody(exchange, hash);
|
||||
listVersions(exchange, query, bucketName);
|
||||
return;
|
||||
}
|
||||
if (exchange.getRequestMethod().equals("GET") && query.containsKey("uploads")) {
|
||||
handleListVersions(exchange, query, hash, bucketName);
|
||||
} else if (method.equals("GET") && query.containsKey("uploads")) {
|
||||
access.requireOwner(principal);
|
||||
if (!query.get("uploads").isEmpty() ||
|
||||
!query.keySet().stream().allMatch(java.util.Set.of("uploads", "prefix", "key-marker",
|
||||
"upload-id-marker", "max-uploads", "x-id")::contains) ||
|
||||
(query.containsKey("x-id") && !"ListMultipartUploads".equals(query.get("x-id"))))
|
||||
S3Request.unsupported("Bucket operation");
|
||||
S3Request.requireEmptyBody(exchange, hash);
|
||||
multipartHandler.listUploads(exchange, query, bucketName);
|
||||
return;
|
||||
handleListUploads(exchange, query, hash, bucketName);
|
||||
} else {
|
||||
handleListObjects(exchange, query, hash, bucketName, principal);
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean versioningRequest(Map<String, String> query, String method) {
|
||||
String operation = method.equals("GET") ? "GetBucketVersioning" :
|
||||
method.equals("PUT") ? "PutBucketVersioning" : null;
|
||||
return query.containsKey("versioning") && query.get("versioning").isEmpty() &&
|
||||
(query.size() == 1 || query.size() == 2 && operation != null &&
|
||||
operation.equals(query.get("x-id")));
|
||||
}
|
||||
|
||||
private void handleListVersions(HttpExchange exchange, Map<String, String> query,
|
||||
String hash, String bucketName) throws IOException {
|
||||
if (!query.keySet().stream().allMatch(java.util.Set.of("versions", "prefix", "key-marker",
|
||||
"version-id-marker", "max-keys", "encoding-type", "x-id")::contains) ||
|
||||
query.containsKey("x-id") && !"ListObjectVersions".equals(query.get("x-id")))
|
||||
S3Request.unsupported("Version listing option");
|
||||
S3Request.requireEmptyBody(exchange, hash);
|
||||
listVersions(exchange, query, bucketName);
|
||||
}
|
||||
|
||||
private void handleListUploads(HttpExchange exchange, Map<String, String> query,
|
||||
String hash, String bucketName) throws IOException {
|
||||
if (!query.get("uploads").isEmpty() ||
|
||||
!query.keySet().stream().allMatch(java.util.Set.of("uploads", "prefix", "key-marker",
|
||||
"upload-id-marker", "max-uploads", "x-id")::contains) ||
|
||||
(query.containsKey("x-id") && !"ListMultipartUploads".equals(query.get("x-id"))))
|
||||
S3Request.unsupported("Bucket operation");
|
||||
S3Request.requireEmptyBody(exchange, hash);
|
||||
multipartHandler.listUploads(exchange, query, bucketName);
|
||||
}
|
||||
|
||||
private void handleListObjects(HttpExchange exchange, Map<String, String> query, String hash,
|
||||
String bucketName, String principal) throws IOException {
|
||||
if (!exchange.getRequestMethod().equals("GET") || !"2".equals(query.get("list-type")) ||
|
||||
!query.keySet().stream().allMatch(java.util.Set.of("list-type", "prefix", "delimiter", "max-keys",
|
||||
"continuation-token", "start-after", "encoding-type", "x-id")::contains) ||
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import java.io.IOException;
|
||||
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.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
final class BucketNameCatalog {
|
||||
private final DiskStore store;
|
||||
private final Path catalog;
|
||||
private final Path deletion;
|
||||
|
||||
BucketNameCatalog(DiskStore store) {
|
||||
this.store = store;
|
||||
catalog = store.root().resolve("bucket-names.txt");
|
||||
deletion = store.root().resolve("bucket-name-deletion.txt");
|
||||
}
|
||||
|
||||
Map<String, String> load() throws IOException {
|
||||
Map<String, String> loaded = new HashMap<>();
|
||||
if (Files.exists(catalog)) {
|
||||
for (String line : Files.readAllLines(catalog, StandardCharsets.UTF_8)) {
|
||||
String[] names = parse(line);
|
||||
if (loaded.putIfAbsent(names[0], names[1]) != null)
|
||||
throw new IOException("Duplicate bucket alias");
|
||||
}
|
||||
}
|
||||
Set<String> physical = store.buckets().stream().map(ObjectStorage.Bucket::name)
|
||||
.collect(Collectors.toSet());
|
||||
if (Files.exists(deletion)) {
|
||||
String[] names = parse(Files.readString(deletion, StandardCharsets.UTF_8).strip());
|
||||
String target = loaded.get(names[0]);
|
||||
if (target != null && !target.equals(names[1]))
|
||||
throw new IOException("Bucket deletion conflicts with name catalog");
|
||||
if (!physical.contains(names[1])) {
|
||||
loaded.remove(names[0]);
|
||||
save(loaded);
|
||||
}
|
||||
finishDelete();
|
||||
}
|
||||
if (!physical.containsAll(loaded.values()) ||
|
||||
loaded.values().stream().distinct().count() != loaded.size() ||
|
||||
loaded.keySet().stream().anyMatch(physical::contains))
|
||||
throw new IOException("Bucket name catalog conflicts with stored buckets");
|
||||
return Map.copyOf(loaded);
|
||||
}
|
||||
|
||||
private static String[] parse(String line) throws IOException {
|
||||
String[] names = line.split("\t", -1);
|
||||
if (names.length != 2 || !valid(names[0]) || !valid(names[1]) || names[0].equals(names[1]))
|
||||
throw new IOException("Invalid bucket name catalog");
|
||||
return names;
|
||||
}
|
||||
|
||||
private static boolean valid(String name) {
|
||||
return name.matches("[a-z0-9][a-z0-9-]{1,61}[a-z0-9]");
|
||||
}
|
||||
|
||||
void save(Map<String, String> next) throws IOException {
|
||||
StringBuilder text = new StringBuilder();
|
||||
next.entrySet().stream().sorted(Map.Entry.comparingByKey()).forEach(entry ->
|
||||
text.append(entry.getKey()).append('\t').append(entry.getValue()).append('\n'));
|
||||
write(catalog, text.toString());
|
||||
}
|
||||
|
||||
void beginDelete(String visible, String physical) throws IOException {
|
||||
if (Files.exists(deletion))
|
||||
throw new IOException("An interrupted bucket deletion requires a restart before deleting another renamed bucket");
|
||||
write(deletion, visible + "\t" + physical + "\n");
|
||||
}
|
||||
|
||||
void finishDelete() throws IOException {
|
||||
Files.deleteIfExists(deletion);
|
||||
DiskStore.syncDirectory(store.root());
|
||||
}
|
||||
|
||||
private void write(Path destination, String text) throws IOException {
|
||||
Path pending = Files.createTempFile(store.root().resolve("pending"), "bucket-names-", ".part");
|
||||
try {
|
||||
Files.writeString(pending, text, StandardCharsets.UTF_8);
|
||||
try (FileChannel channel = FileChannel.open(pending, StandardOpenOption.WRITE)) {
|
||||
channel.force(true);
|
||||
}
|
||||
Files.move(pending, destination, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
|
||||
DiskStore.syncDirectory(store.root());
|
||||
} finally {
|
||||
Files.deleteIfExists(pending);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
final class BucketPolicy {
|
||||
private static final BucketPolicy EMPTY = new BucketPolicy(List.of());
|
||||
private record Statement(boolean allow, List<String> principals, List<String> actions,
|
||||
List<String> resources) {
|
||||
boolean matches(String principal, String action, String resource) {
|
||||
return (principals.contains("*") || principal != null && principals.contains(principal)) &&
|
||||
actions.stream().anyMatch(pattern -> glob(pattern, action)) &&
|
||||
resources.stream().anyMatch(pattern -> glob(pattern, resource));
|
||||
}
|
||||
}
|
||||
|
||||
private final List<Statement> statements;
|
||||
private final boolean publicAllow;
|
||||
|
||||
private BucketPolicy(List<Statement> statements) {
|
||||
this.statements = List.copyOf(statements);
|
||||
this.publicAllow = statements.stream().anyMatch(
|
||||
statement -> statement.allow() && statement.principals().contains("*"));
|
||||
}
|
||||
|
||||
static BucketPolicy empty() { return EMPTY; }
|
||||
|
||||
boolean publicAllow() { return publicAllow; }
|
||||
|
||||
int decide(String principal, String action, String resource) {
|
||||
boolean allowed = false;
|
||||
for (Statement statement : statements) {
|
||||
if (!statement.matches(principal, action, resource)) continue;
|
||||
if (!statement.allow()) return -1;
|
||||
allowed = true;
|
||||
}
|
||||
return allowed ? 1 : 0;
|
||||
}
|
||||
|
||||
static BucketPolicy parse(String json, String bucket) {
|
||||
return parse(json, bucket, false);
|
||||
}
|
||||
|
||||
static BucketPolicy parseIdentity(String json) {
|
||||
return parse(json, null, true);
|
||||
}
|
||||
|
||||
private static BucketPolicy parse(String json, String bucket, boolean identity) {
|
||||
if (json == null || json.isBlank() || json.getBytes(StandardCharsets.UTF_8).length > 20480)
|
||||
throw invalid();
|
||||
Object parsed = new Parser(json).parse();
|
||||
Map<String, Object> policy = object(parsed);
|
||||
if (!policy.keySet().stream().allMatch(Set.of("Version", "Id", "Statement")::contains) ||
|
||||
!"2012-10-17".equals(policy.get("Version"))) throw invalid();
|
||||
Object raw = policy.get("Statement");
|
||||
if (raw == null) throw invalid();
|
||||
List<?> entries = raw instanceof List<?> list ? list : List.of(raw);
|
||||
if (entries.isEmpty() || entries.size() > 64) throw invalid();
|
||||
List<Statement> statements = new ArrayList<>();
|
||||
for (Object entry : entries) {
|
||||
Map<String, Object> item = object(entry);
|
||||
Set<String> keys = identity ? Set.of("Sid", "Effect", "Action", "Resource") :
|
||||
Set.of("Sid", "Effect", "Principal", "Action", "Resource");
|
||||
if (!item.keySet().stream().allMatch(keys::contains))
|
||||
throw invalid();
|
||||
boolean allow;
|
||||
if ("Allow".equals(item.get("Effect"))) allow = true;
|
||||
else if ("Deny".equals(item.get("Effect"))) allow = false;
|
||||
else throw invalid();
|
||||
Object principal = item.get("Principal");
|
||||
List<String> principals = identity ? List.of("*") : principal instanceof Map<?, ?> map
|
||||
? strings(object(map).get("AWS")) : strings(principal);
|
||||
if (!identity && principal instanceof Map<?, ?> map && !map.keySet().equals(Set.of("AWS")))
|
||||
throw invalid();
|
||||
for (String name : principals)
|
||||
if (!name.equals("*") && !name.matches("[A-Za-z0-9]{16,128}")) throw invalid();
|
||||
List<String> actions = strings(item.get("Action"));
|
||||
for (String action : actions)
|
||||
if (!action.matches("s3:[A-Za-z*]+")) throw invalid();
|
||||
List<String> resources = strings(item.get("Resource"));
|
||||
String bucketArn = "arn:aws:s3:::" + bucket;
|
||||
for (String resource : resources)
|
||||
if (identity ? !resource.matches("arn:aws:s3:::[a-z0-9*?][a-z0-9*?.-]{0,62}(/[^\\p{Cntrl}]+)?") :
|
||||
!resource.equals(bucketArn) && !resource.startsWith(bucketArn + "/")) throw invalid();
|
||||
statements.add(new Statement(allow, principals, actions, resources));
|
||||
}
|
||||
return new BucketPolicy(statements);
|
||||
}
|
||||
|
||||
private static List<String> strings(Object value) {
|
||||
if (value == null) throw invalid();
|
||||
List<?> values = value instanceof List<?> list ? list : List.of(value);
|
||||
if (values.isEmpty() || values.size() > 64) throw invalid();
|
||||
List<String> result = new ArrayList<>();
|
||||
for (Object item : values) {
|
||||
if (!(item instanceof String text) || text.isBlank() || text.length() > 1024)
|
||||
throw invalid();
|
||||
result.add(text);
|
||||
}
|
||||
return List.copyOf(result);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static Map<String, Object> object(Object value) {
|
||||
if (!(value instanceof Map<?, ?>)) throw invalid();
|
||||
return (Map<String, Object>) value;
|
||||
}
|
||||
|
||||
private static StoreException invalid() {
|
||||
return new StoreException(400, "MalformedPolicy", "Unsupported or malformed bucket policy");
|
||||
}
|
||||
|
||||
private static boolean glob(String pattern, String text) {
|
||||
int p = 0;
|
||||
int t = 0;
|
||||
int star = -1;
|
||||
int retry = 0;
|
||||
while (t < text.length()) {
|
||||
if (p < pattern.length() && pattern.charAt(p) == text.charAt(t)) {
|
||||
p++;
|
||||
t++;
|
||||
} else if (p < pattern.length() && pattern.charAt(p) == '*') {
|
||||
star = p++;
|
||||
retry = t;
|
||||
} else if (star >= 0) {
|
||||
p = star + 1;
|
||||
t = ++retry;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
while (p < pattern.length() && pattern.charAt(p) == '*') p++;
|
||||
return p == pattern.length();
|
||||
}
|
||||
|
||||
private static final class Parser {
|
||||
private final String input;
|
||||
private int index;
|
||||
|
||||
Parser(String input) { this.input = input; }
|
||||
|
||||
Object parse() {
|
||||
Object value = value(0);
|
||||
space();
|
||||
if (index != input.length()) throw invalid();
|
||||
return value;
|
||||
}
|
||||
|
||||
private Object value(int depth) {
|
||||
if (depth > 16) throw invalid();
|
||||
space();
|
||||
if (index == input.length()) throw invalid();
|
||||
return switch (input.charAt(index)) {
|
||||
case '"' -> string();
|
||||
case '{' -> object(depth + 1);
|
||||
case '[' -> array(depth + 1);
|
||||
default -> throw invalid();
|
||||
};
|
||||
}
|
||||
|
||||
private Map<String, Object> object(int depth) {
|
||||
index++;
|
||||
Map<String, Object> map = new LinkedHashMap<>();
|
||||
space();
|
||||
if (take('}')) return map;
|
||||
do {
|
||||
space();
|
||||
if (index == input.length() || input.charAt(index) != '"') throw invalid();
|
||||
String key = string();
|
||||
space();
|
||||
expect(':');
|
||||
if (map.putIfAbsent(key, value(depth)) != null) throw invalid();
|
||||
space();
|
||||
if (take('}')) return map;
|
||||
expect(',');
|
||||
} while (true);
|
||||
}
|
||||
|
||||
private List<Object> array(int depth) {
|
||||
index++;
|
||||
List<Object> list = new ArrayList<>();
|
||||
space();
|
||||
if (take(']')) return list;
|
||||
do {
|
||||
if (list.size() >= 64) throw invalid();
|
||||
list.add(value(depth));
|
||||
space();
|
||||
if (take(']')) return list;
|
||||
expect(',');
|
||||
} while (true);
|
||||
}
|
||||
|
||||
private String string() {
|
||||
expect('"');
|
||||
StringBuilder result = new StringBuilder();
|
||||
while (index < input.length()) {
|
||||
char c = input.charAt(index++);
|
||||
if (c == '"') return result.toString();
|
||||
if (c < 0x20) throw invalid();
|
||||
if (c != '\\') {
|
||||
result.append(c);
|
||||
continue;
|
||||
}
|
||||
if (index == input.length()) throw invalid();
|
||||
char escape = input.charAt(index++);
|
||||
switch (escape) {
|
||||
case '"', '\\', '/' -> result.append(escape);
|
||||
case 'b' -> result.append('\b');
|
||||
case 'f' -> result.append('\f');
|
||||
case 'n' -> result.append('\n');
|
||||
case 'r' -> result.append('\r');
|
||||
case 't' -> result.append('\t');
|
||||
case 'u' -> {
|
||||
if (index + 4 > input.length()) throw invalid();
|
||||
try { result.append((char) Integer.parseInt(input.substring(index, index + 4), 16)); }
|
||||
catch (NumberFormatException error) { throw invalid(); }
|
||||
index += 4;
|
||||
}
|
||||
default -> throw invalid();
|
||||
}
|
||||
}
|
||||
throw invalid();
|
||||
}
|
||||
|
||||
private void space() {
|
||||
while (index < input.length() && Character.isWhitespace(input.charAt(index))) index++;
|
||||
}
|
||||
|
||||
private boolean take(char expected) {
|
||||
if (index < input.length() && input.charAt(index) == expected) {
|
||||
index++;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private void expect(char expected) {
|
||||
if (!take(expected)) throw invalid();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import com.sun.net.httpserver.Headers;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import javax.xml.XMLConstants;
|
||||
import javax.xml.parsers.DocumentBuilderFactory;
|
||||
import org.w3c.dom.Element;
|
||||
|
||||
final class BucketSecurity {
|
||||
private BucketSecurity() { }
|
||||
|
||||
static String ownershipName(ObjectStorage.ObjectOwnership ownership) {
|
||||
return switch (ownership) {
|
||||
case BUCKET_OWNER_ENFORCED -> "BucketOwnerEnforced";
|
||||
case BUCKET_OWNER_PREFERRED -> "BucketOwnerPreferred";
|
||||
case OBJECT_WRITER -> "ObjectWriter";
|
||||
};
|
||||
}
|
||||
|
||||
static ObjectStorage.ObjectOwnership ownership(String value) {
|
||||
return switch (value) {
|
||||
case "BucketOwnerEnforced" -> ObjectStorage.ObjectOwnership.BUCKET_OWNER_ENFORCED;
|
||||
case "BucketOwnerPreferred" -> ObjectStorage.ObjectOwnership.BUCKET_OWNER_PREFERRED;
|
||||
case "ObjectWriter" -> ObjectStorage.ObjectOwnership.OBJECT_WRITER;
|
||||
default -> throw new StoreException(400, "InvalidArgument", "Invalid object ownership setting");
|
||||
};
|
||||
}
|
||||
|
||||
static String ownershipXml(ObjectStorage.ObjectOwnership ownership) {
|
||||
return "<OwnershipControls xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">" +
|
||||
"<Rule><ObjectOwnership>" + ownershipName(ownership) +
|
||||
"</ObjectOwnership></Rule></OwnershipControls>";
|
||||
}
|
||||
|
||||
static ObjectStorage.ObjectOwnership parseOwnership(byte[] body) {
|
||||
Element root = root(body, "OwnershipControls");
|
||||
Element rule = onlyChild(root, "Rule");
|
||||
return ownership(onlyChild(rule, "ObjectOwnership").getTextContent().trim());
|
||||
}
|
||||
|
||||
static String publicAccessXml(ObjectStorage.PublicAccessBlock block) {
|
||||
return "<PublicAccessBlockConfiguration xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">" +
|
||||
"<BlockPublicAcls>" + block.blockPublicAcls() + "</BlockPublicAcls>" +
|
||||
"<IgnorePublicAcls>" + block.ignorePublicAcls() + "</IgnorePublicAcls>" +
|
||||
"<BlockPublicPolicy>" + block.blockPublicPolicy() + "</BlockPublicPolicy>" +
|
||||
"<RestrictPublicBuckets>" + block.restrictPublicBuckets() +
|
||||
"</RestrictPublicBuckets></PublicAccessBlockConfiguration>";
|
||||
}
|
||||
|
||||
static ObjectStorage.PublicAccessBlock parsePublicAccess(byte[] body) {
|
||||
Element root = root(body, "PublicAccessBlockConfiguration");
|
||||
if (elements(root) != 4) malformed();
|
||||
return new ObjectStorage.PublicAccessBlock(
|
||||
bool(onlyNamedChild(root, "BlockPublicAcls")),
|
||||
bool(onlyNamedChild(root, "IgnorePublicAcls")),
|
||||
bool(onlyNamedChild(root, "BlockPublicPolicy")),
|
||||
bool(onlyNamedChild(root, "RestrictPublicBuckets")));
|
||||
}
|
||||
|
||||
static void checkAcl(ObjectStorage.Bucket bucket, Headers headers, Map<String, String> acl,
|
||||
boolean aclOperation) {
|
||||
if (bucket.ownership() == ObjectStorage.ObjectOwnership.BUCKET_OWNER_ENFORCED) {
|
||||
String canned = SigV4.single(headers, "x-amz-acl");
|
||||
if (aclOperation || !acl.isEmpty() ||
|
||||
canned != null && !canned.equals("bucket-owner-full-control"))
|
||||
throw new StoreException(400, "AccessControlListNotSupported", "ACLs are disabled for this bucket");
|
||||
}
|
||||
if (bucket.publicAccessBlock().blockPublicAcls() && isPublic(acl))
|
||||
throw new StoreException(403, "AccessDenied", "Public ACLs are blocked for this bucket");
|
||||
}
|
||||
|
||||
static boolean allowsAcl(ObjectStorage.Bucket bucket, Map<String, String> acl,
|
||||
String principal, String owner, int permission) {
|
||||
if (bucket.ownership() == ObjectStorage.ObjectOwnership.BUCKET_OWNER_ENFORCED)
|
||||
return owner.equals(principal);
|
||||
if (bucket.publicAccessBlock().ignorePublicAcls() && isPublicPrincipal(principal))
|
||||
return false;
|
||||
if (bucket.publicAccessBlock().ignorePublicAcls())
|
||||
acl = acl.entrySet().stream()
|
||||
.filter(entry -> !isPublicPrincipal(entry.getKey()))
|
||||
.collect(java.util.stream.Collectors.toUnmodifiableMap(Map.Entry::getKey, Map.Entry::getValue));
|
||||
return Acl.allows(acl, principal, owner, permission);
|
||||
}
|
||||
|
||||
static boolean isPublic(Map<String, String> acl) {
|
||||
return acl.containsKey(Acl.ALL_USERS) || acl.containsKey(Acl.AUTHENTICATED_USERS);
|
||||
}
|
||||
|
||||
private static boolean isPublicPrincipal(String principal) {
|
||||
return Acl.ALL_USERS.equals(principal) || Acl.AUTHENTICATED_USERS.equals(principal);
|
||||
}
|
||||
|
||||
private static boolean bool(Element element) {
|
||||
if (elements(element) != 0) malformed();
|
||||
return switch (element.getTextContent().trim().toLowerCase(java.util.Locale.ROOT)) {
|
||||
case "true" -> true;
|
||||
case "false" -> false;
|
||||
default -> throw new StoreException(400, "MalformedXML", "Invalid public access block setting");
|
||||
};
|
||||
}
|
||||
|
||||
private static Element root(byte[] body, String name) {
|
||||
try {
|
||||
var factory = DocumentBuilderFactory.newInstance();
|
||||
factory.setNamespaceAware(true);
|
||||
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
|
||||
factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
|
||||
factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
|
||||
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
|
||||
factory.setExpandEntityReferences(false);
|
||||
Element root = factory.newDocumentBuilder().parse(new ByteArrayInputStream(body)).getDocumentElement();
|
||||
if (!name.equals(root.getLocalName())) malformed();
|
||||
return root;
|
||||
} catch (StoreException error) { throw error; }
|
||||
catch (Exception error) { throw new StoreException(400, "MalformedXML", "Invalid bucket configuration"); }
|
||||
}
|
||||
|
||||
private static Element onlyChild(Element parent, String name) {
|
||||
if (elements(parent) != 1) malformed();
|
||||
return onlyNamedChild(parent, name);
|
||||
}
|
||||
|
||||
private static Element onlyNamedChild(Element parent, String name) {
|
||||
var children = parent.getChildNodes();
|
||||
Element found = null;
|
||||
for (int i = 0; i < children.getLength(); i++) {
|
||||
if (children.item(i) instanceof Element child && name.equals(child.getLocalName())) {
|
||||
if (found != null) malformed();
|
||||
found = child;
|
||||
}
|
||||
}
|
||||
if (found == null) malformed();
|
||||
return found;
|
||||
}
|
||||
|
||||
private static int elements(Element parent) {
|
||||
int count = 0;
|
||||
var children = parent.getChildNodes();
|
||||
for (int i = 0; i < children.getLength(); i++)
|
||||
if (children.item(i) instanceof Element) count++;
|
||||
return count;
|
||||
}
|
||||
|
||||
private static void malformed() {
|
||||
throw new StoreException(400, "MalformedXML", "Invalid bucket configuration");
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import static cloud.lunarsky.store.ClusterStore.*;
|
||||
|
||||
final class ClusterMonitor {
|
||||
@FunctionalInterface
|
||||
interface Connections { Connection open() throws SQLException; }
|
||||
private final Connections connections;
|
||||
private final NodeClient nodes;
|
||||
private volatile ClusterStatus cachedStatus;
|
||||
private volatile long statusUntil;
|
||||
|
||||
ClusterMonitor(Connections connections, NodeClient nodes) {
|
||||
this.connections = connections;
|
||||
this.nodes = nodes;
|
||||
}
|
||||
|
||||
synchronized ClusterStatus status() {
|
||||
long now = System.nanoTime();
|
||||
ClusterStatus cached = cachedStatus;
|
||||
if (cached != null && now < statusUntil) return cached;
|
||||
boolean writable = false;
|
||||
RepairStatus repair = null;
|
||||
Map<UUID, Long> verifiedReplicas = new java.util.HashMap<>();
|
||||
try (Connection connection = connections.open(); var statement = connection.createStatement()) {
|
||||
connection.setAutoCommit(false);
|
||||
connection.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
|
||||
try (ResultSet result = statement.executeQuery(
|
||||
"SELECT NOT pg_is_in_recovery() AND current_setting('transaction_read_only') = 'off'")) {
|
||||
writable = result.next() && result.getBoolean(1);
|
||||
}
|
||||
try (ResultSet result = statement.executeQuery("SELECT started_at, updated_at, finished_at, state, " +
|
||||
"scanned, restored, rebalanced, under_replicated, unrecoverable " +
|
||||
"FROM cluster_repair_status WHERE singleton=1")) {
|
||||
if (result.next()) repair = new RepairStatus(result.getLong(1), result.getLong(2),
|
||||
result.getLong(3), result.getString(4),
|
||||
new RepairReport(result.getInt(5), result.getInt(6), result.getInt(7),
|
||||
result.getInt(8), result.getInt(9)));
|
||||
}
|
||||
if (repair != null && repair.state().equals("completed")) {
|
||||
try (PreparedStatement query = connection.prepareStatement(
|
||||
"SELECT node_id, verified_replicas FROM cluster_repair_node_counts " +
|
||||
"WHERE finished_at >= ?")) {
|
||||
query.setLong(1, repair.startedAt());
|
||||
try (ResultSet result = query.executeQuery()) {
|
||||
while (result.next())
|
||||
verifiedReplicas.put((UUID) result.getObject(1), result.getLong(2));
|
||||
}
|
||||
}
|
||||
}
|
||||
connection.commit();
|
||||
} catch (SQLException unavailable) { writable = false; }
|
||||
List<NodeClient.Node> configured = nodes.nodes();
|
||||
int visible = Math.min(64, configured.size());
|
||||
List<NodeStatus> live = new ArrayList<>();
|
||||
try (var executor = java.util.concurrent.Executors.newVirtualThreadPerTaskExecutor()) {
|
||||
java.util.concurrent.Semaphore slots = new java.util.concurrent.Semaphore(16);
|
||||
List<java.util.concurrent.Future<NodeStatus>> checks = new ArrayList<>();
|
||||
for (int i = 0; i < visible; i++) {
|
||||
NodeClient.Node node = configured.get(i);
|
||||
checks.add(executor.submit(() -> {
|
||||
slots.acquireUninterruptibly();
|
||||
try { return new NodeStatus(node, nodes.reachable(node)); }
|
||||
finally { slots.release(); }
|
||||
}));
|
||||
}
|
||||
for (var check : checks) {
|
||||
try { live.add(check.get()); }
|
||||
catch (Exception error) { live.add(new NodeStatus(configured.get(live.size()), false)); }
|
||||
}
|
||||
}
|
||||
ClusterStatus snapshot = new ClusterStatus(writable, List.copyOf(live),
|
||||
configured.size() - visible, repair, Map.copyOf(verifiedReplicas),
|
||||
System.currentTimeMillis());
|
||||
cachedStatus = snapshot;
|
||||
statusUntil = System.nanoTime() + java.util.concurrent.TimeUnit.SECONDS.toNanos(15);
|
||||
return snapshot;
|
||||
}
|
||||
void completeRepair(long startedAt, RepairReport report, Map<UUID, Long> counts) {
|
||||
try (Connection connection = connections.open()) {
|
||||
connection.setAutoCommit(false);
|
||||
long now = System.currentTimeMillis();
|
||||
try (var clear = connection.createStatement()) {
|
||||
clear.executeUpdate("DELETE FROM cluster_repair_node_counts");
|
||||
}
|
||||
try (PreparedStatement insert = connection.prepareStatement(
|
||||
"INSERT INTO cluster_repair_node_counts VALUES (?, ?, ?)")) {
|
||||
for (var entry : counts.entrySet()) {
|
||||
insert.setObject(1, entry.getKey());
|
||||
insert.setLong(2, entry.getValue());
|
||||
insert.setLong(3, now);
|
||||
insert.addBatch();
|
||||
}
|
||||
insert.executeBatch();
|
||||
}
|
||||
writeRepairStatus(connection, "completed", startedAt, now, report);
|
||||
connection.commit();
|
||||
cachedStatus = null;
|
||||
} catch (SQLException error) {
|
||||
System.err.println("Cluster repair summary could not be saved: " + error.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
void recordRepairStatus(String state, long startedAt, RepairReport report) {
|
||||
try (Connection connection = connections.open()) {
|
||||
writeRepairStatus(connection, state, startedAt, System.currentTimeMillis(), report);
|
||||
cachedStatus = null;
|
||||
} catch (SQLException error) {
|
||||
System.err.println("Cluster repair status could not be saved: " + error.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private void writeRepairStatus(Connection connection, String state, long startedAt, long now,
|
||||
RepairReport report) throws SQLException {
|
||||
try (PreparedStatement update = connection.prepareStatement(
|
||||
"INSERT INTO cluster_repair_status (singleton, started_at, updated_at, finished_at, state, " +
|
||||
"scanned, restored, rebalanced, under_replicated, unrecoverable) " +
|
||||
"VALUES (1, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT (singleton) DO UPDATE SET " +
|
||||
"started_at=EXCLUDED.started_at, updated_at=EXCLUDED.updated_at, " +
|
||||
"finished_at=EXCLUDED.finished_at, state=EXCLUDED.state, " +
|
||||
"scanned=EXCLUDED.scanned, restored=EXCLUDED.restored, " +
|
||||
"rebalanced=EXCLUDED.rebalanced, under_replicated=EXCLUDED.under_replicated, " +
|
||||
"unrecoverable=EXCLUDED.unrecoverable")) {
|
||||
update.setLong(1, startedAt);
|
||||
update.setLong(2, now);
|
||||
update.setLong(3, state.equals("running") ? 0 : now);
|
||||
update.setString(4, state);
|
||||
update.setInt(5, report.scanned());
|
||||
update.setInt(6, report.restored());
|
||||
update.setInt(7, report.rebalanced());
|
||||
update.setInt(8, report.underReplicated());
|
||||
update.setInt(9, report.unrecoverable());
|
||||
update.executeUpdate();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import static cloud.lunarsky.store.ClusterStore.RepairReport;
|
||||
|
||||
final class ClusterRepairPass {
|
||||
private record Target(UUID owner, int part, int ordinal, long version,
|
||||
UUID segment, int length, byte[] hash, List<UUID> replicas) {}
|
||||
private final ClusterMonitor.Connections connections;
|
||||
private final NodeClient nodes;
|
||||
private final boolean testNodeDomains;
|
||||
private final ClusterMonitor monitor;
|
||||
private final Map<UUID, Long> verifiedCounts = new HashMap<>();
|
||||
private int scanned;
|
||||
private int restored;
|
||||
private int rebalanced;
|
||||
private int underReplicated;
|
||||
private int unrecoverable;
|
||||
|
||||
ClusterRepairPass(ClusterMonitor.Connections connections, NodeClient nodes,
|
||||
boolean testNodeDomains, ClusterMonitor monitor) {
|
||||
this.connections = connections;
|
||||
this.nodes = nodes;
|
||||
this.testNodeDomains = testNodeDomains;
|
||||
this.monitor = monitor;
|
||||
}
|
||||
|
||||
RepairReport run() throws IOException {
|
||||
try (Connection reader = connections.open()) {
|
||||
reader.setAutoCommit(false);
|
||||
try (var lock = reader.createStatement()) {
|
||||
lock.execute("SELECT pg_advisory_xact_lock(6834071092782)");
|
||||
}
|
||||
long startedAt = System.currentTimeMillis();
|
||||
monitor.recordRepairStatus("running", startedAt, report());
|
||||
try {
|
||||
scan(reader, startedAt);
|
||||
monitor.completeRepair(startedAt, report(), verifiedCounts);
|
||||
reader.commit();
|
||||
return report();
|
||||
} catch (SQLException | IOException | RuntimeException error) {
|
||||
monitor.recordRepairStatus("failed", startedAt, report());
|
||||
throw error;
|
||||
}
|
||||
} catch (SQLException error) {
|
||||
throw new IOException("Metadata database operation failed", error);
|
||||
}
|
||||
}
|
||||
|
||||
private RepairReport report() {
|
||||
return new RepairReport(scanned, restored, rebalanced, underReplicated, unrecoverable);
|
||||
}
|
||||
|
||||
private void scan(Connection reader, long startedAt) throws SQLException, IOException {
|
||||
long lastProgressAt = startedAt;
|
||||
try (PreparedStatement query = reader.prepareStatement(
|
||||
"SELECT s.generation, 0, s.ordinal, s.segment_id, s.length, s.sha256, s.replica_ids, s.placement_version " +
|
||||
"FROM cluster_segments s JOIN cluster_object_versions o ON o.generation=s.generation " +
|
||||
"UNION ALL SELECT s.upload_id, s.part_number, s.ordinal, s.segment_id, s.length, s.sha256, " +
|
||||
"s.replica_ids, s.placement_version FROM cluster_upload_segments s ORDER BY 1, 2, 3")) {
|
||||
query.setFetchSize(128);
|
||||
try (ResultSet rows = query.executeQuery()) {
|
||||
while (rows.next()) {
|
||||
scanned++;
|
||||
repair(target(rows));
|
||||
long now = System.currentTimeMillis();
|
||||
if (scanned % 256 == 0 || now - lastProgressAt >= 5000) {
|
||||
monitor.recordRepairStatus("running", startedAt, report());
|
||||
lastProgressAt = now;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static Target target(ResultSet rows) throws SQLException, IOException {
|
||||
java.sql.Array value = rows.getArray(7);
|
||||
if (value == null) throw new IOException("Segment has no migrated replica identities");
|
||||
try {
|
||||
List<UUID> replicas = new ArrayList<>();
|
||||
for (Object id : (Object[]) value.getArray()) replicas.add((UUID) id);
|
||||
return new Target((UUID) rows.getObject(1), rows.getInt(2), rows.getInt(3),
|
||||
rows.getLong(8), (UUID) rows.getObject(4), rows.getInt(5), rows.getBytes(6),
|
||||
List.copyOf(replicas));
|
||||
} finally {
|
||||
value.free();
|
||||
}
|
||||
}
|
||||
|
||||
private void repair(Target target) throws SQLException {
|
||||
Set<UUID> healthy = new LinkedHashSet<>();
|
||||
Set<UUID> healthyHosts = new HashSet<>();
|
||||
byte[] copy = readReplicas(target, healthy, healthyHosts);
|
||||
if (copy == null) {
|
||||
unrecoverable++;
|
||||
return;
|
||||
}
|
||||
List<UUID> preferred = preferred(target.segment());
|
||||
for (UUID id : preferred) {
|
||||
int node = nodes.index(id);
|
||||
if (healthy.contains(id)) continue;
|
||||
if (repairReplica(node, target, copy)) {
|
||||
healthy.add(id);
|
||||
healthyHosts.add(nodes.faultDomain(node, testNodeDomains));
|
||||
restored++;
|
||||
}
|
||||
}
|
||||
if (healthyHosts.size() < 3) underReplicated++;
|
||||
List<UUID> listed = placement(target, preferred, healthy);
|
||||
boolean published = listed.equals(target.replicas()) || updatePlacement(target, listed);
|
||||
if (published && preferred.stream().anyMatch(id ->
|
||||
!target.replicas().contains(id) && listed.contains(id))) rebalanced++;
|
||||
for (UUID id : published ? listed : target.replicas()) {
|
||||
if (healthy.contains(id)) verifiedCounts.merge(id, 1L, Long::sum);
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] readReplicas(Target target, Set<UUID> healthy, Set<UUID> hosts) {
|
||||
byte[] copy = null;
|
||||
for (UUID id : target.replicas()) {
|
||||
int node = nodes.index(id);
|
||||
if (node < 0) continue;
|
||||
byte[] candidate = readableReplica(node, target);
|
||||
if (candidate == null) continue;
|
||||
if (copy == null) copy = candidate;
|
||||
healthy.add(id);
|
||||
hosts.add(nodes.faultDomain(node, testNodeDomains));
|
||||
}
|
||||
return copy;
|
||||
}
|
||||
|
||||
private byte[] readableReplica(int node, Target target) {
|
||||
try { return nodes.get(node, target.segment(), target.length(), target.hash()); }
|
||||
catch (IOException unavailable) { return null; }
|
||||
}
|
||||
|
||||
private boolean repairReplica(int node, Target target, byte[] copy) {
|
||||
try {
|
||||
nodes.repair(node, target.segment(), copy, target.hash());
|
||||
return true;
|
||||
} catch (IOException unavailable) { return false; }
|
||||
}
|
||||
|
||||
private List<UUID> preferred(UUID segment) {
|
||||
List<UUID> preferred = new ArrayList<>();
|
||||
Set<UUID> hosts = new HashSet<>();
|
||||
for (int node : PlacementPolicy.candidates(segment, nodes, testNodeDomains)) {
|
||||
if (!hosts.add(nodes.faultDomain(node, testNodeDomains))) continue;
|
||||
preferred.add(nodes.node(node).id());
|
||||
if (preferred.size() == 3) break;
|
||||
}
|
||||
return preferred;
|
||||
}
|
||||
|
||||
private List<UUID> placement(Target target, List<UUID> preferred, Set<UUID> healthy) {
|
||||
List<UUID> listed = new ArrayList<>();
|
||||
Set<UUID> hosts = new HashSet<>();
|
||||
for (UUID id : preferred) {
|
||||
if (healthy.contains(id)) {
|
||||
listed.add(id);
|
||||
hosts.add(nodes.faultDomain(nodes.index(id), testNodeDomains));
|
||||
}
|
||||
}
|
||||
for (UUID id : target.replicas()) {
|
||||
if (listed.size() == 3) break;
|
||||
int node = nodes.index(id);
|
||||
if (healthy.contains(id) && node >= 0 &&
|
||||
hosts.add(nodes.faultDomain(node, testNodeDomains))) listed.add(id);
|
||||
}
|
||||
if (listed.size() < 3) {
|
||||
for (UUID id : target.replicas()) {
|
||||
if (!listed.contains(id)) listed.add(id);
|
||||
}
|
||||
}
|
||||
return listed;
|
||||
}
|
||||
|
||||
private boolean updatePlacement(Target target, List<UUID> listed) throws SQLException {
|
||||
String table = target.part() == 0 ? "cluster_segments" : "cluster_upload_segments";
|
||||
String identity = target.part() == 0 ? "generation=? AND ordinal=?" :
|
||||
"upload_id=? AND part_number=? AND ordinal=?";
|
||||
try (Connection writer = connections.open(); PreparedStatement update = writer.prepareStatement(
|
||||
"UPDATE " + table + " SET replica_ids=?, placement_version=placement_version+1 WHERE " +
|
||||
identity + " AND placement_version=?")) {
|
||||
java.sql.Array ids = writer.createArrayOf("uuid", listed.toArray());
|
||||
try {
|
||||
update.setArray(1, ids);
|
||||
update.setObject(2, target.owner());
|
||||
int next = 3;
|
||||
if (target.part() != 0) update.setInt(next++, target.part());
|
||||
update.setInt(next++, target.ordinal());
|
||||
update.setLong(next, target.version());
|
||||
return update.executeUpdate() == 1;
|
||||
} finally {
|
||||
ids.free();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -21,7 +21,6 @@ import java.util.Base64;
|
||||
import java.util.Comparator;
|
||||
import java.util.HexFormat;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
@@ -29,16 +28,22 @@ import java.util.UUID;
|
||||
|
||||
final class ClusterStore implements ObjectStorage, MultipartStorage {
|
||||
private record Segment(UUID id, int length, byte[] hash, List<UUID> replicas) {}
|
||||
private record RepairTarget(UUID id, int part, int ordinal, long version, Segment segment) {}
|
||||
private record Upload(String contentType, Map<String, String> userMetadata,
|
||||
Map<String, String> tags, Map<String, String> acl) {}
|
||||
private record StoredPart(long length, String etag, List<Segment> segments) {}
|
||||
record RepairReport(int scanned, int restored, int rebalanced, int underReplicated, int unrecoverable) {}
|
||||
record RepairStatus(long startedAt, long updatedAt, long finishedAt, String state,
|
||||
RepairReport report) {}
|
||||
record NodeStatus(NodeClient.Node node, boolean reachable) {}
|
||||
record ClusterStatus(boolean metadataWritable, List<NodeStatus> nodes,
|
||||
int omittedNodes, RepairStatus repair,
|
||||
Map<UUID, Long> verifiedReplicas, long checkedAt) {}
|
||||
record GcReport(int scanned, int eligible, int deleted, int unavailableNodes) {}
|
||||
private final String jdbcUrl, user, password, configuredBucket;
|
||||
private final String jdbcUrl, user, password;
|
||||
private final NodeClient nodes;
|
||||
private final long maxObject, maxTotal;
|
||||
private final boolean testNodeDomains;
|
||||
private final ClusterMonitor monitor;
|
||||
|
||||
ClusterStore(String jdbcUrl, String user, String password, String bucket,
|
||||
List<URI> nodeUrls, String token, String repairToken, long maxObject, long maxTotal,
|
||||
@@ -50,7 +55,6 @@ final class ClusterStore implements ObjectStorage, MultipartStorage {
|
||||
this.jdbcUrl = jdbcUrl;
|
||||
this.user = user;
|
||||
this.password = password;
|
||||
this.configuredBucket = bucket;
|
||||
this.maxObject = maxObject;
|
||||
this.maxTotal = maxTotal;
|
||||
this.testNodeDomains = testNodeDomains;
|
||||
@@ -58,11 +62,14 @@ final class ClusterStore implements ObjectStorage, MultipartStorage {
|
||||
int format = SchemaMigrator.prepare(connection, bucket);
|
||||
if (format != 2) throw new IOException("Legacy replica positions require objectstore cluster-migrate before this gateway can start");
|
||||
nodes = NodeRegistry.load(connection, nodeUrls, token, repairToken);
|
||||
monitor = new ClusterMonitor(this::connect, nodes);
|
||||
} catch (SQLException error) { throw databaseError(error); }
|
||||
}
|
||||
|
||||
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 {
|
||||
@@ -78,12 +85,16 @@ final class ClusterStore implements ObjectStorage, MultipartStorage {
|
||||
|
||||
@Override public Bucket bucket(String name) throws IOException {
|
||||
try (Connection connection = connect(); PreparedStatement query = connection.prepareStatement(
|
||||
"SELECT created_at, versioning_state, acl FROM cluster_buckets WHERE name=?")) {
|
||||
"SELECT created_at, versioning_state, acl, object_ownership, block_public_acls, " +
|
||||
"ignore_public_acls, block_public_policy, restrict_public_buckets, bucket_policy " +
|
||||
"FROM cluster_buckets WHERE name=?")) {
|
||||
query.setString(1, name);
|
||||
try (ResultSet result = query.executeQuery()) {
|
||||
if (!result.next()) throw new StoreException(404, "NoSuchBucket", "Bucket not found");
|
||||
return new Bucket(name, result.getLong(1), VersioningState.valueOf(result.getString(2)),
|
||||
ObjectAttributes.decode(result.getBytes(3)));
|
||||
ObjectAttributes.decode(result.getBytes(3)), ObjectOwnership.valueOf(result.getString(4)),
|
||||
new PublicAccessBlock(result.getBoolean(5), result.getBoolean(6),
|
||||
result.getBoolean(7), result.getBoolean(8)), result.getString(9));
|
||||
}
|
||||
} catch (SQLException error) { throw databaseError(error); }
|
||||
}
|
||||
@@ -91,9 +102,14 @@ final class ClusterStore implements ObjectStorage, MultipartStorage {
|
||||
@Override public List<Bucket> buckets() throws IOException {
|
||||
List<Bucket> result = new ArrayList<>();
|
||||
try (Connection connection = connect(); var query = connection.createStatement();
|
||||
ResultSet rows = query.executeQuery("SELECT name, created_at, versioning_state, acl FROM cluster_buckets ORDER BY name")) {
|
||||
ResultSet rows = query.executeQuery("SELECT name, created_at, versioning_state, acl, " +
|
||||
"object_ownership, block_public_acls, ignore_public_acls, block_public_policy, " +
|
||||
"restrict_public_buckets, bucket_policy FROM cluster_buckets ORDER BY name")) {
|
||||
while (rows.next()) result.add(new Bucket(rows.getString(1), rows.getLong(2),
|
||||
VersioningState.valueOf(rows.getString(3)), ObjectAttributes.decode(rows.getBytes(4))));
|
||||
VersioningState.valueOf(rows.getString(3)), ObjectAttributes.decode(rows.getBytes(4)),
|
||||
ObjectOwnership.valueOf(rows.getString(5)),
|
||||
new PublicAccessBlock(rows.getBoolean(6), rows.getBoolean(7),
|
||||
rows.getBoolean(8), rows.getBoolean(9)), rows.getString(10)));
|
||||
return result;
|
||||
} catch (SQLException error) { throw databaseError(error); }
|
||||
}
|
||||
@@ -133,6 +149,38 @@ final class ClusterStore implements ObjectStorage, MultipartStorage {
|
||||
} catch (SQLException error) { throw databaseError(error); }
|
||||
}
|
||||
|
||||
@Override public void setBucketOwnership(String bucket, ObjectOwnership ownership) throws IOException {
|
||||
updateBucketAccess(bucket, "object_ownership", ownership.name());
|
||||
}
|
||||
|
||||
@Override public void setPublicAccessBlock(String bucket, PublicAccessBlock block) throws IOException {
|
||||
try (Connection connection = connect(); PreparedStatement update = connection.prepareStatement(
|
||||
"UPDATE cluster_buckets SET block_public_acls=?, ignore_public_acls=?, " +
|
||||
"block_public_policy=?, restrict_public_buckets=? WHERE name=?")) {
|
||||
update.setBoolean(1, block.blockPublicAcls());
|
||||
update.setBoolean(2, block.ignorePublicAcls());
|
||||
update.setBoolean(3, block.blockPublicPolicy());
|
||||
update.setBoolean(4, block.restrictPublicBuckets());
|
||||
update.setString(5, bucket);
|
||||
if (update.executeUpdate() == 0)
|
||||
throw new StoreException(404, "NoSuchBucket", "Bucket not found");
|
||||
} catch (SQLException error) { throw databaseError(error); }
|
||||
}
|
||||
|
||||
@Override public void setBucketPolicy(String bucket, String policy) throws IOException {
|
||||
updateBucketAccess(bucket, "bucket_policy", policy);
|
||||
}
|
||||
|
||||
private void updateBucketAccess(String bucket, String column, String value) throws IOException {
|
||||
try (Connection connection = connect(); PreparedStatement update = connection.prepareStatement(
|
||||
"UPDATE cluster_buckets SET " + column + "=? WHERE name=?")) {
|
||||
update.setString(1, value);
|
||||
update.setString(2, bucket);
|
||||
if (update.executeUpdate() == 0)
|
||||
throw new StoreException(404, "NoSuchBucket", "Bucket not found");
|
||||
} catch (SQLException error) { throw databaseError(error); }
|
||||
}
|
||||
|
||||
private static VersioningState versioningState(Connection connection, String bucket) throws SQLException {
|
||||
try (PreparedStatement query = connection.prepareStatement(
|
||||
"SELECT versioning_state FROM cluster_buckets WHERE name=? FOR UPDATE")) {
|
||||
@@ -171,7 +219,9 @@ final class ClusterStore implements ObjectStorage, MultipartStorage {
|
||||
throw new StoreException(400, "TooManyBuckets", "Bucket limit reached");
|
||||
}
|
||||
try (PreparedStatement insert = connection.prepareStatement(
|
||||
"INSERT INTO cluster_buckets (name, created_at) VALUES (?, ?) ON CONFLICT DO NOTHING")) {
|
||||
"INSERT INTO cluster_buckets (name, created_at, object_ownership, block_public_acls, " +
|
||||
"ignore_public_acls, block_public_policy, restrict_public_buckets) " +
|
||||
"VALUES (?, ?, 'BUCKET_OWNER_ENFORCED', true, true, true, true) ON CONFLICT DO NOTHING")) {
|
||||
insert.setString(1, name);
|
||||
insert.setLong(2, Instant.now().toEpochMilli());
|
||||
if (insert.executeUpdate() == 0)
|
||||
@@ -196,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=?)")) {
|
||||
@@ -225,6 +276,61 @@ final class ClusterStore implements ObjectStorage, MultipartStorage {
|
||||
} catch (SQLException error) { throw databaseError(error); }
|
||||
}
|
||||
|
||||
@Override public void renameBucket(String oldName, String newName) throws IOException {
|
||||
if (newName == null || !newName.matches("[a-z0-9][a-z0-9-]{1,61}[a-z0-9]"))
|
||||
throw new StoreException(400, "InvalidBucketName", "Invalid bucket name");
|
||||
if (oldName.equals(newName))
|
||||
throw new StoreException(400, "InvalidArgument", "Choose a different name");
|
||||
try (Connection connection = connect()) {
|
||||
connection.setAutoCommit(false);
|
||||
try {
|
||||
try (var lock = connection.createStatement()) {
|
||||
lock.execute("SELECT pg_advisory_xact_lock(6834071092784)");
|
||||
lock.execute("LOCK TABLE cluster_usage, cluster_buckets, cluster_objects, " +
|
||||
"cluster_tombstones, cluster_object_versions, cluster_object_heads, " +
|
||||
"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);
|
||||
try (ResultSet result = check.executeQuery()) {
|
||||
result.next();
|
||||
if (result.getBoolean(1))
|
||||
throw new StoreException(409, "BucketAlreadyExists", "Bucket name is already in use");
|
||||
}
|
||||
}
|
||||
try (PreparedStatement update = connection.prepareStatement(
|
||||
"UPDATE cluster_buckets SET name=?, bucket_policy=" +
|
||||
"replace(replace(bucket_policy, ?, ?), ?, ?) WHERE name=?")) {
|
||||
update.setString(1, newName);
|
||||
update.setString(2, "arn:aws:s3:::" + oldName + "/");
|
||||
update.setString(3, "arn:aws:s3:::" + newName + "/");
|
||||
update.setString(4, "arn:aws:s3:::" + oldName + "\"");
|
||||
update.setString(5, "arn:aws:s3:::" + newName + "\"");
|
||||
update.setString(6, oldName);
|
||||
if (update.executeUpdate() != 1)
|
||||
throw new StoreException(404, "NoSuchBucket", "Bucket not found");
|
||||
}
|
||||
for (String table : List.of("cluster_usage", "cluster_objects", "cluster_tombstones",
|
||||
"cluster_object_versions", "cluster_object_heads", "cluster_uploads")) {
|
||||
try (PreparedStatement update = connection.prepareStatement(
|
||||
"UPDATE " + table + " SET bucket=? WHERE bucket=?")) {
|
||||
update.setString(1, newName);
|
||||
update.setString(2, oldName);
|
||||
update.executeUpdate();
|
||||
}
|
||||
}
|
||||
connection.commit();
|
||||
} catch (SQLException | RuntimeException error) {
|
||||
connection.rollback();
|
||||
if (error instanceof SQLException sql) throw databaseError(sql);
|
||||
throw error;
|
||||
}
|
||||
} catch (SQLException error) { throw databaseError(error); }
|
||||
}
|
||||
|
||||
private static void lockGc(Connection connection, boolean shared) throws SQLException {
|
||||
try (var statement = connection.createStatement()) {
|
||||
statement.execute("SELECT pg_advisory_lock" + (shared ? "_shared" : "") + "(6834071092783)");
|
||||
@@ -236,6 +342,24 @@ final class ClusterStore implements ObjectStorage, MultipartStorage {
|
||||
Map<String, String> userMetadata, Map<String, String> tags,
|
||||
java.util.function.Supplier<Map<String, String>> checksums,
|
||||
Map<String, String> acl) throws IOException {
|
||||
return put(bucket, key, input, length, expectedHash, checksum, createOnly, contentType,
|
||||
userMetadata, tags, checksums, acl, null);
|
||||
}
|
||||
|
||||
@Override public Metadata replaceVersion(String bucket, String key, byte[] content, Metadata expected)
|
||||
throws IOException {
|
||||
if (expected == null || expected.versionId() == null)
|
||||
throw new StoreException(412, "PreconditionFailed", "Object has no stable version to replace");
|
||||
return put(bucket, key, new ByteArrayInputStream(content), content.length, null, null, false,
|
||||
expected.contentType(), expected.userMetadata(), expected.tags(), Map::of, expected.acl(),
|
||||
expected);
|
||||
}
|
||||
|
||||
private Metadata put(String bucket, String key, InputStream input, long length, String expectedHash,
|
||||
String checksum, boolean createOnly, String contentType,
|
||||
Map<String, String> userMetadata, Map<String, String> tags,
|
||||
java.util.function.Supplier<Map<String, String>> checksums,
|
||||
Map<String, String> acl, Metadata expected) throws IOException {
|
||||
validatePut(bucket, length, contentType);
|
||||
MessageDigest md5 = digest("MD5");
|
||||
Crc64Nvme crc64 = new Crc64Nvme();
|
||||
@@ -252,7 +376,7 @@ final class ClusterStore implements ObjectStorage, MultipartStorage {
|
||||
Metadata metadata = new Metadata(length, Instant.now().toEpochMilli(),
|
||||
HexFormat.of().formatHex(md5.digest()), fullHash, bucket, key, contentType,
|
||||
Map.copyOf(userMetadata), Map.copyOf(tags), null, storedChecksums, Map.copyOf(acl));
|
||||
return persistObject(connection, metadata, segments, createOnly);
|
||||
return persistObject(connection, metadata, segments, createOnly, expected);
|
||||
} catch (SQLException error) { throw databaseError(error); }
|
||||
} finally { Files.deleteIfExists(staged); }
|
||||
}
|
||||
@@ -341,7 +465,7 @@ final class ClusterStore implements ObjectStorage, MultipartStorage {
|
||||
}
|
||||
|
||||
private Metadata persistObject(Connection connection, Metadata metadata, List<Segment> segments,
|
||||
boolean createOnly) throws IOException {
|
||||
boolean createOnly, Metadata expected) throws IOException {
|
||||
String bucket = metadata.bucket(), key = metadata.key();
|
||||
long length = metadata.length();
|
||||
UUID generation = UUID.randomUUID();
|
||||
@@ -350,6 +474,7 @@ final class ClusterStore implements ObjectStorage, MultipartStorage {
|
||||
try {
|
||||
long used = lockUsage(connection, bucket);
|
||||
VersioningState state = versioningState(connection, bucket);
|
||||
if (expected != null) requireCurrentVersion(connection, bucket, key, state, expected);
|
||||
long previous = currentLength(connection, bucket, key);
|
||||
if (createOnly && previous >= 0)
|
||||
throw new StoreException(412, "PreconditionFailed", "Object already exists");
|
||||
@@ -373,7 +498,7 @@ final class ClusterStore implements ObjectStorage, MultipartStorage {
|
||||
Metadata stored = publishObject(connection, metadata, generation, used, replaced, state);
|
||||
connection.commit();
|
||||
return stored;
|
||||
} catch (SQLException | RuntimeException error) {
|
||||
} catch (SQLException | IOException | RuntimeException error) {
|
||||
connection.rollback();
|
||||
if (error instanceof SQLException sql) throw databaseError(sql);
|
||||
throw error;
|
||||
@@ -381,6 +506,24 @@ final class ClusterStore implements ObjectStorage, MultipartStorage {
|
||||
} catch (SQLException error) { throw databaseError(error); }
|
||||
}
|
||||
|
||||
private static void requireCurrentVersion(Connection connection, String bucket, String key,
|
||||
VersioningState state, Metadata expected) throws SQLException, IOException {
|
||||
try (PreparedStatement query = connection.prepareStatement(
|
||||
"SELECT h.version_id, v.sha256, v.tags, v.acl FROM cluster_object_heads h JOIN cluster_object_versions v " +
|
||||
"USING (bucket, object_key, version_id) WHERE h.bucket=? AND h.object_key=? AND NOT v.delete_marker")) {
|
||||
query.setString(1, bucket);
|
||||
query.setString(2, key);
|
||||
try (ResultSet row = query.executeQuery()) {
|
||||
if (state != VersioningState.ENABLED || !row.next() ||
|
||||
!expected.versionId().equals(row.getString(1)) ||
|
||||
!MessageDigest.isEqual(expected.sha256(), row.getBytes(2)) ||
|
||||
!expected.tags().equals(ObjectAttributes.decode(row.getBytes(3))) ||
|
||||
!expected.acl().equals(ObjectAttributes.decode(row.getBytes(4))))
|
||||
throw new StoreException(412, "PreconditionFailed", "Object changed since it was opened");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static long nullVersionLength(Connection connection, String bucket, String key) throws SQLException {
|
||||
try (PreparedStatement query = connection.prepareStatement(
|
||||
"SELECT length FROM cluster_object_versions WHERE bucket=? AND object_key=? AND version_id='null'")) {
|
||||
@@ -599,17 +742,20 @@ final class ClusterStore implements ObjectStorage, MultipartStorage {
|
||||
throw new StoreException(413, "EntityTooLarge", "Object exceeds the configured size limit");
|
||||
total += part.length();
|
||||
MessageDigest partHash = digest("MD5");
|
||||
java.util.zip.CRC32 partCrc32 = new java.util.zip.CRC32();
|
||||
for (Segment segment : part.segments()) {
|
||||
byte[] bytes = readableSegment(segment);
|
||||
if (bytes == null) throw new StoreException(503, "SlowDown", "A part has no verified replica");
|
||||
fullHash.update(bytes);
|
||||
crc64.update(bytes, 0, bytes.length);
|
||||
partHash.update(bytes);
|
||||
partCrc32.update(bytes, 0, bytes.length);
|
||||
selected.add(segment);
|
||||
}
|
||||
byte[] md5 = partHash.digest();
|
||||
if (!part.etag().equals(HexFormat.of().formatHex(md5)))
|
||||
throw new StoreException(503, "SlowDown", "A part failed integrity verification");
|
||||
requested.verifyCrc32(partCrc32.getValue());
|
||||
etagHash.update(md5);
|
||||
}
|
||||
long replaced = state == VersioningState.ENABLED ? 0 : nullVersionLength(connection, bucket, key);
|
||||
@@ -717,8 +863,7 @@ final class ClusterStore implements ObjectStorage, MultipartStorage {
|
||||
|
||||
@Override public int activeUploads() {
|
||||
try (Connection connection = connect(); PreparedStatement query = connection.prepareStatement(
|
||||
"SELECT count(*) FROM cluster_uploads WHERE bucket=?")) {
|
||||
query.setString(1, configuredBucket);
|
||||
"SELECT count(*) FROM cluster_uploads")) {
|
||||
try (ResultSet result = query.executeQuery()) {
|
||||
result.next();
|
||||
return result.getInt(1);
|
||||
@@ -727,8 +872,11 @@ final class ClusterStore implements ObjectStorage, MultipartStorage {
|
||||
}
|
||||
|
||||
@Override public long stagedBytes() {
|
||||
try (Connection connection = connect()) { return stagedBytes(connection, configuredBucket); }
|
||||
catch (SQLException error) { throw new IllegalStateException("Could not count staged bytes", error); }
|
||||
try (Connection connection = connect(); var query = connection.createStatement();
|
||||
ResultSet result = query.executeQuery("SELECT COALESCE(sum(length), 0) FROM cluster_upload_parts")) {
|
||||
result.next();
|
||||
return result.getLong(1);
|
||||
} catch (SQLException error) { throw new IllegalStateException("Could not count staged bytes", error); }
|
||||
}
|
||||
|
||||
@Override public OpenObject open(String bucket, String key) throws IOException {
|
||||
@@ -1354,104 +1502,9 @@ final class ClusterStore implements ObjectStorage, MultipartStorage {
|
||||
return result.next() && result.getBoolean(1);
|
||||
} catch (SQLException error) { return false; }
|
||||
}
|
||||
ClusterStatus status() { return monitor.status(); }
|
||||
RepairReport repairOnce() throws IOException {
|
||||
int scanned = 0, restored = 0, rebalanced = 0, underReplicated = 0, unrecoverable = 0;
|
||||
try (Connection reader = connect()) {
|
||||
reader.setAutoCommit(false);
|
||||
try (var lock = reader.createStatement()) {
|
||||
lock.execute("SELECT pg_advisory_xact_lock(6834071092782)");
|
||||
}
|
||||
try (PreparedStatement query = reader.prepareStatement(
|
||||
"SELECT s.generation, 0, s.ordinal, s.segment_id, s.length, s.sha256, s.replica_ids, s.placement_version " +
|
||||
"FROM cluster_segments s JOIN cluster_object_versions o ON o.generation=s.generation " +
|
||||
"UNION ALL SELECT s.upload_id, s.part_number, s.ordinal, s.segment_id, s.length, s.sha256, " +
|
||||
"s.replica_ids, s.placement_version FROM cluster_upload_segments s " +
|
||||
"ORDER BY 1, 2, 3")) {
|
||||
query.setFetchSize(128);
|
||||
try (ResultSet result = query.executeQuery()) {
|
||||
while (result.next()) {
|
||||
scanned++;
|
||||
RepairTarget target = new RepairTarget((UUID) result.getObject(1), result.getInt(2),
|
||||
result.getInt(3), result.getLong(8), new Segment((UUID) result.getObject(4),
|
||||
result.getInt(5), result.getBytes(6), replicaIds(result, 7)));
|
||||
Segment segment = target.segment();
|
||||
byte[] copy = null;
|
||||
Set<UUID> healthy = new LinkedHashSet<>();
|
||||
Set<UUID> healthyHosts = new HashSet<>();
|
||||
for (UUID id : segment.replicas()) {
|
||||
int node = nodes.index(id);
|
||||
if (node < 0) continue;
|
||||
byte[] candidate = readableReplica(node, segment);
|
||||
if (candidate == null) continue;
|
||||
if (copy == null) copy = candidate;
|
||||
healthy.add(id);
|
||||
healthyHosts.add(nodes.faultDomain(node, testNodeDomains));
|
||||
}
|
||||
if (copy == null) {
|
||||
unrecoverable++;
|
||||
continue;
|
||||
}
|
||||
List<UUID> preferred = new ArrayList<>();
|
||||
Set<UUID> preferredHosts = new HashSet<>();
|
||||
for (int node : PlacementPolicy.candidates(segment.id(), nodes, testNodeDomains)) {
|
||||
UUID host = nodes.faultDomain(node, testNodeDomains);
|
||||
if (!preferredHosts.add(host)) continue;
|
||||
preferred.add(nodes.node(node).id());
|
||||
if (preferred.size() == 3) break;
|
||||
}
|
||||
for (UUID id : preferred) {
|
||||
int node = nodes.index(id);
|
||||
UUID host = nodes.faultDomain(node, testNodeDomains);
|
||||
if (healthy.contains(id)) continue;
|
||||
if (repairReplica(node, segment, copy)) {
|
||||
healthy.add(id);
|
||||
healthyHosts.add(host);
|
||||
restored++;
|
||||
}
|
||||
}
|
||||
if (healthyHosts.size() < 3) underReplicated++;
|
||||
List<UUID> listed = new ArrayList<>();
|
||||
Set<UUID> listedHosts = new HashSet<>();
|
||||
for (UUID id : preferred) {
|
||||
if (healthy.contains(id)) {
|
||||
listed.add(id);
|
||||
listedHosts.add(nodes.faultDomain(nodes.index(id), testNodeDomains));
|
||||
}
|
||||
}
|
||||
for (UUID id : segment.replicas()) {
|
||||
if (listed.size() == 3) break;
|
||||
int node = nodes.index(id);
|
||||
if (healthy.contains(id) && node >= 0 &&
|
||||
listedHosts.add(nodes.faultDomain(node, testNodeDomains))) listed.add(id);
|
||||
}
|
||||
if (listed.size() < 3) {
|
||||
for (UUID id : segment.replicas()) {
|
||||
if (!listed.contains(id)) listed.add(id);
|
||||
}
|
||||
}
|
||||
if (!listed.equals(segment.replicas())) {
|
||||
String table = target.part() == 0 ? "cluster_segments" : "cluster_upload_segments";
|
||||
String identity = target.part() == 0 ? "generation=? AND ordinal=?" :
|
||||
"upload_id=? AND part_number=? AND ordinal=?";
|
||||
try (Connection writer = connect(); PreparedStatement update = writer.prepareStatement(
|
||||
"UPDATE " + table + " SET replica_ids=?, placement_version=placement_version+1 WHERE " +
|
||||
identity + " AND placement_version=?")) {
|
||||
update.setArray(1, writer.createArrayOf("uuid", listed.toArray()));
|
||||
update.setObject(2, target.id());
|
||||
int next = 3;
|
||||
if (target.part() != 0) update.setInt(next++, target.part());
|
||||
update.setInt(next++, target.ordinal());
|
||||
update.setLong(next, target.version());
|
||||
if (update.executeUpdate() == 1 && preferred.stream().anyMatch(id ->
|
||||
!segment.replicas().contains(id) && listed.contains(id))) rebalanced++;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
reader.commit();
|
||||
} catch (SQLException error) { throw databaseError(error); }
|
||||
return new RepairReport(scanned, restored, rebalanced, underReplicated, unrecoverable);
|
||||
return new ClusterRepairPass(this::connect, nodes, testNodeDomains, monitor).run();
|
||||
}
|
||||
|
||||
private byte[] readableReplica(int node, Segment segment) {
|
||||
@@ -1459,13 +1512,6 @@ final class ClusterStore implements ObjectStorage, MultipartStorage {
|
||||
catch (IOException unavailable) { return null; }
|
||||
}
|
||||
|
||||
private boolean repairReplica(int node, Segment segment, byte[] copy) {
|
||||
try {
|
||||
nodes.repair(node, segment.id(), copy, segment.hash());
|
||||
return true;
|
||||
} catch (IOException unavailable) { return false; }
|
||||
}
|
||||
|
||||
GcReport collectGarbage(long minimumAgeMillis, boolean apply) throws IOException {
|
||||
if (minimumAgeMillis < 0 || (minimumAgeMillis == 0 && !testNodeDomains))
|
||||
throw new IllegalArgumentException("Invalid garbage collection age");
|
||||
|
||||
@@ -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,253 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
final class DiskBucketNames implements ObjectStorage, MultipartStorage {
|
||||
private final DiskStore store;
|
||||
private final MultipartStore uploads;
|
||||
private final BucketNameCatalog catalog;
|
||||
private volatile Map<String, String> aliases;
|
||||
|
||||
DiskBucketNames(DiskStore store, MultipartStore uploads) throws IOException {
|
||||
this.store = store;
|
||||
this.uploads = uploads;
|
||||
catalog = new BucketNameCatalog(store);
|
||||
aliases = catalog.load();
|
||||
}
|
||||
|
||||
private static boolean valid(String name) {
|
||||
return name != null && name.matches("[a-z0-9][a-z0-9-]{1,61}[a-z0-9]");
|
||||
}
|
||||
|
||||
private String physical(String name) {
|
||||
Map<String, String> current = aliases;
|
||||
String found = current.get(name);
|
||||
if (found != null) return found;
|
||||
if (current.containsValue(name))
|
||||
throw new StoreException(404, "NoSuchBucket", "Bucket not found");
|
||||
return name;
|
||||
}
|
||||
|
||||
private String visible(String physical) {
|
||||
for (var entry : aliases.entrySet())
|
||||
if (entry.getValue().equals(physical)) return entry.getKey();
|
||||
return physical;
|
||||
}
|
||||
|
||||
private static String policyName(String policy, String from, String to) {
|
||||
if (policy == null) return null;
|
||||
String arn = "arn:aws:s3:::";
|
||||
return policy.replace(arn + from + "/", arn + to + "/")
|
||||
.replace(arn + from + "\"", arn + to + "\"");
|
||||
}
|
||||
|
||||
private Bucket visible(Bucket bucket) {
|
||||
String name = visible(bucket.name());
|
||||
return new Bucket(name, bucket.created(), bucket.versioning(), bucket.acl(),
|
||||
bucket.ownership(), bucket.publicAccessBlock(),
|
||||
policyName(bucket.policy(), bucket.name(), name));
|
||||
}
|
||||
|
||||
private Metadata visible(Metadata metadata) {
|
||||
if (metadata == null) return null;
|
||||
return new Metadata(metadata.length(), metadata.modified(), metadata.etag(), metadata.sha256(),
|
||||
visible(metadata.bucket()), metadata.key(), metadata.contentType(), metadata.userMetadata(),
|
||||
metadata.tags(), metadata.versionId(), metadata.checksums(), metadata.acl());
|
||||
}
|
||||
|
||||
private void save(Map<String, String> next) throws IOException {
|
||||
catalog.save(next);
|
||||
aliases = Map.copyOf(next);
|
||||
}
|
||||
|
||||
@Override public synchronized void renameBucket(String oldName, String newName) throws IOException {
|
||||
if (!valid(newName)) throw new StoreException(400, "InvalidBucketName", "Invalid bucket name");
|
||||
String underlying = physical(oldName);
|
||||
store.bucket(underlying);
|
||||
if (oldName.equals(newName)) throw new StoreException(400, "InvalidArgument", "Choose a different name");
|
||||
if (aliases.containsKey(newName) || store.buckets().stream().anyMatch(b -> b.name().equals(newName)))
|
||||
throw new StoreException(409, "BucketAlreadyExists", "Bucket name is already in use");
|
||||
Map<String, String> next = new HashMap<>(aliases);
|
||||
next.remove(oldName);
|
||||
next.put(newName, underlying);
|
||||
save(next);
|
||||
}
|
||||
|
||||
@Override public Metadata put(String bucket, String key, InputStream input, long length,
|
||||
String expectedHash, String checksum, boolean createOnly,
|
||||
String contentType, Map<String, String> userMetadata,
|
||||
Map<String, String> tags, Supplier<Map<String, String>> checksums,
|
||||
Map<String, String> acl) throws IOException {
|
||||
return visible(store.put(physical(bucket), key, input, length, expectedHash, checksum,
|
||||
createOnly, contentType, userMetadata, tags, checksums, acl));
|
||||
}
|
||||
|
||||
@Override public Metadata replaceVersion(String bucket, String key, byte[] content, Metadata expected)
|
||||
throws IOException {
|
||||
return visible(store.replaceVersion(physical(bucket), key, content, expected));
|
||||
}
|
||||
|
||||
@Override public OpenObject open(String bucket, String key) throws IOException {
|
||||
return open(bucket, key, null);
|
||||
}
|
||||
|
||||
@Override public OpenObject open(String bucket, String key, String versionId) throws IOException {
|
||||
OpenObject opened = store.open(physical(bucket), key, versionId);
|
||||
return new OpenObject(visible(opened.metadata()), opened.stream());
|
||||
}
|
||||
|
||||
@Override public Map<String, String> tags(String bucket, String key) throws IOException {
|
||||
return store.tags(physical(bucket), key);
|
||||
}
|
||||
|
||||
@Override public Map<String, String> tags(String bucket, String key, String versionId) throws IOException {
|
||||
return store.tags(physical(bucket), key, versionId);
|
||||
}
|
||||
|
||||
@Override public void setTags(String bucket, String key, Map<String, String> tags) throws IOException {
|
||||
store.setTags(physical(bucket), key, tags);
|
||||
}
|
||||
|
||||
@Override public void setTags(String bucket, String key, String versionId,
|
||||
Map<String, String> tags) throws IOException {
|
||||
store.setTags(physical(bucket), key, versionId, tags);
|
||||
}
|
||||
|
||||
@Override public void delete(String bucket, String key) throws IOException {
|
||||
store.delete(physical(bucket), key);
|
||||
}
|
||||
|
||||
@Override public DeleteResult delete(String bucket, String key, String versionId) throws IOException {
|
||||
return store.delete(physical(bucket), key, versionId);
|
||||
}
|
||||
|
||||
@Override public void setVersioning(String bucket, VersioningState state) throws IOException {
|
||||
store.setVersioning(physical(bucket), state);
|
||||
}
|
||||
|
||||
@Override public VersionPage listVersions(String bucket, String prefix, String keyMarker,
|
||||
String versionMarker, int maxKeys) throws IOException {
|
||||
VersionPage page = store.listVersions(physical(bucket), prefix, keyMarker, versionMarker, maxKeys);
|
||||
return new VersionPage(page.entries().stream().map(entry -> new VersionEntry(entry.key(),
|
||||
entry.versionId(), entry.modified(), entry.deleteMarker(), entry.latest(),
|
||||
visible(entry.metadata()))).toList(), page.nextKey(), page.nextVersionId(), page.truncated());
|
||||
}
|
||||
|
||||
@Override public ListPage list(String bucket, String prefix, String delimiter,
|
||||
int maxKeys, String after) throws IOException {
|
||||
ListPage page = store.list(physical(bucket), prefix, delimiter, maxKeys, after);
|
||||
return new ListPage(page.objects().stream().map(entry ->
|
||||
new ListedObject(entry.key(), visible(entry.metadata()))).toList(),
|
||||
page.prefixes(), page.nextKey(), page.truncated());
|
||||
}
|
||||
|
||||
@Override public synchronized void ensureBucket(String bucket) throws IOException {
|
||||
if (aliases.containsValue(bucket)) return;
|
||||
store.ensureBucket(physical(bucket));
|
||||
}
|
||||
|
||||
@Override public Bucket bucket(String bucket) throws IOException {
|
||||
return visible(store.bucket(physical(bucket)));
|
||||
}
|
||||
|
||||
@Override public List<Bucket> buckets() throws IOException {
|
||||
return store.buckets().stream().map(this::visible).toList();
|
||||
}
|
||||
|
||||
@Override public synchronized void createBucket(String bucket) throws IOException {
|
||||
if (aliases.containsKey(bucket) || aliases.containsValue(bucket))
|
||||
throw new StoreException(409, "BucketAlreadyExists", "Bucket name is already in use");
|
||||
store.createBucket(bucket);
|
||||
}
|
||||
|
||||
@Override public synchronized void deleteBucket(String bucket) throws IOException {
|
||||
String name = physical(bucket);
|
||||
synchronized (uploads) {
|
||||
if (!uploads.listUploads(name, "").isEmpty())
|
||||
throw new StoreException(409, "BucketNotEmpty", "Bucket contains multipart uploads");
|
||||
if (!aliases.containsKey(bucket)) {
|
||||
store.deleteBucket(name);
|
||||
return;
|
||||
}
|
||||
catalog.beginDelete(bucket, name);
|
||||
boolean deleted = false;
|
||||
try {
|
||||
store.deleteBucket(name);
|
||||
deleted = true;
|
||||
Map<String, String> next = new HashMap<>(aliases);
|
||||
next.remove(bucket);
|
||||
save(next);
|
||||
catalog.finishDelete();
|
||||
} catch (IOException | RuntimeException error) {
|
||||
try {
|
||||
if (deleted) aliases = catalog.load();
|
||||
else if (error instanceof StoreException) catalog.finishDelete();
|
||||
} catch (IOException recovery) { error.addSuppressed(recovery); }
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override public void setBucketAcl(String bucket, Map<String, String> acl) throws IOException {
|
||||
store.setBucketAcl(physical(bucket), acl);
|
||||
}
|
||||
|
||||
@Override public void setBucketOwnership(String bucket, ObjectOwnership ownership) throws IOException {
|
||||
store.setBucketOwnership(physical(bucket), ownership);
|
||||
}
|
||||
|
||||
@Override public void setPublicAccessBlock(String bucket, PublicAccessBlock block) throws IOException {
|
||||
store.setPublicAccessBlock(physical(bucket), block);
|
||||
}
|
||||
|
||||
@Override public void setBucketPolicy(String bucket, String policy) throws IOException {
|
||||
String name = physical(bucket);
|
||||
store.setBucketPolicy(name, policyName(policy, bucket, name));
|
||||
}
|
||||
|
||||
@Override public void setObjectAcl(String bucket, String key, String versionId,
|
||||
Map<String, String> acl) throws IOException {
|
||||
store.setObjectAcl(physical(bucket), key, versionId, acl);
|
||||
}
|
||||
|
||||
@Override public Limits limits() { return store.limits(); }
|
||||
@Override public boolean ready() { return store.ready(); }
|
||||
@Override public void close() throws IOException { store.close(); }
|
||||
|
||||
@Override public String create(String bucket, String key, String contentType,
|
||||
Map<String, String> userMetadata, Map<String, String> tags,
|
||||
Map<String, String> acl) throws IOException {
|
||||
return uploads.create(physical(bucket), key, contentType, userMetadata, tags, acl);
|
||||
}
|
||||
|
||||
@Override public String putPart(String id, String bucket, String key, int number, InputStream input,
|
||||
long length, String expectedHash, String checksum) throws IOException {
|
||||
return uploads.putPart(id, physical(bucket), key, number, input, length, expectedHash, checksum);
|
||||
}
|
||||
|
||||
@Override public Metadata complete(String id, String bucket, String key, List<Part> parts)
|
||||
throws IOException {
|
||||
return visible(uploads.complete(id, physical(bucket), key, parts));
|
||||
}
|
||||
|
||||
@Override public void abort(String id, String bucket, String key) throws IOException {
|
||||
uploads.abort(id, physical(bucket), key);
|
||||
}
|
||||
|
||||
@Override public PartPage listParts(String id, String bucket, String key, int marker, int maxParts)
|
||||
throws IOException {
|
||||
return uploads.listParts(id, physical(bucket), key, marker, maxParts);
|
||||
}
|
||||
|
||||
@Override public List<UploadInfo> listUploads(String bucket, String prefix) throws IOException {
|
||||
return uploads.listUploads(physical(bucket), prefix);
|
||||
}
|
||||
|
||||
@Override public int activeUploads() { return uploads.activeUploads(); }
|
||||
@Override public long stagedBytes() { return uploads.stagedBytes(); }
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -32,6 +32,7 @@ final class DiskStore implements ObjectStorage {
|
||||
private static final int BUCKET_MAGIC = 0x4c534243;
|
||||
private static final int BUCKET_MAGIC_V2 = 0x4c534244;
|
||||
private static final int BUCKET_MAGIC_V3 = 0x4c534245;
|
||||
private static final int BUCKET_MAGIC_V4 = 0x4c534246;
|
||||
private static final int VERSION_MAGIC = 0x4c53564d;
|
||||
private final Path root, objects, temporary, catalog, versions;
|
||||
private final FileChannel lockChannel;
|
||||
@@ -94,7 +95,8 @@ final class DiskStore implements ObjectStorage {
|
||||
if (Files.exists(catalog)) {
|
||||
try (DataInputStream input = new DataInputStream(Files.newInputStream(catalog))) {
|
||||
int magic = input.readInt();
|
||||
if (magic != BUCKET_MAGIC && magic != BUCKET_MAGIC_V2 && magic != BUCKET_MAGIC_V3)
|
||||
if (magic != BUCKET_MAGIC && magic != BUCKET_MAGIC_V2 &&
|
||||
magic != BUCKET_MAGIC_V3 && magic != BUCKET_MAGIC_V4)
|
||||
throw new IOException("Invalid bucket catalog");
|
||||
int count = input.readInt();
|
||||
if (count < 0 || count > 1000) throw new IOException("Invalid bucket catalog");
|
||||
@@ -102,20 +104,35 @@ final class DiskStore implements ObjectStorage {
|
||||
String name = input.readUTF();
|
||||
long created = input.readLong();
|
||||
VersioningState state = VersioningState.NEVER;
|
||||
if (magic == BUCKET_MAGIC_V2 || magic == BUCKET_MAGIC_V3) {
|
||||
if (magic != BUCKET_MAGIC) {
|
||||
int ordinal = input.readUnsignedByte();
|
||||
if (ordinal >= VersioningState.values().length)
|
||||
throw new IOException("Invalid bucket versioning state");
|
||||
state = VersioningState.values()[ordinal];
|
||||
}
|
||||
Map<String, String> acl = Map.of();
|
||||
if (magic == BUCKET_MAGIC_V3) {
|
||||
if (magic == BUCKET_MAGIC_V3 || magic == BUCKET_MAGIC_V4) {
|
||||
int size = input.readUnsignedShort();
|
||||
if (size > ACL_AREA) throw new IOException("Invalid bucket ACL");
|
||||
acl = ObjectAttributes.decode(input.readNBytes(size));
|
||||
}
|
||||
ObjectOwnership ownership = ObjectOwnership.OBJECT_WRITER;
|
||||
PublicAccessBlock block = PublicAccessBlock.open();
|
||||
String policy = null;
|
||||
if (magic == BUCKET_MAGIC_V4) {
|
||||
int ordinal = input.readUnsignedByte();
|
||||
int flags = input.readUnsignedByte();
|
||||
if (ordinal >= ObjectOwnership.values().length || (flags & ~15) != 0)
|
||||
throw new IOException("Invalid bucket access settings");
|
||||
ownership = ObjectOwnership.values()[ordinal];
|
||||
block = new PublicAccessBlock((flags & 1) != 0, (flags & 2) != 0,
|
||||
(flags & 4) != 0, (flags & 8) != 0);
|
||||
policy = input.readUTF();
|
||||
if (policy.isEmpty()) policy = null;
|
||||
}
|
||||
if (!validBucket(name) || created < 0 ||
|
||||
buckets.put(name, new Bucket(name, created, state, acl)) != null)
|
||||
buckets.put(name, new Bucket(name, created, state, acl,
|
||||
ownership, block, policy)) != null)
|
||||
throw new IOException("Invalid bucket catalog");
|
||||
}
|
||||
if (input.read() != -1) throw new IOException("Invalid bucket catalog");
|
||||
@@ -212,7 +229,7 @@ final class DiskStore implements ObjectStorage {
|
||||
Path pending = Files.createTempFile(temporary, "buckets-", ".part");
|
||||
try {
|
||||
try (DataOutputStream output = new DataOutputStream(Files.newOutputStream(pending))) {
|
||||
output.writeInt(BUCKET_MAGIC_V3);
|
||||
output.writeInt(BUCKET_MAGIC_V4);
|
||||
output.writeInt(next.size());
|
||||
for (Bucket entry : next.values()) {
|
||||
output.writeUTF(entry.name());
|
||||
@@ -221,6 +238,13 @@ final class DiskStore implements ObjectStorage {
|
||||
byte[] acl = ObjectAttributes.encode(entry.acl(), ACL_AREA);
|
||||
output.writeShort(acl.length);
|
||||
output.write(acl);
|
||||
output.writeByte(entry.ownership().ordinal());
|
||||
PublicAccessBlock block = entry.publicAccessBlock();
|
||||
output.writeByte((block.blockPublicAcls() ? 1 : 0) |
|
||||
(block.ignorePublicAcls() ? 2 : 0) |
|
||||
(block.blockPublicPolicy() ? 4 : 0) |
|
||||
(block.restrictPublicBuckets() ? 8 : 0));
|
||||
output.writeUTF(entry.policy() == null ? "" : entry.policy());
|
||||
}
|
||||
}
|
||||
try (FileChannel channel = FileChannel.open(pending, StandardOpenOption.WRITE)) { channel.force(true); }
|
||||
@@ -237,7 +261,8 @@ final class DiskStore implements ObjectStorage {
|
||||
if (old.versioning() == VersioningState.NEVER && state == VersioningState.SUSPENDED)
|
||||
throw new StoreException(400, "InvalidArgument", "Enable versioning before suspending it");
|
||||
NavigableMap<String, Bucket> next = new TreeMap<>(buckets);
|
||||
next.put(name, new Bucket(name, old.created(), state, old.acl()));
|
||||
next.put(name, new Bucket(name, old.created(), state, old.acl(),
|
||||
old.ownership(), old.publicAccessBlock(), old.policy()));
|
||||
saveBuckets(next);
|
||||
buckets.clear();
|
||||
buckets.putAll(next);
|
||||
@@ -246,7 +271,37 @@ final class DiskStore implements ObjectStorage {
|
||||
@Override public synchronized void setBucketAcl(String name, Map<String, String> acl) throws IOException {
|
||||
Bucket old = bucket(name);
|
||||
NavigableMap<String, Bucket> next = new TreeMap<>(buckets);
|
||||
next.put(name, new Bucket(name, old.created(), old.versioning(), Map.copyOf(acl)));
|
||||
next.put(name, new Bucket(name, old.created(), old.versioning(), Map.copyOf(acl),
|
||||
old.ownership(), old.publicAccessBlock(), old.policy()));
|
||||
saveBuckets(next);
|
||||
buckets.clear();
|
||||
buckets.putAll(next);
|
||||
}
|
||||
|
||||
@Override public synchronized void setBucketOwnership(String name, ObjectOwnership ownership)
|
||||
throws IOException {
|
||||
Bucket old = bucket(name);
|
||||
updateBucket(new Bucket(name, old.created(), old.versioning(), old.acl(),
|
||||
ownership, old.publicAccessBlock(), old.policy()));
|
||||
}
|
||||
|
||||
@Override public synchronized void setPublicAccessBlock(String name, PublicAccessBlock block)
|
||||
throws IOException {
|
||||
Bucket old = bucket(name);
|
||||
updateBucket(new Bucket(name, old.created(), old.versioning(), old.acl(),
|
||||
old.ownership(), block, old.policy()));
|
||||
}
|
||||
|
||||
@Override public synchronized void setBucketPolicy(String name, String policy)
|
||||
throws IOException {
|
||||
Bucket old = bucket(name);
|
||||
updateBucket(new Bucket(name, old.created(), old.versioning(), old.acl(),
|
||||
old.ownership(), old.publicAccessBlock(), policy));
|
||||
}
|
||||
|
||||
private void updateBucket(Bucket bucket) throws IOException {
|
||||
NavigableMap<String, Bucket> next = new TreeMap<>(buckets);
|
||||
next.put(bucket.name(), bucket);
|
||||
saveBuckets(next);
|
||||
buckets.clear();
|
||||
buckets.putAll(next);
|
||||
@@ -420,6 +475,24 @@ final class DiskStore implements ObjectStorage {
|
||||
Map<String, String> userMetadata, Map<String, String> tags,
|
||||
java.util.function.Supplier<Map<String, String>> checksums,
|
||||
Map<String, String> acl) throws IOException {
|
||||
return put(bucket, key, input, length, expectedHash, checksum, createOnly, contentType,
|
||||
userMetadata, tags, checksums, acl, null);
|
||||
}
|
||||
|
||||
@Override public Metadata replaceVersion(String bucket, String key, byte[] content, Metadata expected)
|
||||
throws IOException {
|
||||
if (expected == null || expected.versionId() == null)
|
||||
throw new StoreException(412, "PreconditionFailed", "Object has no stable version to replace");
|
||||
return put(bucket, key, new ByteArrayInputStream(content), content.length, null, null, false,
|
||||
expected.contentType(), expected.userMetadata(), expected.tags(), Map::of, expected.acl(),
|
||||
expected);
|
||||
}
|
||||
|
||||
private Metadata put(String bucket, String key, InputStream input, long length, String expectedHash,
|
||||
String checksum, boolean createOnly, String contentType,
|
||||
Map<String, String> userMetadata, Map<String, String> tags,
|
||||
java.util.function.Supplier<Map<String, String>> checksums,
|
||||
Map<String, String> acl, Metadata expected) throws IOException {
|
||||
if (length < 0) throw new StoreException(411, "MissingContentLength", "Content-Length is required");
|
||||
if (length > maxObject) throw new StoreException(413, "EntityTooLarge", "Object exceeds the configured size limit");
|
||||
byte[] bucketBytes = bucket.getBytes(StandardCharsets.UTF_8);
|
||||
@@ -433,7 +506,7 @@ final class DiskStore implements ObjectStorage {
|
||||
Metadata metadata = stagePut(pending, input, length, expectedHash, checksum,
|
||||
bucket, key, contentType, bucketBytes, keyBytes, typeBytes,
|
||||
metadataBytes, tagBytes, userMetadata, tags, checksums, acl);
|
||||
return installPending(destination, pending, metadata, createOnly);
|
||||
return installPending(destination, pending, metadata, createOnly, expected);
|
||||
} finally { Files.deleteIfExists(pending); }
|
||||
}
|
||||
|
||||
@@ -499,60 +572,87 @@ final class DiskStore implements ObjectStorage {
|
||||
}
|
||||
|
||||
private Metadata installPending(Path destination, Path pending, Metadata metadata,
|
||||
boolean createOnly) throws IOException {
|
||||
boolean createOnly, Metadata expected) throws IOException {
|
||||
synchronized (lock(destination)) {
|
||||
synchronized (this) {
|
||||
Bucket configured = buckets.get(metadata.bucket());
|
||||
if (configured != null && configured.versioning() != VersioningState.NEVER)
|
||||
checkExpectedVersion(configured, metadata, expected);
|
||||
if (isVersioned(configured))
|
||||
return installVersionedPending(destination, pending, metadata, createOnly,
|
||||
configured.versioning());
|
||||
}
|
||||
long previous = 0;
|
||||
boolean existed = Files.exists(destination);
|
||||
boolean legacy = false;
|
||||
if (existed) {
|
||||
if (createOnly) throw new StoreException(412, "PreconditionFailed", "Object already exists");
|
||||
try (var in = new DataInputStream(Files.newInputStream(destination))) {
|
||||
Metadata old = readRecord(in).metadata();
|
||||
previous = old.length();
|
||||
legacy = old.key() == null;
|
||||
}
|
||||
}
|
||||
long additional = Math.max(0, metadata.length() - previous);
|
||||
Metadata previous = previousMetadata(destination, createOnly);
|
||||
long previousLength = previous == null ? 0 : previous.length();
|
||||
long additional = Math.max(0, metadata.length() - previousLength);
|
||||
synchronized (this) {
|
||||
Bucket configured = buckets.get(metadata.bucket());
|
||||
if (configured != null && configured.versioning() != VersioningState.NEVER)
|
||||
if (isVersioned(configured))
|
||||
return installVersionedPending(destination, pending, metadata, createOnly,
|
||||
configured.versioning());
|
||||
if (Files.exists(catalog) && configured == null)
|
||||
throw new StoreException(404, "NoSuchBucket", "Bucket not found");
|
||||
if (maxTotal - used - reservedBytes < additional)
|
||||
throw new StoreException(507, "InsufficientStorage", "Store capacity limit reached");
|
||||
reservedBytes += additional;
|
||||
publishingByBucket.merge(metadata.bucket(), 1, Integer::sum);
|
||||
}
|
||||
boolean moved = false;
|
||||
try {
|
||||
Files.move(pending, destination, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
|
||||
moved = true;
|
||||
syncDirectory(destination.getParent());
|
||||
} finally {
|
||||
synchronized (this) {
|
||||
if (moved) {
|
||||
used = used - previous + metadata.length();
|
||||
if (!existed) objectCount++;
|
||||
if (legacy) legacyCount--;
|
||||
index.put(indexKey(metadata.bucket(), metadata.key()), metadata);
|
||||
}
|
||||
reservedBytes -= additional;
|
||||
publishingByBucket.compute(metadata.bucket(), (bucket, count) -> count == 1 ? null : count - 1);
|
||||
notifyAll();
|
||||
}
|
||||
reservePublication(metadata.bucket(), configured, additional);
|
||||
}
|
||||
publishUnversioned(destination, pending, metadata, previous, additional);
|
||||
return metadata;
|
||||
}
|
||||
}
|
||||
|
||||
private void checkExpectedVersion(Bucket configured, Metadata metadata, Metadata expected) {
|
||||
if (expected == null) return;
|
||||
Metadata current = index.get(indexKey(metadata.bucket(), metadata.key()));
|
||||
if (configured == null || configured.versioning() != VersioningState.ENABLED ||
|
||||
current == null || !expected.versionId().equals(
|
||||
current.versionId() == null ? "null" : current.versionId()) ||
|
||||
!MessageDigest.isEqual(expected.sha256(), current.sha256()) ||
|
||||
!expected.tags().equals(current.tags()) || !expected.acl().equals(current.acl()))
|
||||
throw new StoreException(412, "PreconditionFailed", "Object changed since it was opened");
|
||||
}
|
||||
|
||||
private static boolean isVersioned(Bucket configured) {
|
||||
return configured != null && configured.versioning() != VersioningState.NEVER;
|
||||
}
|
||||
|
||||
private Metadata previousMetadata(Path destination, boolean createOnly) throws IOException {
|
||||
if (!Files.exists(destination)) return null;
|
||||
if (createOnly) throw new StoreException(412, "PreconditionFailed", "Object already exists");
|
||||
try (var in = new DataInputStream(Files.newInputStream(destination))) {
|
||||
return readRecord(in).metadata();
|
||||
}
|
||||
}
|
||||
|
||||
private void reservePublication(String bucket, Bucket configured, long additional) {
|
||||
if (Files.exists(catalog) && configured == null)
|
||||
throw new StoreException(404, "NoSuchBucket", "Bucket not found");
|
||||
if (maxTotal - used - reservedBytes < additional)
|
||||
throw new StoreException(507, "InsufficientStorage", "Store capacity limit reached");
|
||||
reservedBytes += additional;
|
||||
publishingByBucket.merge(bucket, 1, Integer::sum);
|
||||
}
|
||||
|
||||
private void publishUnversioned(Path destination, Path pending, Metadata metadata,
|
||||
Metadata previous, long additional) throws IOException {
|
||||
boolean moved = false;
|
||||
try {
|
||||
Files.move(pending, destination, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
|
||||
moved = true;
|
||||
syncDirectory(destination.getParent());
|
||||
} finally {
|
||||
finishPublication(metadata, previous, additional, moved);
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized void finishPublication(Metadata metadata, Metadata previous,
|
||||
long additional, boolean moved) {
|
||||
if (moved) {
|
||||
used = used - (previous == null ? 0 : previous.length()) + metadata.length();
|
||||
if (previous == null) objectCount++;
|
||||
else if (previous.key() == null) legacyCount--;
|
||||
index.put(indexKey(metadata.bucket(), metadata.key()), metadata);
|
||||
}
|
||||
reservedBytes -= additional;
|
||||
publishingByBucket.compute(metadata.bucket(), (bucket, count) -> count == 1 ? null : count - 1);
|
||||
notifyAll();
|
||||
}
|
||||
|
||||
private Metadata installVersionedPending(Path destination, Path pending, Metadata metadata,
|
||||
boolean createOnly, VersioningState state) throws IOException {
|
||||
String bucket = metadata.bucket();
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
final class IdentityPolicies {
|
||||
private IdentityPolicies() { }
|
||||
|
||||
static Map<String, BucketPolicy> fromEnvironment(Map<String, String> env, String owner,
|
||||
Set<String> identities)
|
||||
throws IOException {
|
||||
String configured = env.get("S3_IDENTITY_POLICIES_DIR");
|
||||
if (configured == null || configured.isBlank()) return Map.of();
|
||||
Map<String, BucketPolicy> policies = new HashMap<>();
|
||||
try (var files = Files.newDirectoryStream(Path.of(configured), "*.json")) {
|
||||
for (Path path : files) {
|
||||
String name = path.getFileName().toString();
|
||||
String key = name.substring(0, name.length() - 5);
|
||||
if (!identities.contains(key) || key.equals(owner) || Files.isSymbolicLink(path) ||
|
||||
Files.size(path) > 20480 || policies.size() >= 256)
|
||||
throw new IllegalArgumentException("Invalid identity policy file");
|
||||
String json = Files.readString(path, StandardCharsets.UTF_8);
|
||||
policies.put(key, BucketPolicy.parseIdentity(json));
|
||||
}
|
||||
}
|
||||
return Map.copyOf(policies);
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package cloud.lunarsky.store;
|
||||
|
||||
import com.sun.net.httpserver.HttpExchange;
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
@@ -20,11 +21,24 @@ public final class Main {
|
||||
private final ObjectHandler objectHandler;
|
||||
private final ClientLimits clientLimits;
|
||||
private final Semaphore slots;
|
||||
private final Semaphore adminSlots = new Semaphore(8);
|
||||
private final Semaphore adminStreams = new Semaphore(4);
|
||||
private final String virtualHostSuffix;
|
||||
private final BrowserCors cors;
|
||||
private final KeyScopes keyScopes;
|
||||
private final RequestMetrics metrics;
|
||||
private final StoreOperations operations = new StoreOperations();
|
||||
private final RequestDiagnostics diagnostics = new RequestDiagnostics();
|
||||
private volatile BucketActivity bucketActivity;
|
||||
private final int maxInFlight;
|
||||
private volatile AdminConsole adminConsole;
|
||||
private volatile ManagedCredentials managedCredentials;
|
||||
|
||||
private static final class RequestContext {
|
||||
String principal;
|
||||
String bucket;
|
||||
String operation;
|
||||
}
|
||||
|
||||
Main(DiskStore store, SigV4 authentication, String bucket) throws IOException {
|
||||
this(store, new MultipartStore(store), authentication, bucket);
|
||||
@@ -62,12 +76,29 @@ public final class Main {
|
||||
Main(ObjectStorage store, MultipartStorage multipart, SigV4 authentication, String bucket,
|
||||
ClientLimits clientLimits, int maxInFlight, String virtualHostSuffix,
|
||||
BrowserCors cors, KeyScopes keyScopes, RequestMetrics metrics) throws IOException {
|
||||
this(store, multipart, authentication, bucket, clientLimits, maxInFlight, virtualHostSuffix,
|
||||
cors, keyScopes, metrics, Map.of());
|
||||
}
|
||||
|
||||
Main(ObjectStorage store, MultipartStorage multipart, SigV4 authentication, String bucket,
|
||||
ClientLimits clientLimits, int maxInFlight, String virtualHostSuffix,
|
||||
BrowserCors cors, KeyScopes keyScopes, RequestMetrics metrics,
|
||||
Map<String, BucketPolicy> identityPolicies) throws IOException {
|
||||
this(store, multipart, authentication, bucket, clientLimits, maxInFlight, virtualHostSuffix,
|
||||
cors, keyScopes, metrics, identityPolicies, null);
|
||||
}
|
||||
|
||||
Main(ObjectStorage store, MultipartStorage multipart, SigV4 authentication, String bucket,
|
||||
ClientLimits clientLimits, int maxInFlight, String virtualHostSuffix,
|
||||
BrowserCors cors, KeyScopes keyScopes, RequestMetrics metrics,
|
||||
Map<String, BucketPolicy> identityPolicies, URI publicEndpoint) throws IOException {
|
||||
if (maxInFlight < 1 || maxInFlight > 1024)
|
||||
throw new IllegalArgumentException("MAX_IN_FLIGHT_REQUESTS must be between 1 and 1024");
|
||||
this.store = store;
|
||||
this.authentication = authentication;
|
||||
this.access = new S3Access(store, authentication.root());
|
||||
MultipartHandler multipartHandler = new MultipartHandler(store, multipart, authentication);
|
||||
this.access = new S3Access(store, authentication.root(), identityPolicies);
|
||||
MultipartHandler multipartHandler = new MultipartHandler(store, multipart, authentication, access,
|
||||
publicEndpoint);
|
||||
this.bucketHandler = new BucketHandler(store, multipart, multipartHandler,
|
||||
authentication, access, bucket);
|
||||
this.objectHandler = new ObjectHandler(store, multipartHandler, authentication, access);
|
||||
@@ -81,21 +112,71 @@ public final class Main {
|
||||
store.ensureBucket(bucket);
|
||||
}
|
||||
|
||||
void setAdminConsole(AdminConsole adminConsole) {
|
||||
this.adminConsole = adminConsole;
|
||||
if (adminConsole != null) {
|
||||
adminConsole.setOperations(operations);
|
||||
adminConsole.setMetrics(metrics);
|
||||
adminConsole.setDiagnostics(diagnostics);
|
||||
adminConsole.setBucketActivity(bucketActivity);
|
||||
adminConsole.setIdentities(authentication.identities());
|
||||
adminConsole.setManagedCredentials(managedCredentials, this::refreshManagedCredentials);
|
||||
adminConsole.setAccessCheck((principal, operation, bucket, key) ->
|
||||
new AdminAccessCheck(store, access, keyScopes, authentication.identities(),
|
||||
managedCredentials).check(principal, operation, bucket, key));
|
||||
}
|
||||
}
|
||||
|
||||
void setBucketActivity(BucketActivity bucketActivity) {
|
||||
this.bucketActivity = bucketActivity;
|
||||
if (adminConsole != null) adminConsole.setBucketActivity(bucketActivity);
|
||||
}
|
||||
|
||||
void setManagedCredentials(ManagedCredentials managedCredentials) {
|
||||
this.managedCredentials = managedCredentials;
|
||||
access.setManagedCredentials(managedCredentials);
|
||||
authentication.setManagedCredentials(managedCredentials);
|
||||
refreshManagedCredentials();
|
||||
if (adminConsole != null)
|
||||
adminConsole.setManagedCredentials(managedCredentials, this::refreshManagedCredentials);
|
||||
}
|
||||
|
||||
private synchronized void refreshManagedCredentials() {
|
||||
ManagedCredentials managed = managedCredentials;
|
||||
if (managed == null) return;
|
||||
if (adminConsole != null) adminConsole.setIdentities(authentication.identities());
|
||||
}
|
||||
|
||||
void handle(HttpExchange exchange) throws IOException {
|
||||
long started = System.nanoTime();
|
||||
boolean admitted = false;
|
||||
boolean dataStarted = false;
|
||||
TrafficMeter traffic = null;
|
||||
ClientLimits.Client client = null;
|
||||
String requestId = UUID.randomUUID().toString();
|
||||
RequestContext context = new RequestContext();
|
||||
exchange.getResponseHeaders().set("x-amz-request-id", requestId);
|
||||
exchange.getResponseHeaders().set("X-Content-Type-Options", "nosniff");
|
||||
cors.decorate(exchange);
|
||||
try {
|
||||
String path = exchange.getRequestURI().getRawPath();
|
||||
if (!(path.equals(AdminConsole.PATH) || path.startsWith(AdminConsole.PATH + "/") ||
|
||||
path.equals("/health") || path.equals("/ready") || path.equals("/metrics"))) {
|
||||
traffic = TrafficMeter.attach(exchange);
|
||||
metrics.dataStarted();
|
||||
dataStarted = true;
|
||||
}
|
||||
if (path.equals(AdminConsole.PATH) || path.startsWith(AdminConsole.PATH + "/")) {
|
||||
exchange.sendResponseHeaders(404, -1);
|
||||
return;
|
||||
}
|
||||
cors.decorate(exchange);
|
||||
client = clientLimits.enter(exchange);
|
||||
admitted = slots.tryAcquire();
|
||||
if (!admitted) throw new StoreException(503, "SlowDown", "Too many concurrent requests");
|
||||
if (cors.preflight(exchange)) return;
|
||||
if (handleStatus(exchange)) return;
|
||||
dispatch(exchange);
|
||||
operations.read(() -> {
|
||||
if (!handleStatus(exchange)) dispatch(exchange, context);
|
||||
});
|
||||
} catch (StoreException error) {
|
||||
sendStoreError(exchange, error, requestId);
|
||||
} catch (Exception error) {
|
||||
@@ -106,53 +187,146 @@ public final class Main {
|
||||
finally {
|
||||
if (admitted) slots.release();
|
||||
clientLimits.leave(client);
|
||||
metrics.record(exchange.getResponseCode(), System.nanoTime() - started);
|
||||
long elapsed = System.nanoTime() - started;
|
||||
metrics.record(exchange.getResponseCode(), elapsed);
|
||||
if (dataStarted) {
|
||||
metrics.dataFinished(exchange.getResponseCode(), elapsed,
|
||||
traffic.inbound(), traffic.outbound());
|
||||
if (adminConsole != null) diagnostics.record(requestId,
|
||||
context.operation, context.bucket, exchange.getResponseCode(), elapsed,
|
||||
context.principal);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void dispatch(HttpExchange exchange) throws IOException {
|
||||
SigV4.Verified verified = anonymousRead(exchange)
|
||||
? new SigV4.Verified("UNSIGNED-PAYLOAD", exchange.getRequestURI().getRawQuery(),
|
||||
null, null, null, null, null)
|
||||
: authentication.verifyRequest(exchange.getRequestMethod(),
|
||||
exchange.getRequestURI(), exchange.getRequestHeaders());
|
||||
void handleAdmin(HttpExchange exchange) throws IOException {
|
||||
boolean admitted = false;
|
||||
boolean streaming = false;
|
||||
try {
|
||||
String path = exchange.getRequestURI().getRawPath();
|
||||
if (adminConsole == null ||
|
||||
!(path.equals(AdminConsole.PATH) || path.startsWith(AdminConsole.PATH + "/"))) {
|
||||
exchange.sendResponseHeaders(404, -1);
|
||||
return;
|
||||
}
|
||||
streaming = path.equals(AdminConsole.PATH + "/performance.events");
|
||||
admitted = (streaming ? adminStreams : adminSlots).tryAcquire();
|
||||
if (!admitted) {
|
||||
exchange.sendResponseHeaders(503, -1);
|
||||
return;
|
||||
}
|
||||
adminConsole.handle(exchange);
|
||||
} catch (StoreException error) {
|
||||
if (exchange.getResponseCode() <= 0) exchange.sendResponseHeaders(error.status, -1);
|
||||
} catch (Exception error) {
|
||||
System.err.println("ObjectStore admin request failed: " + error.getClass().getSimpleName());
|
||||
if (exchange.getResponseCode() <= 0) exchange.sendResponseHeaders(500, -1);
|
||||
} finally {
|
||||
exchange.close();
|
||||
if (admitted) (streaming ? adminStreams : adminSlots).release();
|
||||
}
|
||||
}
|
||||
|
||||
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());
|
||||
Map<String, String> query = S3Request.query(verified.applicationQuery());
|
||||
if (path.equals(CAPABILITIES_PATH)) {
|
||||
access.requireOwner(verified.principal());
|
||||
if (!exchange.getRequestMethod().equals("GET")) S3Request.unsupported("Capability operation");
|
||||
if (!query.isEmpty())
|
||||
throw new StoreException(400, "InvalidArgument", "Capability request has unsupported query parameters");
|
||||
S3Request.requireEmptyBody(exchange, verified.payload());
|
||||
capabilities(exchange);
|
||||
handleCapabilities(exchange, query, verified);
|
||||
return;
|
||||
}
|
||||
String hostBucket = virtualHostBucket(exchange);
|
||||
if (path.equals("/") && hostBucket == null) {
|
||||
access.requireOwner(verified.principal());
|
||||
if (!exchange.getRequestMethod().equals("GET") ||
|
||||
!(query.isEmpty() || query.size() == 1 && "ListBuckets".equals(query.get("x-id"))))
|
||||
S3Request.unsupported("Service operation");
|
||||
S3Request.requireEmptyBody(exchange, verified.payload());
|
||||
bucketHandler.listBuckets(exchange);
|
||||
handleService(exchange, query, verified);
|
||||
return;
|
||||
}
|
||||
int slash = path.indexOf('/', 1);
|
||||
String requestedBucket = hostBucket == null ?
|
||||
(slash < 0 ? path.substring(1) : path.substring(1, slash)) : hostBucket;
|
||||
boolean bucketRequest = hostBucket != null ? path.equals("/") : slash < 0 || slash == path.length() - 1;
|
||||
context.bucket = requestedBucket;
|
||||
context.operation = (bucketRequest ? "Bucket " : "Object ") + exchange.getRequestMethod();
|
||||
if (requestedBucket.isEmpty()) throw new StoreException(404, "NoSuchBucket", "Bucket not found");
|
||||
if (hostBucket != null ? path.equals("/") : slash < 0 || slash == path.length() - 1) {
|
||||
keyScopes.checkBucket(verified.principal(), requestedBucket, exchange.getRequestMethod(), query);
|
||||
bucketHandler.handleBucket(exchange, query, verified.payload(), requestedBucket, verified.principal());
|
||||
if (bucketRequest) {
|
||||
dispatchBucket(exchange, query, verified, requestedBucket);
|
||||
} else {
|
||||
store.bucket(requestedBucket);
|
||||
String key = hostBucket == null ? path.substring(slash + 1) : path.substring(1);
|
||||
keyScopes.checkObject(verified.principal(), requestedBucket, key,
|
||||
exchange.getRequestMethod(), query, exchange.getRequestHeaders());
|
||||
objectHandler.handleObject(exchange, key,
|
||||
query, verified, requestedBucket);
|
||||
dispatchObject(exchange, query, verified, requestedBucket, key);
|
||||
}
|
||||
recordBucketActivity(exchange, requestedBucket);
|
||||
}
|
||||
|
||||
private SigV4.Verified verifyRequest(HttpExchange exchange) {
|
||||
if (anonymousRead(exchange))
|
||||
return new SigV4.Verified("UNSIGNED-PAYLOAD", exchange.getRequestURI().getRawQuery(),
|
||||
null, null, null, null, null);
|
||||
return authentication.verifyRequest(exchange.getRequestMethod(),
|
||||
exchange.getRequestURI(), exchange.getRequestHeaders());
|
||||
}
|
||||
|
||||
private void handleCapabilities(HttpExchange exchange, Map<String, String> query,
|
||||
SigV4.Verified verified) throws IOException {
|
||||
access.requireOwner(verified.principal());
|
||||
if (!exchange.getRequestMethod().equals("GET")) S3Request.unsupported("Capability operation");
|
||||
if (!query.isEmpty())
|
||||
throw new StoreException(400, "InvalidArgument", "Capability request has unsupported query parameters");
|
||||
S3Request.requireEmptyBody(exchange, verified.payload());
|
||||
capabilities(exchange);
|
||||
}
|
||||
|
||||
private void handleService(HttpExchange exchange, Map<String, String> query,
|
||||
SigV4.Verified verified) throws IOException {
|
||||
access.requireOwner(verified.principal());
|
||||
if (!exchange.getRequestMethod().equals("GET") ||
|
||||
!(query.isEmpty() || query.size() == 1 && "ListBuckets".equals(query.get("x-id"))))
|
||||
S3Request.unsupported("Service operation");
|
||||
S3Request.requireEmptyBody(exchange, verified.payload());
|
||||
bucketHandler.listBuckets(exchange);
|
||||
}
|
||||
|
||||
private void dispatchBucket(HttpExchange exchange, Map<String, String> query,
|
||||
SigV4.Verified verified, String bucket) throws IOException {
|
||||
ManagedCredentials managed = managedScope(verified.principal());
|
||||
if (managed != null)
|
||||
managed.checkBucket(verified.principal(), bucket, exchange.getRequestMethod(), query);
|
||||
else keyScopes.checkBucket(verified.principal(), bucket, exchange.getRequestMethod(), query);
|
||||
bucketHandler.handleBucket(exchange, query, verified.payload(), bucket, verified.principal());
|
||||
}
|
||||
|
||||
private void dispatchObject(HttpExchange exchange, Map<String, String> query,
|
||||
SigV4.Verified verified, String bucket, String key) throws IOException {
|
||||
ManagedCredentials managed = managedScope(verified.principal());
|
||||
if (managed != null)
|
||||
managed.checkObject(verified.principal(), bucket, key,
|
||||
exchange.getRequestMethod(), query, exchange.getRequestHeaders());
|
||||
else keyScopes.checkObject(verified.principal(), bucket, key,
|
||||
exchange.getRequestMethod(), query, exchange.getRequestHeaders());
|
||||
objectHandler.handleObject(exchange, key, query, verified, bucket);
|
||||
}
|
||||
|
||||
private void recordBucketActivity(HttpExchange exchange, String requestedBucket) {
|
||||
BucketActivity activity = bucketActivity;
|
||||
if (activity != null && exchange.getResponseCode() > 0 && exchange.getResponseCode() < 400)
|
||||
activity.record(requestedBucket, exchange.getRequestMethod());
|
||||
}
|
||||
|
||||
private ManagedCredentials managedScope(String principal) {
|
||||
if (principal == null || authentication.configuredIdentity(principal)) return null;
|
||||
ManagedCredentials managed = managedCredentials;
|
||||
if (managed == null || !managed.contains(principal))
|
||||
throw new StoreException(403, "AccessDenied", "Access denied");
|
||||
return managed;
|
||||
}
|
||||
|
||||
private static String validateVirtualHostSuffix(String value) {
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import com.sun.net.httpserver.Headers;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.HashMap;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
final class ManagedCredentials {
|
||||
record Key(String id, String secret, String bucket, String prefix,
|
||||
Set<String> actions, boolean enabled) { }
|
||||
|
||||
private static final SecureRandom RANDOM = new SecureRandom();
|
||||
private static final Set<String> ACTIONS = Set.of("read", "write", "list");
|
||||
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 final ThreadLocal<Snapshot> request = new ThreadLocal<>();
|
||||
private volatile Snapshot snapshot;
|
||||
|
||||
ManagedCredentials(ManagedCredentialStore storage, byte[] master, Set<String> reserved)
|
||||
throws IOException {
|
||||
this.storage = storage;
|
||||
this.cipher = new CredentialCipher(master);
|
||||
this.reserved = Set.copyOf(reserved);
|
||||
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;
|
||||
byte[] master;
|
||||
try {
|
||||
master = HexFormat.of().parseHex(Files.readString(Path.of(configured)).trim());
|
||||
} catch (IllegalArgumentException error) {
|
||||
throw new IllegalArgumentException("Invalid managed credentials master key", error);
|
||||
}
|
||||
if (master.length != 32)
|
||||
throw new IllegalArgumentException("Managed credentials master key must contain 32 bytes");
|
||||
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 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(); }
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
List<String> objectActions = new ArrayList<>();
|
||||
if (key.actions().contains("read")) {
|
||||
objectActions.add("s3:GetObject");
|
||||
objectActions.add("s3:GetObjectVersion");
|
||||
}
|
||||
if (key.actions().contains("write")) {
|
||||
objectActions.add("s3:PutObject");
|
||||
objectActions.add("s3:DeleteObject");
|
||||
objectActions.add("s3:DeleteObjectVersion");
|
||||
objectActions.add("s3:AbortMultipartUpload");
|
||||
}
|
||||
String bucketArn = "arn:aws:s3:::" + key.bucket();
|
||||
StringBuilder statements = new StringBuilder();
|
||||
if (key.actions().contains("list"))
|
||||
statements.append("{\"Effect\":\"Allow\",\"Action\":\"s3:ListBucket\",\"Resource\":\"")
|
||||
.append(bucketArn).append("\"}");
|
||||
if (!objectActions.isEmpty()) {
|
||||
if (!statements.isEmpty()) statements.append(',');
|
||||
statements.append("{\"Effect\":\"Allow\",\"Action\":[");
|
||||
for (int i = 0; i < objectActions.size(); i++) {
|
||||
if (i > 0) statements.append(',');
|
||||
statements.append('"').append(objectActions.get(i)).append('"');
|
||||
}
|
||||
statements.append("],\"Resource\":\"").append(bucketArn).append('/')
|
||||
.append(key.prefix()).append("*\"}");
|
||||
}
|
||||
active.put(key.id(), BucketPolicy.parseIdentity(
|
||||
"{\"Version\":\"2012-10-17\",\"Statement\":[" + statements + "]}"));
|
||||
}
|
||||
return Map.copyOf(active);
|
||||
}
|
||||
|
||||
synchronized Key create(String bucket, String prefix, Set<String> actions) throws IOException {
|
||||
validateScope(bucket, prefix, actions);
|
||||
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);
|
||||
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 {
|
||||
validateScope(bucket, prefix, actions);
|
||||
mutate(keys -> {
|
||||
Key old = key(keys, id);
|
||||
keys.put(id, new Key(id, old.secret(), bucket, prefix, Set.copyOf(actions), old.enabled()));
|
||||
});
|
||||
}
|
||||
|
||||
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/_-]*") ||
|
||||
actions.isEmpty() || !ACTIONS.containsAll(actions))
|
||||
invalid("Invalid key scope");
|
||||
}
|
||||
|
||||
synchronized void setEnabled(String id, boolean enabled) throws IOException {
|
||||
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 {
|
||||
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) {
|
||||
Key key = key(principal);
|
||||
boolean head = method.equals("HEAD") &&
|
||||
(query.isEmpty() || query.size() == 1 && "HeadBucket".equals(query.get("x-id")));
|
||||
boolean list = method.equals("GET") && "2".equals(query.get("list-type")) &&
|
||||
query.getOrDefault("prefix", "").startsWith(key.prefix());
|
||||
if (!key.enabled() || !key.bucket().equals(bucket) || !key.actions().contains("list") ||
|
||||
!(head || list))
|
||||
denied();
|
||||
}
|
||||
|
||||
void checkObject(String principal, String bucket, String object, String method,
|
||||
Map<String, String> query, Headers headers) {
|
||||
Key key = key(principal);
|
||||
String action = method.equals("GET") || method.equals("HEAD") ? "read" : "write";
|
||||
if (!key.enabled() || !key.bucket().equals(bucket) || !object.startsWith(key.prefix()) ||
|
||||
!key.actions().contains(action) || query.containsKey("acl") ||
|
||||
headers.containsKey("x-amz-acl") || headers.keySet().stream().anyMatch(name ->
|
||||
name.toLowerCase(java.util.Locale.ROOT).startsWith("x-amz-grant-"))) denied();
|
||||
String source = headers.getFirst("x-amz-copy-source");
|
||||
if (source != null) {
|
||||
if (source.startsWith("/")) source = source.substring(1);
|
||||
int question = source.indexOf('?');
|
||||
if (question >= 0) source = source.substring(0, question);
|
||||
int slash = source.indexOf('/');
|
||||
if (slash < 1 || !key.actions().contains("read") ||
|
||||
!key.bucket().equals(SigV4.decode(source.substring(0, slash))) ||
|
||||
!SigV4.decode(source.substring(slash + 1)).startsWith(key.prefix())) denied();
|
||||
}
|
||||
}
|
||||
|
||||
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 static byte[] randomToken() {
|
||||
byte[] nonce = new byte[12];
|
||||
RANDOM.nextBytes(nonce);
|
||||
return nonce;
|
||||
}
|
||||
|
||||
private static void invalid(String message) { throw new StoreException(400, "InvalidArgument", message); }
|
||||
private static void denied() { throw new StoreException(403, "AccessDenied", "Access denied"); }
|
||||
}
|
||||
@@ -1,7 +1,10 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import com.sun.net.httpserver.HttpExchange;
|
||||
import com.sun.net.httpserver.Headers;
|
||||
import com.sun.net.httpserver.HttpsExchange;
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
@@ -12,75 +15,34 @@ final class MultipartHandler {
|
||||
private final ObjectStorage store;
|
||||
private final MultipartStorage multipart;
|
||||
private final SigV4 authentication;
|
||||
private final S3Access access;
|
||||
private final String owner;
|
||||
private final URI publicEndpoint;
|
||||
|
||||
MultipartHandler(ObjectStorage store, MultipartStorage multipart, SigV4 authentication) {
|
||||
MultipartHandler(ObjectStorage store, MultipartStorage multipart, SigV4 authentication,
|
||||
S3Access access, URI publicEndpoint) {
|
||||
this.store = store;
|
||||
this.multipart = multipart;
|
||||
this.authentication = authentication;
|
||||
this.access = access;
|
||||
this.owner = authentication.root();
|
||||
this.publicEndpoint = publicEndpoint;
|
||||
}
|
||||
|
||||
void handleMultipart(HttpExchange exchange, String method, Map<String, String> query,
|
||||
String key, SigV4.Verified verified, String bucketName) throws IOException {
|
||||
String hash = verified.payload();
|
||||
var headers = exchange.getRequestHeaders();
|
||||
if ((headers.containsKey("content-encoding") && !(method.equals("PUT") && verified.streaming())) ||
|
||||
headers.containsKey("if-none-match"))
|
||||
S3Request.unsupported("Multipart request header");
|
||||
if (headers.containsKey("x-amz-copy-source") || headers.containsKey("x-amz-metadata-directive") ||
|
||||
headers.containsKey("x-amz-tagging-directive"))
|
||||
S3Request.unsupported("Multipart copy request");
|
||||
if (!query.containsKey("uploads") &&
|
||||
(headers.containsKey("x-amz-tagging") || !ObjectAttributes.userMetadata(headers).isEmpty() ||
|
||||
headers.containsKey("x-amz-acl") || headers.keySet().stream().anyMatch(
|
||||
name -> name.toLowerCase(Locale.ROOT).startsWith("x-amz-grant-"))))
|
||||
S3Request.unsupported("Multipart object attributes belong on initiation");
|
||||
if (!method.equals("PUT") && (headers.containsKey("content-md5") ||
|
||||
headers.containsKey("x-amz-sdk-checksum-algorithm") ||
|
||||
headers.keySet().stream().anyMatch(name -> name.toLowerCase(Locale.ROOT).startsWith("x-amz-checksum-"))))
|
||||
S3Request.unsupported("Multipart checksum header");
|
||||
if (query.containsKey("uploads")) {
|
||||
S3Request.requireEmptyBody(exchange, hash);
|
||||
Map<String, String> acl = Acl.fromHeaders(headers, authentication.identities());
|
||||
if (!acl.isEmpty() && !owner.equals(verified.principal()))
|
||||
Acl.require(store.bucket(bucketName).acl(), verified.principal(), owner, Acl.WRITE_ACP);
|
||||
String id = multipart.create(bucketName, key, S3Request.contentType(headers),
|
||||
ObjectAttributes.userMetadata(headers),
|
||||
ObjectAttributes.tagsHeader(SigV4.single(headers, "x-amz-tagging")), acl);
|
||||
S3Xml.sendXml(exchange, 200, "<InitiateMultipartUploadResult><Bucket>" + S3Xml.xml(bucketName) +
|
||||
"</Bucket><Key>" + S3Xml.xml(key) + "</Key><UploadId>" + id +
|
||||
"</UploadId></InitiateMultipartUploadResult>");
|
||||
boolean initiate = query.containsKey("uploads");
|
||||
validateHeaders(headers, method, verified.streaming(), initiate);
|
||||
if (initiate) {
|
||||
initiateUpload(exchange, key, verified, bucketName);
|
||||
return;
|
||||
}
|
||||
String id = query.get("uploadId");
|
||||
switch (method) {
|
||||
case "PUT" -> {
|
||||
int number;
|
||||
try { number = Integer.parseInt(query.get("partNumber")); }
|
||||
catch (NumberFormatException e) { throw new StoreException(400, "InvalidArgument", "Invalid part number"); }
|
||||
long length = verified.streaming() ? S3Request.decodedLength(headers) : S3Request.contentLength(headers);
|
||||
UploadChecksums checksums = UploadChecksums.from(headers);
|
||||
AwsChunkedInputStream chunked = verified.streaming() ? S3Request.chunkedBody(exchange, verified) : null;
|
||||
String etag = multipart.putPart(id, bucketName, key, number,
|
||||
checksums.verifying(chunked == null ? exchange.getRequestBody() : chunked),
|
||||
length, S3Request.expectedPayloadHash(hash), checksums.sha256());
|
||||
exchange.getResponseHeaders().set("ETag", "\"" + etag + "\"");
|
||||
checksums.response(exchange.getResponseHeaders());
|
||||
if (chunked != null && chunked.trailerValue() != null)
|
||||
exchange.getResponseHeaders().set(SigV4.single(headers, "x-amz-trailer"), chunked.trailerValue());
|
||||
exchange.sendResponseHeaders(200, -1);
|
||||
}
|
||||
case "POST" -> {
|
||||
byte[] body = S3Request.signedBody(exchange, hash, 65536);
|
||||
List<MultipartStorage.Part> parts = S3Xml.completedParts(body);
|
||||
var meta = multipart.complete(id, bucketName, key, parts);
|
||||
if (meta.versionId() != null)
|
||||
exchange.getResponseHeaders().set("x-amz-version-id", meta.versionId());
|
||||
S3Xml.sendXml(exchange, 200, "<CompleteMultipartUploadResult><Bucket>" + S3Xml.xml(bucketName) +
|
||||
"</Bucket><Key>" + S3Xml.xml(key) + "</Key><ETag>"" + meta.etag() +
|
||||
""</ETag></CompleteMultipartUploadResult>");
|
||||
}
|
||||
case "PUT" -> uploadPart(exchange, id, key, query.get("partNumber"), verified, bucketName);
|
||||
case "POST" -> completeUpload(exchange, id, key, hash, bucketName);
|
||||
case "DELETE" -> {
|
||||
S3Request.requireEmptyBody(exchange, hash);
|
||||
multipart.abort(id, bucketName, key);
|
||||
@@ -94,6 +56,100 @@ final class MultipartHandler {
|
||||
}
|
||||
}
|
||||
|
||||
private static void validateHeaders(Headers headers, String method, boolean streaming, boolean initiate) {
|
||||
if ((headers.containsKey("content-encoding") && !(method.equals("PUT") && streaming)) ||
|
||||
headers.containsKey("if-none-match"))
|
||||
S3Request.unsupported("Multipart request header");
|
||||
if (headers.containsKey("x-amz-copy-source") || headers.containsKey("x-amz-metadata-directive") ||
|
||||
headers.containsKey("x-amz-tagging-directive"))
|
||||
S3Request.unsupported("Multipart copy request");
|
||||
if (!initiate && hasObjectAttributes(headers))
|
||||
S3Request.unsupported("Multipart object attributes belong on initiation");
|
||||
validateChecksumHeaders(headers, method, initiate);
|
||||
}
|
||||
|
||||
private static boolean hasObjectAttributes(Headers headers) {
|
||||
return headers.containsKey("x-amz-tagging") || !ObjectAttributes.userMetadata(headers).isEmpty() ||
|
||||
headers.containsKey("x-amz-acl") || headers.keySet().stream().anyMatch(
|
||||
name -> name.toLowerCase(Locale.ROOT).startsWith("x-amz-grant-"));
|
||||
}
|
||||
|
||||
private static void validateChecksumHeaders(Headers headers, String method, boolean initiate) {
|
||||
if (!method.equals("PUT") && (headers.containsKey("content-md5") ||
|
||||
headers.containsKey("x-amz-sdk-checksum-algorithm") ||
|
||||
headers.keySet().stream().anyMatch(name -> {
|
||||
String lower = name.toLowerCase(Locale.ROOT);
|
||||
return lower.startsWith("x-amz-checksum-") &&
|
||||
!(initiate && lower.equals("x-amz-checksum-algorithm"));
|
||||
})))
|
||||
S3Request.unsupported("Multipart checksum header");
|
||||
}
|
||||
|
||||
private void initiateUpload(HttpExchange exchange, String key, SigV4.Verified verified,
|
||||
String bucketName) throws IOException {
|
||||
var headers = exchange.getRequestHeaders();
|
||||
String algorithm = SigV4.single(headers, "x-amz-checksum-algorithm");
|
||||
if (algorithm != null && !algorithm.equals("CRC32"))
|
||||
S3Request.unsupported("Multipart checksum algorithm");
|
||||
S3Request.requireEmptyBody(exchange, verified.payload());
|
||||
Map<String, String> acl = Acl.fromHeaders(headers, authentication.identities());
|
||||
BucketSecurity.checkAcl(store.bucket(bucketName), headers, acl, false);
|
||||
if (!acl.isEmpty() && !owner.equals(verified.principal()))
|
||||
access.requireBucket(bucketName, verified.principal(), Acl.WRITE_ACP);
|
||||
String id = multipart.create(bucketName, key, S3Request.contentType(headers),
|
||||
ObjectAttributes.userMetadata(headers),
|
||||
ObjectAttributes.tagsHeader(SigV4.single(headers, "x-amz-tagging")), acl);
|
||||
S3Xml.sendXml(exchange, 200, "<InitiateMultipartUploadResult><Bucket>" + S3Xml.xml(bucketName) +
|
||||
"</Bucket><Key>" + S3Xml.xml(key) + "</Key><UploadId>" + id +
|
||||
"</UploadId></InitiateMultipartUploadResult>");
|
||||
}
|
||||
|
||||
private void uploadPart(HttpExchange exchange, String id, String key, String partNumber,
|
||||
SigV4.Verified verified, String bucketName) throws IOException {
|
||||
var headers = exchange.getRequestHeaders();
|
||||
int number;
|
||||
try { number = Integer.parseInt(partNumber); }
|
||||
catch (NumberFormatException e) { throw new StoreException(400, "InvalidArgument", "Invalid part number"); }
|
||||
long length = verified.streaming() ? S3Request.decodedLength(headers) : S3Request.contentLength(headers);
|
||||
UploadChecksums checksums = UploadChecksums.from(headers);
|
||||
AwsChunkedInputStream chunked = verified.streaming() ? S3Request.chunkedBody(exchange, verified) : null;
|
||||
String etag = multipart.putPart(id, bucketName, key, number,
|
||||
checksums.verifying(chunked == null ? exchange.getRequestBody() : chunked),
|
||||
length, S3Request.expectedPayloadHash(verified.payload()), checksums.sha256());
|
||||
exchange.getResponseHeaders().set("ETag", "\"" + etag + "\"");
|
||||
checksums.response(exchange.getResponseHeaders());
|
||||
if (chunked != null && chunked.trailerValue() != null)
|
||||
exchange.getResponseHeaders().set(SigV4.single(headers, "x-amz-trailer"), chunked.trailerValue());
|
||||
exchange.sendResponseHeaders(200, -1);
|
||||
}
|
||||
|
||||
private void completeUpload(HttpExchange exchange, String id, String key, String hash,
|
||||
String bucketName) throws IOException {
|
||||
byte[] body = S3Request.signedBody(exchange, hash, 65536);
|
||||
List<MultipartStorage.Part> parts = S3Xml.completedParts(body);
|
||||
var meta = multipart.complete(id, bucketName, key, parts);
|
||||
if (meta.versionId() != null)
|
||||
exchange.getResponseHeaders().set("x-amz-version-id", meta.versionId());
|
||||
S3Xml.sendXml(exchange, 200, "<CompleteMultipartUploadResult><Location>" +
|
||||
S3Xml.xml(location(exchange, bucketName, key)) + "</Location><Bucket>" + S3Xml.xml(bucketName) +
|
||||
"</Bucket><Key>" + S3Xml.xml(key) + "</Key><ETag>"" + meta.etag() +
|
||||
""</ETag></CompleteMultipartUploadResult>");
|
||||
}
|
||||
|
||||
private String location(HttpExchange exchange, String bucket, String key) {
|
||||
String host = SigV4.single(exchange.getRequestHeaders(), "host");
|
||||
if (host == null) throw new StoreException(400, "InvalidRequest", "Missing Host header");
|
||||
String scheme = exchange instanceof HttpsExchange ? "https" : "http";
|
||||
return objectLocation(publicEndpoint, host, scheme, exchange.getRequestURI().getRawPath(), bucket, key);
|
||||
}
|
||||
|
||||
static String objectLocation(URI endpoint, String host, String scheme, String rawPath,
|
||||
String bucket, String key) {
|
||||
if (endpoint != null)
|
||||
return endpoint + "/" + bucket + "/" + SigV4.encode(key, true);
|
||||
return URI.create(scheme + "://" + host + rawPath).toASCIIString();
|
||||
}
|
||||
|
||||
private void listParts(HttpExchange exchange, String id, String key, Map<String, String> query,
|
||||
String bucketName) throws IOException {
|
||||
int marker = S3Request.boundedNumber(query.get("part-number-marker"), 0, 10000, 0);
|
||||
|
||||
@@ -6,7 +6,16 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
interface MultipartStorage {
|
||||
record Part(int number, String etag) {}
|
||||
record Part(int number, String etag, String checksumCrc32) {
|
||||
Part(int number, String etag) { this(number, etag, null); }
|
||||
|
||||
void verifyCrc32(long value) {
|
||||
if (checksumCrc32 == null) return;
|
||||
byte[] bytes = java.nio.ByteBuffer.allocate(4).putInt((int) value).array();
|
||||
if (!checksumCrc32.equals(java.util.Base64.getEncoder().encodeToString(bytes)))
|
||||
throw new StoreException(400, "BadDigest", "Part CRC32 checksum mismatch");
|
||||
}
|
||||
}
|
||||
record PartInfo(int number, long length, String etag, long modified) {}
|
||||
record PartPage(List<PartInfo> parts, int nextMarker, boolean truncated) {}
|
||||
record UploadInfo(String id, String key, long created) {}
|
||||
|
||||
@@ -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,19 +152,23 @@ 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)) {
|
||||
byte[] buffer = new byte[65536];
|
||||
int n;
|
||||
while ((n = input.read(buffer)) != -1) {
|
||||
sha.update(buffer, 0, n);
|
||||
md5.update(buffer, 0, n);
|
||||
crc32.update(buffer, 0, n);
|
||||
}
|
||||
}
|
||||
if (!SigV4.hex(md5.digest()).equals(part.etag().replace("\"", "")))
|
||||
throw new StoreException(400, "InvalidPart", "Part ETag mismatch");
|
||||
part.verifyCrc32(crc32.getValue());
|
||||
paths.add(file);
|
||||
}
|
||||
ObjectStorage.Metadata result;
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
@@ -76,18 +75,11 @@ final class NodeClient {
|
||||
HttpRequest request = HttpRequest.newBuilder(url.resolve("/identity"))
|
||||
.timeout(Duration.ofSeconds(2)).header("X-Cluster-Token", token).GET().build();
|
||||
try {
|
||||
HttpResponse<InputStream> response = http.send(request, HttpResponse.BodyHandlers.ofInputStream());
|
||||
try (InputStream body = response.body()) {
|
||||
if (response.statusCode() != 200) throw new IOException("Node identity request failed: " + response.statusCode());
|
||||
byte[] bytes = body.readNBytes(128);
|
||||
if (bytes.length == 128) throw new IOException("Node identity response is too large");
|
||||
String[] parts = new String(bytes, java.nio.charset.StandardCharsets.US_ASCII).trim().split(" ", -1);
|
||||
if (parts.length != 2) throw new IOException("Invalid node identity response");
|
||||
return new NodeIdentity(UUID.fromString(parts[0]), UUID.fromString(parts[1]));
|
||||
}
|
||||
} catch (InterruptedException error) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new IOException("Interrupted during node identity request", error);
|
||||
HttpResponse<byte[]> response = NodeHttp.bytes(http, request, 127);
|
||||
if (response.statusCode() != 200) throw new IOException("Node identity request failed: " + response.statusCode());
|
||||
String[] parts = new String(response.body(), java.nio.charset.StandardCharsets.US_ASCII).trim().split(" ", -1);
|
||||
if (parts.length != 2) throw new IOException("Invalid node identity response");
|
||||
return new NodeIdentity(UUID.fromString(parts[0]), UUID.fromString(parts[1]));
|
||||
} catch (IllegalArgumentException error) {
|
||||
throw new IOException("Invalid node identity response", error);
|
||||
}
|
||||
@@ -98,6 +90,12 @@ final class NodeClient {
|
||||
catch (IOException offline) { return null; }
|
||||
}
|
||||
|
||||
boolean reachable(Node node) {
|
||||
NodeIdentity actual = probeIfAvailable(node.url(), token, http);
|
||||
return actual != null && actual.nodeId().equals(node.id()) &&
|
||||
actual.hostId().equals(node.hostId());
|
||||
}
|
||||
|
||||
private static NodeIdentity probeIfAvailable(URI url, String token, HttpClient http) {
|
||||
try { return probe(url, token, http); }
|
||||
catch (IOException offline) { return null; }
|
||||
@@ -176,8 +174,8 @@ final class NodeClient {
|
||||
throw new IOException("Repair authority is not available to this process");
|
||||
builder.header("X-Cluster-Repair", "true").header("X-Cluster-Repair-Token", repairToken);
|
||||
}
|
||||
HttpResponse<Void> response = send(builder.PUT(HttpRequest.BodyPublishers.ofByteArray(data)).build(),
|
||||
HttpResponse.BodyHandlers.discarding());
|
||||
HttpResponse<Void> response = NodeHttp.discard(http,
|
||||
builder.PUT(HttpRequest.BodyPublishers.ofByteArray(data)).build());
|
||||
if (response.statusCode() != 200) throw new IOException("Node " + node.id() + " rejected segment: " + response.statusCode());
|
||||
}
|
||||
|
||||
@@ -196,22 +194,15 @@ final class NodeClient {
|
||||
HttpRequest request = HttpRequest.newBuilder(node.url().resolve("/segments/" + id))
|
||||
.timeout(Duration.ofSeconds(30)).header("X-Cluster-Token", token)
|
||||
.header("X-Cluster-Expected-Node", node.id().toString()).GET().build();
|
||||
HttpResponse<InputStream> response;
|
||||
try { response = send(request, HttpResponse.BodyHandlers.ofInputStream()); }
|
||||
HttpResponse<byte[]> response;
|
||||
try { response = NodeHttp.bytes(http, request, length + 1); }
|
||||
catch (IOException error) {
|
||||
markUnreadable(node);
|
||||
throw error;
|
||||
}
|
||||
if (response.statusCode() != 200) {
|
||||
response.body().close();
|
||||
if (response.statusCode() != 200)
|
||||
throw new IOException("Node " + node.id() + " has no verified copy of segment " + id);
|
||||
}
|
||||
byte[] bytes;
|
||||
try (InputStream body = response.body()) { bytes = body.readNBytes(length + 1); }
|
||||
catch (IOException error) {
|
||||
markUnreadable(node);
|
||||
throw error;
|
||||
}
|
||||
byte[] bytes = response.body();
|
||||
if (bytes.length != length || !MessageDigest.isEqual(SigV4.hash(bytes), sha256))
|
||||
throw new IOException("Node " + node.id() + " has no verified copy of segment " + id);
|
||||
unreadableUntil.remove(node.id());
|
||||
@@ -228,31 +219,28 @@ final class NodeClient {
|
||||
.timeout(Duration.ofSeconds(30)).header("X-Cluster-Token", token)
|
||||
.header("X-Cluster-Expected-Node", node.id().toString())
|
||||
.header("X-Cluster-Repair-Token", repairToken).GET().build();
|
||||
HttpResponse<InputStream> response = send(request, HttpResponse.BodyHandlers.ofInputStream());
|
||||
try (InputStream body = response.body()) {
|
||||
if (response.statusCode() != 200) throw new IOException("Node inventory failed: " + response.statusCode());
|
||||
byte[] bytes = body.readNBytes(70001);
|
||||
if (bytes.length > 70000) throw new IOException("Node inventory response is too large");
|
||||
List<StoredSegment> result = new ArrayList<>();
|
||||
String last = after == null ? "" : after.toString();
|
||||
for (String line : new String(bytes, java.nio.charset.StandardCharsets.US_ASCII).split("\n")) {
|
||||
if (line.isEmpty()) continue;
|
||||
String[] fields = line.split(" ", -1);
|
||||
if (fields.length != 2) throw new IOException("Invalid node inventory response");
|
||||
try {
|
||||
UUID id = UUID.fromString(fields[0]);
|
||||
if (!id.toString().equals(fields[0]) || !fields[0].startsWith(shard) ||
|
||||
fields[0].compareTo(last) <= 0)
|
||||
throw new IOException("Invalid node inventory cursor");
|
||||
result.add(new StoredSegment(id, Long.parseLong(fields[1])));
|
||||
last = fields[0];
|
||||
} catch (IllegalArgumentException error) {
|
||||
throw new IOException("Invalid node inventory response", error);
|
||||
}
|
||||
HttpResponse<byte[]> response = NodeHttp.bytes(http, request, 70000);
|
||||
if (response.statusCode() != 200) throw new IOException("Node inventory failed: " + response.statusCode());
|
||||
byte[] bytes = response.body();
|
||||
List<StoredSegment> result = new ArrayList<>();
|
||||
String last = after == null ? "" : after.toString();
|
||||
for (String line : new String(bytes, java.nio.charset.StandardCharsets.US_ASCII).split("\n")) {
|
||||
if (line.isEmpty()) continue;
|
||||
String[] fields = line.split(" ", -1);
|
||||
if (fields.length != 2) throw new IOException("Invalid node inventory response");
|
||||
try {
|
||||
UUID id = UUID.fromString(fields[0]);
|
||||
if (!id.toString().equals(fields[0]) || !fields[0].startsWith(shard) ||
|
||||
fields[0].compareTo(last) <= 0)
|
||||
throw new IOException("Invalid node inventory cursor");
|
||||
result.add(new StoredSegment(id, Long.parseLong(fields[1])));
|
||||
last = fields[0];
|
||||
} catch (IllegalArgumentException error) {
|
||||
throw new IOException("Invalid node inventory response", error);
|
||||
}
|
||||
if (result.size() > 1000) throw new IOException("Node inventory page is too large");
|
||||
return result;
|
||||
}
|
||||
if (result.size() > 1000) throw new IOException("Node inventory page is too large");
|
||||
return result;
|
||||
}
|
||||
|
||||
boolean deleteOrphan(int index, StoredSegment segment, long minimumAgeMillis) throws IOException {
|
||||
@@ -266,17 +254,10 @@ final class NodeClient {
|
||||
.header("X-Cluster-Expected-Mtime", Long.toString(segment.modified()))
|
||||
.header("X-Cluster-Gc-Min-Age-Millis", Long.toString(minimumAgeMillis))
|
||||
.DELETE().build();
|
||||
HttpResponse<Void> response = send(request, HttpResponse.BodyHandlers.discarding());
|
||||
HttpResponse<Void> response = NodeHttp.discard(http, request);
|
||||
if (response.statusCode() == 204) return true;
|
||||
if (response.statusCode() == 404 || response.statusCode() == 409) return false;
|
||||
throw new IOException("Node refused orphan deletion: " + response.statusCode());
|
||||
}
|
||||
|
||||
private <T> HttpResponse<T> send(HttpRequest request, HttpResponse.BodyHandler<T> handler) throws IOException {
|
||||
try { return http.send(request, handler); }
|
||||
catch (InterruptedException error) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new IOException("Interrupted during node request", error);
|
||||
}
|
||||
}
|
||||
}
|
||||