From 3c739deb090a364344c904b34f109599ca584eae Mon Sep 17 00:00:00 2001 From: LunarSkyOSS Date: Sat, 7 Nov 2026 11:00:16 +0100 Subject: [PATCH] Refactor complex admin and storage methods --- Dockerfile | 1 + TESTS.md | 1 + admin-ui/performance.js | 125 +- scripts/test.sh | 1 + .../lunarsky/store/AdminAccessCheck.java | 72 +- src/cloud/lunarsky/store/AdminActions.java | 305 ++-- src/cloud/lunarsky/store/AdminBulkJobs.java | 77 +- .../lunarsky/store/AdminOperationsPages.java | 74 +- src/cloud/lunarsky/store/DiskStore.java | 112 +- .../lunarsky/store/RequestDiagnostics.java | 62 +- .../lunarsky/store/AdminBulkJobsTest.java | 137 ++ .../lunarsky/store/AdminConsoleTest.java | 1377 +++++++++-------- .../store/RequestDiagnosticsTest.java | 40 +- 13 files changed, 1434 insertions(+), 950 deletions(-) create mode 100644 test/cloud/lunarsky/store/AdminBulkJobsTest.java diff --git a/Dockerfile b/Dockerfile index 5ff3729..d93a16d 100644 --- a/Dockerfile +++ b/Dockerfile @@ -20,6 +20,7 @@ RUN java --add-modules jdk.httpserver,java.net.http -cp /out:/tmp/hash4j.jar clo RUN java -cp /out:/tmp/hash4j.jar cloud.lunarsky.store.RequestDiagnosticsTest RUN java -cp /out:/tmp/hash4j.jar cloud.lunarsky.store.BucketActivityTest RUN java --add-modules jdk.httpserver -cp /out:/tmp/hash4j.jar cloud.lunarsky.store.AdminOperationsTest +RUN java --add-modules jdk.httpserver -cp /out:/tmp/hash4j.jar cloud.lunarsky.store.AdminBulkJobsTest RUN java --add-modules jdk.httpserver,java.net.http -cp /out:/tmp/hash4j.jar cloud.lunarsky.store.FeatureTest RUN java -cp /out:/tmp/hash4j.jar cloud.lunarsky.store.EncryptedVolumeTest RUN java --add-modules jdk.httpserver,java.net.http -cp /out:/tmp/hash4j.jar cloud.lunarsky.store.NodeHttpTest diff --git a/TESTS.md b/TESTS.md index 2cbd6cd..6c5be52 100644 --- a/TESTS.md +++ b/TESTS.md @@ -26,6 +26,7 @@ The script compiles the source and test programs into `out/classes`, then runs: | `ClientLimitsTest` | Disabled defaults, trusted-proxy address validation, ignored untrusted headers, per-IP request refusal, and paced response bytes. | | `AdminConsoleTest` | Admin sign-in, CSRF and origin checks, bucket and object changes, public-access confirmations, live metrics, encrypted managed-key persistence, scoped reads and listings, and key revocation. | | `AdminOperationsTest` | Persisted admin events, effective access checks, stale editor conflicts, and paged copy, tag, inventory, and delete jobs; private copy ACLs, checksum verification, and tag validation. | +| `AdminBulkJobsTest` | Exact job limits, truncated and stalled pagination, cancellation, and bounded per-object error reports. | | `EncryptedVolumeTest` | Marker acceptance and refusal when the configured encrypted directory is missing, mismatched, or a symlink. | | `NodeHttpTest` | Total node response deadlines, stalled-body cancellation, response-size limits, and interruption. | | `ClusterNodeTest` | Node identity and locking, authenticated segment transfers, checksum rejection, repair authorization, inventory and guarded deletion, and restart cleanup. | diff --git a/admin-ui/performance.js b/admin-ui/performance.js index 74f02f3..483a5be 100644 --- a/admin-ui/performance.js +++ b/admin-ui/performance.js @@ -72,63 +72,86 @@ ? history.filter(point => point.cpu !== null) : history; } + function showMemory(sample) { + const rss = sample.rssBytes >= 0 ? sample.rssBytes : sample.heapBytes + sample.nonHeapBytes; + if (sample.rssBytes < 0 && !memoryFallback) { + memoryFallback = true; + document.querySelector('#perf-ram').previousElementSibling.textContent = 'JVM memory used'; + charts[3].series = [ + { type: 'line', x: 'time', y: 'memory', name: 'JVM used MiB' }, + { type: 'line', x: 'time', y: 'heap', name: 'Heap MiB' } + ]; + } + show('perf-ram', bytes(rss)); + return rss; + } + + function cpuUsage(sample, before, seconds) { + if (!(sample.cpuNanos >= 0 && before.cpuNanos >= 0)) return null; + return Math.max(0, Math.min(100, + (sample.cpuNanos - before.cpuNanos) / + (seconds * 1e9 * Math.max(1, sample.processors)) * 100)); + } + + function samplePoint(sample, before, seconds, rss) { + const errors = counterDelta(sample, before, 'failures4xx') + + counterDelta(sample, before, 'failures5xx'); + return { + time: new Date().toLocaleTimeString(), + requests: counterDelta(sample, before, 'requests') / seconds, + errors: errors / seconds, + inbound: counterDelta(sample, before, 'inboundBytes') / seconds / 1024, + outbound: counterDelta(sample, before, 'outboundBytes') / seconds / 1024, + cpu: cpuUsage(sample, before, seconds), + memory: rss / 1048576, + heap: sample.heapBytes / 1048576, + seconds + }; + } + + function showCpuAverage() { + const cpuPoints = history.filter(entry => entry.cpu !== null); + const cpuSeconds = cpuPoints.reduce((total, entry) => total + entry.seconds, 0); + show('perf-cpu', cpuSeconds ? + (cpuPoints.reduce((total, entry) => total + entry.cpu * entry.seconds, 0) / + cpuSeconds).toFixed(1) + '%' : '—'); + } + + function showInterval(sample, before, point) { + const requests = counterDelta(sample, before, 'requests'); + show('perf-rps', rate(point.requests)); + show('perf-latency', requests ? + (counterDelta(sample, before, 'durationNanos') / requests / 1e6).toFixed(1) + ' ms' : '—'); + show('perf-inbound', bytes(point.inbound * 1024, '/s')); + show('perf-outbound', bytes(point.outbound * 1024, '/s')); + showCpuAverage(); + updateCharts(); + } + + function recordSample(sample, now, rss) { + if (!previous) return; + const before = previous.sample; + if (sample.requests < before.requests) { + history.length = 0; + updateCharts(); + } + if (!(sample.requests >= before.requests)) return; + const seconds = (now - previous.at) / 1000; + if (!(seconds > 0.1)) return; + const point = samplePoint(sample, before, seconds, rss); + history.push(point); + if (history.length > 60) history.shift(); + showInterval(sample, before, point); + } + function accept(sample) { if (!active || document.hidden) return; try { const now = performance.now(); - const rss = 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)); + const rss = showMemory(sample); 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(); - } - } + recordSample(sample, now, rss); previous = { sample, at: now }; showState(history.length ? 'Live · one-second samples' : 'Collecting a second sample…', history.length ? 'live' : 'loading'); diff --git a/scripts/test.sh b/scripts/test.sh index dcfa6d7..a78c17c 100644 --- a/scripts/test.sh +++ b/scripts/test.sh @@ -18,6 +18,7 @@ java --add-modules jdk.httpserver,java.net.http -cp out/classes:lib/hash4j-0.30. java -cp out/classes:lib/hash4j-0.30.0.jar cloud.lunarsky.store.RequestDiagnosticsTest java -cp out/classes:lib/hash4j-0.30.0.jar cloud.lunarsky.store.BucketActivityTest java --add-modules jdk.httpserver -cp out/classes:lib/hash4j-0.30.0.jar cloud.lunarsky.store.AdminOperationsTest +java --add-modules jdk.httpserver -cp out/classes:lib/hash4j-0.30.0.jar cloud.lunarsky.store.AdminBulkJobsTest java --add-modules jdk.httpserver,java.net.http -cp out/classes:lib/hash4j-0.30.0.jar cloud.lunarsky.store.FeatureTest java -cp out/classes:lib/hash4j-0.30.0.jar cloud.lunarsky.store.EncryptedVolumeTest java --add-modules jdk.httpserver,java.net.http -cp out/classes:lib/hash4j-0.30.0.jar cloud.lunarsky.store.NodeHttpTest diff --git a/src/cloud/lunarsky/store/AdminAccessCheck.java b/src/cloud/lunarsky/store/AdminAccessCheck.java index a0cc0b6..1f90a6f 100644 --- a/src/cloud/lunarsky/store/AdminAccessCheck.java +++ b/src/cloud/lunarsky/store/AdminAccessCheck.java @@ -26,6 +26,17 @@ final class AdminAccessCheck { Result check(String principal, String operation, String bucket, String key) throws IOException { if (principal == null || !identities.contains(principal)) return new Result(false, "Authentication", "Access key is unknown or disabled"); + validateRequest(operation, bucket, key); + try { + checkScope(principal, operation, bucket, key); + } catch (StoreException denied) { + if (denied.status != 403) throw denied; + return new Result(false, "Key scope", "Key scope does not allow this bucket, prefix, or operation"); + } + return inspectAccess(principal, operation, bucket, key); + } + + private static void validateRequest(String operation, String bucket, String key) { if (operation == null || !Set.of("list", "read", "write", "delete").contains(operation)) throw new StoreException(400, "InvalidArgument", "Choose a supported operation"); if (bucket == null || !bucket.matches("[a-z0-9][a-z0-9-]{1,61}[a-z0-9]")) @@ -34,39 +45,44 @@ final class AdminAccessCheck { throw new StoreException(400, "InvalidArgument", "Object key or prefix is too long"); if (!operation.equals("list") && (key == null || key.isEmpty() || key.length() > 1024)) throw new StoreException(400, "InvalidArgument", "Enter an object key"); + } + + private void checkScope(String principal, String operation, String bucket, String key) { + if (operation.equals("list")) { + Map query = Map.of("list-type", "2", "prefix", key == null ? "" : key); + if (managed != null && managed.contains(principal)) + managed.checkBucket(principal, bucket, "GET", query); + else scopes.checkBucket(principal, bucket, "GET", query); + return; + } String method = switch (operation) { - case "read" -> "GET"; case "write" -> "PUT"; case "delete" -> "DELETE"; default -> "GET"; }; - try { - if (operation.equals("list")) { - Map 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"); - } + if (managed != null && managed.contains(principal)) + managed.checkObject(principal, bucket, key, method, Map.of(), new Headers()); + else scopes.checkObject(principal, bucket, key, method, Map.of(), new Headers()); + } + + private Result inspectAccess(String principal, String operation, String bucket, String key) + throws IOException { + return switch (operation) { + case "list" -> policyResult(access.inspectBucket(bucket, principal)); + case "read" -> inspectRead(principal, bucket, key); + case "delete" -> policyResult(access.inspectWrite(bucket, key, principal, "s3:DeleteObject")); + default -> policyResult(access.inspectWrite(bucket, key, principal, "s3:PutObject")); + }; + } + + private Result inspectRead(String principal, String bucket, String key) throws IOException { + ObjectStorage.ListPage page = store.list(bucket, key, "", 1, null); + if (page.objects().isEmpty() || !key.equals(page.objects().get(0).key())) + return new Result(false, "Object", "Current object does not exist"); + return policyResult(access.inspectObject(bucket, key, page.objects().get(0).metadata(), principal)); + } + + private static Result policyResult(S3Access.Decision decision) { return new Result(decision.allowed(), "Bucket and identity policy", decision.reason()); } } diff --git a/src/cloud/lunarsky/store/AdminActions.java b/src/cloud/lunarsky/store/AdminActions.java index da13c1d..fbee316 100644 --- a/src/cloud/lunarsky/store/AdminActions.java +++ b/src/cloud/lunarsky/store/AdminActions.java @@ -12,143 +12,188 @@ final class AdminActions { static String apply(ObjectStorage store, String action, Map form, Set 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"; - } + String bucket = required(form, "bucket", 63); + return switch (action) { + case "create-bucket" -> createBucket(store, bucket, form); + case "rename-bucket" -> renameBucket(store, bucket, form, managed); + case "delete-bucket" -> deleteBucket(store, bucket, form); + default -> updateBucket(store, bucket, action, form, identities); + }; + } + + private static String createBucket(ObjectStorage store, String bucket, Map form) + throws IOException { + boolean wizard = "wizard".equals(form.get("setup")); + String versioning = form.getOrDefault("versioning", "off"); + if (wizard && !versioning.equals("off") && !versioning.equals("enabled")) + invalid("Invalid initial versioning setting"); + ObjectStorage.ObjectOwnership ownership = wizard ? + BucketSecurity.ownership(form.getOrDefault("ownership", "BucketOwnerEnforced")) : + ObjectStorage.ObjectOwnership.BUCKET_OWNER_ENFORCED; + ObjectStorage.PublicAccessBlock publicBlock = wizard ? publicAccessBlock(form) : + ObjectStorage.PublicAccessBlock.secure(); + if (wizard && !publicBlock.equals(ObjectStorage.PublicAccessBlock.secure()) && + !"yes".equals(form.get("acknowledgePublic"))) + invalid("Confirm that relaxing public access controls may expose this bucket"); + store.createBucket(bucket); + if (wizard) configureCreatedBucket(store, bucket, versioning, ownership, publicBlock); + return AdminBrowser.bucketUrl(bucket, "", null); + } + + private static void configureCreatedBucket(ObjectStorage store, String bucket, String versioning, + ObjectStorage.ObjectOwnership ownership, ObjectStorage.PublicAccessBlock publicBlock) + throws IOException { + if (versioning.equals("enabled")) + store.setVersioning(bucket, ObjectStorage.VersioningState.ENABLED); + if (ownership != ObjectStorage.ObjectOwnership.BUCKET_OWNER_ENFORCED) + store.setBucketOwnership(bucket, ownership); + if (!publicBlock.equals(ObjectStorage.PublicAccessBlock.secure())) + store.setPublicAccessBlock(bucket, publicBlock); + } + + private static String renameBucket(ObjectStorage store, String bucket, Map form, + ManagedCredentials managed) throws IOException { + confirm(form, bucket); + String newName = required(form, "newName", 63); + if (managed != null && managed.list().stream().anyMatch(key -> key.bucket().equals(bucket))) + throw new StoreException(409, "BucketHasScopedKeys", + "Move or remove scoped access keys for this bucket before renaming it"); + store.renameBucket(bucket, newName); + return AdminBrowser.bucketUrl(newName, "", null); + } + + private static String deleteBucket(ObjectStorage store, String bucket, Map form) + throws IOException { + confirm(form, bucket); + store.deleteBucket(bucket); + return AdminConsole.PATH + "/buckets"; + } + + private static String updateBucket(ObjectStorage store, String bucket, String action, + Map form, Set identities) throws IOException { 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 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 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 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)); - } + case "delete-object" -> { return deleteObject(store, bucket, form); } + case "versioning" -> setVersioning(store, bucket, form); + case "ownership" -> setOwnership(store, bucket, form); + case "public-access" -> setPublicAccess(store, bucket, current, form); + case "policy" -> setPolicy(store, bucket, current, form); + case "bucket-grant" -> setBucketGrant(store, bucket, current, form, identities); + case "object-grant" -> { return setObjectGrant(store, bucket, current, form, identities); } + case "object-tag" -> { return setObjectTag(store, bucket, form); } default -> invalid("Unknown admin action"); } return AdminBrowser.bucketUrl(bucket, "", null) + "#settings"; } + private static String deleteObject(ObjectStorage store, String bucket, Map form) + throws IOException { + String key = required(form, "key", 1024); + if (!key.equals(form.get("confirm"))) invalid("Type the object key to confirm"); + String version = version(form); + if (version != null && !version.equals(form.get("confirmVersion"))) + invalid("Type the version ID to confirm permanent deletion"); + store.delete(bucket, key, version); + return AdminBrowser.bucketUrl(bucket, key.contains("/") ? + key.substring(0, key.lastIndexOf('/') + 1) : "", null); + } + + private static void setVersioning(ObjectStorage store, String bucket, Map form) + throws IOException { + String state = required(form, "state", 16); + if (!state.equals("ENABLED") && !state.equals("SUSPENDED")) invalid("Invalid versioning state"); + store.setVersioning(bucket, ObjectStorage.VersioningState.valueOf(state)); + } + + private static void setOwnership(ObjectStorage store, String bucket, Map form) + throws IOException { + confirm(form, bucket); + String value = required(form, "ownership", 32); + store.setBucketOwnership(bucket, BucketSecurity.ownership(value)); + } + + private static void setPublicAccess(ObjectStorage store, String bucket, ObjectStorage.Bucket current, + Map form) throws IOException { + ObjectStorage.PublicAccessBlock block = publicAccessBlock(form); + ObjectStorage.PublicAccessBlock previous = current.publicAccessBlock(); + if (previous.blockPublicAcls() && !block.blockPublicAcls() || + previous.ignorePublicAcls() && !block.ignorePublicAcls() || + previous.blockPublicPolicy() && !block.blockPublicPolicy() || + previous.restrictPublicBuckets() && !block.restrictPublicBuckets()) confirm(form, bucket); + store.setPublicAccessBlock(bucket, block); + } + + private static ObjectStorage.PublicAccessBlock publicAccessBlock(Map form) { + return new ObjectStorage.PublicAccessBlock( + form.containsKey("blockPublicAcls"), form.containsKey("ignorePublicAcls"), + form.containsKey("blockPublicPolicy"), form.containsKey("restrictPublicBuckets")); + } + + private static void setPolicy(ObjectStorage store, String bucket, ObjectStorage.Bucket current, + Map form) throws IOException { + String policy = form.getOrDefault("policy", "").trim(); + if (policy.getBytes(StandardCharsets.UTF_8).length > 20480) invalid("Policy is too large"); + if (!policy.isEmpty()) { + BucketPolicy parsed = BucketPolicy.parse(policy, bucket); + if (current.publicAccessBlock().blockPublicPolicy() && parsed.publicAllow()) + throw new StoreException(403, "AccessDenied", "Public bucket policies are blocked"); + if (parsed.publicAllow()) confirm(form, bucket); + } + store.setBucketPolicy(bucket, policy.isEmpty() ? null : policy); + } + + private static void setBucketGrant(ObjectStorage store, String bucket, ObjectStorage.Bucket current, + Map form, Set identities) throws IOException { + Map acl = updateGrants(current.acl(), form, identities); + if (newPublicGrant(current.acl(), acl)) confirm(form, bucket); + BucketSecurity.checkAcl(current, new Headers(), acl, true); + store.setBucketAcl(bucket, acl); + } + + private static String setObjectGrant(ObjectStorage store, String bucket, ObjectStorage.Bucket current, + Map form, Set identities) throws IOException { + String key = required(form, "key", 1024); + String version = version(form); + ObjectStorage.Metadata metadata; + try (ObjectStorage.OpenObject opened = store.open(bucket, key, version)) { + metadata = opened.metadata(); + } + Map acl = updateGrants(metadata.acl(), form, identities); + if (newPublicGrant(metadata.acl(), acl)) confirm(form, bucket); + BucketSecurity.checkAcl(current, new Headers(), acl, true); + store.setObjectAcl(bucket, key, version, acl); + return objectUrl(bucket, key, version); + } + + private static String setObjectTag(ObjectStorage store, String bucket, Map form) + throws IOException { + String key = required(form, "key", 1024); + String tag = required(form, "tag", 128); + String version = version(form); + Map tags = new HashMap<>(store.tags(bucket, key, version)); + if ("remove".equals(form.get("operation"))) tags.remove(tag); + else if ("add".equals(form.get("operation"))) { + String value = form.get("value"); + if (value == null || value.length() > 256) invalid("Invalid value"); + tags.put(tag, value); + } else invalid("Invalid tag operation"); + ObjectAttributes.validateTags(tags); + store.setTags(bucket, key, version, Map.copyOf(tags)); + return objectUrl(bucket, key, version); + } + + private static String version(Map form) { + String version = form.getOrDefault("version", ""); + if (version.length() > 256) invalid("Invalid object version"); + return version.isEmpty() ? null : version; + } + + private static String objectUrl(String bucket, String key, String version) { + return AdminConsole.PATH + "/object?bucket=" + AdminBrowser.encoded(bucket) + + "&key=" + AdminBrowser.encoded(key) + + (version == null ? "" : "&version=" + AdminBrowser.encoded(version)); + } + private static Map updateGrants(Map current, Map form, Set identities) { String principal = required(form, "principal", 128); diff --git a/src/cloud/lunarsky/store/AdminBulkJobs.java b/src/cloud/lunarsky/store/AdminBulkJobs.java index 56d9bda..3c8a7a0 100644 --- a/src/cloud/lunarsky/store/AdminBulkJobs.java +++ b/src/cloud/lunarsky/store/AdminBulkJobs.java @@ -119,39 +119,7 @@ final class AdminBulkJobs { 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); + processPages(job); job.state = job.cancel ? "Cancelled" : job.capped ? "Capped" : "Completed"; } catch (Exception error) { job.state = "Failed"; @@ -162,6 +130,49 @@ final class AdminBulkJobs { } } + private void processPages(Job job) throws IOException { + String after = null; + while (!job.cancel) { + ObjectStorage.ListPage page = list(job, after); + if (processPage(job, page) || !page.truncated()) return; + if (page.nextKey() == null || page.nextKey().equals(after)) + throw new IOException("Storage listing did not advance"); + after = page.nextKey(); + } + } + + private boolean processPage(Job job, ObjectStorage.ListPage page) { + int remaining = MAX_ITEMS - job.processed; + for (ObjectStorage.ListedObject entry : page.objects()) { + if (job.cancel || job.processed >= MAX_ITEMS) break; + processEntry(job, entry); + } + if (job.processed < MAX_ITEMS) return false; + job.capped = page.truncated() || page.objects().size() > remaining; + return true; + } + + private void processEntry(Job job, ObjectStorage.ListedObject entry) { + try { + operations.read(() -> process(job.spec, entry)); + job.succeeded++; + String detail = job.spec.operation().equals("inventory") ? + "bytes=" + entry.metadata().length() + " etag=" + entry.metadata().etag() : + job.spec.operation(); + append(job, "ok", entry.key(), detail); + } catch (Exception error) { + job.failed++; + append(job, "error", entry.key(), errorDetail(error)); + } + job.processed++; + } + + private static String errorDetail(Exception error) { + String detail = error instanceof StoreException storeError ? + storeError.code + ": " + storeError.getMessage() : error.getClass().getSimpleName(); + return detail.length() > 200 ? detail.substring(0, 200) : detail; + } + private ObjectStorage.ListPage list(Job job, String after) throws IOException { return operations.readValue(() -> store.list(job.spec.bucket(), job.spec.prefix(), "", 100, after)); diff --git a/src/cloud/lunarsky/store/AdminOperationsPages.java b/src/cloud/lunarsky/store/AdminOperationsPages.java index 851e71a..d9632c1 100644 --- a/src/cloud/lunarsky/store/AdminOperationsPages.java +++ b/src/cloud/lunarsky/store/AdminOperationsPages.java @@ -138,6 +138,13 @@ final class AdminOperationsPages { return page(content.toString(), true); } ClusterStore.ClusterStatus status = cluster.status(); + appendClusterSummary(content, status); + appendClusterTopology(content, status); + appendRepairProgress(content, status.repair()); + return page(content.toString(), true); + } + + private static void appendClusterSummary(StringBuilder content, ClusterStore.ClusterStatus status) { long healthy = status.nodes().stream().filter(ClusterStore.NodeStatus::reachable).count(); long hosts = status.nodes().stream().filter(ClusterStore.NodeStatus::reachable) .map(node -> node.node().hostId()).distinct().count(); @@ -150,8 +157,11 @@ final class AdminOperationsPages { .append("Reachable nodes") .append(healthy).append(" / ").append(status.nodes().size()) .append("Reachable hosts") - .append(hosts).append("") - .append("
") + .append(hosts).append("
"); + } + + private static void appendClusterTopology(StringBuilder content, ClusterStore.ClusterStatus status) { + content.append("
") .append("Metadata primary

") .append(status.metadataWritable() ? "Writable" : "Unavailable or read-only") .append("

"); @@ -163,8 +173,7 @@ final class AdminOperationsPages { .append("Host ").append(node.node().hostId()) .append("").append(escape(node.node().url().toString())) .append("Verified replicas at last repair: ") - .append(status.repair() == null || !status.repair().state().equals("completed") || - status.repair().report().scanned() > 0 && status.verifiedReplicas().isEmpty() ? + .append(!replicasMeasured(status) ? "Not measured" : Long.toString(status.verifiedReplicas().getOrDefault(node.node().id(), 0L))) .append("
"); @@ -174,33 +183,48 @@ final class AdminOperationsPages { "Multiple nodes on one host do not provide host-level redundancy.

"); if (status.omittedNodes() > 0) content.append("

") .append(status.omittedNodes()).append(" additional nodes are not probed in this view.

"); + } + + private static boolean replicasMeasured(ClusterStore.ClusterStatus status) { ClusterStore.RepairStatus repair = status.repair(); + if (repair == null || !repair.state().equals("completed")) return false; + return repair.report().scanned() <= 0 || !status.verifiedReplicas().isEmpty(); + } + + private static void appendRepairProgress(StringBuilder content, ClusterStore.RepairStatus repair) { content.append("

Repair progress

"); if (repair == null) content.append("

No repair report has been recorded yet.

"); else { - ClusterStore.RepairReport report = repair.report(); - boolean stale = repair.state().equals("running") && - System.currentTimeMillis() - repair.updatedAt() > 300_000; - content.append("

").append(stale ? "May be interrupted" : - repair.state().equals("running") ? "Running" : - repair.state().equals("failed") ? "Failed" : "Completed") - .append(" · Started ") - .append(java.time.Instant.ofEpochMilli(repair.startedAt())) - .append(" UTC · Last update ") - .append(java.time.Instant.ofEpochMilli(repair.updatedAt())) - .append(" UTC

These counts are from this repair pass, " + - "not a live replica inventory.

") - .append("Segments scanned") - .append(report.scanned()).append("") - .append("Replicas restored") - .append(report.restored()).append("") - .append("Under-replicated") - .append(report.underReplicated()).append("") - .append("Unrecoverable") - .append(report.unrecoverable()).append("
"); + appendRepairReport(content, repair); } content.append("

Repair is run by the separate cluster maintenance service. " + "This panel does not trigger repair or change placement.

"); - return page(content.toString(), true); + } + + private static void appendRepairReport(StringBuilder content, ClusterStore.RepairStatus repair) { + ClusterStore.RepairReport report = repair.report(); + content.append("

").append(repairLabel(repair)) + .append(" · Started ") + .append(java.time.Instant.ofEpochMilli(repair.startedAt())) + .append(" UTC · Last update ") + .append(java.time.Instant.ofEpochMilli(repair.updatedAt())) + .append(" UTC

These counts are from this repair pass, " + + "not a live replica inventory.

") + .append("Segments scanned") + .append(report.scanned()).append("") + .append("Replicas restored") + .append(report.restored()).append("") + .append("Under-replicated") + .append(report.underReplicated()).append("") + .append("Unrecoverable") + .append(report.unrecoverable()).append("
"); + } + + private static String repairLabel(ClusterStore.RepairStatus repair) { + if (repair.state().equals("running")) { + return System.currentTimeMillis() - repair.updatedAt() > 300_000 + ? "May be interrupted" : "Running"; + } + return repair.state().equals("failed") ? "Failed" : "Completed"; } } diff --git a/src/cloud/lunarsky/store/DiskStore.java b/src/cloud/lunarsky/store/DiskStore.java index 6e6b5c9..a30c6b3 100644 --- a/src/cloud/lunarsky/store/DiskStore.java +++ b/src/cloud/lunarsky/store/DiskStore.java @@ -576,65 +576,83 @@ final class DiskStore implements ObjectStorage { 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) + checkExpectedVersion(configured, metadata, expected); + if (isVersioned(configured)) return installVersionedPending(destination, pending, metadata, createOnly, configured.versioning()); } - long previous = 0; - boolean existed = Files.exists(destination); - boolean legacy = false; - if (existed) { - if (createOnly) throw new StoreException(412, "PreconditionFailed", "Object already exists"); - try (var in = new DataInputStream(Files.newInputStream(destination))) { - Metadata old = readRecord(in).metadata(); - previous = old.length(); - legacy = old.key() == null; - } - } - long additional = Math.max(0, metadata.length() - previous); + Metadata previous = previousMetadata(destination, createOnly); + long previousLength = previous == null ? 0 : previous.length(); + long additional = Math.max(0, metadata.length() - previousLength); synchronized (this) { Bucket configured = buckets.get(metadata.bucket()); - if (configured != null && configured.versioning() != VersioningState.NEVER) + if (isVersioned(configured)) return installVersionedPending(destination, pending, metadata, createOnly, configured.versioning()); - if (Files.exists(catalog) && configured == null) - throw new StoreException(404, "NoSuchBucket", "Bucket not found"); - if (maxTotal - used - reservedBytes < additional) - throw new StoreException(507, "InsufficientStorage", "Store capacity limit reached"); - reservedBytes += additional; - publishingByBucket.merge(metadata.bucket(), 1, Integer::sum); - } - boolean moved = false; - try { - Files.move(pending, destination, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); - moved = true; - syncDirectory(destination.getParent()); - } finally { - synchronized (this) { - if (moved) { - used = used - previous + metadata.length(); - if (!existed) objectCount++; - if (legacy) legacyCount--; - index.put(indexKey(metadata.bucket(), metadata.key()), metadata); - } - reservedBytes -= additional; - publishingByBucket.compute(metadata.bucket(), (bucket, count) -> count == 1 ? null : count - 1); - notifyAll(); - } + reservePublication(metadata.bucket(), configured, additional); } + publishUnversioned(destination, pending, metadata, previous, additional); return metadata; } } + private void checkExpectedVersion(Bucket configured, Metadata metadata, Metadata expected) { + if (expected == null) return; + Metadata current = index.get(indexKey(metadata.bucket(), metadata.key())); + if (configured == null || configured.versioning() != VersioningState.ENABLED || + current == null || !expected.versionId().equals( + current.versionId() == null ? "null" : current.versionId()) || + !MessageDigest.isEqual(expected.sha256(), current.sha256()) || + !expected.tags().equals(current.tags()) || !expected.acl().equals(current.acl())) + throw new StoreException(412, "PreconditionFailed", "Object changed since it was opened"); + } + + private static boolean isVersioned(Bucket configured) { + return configured != null && configured.versioning() != VersioningState.NEVER; + } + + private Metadata previousMetadata(Path destination, boolean createOnly) throws IOException { + if (!Files.exists(destination)) return null; + if (createOnly) throw new StoreException(412, "PreconditionFailed", "Object already exists"); + try (var in = new DataInputStream(Files.newInputStream(destination))) { + return readRecord(in).metadata(); + } + } + + private void reservePublication(String bucket, Bucket configured, long additional) { + if (Files.exists(catalog) && configured == null) + throw new StoreException(404, "NoSuchBucket", "Bucket not found"); + if (maxTotal - used - reservedBytes < additional) + throw new StoreException(507, "InsufficientStorage", "Store capacity limit reached"); + reservedBytes += additional; + publishingByBucket.merge(bucket, 1, Integer::sum); + } + + private void publishUnversioned(Path destination, Path pending, Metadata metadata, + Metadata previous, long additional) throws IOException { + boolean moved = false; + try { + Files.move(pending, destination, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); + moved = true; + syncDirectory(destination.getParent()); + } finally { + finishPublication(metadata, previous, additional, moved); + } + } + + private synchronized void finishPublication(Metadata metadata, Metadata previous, + long additional, boolean moved) { + if (moved) { + used = used - (previous == null ? 0 : previous.length()) + metadata.length(); + if (previous == null) objectCount++; + else if (previous.key() == null) legacyCount--; + index.put(indexKey(metadata.bucket(), metadata.key()), metadata); + } + reservedBytes -= additional; + publishingByBucket.compute(metadata.bucket(), (bucket, count) -> count == 1 ? null : count - 1); + notifyAll(); + } + private Metadata installVersionedPending(Path destination, Path pending, Metadata metadata, boolean createOnly, VersioningState state) throws IOException { String bucket = metadata.bucket(); diff --git a/src/cloud/lunarsky/store/RequestDiagnostics.java b/src/cloud/lunarsky/store/RequestDiagnostics.java index a6c5a2d..42e324c 100644 --- a/src/cloud/lunarsky/store/RequestDiagnostics.java +++ b/src/cloud/lunarsky/store/RequestDiagnostics.java @@ -46,20 +46,23 @@ final class RequestDiagnostics { 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; + recordWindow(currentWindow(now / MINUTE_MILLIS), status, elapsedNanos); + recordKey(principal, status, now); + if (status >= 400) recordFailure(requestId, operation, bucket, status, now); + } + + private Window currentWindow(long minute) { int slot = (int) Math.floorMod(minute, windows.length()); - Window window; - do { - window = windows.get(slot); - if (window != null && window.minute == minute) break; + while (true) { + Window window = windows.get(slot); + if (window != null && window.minute == minute) return window; Window fresh = new Window(minute); - if (windows.compareAndSet(slot, window, fresh)) { - window = fresh; - break; - } - } while (true); + if (windows.compareAndSet(slot, window, fresh)) return fresh; + } + } + + private static void recordWindow(Window window, int status, long elapsedNanos) { window.requests.increment(); if (status >= 500) window.serverErrors.increment(); else if (status >= 400) window.clientErrors.increment(); @@ -68,23 +71,26 @@ final class RequestDiagnostics { 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)); - } + } + + private void recordKey(String principal, int status, long now) { + if (principal == null || principal.length() > 128) return; + KeyCounters counters = keys.get(principal); + if (counters == null && keys.size() < 128) + counters = keys.computeIfAbsent(principal, ignored -> new KeyCounters()); + if (counters == null) return; + counters.requests.increment(); + if (status >= 400) counters.failures.increment(); + counters.lastSeen.set(now); + } + + private void recordFailure(String requestId, String operation, String bucket, int status, long now) { + if (operation == null) operation = "Service"; + 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() { diff --git a/test/cloud/lunarsky/store/AdminBulkJobsTest.java b/test/cloud/lunarsky/store/AdminBulkJobsTest.java new file mode 100644 index 0000000..908c410 --- /dev/null +++ b/test/cloud/lunarsky/store/AdminBulkJobsTest.java @@ -0,0 +1,137 @@ +package cloud.lunarsky.store; + +import java.lang.reflect.Proxy; +import java.util.List; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.IntStream; + +public final class AdminBulkJobsTest { + private static final String BUCKET = "test-bucket"; + private static final ObjectStorage.Metadata METADATA = new ObjectStorage.Metadata( + 4, 0, "etag", new byte[32], BUCKET, "", "text/plain"); + + @FunctionalInterface + private interface Listing { + ObjectStorage.ListPage get(int count, String after) throws Exception; + } + + @FunctionalInterface + private interface Deletion { + void delete(String key) throws Exception; + } + + private static void check(boolean value, String message) { + if (!value) throw new AssertionError(message); + } + + private static ObjectStorage storage(Listing listing, Deletion deletion) { + return (ObjectStorage) Proxy.newProxyInstance(ObjectStorage.class.getClassLoader(), + new Class[]{ObjectStorage.class}, (proxy, method, arguments) -> switch (method.getName()) { + case "bucket" -> new ObjectStorage.Bucket(BUCKET, 0); + case "list" -> listing.get((int) arguments[3], (String) arguments[4]); + case "delete" -> { + deletion.delete((String) arguments[1]); + yield null; + } + default -> throw new AssertionError("Unexpected storage operation: " + method.getName()); + }); + } + + private static ObjectStorage.ListPage page(int start, int end, String next, boolean truncated) { + List objects = IntStream.range(start, end) + .mapToObj(index -> new ObjectStorage.ListedObject(Integer.toString(index), METADATA)).toList(); + return new ObjectStorage.ListPage(objects, List.of(), next, truncated); + } + + private static AdminBulkJobs.Spec spec(String operation) { + return new AdminBulkJobs.Spec(operation, BUCKET, "", "", "", "", ""); + } + + private static AdminBulkJobs.Snapshot finished(ArrayBlockingQueue results) + throws InterruptedException { + AdminBulkJobs.Snapshot result = results.poll(10, TimeUnit.SECONDS); + if (result == null) throw new AssertionError("Bulk job did not finish"); + return result; + } + + private static void itemLimit(int total, boolean oversizedPage) throws Exception { + ObjectStorage store = storage((count, after) -> { + int start = after == null ? 0 : Integer.parseInt(after) + 1; + int end = oversizedPage ? total : Math.min(start + count, total); + return page(start, end, Integer.toString(end - 1), end < total); + }, key -> { }); + var results = new ArrayBlockingQueue(2); + AdminBulkJobs jobs = new AdminBulkJobs(store, results::add); + jobs.start(spec("inventory")); + AdminBulkJobs.Snapshot result = finished(results); + boolean capped = total > AdminBulkJobs.MAX_ITEMS; + check(result.capped() == capped, "Incorrect cap at the item boundary"); + check(result.state().equals(capped ? "Capped" : "Completed"), "Incorrect completion state"); + check(result.processed() == AdminBulkJobs.MAX_ITEMS && result.succeeded() == result.processed(), + "Item limit lost or overran entries"); + check(!jobs.hasActiveJob(), "Finished job is still active"); + } + + private static void cancellation() throws Exception { + CountDownLatch entered = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + AtomicInteger deletes = new AtomicInteger(); + ObjectStorage store = storage((count, after) -> page(0, 3, null, false), key -> { + deletes.incrementAndGet(); + entered.countDown(); + if (!release.await(10, TimeUnit.SECONDS)) throw new AssertionError("Delete was not released"); + }); + var results = new ArrayBlockingQueue(2); + AdminBulkJobs jobs = new AdminBulkJobs(store, results::add); + AdminBulkJobs.Snapshot started = jobs.start(spec("delete")); + try { + check(entered.await(10, TimeUnit.SECONDS), "Delete did not start"); + jobs.cancel(started.id()); + } finally { + release.countDown(); + } + AdminBulkJobs.Snapshot result = finished(results); + check(result.state().equals("Cancelled") && result.processed() == 1 && result.succeeded() == 1, + "Cancellation did not finish the in-progress entry"); + check(deletes.get() == 1, "Cancellation started another entry"); + } + + private static void stalledPagination() throws Exception { + ObjectStorage store = storage((count, after) -> page(0, 1, "0", true), key -> { }); + var results = new ArrayBlockingQueue(2); + AdminBulkJobs jobs = new AdminBulkJobs(store, results::add); + jobs.start(spec("inventory")); + AdminBulkJobs.Snapshot result = finished(results); + check(result.state().equals("Failed") && result.processed() == 2, + "A repeated pagination marker did not stop the job"); + check(jobs.report(result.id()).contains("IOException"), "Listing failure missing from report"); + } + + private static void entryFailure() throws Exception { + ObjectStorage store = storage((count, after) -> page(0, 3, null, false), key -> { + if (key.equals("1")) throw new StoreException(403, "AccessDenied", "x".repeat(300)); + }); + var results = new ArrayBlockingQueue(2); + AdminBulkJobs jobs = new AdminBulkJobs(store, results::add); + jobs.start(spec("delete")); + AdminBulkJobs.Snapshot result = finished(results); + check(result.state().equals("Completed") && result.processed() == 3 && + result.succeeded() == 2 && result.failed() == 1, "Entry failure aborted or miscounted the job"); + String report = jobs.report(result.id()); + check(report.contains("AccessDenied: ") && !report.contains("x".repeat(201)), + "Entry failure detail was missing or unbounded"); + } + + public static void main(String[] args) throws Exception { + itemLimit(AdminBulkJobs.MAX_ITEMS, false); + itemLimit(AdminBulkJobs.MAX_ITEMS + 1, false); + itemLimit(AdminBulkJobs.MAX_ITEMS + 1, true); + cancellation(); + stalledPagination(); + entryFailure(); + System.out.println("Admin bulk job tests passed: cap, cancellation, pagination, errors"); + } +} diff --git a/test/cloud/lunarsky/store/AdminConsoleTest.java b/test/cloud/lunarsky/store/AdminConsoleTest.java index 61821e5..e8e6d98 100644 --- a/test/cloud/lunarsky/store/AdminConsoleTest.java +++ b/test/cloud/lunarsky/store/AdminConsoleTest.java @@ -16,8 +16,24 @@ import java.util.Comparator; import java.util.Map; import java.util.concurrent.Executors; -public final class AdminConsoleTest { +public final class AdminConsoleTest implements AutoCloseable { private static final String PASSWORD = "a-very-long-test-admin-password"; + private final Path root; + private final Path passwordFile; + private final Path masterFile; + private final DiskStore store; + private final DiskBucketNames names; + private final BucketActivity activity; + private final java.util.concurrent.ExecutorService executor; + private final HttpServer server; + private final HttpServer s3Server; + private final HttpClient client; + private final String base; + private final String s3Base; + private Main app; + private ManagedCredentials managed; + private String cookie; + private String adminCsrf; private static void status(int wanted, HttpResponse response) { if (response.statusCode() != wanted) @@ -85,8 +101,66 @@ public final class AdminConsoleTest { } } + private AdminConsoleTest() throws Exception { + root = Files.createTempDirectory("admin-console-test-"); + passwordFile = root.resolve("password"); + Files.writeString(passwordFile, PASSWORD + "\n"); + masterFile = root.resolve("credential-master"); + Files.writeString(masterFile, "0123456789abcdef".repeat(4)); + 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"); + names = new DiskBucketNames(store, new MultipartStore(store)); + activity = new BucketActivity(root.resolve("data/bucket-activity.tsv")); + activity.record("photos", "GET"); + executor = Executors.newVirtualThreadPerTaskExecutor(); + server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 16); + s3Server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 16); + base = "http://127.0.0.1:" + server.getAddress().getPort(); + s3Base = "http://127.0.0.1:" + s3Server.getAddress().getPort(); + client = HttpClient.newHttpClient(); + } + public static void main(String[] args) throws Exception { - Path root = Files.createTempDirectory("admin-console-test-"); + try (AdminConsoleTest test = new AdminConsoleTest()) { + test.verifyLegacyBranding(); + test.verifyConfiguration(); + test.startServers(); + test.verifyUnauthenticatedAccess(); + test.verifyLoginPage(); + test.verifyPublicAssets(); + test.login(); + test.verifyOverview(); + test.verifyWorkspaceAssets(); + test.verifyHealthAndDiagnostics(); + test.verifyAuditAccessCheck(); + test.verifyJobsAndClusterViews(); + test.verifyPerformanceView(); + test.verifyPerformanceEvents(); + test.verifyPerformanceCounters(); + test.verifyBucketBrowser(); + test.verifyObjectBrowser(); + test.verifyUploadAndDownload(); + test.verifyBucketCreation(); + test.verifyManagedCredentials(); + test.verifyBucketPolicies(); + test.verifyBucketGrantsAndVersioning(); + test.verifyVersionedUpload(); + test.verifyTextEditing(); + test.verifyTagsAndDeletion(); + test.verifyBucketRename(); + test.verifyThemeAndBrandingName(); + test.verifyBrandingIcon(); + test.verifyInputEscaping(); + test.verifyLogoutAndCooldown(); + test.verifyPrivateOrigin(); + System.out.println("Admin console tests passed"); + } + } + + private void verifyLegacyBranding() throws Exception { Path legacyBranding = root.resolve("legacy-branding.txt"); Files.writeString(legacyBranding, "ObjectStoreBranding 1\n" + java.util.Base64.getEncoder().encodeToString("Old name".getBytes(StandardCharsets.UTF_8)) + @@ -99,618 +173,707 @@ public final class AdminConsoleTest { 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); + } + + private void verifyConfiguration() throws Exception { + if (AdminConsole.fromEnvironment(Map.of(), store) != null) + throw new AssertionError("Admin console enabled without configuration"); try { - if (AdminConsole.fromEnvironment(Map.of(), store) != null) - throw new AssertionError("Admin console enabled without configuration"); - try { - AdminConsole.fromEnvironment(Map.of("ADMIN_UI_ENABLED", "true"), store); - throw new AssertionError("Admin console enabled without password file"); - } catch (IllegalArgumentException expected) { } + AdminConsole.fromEnvironment(Map.of("ADMIN_UI_ENABLED", "true"), store); + throw new AssertionError("Admin console enabled without password file"); + } catch (IllegalArgumentException expected) { } + try { + AdminConsole.fromEnvironment(Map.of("ADMIN_UI_ENABLED", "true", + "ADMIN_UI_PASSWORD_FILE", passwordFile.toString(), + "ADMIN_UI_ORIGIN", "http://public.example"), store); + throw new AssertionError("Admin console accepted a remote HTTP origin"); + } catch (IllegalArgumentException expected) { } + for (String invalid : new String[] { "http://public.example:9001", "http://8.8.8.8:9001", + "http://10.30.0.120", "https://10.30.0.120:9001" }) { try { AdminConsole.fromEnvironment(Map.of("ADMIN_UI_ENABLED", "true", "ADMIN_UI_PASSWORD_FILE", passwordFile.toString(), - "ADMIN_UI_ORIGIN", "http://public.example"), store); - throw new AssertionError("Admin console accepted a remote HTTP origin"); + "ADMIN_UI_PRIVATE_ORIGIN", invalid), store); + throw new AssertionError("Admin console accepted invalid private origin: " + invalid); } catch (IllegalArgumentException expected) { } - for (String invalid : new String[] { "http://public.example:9001", "http://8.8.8.8:9001", - "http://10.30.0.120", "https://10.30.0.120:9001" }) { - try { - AdminConsole.fromEnvironment(Map.of("ADMIN_UI_ENABLED", "true", - "ADMIN_UI_PASSWORD_FILE", passwordFile.toString(), - "ADMIN_UI_PRIVATE_ORIGIN", invalid), store); - throw new AssertionError("Admin console accepted invalid private origin: " + invalid); - } catch (IllegalArgumentException expected) { } - } - AdminConsole console = AdminConsole.fromEnvironment(Map.of( - "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(); - s3Server.setExecutor(executor); - s3Server.createContext("/", app::handle); - s3Server.start(); - String base = "http://127.0.0.1:" + server.getAddress().getPort(); - String s3Base = "http://127.0.0.1:" + s3Server.getAddress().getPort(); - HttpClient client = HttpClient.newHttpClient(); - status(404, client.send(request(s3Base, "/login").GET().build(), - HttpResponse.BodyHandlers.discarding())); - status(404, client.send(HttpRequest.newBuilder(URI.create(base + "/health")).GET().build(), - HttpResponse.BodyHandlers.discarding())); - try (Socket socket = new Socket("127.0.0.1", server.getAddress().getPort())) { - socket.getOutputStream().write(("GET " + AdminConsole.PATH + "/login HTTP/1.1\r\n" + - "Host: public.example\r\nConnection: close\r\n\r\n").getBytes(StandardCharsets.US_ASCII)); - String response = new String(socket.getInputStream().readAllBytes(), StandardCharsets.UTF_8); - if (!response.startsWith("HTTP/1.1 403")) - throw new AssertionError("Public Host header reached the admin console"); - } - status(303, client.send(request(base, "/overview").GET().build(), + } + } + + private void startServers() throws Exception { + AdminConsole console = AdminConsole.fromEnvironment(Map.of( + "ADMIN_UI_ENABLED", "true", "ADMIN_UI_PASSWORD_FILE", passwordFile.toString(), + "DATA_DIR", root.resolve("data").toString()), names); + console.setDiskStore(store); + 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); + 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(); + s3Server.setExecutor(executor); + s3Server.createContext("/", app::handle); + s3Server.start(); + } + + private void verifyUnauthenticatedAccess() throws Exception { + status(404, client.send(request(s3Base, "/login").GET().build(), + HttpResponse.BodyHandlers.discarding())); + status(404, client.send(HttpRequest.newBuilder(URI.create(base + "/health")).GET().build(), + HttpResponse.BodyHandlers.discarding())); + try (Socket socket = new Socket("127.0.0.1", server.getAddress().getPort())) { + socket.getOutputStream().write(("GET " + AdminConsole.PATH + "/login HTTP/1.1\r\n" + + "Host: public.example\r\nConnection: close\r\n\r\n").getBytes(StandardCharsets.US_ASCII)); + String response = new String(socket.getInputStream().readAllBytes(), StandardCharsets.UTF_8); + if (!response.startsWith("HTTP/1.1 403")) + throw new AssertionError("Public Host header reached the admin console"); + } + status(303, client.send(request(base, "/overview").GET().build(), + HttpResponse.BodyHandlers.ofString())); + for (String path : new String[] { "/performance", "/performance.json", "/performance.js", "/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())); - 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); - if (!loginPage.body().contains("Admin password") || - !loginPage.body().contains("/_objectstore/admin/logo.png") || - !loginPage.headers().firstValue("Cache-Control").orElse("").equals("no-store")) - throw new AssertionError("Login page or cache control missing"); - 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"); - var logo = client.send(request(base, "/logo.png").GET().build(), - HttpResponse.BodyHandlers.ofByteArray()); - status(200, logo); - if (!logo.headers().firstValue("Content-Type").orElse("").equals("image/png") || - logo.body().length < 8 || logo.body()[0] != (byte) 0x89 || - logo.body()[1] != 'P' || logo.body()[2] != 'N' || logo.body()[3] != 'G') - throw new AssertionError("ObjectStore icon is unavailable"); - var style = client.send(request(base, "/style.css").GET().build(), - HttpResponse.BodyHandlers.ofString()); - status(200, style); - if (!style.body().contains("color-scheme: dark") || - !style.body().contains("--biscuit-chart-surface: #211c2b")) - throw new AssertionError("Dark chart styles missing"); - status(303, client.send(request(base, "/biscuit.js").GET().build(), - HttpResponse.BodyHandlers.discarding())); - status(403, post(client, base, "/login", PASSWORD, "invalid", null, null)); + } + status(401, client.send(request(base, "/jobs.json?id=abcdefghijklmnop").GET().build(), + HttpResponse.BodyHandlers.ofString())); + } + + private void verifyLoginPage() throws Exception { + var loginPage = client.send(request(base, "/login").GET().build(), + HttpResponse.BodyHandlers.ofString()); + status(200, loginPage); + if (!loginPage.body().contains("Admin password") || + !loginPage.body().contains("/_objectstore/admin/logo.png") || + !loginPage.headers().firstValue("Cache-Control").orElse("").equals("no-store")) + throw new AssertionError("Login page or cache control missing"); + 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"); + } + + private void verifyPublicAssets() throws Exception { + var logo = client.send(request(base, "/logo.png").GET().build(), + HttpResponse.BodyHandlers.ofByteArray()); + status(200, logo); + if (!logo.headers().firstValue("Content-Type").orElse("").equals("image/png") || + logo.body().length < 8 || logo.body()[0] != (byte) 0x89 || + logo.body()[1] != 'P' || logo.body()[2] != 'N' || logo.body()[3] != 'G') + throw new AssertionError("ObjectStore icon is unavailable"); + var style = client.send(request(base, "/style.css").GET().build(), + HttpResponse.BodyHandlers.ofString()); + status(200, style); + if (!style.body().contains("color-scheme: dark") || + !style.body().contains("--biscuit-chart-surface: #211c2b")) + throw new AssertionError("Dark chart styles missing"); + status(303, client.send(request(base, "/biscuit.js").GET().build(), + HttpResponse.BodyHandlers.discarding())); + } + + private void login() throws Exception { + status(403, post(client, base, "/login", PASSWORD, "invalid", null, null)); + status(401, post(client, base, "/login", "incorrect", loginToken(client, base), null, null)); + var login = post(client, base, "/login", PASSWORD, loginToken(client, base), null, null); + status(303, login); + cookie = login.headers().firstValue("Set-Cookie").orElseThrow().split(";", 2)[0]; + if (!login.headers().firstValue("Set-Cookie").orElseThrow().contains("HttpOnly; SameSite=Strict")) + throw new AssertionError("Session cookie protections missing"); + } + + private void verifyOverview() throws Exception { + var overview = client.send(request(base, "/overview").header("Cookie", cookie).GET().build(), + HttpResponse.BodyHandlers.ofString()); + status(200, overview); + if (!overview.body().contains("Storage mode") || + !overview.body().contains("biscuit-cardview") || !overview.body().contains("photos") || + !overview.body().contains("/performance") || + !overview.body().contains("/_objectstore/admin/logo.png") || + !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"); + adminCsrf = csrf(overview.body()); + } + + private void verifyWorkspaceAssets() throws Exception { + 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("