Expand admin tools and harden storage operations

This commit is contained in:
admin committed 2026-11-07 10:09:32 +01:00
1 parent fbec6694df
commit 5304dfc047
86 files changed
+8111 -1102

No files matched your search

+89
View File
@@ -0,0 +1,89 @@
const assert = require("node:assert/strict");
const fs = require("node:fs");
const path = require("node:path");
const vm = require("node:vm");
async function staleAccessCheck() {
const base = "http://localhost/_objectstore/admin";
const location = new URL(base + "/audit");
const events = new Map();
const requests = [];
let content;
let replacements = 0;
const makeContent = () => ({
isConnected: true,
querySelector: () => null,
querySelectorAll: () => [],
replaceWith(next) {
this.isConnected = false;
content = next;
replacements++;
}
});
content = makeContent();
const initial = content;
class Form {
action = base + "/action/access-check";
get isConnected() { return initial.isConnected; }
closest() { return initial; }
}
class Link {
href = base + "/buckets";
target = "";
hasAttribute() { return false; }
}
const document = {
body: { dataset: {} },
getElementById: () => null,
querySelector: selector => selector === ".workspace-content" ? content : null,
querySelectorAll: () => [],
addEventListener: (type, callback) => events.set(type, callback),
importNode: node => node
};
const history = {
state: null,
replaceState(state, title, url) {
this.state = state;
location.href = new URL(url, location).href;
},
pushState(state, title, url) { this.replaceState(state, title, url); }
};
const context = {
document, history, location, URL, URLSearchParams, AbortController, AbortSignal,
HTMLFormElement: Form, HTMLAnchorElement: Link,
FormData: class extends Map { constructor() { super(); } },
DOMParser: class {
parseFromString() {
return { title: "ObjectStore admin", querySelector: () => makeContent() };
}
},
localStorage: { getItem: () => null },
matchMedia: () => ({ matches: false, addEventListener() {} }),
setTimeout, clearTimeout, console,
window: { scrollY: 0, scrollTo() {}, addEventListener() {} },
fetch(url, options) {
if (String(url).endsWith("/branding.json")) return Promise.resolve({ ok: false });
return new Promise(resolve => requests.push({ url: String(url), options, resolve }));
}
};
vm.runInNewContext(fs.readFileSync(path.join(__dirname, "../admin-ui/workspace.js"), "utf8"), context);
events.get("submit")({ target: new Form(), defaultPrevented: false, preventDefault() {} });
assert.equal(requests.length, 1);
events.get("click")({ defaultPrevented: false, button: 0,
composedPath: () => [new Link()], preventDefault() {} });
assert.equal(requests.length, 2);
assert.equal(requests[0].options.signal.aborted, true, "Navigation must cancel the old access check");
const respond = (request, url) => request.resolve({
url, ok: true, headers: { get: () => "text/html" }, text: async () => "page"
});
respond(requests[1], base + "/buckets");
await new Promise(setImmediate);
respond(requests[0], base + "/audit");
await new Promise(setImmediate);
assert.equal(location.pathname, "/_objectstore/admin/buckets");
assert.equal(replacements, 1, "Late access-check response replaced the newly opened page");
}
staleAccessCheck().then(() => console.log("Admin workspace tests passed: stale access-check response"))
.catch(error => { console.error(error); process.exitCode = 1; });
+457 -8
View File
@@ -45,6 +45,28 @@ public final class AdminConsoleTest {
return match.group(1);
}
private static HttpResponse<String> action(HttpClient client, String base, String name,
String cookie, String origin, String form) throws Exception {
var builder = request(base, "/action/" + name)
.header("Content-Type", "application/x-www-form-urlencoded")
.header("Cookie", cookie);
if (origin != null) builder.header("Origin", origin);
return client.send(builder.POST(HttpRequest.BodyPublishers.ofString(form)).build(),
HttpResponse.BodyHandlers.ofString());
}
private static HttpResponse<String> upload(HttpClient client, String base, String path,
String cookie, String origin, String csrf,
byte[] content) throws Exception {
var builder = request(base, "/upload?" + path)
.header("Content-Type", "text/plain")
.header("Cookie", cookie);
if (origin != null) builder.header("Origin", origin);
if (csrf != null) builder.header("X-ObjectStore-CSRF", csrf);
return client.send(builder.POST(HttpRequest.BodyPublishers.ofByteArray(content)).build(),
HttpResponse.BodyHandlers.ofString());
}
private static String loginToken(HttpClient client, String base) throws Exception {
return csrf(client.send(request(base, "/login").GET().build(),
HttpResponse.BodyHandlers.ofString()).body());
@@ -65,13 +87,30 @@ public final class AdminConsoleTest {
public static void main(String[] args) throws Exception {
Path root = Files.createTempDirectory("admin-console-test-");
Path legacyBranding = root.resolve("legacy-branding.txt");
Files.writeString(legacyBranding, "ObjectStoreBranding 1\n" +
java.util.Base64.getEncoder().encodeToString("Old name".getBytes(StandardCharsets.UTF_8)) +
"\n\n\n");
AdminBranding migrated = new AdminBranding(legacyBranding);
if (!migrated.state().name().equals("Old name") ||
!migrated.state().defaultTheme().equals("deep-dark"))
throw new AssertionError("Legacy branding or deep-dark default was lost");
migrated.setDefaultTheme("light");
if (!new AdminBranding(legacyBranding).state().defaultTheme().equals("light") ||
!new AdminBranding(legacyBranding).state().name().equals("Old name"))
throw new AssertionError("Global theme did not persist across branding migration");
Path passwordFile = root.resolve("password");
Files.writeString(passwordFile, PASSWORD + "\n");
Path masterFile = root.resolve("credential-master");
Files.writeString(masterFile, "0123456789abcdef".repeat(4));
DiskStore store = new DiskStore(root.resolve("data"), 1024, 4096);
store.ensureBucket("photos");
byte[] image = "small preview".getBytes(StandardCharsets.UTF_8);
store.put("photos", "images/cat.txt", new ByteArrayInputStream(image), image.length,
SigV4.hex(SigV4.hash(image)), null, true, "text/plain");
DiskBucketNames names = new DiskBucketNames(store, new MultipartStore(store));
BucketActivity activity = new BucketActivity(root.resolve("data/bucket-activity.tsv"));
activity.record("photos", "GET");
var executor = Executors.newVirtualThreadPerTaskExecutor();
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 16);
HttpServer s3Server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 16);
@@ -98,11 +137,18 @@ public final class AdminConsoleTest {
} catch (IllegalArgumentException expected) { }
}
AdminConsole console = AdminConsole.fromEnvironment(Map.of(
"ADMIN_UI_ENABLED", "true", "ADMIN_UI_PASSWORD_FILE", passwordFile.toString()), store);
var app = new Main(store, new MultipartStore(store),
"ADMIN_UI_ENABLED", "true", "ADMIN_UI_PASSWORD_FILE", passwordFile.toString(),
"DATA_DIR", root.resolve("data").toString()), names);
console.setDiskStore(store);
var app = new Main(names, names,
new SigV4("TESTACCESSKEY123", "test-secret-key-that-is-at-least-32-characters",
"us-east-1", Clock.systemUTC()), "objects");
app.setBucketActivity(activity);
app.setAdminConsole(console);
ManagedCredentials managed = ManagedCredentials.fromEnvironment(Map.of(
"S3_MANAGED_KEYS_MASTER_FILE", masterFile.toString(),
"DATA_DIR", root.resolve("data").toString()), store, java.util.Set.of("TESTACCESSKEY123"));
app.setManagedCredentials(managed);
server.setExecutor(executor);
server.createContext("/", app::handleAdmin);
server.start();
@@ -125,12 +171,16 @@ public final class AdminConsoleTest {
}
status(303, client.send(request(base, "/overview").GET().build(),
HttpResponse.BodyHandlers.ofString()));
for (String path : new String[] { "/performance", "/performance.json", "/performance.js",
for (String path : new String[] { "/performance", "/performance.json", "/performance.js", "/settings",
"/health", "/diagnostics", "/diagnostics/probe.bin",
"/audit", "/jobs", "/cluster",
"/buckets", "/bucket?name=photos",
"/object?bucket=photos&key=images%2Fcat.txt" }) {
status(303, client.send(request(base, path).GET().build(),
HttpResponse.BodyHandlers.ofString()));
}
status(401, client.send(request(base, "/jobs.json?id=abcdefghijklmnop").GET().build(),
HttpResponse.BodyHandlers.ofString()));
var loginPage = client.send(request(base, "/login").GET().build(),
HttpResponse.BodyHandlers.ofString());
status(200, loginPage);
@@ -138,6 +188,11 @@ public final class AdminConsoleTest {
!loginPage.body().contains("/_objectstore/admin/logo.png") ||
!loginPage.headers().firstValue("Cache-Control").orElse("").equals("no-store"))
throw new AssertionError("Login page or cache control missing");
var loginAppearance = client.send(request(base, "/workspace.js").GET().build(),
HttpResponse.BodyHandlers.ofString());
status(200, loginAppearance);
if (!loginAppearance.body().contains("applyPreferences"))
throw new AssertionError("Login appearance script missing");
String policy = loginPage.headers().firstValue("Content-Security-Policy").orElse("");
if (!policy.contains("style-src 'self'") || !policy.contains("img-src 'self'"))
throw new AssertionError("Admin console content policy missing");
@@ -169,8 +224,66 @@ public final class AdminConsoleTest {
if (!overview.body().contains("Storage mode") ||
!overview.body().contains("biscuit-cardview") || !overview.body().contains("photos") ||
!overview.body().contains("/performance") ||
!overview.body().contains("/_objectstore/admin/logo.png"))
!overview.body().contains("/_objectstore/admin/logo.png") ||
!overview.body().contains("biscuit-sidebarview") ||
!overview.body().contains("biscuit-navbarview") ||
!overview.body().contains("/icons/bucket.svg") ||
!overview.body().contains("/icons/activity.svg") ||
!overview.body().contains("class=mobile-nav-link") ||
!overview.body().contains("biscuit-footerview"))
throw new AssertionError("Authenticated overview missing");
var workspace = client.send(request(base, "/workspace.js").header("Cookie", cookie).GET().build(),
HttpResponse.BodyHandlers.ofString());
status(200, workspace);
var bucketIcon = client.send(request(base, "/icons/bucket.svg")
.header("Cookie", cookie).GET().build(), HttpResponse.BodyHandlers.ofString());
status(200, bucketIcon);
if (!bucketIcon.body().contains("<svg"))
throw new AssertionError("Biscuit bucket icon is unavailable");
if (!workspace.body().contains("registerCodeLanguage(\"json\""))
throw new AssertionError("CodeView JSON highlighting is unavailable");
var healthView = client.send(request(base, "/health").header("Cookie", cookie).GET().build(),
HttpResponse.BodyHandlers.ofString());
status(200, healthView);
if (!healthView.body().contains("Filesystem available") ||
!healthView.body().contains("Latest restore test") ||
!healthView.body().contains("Not reported"))
throw new AssertionError("Health view implies an unverified backup or hides disk state");
var diagnosticsView = client.send(request(base, "/diagnostics").header("Cookie", cookie).GET().build(),
HttpResponse.BodyHandlers.ofString());
status(200, diagnosticsView);
if (!diagnosticsView.body().contains("p50 / p95") ||
!diagnosticsView.body().contains("Recent errors") ||
!diagnosticsView.body().contains("diagnostic-probe"))
throw new AssertionError("Request diagnostics view missing");
var auditView = client.send(request(base, "/audit").header("Cookie", cookie).GET().build(),
HttpResponse.BodyHandlers.ofString());
status(200, auditView);
if (!auditView.body().contains("Check access") ||
!auditView.body().contains("Admin event trail"))
throw new AssertionError("Audit and access view missing");
var accessResult = action(client, base, "access-check", cookie, base,
"csrf=" + csrf(overview.body()) +
"&principal=TESTACCESSKEY123&operation=list&bucket=photos&key=");
status(200, accessResult);
if (!accessResult.body().contains("Owner or ACL grants this action"))
throw new AssertionError("Access checker did not use live S3 permissions");
var jobsView = client.send(request(base, "/jobs").header("Cookie", cookie).GET().build(),
HttpResponse.BodyHandlers.ofString());
status(200, jobsView);
if (!jobsView.body().contains("Bulk jobs") || !jobsView.body().contains("Export inventory"))
throw new AssertionError("Bulk jobs view missing");
var clusterView = client.send(request(base, "/cluster").header("Cookie", cookie).GET().build(),
HttpResponse.BodyHandlers.ofString());
status(200, clusterView);
if (!clusterView.body().contains("disk mode"))
throw new AssertionError("Disk gateway should not claim cluster health");
var probe = client.send(request(base, "/diagnostics/probe.bin").header("Cookie", cookie).GET().build(),
HttpResponse.BodyHandlers.ofByteArray());
status(200, probe);
if (probe.body().length != 1024 * 1024 ||
!probe.headers().firstValue("Cache-Control").orElse("").equals("no-store"))
throw new AssertionError("Connection probe size or cache control changed");
var performance = client.send(request(base, "/performance").header("Cookie", cookie).GET().build(),
HttpResponse.BodyHandlers.ofString());
status(200, performance);
@@ -181,10 +294,19 @@ public final class AdminConsoleTest {
!performance.body().contains("Process RAM") ||
!performance.body().contains("performance.js"))
throw new AssertionError("Performance view missing");
if (performance.body().split("theme=dark type=line", -1).length != 5)
if (performance.body().split("theme=deep-dark type=line", -1).length != 5)
throw new AssertionError("Performance charts must use Biscuit's dark renderer");
status(200, client.send(request(base, "/performance.js").header("Cookie", cookie).GET().build(),
HttpResponse.BodyHandlers.ofString()));
status(303, client.send(request(base, "/performance.events").GET().build(),
HttpResponse.BodyHandlers.discarding()));
var events = client.send(request(base, "/performance.events")
.header("Cookie", cookie).GET().build(), HttpResponse.BodyHandlers.ofInputStream());
status(200, events);
if (!events.headers().firstValue("Content-Type").orElse("").startsWith("text/event-stream") ||
!new String(events.body().readNBytes(6), StandardCharsets.UTF_8).equals("data: "))
throw new AssertionError("Performance event stream is unavailable");
events.body().close();
for (int poll = 0; poll < 2; poll++) {
var sample = client.send(request(base, "/performance.json")
.header("Cookie", cookie).GET().build(), HttpResponse.BodyHandlers.ofString());
@@ -199,16 +321,26 @@ public final class AdminConsoleTest {
status(200, bucketIndex);
if (!bucketIndex.body().contains("/bucket?name=photos"))
throw new AssertionError("Bucket index did not link to photos");
if (!bucketIndex.body().contains("biscuit-formwizardview") ||
!bucketIndex.body().contains("blockPublicPolicy") ||
!bucketIndex.body().contains("Public access blocked") ||
!bucketIndex.body().contains("biscuit-pageloaderview"))
throw new AssertionError("New bucket setup wizard is missing");
var bucket = client.send(request(base, "/bucket?name=photos").header("Cookie", cookie).GET().build(),
HttpResponse.BodyHandlers.ofString());
status(200, bucket);
if (!bucket.body().contains("images/") || !bucket.body().contains("Bucket settings"))
if (!bucket.body().contains("images/") || !bucket.body().contains("Bucket settings") ||
!bucket.body().contains("biscuit-tablayout") ||
!bucket.body().contains("biscuit-activity-chart") ||
!bucket.body().contains("Daily S3 requests"))
throw new AssertionError("Bucket folder or settings missing");
if (!bucket.body().contains("Upload file") || !bucket.body().contains("class='settings-form upload-form'"))
throw new AssertionError("Bucket upload controls missing");
var folder = client.send(request(base, "/bucket?name=photos&prefix=images%2F")
.header("Cookie", cookie).GET().build(), HttpResponse.BodyHandlers.ofString());
status(200, folder);
if (!folder.body().contains("cat.txt") || !folder.body().contains("biscuit-chartview") ||
!folder.body().contains("theme=dark") ||
!folder.body().contains("theme=deep-dark") ||
!folder.body().contains("this page only"))
throw new AssertionError("Folder listing or bounded chart missing");
var object = client.send(request(base, "/object?bucket=photos&key=images%2Fcat.txt")
@@ -217,6 +349,321 @@ public final class AdminConsoleTest {
if (!object.body().contains("Content type") || !object.body().contains("text/plain") ||
!object.body().contains("SHA-256"))
throw new AssertionError("Object metadata missing");
var versions = client.send(request(base, "/versions?bucket=photos&prefix=images%2F")
.header("Cookie", cookie).GET().build(), HttpResponse.BodyHandlers.ofString());
status(200, versions);
if (!versions.body().contains("cat.txt") || !versions.body().contains("&amp;version=null"))
throw new AssertionError("Version browser did not link to the object");
status(200, client.send(request(base,
"/object?bucket=photos&key=images%2Fcat.txt&version=null")
.header("Cookie", cookie).GET().build(), HttpResponse.BodyHandlers.ofString()));
String adminCsrf = csrf(overview.body());
byte[] uploadBody = "uploaded from admin".getBytes(StandardCharsets.UTF_8);
String uploadPath = "bucket=photos&key=images%2Fupload.txt";
status(401, client.send(request(base, "/upload?" + uploadPath)
.header("Content-Type", "text/plain")
.POST(HttpRequest.BodyPublishers.ofByteArray(uploadBody)).build(),
HttpResponse.BodyHandlers.ofString()));
status(403, upload(client, base, uploadPath, cookie, base, null, uploadBody));
status(403, upload(client, base, uploadPath, cookie, "https://evil.example",
adminCsrf, uploadBody));
var uploaded = upload(client, base, uploadPath, cookie, base, adminCsrf, uploadBody);
status(201, uploaded);
if (!uploaded.headers().firstValue("Location").orElse("")
.equals(AdminConsole.PATH + "/object?bucket=photos&key=images%2Fupload.txt"))
throw new AssertionError("Upload did not link to the object");
status(412, upload(client, base, uploadPath, cookie, base, adminCsrf, uploadBody));
status(409, upload(client, base, uploadPath + "&overwrite=1", cookie, base,
adminCsrf, uploadBody));
status(413, upload(client, base, "bucket=photos&key=too-large.txt", cookie, base,
adminCsrf, new byte[1025]));
var downloaded = client.send(request(base, "/download?" + uploadPath)
.header("Cookie", cookie).GET().build(), HttpResponse.BodyHandlers.ofByteArray());
status(200, downloaded);
if (!java.util.Arrays.equals(uploadBody, downloaded.body()) ||
!downloaded.headers().firstValue("Content-Disposition").orElse("")
.contains("filename*=UTF-8''upload.txt"))
throw new AssertionError("Admin download changed file content or filename");
status(303, client.send(request(base, "/download?" + uploadPath).GET().build(),
HttpResponse.BodyHandlers.discarding()));
status(400, client.send(request(base, "/download?bucket=photos&key=x&key=y")
.header("Cookie", cookie).GET().build(), HttpResponse.BodyHandlers.discarding()));
status(403, action(client, base, "create-bucket", cookie, null, "bucket=archive"));
status(403, action(client, base, "create-bucket", cookie, "https://evil.example",
"csrf=" + adminCsrf + "&bucket=archive"));
status(303, action(client, base, "create-bucket", cookie, base,
"csrf=" + adminCsrf + "&bucket=archive"));
status(400, action(client, base, "create-bucket", cookie, base,
"csrf=" + adminCsrf + "&bucket=wizard-bucket&setup=wizard&versioning=enabled" +
"&ownership=BucketOwnerPreferred&ignorePublicAcls=on&blockPublicPolicy=on" +
"&restrictPublicBuckets=on"));
status(303, action(client, base, "create-bucket", cookie, base,
"csrf=" + adminCsrf + "&bucket=wizard-bucket&setup=wizard&versioning=enabled" +
"&ownership=BucketOwnerPreferred&ignorePublicAcls=on&blockPublicPolicy=on" +
"&restrictPublicBuckets=on&acknowledgePublic=yes"));
var wizardBucket = names.bucket("wizard-bucket");
if (wizardBucket.versioning() != ObjectStorage.VersioningState.ENABLED ||
wizardBucket.ownership() != ObjectStorage.ObjectOwnership.BUCKET_OWNER_PREFERRED ||
wizardBucket.publicAccessBlock().blockPublicAcls())
throw new AssertionError("Bucket wizard did not apply initial settings");
var keys = client.send(request(base, "/credentials").header("Cookie", cookie).GET().build(),
HttpResponse.BodyHandlers.ofString());
status(200, keys);
if (!keys.body().contains("Create scoped key") || !keys.body().contains("photos"))
throw new AssertionError("Access key controls missing");
status(403, action(client, base, "create-key", cookie, base,
"bucket=photos&prefix=images%2F&read=on"));
var newKey = action(client, base, "create-key", cookie, base,
"csrf=" + adminCsrf + "&bucket=photos&prefix=images%2F&read=on&write=on&list=on");
status(200, newKey);
if (!newKey.body().contains("Save this secret now") || managed.list().size() != 1)
throw new AssertionError("Managed access key was not created");
ManagedCredentials.Key scoped = managed.list().getFirst();
status(409, action(client, base, "rename-bucket", cookie, base,
"csrf=" + adminCsrf + "&bucket=photos&newName=other-photos&confirm=photos"));
if (!names.bucket("photos").name().equals("photos"))
throw new AssertionError("Scoped-key rejection changed the bucket name");
if (!newKey.body().contains(scoped.secret()) ||
client.send(request(base, "/credentials").header("Cookie", cookie).GET().build(),
HttpResponse.BodyHandlers.ofString()).body().contains(scoped.secret()))
throw new AssertionError("Secret must be shown once");
if (Files.readString(root.resolve("data/managed-credentials.bin"), StandardCharsets.ISO_8859_1)
.contains(scoped.secret()))
throw new AssertionError("Managed secret was stored in cleartext");
var restored = ManagedCredentials.fromEnvironment(Map.of(
"S3_MANAGED_KEYS_MASTER_FILE", masterFile.toString(),
"DATA_DIR", root.resolve("data").toString()), store, java.util.Set.of("TESTACCESSKEY123"));
if (!restored.list().getFirst().secret().equals(scoped.secret()))
throw new AssertionError("Managed key was not persisted");
status(200, client.send(HttpTest.signedUriAs(URI.create(s3Base + "/photos/images/cat.txt"),
"GET", new byte[0], Map.of(), scoped.id(), scoped.secret()),
HttpResponse.BodyHandlers.ofString()));
status(403, client.send(HttpTest.signedUriAs(URI.create(s3Base + "/photos/outside.txt"),
"GET", new byte[0], Map.of(), scoped.id(), scoped.secret()),
HttpResponse.BodyHandlers.ofString()));
status(200, client.send(HttpTest.signedUriAs(URI.create(s3Base + "/photos?list-type=2&prefix=images%2F"),
"GET", new byte[0], Map.of(), scoped.id(), scoped.secret()),
HttpResponse.BodyHandlers.ofString()));
status(200, client.send(HttpTest.signedUriAs(URI.create(s3Base + "/photos"),
"HEAD", new byte[0], Map.of(), scoped.id(), scoped.secret()),
HttpResponse.BodyHandlers.discarding()));
status(403, client.send(HttpTest.signedUriAs(URI.create(s3Base + "/photos?list-type=2"),
"GET", new byte[0], Map.of(), scoped.id(), scoped.secret()),
HttpResponse.BodyHandlers.ofString()));
status(400, action(client, base, "disable-key", cookie, base,
"csrf=" + adminCsrf + "&id=" + scoped.id()));
status(303, action(client, base, "disable-key", cookie, base,
"csrf=" + adminCsrf + "&id=" + scoped.id() + "&confirm=" + scoped.id()));
status(403, client.send(HttpTest.signedUriAs(URI.create(s3Base + "/photos/images/cat.txt"),
"GET", new byte[0], Map.of(), scoped.id(), scoped.secret()),
HttpResponse.BodyHandlers.ofString()));
status(303, action(client, base, "enable-key", cookie, base,
"csrf=" + adminCsrf + "&id=" + scoped.id() + "&confirm=" + scoped.id()));
status(200, client.send(HttpTest.signedUriAs(URI.create(s3Base + "/photos/images/cat.txt"),
"GET", new byte[0], Map.of(), scoped.id(), scoped.secret()),
HttpResponse.BodyHandlers.ofString()));
status(403, client.send(HttpTest.signedUriAs(URI.create(s3Base + "/objects/images/cat.txt"),
"GET", new byte[0], Map.of(), scoped.id(), scoped.secret()),
HttpResponse.BodyHandlers.ofString()));
status(400, action(client, base, "update-key", cookie, base,
"csrf=" + adminCsrf + "&id=" + scoped.id() + "&bucket=photos&prefix=images%2F&read=on&list=on"));
status(303, action(client, base, "update-key", cookie, base,
"csrf=" + adminCsrf + "&id=" + scoped.id() + "&bucket=photos&prefix=images%2F&read=on&list=on" +
"&confirm=" + scoped.id()));
status(403, client.send(HttpTest.signedUriAs(URI.create(s3Base + "/photos/images/new.txt"),
"PUT", "new".getBytes(StandardCharsets.UTF_8), Map.of(), scoped.id(), scoped.secret()),
HttpResponse.BodyHandlers.ofString()));
status(303, action(client, base, "delete-key", cookie, base,
"csrf=" + adminCsrf + "&id=" + scoped.id() + "&confirm=" + scoped.id()));
status(403, client.send(HttpTest.signedUriAs(URI.create(s3Base + "/photos/images/cat.txt"),
"GET", new byte[0], Map.of(), scoped.id(), scoped.secret()),
HttpResponse.BodyHandlers.ofString()));
if (store.bucket("archive").ownership() != ObjectStorage.ObjectOwnership.BUCKET_OWNER_ENFORCED ||
!store.bucket("archive").publicAccessBlock().equals(ObjectStorage.PublicAccessBlock.secure()))
throw new AssertionError("Created bucket did not have private defaults");
status(400, action(client, base, "public-access", cookie, base,
"csrf=" + adminCsrf + "&bucket=archive"));
status(303, action(client, base, "public-access", cookie, base,
"csrf=" + adminCsrf + "&bucket=archive&confirm=archive"));
status(303, action(client, base, "ownership", cookie, base,
"csrf=" + adminCsrf + "&bucket=archive&ownership=BucketOwnerPreferred&confirm=archive"));
String publicPolicy = "{\"Version\":\"2012-10-17\",\"Statement\":{\"Effect\":\"Allow\",\"Principal\":\"*\"," +
"\"Action\":\"s3:GetObject\",\"Resource\":\"arn:aws:s3:::archive/*\"}}";
String policyForm = "csrf=" + adminCsrf + "&bucket=archive&policy=" +
java.net.URLEncoder.encode(publicPolicy, StandardCharsets.UTF_8);
status(400, action(client, base, "policy", cookie, base, policyForm));
String invalidPolicy = "{\"Version\": invalid}";
var policyError = action(client, base, "policy", cookie, base,
"csrf=" + adminCsrf + "&bucket=archive&policy=" +
java.net.URLEncoder.encode(invalidPolicy, StandardCharsets.UTF_8));
status(400, policyError);
if (!policyError.body().contains("biscuit-codeview") ||
!policyError.body().contains("Version&amp;quot;") &&
!policyError.body().contains("Version&quot;"))
throw new AssertionError("Invalid policy draft was not returned to the editor");
status(303, action(client, base, "policy", cookie, base, policyForm + "&confirm=archive"));
status(303, action(client, base, "policy", cookie, base,
"csrf=" + adminCsrf + "&bucket=archive&policy="));
status(400, action(client, base, "bucket-grant", cookie, base,
"csrf=" + adminCsrf + "&bucket=archive&principal=AllUsers&permission=READ&operation=add"));
status(303, action(client, base, "bucket-grant", cookie, base,
"csrf=" + adminCsrf + "&bucket=archive&principal=AllUsers&permission=READ&operation=add&confirm=archive"));
if (!store.bucket("archive").acl().containsKey(Acl.ALL_USERS))
throw new AssertionError("Admin ACL grant was not persisted");
status(303, action(client, base, "bucket-grant", cookie, base,
"csrf=" + adminCsrf + "&bucket=archive&principal=AllUsers&operation=remove"));
status(303, action(client, base, "versioning", cookie, base,
"csrf=" + adminCsrf + "&bucket=archive&state=ENABLED"));
store.createBucket("editor");
store.setVersioning("editor", ObjectStorage.VersioningState.ENABLED);
String versionedUpload = "bucket=editor&key=up.txt";
byte[] oldUpload = "first".getBytes(StandardCharsets.UTF_8);
byte[] newUpload = "second".getBytes(StandardCharsets.UTF_8);
status(201, upload(client, base, versionedUpload, cookie, base, adminCsrf, oldUpload));
ObjectStorage.Metadata oldUploadMeta;
try (ObjectStorage.OpenObject opened = store.open("editor", "up.txt")) {
oldUploadMeta = opened.metadata();
}
status(412, upload(client, base, versionedUpload, cookie, base, adminCsrf, newUpload));
status(201, upload(client, base, versionedUpload + "&overwrite=1", cookie, base,
adminCsrf, newUpload));
var oldDownload = client.send(request(base, "/download?" + versionedUpload +
"&version=" + java.net.URLEncoder.encode(oldUploadMeta.versionId(), StandardCharsets.UTF_8))
.header("Cookie", cookie).GET().build(), HttpResponse.BodyHandlers.ofByteArray());
status(200, oldDownload);
if (!java.util.Arrays.equals(oldUpload, oldDownload.body()))
throw new AssertionError("Replacing an object lost its prior version");
byte[] firstText = "{\"hello\":1}".getBytes(StandardCharsets.UTF_8);
ObjectStorage.Metadata firstVersion = store.put("editor", "note.json",
new ByteArrayInputStream(firstText), firstText.length,
SigV4.hex(SigV4.hash(firstText)), null, false, "application/json");
var editor = client.send(request(base, "/object?bucket=editor&key=note.json")
.header("Cookie", cookie).GET().build(), HttpResponse.BodyHandlers.ofString());
status(200, editor);
if (!editor.body().contains("class=text-editor language='json'") ||
!editor.body().contains("Save new version"))
throw new AssertionError("Editable text object CodeView is missing");
String editForm = "csrf=" + adminCsrf + "&bucket=editor&key=note.json&originalVersion=" +
java.net.URLEncoder.encode(firstVersion.versionId(), StandardCharsets.UTF_8) +
"&originalSha256=" + SigV4.hex(firstVersion.sha256()) + "&content=" +
java.net.URLEncoder.encode("{\"hello\":2}", StandardCharsets.UTF_8);
status(303, action(client, base, "edit-object", cookie, base, editForm));
try (ObjectStorage.OpenObject saved = store.open("editor", "note.json")) {
if (!new String(saved.stream().readAllBytes(), StandardCharsets.UTF_8)
.equals("{\"hello\":2}"))
throw new AssertionError("Edited object content was not saved");
}
try (ObjectStorage.OpenObject previous = store.open("editor", "note.json", firstVersion.versionId())) {
if (!new String(previous.stream().readAllBytes(), StandardCharsets.UTF_8)
.equals("{\"hello\":1}"))
throw new AssertionError("The prior object version was not retained");
}
var stale = action(client, base, "edit-object", cookie, base, editForm);
status(409, stale);
if (!stale.body().contains("The object changed") || !stale.body().contains("hello&quot;:2"))
throw new AssertionError("Stale edit diagnostic or draft is missing");
if (store.bucket("archive").versioning() != ObjectStorage.VersioningState.ENABLED)
throw new AssertionError("Admin versioning change was not persisted");
status(303, action(client, base, "object-tag", cookie, base,
"csrf=" + adminCsrf + "&bucket=photos&key=images%2Fcat.txt&tag=kind&value=cat&operation=add"));
if (!"cat".equals(store.tags("photos", "images/cat.txt").get("kind")))
throw new AssertionError("Admin tag change was not persisted");
status(400, action(client, base, "delete-object", cookie, base,
"csrf=" + adminCsrf + "&bucket=photos&key=images%2Fcat.txt"));
status(400, action(client, base, "delete-object", cookie, base,
"csrf=" + adminCsrf + "&bucket=photos&key=images%2Fcat.txt&version=null" +
"&confirm=images%2Fcat.txt"));
status(303, action(client, base, "delete-object", cookie, base,
"csrf=" + adminCsrf + "&bucket=photos&key=images%2Fcat.txt&confirm=images%2Fcat.txt"));
status(404, client.send(request(base, "/object?bucket=photos&key=images%2Fcat.txt")
.header("Cookie", cookie).GET().build(), HttpResponse.BodyHandlers.ofString()));
status(400, action(client, base, "delete-bucket", cookie, base,
"csrf=" + adminCsrf + "&bucket=archive"));
status(303, action(client, base, "delete-bucket", cookie, base,
"csrf=" + adminCsrf + "&bucket=archive&confirm=archive"));
status(303, action(client, base, "create-bucket", cookie, base,
"csrf=" + adminCsrf + "&bucket=rename-source"));
byte[] renamedBody = "renamed object".getBytes(StandardCharsets.UTF_8);
names.put("rename-source", "stored.txt", new ByteArrayInputStream(renamedBody),
renamedBody.length, null, null, false, "text/plain");
var sourcePage = client.send(request(base, "/bucket?name=rename-source")
.header("Cookie", cookie).GET().build(), HttpResponse.BodyHandlers.ofString());
status(200, sourcePage);
if (!sourcePage.body().contains("biscuit-accordionview") ||
!sourcePage.body().contains("Renaming changes the bucket URL"))
throw new AssertionError("Rename warning or controls missing");
status(400, action(client, base, "rename-bucket", cookie, base,
"csrf=" + adminCsrf + "&bucket=rename-source&newName=rename-target"));
status(303, action(client, base, "rename-bucket", cookie, base,
"csrf=" + adminCsrf + "&bucket=rename-source&newName=rename-target&confirm=rename-source"));
status(404, client.send(request(base, "/bucket?name=rename-source")
.header("Cookie", cookie).GET().build(), HttpResponse.BodyHandlers.ofString()));
status(200, client.send(request(base, "/object?bucket=rename-target&key=stored.txt")
.header("Cookie", cookie).GET().build(), HttpResponse.BodyHandlers.ofString()));
status(200, client.send(HttpTest.signedUriAs(URI.create(s3Base + "/rename-target/stored.txt"),
"GET", new byte[0], Map.of(), "TESTACCESSKEY123",
"test-secret-key-that-is-at-least-32-characters"), HttpResponse.BodyHandlers.ofString()));
status(404, client.send(HttpTest.signedUriAs(URI.create(s3Base + "/rename-source/stored.txt"),
"GET", new byte[0], Map.of(), "TESTACCESSKEY123",
"test-secret-key-that-is-at-least-32-characters"), HttpResponse.BodyHandlers.ofString()));
var settingsPage = client.send(request(base, "/settings").header("Cookie", cookie).GET().build(),
HttpResponse.BodyHandlers.ofString());
status(200, settingsPage);
if (!settingsPage.body().contains("Save global default") ||
!settingsPage.body().contains("Use server default") ||
!settingsPage.body().contains("Follow system") ||
!settingsPage.body().contains("admin-brand-icon"))
throw new AssertionError("Appearance settings missing");
var initialBrand = client.send(request(base, "/branding.json").GET().build(),
HttpResponse.BodyHandlers.ofString());
if (!initialBrand.body().contains("\"defaultTheme\":\"deep-dark\""))
throw new AssertionError("Deep dark is not the default for new browsers");
status(400, action(client, base, "default-theme", cookie, base,
"csrf=" + adminCsrf + "&defaultTheme=unknown"));
status(303, action(client, base, "default-theme", cookie, base,
"csrf=" + adminCsrf + "&defaultTheme=light"));
if (!new AdminBranding(root.resolve("data/admin-branding.txt")).state()
.defaultTheme().equals("light"))
throw new AssertionError("Global default theme was not saved");
status(303, action(client, base, "branding-name", cookie, "null",
"csrf=" + adminCsrf + "&displayName=LunarSky+Storage"));
var brand = client.send(request(base, "/branding.json").GET().build(),
HttpResponse.BodyHandlers.ofString());
status(200, brand);
if (!brand.body().contains("LunarSky Storage"))
throw new AssertionError("Server branding name was not saved");
byte[] tinyPng = java.util.Base64.getDecoder().decode(
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+X5ZcAAAAASUVORK5CYII=");
status(401, client.send(request(base, "/branding-icon/upload")
.header("Content-Type", "image/png")
.POST(HttpRequest.BodyPublishers.ofByteArray(tinyPng)).build(),
HttpResponse.BodyHandlers.ofString()));
status(403, client.send(request(base, "/branding-icon/upload")
.header("Cookie", cookie).header("Content-Type", "image/png")
.POST(HttpRequest.BodyPublishers.ofByteArray(tinyPng)).build(),
HttpResponse.BodyHandlers.ofString()));
var iconRequest = request(base, "/branding-icon/upload")
.header("Cookie", cookie).header("Origin", base).header("Content-Type", "image/png")
.header("X-CSRF-Token", adminCsrf);
status(415, client.send(iconRequest.POST(HttpRequest.BodyPublishers.ofString("not an image")).build(),
HttpResponse.BodyHandlers.ofString()));
status(200, client.send(iconRequest.POST(HttpRequest.BodyPublishers.ofByteArray(tinyPng)).build(),
HttpResponse.BodyHandlers.ofString()));
var storedIcon = client.send(request(base, "/branding-icon").GET().build(),
HttpResponse.BodyHandlers.ofByteArray());
status(200, storedIcon);
if (!java.util.Arrays.equals(tinyPng, storedIcon.body()) ||
!storedIcon.headers().firstValue("Content-Type").orElse("").equals("image/png"))
throw new AssertionError("Server branding icon was not saved");
var persistedBrand = new AdminBranding(root.resolve("data/admin-branding.txt")).state();
if (!persistedBrand.name().equals("LunarSky Storage") ||
!java.util.Arrays.equals(tinyPng, persistedBrand.icon()))
throw new AssertionError("Branding did not survive a reload");
status(303, action(client, base, "branding-reset", cookie, base, "csrf=" + adminCsrf));
var resetBrand = new AdminBranding(root.resolve("data/admin-branding.txt")).state();
if (!resetBrand.name().equals(AdminBranding.DEFAULT_NAME) ||
!resetBrand.defaultTheme().equals("light"))
throw new AssertionError("Branding reset changed the global theme");
status(400, client.send(request(base, "/bucket?name=photos&name=other")
.header("Cookie", cookie).GET().build(), HttpResponse.BodyHandlers.ofString()));
var reflected = client.send(request(base, "/buckets?filter=%3Cscript%3E")
@@ -239,7 +686,8 @@ public final class AdminConsoleTest {
status(429, post(client, base, "/login", PASSWORD, loginToken(client, base), null, null));
app.setAdminConsole(AdminConsole.fromEnvironment(Map.of(
"ADMIN_UI_ENABLED", "true", "ADMIN_UI_PASSWORD_FILE", passwordFile.toString(),
"ADMIN_UI_PRIVATE_ORIGIN", "http://10.30.0.120:9001"), store));
"ADMIN_UI_PRIVATE_ORIGIN", "http://10.30.0.120:9001",
"DATA_DIR", root.resolve("data").toString()), store));
int port = server.getAddress().getPort();
String privatePage = rawRequest(port, "10.30.0.120:9001", "GET", "/login", "");
if (!privatePage.startsWith("HTTP/1.1 200") || !privatePage.contains("Admin password"))
@@ -258,6 +706,7 @@ public final class AdminConsoleTest {
server.stop(0);
s3Server.stop(0);
executor.close();
activity.close();
store.close();
try (var paths = Files.walk(root)) {
for (Path path : paths.sorted(Comparator.reverseOrder()).toList()) Files.delete(path);
@@ -0,0 +1,179 @@
package cloud.lunarsky.store;
import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Proxy;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public final class AdminOperationsTest {
private static void check(boolean value, String message) {
if (!value) throw new AssertionError(message);
}
private static AdminBulkJobs.Snapshot await(AdminBulkJobs jobs, String id) throws Exception {
for (int retry = 0; retry < 200; retry++) {
AdminBulkJobs.Snapshot snapshot = jobs.get(id);
if (snapshot.finished() != 0) return snapshot;
Thread.sleep(25);
}
throw new AssertionError("Bulk job did not finish");
}
private static void copySafety(DiskStore store) throws Exception {
byte[] contents = "private destination".getBytes(StandardCharsets.UTF_8);
store.setBucketOwnership("source-bucket", ObjectStorage.ObjectOwnership.OBJECT_WRITER);
store.setPublicAccessBlock("source-bucket", ObjectStorage.PublicAccessBlock.open());
store.put("source-bucket", "shared.txt", new ByteArrayInputStream(contents), contents.length,
null, null, false, "text/plain", Map.of("purpose", "test"), Map.of("empty", ""),
Map::of, Map.of(Acl.ALL_USERS, Integer.toString(Acl.READ)));
AdminBulkJobs jobs = new AdminBulkJobs(store);
var copy = jobs.start(new AdminBulkJobs.Spec("copy", "source-bucket", "shared.txt",
"target-bucket", "private.txt", "", ""));
check(await(jobs, copy.id()).succeeded() == 1, "Private bulk copy failed");
try (var opened = store.open("target-bucket", "private.txt")) {
check(opened.metadata().acl().isEmpty(), "Bulk copy carried source ACL into destination");
check(opened.metadata().userMetadata().get("purpose").equals("test") &&
opened.metadata().tags().containsKey("empty"), "Bulk copy lost metadata or tags");
}
ObjectStorage corrupting = (ObjectStorage) Proxy.newProxyInstance(
ObjectStorage.class.getClassLoader(), new Class<?>[]{ObjectStorage.class},
(proxy, method, arguments) -> {
if (method.getName().equals("open")) {
try (var original = store.open((String) arguments[0], (String) arguments[1])) {
byte[] corrupted = original.stream().readAllBytes();
corrupted[0] ^= 1;
return new ObjectStorage.OpenObject(original.metadata(), new ByteArrayInputStream(corrupted));
}
}
try { return method.invoke(store, arguments); }
catch (InvocationTargetException error) { throw error.getCause(); }
});
AdminBulkJobs corruptJobs = new AdminBulkJobs(corrupting);
var corrupted = corruptJobs.start(new AdminBulkJobs.Spec("copy", "source-bucket", "shared.txt",
"target-bucket", "corrupt.txt", "", ""));
check(await(corruptJobs, corrupted.id()).failed() == 1, "Corrupted bulk copy was accepted");
check(store.list("target-bucket", "corrupt.txt", "", 1, null).objects().isEmpty(),
"Corrupted bulk copy installed an object");
}
private static void emptyTagValue(DiskStore store) throws Exception {
AdminActions.apply(store, "object-tag", Map.of("bucket", "target-bucket", "key", "copy-000",
"operation", "add", "tag", "empty", "value", ""), Set.of(), null);
check("".equals(store.tags("target-bucket", "copy-000").get("empty")),
"Admin tag editor rejected an empty tag value");
Map<String, String> tags = new HashMap<>();
for (int i = 0; i < 10; i++) tags.put("tag-" + i, "");
store.setTags("target-bucket", "copy-000", tags);
try {
AdminActions.apply(store, "object-tag", Map.of("bucket", "target-bucket", "key", "copy-000",
"operation", "add", "tag", "extra", "value", ""), Set.of(), null);
throw new AssertionError("Admin accepted more than ten tags");
} catch (StoreException expected) {
check(expected.status == 400 && expected.code.equals("InvalidTag"), "Unexpected tag failure");
}
AdminBulkJobs jobs = new AdminBulkJobs(store);
var tag = jobs.start(new AdminBulkJobs.Spec("tag", "target-bucket", "copy-000",
"", "", "extra", ""));
check(await(jobs, tag.id()).failed() == 1, "Bulk job accepted more than ten tags");
check(store.tags("target-bucket", "copy-000").equals(tags), "Rejected tagging changed the object");
}
private static void staleEditorSave(DiskStore store) throws Exception {
store.createBucket("editor-bucket");
store.setVersioning("editor-bucket", ObjectStorage.VersioningState.ENABLED);
byte[] original = "original".getBytes(StandardCharsets.UTF_8);
ObjectStorage.Metadata metadata = store.put("editor-bucket", "note.txt",
new ByteArrayInputStream(original), original.length, null, null, false, "text/plain");
byte[] concurrent = "concurrent update".getBytes(StandardCharsets.UTF_8);
ObjectStorage racing = (ObjectStorage) Proxy.newProxyInstance(
ObjectStorage.class.getClassLoader(), new Class<?>[]{ObjectStorage.class},
(proxy, method, arguments) -> {
if (method.getName().equals("replaceVersion"))
store.put("editor-bucket", "note.txt", new ByteArrayInputStream(concurrent),
concurrent.length, null, null, false, "text/plain");
try { return method.invoke(store, arguments); }
catch (InvocationTargetException error) { throw error.getCause(); }
});
try {
AdminTextEditor.save(racing, Map.of("bucket", "editor-bucket", "key", "note.txt",
"originalVersion", metadata.versionId(), "originalSha256", SigV4.hex(metadata.sha256()),
"content", "stale editor content"));
throw new AssertionError("Stale editor save overwrote a concurrent update");
} catch (StoreException expected) {
check(expected.status == 409 && expected.code.equals("Conflict"), "Unexpected editor conflict");
}
try (var opened = store.open("editor-bucket", "note.txt")) {
check(new String(opened.stream().readAllBytes(), StandardCharsets.UTF_8).equals("concurrent update"),
"Editor replaced the concurrent update");
}
check(store.listVersions("editor-bucket", "note.txt", null, null, 10).entries().size() == 2,
"Rejected editor save created a new version");
}
public static void main(String[] args) throws Exception {
Path root = Files.createTempDirectory("admin-operations-");
try {
AdminAuditTrail audit = new AdminAuditTrail(root);
audit.record("create-bucket", "source", "started", "127.0.0.1");
audit.record("create-bucket", "source", "succeeded", "127.0.0.1");
check(new AdminAuditTrail(root).recent(1).getFirst().result().equals("succeeded"),
"Audit event did not survive restart");
try (DiskStore store = new DiskStore(root.resolve("data"), 1024, 1024 * 1024)) {
store.createBucket("source-bucket");
store.createBucket("target-bucket");
byte[] value = "hello".getBytes(StandardCharsets.UTF_8);
for (int i = 0; i < 225; i++)
store.put("source-bucket", "item-" + String.format("%03d", i),
new ByteArrayInputStream(value), value.length, null, null, false,
"text/plain", Map.of(), Map.of());
S3Access access = new S3Access(store, "OWNERACCESSKEY123");
AdminAccessCheck checker = new AdminAccessCheck(store, access,
KeyScopes.unrestricted("OWNERACCESSKEY123"),
Set.of("OWNERACCESSKEY123", "OTHERACCESSKEY123"), null);
check(checker.check("OWNERACCESSKEY123", "read", "source-bucket", "item-000").allowed(),
"Owner should read a current object");
check(!checker.check("OTHERACCESSKEY123", "read", "source-bucket", "item-000").allowed(),
"Unrelated key should not read an object");
check(!checker.check("OWNERACCESSKEY123", "read", "source-bucket", "missing").allowed(),
"Missing object should not read as allowed");
AdminBulkJobs jobs = new AdminBulkJobs(store);
var copy = jobs.start(new AdminBulkJobs.Spec("copy", "source-bucket", "item-",
"target-bucket", "copy-", "", ""));
check(await(jobs, copy.id()).succeeded() == 225, "Paged copy missed objects");
try (var opened = store.open("target-bucket", "copy-224")) {
check(new String(opened.stream().readAllBytes(), StandardCharsets.UTF_8).equals("hello"),
"Copied data changed");
}
var tag = jobs.start(new AdminBulkJobs.Spec("tag", "target-bucket", "copy-",
"", "", "group", "example"));
check(await(jobs, tag.id()).succeeded() == 225, "Paged tag missed objects");
check(store.tags("target-bucket", "copy-224").get("group").equals("example"),
"Tag not persisted");
var inventory = jobs.start(new AdminBulkJobs.Spec("inventory", "target-bucket", "copy-",
"", "", "", ""));
check(await(jobs, inventory.id()).processed() == 225 &&
jobs.report(inventory.id()).contains("copy-224"), "Inventory report incomplete");
var deletion = jobs.start(new AdminBulkJobs.Spec("delete", "source-bucket", "item-",
"", "", "", ""));
check(await(jobs, deletion.id()).succeeded() == 225 &&
store.list("source-bucket", "", "", 10, null).objects().isEmpty(),
"Paged delete missed objects");
copySafety(store);
emptyTagValue(store);
staleEditorSave(store);
System.out.println("Admin operations tests passed: audit, access, paged jobs");
}
} finally {
try (var files = Files.walk(root)) {
for (Path path : files.sorted(Comparator.reverseOrder()).toList()) Files.deleteIfExists(path);
}
}
}
}
@@ -0,0 +1,43 @@
package cloud.lunarsky.store;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.LocalDate;
import java.time.ZoneOffset;
public final class BucketActivityTest {
public static void main(String[] args) throws Exception {
Path directory = Files.createTempDirectory("bucket-activity-test-");
Path file = directory.resolve("activity.tsv");
try {
try (BucketActivity activity = new BucketActivity(file)) {
activity.record("first-bucket", "GET");
activity.record("first-bucket", "HEAD");
activity.record("first-bucket", "PUT");
activity.record("first-bucket", "OPTIONS");
activity.record("invalid/bucket", "PUT");
var today = activity.days("first-bucket").getLast();
if (!today.date().equals(LocalDate.now(ZoneOffset.UTC)) ||
today.reads() != 2 || today.writes() != 1)
throw new AssertionError("Daily requests were counted incorrectly");
activity.rename("first-bucket", "second-bucket");
if (activity.days("first-bucket").getLast().total() != 0 ||
activity.days("second-bucket").getLast().total() != 3)
throw new AssertionError("Rename lost bucket activity");
}
try (BucketActivity reloaded = new BucketActivity(file)) {
if (reloaded.days("second-bucket").getLast().total() != 3)
throw new AssertionError("Bucket activity did not survive a restart");
reloaded.remove("second-bucket");
}
try (BucketActivity reloaded = new BucketActivity(file)) {
if (reloaded.days("second-bucket").getLast().total() != 0)
throw new AssertionError("Deleted bucket activity reappeared");
}
System.out.println("Bucket activity tests passed");
} finally {
Files.deleteIfExists(file);
Files.deleteIfExists(directory);
}
}
}
@@ -0,0 +1,116 @@
package cloud.lunarsky.store;
import java.net.URI;
import java.sql.DriverManager;
import java.util.List;
import java.util.UUID;
public final class ClusterBucketRenameTest {
private static void check(boolean condition, String message) {
if (!condition) throw new AssertionError(message);
}
private static long count(java.sql.Connection connection, String table, String bucket) throws Exception {
try (var query = connection.prepareStatement("SELECT count(*) FROM " + table + " WHERE bucket=?")) {
query.setString(1, bucket);
try (var rows = query.executeQuery()) {
rows.next();
return rows.getLong(1);
}
}
}
public static void main(String[] args) throws Exception {
if (args.length != 3) throw new IllegalArgumentException("Expected JDBC URL, user, password");
String url = args[0], user = args[1], password = args[2];
String configured = "rename-default", source = "rename-source", target = "rename-target";
List<URI> nodes = List.of(URI.create("http://127.0.0.1:19091"),
URI.create("http://127.0.0.1:19092"));
try (var connection = DriverManager.getConnection(url, user, password)) {
SchemaMigrator.prepare(connection, configured);
try (var insert = connection.prepareStatement(
"INSERT INTO cluster_nodes (node_id,host_id,endpoint,state) VALUES (?,?,?,'active')")) {
for (URI node : nodes) {
insert.setObject(1, UUID.randomUUID());
insert.setObject(2, UUID.randomUUID());
insert.setString(3, node.toString());
insert.executeUpdate();
}
}
}
try (ClusterStore store = new ClusterStore(url, user, password, configured, nodes,
"cluster-rename-test-token-1234567890123456", null, 1024, 8192, true)) {
store.createBucket(source);
store.createBucket("rename-taken");
store.setBucketPolicy(source, "{\"Resource\":\"arn:aws:s3:::rename-source/*\"}");
try (var connection = DriverManager.getConnection(url, user, password)) {
UUID generation = UUID.randomUUID();
try (var insert = connection.prepareStatement(
"INSERT INTO cluster_object_versions (bucket,object_key,version_id,delete_marker," +
"generation,length,modified,etag,sha256,content_type) VALUES (?,?,?,false,?,?,?,?,?,?)")) {
insert.setString(1, source);
insert.setString(2, "key.txt");
insert.setString(3, UUID.randomUUID().toString());
insert.setObject(4, generation);
insert.setLong(5, 4);
insert.setLong(6, System.currentTimeMillis());
insert.setString(7, "0".repeat(32));
insert.setBytes(8, new byte[32]);
insert.setString(9, "text/plain");
insert.executeUpdate();
}
try (var insert = connection.prepareStatement(
"INSERT INTO cluster_object_heads (bucket,object_key,version_id) " +
"SELECT bucket,object_key,version_id FROM cluster_object_versions WHERE bucket=?")) {
insert.setString(1, source);
insert.executeUpdate();
}
try (var insert = connection.prepareStatement(
"INSERT INTO cluster_uploads (upload_id,bucket,object_key,content_type,created_at) " +
"VALUES (?,?,?,?,?)")) {
insert.setObject(1, UUID.randomUUID());
insert.setString(2, source);
insert.setString(3, "pending.txt");
insert.setString(4, "text/plain");
insert.setLong(5, System.currentTimeMillis());
insert.executeUpdate();
}
}
try {
store.renameBucket(source, "rename-taken");
throw new AssertionError("Duplicate target was accepted");
} catch (StoreException expected) {
check(expected.status == 409, "Wrong duplicate-name status");
}
check(store.bucket(source).name().equals(source), "Rejected rename changed source");
store.renameBucket(source, target);
check(store.bucket(target).policy().contains("arn:aws:s3:::rename-target/*"),
"Policy did not follow the rename");
try {
store.bucket(source);
throw new AssertionError("Old name remained available");
} catch (StoreException expected) {
check(expected.status == 404, "Wrong old-name response");
}
try (var connection = DriverManager.getConnection(url, user, password)) {
for (String table : List.of("cluster_usage", "cluster_object_versions",
"cluster_object_heads", "cluster_uploads")) {
check(count(connection, table, target) == 1, table + " was not renamed");
check(count(connection, table, source) == 0, table + " retained the old name");
}
}
}
try (ClusterStore store = new ClusterStore(url, user, password, configured, nodes,
"cluster-rename-test-token-1234567890123456", null, 1024, 8192, true)) {
check(store.bucket(target).name().equals(target), "Rename did not survive restart");
}
try {
new ClusterStore(url, user, password, source, nodes,
"cluster-rename-test-token-1234567890123456", null, 1024, 8192, true).close();
throw new AssertionError("Old default bucket was recreated");
} catch (java.io.IOException expected) {
check(expected.getMessage().contains("S3_BUCKET"), "Wrong stale-config failure");
}
System.out.println("Cluster bucket rename tests passed");
}
}
@@ -25,6 +25,16 @@ public final class ClusterIntegrationTest {
String bucket = env.get("S3_BUCKET");
byte[] stable = "acknowledged object survives node loss".getBytes(StandardCharsets.UTF_8);
switch (args[0]) {
case "status" -> {
ClusterStore.ClusterStatus status = store.status();
require(status.metadataWritable(), "Cluster status lost writable metadata primary");
require(status.nodes().size() >= 3 &&
status.nodes().stream().allMatch(ClusterStore.NodeStatus::reachable),
"Cluster status missed reachable storage nodes");
require(status.repair() != null && status.repair().report().scanned() >= 0,
"Last repair report is missing");
System.out.println("Cluster status test passed");
}
case "basic" -> {
byte[] large = new byte[ClusterNode.MAX_SEGMENT + 37];
for (int i = 0; i < large.length; i++) {
@@ -0,0 +1,127 @@
package cloud.lunarsky.store;
import com.sun.net.httpserver.HttpServer;
import java.io.ByteArrayInputStream;
import java.net.InetSocketAddress;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.sql.DriverManager;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
public final class ClusterMaintenanceTest {
private static void check(boolean value, String message) {
if (!value) throw new AssertionError(message);
}
public static void main(String[] args) throws Exception {
if (args.length != 3) throw new IllegalArgumentException("Expected JDBC URL, user, password");
Path root = Files.createTempDirectory("objectstore-maintenance-");
List<ClusterNode> nodes = new ArrayList<>();
List<HttpServer> servers = new ArrayList<>();
List<URI> urls = new ArrayList<>();
String token = "maintenance-test-node-token-0123456789";
String repair = "maintenance-test-repair-token-0123456";
try {
for (int i = 0; i < 3; i++) {
ClusterNode node = new ClusterNode(root.resolve("node" + i), token, repair, UUID.randomUUID());
nodes.add(node);
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
servers.add(server);
server.createContext("/", node::handle);
server.start();
urls.add(URI.create("http://127.0.0.1:" + server.getAddress().getPort()));
}
try (ClusterStore store = new ClusterStore(args[0], args[1], args[2], "maintenance-default",
urls, token, repair, 1024, 8192, false)) {
store.createBucket("maintenance-source");
store.setVersioning("maintenance-source", ObjectStorage.VersioningState.ENABLED);
byte[] value = new byte[] { 1, 2, 3, 4 };
for (int i = 0; i < 2; i++)
store.put("maintenance-source", "file", new ByteArrayInputStream(value), value.length,
null, null, false, "application/octet-stream");
String upload = store.create("maintenance-source", "part", "application/octet-stream");
store.putPart(upload, "maintenance-source", "part", 1,
new ByteArrayInputStream(value), value.length, null, null);
check(store.activeUploads() == 1 && store.stagedBytes() == value.length,
"Global multipart statistics excluded a non-default bucket");
renameUnderContention(store, args);
check(store.listVersions("maintenance-target", "", null, null, 10).entries().size() == 2,
"Rename lost retained versions");
try (var files = Files.walk(root.resolve("node0/segments"))) {
for (Path path : files.filter(Files::isRegularFile).toList())
Files.write(path, new byte[] { 9 });
}
var repaired = store.repairOnce();
check(repaired.scanned() == 3 && repaired.restored() == 3 && repaired.unrecoverable() == 0,
"Repair did not restore committed and staged replicas");
var status = store.status();
check(status.metadataWritable() && status.repair().state().equals("completed"),
"Completed repair status unavailable");
check(status.verifiedReplicas().values().stream().mapToLong(Long::longValue).sum() == 9,
"Repair replica counts do not match committed and staged replicas");
try (var opened = store.open("maintenance-target", "file")) {
check(java.util.Arrays.equals(value, opened.stream().readAllBytes()), "Repaired data changed");
}
for (int i = 0; i < 3; i++) {
try (var files = Files.walk(root.resolve("node" + i + "/segments"))) {
for (Path path : files.filter(Files::isRegularFile).toList()) Files.delete(path);
}
}
var lost = store.repairOnce();
check(lost.scanned() == 3 && lost.unrecoverable() == 3,
"Unrecoverable segments were omitted from repair report");
check(store.status().verifiedReplicas().isEmpty(), "Old replica counts survived the next scan");
try (ClusterStore second = new ClusterStore(args[0], args[1], args[2], "maintenance-default",
urls, token, repair, 1024, 8192, false)) {
ConditionalEditTest.exercise(store, second, "conditional-cluster-edit");
}
}
System.out.println("Cluster maintenance tests passed: rename contention, multipart totals, repair status");
} finally {
for (HttpServer server : servers) server.stop(0);
for (ClusterNode node : nodes) node.close();
try (var files = Files.walk(root)) {
for (Path path : files.sorted(java.util.Comparator.reverseOrder()).toList()) Files.deleteIfExists(path);
}
}
}
private static void renameUnderContention(ClusterStore store, String[] args) throws Exception {
try (var executor = java.util.concurrent.Executors.newVirtualThreadPerTaskExecutor();
var blocker = DriverManager.getConnection(args[0], args[1], args[2])) {
blocker.setAutoCommit(false);
try (var query = blocker.createStatement()) {
query.execute("SELECT pg_advisory_xact_lock(6834071092784)");
}
var rename = executor.submit(() -> {
store.renameBucket("maintenance-source", "maintenance-target");
return null;
});
try {
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5);
boolean waiting = false;
try (var observer = DriverManager.getConnection(args[0], args[1], args[2]);
var query = observer.createStatement()) {
while (System.nanoTime() < deadline && !waiting) {
try (var rows = query.executeQuery("SELECT EXISTS (SELECT 1 FROM pg_locks " +
"WHERE locktype='advisory' AND NOT granted)")) {
rows.next();
waiting = rows.getBoolean(1);
}
if (!waiting) Thread.sleep(10);
}
check(waiting, "Rename did not wait for the existing mutation lock");
query.execute("SET statement_timeout='2s'");
query.executeQuery("SELECT count(*) FROM cluster_buckets").close();
}
} finally {
blocker.commit();
}
rename.get(5, TimeUnit.SECONDS);
}
}
}
@@ -0,0 +1,14 @@
package cloud.lunarsky.store;
public final class ClusterRepairCliTest {
public static void main(String[] args) throws Exception {
try {
ClusterRepair.main(new String[] { "--invalid" });
throw new AssertionError("Cluster repair accepted invalid arguments");
} catch (IllegalArgumentException expected) {
if (!expected.getMessage().equals("Usage: objectstore cluster-repair [--loop]"))
throw new AssertionError("Cluster repair CLI entrypoint changed", expected);
}
System.out.println("Cluster repair CLI entrypoint passed");
}
}
@@ -0,0 +1,101 @@
package cloud.lunarsky.store;
import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
public final class ConditionalEditTest {
private static void check(boolean value, String message) {
if (!value) throw new AssertionError(message);
}
private static ObjectStorage.Metadata put(ObjectStorage store, String bucket, String key, String text)
throws Exception {
byte[] bytes = text.getBytes(StandardCharsets.UTF_8);
return store.put(bucket, key, new ByteArrayInputStream(bytes), bytes.length, null, null, false,
"text/plain", Map.of("source", "editor-test"), Map.of("purpose", "test"));
}
private static ObjectStorage.Metadata head(ObjectStorage store, String bucket, String key) throws Exception {
try (var opened = store.open(bucket, key)) { return opened.metadata(); }
}
private static boolean replace(ObjectStorage store, String bucket, String key,
ObjectStorage.Metadata expected, String text) throws Exception {
try {
store.replaceVersion(bucket, key, text.getBytes(StandardCharsets.UTF_8), expected);
return true;
} catch (StoreException conflict) {
check(conflict.status == 412, "Wrong conditional-edit rejection");
return false;
}
}
static void exercise(ObjectStorage first, ObjectStorage second, String bucket) throws Exception {
first.createBucket(bucket);
put(first, bucket, "text", "original");
first.setVersioning(bucket, ObjectStorage.VersioningState.ENABLED);
check(replace(first, bucket, "text", head(first, bucket, "text"), "enabled"),
"Could not edit an object written before versioning was enabled");
var original = head(first, bucket, "text");
CountDownLatch ready = new CountDownLatch(2);
CountDownLatch start = new CountDownLatch(1);
try (var executor = java.util.concurrent.Executors.newVirtualThreadPerTaskExecutor()) {
var a = executor.submit(() -> {
ready.countDown();
start.await();
return replace(first, bucket, "text", original, "first");
});
var b = executor.submit(() -> {
ready.countDown();
start.await();
return replace(second, bucket, "text", original, "second");
});
check(ready.await(5, TimeUnit.SECONDS), "Editors did not start");
start.countDown();
check(a.get(10, TimeUnit.SECONDS) != b.get(10, TimeUnit.SECONDS),
"Both concurrent editors succeeded, or neither did");
}
var current = head(first, bucket, "text");
check(current.userMetadata().equals(original.userMetadata()) && current.tags().equals(original.tags()),
"Conditional edit lost object attributes");
check(!replace(second, bucket, "text", original, "stale"), "Stale edit overwrote newer data");
second.setTags(bucket, "text", Map.of("purpose", "changed"));
check(!replace(first, bucket, "text", current, "stale tags"), "Edit reverted a concurrent tag update");
current = head(first, bucket, "text");
second.setObjectAcl(bucket, "text", current.versionId(), Map.of("owner", "updated-owner"));
check(!replace(first, bucket, "text", current, "stale ACL"), "Edit reverted a concurrent ACL update");
current = head(first, bucket, "text");
first.setVersioning(bucket, ObjectStorage.VersioningState.SUSPENDED);
check(!replace(second, bucket, "text", current, "unsafe"), "Edit succeeded after versioning was suspended");
put(first, bucket, "other", "old null version");
var previousNull = head(first, bucket, "other");
put(second, bucket, "other", "new null version");
first.setVersioning(bucket, ObjectStorage.VersioningState.ENABLED);
check(!replace(first, bucket, "other", previousNull, "stale null version"),
"Reused null version ID bypassed the content check");
first.delete(bucket, "text");
check(!replace(second, bucket, "text", current, "resurrected"), "Edit replaced a delete marker");
}
public static void main(String[] args) throws Exception {
Path root = Files.createTempDirectory("objectstore-conditional-edit-");
try (DiskStore disk = new DiskStore(root, 1024, 8192)) {
DiskBucketNames names = new DiskBucketNames(disk, new MultipartStore(disk));
exercise(names, names, "conditional-edit");
names.renameBucket("conditional-edit", "edited-rename");
var expected = head(names, "edited-rename", "other");
check(replace(names, "edited-rename", "other", expected, "renamed"),
"Conditional edit did not resolve a renamed bucket");
} finally {
try (var files = Files.walk(root)) {
for (Path path : files.sorted(java.util.Comparator.reverseOrder()).toList()) Files.deleteIfExists(path);
}
}
System.out.println("Conditional edit tests passed: concurrent saves, versioning changes, renamed buckets");
}
}
@@ -0,0 +1,142 @@
package cloud.lunarsky.store;
import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
public final class DiskBucketNamesTest {
private static void check(boolean condition, String message) {
if (!condition) throw new AssertionError(message);
}
private static void missing(Runnable operation) {
try {
operation.run();
throw new AssertionError("Old bucket name was still available");
} catch (StoreException error) {
check(error.status == 404, "Wrong missing-bucket response");
}
}
private static ObjectStorage.Metadata put(DiskBucketNames names, String bucket, String key, String value)
throws Exception {
byte[] bytes = value.getBytes(StandardCharsets.UTF_8);
return names.put(bucket, key, new ByteArrayInputStream(bytes), bytes.length,
null, null, false, "text/plain", Map.of("source", "test"), Map.of());
}
private static void run(Path root) throws Exception {
String old = "renamed-source", next = "renamed-target";
String firstId;
String uploadId;
try (DiskStore disk = new DiskStore(root, 1024, 8192)) {
disk.createBucket(old);
DiskBucketNames names = new DiskBucketNames(disk, new MultipartStore(disk));
names.setVersioning(old, ObjectStorage.VersioningState.ENABLED);
firstId = put(names, old, "folder/item.txt", "one").versionId();
put(names, old, "folder/item.txt", "two");
names.setBucketPolicy(old, "{\"Resource\":\"arn:aws:s3:::renamed-source/*\"}");
uploadId = names.create(old, "pending.txt", "text/plain");
names.putPart(uploadId, old, "pending.txt", 1,
new ByteArrayInputStream("part".getBytes(StandardCharsets.UTF_8)), 4, null, null);
names.renameBucket(old, next);
check(names.bucket(next).name().equals(next), "Renamed bucket is not visible");
check(names.bucket(next).policy().contains("arn:aws:s3:::renamed-target/*"),
"Policy did not follow the public name");
check(names.listVersions(next, "", null, null, 100).entries().size() == 2,
"Retained versions were lost");
try (var opened = names.open(next, "folder/item.txt", firstId)) {
check(new String(opened.stream().readAllBytes(), StandardCharsets.UTF_8).equals("one"),
"Historical version changed");
check(opened.metadata().bucket().equals(next), "Metadata exposed the physical name");
}
check(names.listUploads(next, "").size() == 1, "Multipart upload did not follow rename");
missing(() -> { try { names.bucket(old); } catch (java.io.IOException error) {
throw new RuntimeException(error); } });
try {
names.createBucket(old);
throw new AssertionError("Hidden physical name was reused");
} catch (StoreException error) {
check(error.status == 409, "Wrong reused-name response");
}
}
try (DiskStore disk = new DiskStore(root, 1024, 8192)) {
DiskBucketNames names = new DiskBucketNames(disk, new MultipartStore(disk));
names.ensureBucket(old);
check(names.buckets().stream().map(ObjectStorage.Bucket::name).toList().equals(List.of(next)),
"Public bucket name did not survive restart");
check(names.listVersions(next, "", null, null, 100).entries().size() == 2,
"Versions did not survive restart");
var part = names.listParts(uploadId, next, "pending.txt", 0, 10).parts().getFirst();
names.complete(uploadId, next, "pending.txt", List.of(new MultipartStorage.Part(1, part.etag())));
try (var opened = names.open(next, "pending.txt")) {
check(new String(opened.stream().readAllBytes(), StandardCharsets.UTF_8).equals("part"),
"Multipart completion failed after restart");
}
names.renameBucket(next, "final-bucket");
check(names.bucket("final-bucket").policy().contains("arn:aws:s3:::final-bucket/*"),
"Repeated rename lost policy mapping");
}
try (DiskStore disk = new DiskStore(root, 1024, 8192)) {
DiskBucketNames names = new DiskBucketNames(disk, new MultipartStore(disk));
check(names.list("final-bucket", "", "", 100, null).objects().size() == 2,
"Repeated rename lost objects");
}
}
private static void deleteRecovery(Path root) throws Exception {
String source = "delete-source", target = "delete-target";
try (DiskStore disk = new DiskStore(root, 1024, 8192)) {
DiskBucketNames names = new DiskBucketNames(disk, new MultipartStore(disk));
names.createBucket(source);
names.renameBucket(source, target);
String upload = names.create(target, "unfinished.txt", "text/plain");
try {
names.deleteBucket(target);
throw new AssertionError("Bucket with multipart upload was deleted");
} catch (StoreException expected) {
check(expected.status == 409, "Wrong active-upload rejection");
}
names.abort(upload, target, "unfinished.txt");
new BucketNameCatalog(disk).beginDelete(target, source);
}
try (DiskStore disk = new DiskStore(root, 1024, 8192)) {
DiskBucketNames names = new DiskBucketNames(disk, new MultipartStore(disk));
check(names.bucket(target).name().equals(target), "Interrupted deletion lost the bucket");
new BucketNameCatalog(disk).beginDelete(target, source);
disk.deleteBucket(source);
}
try (DiskStore disk = new DiskStore(root, 1024, 8192)) {
DiskBucketNames names = new DiskBucketNames(disk, new MultipartStore(disk));
check(names.buckets().stream().noneMatch(bucket -> bucket.name().equals(target)),
"Interrupted deletion left a stale alias");
check(!Files.exists(root.resolve("bucket-name-deletion.txt")), "Deletion journal was retained");
names.createBucket(source);
names.renameBucket(source, target);
names.deleteBucket(target);
names.createBucket(source);
}
try (DiskStore disk = new DiskStore(root, 1024, 8192)) {
DiskBucketNames names = new DiskBucketNames(disk, new MultipartStore(disk));
check(names.bucket(source).name().equals(source), "Deleted physical name could not be reused");
}
}
public static void main(String[] args) throws Exception {
Path root = Files.createTempDirectory("objectstore-bucket-rename-");
try {
run(root);
deleteRecovery(root);
}
finally {
try (var files = Files.walk(root)) {
for (Path path : files.sorted(java.util.Comparator.reverseOrder()).toList())
Files.deleteIfExists(path);
}
}
System.out.println("Bucket rename tests passed: versions, multipart, policy, restart");
}
}
@@ -121,6 +121,15 @@ public final class FeatureTest {
status(200, client.send(HttpTest.signedUriAs(ownReadable,
"GET", new byte[0], Map.of(), LIMITED, LIMITED_SECRET), HttpResponse.BodyHandlers.ofString()));
var trafficAfter = metrics.dataSnapshot();
long metricsDeadline = System.nanoTime() + 2_000_000_000L;
while (System.nanoTime() < metricsDeadline &&
(trafficAfter.requests() - trafficBefore.requests() < 2 ||
trafficAfter.inboundBytes() - trafficBefore.inboundBytes() < content.length ||
trafficAfter.outboundBytes() - trafficBefore.outboundBytes() < content.length ||
trafficAfter.inFlight() != 0)) {
Thread.sleep(10);
trafficAfter = metrics.dataSnapshot();
}
if (trafficAfter.requests() - trafficBefore.requests() != 2 ||
trafficAfter.inboundBytes() - trafficBefore.inboundBytes() < content.length ||
trafficAfter.outboundBytes() - trafficBefore.outboundBytes() < content.length ||
+8
View File
@@ -318,6 +318,14 @@ public final class HttpTest {
if (!java.util.Arrays.equals(body, read.body())) throw new AssertionError("Streaming upload mismatch");
status(204, client.send(signedUri(object, "DELETE", new byte[0], Map.of()),
HttpResponse.BodyHandlers.ofByteArray()));
for (String size : new String[] {"8000000000000000", "ffffffffffffffff"}) {
byte[] oversized = (size + ";chunk-signature=" + "0".repeat(64) + "\r\n")
.getBytes(StandardCharsets.US_ASCII);
status(400, client.send(request.PUT(HttpRequest.BodyPublishers.ofByteArray(oversized))
.build(), HttpResponse.BodyHandlers.ofByteArray()));
}
status(404, client.send(signedUri(object, "GET", new byte[0], Map.of()),
HttpResponse.BodyHandlers.ofByteArray()));
}
private static void testStreamingTrailer(HttpClient client, String base) throws Exception {
+183
View File
@@ -0,0 +1,183 @@
package cloud.lunarsky.store;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
public final class NodeHttpTest {
private static final String TOKEN = "local-node-http-test-token-0123456789";
public static void main(String[] args) throws Exception {
try (HttpClient client = HttpClient.newBuilder().version(HttpClient.Version.HTTP_1_1).build()) {
stalledBody(client, false);
stalledBody(client, true);
oversizedBody(client);
interruptedBody(client);
stalledProbe(client);
nodeResponseLimits(client);
}
System.out.println("Node HTTP tests passed: total deadlines, cancellation, bounded responses, interruption");
}
private static void stalledBody(HttpClient client, boolean discard) throws Exception {
try (StalledResponse server = new StalledResponse(1)) {
HttpRequest request = HttpRequest.newBuilder(server.uri()).timeout(Duration.ofMillis(500)).GET().build();
long started = System.nanoTime();
expectFailure(() -> {
if (discard) NodeHttp.discard(client, request);
else NodeHttp.bytes(client, request, 32);
}, "timed out");
require(server.sent.await(1, TimeUnit.SECONDS), "Request did not reach the stalled response body");
require(System.nanoTime() - started < TimeUnit.SECONDS.toNanos(3), "Body timeout exceeded its deadline");
server.requireCancelled();
}
}
private static void oversizedBody(HttpClient client) throws Exception {
try (StalledResponse server = new StalledResponse(33)) {
HttpRequest request = HttpRequest.newBuilder(server.uri()).timeout(Duration.ofSeconds(5)).GET().build();
long started = System.nanoTime();
expectFailure(() -> NodeHttp.bytes(client, request, 32), "too large");
require(System.nanoTime() - started < TimeUnit.SECONDS.toNanos(3), "Oversized body waited for EOF");
server.requireCancelled();
}
}
private static void interruptedBody(HttpClient client) throws Exception {
try (StalledResponse server = new StalledResponse(1)) {
HttpRequest request = HttpRequest.newBuilder(server.uri()).timeout(Duration.ofSeconds(5)).GET().build();
CompletableFuture<Boolean> interrupted = new CompletableFuture<>();
Thread worker = Thread.ofVirtual().start(() -> {
try {
NodeHttp.bytes(client, request, 32);
interrupted.complete(false);
} catch (IOException expected) {
interrupted.complete(Thread.currentThread().isInterrupted());
}
});
try {
require(server.sent.await(2, TimeUnit.SECONDS), "Interrupted request never received headers");
worker.interrupt();
require(interrupted.get(2, TimeUnit.SECONDS), "Node request did not preserve interruption");
server.requireCancelled();
} finally {
worker.interrupt();
worker.join(2000);
}
}
}
private static void stalledProbe(HttpClient client) throws Exception {
try (StalledResponse server = new StalledResponse(1)) {
long started = System.nanoTime();
expectFailure(() -> NodeClient.probe(server.uri(), TOKEN, client), "timed out");
require(System.nanoTime() - started < TimeUnit.SECONDS.toNanos(4), "Identity body ignored probe timeout");
server.requireCancelled();
}
}
private static void nodeResponseLimits(HttpClient http) throws Exception {
UUID nodeId = UUID.randomUUID();
UUID hostId = UUID.randomUUID();
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
server.createContext("/identity", exchange -> {
byte[] identity = (nodeId + " " + hostId).getBytes(StandardCharsets.US_ASCII);
exchange.sendResponseHeaders(200, identity.length);
exchange.getResponseBody().write(identity);
exchange.close();
});
server.createContext("/segments", exchange -> {
byte[] body = new byte[exchange.getRequestURI().getRawQuery() == null ? 6 : 70001];
exchange.sendResponseHeaders(200, 0);
try (var output = exchange.getResponseBody()) { output.write(body); }
});
server.start();
try {
URI uri = URI.create("http://127.0.0.1:" + server.getAddress().getPort());
NodeClient client = new NodeClient(List.of(new NodeClient.Node(nodeId, hostId, uri)), TOKEN, TOKEN, http);
expectFailure(() -> client.get(0, UUID.randomUUID(), 4, SigV4.hash(new byte[4])), "too large");
expectFailure(() -> client.inventory(0, "00", null), "too large");
} finally {
server.stop(0);
}
}
@FunctionalInterface
private interface Request { void run() throws IOException; }
private static void expectFailure(Request request, String message) throws IOException {
try {
request.run();
throw new AssertionError("Invalid node response was accepted");
} catch (IOException expected) {
require(expected.getMessage().contains(message), "Unexpected failure: " + expected);
}
}
private static void require(boolean condition, String message) {
if (!condition) throw new AssertionError(message);
}
private static final class StalledResponse implements AutoCloseable {
private final ServerSocket server = new ServerSocket();
private final CountDownLatch sent = new CountDownLatch(1);
private final CompletableFuture<Boolean> cancelled = new CompletableFuture<>();
private final Thread worker;
private volatile Socket peer;
StalledResponse(int bodyBytes) throws IOException {
server.bind(new InetSocketAddress("127.0.0.1", 0));
worker = Thread.ofVirtual().start(() -> serve(bodyBytes));
}
URI uri() { return URI.create("http://127.0.0.1:" + server.getLocalPort()); }
private void serve(int bodyBytes) {
try (Socket socket = server.accept()) {
peer = socket;
socket.setSoTimeout(6000);
var input = socket.getInputStream();
int tail = 0;
int count = 0;
while (tail != 0x0d0a0d0a && count++ < 16384) {
int next = input.read();
if (next < 0) throw new IOException("Request ended before headers");
tail = (tail << 8) | next;
}
var output = socket.getOutputStream();
output.write("HTTP/1.1 200 OK\r\nContent-Length: 100000\r\n\r\n".getBytes(StandardCharsets.US_ASCII));
output.write(new byte[bodyBytes]);
output.flush();
sent.countDown();
try { cancelled.complete(input.read() == -1); }
catch (SocketException closed) { cancelled.complete(true); }
} catch (Exception error) {
cancelled.completeExceptionally(error);
}
}
void requireCancelled() throws Exception {
require(cancelled.get(2, TimeUnit.SECONDS), "Cancelled body left its connection open");
}
@Override
public void close() throws Exception {
server.close();
if (peer != null) peer.close();
worker.join(2000);
}
}
}
@@ -0,0 +1,199 @@
package cloud.lunarsky.store;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Proxy;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Clock;
import java.time.Duration;
import java.util.Comparator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.regex.Pattern;
public final class RequestCoordinationTest {
private static final String PASSWORD = "a-long-admin-password-for-tests";
public static void main(String[] args) throws Exception {
Path root = Files.createTempDirectory("request-coordination-");
CountDownLatch readStarted = new CountDownLatch(1);
CountDownLatch releaseRead = new CountDownLatch(1);
AtomicBoolean blockReady = new AtomicBoolean();
AtomicReference<StoreOperations.Action> bucketAction = new AtomicReference<>();
var executor = Executors.newVirtualThreadPerTaskExecutor();
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 16);
HttpServer admin = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 16);
try (DiskStore disk = new DiskStore(root.resolve("data"), 1024, 4096)) {
DiskBucketNames names = new DiskBucketNames(disk, new MultipartStore(disk));
ObjectStorage store = (ObjectStorage) Proxy.newProxyInstance(
ObjectStorage.class.getClassLoader(), new Class<?>[] {ObjectStorage.class},
(proxy, method, arguments) -> {
if (method.getName().equals("bucket")) {
StoreOperations.Action action = bucketAction.getAndSet(null);
if (action != null) action.run();
}
if (method.getName().equals("ready") && blockReady.get()) {
readStarted.countDown();
if (!releaseRead.await(5, TimeUnit.SECONDS))
throw new IOException("Read was not released");
}
try {
return method.invoke(names, arguments);
} catch (InvocationTargetException error) {
throw error.getCause();
}
});
Path password = root.resolve("password");
Files.writeString(password, PASSWORD);
AdminConsole console = AdminConsole.fromEnvironment(Map.of(
"ADMIN_UI_ENABLED", "true", "ADMIN_UI_PASSWORD_FILE", password.toString(),
"DATA_DIR", root.resolve("data").toString()), store);
Main app = new Main(store, names, new SigV4("TESTACCESSKEY123",
"test-secret-key-that-is-at-least-32-characters", "us-east-1", Clock.systemUTC()),
"objects");
app.setAdminConsole(console);
server.setExecutor(executor);
server.createContext("/", app::handle);
admin.setExecutor(executor);
admin.createContext("/", app::handleAdmin);
server.start();
admin.start();
try (HttpClient client = HttpClient.newHttpClient()) {
String base = "http://127.0.0.1:" + server.getAddress().getPort();
String adminBase = "http://127.0.0.1:" + admin.getAddress().getPort();
String loginPage = send(client, request(adminBase + AdminConsole.PATH + "/login").GET()).body();
HttpResponse<String> login = send(client,
form(adminBase + AdminConsole.PATH + "/login", "password=" + PASSWORD +
"&csrf=" + csrf(loginPage)));
status(login, 303);
String cookie = login.headers().firstValue("Set-Cookie").orElseThrow().split(";", 2)[0];
String overview = send(client, request(adminBase + AdminConsole.PATH + "/overview")
.header("Cookie", cookie).GET()).body();
String token = csrf(overview);
verifyRenameIsolation(client, base, adminBase, cookie, token,
blockReady, readStarted, releaseRead);
verifyDiagnostics(client, base, adminBase, cookie);
verifyRevocation(client, base, app, names, disk, root, bucketAction);
}
} finally {
releaseRead.countDown();
server.stop(0);
admin.stop(0);
executor.close();
try (var files = Files.walk(root)) {
for (Path file : files.sorted(Comparator.reverseOrder()).toList()) Files.delete(file);
}
}
System.out.println("Request coordination tests passed");
}
private static void verifyRenameIsolation(HttpClient client, String base, String adminBase,
String cookie, String token, AtomicBoolean blockReady,
CountDownLatch readStarted, CountDownLatch releaseRead)
throws Exception {
blockReady.set(true);
var heldRead = client.sendAsync(request(base + "/ready").GET().build(),
HttpResponse.BodyHandlers.ofString());
if (!readStarted.await(2, TimeUnit.SECONDS)) throw new AssertionError("Read did not start");
String url = adminBase + AdminConsole.PATH + "/action/rename-bucket";
status(send(client, form(url, "bucket=objects&newName=renamed&confirm=objects")), 303);
status(send(client, form(url, "bucket=objects&newName=renamed&confirm=objects&csrf=invalid")
.header("Cookie", cookie)), 403);
status(send(client, form(url, "bucket=objects&newName=renamed&confirm=objects&csrf=" + token)
.header("Cookie", cookie)), 409);
status(send(client, request(base + "/health").GET()), 200);
var rename = client.sendAsync(form(url, "bucket=objects&newName=renamed&confirm=objects&csrf=" + token)
.header("Cookie", cookie).build(), HttpResponse.BodyHandlers.ofString());
Thread.sleep(100);
if (rename.isDone()) throw new AssertionError("Rename did not wait for the active storage request");
blockReady.set(false);
releaseRead.countDown();
status(heldRead.get(2, TimeUnit.SECONDS), 200);
status(rename.get(2, TimeUnit.SECONDS), 303);
}
private static void verifyDiagnostics(HttpClient client, String base, String adminBase,
String cookie) throws Exception {
HttpResponse<String> signed = client.send(HttpTest.signedUri(
URI.create(base + "/renamed/missing"), "GET", new byte[0], Map.of()),
HttpResponse.BodyHandlers.ofString());
status(signed, 404);
HttpResponse<String> failed = send(client, request(base + "/other/missing")
.header("Authorization", "invalid").GET());
status(failed, 403);
String requestId = failed.headers().firstValue("x-amz-request-id").orElseThrow();
String page = "";
for (int attempt = 0; attempt < 20; attempt++) {
page = send(client, request(adminBase + AdminConsole.PATH + "/diagnostics")
.header("Cookie", cookie).GET()).body();
if (page.contains(requestId)) break;
Thread.sleep(10);
}
var row = Pattern.compile("<tr>(?:(?!</tr>).)*" + Pattern.quote(requestId) +
"(?:(?!</tr>).)*</tr>", Pattern.DOTALL).matcher(page);
if (!row.find() || !row.group().contains("Service") || row.group().contains("renamed"))
throw new AssertionError("Failed authentication inherited another request's bucket or operation");
}
private static void verifyRevocation(HttpClient client, String base, Main app, DiskBucketNames store,
DiskStore disk, Path root,
AtomicReference<StoreOperations.Action> bucketAction) throws Exception {
Path master = root.resolve("master-key");
Files.writeString(master, "0123456789abcdef".repeat(4));
ManagedCredentials managed = ManagedCredentials.fromEnvironment(Map.of(
"S3_MANAGED_KEYS_MASTER_FILE", master.toString(), "DATA_DIR", root.resolve("data").toString()),
disk, Set.of("TESTACCESSKEY123"));
ManagedCredentials.Key key = managed.create("renamed", "private/", Set.of("read"));
app.setManagedCredentials(managed);
byte[] value = {1};
store.put("renamed", "outside.txt", new java.io.ByteArrayInputStream(value), value.length,
SigV4.hex(SigV4.hash(value)), null, true, "text/plain");
store.setBucketPolicy("renamed", "{\"Version\":\"2012-10-17\",\"Statement\":[{" +
"\"Effect\":\"Allow\",\"Principal\":\"" + key.id() + "\",\"Action\":\"s3:GetObject\"," +
"\"Resource\":\"arn:aws:s3:::renamed/*\"}]}");
URI object = URI.create(base + "/renamed/outside.txt");
status(client.send(HttpTest.signedUriAs(object, "GET", new byte[0], Map.of(), key.id(), key.secret()),
HttpResponse.BodyHandlers.ofString()), 403);
bucketAction.set(() -> managed.remove(key.id()));
status(client.send(HttpTest.signedUriAs(object, "GET", new byte[0], Map.of(), key.id(), key.secret()),
HttpResponse.BodyHandlers.ofString()), 403);
if (managed.contains(key.id())) throw new AssertionError("Key revocation did not happen during request");
}
private static HttpRequest.Builder request(String url) {
return HttpRequest.newBuilder(URI.create(url)).timeout(Duration.ofSeconds(2));
}
private static HttpRequest.Builder form(String url, String body) {
return request(url).header("Content-Type", "application/x-www-form-urlencoded")
.POST(HttpRequest.BodyPublishers.ofString(body));
}
private static HttpResponse<String> send(HttpClient client, HttpRequest.Builder request)
throws Exception {
return client.send(request.build(), HttpResponse.BodyHandlers.ofString());
}
private static String csrf(String page) {
var token = Pattern.compile("name=csrf value='([A-Za-z0-9_-]{43})'").matcher(page);
if (!token.find()) throw new AssertionError("Missing CSRF token");
return token.group(1);
}
private static void status(HttpResponse<?> response, int expected) {
if (response.statusCode() != expected)
throw new AssertionError("Expected " + expected + ", got " + response.statusCode());
}
}
@@ -0,0 +1,26 @@
package cloud.lunarsky.store;
public final class RequestDiagnosticsTest {
public static void main(String[] args) {
RequestDiagnostics diagnostics = new RequestDiagnostics();
diagnostics.record("request-1", "Object GET", "photos", 200, 4_000_000);
diagnostics.record("request-2", "Object PUT", "photos", 403, 16_000_000);
diagnostics.record("request-3", "Object GET", "a".repeat(200), 503, 700_000_000);
RequestDiagnostics.Snapshot result = diagnostics.snapshot();
if (result.requests() != 3 || result.clientErrors() != 1 || result.serverErrors() != 1 ||
result.p50Millis() != 25 || result.p95Millis() != 1000 || result.p99Millis() != 1000 ||
result.recentFailures().size() != 2 ||
!result.recentFailures().get(0).requestId().equals("request-3") ||
!result.recentFailures().get(0).bucket().equals("—") ||
!result.recentFailures().get(1).bucket().equals("photos"))
throw new AssertionError("Rolling request diagnostics changed");
for (int index = 0; index < 70; index++)
diagnostics.record("bounded-" + index, "Object GET", "photos", 404, 1_000_000);
RequestDiagnostics.Snapshot bounded = diagnostics.snapshot();
if (bounded.recentFailures().size() != 64 ||
!bounded.recentFailures().get(0).requestId().equals("bounded-69") ||
!bounded.recentFailures().get(63).requestId().equals("bounded-6"))
throw new AssertionError("Recent failure history is not bounded");
System.out.println("Request diagnostics tests passed");
}
}