Expand admin tools and harden storage operations
No files matched your search
@@ -14,6 +14,7 @@ HOST_PORT=9000
|
||||
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
|
||||
|
||||
@@ -9,12 +9,20 @@ COPY lib/hash4j-0.30.0.jar /tmp/hash4j.jar
|
||||
RUN echo 'd3224b113ea835ce3452097747e5209ec760cf443dbed770d6ba68a0d480178f /tmp/hash4j.jar' | sha256sum -c -
|
||||
RUN mkdir /out && javac --release 21 --add-modules jdk.httpserver,java.net.http -cp /tmp/hash4j.jar -d /out src/cloud/lunarsky/store/*.java test/cloud/lunarsky/store/*.java
|
||||
RUN java --add-modules jdk.httpserver -cp /out:/tmp/hash4j.jar cloud.lunarsky.store.StoreTest
|
||||
RUN java --add-modules jdk.httpserver -cp /out:/tmp/hash4j.jar cloud.lunarsky.store.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,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
|
||||
|
||||
@@ -67,7 +67,17 @@ Set `METRICS_BEARER_TOKEN` to a random value of at least 32 characters to enable
|
||||
|
||||
### Local admin console
|
||||
|
||||
The admin console is a read-only status, bucket, and performance view at `http://127.0.0.1:9001/_objectstore/admin/`. It lists buckets, navigates object prefixes, and shows object metadata and bucket access settings. The object-size chart and counts cover only the current page of a listing. The performance view samples every three seconds while visible and graphs S3 request rate, inbound and outbound body bytes, process CPU, and memory. It also shows GC collections. Admin requests and health checks are excluded from those S3 rates, and chart history lives only in the browser tab. RSS is read from Linux when available; otherwise the memory card shows JVM heap plus non-heap usage. This view does not require the separate Prometheus token. It is disabled by default and uses a separate password, not an S3 access key. Its Biscuit widgets are bundled with the image under the MIT license in `admin-ui/LICENSE.Biscuit`. To enable it for the local Compose stack:
|
||||
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 version 14 stores 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
|
||||
@@ -80,10 +90,27 @@ 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. This local key manager currently supports disk mode only; the cluster requires externally managed identities, because gateways do not share this credential database.
|
||||
|
||||
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.
|
||||
|
||||
## Cold snapshots
|
||||
|
||||
@@ -54,7 +54,21 @@ Versioning supports enabled and suspended states. Old versions and delete marker
|
||||
|
||||
## 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
|
||||
@@ -64,7 +78,7 @@ curl http://127.0.0.1:9000/health
|
||||
|
||||
Port 9000 binds to localhost. Data stays in the `object-data` Docker volume. `docker compose down -v` deletes that volume.
|
||||
|
||||
The optional [local admin console](OPERATIONS.md#local-admin-console) has bucket and live performance views, its own password, and is disabled by default.
|
||||
The optional [local admin console](OPERATIONS.md#local-admin-console) manages buckets, ACLs, policies, scoped keys, bulk jobs, access checks, and live performance. It has its own password and is disabled in the base Compose stack.
|
||||
|
||||
The standalone defaults are 128 MiB per object and 2 GiB total. Set `MAX_OBJECT_BYTES` and `MAX_TOTAL_BYTES` in `.env` to change them. Incomplete multipart uploads consume space until aborted.
|
||||
|
||||
|
||||
@@ -17,19 +17,32 @@ 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. |
|
||||
| `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. |
|
||||
| `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 `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.
|
||||
|
||||
## 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.
|
||||
@@ -61,6 +74,10 @@ The Docker suite checks signed capability discovery and S3 operations, bucket cr
|
||||
|
||||
`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).
|
||||
|
||||
`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
|
||||
|
||||
The [manual two-machine drill](tests/two-host/README.md) uses machine A and machine B with disposable volumes. It records acknowledged writes during a machine interruption, checks reads and write rejection with either storage machine unavailable, restarts test containers during writes, and restores a metadata backup on machine B. This drill is not part of `scripts/test.sh` because it requires two machines and a coordinated interruption.
|
||||
|
||||
@@ -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 |
@@ -1,153 +1,224 @@
|
||||
(() => {
|
||||
const base = '/_objectstore/admin';
|
||||
const state = document.getElementById('perf-state');
|
||||
const charts = [
|
||||
['perf-requests-chart', [
|
||||
{ type: 'line', x: 'time', y: 'requests', name: 'Requests/s' },
|
||||
{ type: 'line', x: 'time', y: 'errors', name: 'Errors/s' }
|
||||
]],
|
||||
['perf-transfer-chart', [
|
||||
{ type: 'line', x: 'time', y: 'inbound', name: 'Inbound KiB/s' },
|
||||
{ type: 'line', x: 'time', y: 'outbound', name: 'Outbound KiB/s' }
|
||||
]],
|
||||
['perf-cpu-chart', [
|
||||
{ type: 'line', x: 'time', y: 'cpu', name: 'CPU %' }
|
||||
]],
|
||||
['perf-memory-chart', [
|
||||
{ type: 'line', x: 'time', y: 'memory', name: 'RSS MiB' },
|
||||
{ type: 'line', x: 'time', y: 'heap', name: 'Heap MiB' }
|
||||
]]
|
||||
].map(([id, series]) => {
|
||||
const chart = document.getElementById(id);
|
||||
chart.series = series;
|
||||
return chart;
|
||||
});
|
||||
const history = [];
|
||||
let previous = null;
|
||||
let polling = false;
|
||||
let memoryFallback = false;
|
||||
let cleanup = null;
|
||||
|
||||
function show(id, value) {
|
||||
document.getElementById(id).textContent = value;
|
||||
}
|
||||
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 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++;
|
||||
function show(id, value) {
|
||||
document.getElementById(id).textContent = value;
|
||||
}
|
||||
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 showState(message, status) {
|
||||
state.textContent = message;
|
||||
state.dataset.state = status;
|
||||
if (loader) loader.hidden = status !== 'loading';
|
||||
}
|
||||
|
||||
function counterDelta(current, before, key) {
|
||||
return Math.max(0, current[key] - before[key]);
|
||||
}
|
||||
|
||||
function updateCharts() {
|
||||
document.querySelector('.perf-charts').hidden = history.length === 0;
|
||||
for (const chart of charts)
|
||||
chart.data = chart.id === 'perf-cpu-chart'
|
||||
? history.filter(point => point.cpu !== null) : history;
|
||||
}
|
||||
|
||||
async function poll() {
|
||||
if (polling || document.hidden) return;
|
||||
polling = true;
|
||||
const controller = new AbortController();
|
||||
const timeout = setTimeout(() => controller.abort(), 5000);
|
||||
try {
|
||||
const response = await fetch(base + '/performance.json', {
|
||||
cache: 'no-store', credentials: 'same-origin', signal: controller.signal
|
||||
});
|
||||
if (response.redirected) {
|
||||
location.assign(base + '/login');
|
||||
return;
|
||||
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++;
|
||||
}
|
||||
if (!response.ok) throw new Error('Metrics unavailable');
|
||||
if (!response.headers.get('Content-Type')?.includes('application/json'))
|
||||
throw new Error('Unexpected metrics response');
|
||||
const sample = await response.json();
|
||||
const now = performance.now();
|
||||
const rss = sample.rssBytes >= 0 ? sample.rssBytes : sample.heapBytes + sample.nonHeapBytes;
|
||||
if (sample.rssBytes < 0 && !memoryFallback) {
|
||||
memoryFallback = true;
|
||||
document.querySelector('#perf-ram').previousElementSibling.textContent = 'JVM memory used';
|
||||
charts[3].series = [
|
||||
{ type: 'line', x: 'time', y: 'memory', name: 'JVM used MiB' },
|
||||
{ type: 'line', x: 'time', y: 'heap', name: 'Heap MiB' }
|
||||
];
|
||||
}
|
||||
show('perf-ram', bytes(rss));
|
||||
show('perf-gc', Number(sample.gcCount).toLocaleString());
|
||||
show('perf-inflight', Number(sample.inFlight).toLocaleString());
|
||||
if (previous && sample.requests < previous.sample.requests) {
|
||||
history.length = 0;
|
||||
updateCharts();
|
||||
}
|
||||
if (previous && sample.requests >= previous.sample.requests) {
|
||||
const seconds = (now - previous.at) / 1000;
|
||||
if (seconds > 0.1) {
|
||||
const requests = counterDelta(sample, previous.sample, 'requests');
|
||||
const errors = counterDelta(sample, previous.sample, 'failures4xx') +
|
||||
counterDelta(sample, previous.sample, 'failures5xx');
|
||||
const cpu = sample.cpuNanos >= 0 && previous.sample.cpuNanos >= 0
|
||||
? Math.max(0, Math.min(100,
|
||||
(sample.cpuNanos - previous.sample.cpuNanos) /
|
||||
(seconds * 1e9 * Math.max(1, sample.processors)) * 100))
|
||||
: null;
|
||||
const point = {
|
||||
time: new Date().toLocaleTimeString(),
|
||||
requests: requests / seconds,
|
||||
errors: errors / seconds,
|
||||
inbound: counterDelta(sample, previous.sample, 'inboundBytes') / seconds / 1024,
|
||||
outbound: counterDelta(sample, previous.sample, 'outboundBytes') / seconds / 1024,
|
||||
cpu,
|
||||
memory: rss / 1048576,
|
||||
heap: sample.heapBytes / 1048576,
|
||||
seconds
|
||||
};
|
||||
history.push(point);
|
||||
if (history.length > 60) history.shift();
|
||||
show('perf-rps', rate(point.requests));
|
||||
show('perf-latency', requests ?
|
||||
(counterDelta(sample, previous.sample, 'durationNanos') / requests / 1e6).toFixed(1) + ' ms' : '—');
|
||||
show('perf-inbound', bytes(point.inbound * 1024, '/s'));
|
||||
show('perf-outbound', bytes(point.outbound * 1024, '/s'));
|
||||
const cpuPoints = history.filter(entry => entry.cpu !== null);
|
||||
const cpuSeconds = cpuPoints.reduce((total, entry) => total + entry.seconds, 0);
|
||||
show('perf-cpu', cpuSeconds ?
|
||||
(cpuPoints.reduce((total, entry) => total + entry.cpu * entry.seconds, 0) /
|
||||
cpuSeconds).toFixed(1) + '%' : '—');
|
||||
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 accept(sample) {
|
||||
if (!active || document.hidden) return;
|
||||
try {
|
||||
const now = performance.now();
|
||||
const rss = sample.rssBytes >= 0 ? sample.rssBytes : sample.heapBytes + sample.nonHeapBytes;
|
||||
if (sample.rssBytes < 0 && !memoryFallback) {
|
||||
memoryFallback = true;
|
||||
document.querySelector('#perf-ram').previousElementSibling.textContent = 'JVM memory used';
|
||||
charts[3].series = [
|
||||
{ type: 'line', x: 'time', y: 'memory', name: 'JVM used MiB' },
|
||||
{ type: 'line', x: 'time', y: 'heap', name: 'Heap MiB' }
|
||||
];
|
||||
}
|
||||
show('perf-ram', bytes(rss));
|
||||
show('perf-gc', Number(sample.gcCount).toLocaleString());
|
||||
show('perf-inflight', Number(sample.inFlight).toLocaleString());
|
||||
if (previous && sample.requests < previous.sample.requests) {
|
||||
history.length = 0;
|
||||
updateCharts();
|
||||
}
|
||||
if (previous && sample.requests >= previous.sample.requests) {
|
||||
const seconds = (now - previous.at) / 1000;
|
||||
if (seconds > 0.1) {
|
||||
const requests = counterDelta(sample, previous.sample, 'requests');
|
||||
const errors = counterDelta(sample, previous.sample, 'failures4xx') +
|
||||
counterDelta(sample, previous.sample, 'failures5xx');
|
||||
const cpu = sample.cpuNanos >= 0 && previous.sample.cpuNanos >= 0
|
||||
? Math.max(0, Math.min(100,
|
||||
(sample.cpuNanos - previous.sample.cpuNanos) /
|
||||
(seconds * 1e9 * Math.max(1, sample.processors)) * 100))
|
||||
: null;
|
||||
const point = {
|
||||
time: new Date().toLocaleTimeString(),
|
||||
requests: requests / seconds,
|
||||
errors: errors / seconds,
|
||||
inbound: counterDelta(sample, previous.sample, 'inboundBytes') / seconds / 1024,
|
||||
outbound: counterDelta(sample, previous.sample, 'outboundBytes') / seconds / 1024,
|
||||
cpu,
|
||||
memory: rss / 1048576,
|
||||
heap: sample.heapBytes / 1048576,
|
||||
seconds
|
||||
};
|
||||
history.push(point);
|
||||
if (history.length > 60) history.shift();
|
||||
show('perf-rps', rate(point.requests));
|
||||
show('perf-latency', requests ?
|
||||
(counterDelta(sample, previous.sample, 'durationNanos') / requests / 1e6).toFixed(1) + ' ms' : '—');
|
||||
show('perf-inbound', bytes(point.inbound * 1024, '/s'));
|
||||
show('perf-outbound', bytes(point.outbound * 1024, '/s'));
|
||||
const cpuPoints = history.filter(entry => entry.cpu !== null);
|
||||
const cpuSeconds = cpuPoints.reduce((total, entry) => total + entry.seconds, 0);
|
||||
show('perf-cpu', cpuSeconds ?
|
||||
(cpuPoints.reduce((total, entry) => total + entry.cpu * entry.seconds, 0) /
|
||||
cpuSeconds).toFixed(1) + '%' : '—');
|
||||
updateCharts();
|
||||
}
|
||||
}
|
||||
previous = { sample, at: now };
|
||||
showState(history.length ? 'Live · one-second samples' :
|
||||
'Collecting a second sample…', history.length ? 'live' : 'loading');
|
||||
} catch {
|
||||
showState('Invalid metrics sample · retrying', 'error');
|
||||
previous = null;
|
||||
}
|
||||
previous = { sample, at: now };
|
||||
state.textContent = history.length ? 'Live · recent samples' : 'Collecting a second sample…';
|
||||
} catch {
|
||||
state.textContent = 'Connection lost · retrying';
|
||||
previous = null;
|
||||
} finally {
|
||||
clearTimeout(timeout);
|
||||
polling = false;
|
||||
}
|
||||
|
||||
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);
|
||||
};
|
||||
}
|
||||
|
||||
document.addEventListener('visibilitychange', () => {
|
||||
if (document.hidden) {
|
||||
previous = null;
|
||||
state.textContent = 'Paused while this tab is hidden';
|
||||
} else {
|
||||
state.textContent = 'Collecting a fresh sample…';
|
||||
poll();
|
||||
}
|
||||
});
|
||||
poll();
|
||||
setInterval(poll, 3000);
|
||||
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);
|
||||
}
|
||||
})();
|
||||
@@ -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:
|
||||
|
||||
@@ -37,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:
|
||||
@@ -204,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
|
||||
@@ -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,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'
|
||||
@@ -2,16 +2,25 @@
|
||||
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 --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,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
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
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");
|
||||
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");
|
||||
String method = switch (operation) {
|
||||
case "read" -> "GET";
|
||||
case "write" -> "PUT";
|
||||
case "delete" -> "DELETE";
|
||||
default -> "GET";
|
||||
};
|
||||
try {
|
||||
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, method, query);
|
||||
else scopes.checkBucket(principal, bucket, method, query);
|
||||
} else {
|
||||
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());
|
||||
}
|
||||
} 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");
|
||||
}
|
||||
S3Access.Decision decision;
|
||||
if (operation.equals("list")) {
|
||||
decision = access.inspectBucket(bucket, principal);
|
||||
} else if (operation.equals("read")) {
|
||||
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");
|
||||
decision = access.inspectObject(bucket, key, page.objects().get(0).metadata(), principal);
|
||||
} else {
|
||||
decision = access.inspectWrite(bucket, key, principal,
|
||||
operation.equals("delete") ? "s3:DeleteObject" : "s3:PutObject");
|
||||
}
|
||||
return new Result(decision.allowed(), "Bucket and identity policy", decision.reason());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
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 = form.get("bucket");
|
||||
if (action.equals("create-bucket")) {
|
||||
bucket = required(form, "bucket", 63);
|
||||
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 ? new ObjectStorage.PublicAccessBlock(
|
||||
form.containsKey("blockPublicAcls"), form.containsKey("ignorePublicAcls"),
|
||||
form.containsKey("blockPublicPolicy"), form.containsKey("restrictPublicBuckets")) :
|
||||
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) {
|
||||
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);
|
||||
}
|
||||
return AdminBrowser.bucketUrl(bucket, "", null);
|
||||
}
|
||||
bucket = required(form, "bucket", 63);
|
||||
if (action.equals("rename-bucket")) {
|
||||
confirm(form, bucket);
|
||||
String newName = required(form, "newName", 63);
|
||||
String currentName = bucket;
|
||||
if (managed != null && managed.list().stream().anyMatch(key -> key.bucket().equals(currentName)))
|
||||
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);
|
||||
}
|
||||
if (action.equals("delete-bucket")) {
|
||||
confirm(form, bucket);
|
||||
store.deleteBucket(bucket);
|
||||
return AdminConsole.PATH + "/buckets";
|
||||
}
|
||||
ObjectStorage.Bucket current = store.bucket(bucket);
|
||||
switch (action) {
|
||||
case "delete-object" -> {
|
||||
String key = required(form, "key", 1024);
|
||||
if (!key.equals(form.get("confirm"))) invalid("Type the object key to confirm");
|
||||
String version = form.getOrDefault("version", "");
|
||||
if (version.length() > 256) invalid("Invalid object version");
|
||||
if (!version.isEmpty() && !version.equals(form.get("confirmVersion")))
|
||||
invalid("Type the version ID to confirm permanent deletion");
|
||||
store.delete(bucket, key, version.isEmpty() ? null : version);
|
||||
return AdminBrowser.bucketUrl(bucket, key.contains("/") ?
|
||||
key.substring(0, key.lastIndexOf('/') + 1) : "", null);
|
||||
}
|
||||
case "versioning" -> {
|
||||
String state = required(form, "state", 16);
|
||||
if (!state.equals("ENABLED") && !state.equals("SUSPENDED")) invalid("Invalid versioning state");
|
||||
store.setVersioning(bucket, ObjectStorage.VersioningState.valueOf(state));
|
||||
}
|
||||
case "ownership" -> {
|
||||
confirm(form, bucket);
|
||||
String value = required(form, "ownership", 32);
|
||||
store.setBucketOwnership(bucket, BucketSecurity.ownership(value));
|
||||
}
|
||||
case "public-access" -> {
|
||||
ObjectStorage.PublicAccessBlock block = new ObjectStorage.PublicAccessBlock(
|
||||
form.containsKey("blockPublicAcls"), form.containsKey("ignorePublicAcls"),
|
||||
form.containsKey("blockPublicPolicy"), form.containsKey("restrictPublicBuckets"));
|
||||
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);
|
||||
}
|
||||
case "policy" -> {
|
||||
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);
|
||||
}
|
||||
case "bucket-grant" -> {
|
||||
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);
|
||||
}
|
||||
case "object-grant" -> {
|
||||
String key = required(form, "key", 1024);
|
||||
String version = form.getOrDefault("version", "");
|
||||
if (version.length() > 256) invalid("Invalid object version");
|
||||
String versionId = version.isEmpty() ? null : version;
|
||||
ObjectStorage.Metadata metadata;
|
||||
try (ObjectStorage.OpenObject opened = store.open(bucket, key, versionId)) {
|
||||
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, versionId, acl);
|
||||
return AdminConsole.PATH + "/object?bucket=" + AdminBrowser.encoded(bucket) +
|
||||
"&key=" + AdminBrowser.encoded(key) +
|
||||
(versionId == null ? "" : "&version=" + AdminBrowser.encoded(versionId));
|
||||
}
|
||||
case "object-tag" -> {
|
||||
String key = required(form, "key", 1024);
|
||||
String tag = required(form, "tag", 128);
|
||||
String version = form.getOrDefault("version", "");
|
||||
if (version.length() > 256) invalid("Invalid object version");
|
||||
String versionId = version.isEmpty() ? null : version;
|
||||
Map<String, String> tags = new HashMap<>(store.tags(bucket, key, versionId));
|
||||
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, versionId, Map.copyOf(tags));
|
||||
return AdminConsole.PATH + "/object?bucket=" + AdminBrowser.encoded(bucket) +
|
||||
"&key=" + AdminBrowser.encoded(key) +
|
||||
(versionId == null ? "" : "&version=" + AdminBrowser.encoded(versionId));
|
||||
}
|
||||
default -> invalid("Unknown admin action");
|
||||
}
|
||||
return AdminBrowser.bucketUrl(bucket, "", null) + "#settings";
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -4,75 +4,97 @@ import java.io.IOException;
|
||||
import java.net.URLDecoder;
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import static cloud.lunarsky.store.AdminBrowserView.*;
|
||||
|
||||
final class AdminBrowser {
|
||||
private static final int PAGE_SIZE = 50;
|
||||
private static final DateTimeFormatter TIME = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm 'UTC'")
|
||||
.withZone(ZoneOffset.UTC);
|
||||
|
||||
private AdminBrowser() { }
|
||||
|
||||
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"));
|
||||
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();
|
||||
List<ObjectStorage.Bucket> page = matches.stream()
|
||||
.filter(bucket -> after == null || bucket.name().compareTo(after) > 0)
|
||||
.limit(PAGE_SIZE + 1).toList();
|
||||
boolean next = page.size() > PAGE_SIZE;
|
||||
if (next) page = page.subList(0, PAGE_SIZE);
|
||||
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 · read-only</p></div></div>")
|
||||
.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("/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>Ownership</th><th>Created</th></tr></thead><tbody>");
|
||||
.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(versioning(bucket.versioning())).append("</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 (after != null || next) {
|
||||
html.append("<nav class=pagination aria-label='Bucket pages'><a class=button-link href='")
|
||||
.append(indexUrl(filter, null)).append("'>First page</a>");
|
||||
if (next) html.append("<a class=button-link href='")
|
||||
.append(indexUrl(filter, page.getLast().name())).append("'>Next page →</a>");
|
||||
html.append("</nav>");
|
||||
}
|
||||
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", "");
|
||||
@@ -87,13 +109,33 @@ final class AdminBrowser {
|
||||
html.append(breadcrumbs(name, prefix));
|
||||
html.append("<div class=intro><div><h2>").append(AdminConsole.escape(name))
|
||||
.append("</h2><p>Browse prefixes and inspect object metadata.</p></div>")
|
||||
.append("<biscuit-badgeview theme=dark variant=accent>Read-only</biscuit-badgeview></div>")
|
||||
.append("<div class=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>")
|
||||
@@ -103,24 +145,55 @@ final class AdminBrowser {
|
||||
.append("<input id=prefix name=prefix value='").append(AdminConsole.escape(prefix))
|
||||
.append("' placeholder='e.g. images/2026/'></div><button type=submit>Browse</button></form>")
|
||||
.append("<a class=button-link href='").append(AdminConsole.PATH)
|
||||
.append("/buckets'>All buckets</a></div>");
|
||||
.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></tr></thead><tbody>");
|
||||
.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></tr>");
|
||||
.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></tr>");
|
||||
.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();
|
||||
@@ -130,20 +203,18 @@ final class AdminBrowser {
|
||||
.append(objectUrl(name, object.key())).append("'>")
|
||||
.append(AdminConsole.escape(label)).append("</a></td><td class=kind>Object</td><td>")
|
||||
.append(AdminConsole.formatBytes(meta.length())).append("</td><td>")
|
||||
.append(time(meta.modified())).append("</td></tr>");
|
||||
.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>");
|
||||
}
|
||||
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>");
|
||||
}
|
||||
|
||||
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=dark ")
|
||||
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) ->
|
||||
@@ -155,6 +226,9 @@ final class AdminBrowser {
|
||||
});
|
||||
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())))
|
||||
@@ -173,143 +247,62 @@ final class AdminBrowser {
|
||||
if (!bucket.acl().isEmpty())
|
||||
html.append(attributes("Bucket grants", bucket.acl()));
|
||||
html.append("</section>");
|
||||
return html.toString();
|
||||
}
|
||||
|
||||
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 {
|
||||
Map<String, String> query = query(rawQuery, Set.of("bucket", "key"));
|
||||
String bucketName = required(query, "bucket", 255);
|
||||
String key = required(query, "key", 1024);
|
||||
store.bucket(bucketName);
|
||||
ObjectStorage.Metadata meta;
|
||||
try (ObjectStorage.OpenObject opened = store.open(bucketName, key)) {
|
||||
meta = opened.metadata();
|
||||
}
|
||||
int slash = key.lastIndexOf('/');
|
||||
String prefix = slash < 0 ? "" : key.substring(0, slash + 1);
|
||||
StringBuilder html = new StringBuilder(AdminConsole.consoleHeader(csrf));
|
||||
html.append(breadcrumbs(bucketName, prefix))
|
||||
.append("<div class=intro><div><h2 class=name-cell>")
|
||||
.append(AdminConsole.escape(key.endsWith("/") ? "(folder marker)" : key.substring(prefix.length())))
|
||||
.append("</h2><p>Object metadata · content is not loaded in this view</p></div>")
|
||||
.append("<biscuit-badgeview theme=dark variant=accent>Object</biscuit-badgeview></div>")
|
||||
.append("<div class=grid><biscuit-cardview><small>Size</small><strong>")
|
||||
.append(AdminConsole.formatBytes(meta.length()))
|
||||
.append("</strong></biscuit-cardview><biscuit-cardview><small>Content type</small><strong>")
|
||||
.append(AdminConsole.escape(meta.contentType() == null ? "Unknown" : meta.contentType()))
|
||||
.append("</strong></biscuit-cardview><biscuit-cardview><small>Modified</small><strong>")
|
||||
.append(time(meta.modified())).append("</strong></biscuit-cardview></div>")
|
||||
.append("<div class=detail-grid><div class=detail-card><h3>Identity</h3>")
|
||||
.append(fact("Bucket", bucketName)).append(fact("Key", key))
|
||||
.append(fact("Version ID", meta.versionId() == null ? "Unversioned" : meta.versionId()))
|
||||
.append("</div><div class=detail-card><h3>Integrity</h3>")
|
||||
.append(fact("ETag", meta.etag() == null ? "—" : meta.etag()))
|
||||
.append(fact("SHA-256", meta.sha256() == null ? "—" :
|
||||
java.util.HexFormat.of().formatHex(meta.sha256())))
|
||||
.append("</div></div>")
|
||||
.append(attributes("User metadata", meta.userMetadata()))
|
||||
.append(attributes("Tags", meta.tags()))
|
||||
.append(attributes("Checksums", meta.checksums()))
|
||||
.append(attributes("ACL grants", meta.acl()));
|
||||
return html.toString();
|
||||
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) {
|
||||
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();
|
||||
return AdminBrowserView.bucketUrl(name, prefix, after);
|
||||
}
|
||||
|
||||
private static String objectUrl(String bucket, String key) {
|
||||
return AdminConsole.PATH + "/object?bucket=" + encoded(bucket) + "&key=" + encoded(key);
|
||||
}
|
||||
|
||||
private static String indexUrl(String filter, String after) {
|
||||
StringBuilder url = new StringBuilder(AdminConsole.PATH + "/buckets?filter=" + encoded(filter));
|
||||
if (after != null) url.append("&after=").append(encoded(after));
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
private static String breadcrumbs(String bucket, String prefix) {
|
||||
StringBuilder html = new StringBuilder("<nav class=crumbs aria-label=Breadcrumb><a href='")
|
||||
.append(AdminConsole.PATH).append("/buckets'>Buckets</a><span>/</span>");
|
||||
if (prefix.isEmpty()) {
|
||||
html.append("<span>").append(AdminConsole.escape(bucket)).append("</span>");
|
||||
} else {
|
||||
html.append("<a href='").append(bucketUrl(bucket, "", null)).append("'>")
|
||||
.append(AdminConsole.escape(bucket)).append("</a>");
|
||||
int from = 0;
|
||||
while (from < prefix.length()) {
|
||||
int slash = prefix.indexOf('/', from);
|
||||
if (slash < 0) break;
|
||||
String current = prefix.substring(0, slash + 1);
|
||||
String label = prefix.substring(from, slash + 1);
|
||||
html.append("<span>/</span><a href='").append(bucketUrl(bucket, current, null))
|
||||
.append("'>").append(AdminConsole.escape(label)).append("</a>");
|
||||
from = slash + 1;
|
||||
}
|
||||
}
|
||||
return html.append("</nav>").toString();
|
||||
}
|
||||
|
||||
private static String parentPrefix(String prefix) {
|
||||
int last = prefix.lastIndexOf('/', prefix.length() - 2);
|
||||
return last < 0 ? "" : prefix.substring(0, last + 1);
|
||||
}
|
||||
|
||||
private static String attributes(String title, Map<String, String> values) {
|
||||
if (values == null || values.isEmpty()) return "";
|
||||
StringBuilder html = new StringBuilder("<details><summary>")
|
||||
.append(AdminConsole.escape(title)).append(" (" + values.size() + ")</summary>")
|
||||
.append("<div class=table-wrap><table><thead><tr><th>Name</th><th>Value</th></tr></thead><tbody>");
|
||||
values.entrySet().stream().sorted(Map.Entry.comparingByKey()).forEach(entry ->
|
||||
html.append("<tr><td class=name-cell>").append(AdminConsole.escape(entry.getKey()))
|
||||
.append("</td><td class=name-cell>").append(AdminConsole.escape(entry.getValue() == null ? "" : entry.getValue()))
|
||||
.append("</td></tr>"));
|
||||
return html.append("</tbody></table></div></details>").toString();
|
||||
}
|
||||
|
||||
private static String fact(String name, String value) {
|
||||
return "<div class=fact><span>" + AdminConsole.escape(name) + "</span><strong>" +
|
||||
AdminConsole.escape(value) + "</strong></div>";
|
||||
}
|
||||
|
||||
private static String versioning(ObjectStorage.VersioningState state) {
|
||||
return switch (state) {
|
||||
case NEVER -> "Off";
|
||||
case ENABLED -> "Enabled";
|
||||
case SUSPENDED -> "Suspended";
|
||||
};
|
||||
}
|
||||
|
||||
private static String ownership(ObjectStorage.ObjectOwnership value) {
|
||||
return switch (value) {
|
||||
case BUCKET_OWNER_ENFORCED -> "Owner enforced";
|
||||
case BUCKET_OWNER_PREFERRED -> "Owner preferred";
|
||||
case OBJECT_WRITER -> "Object writer";
|
||||
};
|
||||
}
|
||||
|
||||
private static String yesNo(boolean value) {
|
||||
return value ? "On" : "Off";
|
||||
}
|
||||
|
||||
private static String time(long epochMillis) {
|
||||
return TIME.format(Instant.ofEpochMilli(epochMillis));
|
||||
}
|
||||
|
||||
private static String encoded(String value) {
|
||||
static String encoded(String value) {
|
||||
return URLEncoder.encode(value, StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
private static String required(Map<String, String> values, String name, int limit) {
|
||||
static String required(Map<String, String> values, String name, int limit) {
|
||||
String value = values.get(name);
|
||||
if (value == null || value.isEmpty() || value.length() > limit) throw invalidQuery();
|
||||
return value;
|
||||
}
|
||||
|
||||
private static Map<String, String> query(String raw, Set<String> allowed) {
|
||||
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<>();
|
||||
@@ -328,7 +321,7 @@ final class AdminBrowser {
|
||||
return values;
|
||||
}
|
||||
|
||||
private static StoreException invalidQuery() {
|
||||
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,211 @@
|
||||
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 {
|
||||
String after = null;
|
||||
do {
|
||||
if (job.cancel) break;
|
||||
ObjectStorage.ListPage page = list(job, after);
|
||||
int remaining = MAX_ITEMS - job.processed;
|
||||
for (ObjectStorage.ListedObject entry : page.objects()) {
|
||||
if (job.cancel || job.processed >= MAX_ITEMS) break;
|
||||
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++;
|
||||
String detail = error instanceof StoreException storeError ?
|
||||
storeError.code + ": " + storeError.getMessage() :
|
||||
error.getClass().getSimpleName();
|
||||
append(job, "error", entry.key(), detail.length() > 200 ?
|
||||
detail.substring(0, 200) : detail);
|
||||
}
|
||||
job.processed++;
|
||||
}
|
||||
if (job.processed >= MAX_ITEMS) {
|
||||
job.capped = page.truncated() || page.objects().size() > remaining;
|
||||
break;
|
||||
}
|
||||
if (!page.truncated()) break;
|
||||
if (page.nextKey() == null || page.nextKey().equals(after))
|
||||
throw new IOException("Storage listing did not advance");
|
||||
after = page.nextKey();
|
||||
} while (true);
|
||||
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 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,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,206 @@
|
||||
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();
|
||||
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>")
|
||||
.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(status.repair() == null || !status.repair().state().equals("completed") ||
|
||||
status.repair().report().scanned() > 0 && status.verifiedReplicas().isEmpty() ?
|
||||
"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>");
|
||||
ClusterStore.RepairStatus repair = status.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 {
|
||||
ClusterStore.RepairReport report = repair.report();
|
||||
boolean stale = repair.state().equals("running") &&
|
||||
System.currentTimeMillis() - repair.updatedAt() > 300_000;
|
||||
content.append("<p><strong>").append(stale ? "May be interrupted" :
|
||||
repair.state().equals("running") ? "Running" :
|
||||
repair.state().equals("failed") ? "Failed" : "Completed")
|
||||
.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>");
|
||||
}
|
||||
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>");
|
||||
return page(content.toString(), true);
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -115,12 +115,23 @@ final class BucketPolicy {
|
||||
}
|
||||
|
||||
private static boolean glob(String pattern, String text) {
|
||||
int p = 0, t = 0, star = -1, retry = 0;
|
||||
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;
|
||||
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();
|
||||
@@ -190,7 +201,10 @@ final class BucketPolicy {
|
||||
char c = input.charAt(index++);
|
||||
if (c == '"') return result.toString();
|
||||
if (c < 0x20) throw invalid();
|
||||
if (c != '\\') { result.append(c); continue; }
|
||||
if (c != '\\') {
|
||||
result.append(c);
|
||||
continue;
|
||||
}
|
||||
if (index == input.length()) throw invalid();
|
||||
char escape = input.charAt(index++);
|
||||
switch (escape) {
|
||||
@@ -217,7 +231,10 @@ final class BucketPolicy {
|
||||
}
|
||||
|
||||
private boolean take(char expected) {
|
||||
if (index < input.length() && input.charAt(index) == expected) { index++; return true; }
|
||||
if (index < input.length() && input.charAt(index) == expected) {
|
||||
index++;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
@@ -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,6 +62,7 @@ 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); }
|
||||
}
|
||||
|
||||
@@ -268,6 +273,60 @@ 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);
|
||||
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)");
|
||||
@@ -279,6 +338,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();
|
||||
@@ -295,7 +372,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); }
|
||||
}
|
||||
@@ -384,7 +461,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();
|
||||
@@ -393,6 +470,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");
|
||||
@@ -416,7 +494,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;
|
||||
@@ -424,6 +502,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'")) {
|
||||
@@ -763,8 +859,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);
|
||||
@@ -773,8 +868,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 {
|
||||
@@ -1400,104 +1498,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) {
|
||||
@@ -1505,13 +1508,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,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(); }
|
||||
}
|
||||
@@ -475,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);
|
||||
@@ -488,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); }
|
||||
}
|
||||
|
||||
@@ -554,10 +572,19 @@ 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 (expected != null) {
|
||||
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");
|
||||
}
|
||||
if (configured != null && configured.versioning() != VersioningState.NEVER)
|
||||
return installVersionedPending(destination, pending, metadata, createOnly,
|
||||
configured.versioning());
|
||||
|
||||
@@ -22,12 +22,23 @@ public final class Main {
|
||||
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);
|
||||
@@ -103,7 +114,37 @@ public final class Main {
|
||||
|
||||
void setAdminConsole(AdminConsole adminConsole) {
|
||||
this.adminConsole = adminConsole;
|
||||
if (adminConsole != null) adminConsole.setMetrics(metrics);
|
||||
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;
|
||||
refreshManagedCredentials();
|
||||
if (adminConsole != null)
|
||||
adminConsole.setManagedCredentials(managedCredentials, this::refreshManagedCredentials);
|
||||
}
|
||||
|
||||
private synchronized void refreshManagedCredentials() {
|
||||
ManagedCredentials managed = managedCredentials;
|
||||
if (managed == null) return;
|
||||
access.setManagedPolicies(managed.policies());
|
||||
authentication.setManagedIdentities(managed.identities());
|
||||
if (adminConsole != null) adminConsole.setIdentities(authentication.identities());
|
||||
}
|
||||
|
||||
void handle(HttpExchange exchange) throws IOException {
|
||||
@@ -113,6 +154,7 @@ public final class Main {
|
||||
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");
|
||||
try {
|
||||
@@ -132,8 +174,9 @@ public final class Main {
|
||||
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) {
|
||||
@@ -146,15 +189,20 @@ public final class Main {
|
||||
clientLimits.leave(client);
|
||||
long elapsed = System.nanoTime() - started;
|
||||
metrics.record(exchange.getResponseCode(), elapsed);
|
||||
if (dataStarted)
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void handleAdmin(HttpExchange exchange) throws IOException {
|
||||
boolean admitted = false;
|
||||
boolean streaming = false;
|
||||
try {
|
||||
String path = exchange.getRequestURI().getRawPath();
|
||||
if (adminConsole == null ||
|
||||
@@ -162,29 +210,31 @@ public final class Main {
|
||||
exchange.sendResponseHeaders(404, -1);
|
||||
return;
|
||||
}
|
||||
admitted = adminSlots.tryAcquire();
|
||||
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) {
|
||||
exchange.sendResponseHeaders(error.status, -1);
|
||||
if (exchange.getResponseCode() <= 0) exchange.sendResponseHeaders(error.status, -1);
|
||||
} catch (Exception error) {
|
||||
System.err.println("ObjectStore admin request failed: " + error.getClass().getSimpleName());
|
||||
exchange.sendResponseHeaders(500, -1);
|
||||
if (exchange.getResponseCode() <= 0) exchange.sendResponseHeaders(500, -1);
|
||||
} finally {
|
||||
exchange.close();
|
||||
if (admitted) adminSlots.release();
|
||||
if (admitted) (streaming ? adminStreams : adminSlots).release();
|
||||
}
|
||||
}
|
||||
|
||||
private void dispatch(HttpExchange exchange) throws IOException {
|
||||
private void dispatch(HttpExchange exchange, RequestContext context) 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());
|
||||
context.principal = verified.principal();
|
||||
String path = SigV4.decode(exchange.getRequestURI().getRawPath());
|
||||
Map<String, String> query = S3Request.query(verified.applicationQuery());
|
||||
if (path.equals(CAPABILITIES_PATH)) {
|
||||
@@ -209,18 +259,40 @@ public final class Main {
|
||||
int slash = path.indexOf('/', 1);
|
||||
String requestedBucket = hostBucket == null ?
|
||||
(slash < 0 ? path.substring(1) : path.substring(1, slash)) : hostBucket;
|
||||
context.bucket = requestedBucket;
|
||||
context.operation = (hostBucket != null ? path.equals("/") : slash < 0 ||
|
||||
slash == path.length() - 1) ? "Bucket " + exchange.getRequestMethod() :
|
||||
"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);
|
||||
ManagedCredentials managed = managedScope(verified.principal());
|
||||
if (managed != null)
|
||||
managed.checkBucket(verified.principal(), requestedBucket, exchange.getRequestMethod(), query);
|
||||
else keyScopes.checkBucket(verified.principal(), requestedBucket, exchange.getRequestMethod(), query);
|
||||
bucketHandler.handleBucket(exchange, query, verified.payload(), requestedBucket, verified.principal());
|
||||
} else {
|
||||
store.bucket(requestedBucket);
|
||||
String key = hostBucket == null ? path.substring(slash + 1) : path.substring(1);
|
||||
keyScopes.checkObject(verified.principal(), requestedBucket, key,
|
||||
ManagedCredentials managed = managedScope(verified.principal());
|
||||
if (managed != null)
|
||||
managed.checkObject(verified.principal(), requestedBucket, key,
|
||||
exchange.getRequestMethod(), query, exchange.getRequestHeaders());
|
||||
else keyScopes.checkObject(verified.principal(), requestedBucket, key,
|
||||
exchange.getRequestMethod(), query, exchange.getRequestHeaders());
|
||||
objectHandler.handleObject(exchange, key,
|
||||
query, verified, 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,284 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import com.sun.net.httpserver.Headers;
|
||||
import java.io.IOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.channels.FileChannel;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
import java.security.GeneralSecurityException;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.HashMap;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.spec.GCMParameterSpec;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
|
||||
final class ManagedCredentials {
|
||||
record Key(String id, String secret, String bucket, String prefix,
|
||||
Set<String> actions, boolean enabled) { }
|
||||
|
||||
private static final byte[] MAGIC = { 'O', 'S', 'K', '1' };
|
||||
private static final SecureRandom RANDOM = new SecureRandom();
|
||||
private static final Set<String> ACTIONS = Set.of("read", "write", "list");
|
||||
private final Path path;
|
||||
private final SecretKeySpec master;
|
||||
private final Set<String> reserved;
|
||||
private volatile Map<String, Key> keys;
|
||||
|
||||
private ManagedCredentials(Path path, byte[] master, Set<String> reserved) throws IOException {
|
||||
this.path = path;
|
||||
this.master = new SecretKeySpec(master, "AES");
|
||||
this.reserved = Set.copyOf(reserved);
|
||||
java.util.Arrays.fill(master, (byte) 0);
|
||||
this.keys = load();
|
||||
}
|
||||
|
||||
static ManagedCredentials fromEnvironment(Map<String, String> env, ObjectStorage store,
|
||||
Set<String> reserved) throws IOException {
|
||||
String configured = env.get("S3_MANAGED_KEYS_MASTER_FILE");
|
||||
if (configured == null || configured.isBlank()) return null;
|
||||
if (!(store instanceof DiskStore))
|
||||
throw new IllegalArgumentException("Managed credentials require disk mode");
|
||||
byte[] master;
|
||||
try {
|
||||
master = HexFormat.of().parseHex(Files.readString(Path.of(configured)).trim());
|
||||
} 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");
|
||||
return new ManagedCredentials(Path.of(env.getOrDefault("DATA_DIR", "/data"))
|
||||
.resolve("managed-credentials.bin"), master, reserved);
|
||||
}
|
||||
|
||||
List<Key> list() { return keys.values().stream().sorted(java.util.Comparator.comparing(Key::id)).toList(); }
|
||||
boolean contains(String principal) { return principal != null && keys.containsKey(principal); }
|
||||
|
||||
Map<String, String> identities() {
|
||||
Map<String, String> active = new HashMap<>();
|
||||
keys.values().stream().filter(Key::enabled).forEach(key -> active.put(key.id(), key.secret()));
|
||||
return Map.copyOf(active);
|
||||
}
|
||||
|
||||
Map<String, BucketPolicy> policies() {
|
||||
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 {
|
||||
if (keys.size() >= 64) invalid("Too many managed access keys");
|
||||
validateScope(bucket, prefix, actions);
|
||||
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);
|
||||
Map<String, Key> updated = new HashMap<>(keys);
|
||||
updated.put(id, key);
|
||||
persist(updated);
|
||||
keys = Map.copyOf(updated);
|
||||
return key;
|
||||
}
|
||||
|
||||
synchronized void update(String id, String bucket, String prefix, Set<String> actions) throws IOException {
|
||||
Key old = key(id);
|
||||
validateScope(bucket, prefix, actions);
|
||||
Map<String, Key> updated = new HashMap<>(keys);
|
||||
updated.put(id, new Key(id, old.secret(), bucket, prefix, Set.copyOf(actions), old.enabled()));
|
||||
persist(updated);
|
||||
keys = Map.copyOf(updated);
|
||||
}
|
||||
|
||||
private 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 {
|
||||
Key old = key(id);
|
||||
Map<String, Key> updated = new HashMap<>(keys);
|
||||
updated.put(id, new Key(id, old.secret(), old.bucket(), old.prefix(), old.actions(), enabled));
|
||||
persist(updated);
|
||||
keys = Map.copyOf(updated);
|
||||
}
|
||||
|
||||
synchronized void remove(String id) throws IOException {
|
||||
key(id);
|
||||
Map<String, Key> updated = new HashMap<>(keys);
|
||||
updated.remove(id);
|
||||
persist(updated);
|
||||
keys = Map.copyOf(updated);
|
||||
}
|
||||
|
||||
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) {
|
||||
Key key = keys.get(id);
|
||||
if (key == null) throw new StoreException(404, "NoSuchKey", "Access key not found");
|
||||
return key;
|
||||
}
|
||||
|
||||
private Map<String, Key> load() throws IOException {
|
||||
if (!Files.exists(path)) return Map.of();
|
||||
byte[] bytes = Files.readAllBytes(path);
|
||||
if (bytes.length < MAGIC.length + 12 + 16 || bytes.length > 65536 ||
|
||||
!java.util.Arrays.equals(MAGIC, java.util.Arrays.copyOf(bytes, MAGIC.length)))
|
||||
throw new IOException("Invalid managed credential store");
|
||||
byte[] nonce = java.util.Arrays.copyOfRange(bytes, MAGIC.length, MAGIC.length + 12);
|
||||
byte[] plain;
|
||||
try {
|
||||
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
|
||||
cipher.init(Cipher.DECRYPT_MODE, master, new GCMParameterSpec(128, nonce));
|
||||
cipher.updateAAD(MAGIC);
|
||||
plain = cipher.doFinal(bytes, MAGIC.length + 12, bytes.length - MAGIC.length - 12);
|
||||
} catch (GeneralSecurityException error) {
|
||||
throw new IOException("Managed credential store could not be decrypted", error);
|
||||
}
|
||||
Map<String, Key> loaded = new HashMap<>();
|
||||
for (String line : new String(plain, StandardCharsets.UTF_8).split("\n")) {
|
||||
if (line.isEmpty()) continue;
|
||||
String[] fields = line.split("\t", -1);
|
||||
if (fields.length != 6 || !fields[0].matches("[A-Za-z0-9]{16,128}") ||
|
||||
fields[1].length() < 32 || !fields[2].matches("[a-z0-9][a-z0-9-]{1,61}[a-z0-9]") ||
|
||||
!fields[3].matches("[A-Za-z0-9/_-]*") || fields[3].length() > 256 ||
|
||||
!Set.of("true", "false").contains(fields[5]) || reserved.contains(fields[0]))
|
||||
throw new IOException("Invalid managed credential entry");
|
||||
Set<String> actions;
|
||||
try { actions = Set.of(fields[4].split(",")); }
|
||||
catch (IllegalArgumentException error) { throw new IOException("Invalid managed credential entry", error); }
|
||||
if (actions.isEmpty() || !ACTIONS.containsAll(actions) || loaded.size() >= 64 ||
|
||||
loaded.putIfAbsent(fields[0], new Key(fields[0], fields[1], fields[2], fields[3],
|
||||
actions, Boolean.parseBoolean(fields[5]))) != null)
|
||||
throw new IOException("Invalid managed credential entry");
|
||||
}
|
||||
java.util.Arrays.fill(plain, (byte) 0);
|
||||
return Map.copyOf(loaded);
|
||||
}
|
||||
|
||||
private void persist(Map<String, Key> updated) throws IOException {
|
||||
StringBuilder contents = new StringBuilder();
|
||||
updated.values().stream().sorted(java.util.Comparator.comparing(Key::id)).forEach(key ->
|
||||
contents.append(key.id()).append('\t').append(key.secret()).append('\t')
|
||||
.append(key.bucket()).append('\t').append(key.prefix()).append('\t')
|
||||
.append(String.join(",", key.actions().stream().sorted().toList())).append('\t')
|
||||
.append(key.enabled()).append('\n'));
|
||||
byte[] nonce = randomToken();
|
||||
byte[] encrypted;
|
||||
try {
|
||||
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
|
||||
cipher.init(Cipher.ENCRYPT_MODE, master, new GCMParameterSpec(128, nonce));
|
||||
cipher.updateAAD(MAGIC);
|
||||
encrypted = cipher.doFinal(contents.toString().getBytes(StandardCharsets.UTF_8));
|
||||
} catch (GeneralSecurityException error) {
|
||||
throw new IOException("Could not encrypt managed credentials", error);
|
||||
}
|
||||
Files.createDirectories(path.getParent());
|
||||
Path temporary = Files.createTempFile(path.getParent(), "managed-credentials-", ".tmp");
|
||||
try {
|
||||
Files.setPosixFilePermissions(temporary, java.nio.file.attribute.PosixFilePermissions.fromString("rw-------"));
|
||||
try (FileChannel channel = FileChannel.open(temporary, StandardOpenOption.WRITE)) {
|
||||
writeAll(channel, MAGIC);
|
||||
writeAll(channel, nonce);
|
||||
writeAll(channel, encrypted);
|
||||
channel.force(true);
|
||||
}
|
||||
Files.move(temporary, path, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
|
||||
try (FileChannel directory = FileChannel.open(path.getParent(), StandardOpenOption.READ)) {
|
||||
directory.force(true);
|
||||
}
|
||||
} finally {
|
||||
Files.deleteIfExists(temporary);
|
||||
}
|
||||
}
|
||||
|
||||
private static void writeAll(FileChannel channel, byte[] bytes) throws IOException {
|
||||
ByteBuffer buffer = ByteBuffer.wrap(bytes);
|
||||
while (buffer.hasRemaining()) channel.write(buffer);
|
||||
}
|
||||
|
||||
private static byte[] randomToken() {
|
||||
byte[] nonce = new byte[12];
|
||||
RANDOM.nextBytes(nonce);
|
||||
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,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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.net.http.HttpTimeoutException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionStage;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.Flow;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
|
||||
final class NodeHttp {
|
||||
private NodeHttp() {}
|
||||
|
||||
static HttpResponse<byte[]> bytes(HttpClient client, HttpRequest request, int maximum) throws IOException {
|
||||
if (maximum < 0) throw new IllegalArgumentException("Invalid response size limit");
|
||||
return send(client, request, HttpResponse.BodySubscribers.ofByteArray(), maximum);
|
||||
}
|
||||
|
||||
static HttpResponse<Void> discard(HttpClient client, HttpRequest request) throws IOException {
|
||||
return send(client, request, HttpResponse.BodySubscribers.discarding(), Long.MAX_VALUE);
|
||||
}
|
||||
|
||||
private static <T> HttpResponse<T> send(HttpClient client, HttpRequest request,
|
||||
HttpResponse.BodySubscriber<T> delegate, long maximum) throws IOException {
|
||||
long timeout = request.timeout().orElseThrow().toNanos();
|
||||
long started = System.nanoTime();
|
||||
ResponseBody<T> body = new ResponseBody<>(delegate, maximum);
|
||||
CompletableFuture<HttpResponse<T>> response = client.sendAsync(request, ignored -> body);
|
||||
boolean completed = false;
|
||||
try {
|
||||
HttpResponse<T> result = response.get(Math.max(1, timeout - (System.nanoTime() - started)),
|
||||
TimeUnit.NANOSECONDS);
|
||||
completed = true;
|
||||
return result;
|
||||
} catch (TimeoutException error) {
|
||||
throw new HttpTimeoutException("Storage node response timed out");
|
||||
} catch (InterruptedException error) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new IOException("Interrupted during storage node request", error);
|
||||
} catch (ExecutionException error) {
|
||||
if (error.getCause() instanceof IOException failure) throw failure;
|
||||
throw new IOException("Storage node request failed", error.getCause());
|
||||
} finally {
|
||||
if (!completed) {
|
||||
body.abort(new IOException("Storage node request cancelled"));
|
||||
response.cancel(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static final class ResponseBody<T> implements HttpResponse.BodySubscriber<T> {
|
||||
private final HttpResponse.BodySubscriber<T> delegate;
|
||||
private Flow.Subscription subscription;
|
||||
private long remaining;
|
||||
private boolean finished;
|
||||
|
||||
ResponseBody(HttpResponse.BodySubscriber<T> delegate, long maximum) {
|
||||
this.delegate = delegate;
|
||||
remaining = maximum;
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletionStage<T> getBody() {
|
||||
return delegate.getBody();
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized void onSubscribe(Flow.Subscription incoming) {
|
||||
if (finished || subscription != null) {
|
||||
incoming.cancel();
|
||||
return;
|
||||
}
|
||||
subscription = incoming;
|
||||
delegate.onSubscribe(incoming);
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized void onNext(List<ByteBuffer> buffers) {
|
||||
if (finished) return;
|
||||
for (ByteBuffer buffer : buffers) {
|
||||
if (buffer.remaining() > remaining) {
|
||||
abort(new IOException("Storage node response is too large"));
|
||||
return;
|
||||
}
|
||||
remaining -= buffer.remaining();
|
||||
}
|
||||
delegate.onNext(buffers);
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized void onError(Throwable error) {
|
||||
if (finished) return;
|
||||
finished = true;
|
||||
delegate.onError(error);
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized void onComplete() {
|
||||
if (finished) return;
|
||||
finished = true;
|
||||
delegate.onComplete();
|
||||
}
|
||||
|
||||
synchronized void abort(IOException error) {
|
||||
if (finished) return;
|
||||
finished = true;
|
||||
if (subscription != null) subscription.cancel();
|
||||
delegate.onError(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -92,6 +92,10 @@ interface ObjectStorage extends AutoCloseable {
|
||||
String checksum, boolean createOnly, String contentType) throws IOException {
|
||||
return put(bucket, key, input, length, expectedHash, checksum, createOnly, contentType, Map.of(), Map.of());
|
||||
}
|
||||
default Metadata replaceVersion(String bucket, String key, byte[] content, Metadata expected)
|
||||
throws IOException {
|
||||
throw new StoreException(501, "NotImplemented", "Conditional object editing is unavailable");
|
||||
}
|
||||
OpenObject open(String bucket, String key) throws IOException;
|
||||
default OpenObject open(String bucket, String key, String versionId) throws IOException {
|
||||
if (versionId == null) return open(bucket, key);
|
||||
@@ -126,6 +130,9 @@ interface ObjectStorage extends AutoCloseable {
|
||||
Bucket bucket(String bucket) throws IOException;
|
||||
List<Bucket> buckets() throws IOException;
|
||||
void createBucket(String bucket) throws IOException;
|
||||
default void renameBucket(String bucket, String newName) throws IOException {
|
||||
throw new StoreException(501, "NotImplemented", "Bucket rename is unavailable");
|
||||
}
|
||||
void deleteBucket(String bucket) throws IOException;
|
||||
void setBucketAcl(String bucket, Map<String, String> acl) throws IOException;
|
||||
void setBucketOwnership(String bucket, ObjectOwnership ownership) throws IOException;
|
||||
|
||||
@@ -28,6 +28,7 @@ final class ObjectStoreServer {
|
||||
String mode = env.getOrDefault("STORE_MODE", "disk");
|
||||
ObjectStorage store;
|
||||
MultipartStorage multipart;
|
||||
DiskStore disk = null;
|
||||
if (mode.equals("cluster")) {
|
||||
if (!"true".equals(env.get("CLUSTER_LOCAL_DEV")))
|
||||
throw new IllegalArgumentException("Cluster mode is local development only; set CLUSTER_LOCAL_DEV=true");
|
||||
@@ -39,9 +40,10 @@ final class ObjectStoreServer {
|
||||
maxObject, maxTotal, "true".equals(env.get("CLUSTER_TEST_NODE_DOMAINS")));
|
||||
multipart = (ClusterStore) store;
|
||||
} else if (mode.equals("disk")) {
|
||||
DiskStore disk = new DiskStore(Path.of(env.getOrDefault("DATA_DIR", "/data")), maxObject, maxTotal);
|
||||
store = disk;
|
||||
multipart = new MultipartStore(disk);
|
||||
disk = new DiskStore(Path.of(env.getOrDefault("DATA_DIR", "/data")), maxObject, maxTotal);
|
||||
DiskBucketNames names = new DiskBucketNames(disk, new MultipartStore(disk));
|
||||
store = names;
|
||||
multipart = names;
|
||||
} else throw new IllegalArgumentException("Invalid STORE_MODE");
|
||||
Map<String, String> identities = identities(env, access, secret);
|
||||
var sessions = SessionCredentials.fromEnvironment(env, identities.keySet());
|
||||
@@ -55,7 +57,14 @@ final class ObjectStoreServer {
|
||||
new RequestMetrics(env.get("METRICS_BEARER_TOKEN")),
|
||||
IdentityPolicies.fromEnvironment(env, access, allIdentities),
|
||||
publicEndpoint(env));
|
||||
BucketActivity bucketActivity = "true".equals(env.get("ADMIN_UI_ENABLED")) ?
|
||||
new BucketActivity(Path.of(env.getOrDefault("ADMIN_UI_STATE_DIR",
|
||||
env.getOrDefault("DATA_DIR", "/data")), "bucket-activity.tsv")) : null;
|
||||
if (bucketActivity != null) app.setBucketActivity(bucketActivity);
|
||||
app.setManagedCredentials(ManagedCredentials.fromEnvironment(env,
|
||||
disk == null ? store : disk, allIdentities));
|
||||
AdminConsole adminConsole = AdminConsole.fromEnvironment(env, store);
|
||||
if (adminConsole != null) adminConsole.setDiskStore(disk);
|
||||
app.setAdminConsole(adminConsole);
|
||||
int port = Integer.parseInt(env.getOrDefault("PORT", "9000"));
|
||||
int adminPort = adminConsole == null ? 0 : positiveInt(env, "ADMIN_UI_PORT", 9001, 65535);
|
||||
@@ -77,12 +86,13 @@ final class ObjectStoreServer {
|
||||
server.stop(5);
|
||||
if (adminServer != null) adminServer.stop(5);
|
||||
executor.close();
|
||||
if (bucketActivity != null) bucketActivity.close();
|
||||
try { store.close(); }
|
||||
catch (IOException error) { System.err.println("Could not release ObjectStore data lock: " + error.getMessage()); }
|
||||
}));
|
||||
server.start();
|
||||
if (adminServer != null) adminServer.start();
|
||||
if (store instanceof DiskStore disk) printStartup(disk, multipart, bucket, region, port);
|
||||
if (disk != null) printStartup(disk, multipart, bucket, region, port);
|
||||
else System.out.println("ObjectStore local cluster prototype v" + Version.VALUE + " listening on :" + port);
|
||||
if (adminServer != null) System.out.println("ObjectStore admin listening on :" + adminPort);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import java.util.concurrent.atomic.AtomicReferenceArray;
|
||||
import java.util.concurrent.atomic.LongAdder;
|
||||
|
||||
final class RequestDiagnostics {
|
||||
private static final long MINUTE_MILLIS = 60_000;
|
||||
private static final long[] LATENCY_BOUNDS_MS = {1, 2, 5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000};
|
||||
private final AtomicReferenceArray<Window> windows = new AtomicReferenceArray<>(5);
|
||||
private final AtomicReferenceArray<Failure> failures = new AtomicReferenceArray<>(64);
|
||||
private final AtomicLong failureSequence = new AtomicLong();
|
||||
private final ConcurrentHashMap<String, KeyCounters> keys = new ConcurrentHashMap<>();
|
||||
|
||||
record Failure(long sequence, long timeMillis, String requestId, String operation, String bucket,
|
||||
int status) { }
|
||||
record Snapshot(long requests, long clientErrors, long serverErrors, long p50Millis,
|
||||
long p95Millis, long p99Millis, List<Failure> recentFailures) { }
|
||||
record KeyActivity(String principal, long requests, long failures, long lastSeenMillis) { }
|
||||
|
||||
private static final class KeyCounters {
|
||||
final LongAdder requests = new LongAdder();
|
||||
final LongAdder failures = new LongAdder();
|
||||
final AtomicLong lastSeen = new AtomicLong();
|
||||
}
|
||||
|
||||
private static final class Window {
|
||||
final long minute;
|
||||
final LongAdder requests = new LongAdder();
|
||||
final LongAdder clientErrors = new LongAdder();
|
||||
final LongAdder serverErrors = new LongAdder();
|
||||
final LongAdder[] latency = new LongAdder[LATENCY_BOUNDS_MS.length + 1];
|
||||
|
||||
Window(long minute) {
|
||||
this.minute = minute;
|
||||
for (int i = 0; i < latency.length; i++) latency[i] = new LongAdder();
|
||||
}
|
||||
}
|
||||
|
||||
void record(String requestId, String operation, String bucket, int status, long elapsedNanos) {
|
||||
record(requestId, operation, bucket, status, elapsedNanos, null);
|
||||
}
|
||||
|
||||
void record(String requestId, String operation, String bucket, int status, long elapsedNanos,
|
||||
String principal) {
|
||||
if (operation == null) operation = "Service";
|
||||
long now = System.currentTimeMillis();
|
||||
long minute = now / MINUTE_MILLIS;
|
||||
int slot = (int) Math.floorMod(minute, windows.length());
|
||||
Window window;
|
||||
do {
|
||||
window = windows.get(slot);
|
||||
if (window != null && window.minute == minute) break;
|
||||
Window fresh = new Window(minute);
|
||||
if (windows.compareAndSet(slot, window, fresh)) {
|
||||
window = fresh;
|
||||
break;
|
||||
}
|
||||
} while (true);
|
||||
window.requests.increment();
|
||||
if (status >= 500) window.serverErrors.increment();
|
||||
else if (status >= 400) window.clientErrors.increment();
|
||||
long millis = Math.max(0, elapsedNanos / 1_000_000);
|
||||
int latencySlot = 0;
|
||||
while (latencySlot < LATENCY_BOUNDS_MS.length && millis > LATENCY_BOUNDS_MS[latencySlot])
|
||||
latencySlot++;
|
||||
window.latency[latencySlot].increment();
|
||||
if (principal != null && principal.length() <= 128) {
|
||||
KeyCounters counters = keys.get(principal);
|
||||
if (counters == null && keys.size() < 128)
|
||||
counters = keys.computeIfAbsent(principal, ignored -> new KeyCounters());
|
||||
if (counters != null) {
|
||||
counters.requests.increment();
|
||||
if (status >= 400) counters.failures.increment();
|
||||
counters.lastSeen.set(now);
|
||||
}
|
||||
}
|
||||
if (status >= 400) {
|
||||
if (operation.length() > 32) operation = "Other";
|
||||
if (bucket == null || bucket.length() > 63 || !bucket.matches("[a-zA-Z0-9.-]+")) bucket = "—";
|
||||
long sequence = failureSequence.getAndIncrement();
|
||||
failures.set((int) (sequence % failures.length()),
|
||||
new Failure(sequence, now, requestId, operation, bucket, status));
|
||||
}
|
||||
}
|
||||
|
||||
List<KeyActivity> keyActivity() {
|
||||
return keys.entrySet().stream().map(entry -> new KeyActivity(entry.getKey(),
|
||||
entry.getValue().requests.sum(), entry.getValue().failures.sum(),
|
||||
entry.getValue().lastSeen.get()))
|
||||
.sorted((a, b) -> Long.compare(b.lastSeenMillis(), a.lastSeenMillis()))
|
||||
.limit(100).toList();
|
||||
}
|
||||
|
||||
Snapshot snapshot() {
|
||||
long minute = System.currentTimeMillis() / MINUTE_MILLIS;
|
||||
long requests = 0, clientErrors = 0, serverErrors = 0;
|
||||
long[] histogram = new long[LATENCY_BOUNDS_MS.length + 1];
|
||||
for (int slot = 0; slot < windows.length(); slot++) {
|
||||
Window window = windows.get(slot);
|
||||
if (window == null || window.minute > minute || window.minute <= minute - windows.length()) continue;
|
||||
requests += window.requests.sum();
|
||||
clientErrors += window.clientErrors.sum();
|
||||
serverErrors += window.serverErrors.sum();
|
||||
for (int i = 0; i < histogram.length; i++) histogram[i] += window.latency[i].sum();
|
||||
}
|
||||
List<Failure> recent = new ArrayList<>();
|
||||
long newest = failureSequence.get();
|
||||
for (long sequence = newest - 1; sequence >= Math.max(0, newest - failures.length()); sequence--) {
|
||||
Failure failure = failures.get((int) (sequence % failures.length()));
|
||||
if (failure != null && failure.sequence() == sequence &&
|
||||
failure.timeMillis() >= (minute - windows.length() + 1) * MINUTE_MILLIS &&
|
||||
failure.timeMillis() <= System.currentTimeMillis()) recent.add(failure);
|
||||
}
|
||||
return new Snapshot(requests, clientErrors, serverErrors,
|
||||
percentile(histogram, requests, 50), percentile(histogram, requests, 95),
|
||||
percentile(histogram, requests, 99), List.copyOf(recent));
|
||||
}
|
||||
|
||||
private static long percentile(long[] histogram, long count, int percent) {
|
||||
if (count == 0) return 0;
|
||||
long target = (count * percent + 99) / 100;
|
||||
long seen = 0;
|
||||
for (int i = 0; i < histogram.length; i++) {
|
||||
seen += histogram[i];
|
||||
if (seen >= target) return i == LATENCY_BOUNDS_MS.length ? -1 : LATENCY_BOUNDS_MS[i];
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
@@ -4,9 +4,11 @@ import java.io.IOException;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
final class S3Access {
|
||||
record Decision(boolean allowed, String reason) { }
|
||||
private final ObjectStorage store;
|
||||
private final String owner;
|
||||
private final java.util.Map<String, BucketPolicy> identityPolicies;
|
||||
private final java.util.Map<String, BucketPolicy> configuredIdentityPolicies;
|
||||
private volatile java.util.Map<String, BucketPolicy> identityPolicies;
|
||||
private final ConcurrentHashMap<String, CachedPolicy> policies = new ConcurrentHashMap<>();
|
||||
private record CachedPolicy(String source, BucketPolicy parsed) { }
|
||||
|
||||
@@ -17,7 +19,16 @@ final class S3Access {
|
||||
S3Access(ObjectStorage store, String owner, java.util.Map<String, BucketPolicy> identityPolicies) {
|
||||
this.store = store;
|
||||
this.owner = owner;
|
||||
this.identityPolicies = java.util.Map.copyOf(identityPolicies);
|
||||
this.configuredIdentityPolicies = java.util.Map.copyOf(identityPolicies);
|
||||
this.identityPolicies = configuredIdentityPolicies;
|
||||
}
|
||||
|
||||
synchronized void setManagedPolicies(java.util.Map<String, BucketPolicy> managed) {
|
||||
var combined = new java.util.HashMap<>(configuredIdentityPolicies);
|
||||
for (var entry : managed.entrySet())
|
||||
if (combined.putIfAbsent(entry.getKey(), entry.getValue()) != null)
|
||||
throw new IllegalArgumentException("Managed policy conflicts with a configured identity");
|
||||
identityPolicies = java.util.Map.copyOf(combined);
|
||||
}
|
||||
|
||||
String owner() {
|
||||
@@ -46,19 +57,43 @@ final class S3Access {
|
||||
require(store.bucket(bucket), metadata.acl(), principal, permission, action, key);
|
||||
}
|
||||
|
||||
Decision inspectBucket(String bucket, String principal) throws IOException {
|
||||
ObjectStorage.Bucket current = store.bucket(bucket);
|
||||
return decide(current, current.acl(), principal, Acl.READ, "s3:ListBucket", null);
|
||||
}
|
||||
|
||||
Decision inspectWrite(String bucket, String key, String principal, String action) throws IOException {
|
||||
ObjectStorage.Bucket current = store.bucket(bucket);
|
||||
return decide(current, current.acl(), principal, Acl.WRITE, action, key);
|
||||
}
|
||||
|
||||
Decision inspectObject(String bucket, String key, ObjectStorage.Metadata metadata,
|
||||
String principal) throws IOException {
|
||||
return decide(store.bucket(bucket), metadata.acl(), principal, Acl.READ, "s3:GetObject", key);
|
||||
}
|
||||
|
||||
private void require(ObjectStorage.Bucket bucket, java.util.Map<String, String> acl,
|
||||
String principal, int permission, String action, String key) {
|
||||
if (!decide(bucket, acl, principal, permission, action, key).allowed())
|
||||
throw new StoreException(403, "AccessDenied", "Access denied");
|
||||
}
|
||||
|
||||
private Decision decide(ObjectStorage.Bucket bucket, java.util.Map<String, String> acl,
|
||||
String principal, int permission, String action, String key) {
|
||||
String resource = "arn:aws:s3:::" + bucket.name() + (key == null ? "" : "/" + key);
|
||||
BucketPolicy policy = policy(bucket);
|
||||
int decision = policy.decide(principal, action, resource);
|
||||
int identityDecision = principal == null ? 0 :
|
||||
identityPolicies.getOrDefault(principal, BucketPolicy.empty()).decide(principal, action, resource);
|
||||
if (decision < 0 || identityDecision < 0 ||
|
||||
!BucketSecurity.allowsAcl(bucket, acl, principal, owner, permission) &&
|
||||
identityDecision <= 0 &&
|
||||
!(decision > 0 && (principal != null || !bucket.publicAccessBlock().restrictPublicBuckets() ||
|
||||
!policy.publicAllow())))
|
||||
throw new StoreException(403, "AccessDenied", "Access denied");
|
||||
if (decision < 0) return new Decision(false, "Explicit bucket policy deny");
|
||||
if (identityDecision < 0) return new Decision(false, "Explicit identity policy deny");
|
||||
if (BucketSecurity.allowsAcl(bucket, acl, principal, owner, permission))
|
||||
return new Decision(true, "Owner or ACL grants this action");
|
||||
if (identityDecision > 0) return new Decision(true, "Identity policy allows this action");
|
||||
if (decision > 0 && (principal != null || !bucket.publicAccessBlock().restrictPublicBuckets() ||
|
||||
!policy.publicAllow()))
|
||||
return new Decision(true, "Bucket policy allows this action");
|
||||
return new Decision(false, "No ACL or policy grants this action");
|
||||
}
|
||||
|
||||
private BucketPolicy policy(ObjectStorage.Bucket bucket) {
|
||||
|
||||
@@ -21,7 +21,7 @@ final class SchemaMigrator {
|
||||
result.next();
|
||||
version = result.getInt(1);
|
||||
}
|
||||
if (version > 11) throw new IOException("Metadata schema is newer than this ObjectStore build");
|
||||
if (version > 14) throw new IOException("Metadata schema is newer than this ObjectStore build");
|
||||
if (version < 1) {
|
||||
statement.execute("CREATE TABLE IF NOT EXISTS cluster_usage (bucket text PRIMARY KEY, used_bytes bigint NOT NULL CHECK (used_bytes >= 0))");
|
||||
statement.execute("CREATE TABLE IF NOT EXISTS cluster_objects (bucket text NOT NULL, object_key text COLLATE \"C\" NOT NULL, generation uuid NOT NULL, length bigint NOT NULL, modified bigint NOT NULL, etag text NOT NULL, sha256 bytea NOT NULL, content_type text NOT NULL, PRIMARY KEY (bucket, object_key))");
|
||||
@@ -109,11 +109,36 @@ final class SchemaMigrator {
|
||||
statement.execute("ALTER TABLE cluster_buckets ADD COLUMN bucket_policy text");
|
||||
statement.execute("INSERT INTO cluster_schema_migrations VALUES (11)");
|
||||
}
|
||||
if (version < 12) {
|
||||
statement.execute("CREATE TABLE cluster_repair_status (singleton integer PRIMARY KEY " +
|
||||
"CHECK (singleton=1), finished_at bigint NOT NULL, scanned integer NOT NULL, " +
|
||||
"restored integer NOT NULL, rebalanced integer NOT NULL, under_replicated integer NOT NULL, " +
|
||||
"unrecoverable integer NOT NULL)");
|
||||
statement.execute("INSERT INTO cluster_schema_migrations VALUES (12)");
|
||||
}
|
||||
if (version < 13) {
|
||||
statement.execute("ALTER TABLE cluster_repair_status ADD COLUMN started_at bigint NOT NULL DEFAULT 0");
|
||||
statement.execute("ALTER TABLE cluster_repair_status ADD COLUMN updated_at bigint NOT NULL DEFAULT 0");
|
||||
statement.execute("ALTER TABLE cluster_repair_status ADD COLUMN state text NOT NULL DEFAULT 'completed' " +
|
||||
"CHECK (state IN ('running','completed','failed'))");
|
||||
statement.execute("INSERT INTO cluster_schema_migrations VALUES (13)");
|
||||
}
|
||||
if (version < 14) {
|
||||
statement.execute("CREATE TABLE cluster_repair_node_counts (node_id uuid PRIMARY KEY, " +
|
||||
"verified_replicas bigint NOT NULL CHECK (verified_replicas >= 0), " +
|
||||
"finished_at bigint NOT NULL)");
|
||||
statement.execute("INSERT INTO cluster_schema_migrations VALUES (14)");
|
||||
}
|
||||
statement.execute("INSERT INTO cluster_format SELECT 1, CASE WHEN EXISTS (SELECT 1 FROM cluster_segments WHERE replica_ids IS NULL) THEN 1 ELSE 2 END WHERE NOT EXISTS (SELECT 1 FROM cluster_format)");
|
||||
}
|
||||
try (PreparedStatement insert = connection.prepareStatement("INSERT INTO cluster_usage VALUES (?, 0) ON CONFLICT DO NOTHING")) {
|
||||
insert.setString(1, bucket);
|
||||
insert.executeUpdate();
|
||||
try (PreparedStatement check = connection.prepareStatement(
|
||||
"SELECT count(*), count(*) FILTER (WHERE name=?) FROM cluster_buckets")) {
|
||||
check.setString(1, bucket);
|
||||
try (ResultSet result = check.executeQuery()) {
|
||||
result.next();
|
||||
if (result.getLong(1) > 0 && result.getLong(2) == 0)
|
||||
throw new IOException("Configured S3_BUCKET does not exist; update it or create the bucket explicitly");
|
||||
}
|
||||
}
|
||||
try (PreparedStatement insert = connection.prepareStatement(
|
||||
"INSERT INTO cluster_buckets (name, created_at, object_ownership, block_public_acls, " +
|
||||
@@ -123,6 +148,10 @@ final class SchemaMigrator {
|
||||
insert.setLong(2, System.currentTimeMillis());
|
||||
insert.executeUpdate();
|
||||
}
|
||||
try (PreparedStatement insert = connection.prepareStatement("INSERT INTO cluster_usage VALUES (?, 0) ON CONFLICT DO NOTHING")) {
|
||||
insert.setString(1, bucket);
|
||||
insert.executeUpdate();
|
||||
}
|
||||
int format;
|
||||
try (Statement statement = connection.createStatement();
|
||||
ResultSet result = statement.executeQuery("SELECT version FROM cluster_format WHERE singleton=1")) {
|
||||
|
||||
@@ -29,7 +29,8 @@ final class SigV4 {
|
||||
}
|
||||
private static final DateTimeFormatter DATE = DateTimeFormatter.ofPattern("uuuuMMdd'T'HHmmss'Z'").withZone(ZoneOffset.UTC);
|
||||
private static final Pattern HEX = Pattern.compile("[0-9a-f]{64}");
|
||||
private final Map<String, String> identities;
|
||||
private final Map<String, String> configuredIdentities;
|
||||
private volatile Map<String, String> identities;
|
||||
private final Map<String, SessionCredentials.Session> sessions;
|
||||
private final String root;
|
||||
private final String region;
|
||||
@@ -45,7 +46,8 @@ final class SigV4 {
|
||||
|
||||
SigV4(Map<String, String> identities, Map<String, SessionCredentials.Session> sessions,
|
||||
String root, String region, Clock clock) {
|
||||
this.identities = Map.copyOf(identities);
|
||||
this.configuredIdentities = Map.copyOf(identities);
|
||||
this.identities = configuredIdentities;
|
||||
this.sessions = Map.copyOf(sessions);
|
||||
if (!this.identities.containsKey(root)) throw new IllegalArgumentException("Missing root identity");
|
||||
if (this.sessions.keySet().stream().anyMatch(this.identities::containsKey))
|
||||
@@ -56,6 +58,17 @@ final class SigV4 {
|
||||
}
|
||||
|
||||
String root() { return root; }
|
||||
boolean configuredIdentity(String principal) {
|
||||
return principal != null &&
|
||||
(configuredIdentities.containsKey(principal) || sessions.containsKey(principal));
|
||||
}
|
||||
synchronized void setManagedIdentities(Map<String, String> managed) {
|
||||
Map<String, String> combined = new java.util.HashMap<>(configuredIdentities);
|
||||
for (var entry : managed.entrySet())
|
||||
if (combined.putIfAbsent(entry.getKey(), entry.getValue()) != null || sessions.containsKey(entry.getKey()))
|
||||
throw new IllegalArgumentException("Managed access key conflicts with a configured identity");
|
||||
identities = Map.copyOf(combined);
|
||||
}
|
||||
Set<String> identities() {
|
||||
var all = new java.util.HashSet<>(identities.keySet());
|
||||
all.addAll(sessions.keySet());
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.locks.Lock;
|
||||
import java.util.concurrent.locks.ReentrantReadWriteLock;
|
||||
|
||||
final class StoreOperations {
|
||||
@FunctionalInterface
|
||||
interface Action {
|
||||
void run() throws IOException;
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
interface Query<T> {
|
||||
T get() throws IOException;
|
||||
}
|
||||
|
||||
private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(true);
|
||||
|
||||
void read(Action action) throws IOException {
|
||||
run(lock.readLock(), action);
|
||||
}
|
||||
|
||||
void write(Action action) throws IOException {
|
||||
Lock writing = lock.writeLock();
|
||||
try {
|
||||
if (!writing.tryLock(1, TimeUnit.SECONDS))
|
||||
throw new StoreException(409, "OperationAborted",
|
||||
"Storage is busy; retry after transfers finish");
|
||||
} catch (InterruptedException error) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new StoreException(503, "SlowDown", "Storage operation was interrupted");
|
||||
}
|
||||
try {
|
||||
action.run();
|
||||
} finally {
|
||||
writing.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
<T> T readValue(Query<T> query) throws IOException {
|
||||
Lock reading = lock.readLock();
|
||||
reading.lock();
|
||||
try {
|
||||
return query.get();
|
||||
} finally {
|
||||
reading.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
private static void run(Lock lock, Action action) throws IOException {
|
||||
lock.lock();
|
||||
try {
|
||||
action.run();
|
||||
} finally {
|
||||
lock.unlock();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
const vm = require("node:vm");
|
||||
|
||||
async function staleAccessCheck() {
|
||||
const base = "http://localhost/_objectstore/admin";
|
||||
const location = new URL(base + "/audit");
|
||||
const events = new Map();
|
||||
const requests = [];
|
||||
let content;
|
||||
let replacements = 0;
|
||||
const makeContent = () => ({
|
||||
isConnected: true,
|
||||
querySelector: () => null,
|
||||
querySelectorAll: () => [],
|
||||
replaceWith(next) {
|
||||
this.isConnected = false;
|
||||
content = next;
|
||||
replacements++;
|
||||
}
|
||||
});
|
||||
content = makeContent();
|
||||
const initial = content;
|
||||
class Form {
|
||||
action = base + "/action/access-check";
|
||||
get isConnected() { return initial.isConnected; }
|
||||
closest() { return initial; }
|
||||
}
|
||||
class Link {
|
||||
href = base + "/buckets";
|
||||
target = "";
|
||||
hasAttribute() { return false; }
|
||||
}
|
||||
const document = {
|
||||
body: { dataset: {} },
|
||||
getElementById: () => null,
|
||||
querySelector: selector => selector === ".workspace-content" ? content : null,
|
||||
querySelectorAll: () => [],
|
||||
addEventListener: (type, callback) => events.set(type, callback),
|
||||
importNode: node => node
|
||||
};
|
||||
const history = {
|
||||
state: null,
|
||||
replaceState(state, title, url) {
|
||||
this.state = state;
|
||||
location.href = new URL(url, location).href;
|
||||
},
|
||||
pushState(state, title, url) { this.replaceState(state, title, url); }
|
||||
};
|
||||
const context = {
|
||||
document, history, location, URL, URLSearchParams, AbortController, AbortSignal,
|
||||
HTMLFormElement: Form, HTMLAnchorElement: Link,
|
||||
FormData: class extends Map { constructor() { super(); } },
|
||||
DOMParser: class {
|
||||
parseFromString() {
|
||||
return { title: "ObjectStore admin", querySelector: () => makeContent() };
|
||||
}
|
||||
},
|
||||
localStorage: { getItem: () => null },
|
||||
matchMedia: () => ({ matches: false, addEventListener() {} }),
|
||||
setTimeout, clearTimeout, console,
|
||||
window: { scrollY: 0, scrollTo() {}, addEventListener() {} },
|
||||
fetch(url, options) {
|
||||
if (String(url).endsWith("/branding.json")) return Promise.resolve({ ok: false });
|
||||
return new Promise(resolve => requests.push({ url: String(url), options, resolve }));
|
||||
}
|
||||
};
|
||||
vm.runInNewContext(fs.readFileSync(path.join(__dirname, "../admin-ui/workspace.js"), "utf8"), context);
|
||||
events.get("submit")({ target: new Form(), defaultPrevented: false, preventDefault() {} });
|
||||
assert.equal(requests.length, 1);
|
||||
events.get("click")({ defaultPrevented: false, button: 0,
|
||||
composedPath: () => [new Link()], preventDefault() {} });
|
||||
assert.equal(requests.length, 2);
|
||||
assert.equal(requests[0].options.signal.aborted, true, "Navigation must cancel the old access check");
|
||||
|
||||
const respond = (request, url) => request.resolve({
|
||||
url, ok: true, headers: { get: () => "text/html" }, text: async () => "page"
|
||||
});
|
||||
respond(requests[1], base + "/buckets");
|
||||
await new Promise(setImmediate);
|
||||
respond(requests[0], base + "/audit");
|
||||
await new Promise(setImmediate);
|
||||
assert.equal(location.pathname, "/_objectstore/admin/buckets");
|
||||
assert.equal(replacements, 1, "Late access-check response replaced the newly opened page");
|
||||
}
|
||||
|
||||
staleAccessCheck().then(() => console.log("Admin workspace tests passed: stale access-check response"))
|
||||
.catch(error => { console.error(error); process.exitCode = 1; });
|
||||
@@ -45,6 +45,28 @@ public final class AdminConsoleTest {
|
||||
return match.group(1);
|
||||
}
|
||||
|
||||
private static HttpResponse<String> action(HttpClient client, String base, String name,
|
||||
String cookie, String origin, String form) throws Exception {
|
||||
var builder = request(base, "/action/" + name)
|
||||
.header("Content-Type", "application/x-www-form-urlencoded")
|
||||
.header("Cookie", cookie);
|
||||
if (origin != null) builder.header("Origin", origin);
|
||||
return client.send(builder.POST(HttpRequest.BodyPublishers.ofString(form)).build(),
|
||||
HttpResponse.BodyHandlers.ofString());
|
||||
}
|
||||
|
||||
private static HttpResponse<String> upload(HttpClient client, String base, String path,
|
||||
String cookie, String origin, String csrf,
|
||||
byte[] content) throws Exception {
|
||||
var builder = request(base, "/upload?" + path)
|
||||
.header("Content-Type", "text/plain")
|
||||
.header("Cookie", cookie);
|
||||
if (origin != null) builder.header("Origin", origin);
|
||||
if (csrf != null) builder.header("X-ObjectStore-CSRF", csrf);
|
||||
return client.send(builder.POST(HttpRequest.BodyPublishers.ofByteArray(content)).build(),
|
||||
HttpResponse.BodyHandlers.ofString());
|
||||
}
|
||||
|
||||
private static String loginToken(HttpClient client, String base) throws Exception {
|
||||
return csrf(client.send(request(base, "/login").GET().build(),
|
||||
HttpResponse.BodyHandlers.ofString()).body());
|
||||
@@ -65,13 +87,30 @@ public final class AdminConsoleTest {
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
Path root = Files.createTempDirectory("admin-console-test-");
|
||||
Path legacyBranding = root.resolve("legacy-branding.txt");
|
||||
Files.writeString(legacyBranding, "ObjectStoreBranding 1\n" +
|
||||
java.util.Base64.getEncoder().encodeToString("Old name".getBytes(StandardCharsets.UTF_8)) +
|
||||
"\n\n\n");
|
||||
AdminBranding migrated = new AdminBranding(legacyBranding);
|
||||
if (!migrated.state().name().equals("Old name") ||
|
||||
!migrated.state().defaultTheme().equals("deep-dark"))
|
||||
throw new AssertionError("Legacy branding or deep-dark default was lost");
|
||||
migrated.setDefaultTheme("light");
|
||||
if (!new AdminBranding(legacyBranding).state().defaultTheme().equals("light") ||
|
||||
!new AdminBranding(legacyBranding).state().name().equals("Old name"))
|
||||
throw new AssertionError("Global theme did not persist across branding migration");
|
||||
Path passwordFile = root.resolve("password");
|
||||
Files.writeString(passwordFile, PASSWORD + "\n");
|
||||
Path masterFile = root.resolve("credential-master");
|
||||
Files.writeString(masterFile, "0123456789abcdef".repeat(4));
|
||||
DiskStore store = new DiskStore(root.resolve("data"), 1024, 4096);
|
||||
store.ensureBucket("photos");
|
||||
byte[] image = "small preview".getBytes(StandardCharsets.UTF_8);
|
||||
store.put("photos", "images/cat.txt", new ByteArrayInputStream(image), image.length,
|
||||
SigV4.hex(SigV4.hash(image)), null, true, "text/plain");
|
||||
DiskBucketNames names = new DiskBucketNames(store, new MultipartStore(store));
|
||||
BucketActivity activity = new BucketActivity(root.resolve("data/bucket-activity.tsv"));
|
||||
activity.record("photos", "GET");
|
||||
var executor = Executors.newVirtualThreadPerTaskExecutor();
|
||||
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 16);
|
||||
HttpServer s3Server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 16);
|
||||
@@ -98,11 +137,18 @@ public final class AdminConsoleTest {
|
||||
} catch (IllegalArgumentException expected) { }
|
||||
}
|
||||
AdminConsole console = AdminConsole.fromEnvironment(Map.of(
|
||||
"ADMIN_UI_ENABLED", "true", "ADMIN_UI_PASSWORD_FILE", passwordFile.toString()), store);
|
||||
var app = new Main(store, new MultipartStore(store),
|
||||
"ADMIN_UI_ENABLED", "true", "ADMIN_UI_PASSWORD_FILE", passwordFile.toString(),
|
||||
"DATA_DIR", root.resolve("data").toString()), names);
|
||||
console.setDiskStore(store);
|
||||
var app = new Main(names, names,
|
||||
new SigV4("TESTACCESSKEY123", "test-secret-key-that-is-at-least-32-characters",
|
||||
"us-east-1", Clock.systemUTC()), "objects");
|
||||
app.setBucketActivity(activity);
|
||||
app.setAdminConsole(console);
|
||||
ManagedCredentials managed = ManagedCredentials.fromEnvironment(Map.of(
|
||||
"S3_MANAGED_KEYS_MASTER_FILE", masterFile.toString(),
|
||||
"DATA_DIR", root.resolve("data").toString()), store, java.util.Set.of("TESTACCESSKEY123"));
|
||||
app.setManagedCredentials(managed);
|
||||
server.setExecutor(executor);
|
||||
server.createContext("/", app::handleAdmin);
|
||||
server.start();
|
||||
@@ -125,12 +171,16 @@ public final class AdminConsoleTest {
|
||||
}
|
||||
status(303, client.send(request(base, "/overview").GET().build(),
|
||||
HttpResponse.BodyHandlers.ofString()));
|
||||
for (String path : new String[] { "/performance", "/performance.json", "/performance.js",
|
||||
for (String path : new String[] { "/performance", "/performance.json", "/performance.js", "/settings",
|
||||
"/health", "/diagnostics", "/diagnostics/probe.bin",
|
||||
"/audit", "/jobs", "/cluster",
|
||||
"/buckets", "/bucket?name=photos",
|
||||
"/object?bucket=photos&key=images%2Fcat.txt" }) {
|
||||
status(303, client.send(request(base, path).GET().build(),
|
||||
HttpResponse.BodyHandlers.ofString()));
|
||||
}
|
||||
status(401, client.send(request(base, "/jobs.json?id=abcdefghijklmnop").GET().build(),
|
||||
HttpResponse.BodyHandlers.ofString()));
|
||||
var loginPage = client.send(request(base, "/login").GET().build(),
|
||||
HttpResponse.BodyHandlers.ofString());
|
||||
status(200, loginPage);
|
||||
@@ -138,6 +188,11 @@ public final class AdminConsoleTest {
|
||||
!loginPage.body().contains("/_objectstore/admin/logo.png") ||
|
||||
!loginPage.headers().firstValue("Cache-Control").orElse("").equals("no-store"))
|
||||
throw new AssertionError("Login page or cache control missing");
|
||||
var loginAppearance = client.send(request(base, "/workspace.js").GET().build(),
|
||||
HttpResponse.BodyHandlers.ofString());
|
||||
status(200, loginAppearance);
|
||||
if (!loginAppearance.body().contains("applyPreferences"))
|
||||
throw new AssertionError("Login appearance script missing");
|
||||
String policy = loginPage.headers().firstValue("Content-Security-Policy").orElse("");
|
||||
if (!policy.contains("style-src 'self'") || !policy.contains("img-src 'self'"))
|
||||
throw new AssertionError("Admin console content policy missing");
|
||||
@@ -169,8 +224,66 @@ public final class AdminConsoleTest {
|
||||
if (!overview.body().contains("Storage mode") ||
|
||||
!overview.body().contains("biscuit-cardview") || !overview.body().contains("photos") ||
|
||||
!overview.body().contains("/performance") ||
|
||||
!overview.body().contains("/_objectstore/admin/logo.png"))
|
||||
!overview.body().contains("/_objectstore/admin/logo.png") ||
|
||||
!overview.body().contains("biscuit-sidebarview") ||
|
||||
!overview.body().contains("biscuit-navbarview") ||
|
||||
!overview.body().contains("/icons/bucket.svg") ||
|
||||
!overview.body().contains("/icons/activity.svg") ||
|
||||
!overview.body().contains("class=mobile-nav-link") ||
|
||||
!overview.body().contains("biscuit-footerview"))
|
||||
throw new AssertionError("Authenticated overview missing");
|
||||
var workspace = client.send(request(base, "/workspace.js").header("Cookie", cookie).GET().build(),
|
||||
HttpResponse.BodyHandlers.ofString());
|
||||
status(200, workspace);
|
||||
var bucketIcon = client.send(request(base, "/icons/bucket.svg")
|
||||
.header("Cookie", cookie).GET().build(), HttpResponse.BodyHandlers.ofString());
|
||||
status(200, bucketIcon);
|
||||
if (!bucketIcon.body().contains("<svg"))
|
||||
throw new AssertionError("Biscuit bucket icon is unavailable");
|
||||
if (!workspace.body().contains("registerCodeLanguage(\"json\""))
|
||||
throw new AssertionError("CodeView JSON highlighting is unavailable");
|
||||
var healthView = client.send(request(base, "/health").header("Cookie", cookie).GET().build(),
|
||||
HttpResponse.BodyHandlers.ofString());
|
||||
status(200, healthView);
|
||||
if (!healthView.body().contains("Filesystem available") ||
|
||||
!healthView.body().contains("Latest restore test") ||
|
||||
!healthView.body().contains("Not reported"))
|
||||
throw new AssertionError("Health view implies an unverified backup or hides disk state");
|
||||
var diagnosticsView = client.send(request(base, "/diagnostics").header("Cookie", cookie).GET().build(),
|
||||
HttpResponse.BodyHandlers.ofString());
|
||||
status(200, diagnosticsView);
|
||||
if (!diagnosticsView.body().contains("p50 / p95") ||
|
||||
!diagnosticsView.body().contains("Recent errors") ||
|
||||
!diagnosticsView.body().contains("diagnostic-probe"))
|
||||
throw new AssertionError("Request diagnostics view missing");
|
||||
var auditView = client.send(request(base, "/audit").header("Cookie", cookie).GET().build(),
|
||||
HttpResponse.BodyHandlers.ofString());
|
||||
status(200, auditView);
|
||||
if (!auditView.body().contains("Check access") ||
|
||||
!auditView.body().contains("Admin event trail"))
|
||||
throw new AssertionError("Audit and access view missing");
|
||||
var accessResult = action(client, base, "access-check", cookie, base,
|
||||
"csrf=" + csrf(overview.body()) +
|
||||
"&principal=TESTACCESSKEY123&operation=list&bucket=photos&key=");
|
||||
status(200, accessResult);
|
||||
if (!accessResult.body().contains("Owner or ACL grants this action"))
|
||||
throw new AssertionError("Access checker did not use live S3 permissions");
|
||||
var jobsView = client.send(request(base, "/jobs").header("Cookie", cookie).GET().build(),
|
||||
HttpResponse.BodyHandlers.ofString());
|
||||
status(200, jobsView);
|
||||
if (!jobsView.body().contains("Bulk jobs") || !jobsView.body().contains("Export inventory"))
|
||||
throw new AssertionError("Bulk jobs view missing");
|
||||
var clusterView = client.send(request(base, "/cluster").header("Cookie", cookie).GET().build(),
|
||||
HttpResponse.BodyHandlers.ofString());
|
||||
status(200, clusterView);
|
||||
if (!clusterView.body().contains("disk mode"))
|
||||
throw new AssertionError("Disk gateway should not claim cluster health");
|
||||
var probe = client.send(request(base, "/diagnostics/probe.bin").header("Cookie", cookie).GET().build(),
|
||||
HttpResponse.BodyHandlers.ofByteArray());
|
||||
status(200, probe);
|
||||
if (probe.body().length != 1024 * 1024 ||
|
||||
!probe.headers().firstValue("Cache-Control").orElse("").equals("no-store"))
|
||||
throw new AssertionError("Connection probe size or cache control changed");
|
||||
var performance = client.send(request(base, "/performance").header("Cookie", cookie).GET().build(),
|
||||
HttpResponse.BodyHandlers.ofString());
|
||||
status(200, performance);
|
||||
@@ -181,10 +294,19 @@ public final class AdminConsoleTest {
|
||||
!performance.body().contains("Process RAM") ||
|
||||
!performance.body().contains("performance.js"))
|
||||
throw new AssertionError("Performance view missing");
|
||||
if (performance.body().split("theme=dark type=line", -1).length != 5)
|
||||
if (performance.body().split("theme=deep-dark type=line", -1).length != 5)
|
||||
throw new AssertionError("Performance charts must use Biscuit's dark renderer");
|
||||
status(200, client.send(request(base, "/performance.js").header("Cookie", cookie).GET().build(),
|
||||
HttpResponse.BodyHandlers.ofString()));
|
||||
status(303, client.send(request(base, "/performance.events").GET().build(),
|
||||
HttpResponse.BodyHandlers.discarding()));
|
||||
var events = client.send(request(base, "/performance.events")
|
||||
.header("Cookie", cookie).GET().build(), HttpResponse.BodyHandlers.ofInputStream());
|
||||
status(200, events);
|
||||
if (!events.headers().firstValue("Content-Type").orElse("").startsWith("text/event-stream") ||
|
||||
!new String(events.body().readNBytes(6), StandardCharsets.UTF_8).equals("data: "))
|
||||
throw new AssertionError("Performance event stream is unavailable");
|
||||
events.body().close();
|
||||
for (int poll = 0; poll < 2; poll++) {
|
||||
var sample = client.send(request(base, "/performance.json")
|
||||
.header("Cookie", cookie).GET().build(), HttpResponse.BodyHandlers.ofString());
|
||||
@@ -199,16 +321,26 @@ public final class AdminConsoleTest {
|
||||
status(200, bucketIndex);
|
||||
if (!bucketIndex.body().contains("/bucket?name=photos"))
|
||||
throw new AssertionError("Bucket index did not link to photos");
|
||||
if (!bucketIndex.body().contains("biscuit-formwizardview") ||
|
||||
!bucketIndex.body().contains("blockPublicPolicy") ||
|
||||
!bucketIndex.body().contains("Public access blocked") ||
|
||||
!bucketIndex.body().contains("biscuit-pageloaderview"))
|
||||
throw new AssertionError("New bucket setup wizard is missing");
|
||||
var bucket = client.send(request(base, "/bucket?name=photos").header("Cookie", cookie).GET().build(),
|
||||
HttpResponse.BodyHandlers.ofString());
|
||||
status(200, bucket);
|
||||
if (!bucket.body().contains("images/") || !bucket.body().contains("Bucket settings"))
|
||||
if (!bucket.body().contains("images/") || !bucket.body().contains("Bucket settings") ||
|
||||
!bucket.body().contains("biscuit-tablayout") ||
|
||||
!bucket.body().contains("biscuit-activity-chart") ||
|
||||
!bucket.body().contains("Daily S3 requests"))
|
||||
throw new AssertionError("Bucket folder or settings missing");
|
||||
if (!bucket.body().contains("Upload file") || !bucket.body().contains("class='settings-form upload-form'"))
|
||||
throw new AssertionError("Bucket upload controls missing");
|
||||
var folder = client.send(request(base, "/bucket?name=photos&prefix=images%2F")
|
||||
.header("Cookie", cookie).GET().build(), HttpResponse.BodyHandlers.ofString());
|
||||
status(200, folder);
|
||||
if (!folder.body().contains("cat.txt") || !folder.body().contains("biscuit-chartview") ||
|
||||
!folder.body().contains("theme=dark") ||
|
||||
!folder.body().contains("theme=deep-dark") ||
|
||||
!folder.body().contains("this page only"))
|
||||
throw new AssertionError("Folder listing or bounded chart missing");
|
||||
var object = client.send(request(base, "/object?bucket=photos&key=images%2Fcat.txt")
|
||||
@@ -217,6 +349,321 @@ public final class AdminConsoleTest {
|
||||
if (!object.body().contains("Content type") || !object.body().contains("text/plain") ||
|
||||
!object.body().contains("SHA-256"))
|
||||
throw new AssertionError("Object metadata missing");
|
||||
var versions = client.send(request(base, "/versions?bucket=photos&prefix=images%2F")
|
||||
.header("Cookie", cookie).GET().build(), HttpResponse.BodyHandlers.ofString());
|
||||
status(200, versions);
|
||||
if (!versions.body().contains("cat.txt") || !versions.body().contains("&version=null"))
|
||||
throw new AssertionError("Version browser did not link to the object");
|
||||
status(200, client.send(request(base,
|
||||
"/object?bucket=photos&key=images%2Fcat.txt&version=null")
|
||||
.header("Cookie", cookie).GET().build(), HttpResponse.BodyHandlers.ofString()));
|
||||
String adminCsrf = csrf(overview.body());
|
||||
byte[] uploadBody = "uploaded from admin".getBytes(StandardCharsets.UTF_8);
|
||||
String uploadPath = "bucket=photos&key=images%2Fupload.txt";
|
||||
status(401, client.send(request(base, "/upload?" + uploadPath)
|
||||
.header("Content-Type", "text/plain")
|
||||
.POST(HttpRequest.BodyPublishers.ofByteArray(uploadBody)).build(),
|
||||
HttpResponse.BodyHandlers.ofString()));
|
||||
status(403, upload(client, base, uploadPath, cookie, base, null, uploadBody));
|
||||
status(403, upload(client, base, uploadPath, cookie, "https://evil.example",
|
||||
adminCsrf, uploadBody));
|
||||
var uploaded = upload(client, base, uploadPath, cookie, base, adminCsrf, uploadBody);
|
||||
status(201, uploaded);
|
||||
if (!uploaded.headers().firstValue("Location").orElse("")
|
||||
.equals(AdminConsole.PATH + "/object?bucket=photos&key=images%2Fupload.txt"))
|
||||
throw new AssertionError("Upload did not link to the object");
|
||||
status(412, upload(client, base, uploadPath, cookie, base, adminCsrf, uploadBody));
|
||||
status(409, upload(client, base, uploadPath + "&overwrite=1", cookie, base,
|
||||
adminCsrf, uploadBody));
|
||||
status(413, upload(client, base, "bucket=photos&key=too-large.txt", cookie, base,
|
||||
adminCsrf, new byte[1025]));
|
||||
var downloaded = client.send(request(base, "/download?" + uploadPath)
|
||||
.header("Cookie", cookie).GET().build(), HttpResponse.BodyHandlers.ofByteArray());
|
||||
status(200, downloaded);
|
||||
if (!java.util.Arrays.equals(uploadBody, downloaded.body()) ||
|
||||
!downloaded.headers().firstValue("Content-Disposition").orElse("")
|
||||
.contains("filename*=UTF-8''upload.txt"))
|
||||
throw new AssertionError("Admin download changed file content or filename");
|
||||
status(303, client.send(request(base, "/download?" + uploadPath).GET().build(),
|
||||
HttpResponse.BodyHandlers.discarding()));
|
||||
status(400, client.send(request(base, "/download?bucket=photos&key=x&key=y")
|
||||
.header("Cookie", cookie).GET().build(), HttpResponse.BodyHandlers.discarding()));
|
||||
status(403, action(client, base, "create-bucket", cookie, null, "bucket=archive"));
|
||||
status(403, action(client, base, "create-bucket", cookie, "https://evil.example",
|
||||
"csrf=" + adminCsrf + "&bucket=archive"));
|
||||
status(303, action(client, base, "create-bucket", cookie, base,
|
||||
"csrf=" + adminCsrf + "&bucket=archive"));
|
||||
status(400, action(client, base, "create-bucket", cookie, base,
|
||||
"csrf=" + adminCsrf + "&bucket=wizard-bucket&setup=wizard&versioning=enabled" +
|
||||
"&ownership=BucketOwnerPreferred&ignorePublicAcls=on&blockPublicPolicy=on" +
|
||||
"&restrictPublicBuckets=on"));
|
||||
status(303, action(client, base, "create-bucket", cookie, base,
|
||||
"csrf=" + adminCsrf + "&bucket=wizard-bucket&setup=wizard&versioning=enabled" +
|
||||
"&ownership=BucketOwnerPreferred&ignorePublicAcls=on&blockPublicPolicy=on" +
|
||||
"&restrictPublicBuckets=on&acknowledgePublic=yes"));
|
||||
var wizardBucket = names.bucket("wizard-bucket");
|
||||
if (wizardBucket.versioning() != ObjectStorage.VersioningState.ENABLED ||
|
||||
wizardBucket.ownership() != ObjectStorage.ObjectOwnership.BUCKET_OWNER_PREFERRED ||
|
||||
wizardBucket.publicAccessBlock().blockPublicAcls())
|
||||
throw new AssertionError("Bucket wizard did not apply initial settings");
|
||||
var keys = client.send(request(base, "/credentials").header("Cookie", cookie).GET().build(),
|
||||
HttpResponse.BodyHandlers.ofString());
|
||||
status(200, keys);
|
||||
if (!keys.body().contains("Create scoped key") || !keys.body().contains("photos"))
|
||||
throw new AssertionError("Access key controls missing");
|
||||
status(403, action(client, base, "create-key", cookie, base,
|
||||
"bucket=photos&prefix=images%2F&read=on"));
|
||||
var newKey = action(client, base, "create-key", cookie, base,
|
||||
"csrf=" + adminCsrf + "&bucket=photos&prefix=images%2F&read=on&write=on&list=on");
|
||||
status(200, newKey);
|
||||
if (!newKey.body().contains("Save this secret now") || managed.list().size() != 1)
|
||||
throw new AssertionError("Managed access key was not created");
|
||||
ManagedCredentials.Key scoped = managed.list().getFirst();
|
||||
status(409, action(client, base, "rename-bucket", cookie, base,
|
||||
"csrf=" + adminCsrf + "&bucket=photos&newName=other-photos&confirm=photos"));
|
||||
if (!names.bucket("photos").name().equals("photos"))
|
||||
throw new AssertionError("Scoped-key rejection changed the bucket name");
|
||||
if (!newKey.body().contains(scoped.secret()) ||
|
||||
client.send(request(base, "/credentials").header("Cookie", cookie).GET().build(),
|
||||
HttpResponse.BodyHandlers.ofString()).body().contains(scoped.secret()))
|
||||
throw new AssertionError("Secret must be shown once");
|
||||
if (Files.readString(root.resolve("data/managed-credentials.bin"), StandardCharsets.ISO_8859_1)
|
||||
.contains(scoped.secret()))
|
||||
throw new AssertionError("Managed secret was stored in cleartext");
|
||||
var restored = ManagedCredentials.fromEnvironment(Map.of(
|
||||
"S3_MANAGED_KEYS_MASTER_FILE", masterFile.toString(),
|
||||
"DATA_DIR", root.resolve("data").toString()), store, java.util.Set.of("TESTACCESSKEY123"));
|
||||
if (!restored.list().getFirst().secret().equals(scoped.secret()))
|
||||
throw new AssertionError("Managed key was not persisted");
|
||||
status(200, client.send(HttpTest.signedUriAs(URI.create(s3Base + "/photos/images/cat.txt"),
|
||||
"GET", new byte[0], Map.of(), scoped.id(), scoped.secret()),
|
||||
HttpResponse.BodyHandlers.ofString()));
|
||||
status(403, client.send(HttpTest.signedUriAs(URI.create(s3Base + "/photos/outside.txt"),
|
||||
"GET", new byte[0], Map.of(), scoped.id(), scoped.secret()),
|
||||
HttpResponse.BodyHandlers.ofString()));
|
||||
status(200, client.send(HttpTest.signedUriAs(URI.create(s3Base + "/photos?list-type=2&prefix=images%2F"),
|
||||
"GET", new byte[0], Map.of(), scoped.id(), scoped.secret()),
|
||||
HttpResponse.BodyHandlers.ofString()));
|
||||
status(200, client.send(HttpTest.signedUriAs(URI.create(s3Base + "/photos"),
|
||||
"HEAD", new byte[0], Map.of(), scoped.id(), scoped.secret()),
|
||||
HttpResponse.BodyHandlers.discarding()));
|
||||
status(403, client.send(HttpTest.signedUriAs(URI.create(s3Base + "/photos?list-type=2"),
|
||||
"GET", new byte[0], Map.of(), scoped.id(), scoped.secret()),
|
||||
HttpResponse.BodyHandlers.ofString()));
|
||||
status(400, action(client, base, "disable-key", cookie, base,
|
||||
"csrf=" + adminCsrf + "&id=" + scoped.id()));
|
||||
status(303, action(client, base, "disable-key", cookie, base,
|
||||
"csrf=" + adminCsrf + "&id=" + scoped.id() + "&confirm=" + scoped.id()));
|
||||
status(403, client.send(HttpTest.signedUriAs(URI.create(s3Base + "/photos/images/cat.txt"),
|
||||
"GET", new byte[0], Map.of(), scoped.id(), scoped.secret()),
|
||||
HttpResponse.BodyHandlers.ofString()));
|
||||
status(303, action(client, base, "enable-key", cookie, base,
|
||||
"csrf=" + adminCsrf + "&id=" + scoped.id() + "&confirm=" + scoped.id()));
|
||||
status(200, client.send(HttpTest.signedUriAs(URI.create(s3Base + "/photos/images/cat.txt"),
|
||||
"GET", new byte[0], Map.of(), scoped.id(), scoped.secret()),
|
||||
HttpResponse.BodyHandlers.ofString()));
|
||||
status(403, client.send(HttpTest.signedUriAs(URI.create(s3Base + "/objects/images/cat.txt"),
|
||||
"GET", new byte[0], Map.of(), scoped.id(), scoped.secret()),
|
||||
HttpResponse.BodyHandlers.ofString()));
|
||||
status(400, action(client, base, "update-key", cookie, base,
|
||||
"csrf=" + adminCsrf + "&id=" + scoped.id() + "&bucket=photos&prefix=images%2F&read=on&list=on"));
|
||||
status(303, action(client, base, "update-key", cookie, base,
|
||||
"csrf=" + adminCsrf + "&id=" + scoped.id() + "&bucket=photos&prefix=images%2F&read=on&list=on" +
|
||||
"&confirm=" + scoped.id()));
|
||||
status(403, client.send(HttpTest.signedUriAs(URI.create(s3Base + "/photos/images/new.txt"),
|
||||
"PUT", "new".getBytes(StandardCharsets.UTF_8), Map.of(), scoped.id(), scoped.secret()),
|
||||
HttpResponse.BodyHandlers.ofString()));
|
||||
status(303, action(client, base, "delete-key", cookie, base,
|
||||
"csrf=" + adminCsrf + "&id=" + scoped.id() + "&confirm=" + scoped.id()));
|
||||
status(403, client.send(HttpTest.signedUriAs(URI.create(s3Base + "/photos/images/cat.txt"),
|
||||
"GET", new byte[0], Map.of(), scoped.id(), scoped.secret()),
|
||||
HttpResponse.BodyHandlers.ofString()));
|
||||
if (store.bucket("archive").ownership() != ObjectStorage.ObjectOwnership.BUCKET_OWNER_ENFORCED ||
|
||||
!store.bucket("archive").publicAccessBlock().equals(ObjectStorage.PublicAccessBlock.secure()))
|
||||
throw new AssertionError("Created bucket did not have private defaults");
|
||||
status(400, action(client, base, "public-access", cookie, base,
|
||||
"csrf=" + adminCsrf + "&bucket=archive"));
|
||||
status(303, action(client, base, "public-access", cookie, base,
|
||||
"csrf=" + adminCsrf + "&bucket=archive&confirm=archive"));
|
||||
status(303, action(client, base, "ownership", cookie, base,
|
||||
"csrf=" + adminCsrf + "&bucket=archive&ownership=BucketOwnerPreferred&confirm=archive"));
|
||||
String publicPolicy = "{\"Version\":\"2012-10-17\",\"Statement\":{\"Effect\":\"Allow\",\"Principal\":\"*\"," +
|
||||
"\"Action\":\"s3:GetObject\",\"Resource\":\"arn:aws:s3:::archive/*\"}}";
|
||||
String policyForm = "csrf=" + adminCsrf + "&bucket=archive&policy=" +
|
||||
java.net.URLEncoder.encode(publicPolicy, StandardCharsets.UTF_8);
|
||||
status(400, action(client, base, "policy", cookie, base, policyForm));
|
||||
String invalidPolicy = "{\"Version\": invalid}";
|
||||
var policyError = action(client, base, "policy", cookie, base,
|
||||
"csrf=" + adminCsrf + "&bucket=archive&policy=" +
|
||||
java.net.URLEncoder.encode(invalidPolicy, StandardCharsets.UTF_8));
|
||||
status(400, policyError);
|
||||
if (!policyError.body().contains("biscuit-codeview") ||
|
||||
!policyError.body().contains("Version&quot;") &&
|
||||
!policyError.body().contains("Version""))
|
||||
throw new AssertionError("Invalid policy draft was not returned to the editor");
|
||||
status(303, action(client, base, "policy", cookie, base, policyForm + "&confirm=archive"));
|
||||
status(303, action(client, base, "policy", cookie, base,
|
||||
"csrf=" + adminCsrf + "&bucket=archive&policy="));
|
||||
status(400, action(client, base, "bucket-grant", cookie, base,
|
||||
"csrf=" + adminCsrf + "&bucket=archive&principal=AllUsers&permission=READ&operation=add"));
|
||||
status(303, action(client, base, "bucket-grant", cookie, base,
|
||||
"csrf=" + adminCsrf + "&bucket=archive&principal=AllUsers&permission=READ&operation=add&confirm=archive"));
|
||||
if (!store.bucket("archive").acl().containsKey(Acl.ALL_USERS))
|
||||
throw new AssertionError("Admin ACL grant was not persisted");
|
||||
status(303, action(client, base, "bucket-grant", cookie, base,
|
||||
"csrf=" + adminCsrf + "&bucket=archive&principal=AllUsers&operation=remove"));
|
||||
status(303, action(client, base, "versioning", cookie, base,
|
||||
"csrf=" + adminCsrf + "&bucket=archive&state=ENABLED"));
|
||||
store.createBucket("editor");
|
||||
store.setVersioning("editor", ObjectStorage.VersioningState.ENABLED);
|
||||
String versionedUpload = "bucket=editor&key=up.txt";
|
||||
byte[] oldUpload = "first".getBytes(StandardCharsets.UTF_8);
|
||||
byte[] newUpload = "second".getBytes(StandardCharsets.UTF_8);
|
||||
status(201, upload(client, base, versionedUpload, cookie, base, adminCsrf, oldUpload));
|
||||
ObjectStorage.Metadata oldUploadMeta;
|
||||
try (ObjectStorage.OpenObject opened = store.open("editor", "up.txt")) {
|
||||
oldUploadMeta = opened.metadata();
|
||||
}
|
||||
status(412, upload(client, base, versionedUpload, cookie, base, adminCsrf, newUpload));
|
||||
status(201, upload(client, base, versionedUpload + "&overwrite=1", cookie, base,
|
||||
adminCsrf, newUpload));
|
||||
var oldDownload = client.send(request(base, "/download?" + versionedUpload +
|
||||
"&version=" + java.net.URLEncoder.encode(oldUploadMeta.versionId(), StandardCharsets.UTF_8))
|
||||
.header("Cookie", cookie).GET().build(), HttpResponse.BodyHandlers.ofByteArray());
|
||||
status(200, oldDownload);
|
||||
if (!java.util.Arrays.equals(oldUpload, oldDownload.body()))
|
||||
throw new AssertionError("Replacing an object lost its prior version");
|
||||
byte[] firstText = "{\"hello\":1}".getBytes(StandardCharsets.UTF_8);
|
||||
ObjectStorage.Metadata firstVersion = store.put("editor", "note.json",
|
||||
new ByteArrayInputStream(firstText), firstText.length,
|
||||
SigV4.hex(SigV4.hash(firstText)), null, false, "application/json");
|
||||
var editor = client.send(request(base, "/object?bucket=editor&key=note.json")
|
||||
.header("Cookie", cookie).GET().build(), HttpResponse.BodyHandlers.ofString());
|
||||
status(200, editor);
|
||||
if (!editor.body().contains("class=text-editor language='json'") ||
|
||||
!editor.body().contains("Save new version"))
|
||||
throw new AssertionError("Editable text object CodeView is missing");
|
||||
String editForm = "csrf=" + adminCsrf + "&bucket=editor&key=note.json&originalVersion=" +
|
||||
java.net.URLEncoder.encode(firstVersion.versionId(), StandardCharsets.UTF_8) +
|
||||
"&originalSha256=" + SigV4.hex(firstVersion.sha256()) + "&content=" +
|
||||
java.net.URLEncoder.encode("{\"hello\":2}", StandardCharsets.UTF_8);
|
||||
status(303, action(client, base, "edit-object", cookie, base, editForm));
|
||||
try (ObjectStorage.OpenObject saved = store.open("editor", "note.json")) {
|
||||
if (!new String(saved.stream().readAllBytes(), StandardCharsets.UTF_8)
|
||||
.equals("{\"hello\":2}"))
|
||||
throw new AssertionError("Edited object content was not saved");
|
||||
}
|
||||
try (ObjectStorage.OpenObject previous = store.open("editor", "note.json", firstVersion.versionId())) {
|
||||
if (!new String(previous.stream().readAllBytes(), StandardCharsets.UTF_8)
|
||||
.equals("{\"hello\":1}"))
|
||||
throw new AssertionError("The prior object version was not retained");
|
||||
}
|
||||
var stale = action(client, base, "edit-object", cookie, base, editForm);
|
||||
status(409, stale);
|
||||
if (!stale.body().contains("The object changed") || !stale.body().contains("hello":2"))
|
||||
throw new AssertionError("Stale edit diagnostic or draft is missing");
|
||||
if (store.bucket("archive").versioning() != ObjectStorage.VersioningState.ENABLED)
|
||||
throw new AssertionError("Admin versioning change was not persisted");
|
||||
status(303, action(client, base, "object-tag", cookie, base,
|
||||
"csrf=" + adminCsrf + "&bucket=photos&key=images%2Fcat.txt&tag=kind&value=cat&operation=add"));
|
||||
if (!"cat".equals(store.tags("photos", "images/cat.txt").get("kind")))
|
||||
throw new AssertionError("Admin tag change was not persisted");
|
||||
status(400, action(client, base, "delete-object", cookie, base,
|
||||
"csrf=" + adminCsrf + "&bucket=photos&key=images%2Fcat.txt"));
|
||||
status(400, action(client, base, "delete-object", cookie, base,
|
||||
"csrf=" + adminCsrf + "&bucket=photos&key=images%2Fcat.txt&version=null" +
|
||||
"&confirm=images%2Fcat.txt"));
|
||||
status(303, action(client, base, "delete-object", cookie, base,
|
||||
"csrf=" + adminCsrf + "&bucket=photos&key=images%2Fcat.txt&confirm=images%2Fcat.txt"));
|
||||
status(404, client.send(request(base, "/object?bucket=photos&key=images%2Fcat.txt")
|
||||
.header("Cookie", cookie).GET().build(), HttpResponse.BodyHandlers.ofString()));
|
||||
status(400, action(client, base, "delete-bucket", cookie, base,
|
||||
"csrf=" + adminCsrf + "&bucket=archive"));
|
||||
status(303, action(client, base, "delete-bucket", cookie, base,
|
||||
"csrf=" + adminCsrf + "&bucket=archive&confirm=archive"));
|
||||
status(303, action(client, base, "create-bucket", cookie, base,
|
||||
"csrf=" + adminCsrf + "&bucket=rename-source"));
|
||||
byte[] renamedBody = "renamed object".getBytes(StandardCharsets.UTF_8);
|
||||
names.put("rename-source", "stored.txt", new ByteArrayInputStream(renamedBody),
|
||||
renamedBody.length, null, null, false, "text/plain");
|
||||
var sourcePage = client.send(request(base, "/bucket?name=rename-source")
|
||||
.header("Cookie", cookie).GET().build(), HttpResponse.BodyHandlers.ofString());
|
||||
status(200, sourcePage);
|
||||
if (!sourcePage.body().contains("biscuit-accordionview") ||
|
||||
!sourcePage.body().contains("Renaming changes the bucket URL"))
|
||||
throw new AssertionError("Rename warning or controls missing");
|
||||
status(400, action(client, base, "rename-bucket", cookie, base,
|
||||
"csrf=" + adminCsrf + "&bucket=rename-source&newName=rename-target"));
|
||||
status(303, action(client, base, "rename-bucket", cookie, base,
|
||||
"csrf=" + adminCsrf + "&bucket=rename-source&newName=rename-target&confirm=rename-source"));
|
||||
status(404, client.send(request(base, "/bucket?name=rename-source")
|
||||
.header("Cookie", cookie).GET().build(), HttpResponse.BodyHandlers.ofString()));
|
||||
status(200, client.send(request(base, "/object?bucket=rename-target&key=stored.txt")
|
||||
.header("Cookie", cookie).GET().build(), HttpResponse.BodyHandlers.ofString()));
|
||||
status(200, client.send(HttpTest.signedUriAs(URI.create(s3Base + "/rename-target/stored.txt"),
|
||||
"GET", new byte[0], Map.of(), "TESTACCESSKEY123",
|
||||
"test-secret-key-that-is-at-least-32-characters"), HttpResponse.BodyHandlers.ofString()));
|
||||
status(404, client.send(HttpTest.signedUriAs(URI.create(s3Base + "/rename-source/stored.txt"),
|
||||
"GET", new byte[0], Map.of(), "TESTACCESSKEY123",
|
||||
"test-secret-key-that-is-at-least-32-characters"), HttpResponse.BodyHandlers.ofString()));
|
||||
var settingsPage = client.send(request(base, "/settings").header("Cookie", cookie).GET().build(),
|
||||
HttpResponse.BodyHandlers.ofString());
|
||||
status(200, settingsPage);
|
||||
if (!settingsPage.body().contains("Save global default") ||
|
||||
!settingsPage.body().contains("Use server default") ||
|
||||
!settingsPage.body().contains("Follow system") ||
|
||||
!settingsPage.body().contains("admin-brand-icon"))
|
||||
throw new AssertionError("Appearance settings missing");
|
||||
var initialBrand = client.send(request(base, "/branding.json").GET().build(),
|
||||
HttpResponse.BodyHandlers.ofString());
|
||||
if (!initialBrand.body().contains("\"defaultTheme\":\"deep-dark\""))
|
||||
throw new AssertionError("Deep dark is not the default for new browsers");
|
||||
status(400, action(client, base, "default-theme", cookie, base,
|
||||
"csrf=" + adminCsrf + "&defaultTheme=unknown"));
|
||||
status(303, action(client, base, "default-theme", cookie, base,
|
||||
"csrf=" + adminCsrf + "&defaultTheme=light"));
|
||||
if (!new AdminBranding(root.resolve("data/admin-branding.txt")).state()
|
||||
.defaultTheme().equals("light"))
|
||||
throw new AssertionError("Global default theme was not saved");
|
||||
status(303, action(client, base, "branding-name", cookie, "null",
|
||||
"csrf=" + adminCsrf + "&displayName=LunarSky+Storage"));
|
||||
var brand = client.send(request(base, "/branding.json").GET().build(),
|
||||
HttpResponse.BodyHandlers.ofString());
|
||||
status(200, brand);
|
||||
if (!brand.body().contains("LunarSky Storage"))
|
||||
throw new AssertionError("Server branding name was not saved");
|
||||
byte[] tinyPng = java.util.Base64.getDecoder().decode(
|
||||
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+X5ZcAAAAASUVORK5CYII=");
|
||||
status(401, client.send(request(base, "/branding-icon/upload")
|
||||
.header("Content-Type", "image/png")
|
||||
.POST(HttpRequest.BodyPublishers.ofByteArray(tinyPng)).build(),
|
||||
HttpResponse.BodyHandlers.ofString()));
|
||||
status(403, client.send(request(base, "/branding-icon/upload")
|
||||
.header("Cookie", cookie).header("Content-Type", "image/png")
|
||||
.POST(HttpRequest.BodyPublishers.ofByteArray(tinyPng)).build(),
|
||||
HttpResponse.BodyHandlers.ofString()));
|
||||
var iconRequest = request(base, "/branding-icon/upload")
|
||||
.header("Cookie", cookie).header("Origin", base).header("Content-Type", "image/png")
|
||||
.header("X-CSRF-Token", adminCsrf);
|
||||
status(415, client.send(iconRequest.POST(HttpRequest.BodyPublishers.ofString("not an image")).build(),
|
||||
HttpResponse.BodyHandlers.ofString()));
|
||||
status(200, client.send(iconRequest.POST(HttpRequest.BodyPublishers.ofByteArray(tinyPng)).build(),
|
||||
HttpResponse.BodyHandlers.ofString()));
|
||||
var storedIcon = client.send(request(base, "/branding-icon").GET().build(),
|
||||
HttpResponse.BodyHandlers.ofByteArray());
|
||||
status(200, storedIcon);
|
||||
if (!java.util.Arrays.equals(tinyPng, storedIcon.body()) ||
|
||||
!storedIcon.headers().firstValue("Content-Type").orElse("").equals("image/png"))
|
||||
throw new AssertionError("Server branding icon was not saved");
|
||||
var persistedBrand = new AdminBranding(root.resolve("data/admin-branding.txt")).state();
|
||||
if (!persistedBrand.name().equals("LunarSky Storage") ||
|
||||
!java.util.Arrays.equals(tinyPng, persistedBrand.icon()))
|
||||
throw new AssertionError("Branding did not survive a reload");
|
||||
status(303, action(client, base, "branding-reset", cookie, base, "csrf=" + adminCsrf));
|
||||
var resetBrand = new AdminBranding(root.resolve("data/admin-branding.txt")).state();
|
||||
if (!resetBrand.name().equals(AdminBranding.DEFAULT_NAME) ||
|
||||
!resetBrand.defaultTheme().equals("light"))
|
||||
throw new AssertionError("Branding reset changed the global theme");
|
||||
status(400, client.send(request(base, "/bucket?name=photos&name=other")
|
||||
.header("Cookie", cookie).GET().build(), HttpResponse.BodyHandlers.ofString()));
|
||||
var reflected = client.send(request(base, "/buckets?filter=%3Cscript%3E")
|
||||
@@ -239,7 +686,8 @@ public final class AdminConsoleTest {
|
||||
status(429, post(client, base, "/login", PASSWORD, loginToken(client, base), null, null));
|
||||
app.setAdminConsole(AdminConsole.fromEnvironment(Map.of(
|
||||
"ADMIN_UI_ENABLED", "true", "ADMIN_UI_PASSWORD_FILE", passwordFile.toString(),
|
||||
"ADMIN_UI_PRIVATE_ORIGIN", "http://10.30.0.120:9001"), store));
|
||||
"ADMIN_UI_PRIVATE_ORIGIN", "http://10.30.0.120:9001",
|
||||
"DATA_DIR", root.resolve("data").toString()), store));
|
||||
int port = server.getAddress().getPort();
|
||||
String privatePage = rawRequest(port, "10.30.0.120:9001", "GET", "/login", "");
|
||||
if (!privatePage.startsWith("HTTP/1.1 200") || !privatePage.contains("Admin password"))
|
||||
@@ -258,6 +706,7 @@ public final class AdminConsoleTest {
|
||||
server.stop(0);
|
||||
s3Server.stop(0);
|
||||
executor.close();
|
||||
activity.close();
|
||||
store.close();
|
||||
try (var paths = Files.walk(root)) {
|
||||
for (Path path : paths.sorted(Comparator.reverseOrder()).toList()) Files.delete(path);
|
||||
|
||||
@@ -0,0 +1,179 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Proxy;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
public final class AdminOperationsTest {
|
||||
private static void check(boolean value, String message) {
|
||||
if (!value) throw new AssertionError(message);
|
||||
}
|
||||
|
||||
private static AdminBulkJobs.Snapshot await(AdminBulkJobs jobs, String id) throws Exception {
|
||||
for (int retry = 0; retry < 200; retry++) {
|
||||
AdminBulkJobs.Snapshot snapshot = jobs.get(id);
|
||||
if (snapshot.finished() != 0) return snapshot;
|
||||
Thread.sleep(25);
|
||||
}
|
||||
throw new AssertionError("Bulk job did not finish");
|
||||
}
|
||||
|
||||
private static void copySafety(DiskStore store) throws Exception {
|
||||
byte[] contents = "private destination".getBytes(StandardCharsets.UTF_8);
|
||||
store.setBucketOwnership("source-bucket", ObjectStorage.ObjectOwnership.OBJECT_WRITER);
|
||||
store.setPublicAccessBlock("source-bucket", ObjectStorage.PublicAccessBlock.open());
|
||||
store.put("source-bucket", "shared.txt", new ByteArrayInputStream(contents), contents.length,
|
||||
null, null, false, "text/plain", Map.of("purpose", "test"), Map.of("empty", ""),
|
||||
Map::of, Map.of(Acl.ALL_USERS, Integer.toString(Acl.READ)));
|
||||
AdminBulkJobs jobs = new AdminBulkJobs(store);
|
||||
var copy = jobs.start(new AdminBulkJobs.Spec("copy", "source-bucket", "shared.txt",
|
||||
"target-bucket", "private.txt", "", ""));
|
||||
check(await(jobs, copy.id()).succeeded() == 1, "Private bulk copy failed");
|
||||
try (var opened = store.open("target-bucket", "private.txt")) {
|
||||
check(opened.metadata().acl().isEmpty(), "Bulk copy carried source ACL into destination");
|
||||
check(opened.metadata().userMetadata().get("purpose").equals("test") &&
|
||||
opened.metadata().tags().containsKey("empty"), "Bulk copy lost metadata or tags");
|
||||
}
|
||||
|
||||
ObjectStorage corrupting = (ObjectStorage) Proxy.newProxyInstance(
|
||||
ObjectStorage.class.getClassLoader(), new Class<?>[]{ObjectStorage.class},
|
||||
(proxy, method, arguments) -> {
|
||||
if (method.getName().equals("open")) {
|
||||
try (var original = store.open((String) arguments[0], (String) arguments[1])) {
|
||||
byte[] corrupted = original.stream().readAllBytes();
|
||||
corrupted[0] ^= 1;
|
||||
return new ObjectStorage.OpenObject(original.metadata(), new ByteArrayInputStream(corrupted));
|
||||
}
|
||||
}
|
||||
try { return method.invoke(store, arguments); }
|
||||
catch (InvocationTargetException error) { throw error.getCause(); }
|
||||
});
|
||||
AdminBulkJobs corruptJobs = new AdminBulkJobs(corrupting);
|
||||
var corrupted = corruptJobs.start(new AdminBulkJobs.Spec("copy", "source-bucket", "shared.txt",
|
||||
"target-bucket", "corrupt.txt", "", ""));
|
||||
check(await(corruptJobs, corrupted.id()).failed() == 1, "Corrupted bulk copy was accepted");
|
||||
check(store.list("target-bucket", "corrupt.txt", "", 1, null).objects().isEmpty(),
|
||||
"Corrupted bulk copy installed an object");
|
||||
}
|
||||
|
||||
private static void emptyTagValue(DiskStore store) throws Exception {
|
||||
AdminActions.apply(store, "object-tag", Map.of("bucket", "target-bucket", "key", "copy-000",
|
||||
"operation", "add", "tag", "empty", "value", ""), Set.of(), null);
|
||||
check("".equals(store.tags("target-bucket", "copy-000").get("empty")),
|
||||
"Admin tag editor rejected an empty tag value");
|
||||
Map<String, String> tags = new HashMap<>();
|
||||
for (int i = 0; i < 10; i++) tags.put("tag-" + i, "");
|
||||
store.setTags("target-bucket", "copy-000", tags);
|
||||
try {
|
||||
AdminActions.apply(store, "object-tag", Map.of("bucket", "target-bucket", "key", "copy-000",
|
||||
"operation", "add", "tag", "extra", "value", ""), Set.of(), null);
|
||||
throw new AssertionError("Admin accepted more than ten tags");
|
||||
} catch (StoreException expected) {
|
||||
check(expected.status == 400 && expected.code.equals("InvalidTag"), "Unexpected tag failure");
|
||||
}
|
||||
AdminBulkJobs jobs = new AdminBulkJobs(store);
|
||||
var tag = jobs.start(new AdminBulkJobs.Spec("tag", "target-bucket", "copy-000",
|
||||
"", "", "extra", ""));
|
||||
check(await(jobs, tag.id()).failed() == 1, "Bulk job accepted more than ten tags");
|
||||
check(store.tags("target-bucket", "copy-000").equals(tags), "Rejected tagging changed the object");
|
||||
}
|
||||
|
||||
private static void staleEditorSave(DiskStore store) throws Exception {
|
||||
store.createBucket("editor-bucket");
|
||||
store.setVersioning("editor-bucket", ObjectStorage.VersioningState.ENABLED);
|
||||
byte[] original = "original".getBytes(StandardCharsets.UTF_8);
|
||||
ObjectStorage.Metadata metadata = store.put("editor-bucket", "note.txt",
|
||||
new ByteArrayInputStream(original), original.length, null, null, false, "text/plain");
|
||||
byte[] concurrent = "concurrent update".getBytes(StandardCharsets.UTF_8);
|
||||
ObjectStorage racing = (ObjectStorage) Proxy.newProxyInstance(
|
||||
ObjectStorage.class.getClassLoader(), new Class<?>[]{ObjectStorage.class},
|
||||
(proxy, method, arguments) -> {
|
||||
if (method.getName().equals("replaceVersion"))
|
||||
store.put("editor-bucket", "note.txt", new ByteArrayInputStream(concurrent),
|
||||
concurrent.length, null, null, false, "text/plain");
|
||||
try { return method.invoke(store, arguments); }
|
||||
catch (InvocationTargetException error) { throw error.getCause(); }
|
||||
});
|
||||
try {
|
||||
AdminTextEditor.save(racing, Map.of("bucket", "editor-bucket", "key", "note.txt",
|
||||
"originalVersion", metadata.versionId(), "originalSha256", SigV4.hex(metadata.sha256()),
|
||||
"content", "stale editor content"));
|
||||
throw new AssertionError("Stale editor save overwrote a concurrent update");
|
||||
} catch (StoreException expected) {
|
||||
check(expected.status == 409 && expected.code.equals("Conflict"), "Unexpected editor conflict");
|
||||
}
|
||||
try (var opened = store.open("editor-bucket", "note.txt")) {
|
||||
check(new String(opened.stream().readAllBytes(), StandardCharsets.UTF_8).equals("concurrent update"),
|
||||
"Editor replaced the concurrent update");
|
||||
}
|
||||
check(store.listVersions("editor-bucket", "note.txt", null, null, 10).entries().size() == 2,
|
||||
"Rejected editor save created a new version");
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
Path root = Files.createTempDirectory("admin-operations-");
|
||||
try {
|
||||
AdminAuditTrail audit = new AdminAuditTrail(root);
|
||||
audit.record("create-bucket", "source", "started", "127.0.0.1");
|
||||
audit.record("create-bucket", "source", "succeeded", "127.0.0.1");
|
||||
check(new AdminAuditTrail(root).recent(1).getFirst().result().equals("succeeded"),
|
||||
"Audit event did not survive restart");
|
||||
try (DiskStore store = new DiskStore(root.resolve("data"), 1024, 1024 * 1024)) {
|
||||
store.createBucket("source-bucket");
|
||||
store.createBucket("target-bucket");
|
||||
byte[] value = "hello".getBytes(StandardCharsets.UTF_8);
|
||||
for (int i = 0; i < 225; i++)
|
||||
store.put("source-bucket", "item-" + String.format("%03d", i),
|
||||
new ByteArrayInputStream(value), value.length, null, null, false,
|
||||
"text/plain", Map.of(), Map.of());
|
||||
S3Access access = new S3Access(store, "OWNERACCESSKEY123");
|
||||
AdminAccessCheck checker = new AdminAccessCheck(store, access,
|
||||
KeyScopes.unrestricted("OWNERACCESSKEY123"),
|
||||
Set.of("OWNERACCESSKEY123", "OTHERACCESSKEY123"), null);
|
||||
check(checker.check("OWNERACCESSKEY123", "read", "source-bucket", "item-000").allowed(),
|
||||
"Owner should read a current object");
|
||||
check(!checker.check("OTHERACCESSKEY123", "read", "source-bucket", "item-000").allowed(),
|
||||
"Unrelated key should not read an object");
|
||||
check(!checker.check("OWNERACCESSKEY123", "read", "source-bucket", "missing").allowed(),
|
||||
"Missing object should not read as allowed");
|
||||
AdminBulkJobs jobs = new AdminBulkJobs(store);
|
||||
var copy = jobs.start(new AdminBulkJobs.Spec("copy", "source-bucket", "item-",
|
||||
"target-bucket", "copy-", "", ""));
|
||||
check(await(jobs, copy.id()).succeeded() == 225, "Paged copy missed objects");
|
||||
try (var opened = store.open("target-bucket", "copy-224")) {
|
||||
check(new String(opened.stream().readAllBytes(), StandardCharsets.UTF_8).equals("hello"),
|
||||
"Copied data changed");
|
||||
}
|
||||
var tag = jobs.start(new AdminBulkJobs.Spec("tag", "target-bucket", "copy-",
|
||||
"", "", "group", "example"));
|
||||
check(await(jobs, tag.id()).succeeded() == 225, "Paged tag missed objects");
|
||||
check(store.tags("target-bucket", "copy-224").get("group").equals("example"),
|
||||
"Tag not persisted");
|
||||
var inventory = jobs.start(new AdminBulkJobs.Spec("inventory", "target-bucket", "copy-",
|
||||
"", "", "", ""));
|
||||
check(await(jobs, inventory.id()).processed() == 225 &&
|
||||
jobs.report(inventory.id()).contains("copy-224"), "Inventory report incomplete");
|
||||
var deletion = jobs.start(new AdminBulkJobs.Spec("delete", "source-bucket", "item-",
|
||||
"", "", "", ""));
|
||||
check(await(jobs, deletion.id()).succeeded() == 225 &&
|
||||
store.list("source-bucket", "", "", 10, null).objects().isEmpty(),
|
||||
"Paged delete missed objects");
|
||||
copySafety(store);
|
||||
emptyTagValue(store);
|
||||
staleEditorSave(store);
|
||||
System.out.println("Admin operations tests passed: audit, access, paged jobs");
|
||||
}
|
||||
} finally {
|
||||
try (var files = Files.walk(root)) {
|
||||
for (Path path : files.sorted(Comparator.reverseOrder()).toList()) Files.deleteIfExists(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.LocalDate;
|
||||
import java.time.ZoneOffset;
|
||||
|
||||
public final class BucketActivityTest {
|
||||
public static void main(String[] args) throws Exception {
|
||||
Path directory = Files.createTempDirectory("bucket-activity-test-");
|
||||
Path file = directory.resolve("activity.tsv");
|
||||
try {
|
||||
try (BucketActivity activity = new BucketActivity(file)) {
|
||||
activity.record("first-bucket", "GET");
|
||||
activity.record("first-bucket", "HEAD");
|
||||
activity.record("first-bucket", "PUT");
|
||||
activity.record("first-bucket", "OPTIONS");
|
||||
activity.record("invalid/bucket", "PUT");
|
||||
var today = activity.days("first-bucket").getLast();
|
||||
if (!today.date().equals(LocalDate.now(ZoneOffset.UTC)) ||
|
||||
today.reads() != 2 || today.writes() != 1)
|
||||
throw new AssertionError("Daily requests were counted incorrectly");
|
||||
activity.rename("first-bucket", "second-bucket");
|
||||
if (activity.days("first-bucket").getLast().total() != 0 ||
|
||||
activity.days("second-bucket").getLast().total() != 3)
|
||||
throw new AssertionError("Rename lost bucket activity");
|
||||
}
|
||||
try (BucketActivity reloaded = new BucketActivity(file)) {
|
||||
if (reloaded.days("second-bucket").getLast().total() != 3)
|
||||
throw new AssertionError("Bucket activity did not survive a restart");
|
||||
reloaded.remove("second-bucket");
|
||||
}
|
||||
try (BucketActivity reloaded = new BucketActivity(file)) {
|
||||
if (reloaded.days("second-bucket").getLast().total() != 0)
|
||||
throw new AssertionError("Deleted bucket activity reappeared");
|
||||
}
|
||||
System.out.println("Bucket activity tests passed");
|
||||
} finally {
|
||||
Files.deleteIfExists(file);
|
||||
Files.deleteIfExists(directory);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import java.net.URI;
|
||||
import java.sql.DriverManager;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
public final class ClusterBucketRenameTest {
|
||||
private static void check(boolean condition, String message) {
|
||||
if (!condition) throw new AssertionError(message);
|
||||
}
|
||||
|
||||
private static long count(java.sql.Connection connection, String table, String bucket) throws Exception {
|
||||
try (var query = connection.prepareStatement("SELECT count(*) FROM " + table + " WHERE bucket=?")) {
|
||||
query.setString(1, bucket);
|
||||
try (var rows = query.executeQuery()) {
|
||||
rows.next();
|
||||
return rows.getLong(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
if (args.length != 3) throw new IllegalArgumentException("Expected JDBC URL, user, password");
|
||||
String url = args[0], user = args[1], password = args[2];
|
||||
String configured = "rename-default", source = "rename-source", target = "rename-target";
|
||||
List<URI> nodes = List.of(URI.create("http://127.0.0.1:19091"),
|
||||
URI.create("http://127.0.0.1:19092"));
|
||||
try (var connection = DriverManager.getConnection(url, user, password)) {
|
||||
SchemaMigrator.prepare(connection, configured);
|
||||
try (var insert = connection.prepareStatement(
|
||||
"INSERT INTO cluster_nodes (node_id,host_id,endpoint,state) VALUES (?,?,?,'active')")) {
|
||||
for (URI node : nodes) {
|
||||
insert.setObject(1, UUID.randomUUID());
|
||||
insert.setObject(2, UUID.randomUUID());
|
||||
insert.setString(3, node.toString());
|
||||
insert.executeUpdate();
|
||||
}
|
||||
}
|
||||
}
|
||||
try (ClusterStore store = new ClusterStore(url, user, password, configured, nodes,
|
||||
"cluster-rename-test-token-1234567890123456", null, 1024, 8192, true)) {
|
||||
store.createBucket(source);
|
||||
store.createBucket("rename-taken");
|
||||
store.setBucketPolicy(source, "{\"Resource\":\"arn:aws:s3:::rename-source/*\"}");
|
||||
try (var connection = DriverManager.getConnection(url, user, password)) {
|
||||
UUID generation = UUID.randomUUID();
|
||||
try (var insert = connection.prepareStatement(
|
||||
"INSERT INTO cluster_object_versions (bucket,object_key,version_id,delete_marker," +
|
||||
"generation,length,modified,etag,sha256,content_type) VALUES (?,?,?,false,?,?,?,?,?,?)")) {
|
||||
insert.setString(1, source);
|
||||
insert.setString(2, "key.txt");
|
||||
insert.setString(3, UUID.randomUUID().toString());
|
||||
insert.setObject(4, generation);
|
||||
insert.setLong(5, 4);
|
||||
insert.setLong(6, System.currentTimeMillis());
|
||||
insert.setString(7, "0".repeat(32));
|
||||
insert.setBytes(8, new byte[32]);
|
||||
insert.setString(9, "text/plain");
|
||||
insert.executeUpdate();
|
||||
}
|
||||
try (var insert = connection.prepareStatement(
|
||||
"INSERT INTO cluster_object_heads (bucket,object_key,version_id) " +
|
||||
"SELECT bucket,object_key,version_id FROM cluster_object_versions WHERE bucket=?")) {
|
||||
insert.setString(1, source);
|
||||
insert.executeUpdate();
|
||||
}
|
||||
try (var insert = connection.prepareStatement(
|
||||
"INSERT INTO cluster_uploads (upload_id,bucket,object_key,content_type,created_at) " +
|
||||
"VALUES (?,?,?,?,?)")) {
|
||||
insert.setObject(1, UUID.randomUUID());
|
||||
insert.setString(2, source);
|
||||
insert.setString(3, "pending.txt");
|
||||
insert.setString(4, "text/plain");
|
||||
insert.setLong(5, System.currentTimeMillis());
|
||||
insert.executeUpdate();
|
||||
}
|
||||
}
|
||||
try {
|
||||
store.renameBucket(source, "rename-taken");
|
||||
throw new AssertionError("Duplicate target was accepted");
|
||||
} catch (StoreException expected) {
|
||||
check(expected.status == 409, "Wrong duplicate-name status");
|
||||
}
|
||||
check(store.bucket(source).name().equals(source), "Rejected rename changed source");
|
||||
store.renameBucket(source, target);
|
||||
check(store.bucket(target).policy().contains("arn:aws:s3:::rename-target/*"),
|
||||
"Policy did not follow the rename");
|
||||
try {
|
||||
store.bucket(source);
|
||||
throw new AssertionError("Old name remained available");
|
||||
} catch (StoreException expected) {
|
||||
check(expected.status == 404, "Wrong old-name response");
|
||||
}
|
||||
try (var connection = DriverManager.getConnection(url, user, password)) {
|
||||
for (String table : List.of("cluster_usage", "cluster_object_versions",
|
||||
"cluster_object_heads", "cluster_uploads")) {
|
||||
check(count(connection, table, target) == 1, table + " was not renamed");
|
||||
check(count(connection, table, source) == 0, table + " retained the old name");
|
||||
}
|
||||
}
|
||||
}
|
||||
try (ClusterStore store = new ClusterStore(url, user, password, configured, nodes,
|
||||
"cluster-rename-test-token-1234567890123456", null, 1024, 8192, true)) {
|
||||
check(store.bucket(target).name().equals(target), "Rename did not survive restart");
|
||||
}
|
||||
try {
|
||||
new ClusterStore(url, user, password, source, nodes,
|
||||
"cluster-rename-test-token-1234567890123456", null, 1024, 8192, true).close();
|
||||
throw new AssertionError("Old default bucket was recreated");
|
||||
} catch (java.io.IOException expected) {
|
||||
check(expected.getMessage().contains("S3_BUCKET"), "Wrong stale-config failure");
|
||||
}
|
||||
System.out.println("Cluster bucket rename tests passed");
|
||||
}
|
||||
}
|
||||
@@ -25,6 +25,16 @@ public final class ClusterIntegrationTest {
|
||||
String bucket = env.get("S3_BUCKET");
|
||||
byte[] stable = "acknowledged object survives node loss".getBytes(StandardCharsets.UTF_8);
|
||||
switch (args[0]) {
|
||||
case "status" -> {
|
||||
ClusterStore.ClusterStatus status = store.status();
|
||||
require(status.metadataWritable(), "Cluster status lost writable metadata primary");
|
||||
require(status.nodes().size() >= 3 &&
|
||||
status.nodes().stream().allMatch(ClusterStore.NodeStatus::reachable),
|
||||
"Cluster status missed reachable storage nodes");
|
||||
require(status.repair() != null && status.repair().report().scanned() >= 0,
|
||||
"Last repair report is missing");
|
||||
System.out.println("Cluster status test passed");
|
||||
}
|
||||
case "basic" -> {
|
||||
byte[] large = new byte[ClusterNode.MAX_SEGMENT + 37];
|
||||
for (int i = 0; i < large.length; i++) {
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.URI;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.sql.DriverManager;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
public final class ClusterMaintenanceTest {
|
||||
private static void check(boolean value, String message) {
|
||||
if (!value) throw new AssertionError(message);
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
if (args.length != 3) throw new IllegalArgumentException("Expected JDBC URL, user, password");
|
||||
Path root = Files.createTempDirectory("objectstore-maintenance-");
|
||||
List<ClusterNode> nodes = new ArrayList<>();
|
||||
List<HttpServer> servers = new ArrayList<>();
|
||||
List<URI> urls = new ArrayList<>();
|
||||
String token = "maintenance-test-node-token-0123456789";
|
||||
String repair = "maintenance-test-repair-token-0123456";
|
||||
try {
|
||||
for (int i = 0; i < 3; i++) {
|
||||
ClusterNode node = new ClusterNode(root.resolve("node" + i), token, repair, UUID.randomUUID());
|
||||
nodes.add(node);
|
||||
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
|
||||
servers.add(server);
|
||||
server.createContext("/", node::handle);
|
||||
server.start();
|
||||
urls.add(URI.create("http://127.0.0.1:" + server.getAddress().getPort()));
|
||||
}
|
||||
try (ClusterStore store = new ClusterStore(args[0], args[1], args[2], "maintenance-default",
|
||||
urls, token, repair, 1024, 8192, false)) {
|
||||
store.createBucket("maintenance-source");
|
||||
store.setVersioning("maintenance-source", ObjectStorage.VersioningState.ENABLED);
|
||||
byte[] value = new byte[] { 1, 2, 3, 4 };
|
||||
for (int i = 0; i < 2; i++)
|
||||
store.put("maintenance-source", "file", new ByteArrayInputStream(value), value.length,
|
||||
null, null, false, "application/octet-stream");
|
||||
String upload = store.create("maintenance-source", "part", "application/octet-stream");
|
||||
store.putPart(upload, "maintenance-source", "part", 1,
|
||||
new ByteArrayInputStream(value), value.length, null, null);
|
||||
check(store.activeUploads() == 1 && store.stagedBytes() == value.length,
|
||||
"Global multipart statistics excluded a non-default bucket");
|
||||
renameUnderContention(store, args);
|
||||
check(store.listVersions("maintenance-target", "", null, null, 10).entries().size() == 2,
|
||||
"Rename lost retained versions");
|
||||
try (var files = Files.walk(root.resolve("node0/segments"))) {
|
||||
for (Path path : files.filter(Files::isRegularFile).toList())
|
||||
Files.write(path, new byte[] { 9 });
|
||||
}
|
||||
var repaired = store.repairOnce();
|
||||
check(repaired.scanned() == 3 && repaired.restored() == 3 && repaired.unrecoverable() == 0,
|
||||
"Repair did not restore committed and staged replicas");
|
||||
var status = store.status();
|
||||
check(status.metadataWritable() && status.repair().state().equals("completed"),
|
||||
"Completed repair status unavailable");
|
||||
check(status.verifiedReplicas().values().stream().mapToLong(Long::longValue).sum() == 9,
|
||||
"Repair replica counts do not match committed and staged replicas");
|
||||
try (var opened = store.open("maintenance-target", "file")) {
|
||||
check(java.util.Arrays.equals(value, opened.stream().readAllBytes()), "Repaired data changed");
|
||||
}
|
||||
for (int i = 0; i < 3; i++) {
|
||||
try (var files = Files.walk(root.resolve("node" + i + "/segments"))) {
|
||||
for (Path path : files.filter(Files::isRegularFile).toList()) Files.delete(path);
|
||||
}
|
||||
}
|
||||
var lost = store.repairOnce();
|
||||
check(lost.scanned() == 3 && lost.unrecoverable() == 3,
|
||||
"Unrecoverable segments were omitted from repair report");
|
||||
check(store.status().verifiedReplicas().isEmpty(), "Old replica counts survived the next scan");
|
||||
try (ClusterStore second = new ClusterStore(args[0], args[1], args[2], "maintenance-default",
|
||||
urls, token, repair, 1024, 8192, false)) {
|
||||
ConditionalEditTest.exercise(store, second, "conditional-cluster-edit");
|
||||
}
|
||||
}
|
||||
System.out.println("Cluster maintenance tests passed: rename contention, multipart totals, repair status");
|
||||
} finally {
|
||||
for (HttpServer server : servers) server.stop(0);
|
||||
for (ClusterNode node : nodes) node.close();
|
||||
try (var files = Files.walk(root)) {
|
||||
for (Path path : files.sorted(java.util.Comparator.reverseOrder()).toList()) Files.deleteIfExists(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void renameUnderContention(ClusterStore store, String[] args) throws Exception {
|
||||
try (var executor = java.util.concurrent.Executors.newVirtualThreadPerTaskExecutor();
|
||||
var blocker = DriverManager.getConnection(args[0], args[1], args[2])) {
|
||||
blocker.setAutoCommit(false);
|
||||
try (var query = blocker.createStatement()) {
|
||||
query.execute("SELECT pg_advisory_xact_lock(6834071092784)");
|
||||
}
|
||||
var rename = executor.submit(() -> {
|
||||
store.renameBucket("maintenance-source", "maintenance-target");
|
||||
return null;
|
||||
});
|
||||
try {
|
||||
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5);
|
||||
boolean waiting = false;
|
||||
try (var observer = DriverManager.getConnection(args[0], args[1], args[2]);
|
||||
var query = observer.createStatement()) {
|
||||
while (System.nanoTime() < deadline && !waiting) {
|
||||
try (var rows = query.executeQuery("SELECT EXISTS (SELECT 1 FROM pg_locks " +
|
||||
"WHERE locktype='advisory' AND NOT granted)")) {
|
||||
rows.next();
|
||||
waiting = rows.getBoolean(1);
|
||||
}
|
||||
if (!waiting) Thread.sleep(10);
|
||||
}
|
||||
check(waiting, "Rename did not wait for the existing mutation lock");
|
||||
query.execute("SET statement_timeout='2s'");
|
||||
query.executeQuery("SELECT count(*) FROM cluster_buckets").close();
|
||||
}
|
||||
} finally {
|
||||
blocker.commit();
|
||||
}
|
||||
rename.get(5, TimeUnit.SECONDS);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
public final class ClusterRepairCliTest {
|
||||
public static void main(String[] args) throws Exception {
|
||||
try {
|
||||
ClusterRepair.main(new String[] { "--invalid" });
|
||||
throw new AssertionError("Cluster repair accepted invalid arguments");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
if (!expected.getMessage().equals("Usage: objectstore cluster-repair [--loop]"))
|
||||
throw new AssertionError("Cluster repair CLI entrypoint changed", expected);
|
||||
}
|
||||
System.out.println("Cluster repair CLI entrypoint passed");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
public final class ConditionalEditTest {
|
||||
private static void check(boolean value, String message) {
|
||||
if (!value) throw new AssertionError(message);
|
||||
}
|
||||
|
||||
private static ObjectStorage.Metadata put(ObjectStorage store, String bucket, String key, String text)
|
||||
throws Exception {
|
||||
byte[] bytes = text.getBytes(StandardCharsets.UTF_8);
|
||||
return store.put(bucket, key, new ByteArrayInputStream(bytes), bytes.length, null, null, false,
|
||||
"text/plain", Map.of("source", "editor-test"), Map.of("purpose", "test"));
|
||||
}
|
||||
|
||||
private static ObjectStorage.Metadata head(ObjectStorage store, String bucket, String key) throws Exception {
|
||||
try (var opened = store.open(bucket, key)) { return opened.metadata(); }
|
||||
}
|
||||
|
||||
private static boolean replace(ObjectStorage store, String bucket, String key,
|
||||
ObjectStorage.Metadata expected, String text) throws Exception {
|
||||
try {
|
||||
store.replaceVersion(bucket, key, text.getBytes(StandardCharsets.UTF_8), expected);
|
||||
return true;
|
||||
} catch (StoreException conflict) {
|
||||
check(conflict.status == 412, "Wrong conditional-edit rejection");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
static void exercise(ObjectStorage first, ObjectStorage second, String bucket) throws Exception {
|
||||
first.createBucket(bucket);
|
||||
put(first, bucket, "text", "original");
|
||||
first.setVersioning(bucket, ObjectStorage.VersioningState.ENABLED);
|
||||
check(replace(first, bucket, "text", head(first, bucket, "text"), "enabled"),
|
||||
"Could not edit an object written before versioning was enabled");
|
||||
var original = head(first, bucket, "text");
|
||||
CountDownLatch ready = new CountDownLatch(2);
|
||||
CountDownLatch start = new CountDownLatch(1);
|
||||
try (var executor = java.util.concurrent.Executors.newVirtualThreadPerTaskExecutor()) {
|
||||
var a = executor.submit(() -> {
|
||||
ready.countDown();
|
||||
start.await();
|
||||
return replace(first, bucket, "text", original, "first");
|
||||
});
|
||||
var b = executor.submit(() -> {
|
||||
ready.countDown();
|
||||
start.await();
|
||||
return replace(second, bucket, "text", original, "second");
|
||||
});
|
||||
check(ready.await(5, TimeUnit.SECONDS), "Editors did not start");
|
||||
start.countDown();
|
||||
check(a.get(10, TimeUnit.SECONDS) != b.get(10, TimeUnit.SECONDS),
|
||||
"Both concurrent editors succeeded, or neither did");
|
||||
}
|
||||
var current = head(first, bucket, "text");
|
||||
check(current.userMetadata().equals(original.userMetadata()) && current.tags().equals(original.tags()),
|
||||
"Conditional edit lost object attributes");
|
||||
check(!replace(second, bucket, "text", original, "stale"), "Stale edit overwrote newer data");
|
||||
second.setTags(bucket, "text", Map.of("purpose", "changed"));
|
||||
check(!replace(first, bucket, "text", current, "stale tags"), "Edit reverted a concurrent tag update");
|
||||
current = head(first, bucket, "text");
|
||||
second.setObjectAcl(bucket, "text", current.versionId(), Map.of("owner", "updated-owner"));
|
||||
check(!replace(first, bucket, "text", current, "stale ACL"), "Edit reverted a concurrent ACL update");
|
||||
current = head(first, bucket, "text");
|
||||
first.setVersioning(bucket, ObjectStorage.VersioningState.SUSPENDED);
|
||||
check(!replace(second, bucket, "text", current, "unsafe"), "Edit succeeded after versioning was suspended");
|
||||
put(first, bucket, "other", "old null version");
|
||||
var previousNull = head(first, bucket, "other");
|
||||
put(second, bucket, "other", "new null version");
|
||||
first.setVersioning(bucket, ObjectStorage.VersioningState.ENABLED);
|
||||
check(!replace(first, bucket, "other", previousNull, "stale null version"),
|
||||
"Reused null version ID bypassed the content check");
|
||||
first.delete(bucket, "text");
|
||||
check(!replace(second, bucket, "text", current, "resurrected"), "Edit replaced a delete marker");
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
Path root = Files.createTempDirectory("objectstore-conditional-edit-");
|
||||
try (DiskStore disk = new DiskStore(root, 1024, 8192)) {
|
||||
DiskBucketNames names = new DiskBucketNames(disk, new MultipartStore(disk));
|
||||
exercise(names, names, "conditional-edit");
|
||||
names.renameBucket("conditional-edit", "edited-rename");
|
||||
var expected = head(names, "edited-rename", "other");
|
||||
check(replace(names, "edited-rename", "other", expected, "renamed"),
|
||||
"Conditional edit did not resolve a renamed bucket");
|
||||
} finally {
|
||||
try (var files = Files.walk(root)) {
|
||||
for (Path path : files.sorted(java.util.Comparator.reverseOrder()).toList()) Files.deleteIfExists(path);
|
||||
}
|
||||
}
|
||||
System.out.println("Conditional edit tests passed: concurrent saves, versioning changes, renamed buckets");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public final class DiskBucketNamesTest {
|
||||
private static void check(boolean condition, String message) {
|
||||
if (!condition) throw new AssertionError(message);
|
||||
}
|
||||
|
||||
private static void missing(Runnable operation) {
|
||||
try {
|
||||
operation.run();
|
||||
throw new AssertionError("Old bucket name was still available");
|
||||
} catch (StoreException error) {
|
||||
check(error.status == 404, "Wrong missing-bucket response");
|
||||
}
|
||||
}
|
||||
|
||||
private static ObjectStorage.Metadata put(DiskBucketNames names, String bucket, String key, String value)
|
||||
throws Exception {
|
||||
byte[] bytes = value.getBytes(StandardCharsets.UTF_8);
|
||||
return names.put(bucket, key, new ByteArrayInputStream(bytes), bytes.length,
|
||||
null, null, false, "text/plain", Map.of("source", "test"), Map.of());
|
||||
}
|
||||
|
||||
private static void run(Path root) throws Exception {
|
||||
String old = "renamed-source", next = "renamed-target";
|
||||
String firstId;
|
||||
String uploadId;
|
||||
try (DiskStore disk = new DiskStore(root, 1024, 8192)) {
|
||||
disk.createBucket(old);
|
||||
DiskBucketNames names = new DiskBucketNames(disk, new MultipartStore(disk));
|
||||
names.setVersioning(old, ObjectStorage.VersioningState.ENABLED);
|
||||
firstId = put(names, old, "folder/item.txt", "one").versionId();
|
||||
put(names, old, "folder/item.txt", "two");
|
||||
names.setBucketPolicy(old, "{\"Resource\":\"arn:aws:s3:::renamed-source/*\"}");
|
||||
uploadId = names.create(old, "pending.txt", "text/plain");
|
||||
names.putPart(uploadId, old, "pending.txt", 1,
|
||||
new ByteArrayInputStream("part".getBytes(StandardCharsets.UTF_8)), 4, null, null);
|
||||
names.renameBucket(old, next);
|
||||
check(names.bucket(next).name().equals(next), "Renamed bucket is not visible");
|
||||
check(names.bucket(next).policy().contains("arn:aws:s3:::renamed-target/*"),
|
||||
"Policy did not follow the public name");
|
||||
check(names.listVersions(next, "", null, null, 100).entries().size() == 2,
|
||||
"Retained versions were lost");
|
||||
try (var opened = names.open(next, "folder/item.txt", firstId)) {
|
||||
check(new String(opened.stream().readAllBytes(), StandardCharsets.UTF_8).equals("one"),
|
||||
"Historical version changed");
|
||||
check(opened.metadata().bucket().equals(next), "Metadata exposed the physical name");
|
||||
}
|
||||
check(names.listUploads(next, "").size() == 1, "Multipart upload did not follow rename");
|
||||
missing(() -> { try { names.bucket(old); } catch (java.io.IOException error) {
|
||||
throw new RuntimeException(error); } });
|
||||
try {
|
||||
names.createBucket(old);
|
||||
throw new AssertionError("Hidden physical name was reused");
|
||||
} catch (StoreException error) {
|
||||
check(error.status == 409, "Wrong reused-name response");
|
||||
}
|
||||
}
|
||||
try (DiskStore disk = new DiskStore(root, 1024, 8192)) {
|
||||
DiskBucketNames names = new DiskBucketNames(disk, new MultipartStore(disk));
|
||||
names.ensureBucket(old);
|
||||
check(names.buckets().stream().map(ObjectStorage.Bucket::name).toList().equals(List.of(next)),
|
||||
"Public bucket name did not survive restart");
|
||||
check(names.listVersions(next, "", null, null, 100).entries().size() == 2,
|
||||
"Versions did not survive restart");
|
||||
var part = names.listParts(uploadId, next, "pending.txt", 0, 10).parts().getFirst();
|
||||
names.complete(uploadId, next, "pending.txt", List.of(new MultipartStorage.Part(1, part.etag())));
|
||||
try (var opened = names.open(next, "pending.txt")) {
|
||||
check(new String(opened.stream().readAllBytes(), StandardCharsets.UTF_8).equals("part"),
|
||||
"Multipart completion failed after restart");
|
||||
}
|
||||
names.renameBucket(next, "final-bucket");
|
||||
check(names.bucket("final-bucket").policy().contains("arn:aws:s3:::final-bucket/*"),
|
||||
"Repeated rename lost policy mapping");
|
||||
}
|
||||
try (DiskStore disk = new DiskStore(root, 1024, 8192)) {
|
||||
DiskBucketNames names = new DiskBucketNames(disk, new MultipartStore(disk));
|
||||
check(names.list("final-bucket", "", "", 100, null).objects().size() == 2,
|
||||
"Repeated rename lost objects");
|
||||
}
|
||||
}
|
||||
|
||||
private static void deleteRecovery(Path root) throws Exception {
|
||||
String source = "delete-source", target = "delete-target";
|
||||
try (DiskStore disk = new DiskStore(root, 1024, 8192)) {
|
||||
DiskBucketNames names = new DiskBucketNames(disk, new MultipartStore(disk));
|
||||
names.createBucket(source);
|
||||
names.renameBucket(source, target);
|
||||
String upload = names.create(target, "unfinished.txt", "text/plain");
|
||||
try {
|
||||
names.deleteBucket(target);
|
||||
throw new AssertionError("Bucket with multipart upload was deleted");
|
||||
} catch (StoreException expected) {
|
||||
check(expected.status == 409, "Wrong active-upload rejection");
|
||||
}
|
||||
names.abort(upload, target, "unfinished.txt");
|
||||
new BucketNameCatalog(disk).beginDelete(target, source);
|
||||
}
|
||||
try (DiskStore disk = new DiskStore(root, 1024, 8192)) {
|
||||
DiskBucketNames names = new DiskBucketNames(disk, new MultipartStore(disk));
|
||||
check(names.bucket(target).name().equals(target), "Interrupted deletion lost the bucket");
|
||||
new BucketNameCatalog(disk).beginDelete(target, source);
|
||||
disk.deleteBucket(source);
|
||||
}
|
||||
try (DiskStore disk = new DiskStore(root, 1024, 8192)) {
|
||||
DiskBucketNames names = new DiskBucketNames(disk, new MultipartStore(disk));
|
||||
check(names.buckets().stream().noneMatch(bucket -> bucket.name().equals(target)),
|
||||
"Interrupted deletion left a stale alias");
|
||||
check(!Files.exists(root.resolve("bucket-name-deletion.txt")), "Deletion journal was retained");
|
||||
names.createBucket(source);
|
||||
names.renameBucket(source, target);
|
||||
names.deleteBucket(target);
|
||||
names.createBucket(source);
|
||||
}
|
||||
try (DiskStore disk = new DiskStore(root, 1024, 8192)) {
|
||||
DiskBucketNames names = new DiskBucketNames(disk, new MultipartStore(disk));
|
||||
check(names.bucket(source).name().equals(source), "Deleted physical name could not be reused");
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
Path root = Files.createTempDirectory("objectstore-bucket-rename-");
|
||||
try {
|
||||
run(root);
|
||||
deleteRecovery(root);
|
||||
}
|
||||
finally {
|
||||
try (var files = Files.walk(root)) {
|
||||
for (Path path : files.sorted(java.util.Comparator.reverseOrder()).toList())
|
||||
Files.deleteIfExists(path);
|
||||
}
|
||||
}
|
||||
System.out.println("Bucket rename tests passed: versions, multipart, policy, restart");
|
||||
}
|
||||
}
|
||||
@@ -121,6 +121,15 @@ public final class FeatureTest {
|
||||
status(200, client.send(HttpTest.signedUriAs(ownReadable,
|
||||
"GET", new byte[0], Map.of(), LIMITED, LIMITED_SECRET), HttpResponse.BodyHandlers.ofString()));
|
||||
var trafficAfter = metrics.dataSnapshot();
|
||||
long metricsDeadline = System.nanoTime() + 2_000_000_000L;
|
||||
while (System.nanoTime() < metricsDeadline &&
|
||||
(trafficAfter.requests() - trafficBefore.requests() < 2 ||
|
||||
trafficAfter.inboundBytes() - trafficBefore.inboundBytes() < content.length ||
|
||||
trafficAfter.outboundBytes() - trafficBefore.outboundBytes() < content.length ||
|
||||
trafficAfter.inFlight() != 0)) {
|
||||
Thread.sleep(10);
|
||||
trafficAfter = metrics.dataSnapshot();
|
||||
}
|
||||
if (trafficAfter.requests() - trafficBefore.requests() != 2 ||
|
||||
trafficAfter.inboundBytes() - trafficBefore.inboundBytes() < content.length ||
|
||||
trafficAfter.outboundBytes() - trafficBefore.outboundBytes() < content.length ||
|
||||
|
||||
@@ -318,6 +318,14 @@ public final class HttpTest {
|
||||
if (!java.util.Arrays.equals(body, read.body())) throw new AssertionError("Streaming upload mismatch");
|
||||
status(204, client.send(signedUri(object, "DELETE", new byte[0], Map.of()),
|
||||
HttpResponse.BodyHandlers.ofByteArray()));
|
||||
for (String size : new String[] {"8000000000000000", "ffffffffffffffff"}) {
|
||||
byte[] oversized = (size + ";chunk-signature=" + "0".repeat(64) + "\r\n")
|
||||
.getBytes(StandardCharsets.US_ASCII);
|
||||
status(400, client.send(request.PUT(HttpRequest.BodyPublishers.ofByteArray(oversized))
|
||||
.build(), HttpResponse.BodyHandlers.ofByteArray()));
|
||||
}
|
||||
status(404, client.send(signedUri(object, "GET", new byte[0], Map.of()),
|
||||
HttpResponse.BodyHandlers.ofByteArray()));
|
||||
}
|
||||
|
||||
private static void testStreamingTrailer(HttpClient client, String base) throws Exception {
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
import java.io.IOException;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.ServerSocket;
|
||||
import java.net.Socket;
|
||||
import java.net.SocketException;
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
public final class NodeHttpTest {
|
||||
private static final String TOKEN = "local-node-http-test-token-0123456789";
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
try (HttpClient client = HttpClient.newBuilder().version(HttpClient.Version.HTTP_1_1).build()) {
|
||||
stalledBody(client, false);
|
||||
stalledBody(client, true);
|
||||
oversizedBody(client);
|
||||
interruptedBody(client);
|
||||
stalledProbe(client);
|
||||
nodeResponseLimits(client);
|
||||
}
|
||||
System.out.println("Node HTTP tests passed: total deadlines, cancellation, bounded responses, interruption");
|
||||
}
|
||||
|
||||
private static void stalledBody(HttpClient client, boolean discard) throws Exception {
|
||||
try (StalledResponse server = new StalledResponse(1)) {
|
||||
HttpRequest request = HttpRequest.newBuilder(server.uri()).timeout(Duration.ofMillis(500)).GET().build();
|
||||
long started = System.nanoTime();
|
||||
expectFailure(() -> {
|
||||
if (discard) NodeHttp.discard(client, request);
|
||||
else NodeHttp.bytes(client, request, 32);
|
||||
}, "timed out");
|
||||
require(server.sent.await(1, TimeUnit.SECONDS), "Request did not reach the stalled response body");
|
||||
require(System.nanoTime() - started < TimeUnit.SECONDS.toNanos(3), "Body timeout exceeded its deadline");
|
||||
server.requireCancelled();
|
||||
}
|
||||
}
|
||||
|
||||
private static void oversizedBody(HttpClient client) throws Exception {
|
||||
try (StalledResponse server = new StalledResponse(33)) {
|
||||
HttpRequest request = HttpRequest.newBuilder(server.uri()).timeout(Duration.ofSeconds(5)).GET().build();
|
||||
long started = System.nanoTime();
|
||||
expectFailure(() -> NodeHttp.bytes(client, request, 32), "too large");
|
||||
require(System.nanoTime() - started < TimeUnit.SECONDS.toNanos(3), "Oversized body waited for EOF");
|
||||
server.requireCancelled();
|
||||
}
|
||||
}
|
||||
|
||||
private static void interruptedBody(HttpClient client) throws Exception {
|
||||
try (StalledResponse server = new StalledResponse(1)) {
|
||||
HttpRequest request = HttpRequest.newBuilder(server.uri()).timeout(Duration.ofSeconds(5)).GET().build();
|
||||
CompletableFuture<Boolean> interrupted = new CompletableFuture<>();
|
||||
Thread worker = Thread.ofVirtual().start(() -> {
|
||||
try {
|
||||
NodeHttp.bytes(client, request, 32);
|
||||
interrupted.complete(false);
|
||||
} catch (IOException expected) {
|
||||
interrupted.complete(Thread.currentThread().isInterrupted());
|
||||
}
|
||||
});
|
||||
try {
|
||||
require(server.sent.await(2, TimeUnit.SECONDS), "Interrupted request never received headers");
|
||||
worker.interrupt();
|
||||
require(interrupted.get(2, TimeUnit.SECONDS), "Node request did not preserve interruption");
|
||||
server.requireCancelled();
|
||||
} finally {
|
||||
worker.interrupt();
|
||||
worker.join(2000);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void stalledProbe(HttpClient client) throws Exception {
|
||||
try (StalledResponse server = new StalledResponse(1)) {
|
||||
long started = System.nanoTime();
|
||||
expectFailure(() -> NodeClient.probe(server.uri(), TOKEN, client), "timed out");
|
||||
require(System.nanoTime() - started < TimeUnit.SECONDS.toNanos(4), "Identity body ignored probe timeout");
|
||||
server.requireCancelled();
|
||||
}
|
||||
}
|
||||
|
||||
private static void nodeResponseLimits(HttpClient http) throws Exception {
|
||||
UUID nodeId = UUID.randomUUID();
|
||||
UUID hostId = UUID.randomUUID();
|
||||
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
|
||||
server.createContext("/identity", exchange -> {
|
||||
byte[] identity = (nodeId + " " + hostId).getBytes(StandardCharsets.US_ASCII);
|
||||
exchange.sendResponseHeaders(200, identity.length);
|
||||
exchange.getResponseBody().write(identity);
|
||||
exchange.close();
|
||||
});
|
||||
server.createContext("/segments", exchange -> {
|
||||
byte[] body = new byte[exchange.getRequestURI().getRawQuery() == null ? 6 : 70001];
|
||||
exchange.sendResponseHeaders(200, 0);
|
||||
try (var output = exchange.getResponseBody()) { output.write(body); }
|
||||
});
|
||||
server.start();
|
||||
try {
|
||||
URI uri = URI.create("http://127.0.0.1:" + server.getAddress().getPort());
|
||||
NodeClient client = new NodeClient(List.of(new NodeClient.Node(nodeId, hostId, uri)), TOKEN, TOKEN, http);
|
||||
expectFailure(() -> client.get(0, UUID.randomUUID(), 4, SigV4.hash(new byte[4])), "too large");
|
||||
expectFailure(() -> client.inventory(0, "00", null), "too large");
|
||||
} finally {
|
||||
server.stop(0);
|
||||
}
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
private interface Request { void run() throws IOException; }
|
||||
|
||||
private static void expectFailure(Request request, String message) throws IOException {
|
||||
try {
|
||||
request.run();
|
||||
throw new AssertionError("Invalid node response was accepted");
|
||||
} catch (IOException expected) {
|
||||
require(expected.getMessage().contains(message), "Unexpected failure: " + expected);
|
||||
}
|
||||
}
|
||||
|
||||
private static void require(boolean condition, String message) {
|
||||
if (!condition) throw new AssertionError(message);
|
||||
}
|
||||
|
||||
private static final class StalledResponse implements AutoCloseable {
|
||||
private final ServerSocket server = new ServerSocket();
|
||||
private final CountDownLatch sent = new CountDownLatch(1);
|
||||
private final CompletableFuture<Boolean> cancelled = new CompletableFuture<>();
|
||||
private final Thread worker;
|
||||
private volatile Socket peer;
|
||||
|
||||
StalledResponse(int bodyBytes) throws IOException {
|
||||
server.bind(new InetSocketAddress("127.0.0.1", 0));
|
||||
worker = Thread.ofVirtual().start(() -> serve(bodyBytes));
|
||||
}
|
||||
|
||||
URI uri() { return URI.create("http://127.0.0.1:" + server.getLocalPort()); }
|
||||
|
||||
private void serve(int bodyBytes) {
|
||||
try (Socket socket = server.accept()) {
|
||||
peer = socket;
|
||||
socket.setSoTimeout(6000);
|
||||
var input = socket.getInputStream();
|
||||
int tail = 0;
|
||||
int count = 0;
|
||||
while (tail != 0x0d0a0d0a && count++ < 16384) {
|
||||
int next = input.read();
|
||||
if (next < 0) throw new IOException("Request ended before headers");
|
||||
tail = (tail << 8) | next;
|
||||
}
|
||||
var output = socket.getOutputStream();
|
||||
output.write("HTTP/1.1 200 OK\r\nContent-Length: 100000\r\n\r\n".getBytes(StandardCharsets.US_ASCII));
|
||||
output.write(new byte[bodyBytes]);
|
||||
output.flush();
|
||||
sent.countDown();
|
||||
try { cancelled.complete(input.read() == -1); }
|
||||
catch (SocketException closed) { cancelled.complete(true); }
|
||||
} catch (Exception error) {
|
||||
cancelled.completeExceptionally(error);
|
||||
}
|
||||
}
|
||||
|
||||
void requireCancelled() throws Exception {
|
||||
require(cancelled.get(2, TimeUnit.SECONDS), "Cancelled body left its connection open");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws Exception {
|
||||
server.close();
|
||||
if (peer != null) peer.close();
|
||||
worker.join(2000);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Proxy;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.util.Comparator;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public final class RequestCoordinationTest {
|
||||
private static final String PASSWORD = "a-long-admin-password-for-tests";
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
Path root = Files.createTempDirectory("request-coordination-");
|
||||
CountDownLatch readStarted = new CountDownLatch(1);
|
||||
CountDownLatch releaseRead = new CountDownLatch(1);
|
||||
AtomicBoolean blockReady = new AtomicBoolean();
|
||||
AtomicReference<StoreOperations.Action> bucketAction = new AtomicReference<>();
|
||||
var executor = Executors.newVirtualThreadPerTaskExecutor();
|
||||
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 16);
|
||||
HttpServer admin = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 16);
|
||||
try (DiskStore disk = new DiskStore(root.resolve("data"), 1024, 4096)) {
|
||||
DiskBucketNames names = new DiskBucketNames(disk, new MultipartStore(disk));
|
||||
ObjectStorage store = (ObjectStorage) Proxy.newProxyInstance(
|
||||
ObjectStorage.class.getClassLoader(), new Class<?>[] {ObjectStorage.class},
|
||||
(proxy, method, arguments) -> {
|
||||
if (method.getName().equals("bucket")) {
|
||||
StoreOperations.Action action = bucketAction.getAndSet(null);
|
||||
if (action != null) action.run();
|
||||
}
|
||||
if (method.getName().equals("ready") && blockReady.get()) {
|
||||
readStarted.countDown();
|
||||
if (!releaseRead.await(5, TimeUnit.SECONDS))
|
||||
throw new IOException("Read was not released");
|
||||
}
|
||||
try {
|
||||
return method.invoke(names, arguments);
|
||||
} catch (InvocationTargetException error) {
|
||||
throw error.getCause();
|
||||
}
|
||||
});
|
||||
Path password = root.resolve("password");
|
||||
Files.writeString(password, PASSWORD);
|
||||
AdminConsole console = AdminConsole.fromEnvironment(Map.of(
|
||||
"ADMIN_UI_ENABLED", "true", "ADMIN_UI_PASSWORD_FILE", password.toString(),
|
||||
"DATA_DIR", root.resolve("data").toString()), store);
|
||||
Main app = new Main(store, names, new SigV4("TESTACCESSKEY123",
|
||||
"test-secret-key-that-is-at-least-32-characters", "us-east-1", Clock.systemUTC()),
|
||||
"objects");
|
||||
app.setAdminConsole(console);
|
||||
server.setExecutor(executor);
|
||||
server.createContext("/", app::handle);
|
||||
admin.setExecutor(executor);
|
||||
admin.createContext("/", app::handleAdmin);
|
||||
server.start();
|
||||
admin.start();
|
||||
try (HttpClient client = HttpClient.newHttpClient()) {
|
||||
String base = "http://127.0.0.1:" + server.getAddress().getPort();
|
||||
String adminBase = "http://127.0.0.1:" + admin.getAddress().getPort();
|
||||
String loginPage = send(client, request(adminBase + AdminConsole.PATH + "/login").GET()).body();
|
||||
HttpResponse<String> login = send(client,
|
||||
form(adminBase + AdminConsole.PATH + "/login", "password=" + PASSWORD +
|
||||
"&csrf=" + csrf(loginPage)));
|
||||
status(login, 303);
|
||||
String cookie = login.headers().firstValue("Set-Cookie").orElseThrow().split(";", 2)[0];
|
||||
String overview = send(client, request(adminBase + AdminConsole.PATH + "/overview")
|
||||
.header("Cookie", cookie).GET()).body();
|
||||
String token = csrf(overview);
|
||||
verifyRenameIsolation(client, base, adminBase, cookie, token,
|
||||
blockReady, readStarted, releaseRead);
|
||||
verifyDiagnostics(client, base, adminBase, cookie);
|
||||
verifyRevocation(client, base, app, names, disk, root, bucketAction);
|
||||
}
|
||||
} finally {
|
||||
releaseRead.countDown();
|
||||
server.stop(0);
|
||||
admin.stop(0);
|
||||
executor.close();
|
||||
try (var files = Files.walk(root)) {
|
||||
for (Path file : files.sorted(Comparator.reverseOrder()).toList()) Files.delete(file);
|
||||
}
|
||||
}
|
||||
System.out.println("Request coordination tests passed");
|
||||
}
|
||||
|
||||
private static void verifyRenameIsolation(HttpClient client, String base, String adminBase,
|
||||
String cookie, String token, AtomicBoolean blockReady,
|
||||
CountDownLatch readStarted, CountDownLatch releaseRead)
|
||||
throws Exception {
|
||||
blockReady.set(true);
|
||||
var heldRead = client.sendAsync(request(base + "/ready").GET().build(),
|
||||
HttpResponse.BodyHandlers.ofString());
|
||||
if (!readStarted.await(2, TimeUnit.SECONDS)) throw new AssertionError("Read did not start");
|
||||
String url = adminBase + AdminConsole.PATH + "/action/rename-bucket";
|
||||
status(send(client, form(url, "bucket=objects&newName=renamed&confirm=objects")), 303);
|
||||
status(send(client, form(url, "bucket=objects&newName=renamed&confirm=objects&csrf=invalid")
|
||||
.header("Cookie", cookie)), 403);
|
||||
status(send(client, form(url, "bucket=objects&newName=renamed&confirm=objects&csrf=" + token)
|
||||
.header("Cookie", cookie)), 409);
|
||||
status(send(client, request(base + "/health").GET()), 200);
|
||||
var rename = client.sendAsync(form(url, "bucket=objects&newName=renamed&confirm=objects&csrf=" + token)
|
||||
.header("Cookie", cookie).build(), HttpResponse.BodyHandlers.ofString());
|
||||
Thread.sleep(100);
|
||||
if (rename.isDone()) throw new AssertionError("Rename did not wait for the active storage request");
|
||||
blockReady.set(false);
|
||||
releaseRead.countDown();
|
||||
status(heldRead.get(2, TimeUnit.SECONDS), 200);
|
||||
status(rename.get(2, TimeUnit.SECONDS), 303);
|
||||
}
|
||||
|
||||
private static void verifyDiagnostics(HttpClient client, String base, String adminBase,
|
||||
String cookie) throws Exception {
|
||||
HttpResponse<String> signed = client.send(HttpTest.signedUri(
|
||||
URI.create(base + "/renamed/missing"), "GET", new byte[0], Map.of()),
|
||||
HttpResponse.BodyHandlers.ofString());
|
||||
status(signed, 404);
|
||||
HttpResponse<String> failed = send(client, request(base + "/other/missing")
|
||||
.header("Authorization", "invalid").GET());
|
||||
status(failed, 403);
|
||||
String requestId = failed.headers().firstValue("x-amz-request-id").orElseThrow();
|
||||
String page = "";
|
||||
for (int attempt = 0; attempt < 20; attempt++) {
|
||||
page = send(client, request(adminBase + AdminConsole.PATH + "/diagnostics")
|
||||
.header("Cookie", cookie).GET()).body();
|
||||
if (page.contains(requestId)) break;
|
||||
Thread.sleep(10);
|
||||
}
|
||||
var row = Pattern.compile("<tr>(?:(?!</tr>).)*" + Pattern.quote(requestId) +
|
||||
"(?:(?!</tr>).)*</tr>", Pattern.DOTALL).matcher(page);
|
||||
if (!row.find() || !row.group().contains("Service") || row.group().contains("renamed"))
|
||||
throw new AssertionError("Failed authentication inherited another request's bucket or operation");
|
||||
}
|
||||
|
||||
private static void verifyRevocation(HttpClient client, String base, Main app, DiskBucketNames store,
|
||||
DiskStore disk, Path root,
|
||||
AtomicReference<StoreOperations.Action> bucketAction) throws Exception {
|
||||
Path master = root.resolve("master-key");
|
||||
Files.writeString(master, "0123456789abcdef".repeat(4));
|
||||
ManagedCredentials managed = ManagedCredentials.fromEnvironment(Map.of(
|
||||
"S3_MANAGED_KEYS_MASTER_FILE", master.toString(), "DATA_DIR", root.resolve("data").toString()),
|
||||
disk, Set.of("TESTACCESSKEY123"));
|
||||
ManagedCredentials.Key key = managed.create("renamed", "private/", Set.of("read"));
|
||||
app.setManagedCredentials(managed);
|
||||
byte[] value = {1};
|
||||
store.put("renamed", "outside.txt", new java.io.ByteArrayInputStream(value), value.length,
|
||||
SigV4.hex(SigV4.hash(value)), null, true, "text/plain");
|
||||
store.setBucketPolicy("renamed", "{\"Version\":\"2012-10-17\",\"Statement\":[{" +
|
||||
"\"Effect\":\"Allow\",\"Principal\":\"" + key.id() + "\",\"Action\":\"s3:GetObject\"," +
|
||||
"\"Resource\":\"arn:aws:s3:::renamed/*\"}]}");
|
||||
URI object = URI.create(base + "/renamed/outside.txt");
|
||||
status(client.send(HttpTest.signedUriAs(object, "GET", new byte[0], Map.of(), key.id(), key.secret()),
|
||||
HttpResponse.BodyHandlers.ofString()), 403);
|
||||
bucketAction.set(() -> managed.remove(key.id()));
|
||||
status(client.send(HttpTest.signedUriAs(object, "GET", new byte[0], Map.of(), key.id(), key.secret()),
|
||||
HttpResponse.BodyHandlers.ofString()), 403);
|
||||
if (managed.contains(key.id())) throw new AssertionError("Key revocation did not happen during request");
|
||||
}
|
||||
|
||||
private static HttpRequest.Builder request(String url) {
|
||||
return HttpRequest.newBuilder(URI.create(url)).timeout(Duration.ofSeconds(2));
|
||||
}
|
||||
|
||||
private static HttpRequest.Builder form(String url, String body) {
|
||||
return request(url).header("Content-Type", "application/x-www-form-urlencoded")
|
||||
.POST(HttpRequest.BodyPublishers.ofString(body));
|
||||
}
|
||||
|
||||
private static HttpResponse<String> send(HttpClient client, HttpRequest.Builder request)
|
||||
throws Exception {
|
||||
return client.send(request.build(), HttpResponse.BodyHandlers.ofString());
|
||||
}
|
||||
|
||||
private static String csrf(String page) {
|
||||
var token = Pattern.compile("name=csrf value='([A-Za-z0-9_-]{43})'").matcher(page);
|
||||
if (!token.find()) throw new AssertionError("Missing CSRF token");
|
||||
return token.group(1);
|
||||
}
|
||||
|
||||
private static void status(HttpResponse<?> response, int expected) {
|
||||
if (response.statusCode() != expected)
|
||||
throw new AssertionError("Expected " + expected + ", got " + response.statusCode());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package cloud.lunarsky.store;
|
||||
|
||||
public final class RequestDiagnosticsTest {
|
||||
public static void main(String[] args) {
|
||||
RequestDiagnostics diagnostics = new RequestDiagnostics();
|
||||
diagnostics.record("request-1", "Object GET", "photos", 200, 4_000_000);
|
||||
diagnostics.record("request-2", "Object PUT", "photos", 403, 16_000_000);
|
||||
diagnostics.record("request-3", "Object GET", "a".repeat(200), 503, 700_000_000);
|
||||
RequestDiagnostics.Snapshot result = diagnostics.snapshot();
|
||||
if (result.requests() != 3 || result.clientErrors() != 1 || result.serverErrors() != 1 ||
|
||||
result.p50Millis() != 25 || result.p95Millis() != 1000 || result.p99Millis() != 1000 ||
|
||||
result.recentFailures().size() != 2 ||
|
||||
!result.recentFailures().get(0).requestId().equals("request-3") ||
|
||||
!result.recentFailures().get(0).bucket().equals("—") ||
|
||||
!result.recentFailures().get(1).bucket().equals("photos"))
|
||||
throw new AssertionError("Rolling request diagnostics changed");
|
||||
for (int index = 0; index < 70; index++)
|
||||
diagnostics.record("bounded-" + index, "Object GET", "photos", 404, 1_000_000);
|
||||
RequestDiagnostics.Snapshot bounded = diagnostics.snapshot();
|
||||
if (bounded.recentFailures().size() != 64 ||
|
||||
!bounded.recentFailures().get(0).requestId().equals("bounded-69") ||
|
||||
!bounded.recentFailures().get(63).requestId().equals("bounded-6"))
|
||||
throw new AssertionError("Recent failure history is not bounded");
|
||||
System.out.println("Request diagnostics tests passed");
|
||||
}
|
||||
}
|
||||