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