Refactor complex admin and storage methods

This commit is contained in:
admin committed 2026-11-07 11:00:16 +01:00
1 parent 5304dfc047
commit 3c739deb09
13 files changed
+694 -210

No files matched your search

+1
View File
@@ -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.RequestDiagnosticsTest
RUN java -cp /out:/tmp/hash4j.jar cloud.lunarsky.store.BucketActivityTest 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.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 --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 -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.NodeHttpTest
+1
View File
@@ -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. | | `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. | | `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. | | `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. | | `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. | | `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. | | `ClusterNodeTest` | Node identity and locking, authenticated segment transfers, checksum rejection, repair authorization, inventory and guarded deletion, and restart cleanup. |
+55 -32
View File
@@ -72,10 +72,7 @@
? history.filter(point => point.cpu !== null) : history; ? history.filter(point => point.cpu !== null) : history;
} }
function accept(sample) { function showMemory(sample) {
if (!active || document.hidden) return;
try {
const now = performance.now();
const rss = sample.rssBytes >= 0 ? sample.rssBytes : sample.heapBytes + sample.nonHeapBytes; const rss = sample.rssBytes >= 0 ? sample.rssBytes : sample.heapBytes + sample.nonHeapBytes;
if (sample.rssBytes < 0 && !memoryFallback) { if (sample.rssBytes < 0 && !memoryFallback) {
memoryFallback = true; memoryFallback = true;
@@ -86,49 +83,75 @@
]; ];
} }
show('perf-ram', bytes(rss)); show('perf-ram', bytes(rss));
show('perf-gc', Number(sample.gcCount).toLocaleString()); return rss;
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; function cpuUsage(sample, before, seconds) {
if (seconds > 0.1) { if (!(sample.cpuNanos >= 0 && before.cpuNanos >= 0)) return null;
const requests = counterDelta(sample, previous.sample, 'requests'); return Math.max(0, Math.min(100,
const errors = counterDelta(sample, previous.sample, 'failures4xx') + (sample.cpuNanos - before.cpuNanos) /
counterDelta(sample, previous.sample, 'failures5xx'); (seconds * 1e9 * Math.max(1, sample.processors)) * 100));
const cpu = sample.cpuNanos >= 0 && previous.sample.cpuNanos >= 0 }
? Math.max(0, Math.min(100,
(sample.cpuNanos - previous.sample.cpuNanos) / function samplePoint(sample, before, seconds, rss) {
(seconds * 1e9 * Math.max(1, sample.processors)) * 100)) const errors = counterDelta(sample, before, 'failures4xx') +
: null; counterDelta(sample, before, 'failures5xx');
const point = { return {
time: new Date().toLocaleTimeString(), time: new Date().toLocaleTimeString(),
requests: requests / seconds, requests: counterDelta(sample, before, 'requests') / seconds,
errors: errors / seconds, errors: errors / seconds,
inbound: counterDelta(sample, previous.sample, 'inboundBytes') / seconds / 1024, inbound: counterDelta(sample, before, 'inboundBytes') / seconds / 1024,
outbound: counterDelta(sample, previous.sample, 'outboundBytes') / seconds / 1024, outbound: counterDelta(sample, before, 'outboundBytes') / seconds / 1024,
cpu, cpu: cpuUsage(sample, before, seconds),
memory: rss / 1048576, memory: rss / 1048576,
heap: sample.heapBytes / 1048576, heap: sample.heapBytes / 1048576,
seconds seconds
}; };
history.push(point); }
if (history.length > 60) history.shift();
show('perf-rps', rate(point.requests)); function showCpuAverage() {
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 cpuPoints = history.filter(entry => entry.cpu !== null);
const cpuSeconds = cpuPoints.reduce((total, entry) => total + entry.seconds, 0); const cpuSeconds = cpuPoints.reduce((total, entry) => total + entry.seconds, 0);
show('perf-cpu', cpuSeconds ? show('perf-cpu', cpuSeconds ?
(cpuPoints.reduce((total, entry) => total + entry.cpu * entry.seconds, 0) / (cpuPoints.reduce((total, entry) => total + entry.cpu * entry.seconds, 0) /
cpuSeconds).toFixed(1) + '%' : '—'); 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(); updateCharts();
} }
function recordSample(sample, now, rss) {
if (!previous) return;
const before = previous.sample;
if (sample.requests < before.requests) {
history.length = 0;
updateCharts();
} }
if (!(sample.requests >= before.requests)) return;
const seconds = (now - previous.at) / 1000;
if (!(seconds > 0.1)) return;
const point = samplePoint(sample, before, seconds, rss);
history.push(point);
if (history.length > 60) history.shift();
showInterval(sample, before, point);
}
function accept(sample) {
if (!active || document.hidden) return;
try {
const now = performance.now();
const rss = showMemory(sample);
show('perf-gc', Number(sample.gcCount).toLocaleString());
show('perf-inflight', Number(sample.inFlight).toLocaleString());
recordSample(sample, now, rss);
previous = { sample, at: now }; previous = { sample, at: now };
showState(history.length ? 'Live · one-second samples' : showState(history.length ? 'Live · one-second samples' :
'Collecting a second sample…', history.length ? 'live' : 'loading'); 'Collecting a second sample…', history.length ? 'live' : 'loading');
+1
View File
@@ -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.RequestDiagnosticsTest
java -cp out/classes:lib/hash4j-0.30.0.jar cloud.lunarsky.store.BucketActivityTest 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.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 --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 -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.NodeHttpTest
+35 -19
View File
@@ -26,6 +26,17 @@ final class AdminAccessCheck {
Result check(String principal, String operation, String bucket, String key) throws IOException { Result check(String principal, String operation, String bucket, String key) throws IOException {
if (principal == null || !identities.contains(principal)) if (principal == null || !identities.contains(principal))
return new Result(false, "Authentication", "Access key is unknown or disabled"); 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)) if (operation == null || !Set.of("list", "read", "write", "delete").contains(operation))
throw new StoreException(400, "InvalidArgument", "Choose a supported 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]")) 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"); throw new StoreException(400, "InvalidArgument", "Object key or prefix is too long");
if (!operation.equals("list") && (key == null || key.isEmpty() || key.length() > 1024)) if (!operation.equals("list") && (key == null || key.isEmpty() || key.length() > 1024))
throw new StoreException(400, "InvalidArgument", "Enter an object key"); throw new StoreException(400, "InvalidArgument", "Enter an object key");
}
private void checkScope(String principal, String operation, String bucket, String key) {
if (operation.equals("list")) {
Map<String, String> query = Map.of("list-type", "2", "prefix", key == null ? "" : key);
if (managed != null && managed.contains(principal))
managed.checkBucket(principal, bucket, "GET", query);
else scopes.checkBucket(principal, bucket, "GET", query);
return;
}
String method = switch (operation) { String method = switch (operation) {
case "read" -> "GET";
case "write" -> "PUT"; case "write" -> "PUT";
case "delete" -> "DELETE"; case "delete" -> "DELETE";
default -> "GET"; 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)) if (managed != null && managed.contains(principal))
managed.checkObject(principal, bucket, key, method, Map.of(), new Headers()); managed.checkObject(principal, bucket, key, method, Map.of(), new Headers());
else scopes.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; private Result inspectAccess(String principal, String operation, String bucket, String key)
return new Result(false, "Key scope", "Key scope does not allow this bucket, prefix, or operation"); 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"));
};
} }
S3Access.Decision decision;
if (operation.equals("list")) { private Result inspectRead(String principal, String bucket, String key) throws IOException {
decision = access.inspectBucket(bucket, principal);
} else if (operation.equals("read")) {
ObjectStorage.ListPage page = store.list(bucket, key, "", 1, null); ObjectStorage.ListPage page = store.list(bucket, key, "", 1, null);
if (page.objects().isEmpty() || !key.equals(page.objects().get(0).key())) if (page.objects().isEmpty() || !key.equals(page.objects().get(0).key()))
return new Result(false, "Object", "Current object does not exist"); return new Result(false, "Object", "Current object does not exist");
decision = access.inspectObject(bucket, key, page.objects().get(0).metadata(), principal); return policyResult(access.inspectObject(bucket, key, page.objects().get(0).metadata(), principal));
} else {
decision = access.inspectWrite(bucket, key, principal,
operation.equals("delete") ? "s3:DeleteObject" : "s3:PutObject");
} }
private static Result policyResult(S3Access.Decision decision) {
return new Result(decision.allowed(), "Bucket and identity policy", decision.reason()); return new Result(decision.allowed(), "Bucket and identity policy", decision.reason());
} }
} }
+94 -49
View File
@@ -12,9 +12,17 @@ final class AdminActions {
static String apply(ObjectStorage store, String action, Map<String, String> form, static String apply(ObjectStorage store, String action, Map<String, String> form,
Set<String> identities, ManagedCredentials managed) throws IOException { Set<String> identities, ManagedCredentials managed) throws IOException {
String bucket = form.get("bucket"); String bucket = required(form, "bucket", 63);
if (action.equals("create-bucket")) { return switch (action) {
bucket = required(form, "bucket", 63); case "create-bucket" -> createBucket(store, bucket, form);
case "rename-bucket" -> renameBucket(store, bucket, form, managed);
case "delete-bucket" -> deleteBucket(store, bucket, form);
default -> updateBucket(store, bucket, action, form, identities);
};
}
private static String createBucket(ObjectStorage store, String bucket, Map<String, String> form)
throws IOException {
boolean wizard = "wizard".equals(form.get("setup")); boolean wizard = "wizard".equals(form.get("setup"));
String versioning = form.getOrDefault("versioning", "off"); String versioning = form.getOrDefault("versioning", "off");
if (wizard && !versioning.equals("off") && !versioning.equals("enabled")) if (wizard && !versioning.equals("off") && !versioning.equals("enabled"))
@@ -22,15 +30,19 @@ final class AdminActions {
ObjectStorage.ObjectOwnership ownership = wizard ? ObjectStorage.ObjectOwnership ownership = wizard ?
BucketSecurity.ownership(form.getOrDefault("ownership", "BucketOwnerEnforced")) : BucketSecurity.ownership(form.getOrDefault("ownership", "BucketOwnerEnforced")) :
ObjectStorage.ObjectOwnership.BUCKET_OWNER_ENFORCED; ObjectStorage.ObjectOwnership.BUCKET_OWNER_ENFORCED;
ObjectStorage.PublicAccessBlock publicBlock = wizard ? new ObjectStorage.PublicAccessBlock( ObjectStorage.PublicAccessBlock publicBlock = wizard ? publicAccessBlock(form) :
form.containsKey("blockPublicAcls"), form.containsKey("ignorePublicAcls"),
form.containsKey("blockPublicPolicy"), form.containsKey("restrictPublicBuckets")) :
ObjectStorage.PublicAccessBlock.secure(); ObjectStorage.PublicAccessBlock.secure();
if (wizard && !publicBlock.equals(ObjectStorage.PublicAccessBlock.secure()) && if (wizard && !publicBlock.equals(ObjectStorage.PublicAccessBlock.secure()) &&
!"yes".equals(form.get("acknowledgePublic"))) !"yes".equals(form.get("acknowledgePublic")))
invalid("Confirm that relaxing public access controls may expose this bucket"); invalid("Confirm that relaxing public access controls may expose this bucket");
store.createBucket(bucket); store.createBucket(bucket);
if (wizard) { 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")) if (versioning.equals("enabled"))
store.setVersioning(bucket, ObjectStorage.VersioningState.ENABLED); store.setVersioning(bucket, ObjectStorage.VersioningState.ENABLED);
if (ownership != ObjectStorage.ObjectOwnership.BUCKET_OWNER_ENFORCED) if (ownership != ObjectStorage.ObjectOwnership.BUCKET_OWNER_ENFORCED)
@@ -38,51 +50,71 @@ final class AdminActions {
if (!publicBlock.equals(ObjectStorage.PublicAccessBlock.secure())) if (!publicBlock.equals(ObjectStorage.PublicAccessBlock.secure()))
store.setPublicAccessBlock(bucket, publicBlock); store.setPublicAccessBlock(bucket, publicBlock);
} }
return AdminBrowser.bucketUrl(bucket, "", null);
} private static String renameBucket(ObjectStorage store, String bucket, Map<String, String> form,
bucket = required(form, "bucket", 63); ManagedCredentials managed) throws IOException {
if (action.equals("rename-bucket")) {
confirm(form, bucket); confirm(form, bucket);
String newName = required(form, "newName", 63); String newName = required(form, "newName", 63);
String currentName = bucket; if (managed != null && managed.list().stream().anyMatch(key -> key.bucket().equals(bucket)))
if (managed != null && managed.list().stream().anyMatch(key -> key.bucket().equals(currentName)))
throw new StoreException(409, "BucketHasScopedKeys", throw new StoreException(409, "BucketHasScopedKeys",
"Move or remove scoped access keys for this bucket before renaming it"); "Move or remove scoped access keys for this bucket before renaming it");
store.renameBucket(bucket, newName); store.renameBucket(bucket, newName);
return AdminBrowser.bucketUrl(newName, "", null); return AdminBrowser.bucketUrl(newName, "", null);
} }
if (action.equals("delete-bucket")) {
private static String deleteBucket(ObjectStorage store, String bucket, Map<String, String> form)
throws IOException {
confirm(form, bucket); confirm(form, bucket);
store.deleteBucket(bucket); store.deleteBucket(bucket);
return AdminConsole.PATH + "/buckets"; return AdminConsole.PATH + "/buckets";
} }
private static String updateBucket(ObjectStorage store, String bucket, String action,
Map<String, String> form, Set<String> identities) throws IOException {
ObjectStorage.Bucket current = store.bucket(bucket); ObjectStorage.Bucket current = store.bucket(bucket);
switch (action) { switch (action) {
case "delete-object" -> { case "delete-object" -> { return deleteObject(store, bucket, form); }
case "versioning" -> setVersioning(store, bucket, form);
case "ownership" -> setOwnership(store, bucket, form);
case "public-access" -> setPublicAccess(store, bucket, current, form);
case "policy" -> setPolicy(store, bucket, current, form);
case "bucket-grant" -> setBucketGrant(store, bucket, current, form, identities);
case "object-grant" -> { return setObjectGrant(store, bucket, current, form, identities); }
case "object-tag" -> { return setObjectTag(store, bucket, form); }
default -> invalid("Unknown admin action");
}
return AdminBrowser.bucketUrl(bucket, "", null) + "#settings";
}
private static String deleteObject(ObjectStorage store, String bucket, Map<String, String> form)
throws IOException {
String key = required(form, "key", 1024); String key = required(form, "key", 1024);
if (!key.equals(form.get("confirm"))) invalid("Type the object key to confirm"); if (!key.equals(form.get("confirm"))) invalid("Type the object key to confirm");
String version = form.getOrDefault("version", ""); String version = version(form);
if (version.length() > 256) invalid("Invalid object version"); if (version != null && !version.equals(form.get("confirmVersion")))
if (!version.isEmpty() && !version.equals(form.get("confirmVersion")))
invalid("Type the version ID to confirm permanent deletion"); invalid("Type the version ID to confirm permanent deletion");
store.delete(bucket, key, version.isEmpty() ? null : version); store.delete(bucket, key, version);
return AdminBrowser.bucketUrl(bucket, key.contains("/") ? return AdminBrowser.bucketUrl(bucket, key.contains("/") ?
key.substring(0, key.lastIndexOf('/') + 1) : "", null); key.substring(0, key.lastIndexOf('/') + 1) : "", null);
} }
case "versioning" -> {
private static void setVersioning(ObjectStorage store, String bucket, Map<String, String> form)
throws IOException {
String state = required(form, "state", 16); String state = required(form, "state", 16);
if (!state.equals("ENABLED") && !state.equals("SUSPENDED")) invalid("Invalid versioning state"); if (!state.equals("ENABLED") && !state.equals("SUSPENDED")) invalid("Invalid versioning state");
store.setVersioning(bucket, ObjectStorage.VersioningState.valueOf(state)); store.setVersioning(bucket, ObjectStorage.VersioningState.valueOf(state));
} }
case "ownership" -> {
private static void setOwnership(ObjectStorage store, String bucket, Map<String, String> form)
throws IOException {
confirm(form, bucket); confirm(form, bucket);
String value = required(form, "ownership", 32); String value = required(form, "ownership", 32);
store.setBucketOwnership(bucket, BucketSecurity.ownership(value)); store.setBucketOwnership(bucket, BucketSecurity.ownership(value));
} }
case "public-access" -> {
ObjectStorage.PublicAccessBlock block = new ObjectStorage.PublicAccessBlock( private static void setPublicAccess(ObjectStorage store, String bucket, ObjectStorage.Bucket current,
form.containsKey("blockPublicAcls"), form.containsKey("ignorePublicAcls"), Map<String, String> form) throws IOException {
form.containsKey("blockPublicPolicy"), form.containsKey("restrictPublicBuckets")); ObjectStorage.PublicAccessBlock block = publicAccessBlock(form);
ObjectStorage.PublicAccessBlock previous = current.publicAccessBlock(); ObjectStorage.PublicAccessBlock previous = current.publicAccessBlock();
if (previous.blockPublicAcls() && !block.blockPublicAcls() || if (previous.blockPublicAcls() && !block.blockPublicAcls() ||
previous.ignorePublicAcls() && !block.ignorePublicAcls() || previous.ignorePublicAcls() && !block.ignorePublicAcls() ||
@@ -90,7 +122,15 @@ final class AdminActions {
previous.restrictPublicBuckets() && !block.restrictPublicBuckets()) confirm(form, bucket); previous.restrictPublicBuckets() && !block.restrictPublicBuckets()) confirm(form, bucket);
store.setPublicAccessBlock(bucket, block); store.setPublicAccessBlock(bucket, block);
} }
case "policy" -> {
private static ObjectStorage.PublicAccessBlock publicAccessBlock(Map<String, String> form) {
return new ObjectStorage.PublicAccessBlock(
form.containsKey("blockPublicAcls"), form.containsKey("ignorePublicAcls"),
form.containsKey("blockPublicPolicy"), form.containsKey("restrictPublicBuckets"));
}
private static void setPolicy(ObjectStorage store, String bucket, ObjectStorage.Bucket current,
Map<String, String> form) throws IOException {
String policy = form.getOrDefault("policy", "").trim(); String policy = form.getOrDefault("policy", "").trim();
if (policy.getBytes(StandardCharsets.UTF_8).length > 20480) invalid("Policy is too large"); if (policy.getBytes(StandardCharsets.UTF_8).length > 20480) invalid("Policy is too large");
if (!policy.isEmpty()) { if (!policy.isEmpty()) {
@@ -101,52 +141,57 @@ final class AdminActions {
} }
store.setBucketPolicy(bucket, policy.isEmpty() ? null : policy); store.setBucketPolicy(bucket, policy.isEmpty() ? null : policy);
} }
case "bucket-grant" -> {
private static void setBucketGrant(ObjectStorage store, String bucket, ObjectStorage.Bucket current,
Map<String, String> form, Set<String> identities) throws IOException {
Map<String, String> acl = updateGrants(current.acl(), form, identities); Map<String, String> acl = updateGrants(current.acl(), form, identities);
if (newPublicGrant(current.acl(), acl)) confirm(form, bucket); if (newPublicGrant(current.acl(), acl)) confirm(form, bucket);
BucketSecurity.checkAcl(current, new Headers(), acl, true); BucketSecurity.checkAcl(current, new Headers(), acl, true);
store.setBucketAcl(bucket, acl); store.setBucketAcl(bucket, acl);
} }
case "object-grant" -> {
private static String setObjectGrant(ObjectStorage store, String bucket, ObjectStorage.Bucket current,
Map<String, String> form, Set<String> identities) throws IOException {
String key = required(form, "key", 1024); String key = required(form, "key", 1024);
String version = form.getOrDefault("version", ""); String version = version(form);
if (version.length() > 256) invalid("Invalid object version");
String versionId = version.isEmpty() ? null : version;
ObjectStorage.Metadata metadata; ObjectStorage.Metadata metadata;
try (ObjectStorage.OpenObject opened = store.open(bucket, key, versionId)) { try (ObjectStorage.OpenObject opened = store.open(bucket, key, version)) {
metadata = opened.metadata(); metadata = opened.metadata();
} }
Map<String, String> acl = updateGrants(metadata.acl(), form, identities); Map<String, String> acl = updateGrants(metadata.acl(), form, identities);
if (newPublicGrant(metadata.acl(), acl)) confirm(form, bucket); if (newPublicGrant(metadata.acl(), acl)) confirm(form, bucket);
BucketSecurity.checkAcl(current, new Headers(), acl, true); BucketSecurity.checkAcl(current, new Headers(), acl, true);
store.setObjectAcl(bucket, key, versionId, acl); store.setObjectAcl(bucket, key, version, acl);
return AdminConsole.PATH + "/object?bucket=" + AdminBrowser.encoded(bucket) + return objectUrl(bucket, key, version);
"&key=" + AdminBrowser.encoded(key) +
(versionId == null ? "" : "&version=" + AdminBrowser.encoded(versionId));
} }
case "object-tag" -> {
private static String setObjectTag(ObjectStorage store, String bucket, Map<String, String> form)
throws IOException {
String key = required(form, "key", 1024); String key = required(form, "key", 1024);
String tag = required(form, "tag", 128); String tag = required(form, "tag", 128);
String version = form.getOrDefault("version", ""); String version = version(form);
if (version.length() > 256) invalid("Invalid object version"); Map<String, String> tags = new HashMap<>(store.tags(bucket, key, 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); if ("remove".equals(form.get("operation"))) tags.remove(tag);
else if ("add".equals(form.get("operation"))) { else if ("add".equals(form.get("operation"))) {
String value = form.get("value"); String value = form.get("value");
if (value == null || value.length() > 256) invalid("Invalid value"); if (value == null || value.length() > 256) invalid("Invalid value");
tags.put(tag, value); tags.put(tag, value);
} } else invalid("Invalid tag operation");
else invalid("Invalid tag operation");
ObjectAttributes.validateTags(tags); ObjectAttributes.validateTags(tags);
store.setTags(bucket, key, versionId, Map.copyOf(tags)); store.setTags(bucket, key, version, Map.copyOf(tags));
return objectUrl(bucket, key, version);
}
private static String version(Map<String, String> form) {
String version = form.getOrDefault("version", "");
if (version.length() > 256) invalid("Invalid object version");
return version.isEmpty() ? null : version;
}
private static String objectUrl(String bucket, String key, String version) {
return AdminConsole.PATH + "/object?bucket=" + AdminBrowser.encoded(bucket) + return AdminConsole.PATH + "/object?bucket=" + AdminBrowser.encoded(bucket) +
"&key=" + AdminBrowser.encoded(key) + "&key=" + AdminBrowser.encoded(key) +
(versionId == null ? "" : "&version=" + AdminBrowser.encoded(versionId)); (version == null ? "" : "&version=" + AdminBrowser.encoded(version));
}
default -> invalid("Unknown admin action");
}
return AdminBrowser.bucketUrl(bucket, "", null) + "#settings";
} }
private static Map<String, String> updateGrants(Map<String, String> current, private static Map<String, String> updateGrants(Map<String, String> current,
+35 -24
View File
@@ -119,13 +119,40 @@ final class AdminBulkJobs {
private void run(Job job) { private void run(Job job) {
try { try {
processPages(job);
job.state = job.cancel ? "Cancelled" : job.capped ? "Capped" : "Completed";
} catch (Exception error) {
job.state = "Failed";
append(job, "error", "", error.getClass().getSimpleName());
} finally {
job.finished = System.currentTimeMillis();
onFinish.accept(job.snapshot());
}
}
private void processPages(Job job) throws IOException {
String after = null; String after = null;
do { while (!job.cancel) {
if (job.cancel) break;
ObjectStorage.ListPage page = list(job, after); 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; int remaining = MAX_ITEMS - job.processed;
for (ObjectStorage.ListedObject entry : page.objects()) { for (ObjectStorage.ListedObject entry : page.objects()) {
if (job.cancel || job.processed >= MAX_ITEMS) break; 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 { try {
operations.read(() -> process(job.spec, entry)); operations.read(() -> process(job.spec, entry));
job.succeeded++; job.succeeded++;
@@ -135,31 +162,15 @@ final class AdminBulkJobs {
append(job, "ok", entry.key(), detail); append(job, "ok", entry.key(), detail);
} catch (Exception error) { } catch (Exception error) {
job.failed++; job.failed++;
String detail = error instanceof StoreException storeError ? append(job, "error", entry.key(), errorDetail(error));
storeError.code + ": " + storeError.getMessage() :
error.getClass().getSimpleName();
append(job, "error", entry.key(), detail.length() > 200 ?
detail.substring(0, 200) : detail);
} }
job.processed++; job.processed++;
} }
if (job.processed >= MAX_ITEMS) {
job.capped = page.truncated() || page.objects().size() > remaining; private static String errorDetail(Exception error) {
break; String detail = error instanceof StoreException storeError ?
} storeError.code + ": " + storeError.getMessage() : error.getClass().getSimpleName();
if (!page.truncated()) break; return detail.length() > 200 ? detail.substring(0, 200) : detail;
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 { private ObjectStorage.ListPage list(Job job, String after) throws IOException {
@@ -138,6 +138,13 @@ final class AdminOperationsPages {
return page(content.toString(), true); return page(content.toString(), true);
} }
ClusterStore.ClusterStatus status = cluster.status(); 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 healthy = status.nodes().stream().filter(ClusterStore.NodeStatus::reachable).count();
long hosts = status.nodes().stream().filter(ClusterStore.NodeStatus::reachable) long hosts = status.nodes().stream().filter(ClusterStore.NodeStatus::reachable)
.map(node -> node.node().hostId()).distinct().count(); .map(node -> node.node().hostId()).distinct().count();
@@ -150,8 +157,11 @@ final class AdminOperationsPages {
.append("</strong></biscuit-cardview><biscuit-cardview><small>Reachable nodes</small><strong>") .append("</strong></biscuit-cardview><biscuit-cardview><small>Reachable nodes</small><strong>")
.append(healthy).append(" / ").append(status.nodes().size()) .append(healthy).append(" / ").append(status.nodes().size())
.append("</strong></biscuit-cardview><biscuit-cardview><small>Reachable hosts</small><strong>") .append("</strong></biscuit-cardview><biscuit-cardview><small>Reachable hosts</small><strong>")
.append(hosts).append("</strong></biscuit-cardview></div>") .append(hosts).append("</strong></biscuit-cardview></div>");
.append("<section class=cluster-topology aria-label='Cluster topology'><div class=cluster-core>") }
private static void appendClusterTopology(StringBuilder content, ClusterStore.ClusterStatus status) {
content.append("<section class=cluster-topology aria-label='Cluster topology'><div class=cluster-core>")
.append("<strong>Metadata primary</strong><p>") .append("<strong>Metadata primary</strong><p>")
.append(status.metadataWritable() ? "Writable" : "Unavailable or read-only") .append(status.metadataWritable() ? "Writable" : "Unavailable or read-only")
.append("</p></div><div class=cluster-connect aria-hidden=true></div><div class=cluster-nodes>"); .append("</p></div><div class=cluster-connect aria-hidden=true></div><div class=cluster-nodes>");
@@ -163,8 +173,7 @@ final class AdminOperationsPages {
.append("</code><code>Host ").append(node.node().hostId()) .append("</code><code>Host ").append(node.node().hostId())
.append("</code><code>").append(escape(node.node().url().toString())) .append("</code><code>").append(escape(node.node().url().toString()))
.append("</code><small>Verified replicas at last repair: ") .append("</code><small>Verified replicas at last repair: ")
.append(status.repair() == null || !status.repair().state().equals("completed") || .append(!replicasMeasured(status) ?
status.repair().report().scanned() > 0 && status.verifiedReplicas().isEmpty() ?
"Not measured" : "Not measured" :
Long.toString(status.verifiedReplicas().getOrDefault(node.node().id(), 0L))) Long.toString(status.verifiedReplicas().getOrDefault(node.node().id(), 0L)))
.append("</small></div>"); .append("</small></div>");
@@ -174,16 +183,27 @@ final class AdminOperationsPages {
"Multiple nodes on one host do not provide host-level redundancy.</p>"); "Multiple nodes on one host do not provide host-level redundancy.</p>");
if (status.omittedNodes() > 0) content.append("<p class=rename-warning>") if (status.omittedNodes() > 0) content.append("<p class=rename-warning>")
.append(status.omittedNodes()).append(" additional nodes are not probed in this view.</p>"); .append(status.omittedNodes()).append(" additional nodes are not probed in this view.</p>");
}
private static boolean replicasMeasured(ClusterStore.ClusterStatus status) {
ClusterStore.RepairStatus repair = status.repair(); ClusterStore.RepairStatus repair = status.repair();
if (repair == null || !repair.state().equals("completed")) return false;
return repair.report().scanned() <= 0 || !status.verifiedReplicas().isEmpty();
}
private static void appendRepairProgress(StringBuilder content, ClusterStore.RepairStatus repair) {
content.append("<section class=insight><h3>Repair progress</h3>"); 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>"); if (repair == null) content.append("<p class=muted>No repair report has been recorded yet.</p>");
else { else {
appendRepairReport(content, repair);
}
content.append("<p class=muted>Repair is run by the separate cluster maintenance service. " +
"This panel does not trigger repair or change placement.</p></section>");
}
private static void appendRepairReport(StringBuilder content, ClusterStore.RepairStatus repair) {
ClusterStore.RepairReport report = repair.report(); ClusterStore.RepairReport report = repair.report();
boolean stale = repair.state().equals("running") && content.append("<p><strong>").append(repairLabel(repair))
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("</strong> · Started ")
.append(java.time.Instant.ofEpochMilli(repair.startedAt())) .append(java.time.Instant.ofEpochMilli(repair.startedAt()))
.append(" UTC · Last update ") .append(" UTC · Last update ")
@@ -199,8 +219,12 @@ final class AdminOperationsPages {
.append("<biscuit-cardview><small>Unrecoverable</small><strong>") .append("<biscuit-cardview><small>Unrecoverable</small><strong>")
.append(report.unrecoverable()).append("</strong></biscuit-cardview></div>"); .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>"); private static String repairLabel(ClusterStore.RepairStatus repair) {
return page(content.toString(), true); if (repair.state().equals("running")) {
return System.currentTimeMillis() - repair.updatedAt() > 300_000
? "May be interrupted" : "Running";
}
return repair.state().equals("failed") ? "Failed" : "Completed";
} }
} }
+44 -26
View File
@@ -576,7 +576,28 @@ final class DiskStore implements ObjectStorage {
synchronized (lock(destination)) { synchronized (lock(destination)) {
synchronized (this) { synchronized (this) {
Bucket configured = buckets.get(metadata.bucket()); Bucket configured = buckets.get(metadata.bucket());
if (expected != null) { checkExpectedVersion(configured, metadata, expected);
if (isVersioned(configured))
return installVersionedPending(destination, pending, metadata, createOnly,
configured.versioning());
}
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 (isVersioned(configured))
return installVersionedPending(destination, pending, metadata, createOnly,
configured.versioning());
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())); Metadata current = index.get(indexKey(metadata.bucket(), metadata.key()));
if (configured == null || configured.versioning() != VersioningState.ENABLED || if (configured == null || configured.versioning() != VersioningState.ENABLED ||
current == null || !expected.versionId().equals( current == null || !expected.versionId().equals(
@@ -585,55 +606,52 @@ final class DiskStore implements ObjectStorage {
!expected.tags().equals(current.tags()) || !expected.acl().equals(current.acl())) !expected.tags().equals(current.tags()) || !expected.acl().equals(current.acl()))
throw new StoreException(412, "PreconditionFailed", "Object changed since it was opened"); throw new StoreException(412, "PreconditionFailed", "Object changed since it was opened");
} }
if (configured != null && configured.versioning() != VersioningState.NEVER)
return installVersionedPending(destination, pending, metadata, createOnly, private static boolean isVersioned(Bucket configured) {
configured.versioning()); return configured != null && configured.versioning() != VersioningState.NEVER;
} }
long previous = 0;
boolean existed = Files.exists(destination); private Metadata previousMetadata(Path destination, boolean createOnly) throws IOException {
boolean legacy = false; if (!Files.exists(destination)) return null;
if (existed) {
if (createOnly) throw new StoreException(412, "PreconditionFailed", "Object already exists"); if (createOnly) throw new StoreException(412, "PreconditionFailed", "Object already exists");
try (var in = new DataInputStream(Files.newInputStream(destination))) { try (var in = new DataInputStream(Files.newInputStream(destination))) {
Metadata old = readRecord(in).metadata(); return readRecord(in).metadata();
previous = old.length();
legacy = old.key() == null;
} }
} }
long additional = Math.max(0, metadata.length() - previous);
synchronized (this) { private void reservePublication(String bucket, Bucket configured, long additional) {
Bucket configured = buckets.get(metadata.bucket());
if (configured != null && configured.versioning() != VersioningState.NEVER)
return installVersionedPending(destination, pending, metadata, createOnly,
configured.versioning());
if (Files.exists(catalog) && configured == null) if (Files.exists(catalog) && configured == null)
throw new StoreException(404, "NoSuchBucket", "Bucket not found"); throw new StoreException(404, "NoSuchBucket", "Bucket not found");
if (maxTotal - used - reservedBytes < additional) if (maxTotal - used - reservedBytes < additional)
throw new StoreException(507, "InsufficientStorage", "Store capacity limit reached"); throw new StoreException(507, "InsufficientStorage", "Store capacity limit reached");
reservedBytes += additional; reservedBytes += additional;
publishingByBucket.merge(metadata.bucket(), 1, Integer::sum); publishingByBucket.merge(bucket, 1, Integer::sum);
} }
private void publishUnversioned(Path destination, Path pending, Metadata metadata,
Metadata previous, long additional) throws IOException {
boolean moved = false; boolean moved = false;
try { try {
Files.move(pending, destination, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); Files.move(pending, destination, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
moved = true; moved = true;
syncDirectory(destination.getParent()); syncDirectory(destination.getParent());
} finally { } finally {
synchronized (this) { finishPublication(metadata, previous, additional, moved);
}
}
private synchronized void finishPublication(Metadata metadata, Metadata previous,
long additional, boolean moved) {
if (moved) { if (moved) {
used = used - previous + metadata.length(); used = used - (previous == null ? 0 : previous.length()) + metadata.length();
if (!existed) objectCount++; if (previous == null) objectCount++;
if (legacy) legacyCount--; else if (previous.key() == null) legacyCount--;
index.put(indexKey(metadata.bucket(), metadata.key()), metadata); index.put(indexKey(metadata.bucket(), metadata.key()), metadata);
} }
reservedBytes -= additional; reservedBytes -= additional;
publishingByBucket.compute(metadata.bucket(), (bucket, count) -> count == 1 ? null : count - 1); publishingByBucket.compute(metadata.bucket(), (bucket, count) -> count == 1 ? null : count - 1);
notifyAll(); notifyAll();
} }
}
return metadata;
}
}
private Metadata installVersionedPending(Path destination, Path pending, Metadata metadata, private Metadata installVersionedPending(Path destination, Path pending, Metadata metadata,
boolean createOnly, VersioningState state) throws IOException { boolean createOnly, VersioningState state) throws IOException {
@@ -46,20 +46,23 @@ final class RequestDiagnostics {
void record(String requestId, String operation, String bucket, int status, long elapsedNanos, void record(String requestId, String operation, String bucket, int status, long elapsedNanos,
String principal) { String principal) {
if (operation == null) operation = "Service";
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
long minute = now / MINUTE_MILLIS; recordWindow(currentWindow(now / MINUTE_MILLIS), status, elapsedNanos);
int slot = (int) Math.floorMod(minute, windows.length()); recordKey(principal, status, now);
Window window; if (status >= 400) recordFailure(requestId, operation, bucket, status, now);
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);
private Window currentWindow(long minute) {
int slot = (int) Math.floorMod(minute, windows.length());
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)) return fresh;
}
}
private static void recordWindow(Window window, int status, long elapsedNanos) {
window.requests.increment(); window.requests.increment();
if (status >= 500) window.serverErrors.increment(); if (status >= 500) window.serverErrors.increment();
else if (status >= 400) window.clientErrors.increment(); else if (status >= 400) window.clientErrors.increment();
@@ -68,24 +71,27 @@ final class RequestDiagnostics {
while (latencySlot < LATENCY_BOUNDS_MS.length && millis > LATENCY_BOUNDS_MS[latencySlot]) while (latencySlot < LATENCY_BOUNDS_MS.length && millis > LATENCY_BOUNDS_MS[latencySlot])
latencySlot++; latencySlot++;
window.latency[latencySlot].increment(); window.latency[latencySlot].increment();
if (principal != null && principal.length() <= 128) { }
private void recordKey(String principal, int status, long now) {
if (principal == null || principal.length() > 128) return;
KeyCounters counters = keys.get(principal); KeyCounters counters = keys.get(principal);
if (counters == null && keys.size() < 128) if (counters == null && keys.size() < 128)
counters = keys.computeIfAbsent(principal, ignored -> new KeyCounters()); counters = keys.computeIfAbsent(principal, ignored -> new KeyCounters());
if (counters != null) { if (counters == null) return;
counters.requests.increment(); counters.requests.increment();
if (status >= 400) counters.failures.increment(); if (status >= 400) counters.failures.increment();
counters.lastSeen.set(now); counters.lastSeen.set(now);
} }
}
if (status >= 400) { 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 (operation.length() > 32) operation = "Other";
if (bucket == null || bucket.length() > 63 || !bucket.matches("[a-zA-Z0-9.-]+")) bucket = "—"; if (bucket == null || bucket.length() > 63 || !bucket.matches("[a-zA-Z0-9.-]+")) bucket = "—";
long sequence = failureSequence.getAndIncrement(); long sequence = failureSequence.getAndIncrement();
failures.set((int) (sequence % failures.length()), failures.set((int) (sequence % failures.length()),
new Failure(sequence, now, requestId, operation, bucket, status)); new Failure(sequence, now, requestId, operation, bucket, status));
} }
}
List<KeyActivity> keyActivity() { List<KeyActivity> keyActivity() {
return keys.entrySet().stream().map(entry -> new KeyActivity(entry.getKey(), return keys.entrySet().stream().map(entry -> new KeyActivity(entry.getKey(),
@@ -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<ObjectStorage.ListedObject> 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<AdminBulkJobs.Snapshot> 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<AdminBulkJobs.Snapshot>(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<AdminBulkJobs.Snapshot>(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<AdminBulkJobs.Snapshot>(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<AdminBulkJobs.Snapshot>(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");
}
}
+193 -30
View File
@@ -16,8 +16,24 @@ import java.util.Comparator;
import java.util.Map; import java.util.Map;
import java.util.concurrent.Executors; 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 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) { private static void status(int wanted, HttpResponse<?> response) {
if (response.statusCode() != wanted) 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 { 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"); Path legacyBranding = root.resolve("legacy-branding.txt");
Files.writeString(legacyBranding, "ObjectStoreBranding 1\n" + Files.writeString(legacyBranding, "ObjectStoreBranding 1\n" +
java.util.Base64.getEncoder().encodeToString("Old name".getBytes(StandardCharsets.UTF_8)) + java.util.Base64.getEncoder().encodeToString("Old name".getBytes(StandardCharsets.UTF_8)) +
@@ -99,22 +173,9 @@ public final class AdminConsoleTest {
if (!new AdminBranding(legacyBranding).state().defaultTheme().equals("light") || if (!new AdminBranding(legacyBranding).state().defaultTheme().equals("light") ||
!new AdminBranding(legacyBranding).state().name().equals("Old name")) !new AdminBranding(legacyBranding).state().name().equals("Old name"))
throw new AssertionError("Global theme did not persist across branding migration"); 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"); private void verifyConfiguration() throws Exception {
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);
try {
if (AdminConsole.fromEnvironment(Map.of(), store) != null) if (AdminConsole.fromEnvironment(Map.of(), store) != null)
throw new AssertionError("Admin console enabled without configuration"); throw new AssertionError("Admin console enabled without configuration");
try { try {
@@ -136,16 +197,19 @@ public final class AdminConsoleTest {
throw new AssertionError("Admin console accepted invalid private origin: " + invalid); throw new AssertionError("Admin console accepted invalid private origin: " + invalid);
} catch (IllegalArgumentException expected) { } } catch (IllegalArgumentException expected) { }
} }
}
private void startServers() throws Exception {
AdminConsole console = AdminConsole.fromEnvironment(Map.of( AdminConsole console = AdminConsole.fromEnvironment(Map.of(
"ADMIN_UI_ENABLED", "true", "ADMIN_UI_PASSWORD_FILE", passwordFile.toString(), "ADMIN_UI_ENABLED", "true", "ADMIN_UI_PASSWORD_FILE", passwordFile.toString(),
"DATA_DIR", root.resolve("data").toString()), names); "DATA_DIR", root.resolve("data").toString()), names);
console.setDiskStore(store); console.setDiskStore(store);
var app = new Main(names, names, app = new Main(names, names,
new SigV4("TESTACCESSKEY123", "test-secret-key-that-is-at-least-32-characters", new SigV4("TESTACCESSKEY123", "test-secret-key-that-is-at-least-32-characters",
"us-east-1", Clock.systemUTC()), "objects"); "us-east-1", Clock.systemUTC()), "objects");
app.setBucketActivity(activity); app.setBucketActivity(activity);
app.setAdminConsole(console); app.setAdminConsole(console);
ManagedCredentials managed = ManagedCredentials.fromEnvironment(Map.of( managed = ManagedCredentials.fromEnvironment(Map.of(
"S3_MANAGED_KEYS_MASTER_FILE", masterFile.toString(), "S3_MANAGED_KEYS_MASTER_FILE", masterFile.toString(),
"DATA_DIR", root.resolve("data").toString()), store, java.util.Set.of("TESTACCESSKEY123")); "DATA_DIR", root.resolve("data").toString()), store, java.util.Set.of("TESTACCESSKEY123"));
app.setManagedCredentials(managed); app.setManagedCredentials(managed);
@@ -155,9 +219,9 @@ public final class AdminConsoleTest {
s3Server.setExecutor(executor); s3Server.setExecutor(executor);
s3Server.createContext("/", app::handle); s3Server.createContext("/", app::handle);
s3Server.start(); 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(); private void verifyUnauthenticatedAccess() throws Exception {
status(404, client.send(request(s3Base, "/login").GET().build(), status(404, client.send(request(s3Base, "/login").GET().build(),
HttpResponse.BodyHandlers.discarding())); HttpResponse.BodyHandlers.discarding()));
status(404, client.send(HttpRequest.newBuilder(URI.create(base + "/health")).GET().build(), status(404, client.send(HttpRequest.newBuilder(URI.create(base + "/health")).GET().build(),
@@ -181,6 +245,9 @@ public final class AdminConsoleTest {
} }
status(401, client.send(request(base, "/jobs.json?id=abcdefghijklmnop").GET().build(), status(401, client.send(request(base, "/jobs.json?id=abcdefghijklmnop").GET().build(),
HttpResponse.BodyHandlers.ofString())); HttpResponse.BodyHandlers.ofString()));
}
private void verifyLoginPage() throws Exception {
var loginPage = client.send(request(base, "/login").GET().build(), var loginPage = client.send(request(base, "/login").GET().build(),
HttpResponse.BodyHandlers.ofString()); HttpResponse.BodyHandlers.ofString());
status(200, loginPage); status(200, loginPage);
@@ -196,6 +263,9 @@ public final class AdminConsoleTest {
String policy = loginPage.headers().firstValue("Content-Security-Policy").orElse(""); String policy = loginPage.headers().firstValue("Content-Security-Policy").orElse("");
if (!policy.contains("style-src 'self'") || !policy.contains("img-src 'self'")) if (!policy.contains("style-src 'self'") || !policy.contains("img-src 'self'"))
throw new AssertionError("Admin console content policy missing"); throw new AssertionError("Admin console content policy missing");
}
private void verifyPublicAssets() throws Exception {
var logo = client.send(request(base, "/logo.png").GET().build(), var logo = client.send(request(base, "/logo.png").GET().build(),
HttpResponse.BodyHandlers.ofByteArray()); HttpResponse.BodyHandlers.ofByteArray());
status(200, logo); status(200, logo);
@@ -211,13 +281,19 @@ public final class AdminConsoleTest {
throw new AssertionError("Dark chart styles missing"); throw new AssertionError("Dark chart styles missing");
status(303, client.send(request(base, "/biscuit.js").GET().build(), status(303, client.send(request(base, "/biscuit.js").GET().build(),
HttpResponse.BodyHandlers.discarding())); HttpResponse.BodyHandlers.discarding()));
}
private void login() throws Exception {
status(403, post(client, base, "/login", PASSWORD, "invalid", null, null)); status(403, post(client, base, "/login", PASSWORD, "invalid", null, null));
status(401, post(client, base, "/login", "incorrect", loginToken(client, base), 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); var login = post(client, base, "/login", PASSWORD, loginToken(client, base), null, null);
status(303, login); status(303, login);
String cookie = login.headers().firstValue("Set-Cookie").orElseThrow().split(";", 2)[0]; cookie = login.headers().firstValue("Set-Cookie").orElseThrow().split(";", 2)[0];
if (!login.headers().firstValue("Set-Cookie").orElseThrow().contains("HttpOnly; SameSite=Strict")) if (!login.headers().firstValue("Set-Cookie").orElseThrow().contains("HttpOnly; SameSite=Strict"))
throw new AssertionError("Session cookie protections missing"); throw new AssertionError("Session cookie protections missing");
}
private void verifyOverview() throws Exception {
var overview = client.send(request(base, "/overview").header("Cookie", cookie).GET().build(), var overview = client.send(request(base, "/overview").header("Cookie", cookie).GET().build(),
HttpResponse.BodyHandlers.ofString()); HttpResponse.BodyHandlers.ofString());
status(200, overview); status(200, overview);
@@ -232,6 +308,10 @@ public final class AdminConsoleTest {
!overview.body().contains("class=mobile-nav-link") || !overview.body().contains("class=mobile-nav-link") ||
!overview.body().contains("biscuit-footerview")) !overview.body().contains("biscuit-footerview"))
throw new AssertionError("Authenticated overview missing"); 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(), var workspace = client.send(request(base, "/workspace.js").header("Cookie", cookie).GET().build(),
HttpResponse.BodyHandlers.ofString()); HttpResponse.BodyHandlers.ofString());
status(200, workspace); status(200, workspace);
@@ -242,6 +322,9 @@ public final class AdminConsoleTest {
throw new AssertionError("Biscuit bucket icon is unavailable"); throw new AssertionError("Biscuit bucket icon is unavailable");
if (!workspace.body().contains("registerCodeLanguage(\"json\"")) if (!workspace.body().contains("registerCodeLanguage(\"json\""))
throw new AssertionError("CodeView JSON highlighting is unavailable"); throw new AssertionError("CodeView JSON highlighting is unavailable");
}
private void verifyHealthAndDiagnostics() throws Exception {
var healthView = client.send(request(base, "/health").header("Cookie", cookie).GET().build(), var healthView = client.send(request(base, "/health").header("Cookie", cookie).GET().build(),
HttpResponse.BodyHandlers.ofString()); HttpResponse.BodyHandlers.ofString());
status(200, healthView); status(200, healthView);
@@ -256,6 +339,9 @@ public final class AdminConsoleTest {
!diagnosticsView.body().contains("Recent errors") || !diagnosticsView.body().contains("Recent errors") ||
!diagnosticsView.body().contains("diagnostic-probe")) !diagnosticsView.body().contains("diagnostic-probe"))
throw new AssertionError("Request diagnostics view missing"); throw new AssertionError("Request diagnostics view missing");
}
private void verifyAuditAccessCheck() throws Exception {
var auditView = client.send(request(base, "/audit").header("Cookie", cookie).GET().build(), var auditView = client.send(request(base, "/audit").header("Cookie", cookie).GET().build(),
HttpResponse.BodyHandlers.ofString()); HttpResponse.BodyHandlers.ofString());
status(200, auditView); status(200, auditView);
@@ -263,11 +349,14 @@ public final class AdminConsoleTest {
!auditView.body().contains("Admin event trail")) !auditView.body().contains("Admin event trail"))
throw new AssertionError("Audit and access view missing"); throw new AssertionError("Audit and access view missing");
var accessResult = action(client, base, "access-check", cookie, base, var accessResult = action(client, base, "access-check", cookie, base,
"csrf=" + csrf(overview.body()) + "csrf=" + adminCsrf +
"&principal=TESTACCESSKEY123&operation=list&bucket=photos&key="); "&principal=TESTACCESSKEY123&operation=list&bucket=photos&key=");
status(200, accessResult); status(200, accessResult);
if (!accessResult.body().contains("Owner or ACL grants this action")) if (!accessResult.body().contains("Owner or ACL grants this action"))
throw new AssertionError("Access checker did not use live S3 permissions"); throw new AssertionError("Access checker did not use live S3 permissions");
}
private void verifyJobsAndClusterViews() throws Exception {
var jobsView = client.send(request(base, "/jobs").header("Cookie", cookie).GET().build(), var jobsView = client.send(request(base, "/jobs").header("Cookie", cookie).GET().build(),
HttpResponse.BodyHandlers.ofString()); HttpResponse.BodyHandlers.ofString());
status(200, jobsView); status(200, jobsView);
@@ -284,6 +373,9 @@ public final class AdminConsoleTest {
if (probe.body().length != 1024 * 1024 || if (probe.body().length != 1024 * 1024 ||
!probe.headers().firstValue("Cache-Control").orElse("").equals("no-store")) !probe.headers().firstValue("Cache-Control").orElse("").equals("no-store"))
throw new AssertionError("Connection probe size or cache control changed"); throw new AssertionError("Connection probe size or cache control changed");
}
private void verifyPerformanceView() throws Exception {
var performance = client.send(request(base, "/performance").header("Cookie", cookie).GET().build(), var performance = client.send(request(base, "/performance").header("Cookie", cookie).GET().build(),
HttpResponse.BodyHandlers.ofString()); HttpResponse.BodyHandlers.ofString());
status(200, performance); status(200, performance);
@@ -298,6 +390,9 @@ public final class AdminConsoleTest {
throw new AssertionError("Performance charts must use Biscuit's dark renderer"); throw new AssertionError("Performance charts must use Biscuit's dark renderer");
status(200, client.send(request(base, "/performance.js").header("Cookie", cookie).GET().build(), status(200, client.send(request(base, "/performance.js").header("Cookie", cookie).GET().build(),
HttpResponse.BodyHandlers.ofString())); HttpResponse.BodyHandlers.ofString()));
}
private void verifyPerformanceEvents() throws Exception {
status(303, client.send(request(base, "/performance.events").GET().build(), status(303, client.send(request(base, "/performance.events").GET().build(),
HttpResponse.BodyHandlers.discarding())); HttpResponse.BodyHandlers.discarding()));
var events = client.send(request(base, "/performance.events") var events = client.send(request(base, "/performance.events")
@@ -307,6 +402,9 @@ public final class AdminConsoleTest {
!new String(events.body().readNBytes(6), StandardCharsets.UTF_8).equals("data: ")) !new String(events.body().readNBytes(6), StandardCharsets.UTF_8).equals("data: "))
throw new AssertionError("Performance event stream is unavailable"); throw new AssertionError("Performance event stream is unavailable");
events.body().close(); events.body().close();
}
private void verifyPerformanceCounters() throws Exception {
for (int poll = 0; poll < 2; poll++) { for (int poll = 0; poll < 2; poll++) {
var sample = client.send(request(base, "/performance.json") var sample = client.send(request(base, "/performance.json")
.header("Cookie", cookie).GET().build(), HttpResponse.BodyHandlers.ofString()); .header("Cookie", cookie).GET().build(), HttpResponse.BodyHandlers.ofString());
@@ -316,6 +414,9 @@ public final class AdminConsoleTest {
!sample.body().contains("\"heapBytes\":")) !sample.body().contains("\"heapBytes\":"))
throw new AssertionError("Admin polling was counted as S3 traffic or system data is missing"); throw new AssertionError("Admin polling was counted as S3 traffic or system data is missing");
} }
}
private void verifyBucketBrowser() throws Exception {
var bucketIndex = client.send(request(base, "/buckets").header("Cookie", cookie).GET().build(), var bucketIndex = client.send(request(base, "/buckets").header("Cookie", cookie).GET().build(),
HttpResponse.BodyHandlers.ofString()); HttpResponse.BodyHandlers.ofString());
status(200, bucketIndex); status(200, bucketIndex);
@@ -336,6 +437,9 @@ public final class AdminConsoleTest {
throw new AssertionError("Bucket folder or settings missing"); throw new AssertionError("Bucket folder or settings missing");
if (!bucket.body().contains("Upload file") || !bucket.body().contains("class='settings-form upload-form'")) if (!bucket.body().contains("Upload file") || !bucket.body().contains("class='settings-form upload-form'"))
throw new AssertionError("Bucket upload controls missing"); throw new AssertionError("Bucket upload controls missing");
}
private void verifyObjectBrowser() throws Exception {
var folder = client.send(request(base, "/bucket?name=photos&prefix=images%2F") var folder = client.send(request(base, "/bucket?name=photos&prefix=images%2F")
.header("Cookie", cookie).GET().build(), HttpResponse.BodyHandlers.ofString()); .header("Cookie", cookie).GET().build(), HttpResponse.BodyHandlers.ofString());
status(200, folder); status(200, folder);
@@ -357,7 +461,9 @@ public final class AdminConsoleTest {
status(200, client.send(request(base, status(200, client.send(request(base,
"/object?bucket=photos&key=images%2Fcat.txt&version=null") "/object?bucket=photos&key=images%2Fcat.txt&version=null")
.header("Cookie", cookie).GET().build(), HttpResponse.BodyHandlers.ofString())); .header("Cookie", cookie).GET().build(), HttpResponse.BodyHandlers.ofString()));
String adminCsrf = csrf(overview.body()); }
private void verifyUploadAndDownload() throws Exception {
byte[] uploadBody = "uploaded from admin".getBytes(StandardCharsets.UTF_8); byte[] uploadBody = "uploaded from admin".getBytes(StandardCharsets.UTF_8);
String uploadPath = "bucket=photos&key=images%2Fupload.txt"; String uploadPath = "bucket=photos&key=images%2Fupload.txt";
status(401, client.send(request(base, "/upload?" + uploadPath) status(401, client.send(request(base, "/upload?" + uploadPath)
@@ -388,6 +494,9 @@ public final class AdminConsoleTest {
HttpResponse.BodyHandlers.discarding())); HttpResponse.BodyHandlers.discarding()));
status(400, client.send(request(base, "/download?bucket=photos&key=x&key=y") status(400, client.send(request(base, "/download?bucket=photos&key=x&key=y")
.header("Cookie", cookie).GET().build(), HttpResponse.BodyHandlers.discarding())); .header("Cookie", cookie).GET().build(), HttpResponse.BodyHandlers.discarding()));
}
private void verifyBucketCreation() throws Exception {
status(403, action(client, base, "create-bucket", cookie, null, "bucket=archive")); status(403, action(client, base, "create-bucket", cookie, null, "bucket=archive"));
status(403, action(client, base, "create-bucket", cookie, "https://evil.example", status(403, action(client, base, "create-bucket", cookie, "https://evil.example",
"csrf=" + adminCsrf + "&bucket=archive")); "csrf=" + adminCsrf + "&bucket=archive"));
@@ -406,6 +515,16 @@ public final class AdminConsoleTest {
wizardBucket.ownership() != ObjectStorage.ObjectOwnership.BUCKET_OWNER_PREFERRED || wizardBucket.ownership() != ObjectStorage.ObjectOwnership.BUCKET_OWNER_PREFERRED ||
wizardBucket.publicAccessBlock().blockPublicAcls()) wizardBucket.publicAccessBlock().blockPublicAcls())
throw new AssertionError("Bucket wizard did not apply initial settings"); throw new AssertionError("Bucket wizard did not apply initial settings");
}
private void verifyManagedCredentials() throws Exception {
ManagedCredentials.Key scoped = createScopedKey();
verifyCredentialPersistence(scoped);
verifyCredentialScope(scoped);
verifyCredentialLifecycle(scoped);
}
private ManagedCredentials.Key createScopedKey() throws Exception {
var keys = client.send(request(base, "/credentials").header("Cookie", cookie).GET().build(), var keys = client.send(request(base, "/credentials").header("Cookie", cookie).GET().build(),
HttpResponse.BodyHandlers.ofString()); HttpResponse.BodyHandlers.ofString());
status(200, keys); status(200, keys);
@@ -427,6 +546,10 @@ public final class AdminConsoleTest {
client.send(request(base, "/credentials").header("Cookie", cookie).GET().build(), client.send(request(base, "/credentials").header("Cookie", cookie).GET().build(),
HttpResponse.BodyHandlers.ofString()).body().contains(scoped.secret())) HttpResponse.BodyHandlers.ofString()).body().contains(scoped.secret()))
throw new AssertionError("Secret must be shown once"); throw new AssertionError("Secret must be shown once");
return scoped;
}
private void verifyCredentialPersistence(ManagedCredentials.Key scoped) throws Exception {
if (Files.readString(root.resolve("data/managed-credentials.bin"), StandardCharsets.ISO_8859_1) if (Files.readString(root.resolve("data/managed-credentials.bin"), StandardCharsets.ISO_8859_1)
.contains(scoped.secret())) .contains(scoped.secret()))
throw new AssertionError("Managed secret was stored in cleartext"); throw new AssertionError("Managed secret was stored in cleartext");
@@ -435,6 +558,9 @@ public final class AdminConsoleTest {
"DATA_DIR", root.resolve("data").toString()), store, java.util.Set.of("TESTACCESSKEY123")); "DATA_DIR", root.resolve("data").toString()), store, java.util.Set.of("TESTACCESSKEY123"));
if (!restored.list().getFirst().secret().equals(scoped.secret())) if (!restored.list().getFirst().secret().equals(scoped.secret()))
throw new AssertionError("Managed key was not persisted"); throw new AssertionError("Managed key was not persisted");
}
private void verifyCredentialScope(ManagedCredentials.Key scoped) throws Exception {
status(200, client.send(HttpTest.signedUriAs(URI.create(s3Base + "/photos/images/cat.txt"), status(200, client.send(HttpTest.signedUriAs(URI.create(s3Base + "/photos/images/cat.txt"),
"GET", new byte[0], Map.of(), scoped.id(), scoped.secret()), "GET", new byte[0], Map.of(), scoped.id(), scoped.secret()),
HttpResponse.BodyHandlers.ofString())); HttpResponse.BodyHandlers.ofString()));
@@ -450,6 +576,9 @@ public final class AdminConsoleTest {
status(403, client.send(HttpTest.signedUriAs(URI.create(s3Base + "/photos?list-type=2"), status(403, client.send(HttpTest.signedUriAs(URI.create(s3Base + "/photos?list-type=2"),
"GET", new byte[0], Map.of(), scoped.id(), scoped.secret()), "GET", new byte[0], Map.of(), scoped.id(), scoped.secret()),
HttpResponse.BodyHandlers.ofString())); HttpResponse.BodyHandlers.ofString()));
}
private void verifyCredentialLifecycle(ManagedCredentials.Key scoped) throws Exception {
status(400, action(client, base, "disable-key", cookie, base, status(400, action(client, base, "disable-key", cookie, base,
"csrf=" + adminCsrf + "&id=" + scoped.id())); "csrf=" + adminCsrf + "&id=" + scoped.id()));
status(303, action(client, base, "disable-key", cookie, base, status(303, action(client, base, "disable-key", cookie, base,
@@ -478,6 +607,9 @@ public final class AdminConsoleTest {
status(403, client.send(HttpTest.signedUriAs(URI.create(s3Base + "/photos/images/cat.txt"), status(403, client.send(HttpTest.signedUriAs(URI.create(s3Base + "/photos/images/cat.txt"),
"GET", new byte[0], Map.of(), scoped.id(), scoped.secret()), "GET", new byte[0], Map.of(), scoped.id(), scoped.secret()),
HttpResponse.BodyHandlers.ofString())); HttpResponse.BodyHandlers.ofString()));
}
private void verifyBucketPolicies() throws Exception {
if (store.bucket("archive").ownership() != ObjectStorage.ObjectOwnership.BUCKET_OWNER_ENFORCED || if (store.bucket("archive").ownership() != ObjectStorage.ObjectOwnership.BUCKET_OWNER_ENFORCED ||
!store.bucket("archive").publicAccessBlock().equals(ObjectStorage.PublicAccessBlock.secure())) !store.bucket("archive").publicAccessBlock().equals(ObjectStorage.PublicAccessBlock.secure()))
throw new AssertionError("Created bucket did not have private defaults"); throw new AssertionError("Created bucket did not have private defaults");
@@ -504,6 +636,9 @@ public final class AdminConsoleTest {
status(303, action(client, base, "policy", cookie, base, policyForm + "&confirm=archive")); status(303, action(client, base, "policy", cookie, base, policyForm + "&confirm=archive"));
status(303, action(client, base, "policy", cookie, base, status(303, action(client, base, "policy", cookie, base,
"csrf=" + adminCsrf + "&bucket=archive&policy=")); "csrf=" + adminCsrf + "&bucket=archive&policy="));
}
private void verifyBucketGrantsAndVersioning() throws Exception {
status(400, action(client, base, "bucket-grant", cookie, base, status(400, action(client, base, "bucket-grant", cookie, base,
"csrf=" + adminCsrf + "&bucket=archive&principal=AllUsers&permission=READ&operation=add")); "csrf=" + adminCsrf + "&bucket=archive&principal=AllUsers&permission=READ&operation=add"));
status(303, action(client, base, "bucket-grant", cookie, base, status(303, action(client, base, "bucket-grant", cookie, base,
@@ -514,6 +649,9 @@ public final class AdminConsoleTest {
"csrf=" + adminCsrf + "&bucket=archive&principal=AllUsers&operation=remove")); "csrf=" + adminCsrf + "&bucket=archive&principal=AllUsers&operation=remove"));
status(303, action(client, base, "versioning", cookie, base, status(303, action(client, base, "versioning", cookie, base,
"csrf=" + adminCsrf + "&bucket=archive&state=ENABLED")); "csrf=" + adminCsrf + "&bucket=archive&state=ENABLED"));
}
private void verifyVersionedUpload() throws Exception {
store.createBucket("editor"); store.createBucket("editor");
store.setVersioning("editor", ObjectStorage.VersioningState.ENABLED); store.setVersioning("editor", ObjectStorage.VersioningState.ENABLED);
String versionedUpload = "bucket=editor&key=up.txt"; String versionedUpload = "bucket=editor&key=up.txt";
@@ -533,6 +671,9 @@ public final class AdminConsoleTest {
status(200, oldDownload); status(200, oldDownload);
if (!java.util.Arrays.equals(oldUpload, oldDownload.body())) if (!java.util.Arrays.equals(oldUpload, oldDownload.body()))
throw new AssertionError("Replacing an object lost its prior version"); throw new AssertionError("Replacing an object lost its prior version");
}
private void verifyTextEditing() throws Exception {
byte[] firstText = "{\"hello\":1}".getBytes(StandardCharsets.UTF_8); byte[] firstText = "{\"hello\":1}".getBytes(StandardCharsets.UTF_8);
ObjectStorage.Metadata firstVersion = store.put("editor", "note.json", ObjectStorage.Metadata firstVersion = store.put("editor", "note.json",
new ByteArrayInputStream(firstText), firstText.length, new ByteArrayInputStream(firstText), firstText.length,
@@ -562,6 +703,9 @@ public final class AdminConsoleTest {
status(409, stale); status(409, stale);
if (!stale.body().contains("The object changed") || !stale.body().contains("hello&quot;:2")) if (!stale.body().contains("The object changed") || !stale.body().contains("hello&quot;:2"))
throw new AssertionError("Stale edit diagnostic or draft is missing"); throw new AssertionError("Stale edit diagnostic or draft is missing");
}
private void verifyTagsAndDeletion() throws Exception {
if (store.bucket("archive").versioning() != ObjectStorage.VersioningState.ENABLED) if (store.bucket("archive").versioning() != ObjectStorage.VersioningState.ENABLED)
throw new AssertionError("Admin versioning change was not persisted"); throw new AssertionError("Admin versioning change was not persisted");
status(303, action(client, base, "object-tag", cookie, base, status(303, action(client, base, "object-tag", cookie, base,
@@ -581,6 +725,9 @@ public final class AdminConsoleTest {
"csrf=" + adminCsrf + "&bucket=archive")); "csrf=" + adminCsrf + "&bucket=archive"));
status(303, action(client, base, "delete-bucket", cookie, base, status(303, action(client, base, "delete-bucket", cookie, base,
"csrf=" + adminCsrf + "&bucket=archive&confirm=archive")); "csrf=" + adminCsrf + "&bucket=archive&confirm=archive"));
}
private void verifyBucketRename() throws Exception {
status(303, action(client, base, "create-bucket", cookie, base, status(303, action(client, base, "create-bucket", cookie, base,
"csrf=" + adminCsrf + "&bucket=rename-source")); "csrf=" + adminCsrf + "&bucket=rename-source"));
byte[] renamedBody = "renamed object".getBytes(StandardCharsets.UTF_8); byte[] renamedBody = "renamed object".getBytes(StandardCharsets.UTF_8);
@@ -606,6 +753,9 @@ public final class AdminConsoleTest {
status(404, client.send(HttpTest.signedUriAs(URI.create(s3Base + "/rename-source/stored.txt"), status(404, client.send(HttpTest.signedUriAs(URI.create(s3Base + "/rename-source/stored.txt"),
"GET", new byte[0], Map.of(), "TESTACCESSKEY123", "GET", new byte[0], Map.of(), "TESTACCESSKEY123",
"test-secret-key-that-is-at-least-32-characters"), HttpResponse.BodyHandlers.ofString())); "test-secret-key-that-is-at-least-32-characters"), HttpResponse.BodyHandlers.ofString()));
}
private void verifyThemeAndBrandingName() throws Exception {
var settingsPage = client.send(request(base, "/settings").header("Cookie", cookie).GET().build(), var settingsPage = client.send(request(base, "/settings").header("Cookie", cookie).GET().build(),
HttpResponse.BodyHandlers.ofString()); HttpResponse.BodyHandlers.ofString());
status(200, settingsPage); status(200, settingsPage);
@@ -632,6 +782,9 @@ public final class AdminConsoleTest {
status(200, brand); status(200, brand);
if (!brand.body().contains("LunarSky Storage")) if (!brand.body().contains("LunarSky Storage"))
throw new AssertionError("Server branding name was not saved"); throw new AssertionError("Server branding name was not saved");
}
private void verifyBrandingIcon() throws Exception {
byte[] tinyPng = java.util.Base64.getDecoder().decode( byte[] tinyPng = java.util.Base64.getDecoder().decode(
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+X5ZcAAAAASUVORK5CYII="); "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+X5ZcAAAAASUVORK5CYII=");
status(401, client.send(request(base, "/branding-icon/upload") status(401, client.send(request(base, "/branding-icon/upload")
@@ -664,6 +817,9 @@ public final class AdminConsoleTest {
if (!resetBrand.name().equals(AdminBranding.DEFAULT_NAME) || if (!resetBrand.name().equals(AdminBranding.DEFAULT_NAME) ||
!resetBrand.defaultTheme().equals("light")) !resetBrand.defaultTheme().equals("light"))
throw new AssertionError("Branding reset changed the global theme"); throw new AssertionError("Branding reset changed the global theme");
}
private void verifyInputEscaping() throws Exception {
status(400, client.send(request(base, "/bucket?name=photos&name=other") status(400, client.send(request(base, "/bucket?name=photos&name=other")
.header("Cookie", cookie).GET().build(), HttpResponse.BodyHandlers.ofString())); .header("Cookie", cookie).GET().build(), HttpResponse.BodyHandlers.ofString()));
var reflected = client.send(request(base, "/buckets?filter=%3Cscript%3E") var reflected = client.send(request(base, "/buckets?filter=%3Cscript%3E")
@@ -672,18 +828,24 @@ public final class AdminConsoleTest {
if (reflected.body().contains("value='<script>'") || if (reflected.body().contains("value='<script>'") ||
!reflected.body().contains("&lt;script&gt;")) !reflected.body().contains("&lt;script&gt;"))
throw new AssertionError("Bucket search was not escaped"); throw new AssertionError("Bucket search was not escaped");
}
private void verifyLogoutAndCooldown() throws Exception {
status(200, client.send(request(base, "/biscuit.js").header("Cookie", cookie).GET().build(), status(200, client.send(request(base, "/biscuit.js").header("Cookie", cookie).GET().build(),
HttpResponse.BodyHandlers.discarding())); HttpResponse.BodyHandlers.discarding()));
status(403, post(client, base, "/logout", "", "invalid", null, cookie)); status(403, post(client, base, "/logout", "", "invalid", null, cookie));
status(200, client.send(request(base, "/overview").header("Cookie", cookie).GET().build(), status(200, client.send(request(base, "/overview").header("Cookie", cookie).GET().build(),
HttpResponse.BodyHandlers.ofString())); HttpResponse.BodyHandlers.ofString()));
status(303, post(client, base, "/logout", "", csrf(overview.body()), null, cookie)); status(303, post(client, base, "/logout", "", adminCsrf, null, cookie));
status(303, client.send(request(base, "/overview").header("Cookie", cookie).GET().build(), status(303, client.send(request(base, "/overview").header("Cookie", cookie).GET().build(),
HttpResponse.BodyHandlers.ofString())); HttpResponse.BodyHandlers.ofString()));
for (int i = 0; i < 5; i++) { for (int i = 0; i < 5; i++) {
status(401, post(client, base, "/login", "incorrect", loginToken(client, base), null, null)); status(401, post(client, base, "/login", "incorrect", loginToken(client, base), null, null));
} }
status(429, post(client, base, "/login", PASSWORD, loginToken(client, base), null, null)); status(429, post(client, base, "/login", PASSWORD, loginToken(client, base), null, null));
}
private void verifyPrivateOrigin() throws Exception {
app.setAdminConsole(AdminConsole.fromEnvironment(Map.of( app.setAdminConsole(AdminConsole.fromEnvironment(Map.of(
"ADMIN_UI_ENABLED", "true", "ADMIN_UI_PASSWORD_FILE", passwordFile.toString(), "ADMIN_UI_ENABLED", "true", "ADMIN_UI_PASSWORD_FILE", passwordFile.toString(),
"ADMIN_UI_PRIVATE_ORIGIN", "http://10.30.0.120:9001", "ADMIN_UI_PRIVATE_ORIGIN", "http://10.30.0.120:9001",
@@ -701,8 +863,10 @@ public final class AdminConsoleTest {
!privateLogin.contains("Set-cookie: objectstore_admin=") || !privateLogin.contains("Set-cookie: objectstore_admin=") ||
privateLogin.contains("; Secure")) privateLogin.contains("; Secure"))
throw new AssertionError("Private VPN login or cookie is invalid"); throw new AssertionError("Private VPN login or cookie is invalid");
System.out.println("Admin console tests passed"); }
} finally {
@Override
public void close() throws Exception {
server.stop(0); server.stop(0);
s3Server.stop(0); s3Server.stop(0);
executor.close(); executor.close();
@@ -713,4 +877,3 @@ public final class AdminConsoleTest {
} }
} }
} }
}
@@ -3,6 +3,14 @@ package cloud.lunarsky.store;
public final class RequestDiagnosticsTest { public final class RequestDiagnosticsTest {
public static void main(String[] args) { public static void main(String[] args) {
RequestDiagnostics diagnostics = new RequestDiagnostics(); RequestDiagnostics diagnostics = new RequestDiagnostics();
rollingCounts(diagnostics);
boundedFailures(diagnostics);
keyCounters();
failureLabelsAndLatency();
System.out.println("Request diagnostics tests passed");
}
private static void rollingCounts(RequestDiagnostics diagnostics) {
diagnostics.record("request-1", "Object GET", "photos", 200, 4_000_000); 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-2", "Object PUT", "photos", 403, 16_000_000);
diagnostics.record("request-3", "Object GET", "a".repeat(200), 503, 700_000_000); diagnostics.record("request-3", "Object GET", "a".repeat(200), 503, 700_000_000);
@@ -14,6 +22,9 @@ public final class RequestDiagnosticsTest {
!result.recentFailures().get(0).bucket().equals("—") || !result.recentFailures().get(0).bucket().equals("—") ||
!result.recentFailures().get(1).bucket().equals("photos")) !result.recentFailures().get(1).bucket().equals("photos"))
throw new AssertionError("Rolling request diagnostics changed"); throw new AssertionError("Rolling request diagnostics changed");
}
private static void boundedFailures(RequestDiagnostics diagnostics) {
for (int index = 0; index < 70; index++) for (int index = 0; index < 70; index++)
diagnostics.record("bounded-" + index, "Object GET", "photos", 404, 1_000_000); diagnostics.record("bounded-" + index, "Object GET", "photos", 404, 1_000_000);
RequestDiagnostics.Snapshot bounded = diagnostics.snapshot(); RequestDiagnostics.Snapshot bounded = diagnostics.snapshot();
@@ -21,6 +32,33 @@ public final class RequestDiagnosticsTest {
!bounded.recentFailures().get(0).requestId().equals("bounded-69") || !bounded.recentFailures().get(0).requestId().equals("bounded-69") ||
!bounded.recentFailures().get(63).requestId().equals("bounded-6")) !bounded.recentFailures().get(63).requestId().equals("bounded-6"))
throw new AssertionError("Recent failure history is not bounded"); throw new AssertionError("Recent failure history is not bounded");
System.out.println("Request diagnostics tests passed"); }
private static void keyCounters() {
RequestDiagnostics diagnostics = new RequestDiagnostics();
diagnostics.record("key-ok", "Object GET", "photos", 200, 1_000_000, "reader");
diagnostics.record("key-error", "Object GET", "photos", 403, 1_000_000, "reader");
diagnostics.record("anonymous", "Object GET", "photos", 200, 1_000_000, null);
diagnostics.record("invalid-key", "Object GET", "photos", 403, 1_000_000, "x".repeat(129));
var activity = diagnostics.keyActivity();
if (activity.size() != 1) throw new AssertionError("Invalid principals entered key counters");
var reader = activity.getFirst();
if (!reader.principal().equals("reader") || reader.requests() != 2 ||
reader.failures() != 1 || reader.lastSeenMillis() <= 0)
throw new AssertionError("Authenticated key activity changed");
}
private static void failureLabelsAndLatency() {
RequestDiagnostics diagnostics = new RequestDiagnostics();
diagnostics.record("missing-label", null, "invalid/bucket", 404, -1);
diagnostics.record("long-label", "x".repeat(33), "photos", 503, 10_001_000_000L);
var result = diagnostics.snapshot();
var newest = result.recentFailures().getFirst();
var oldest = result.recentFailures().getLast();
if (!newest.operation().equals("Other") || !newest.bucket().equals("photos") ||
!oldest.operation().equals("Service") || !oldest.bucket().equals("—"))
throw new AssertionError("Failure labels were not normalized");
if (result.p50Millis() != 1 || result.p95Millis() != -1 || result.p99Millis() != -1)
throw new AssertionError("Latency underflow or overflow bucket changed");
} }
} }