Add shared cluster credentials and readiness CI
ObjectStore CI / build (push) Successful in 10m22s

This commit is contained in:
admin committed 2026-11-16 03:41:32 +01:00
1 parent b724a21a0d
commit d73fa2c435
45 files changed
+2733 -226

No files matched your search

+18 -5
View File
@@ -353,9 +353,9 @@ final class AdminConsole {
private void auditPage(HttpExchange exchange, String origin) throws IOException {
Session session = requireSession(exchange, "GET");
if (session == null) return;
operations.read(() -> {
operations.read(() -> withCredentials(() -> {
send(exchange, 200, AdminOperationsPages.auditPage(identities, diagnostics, audit, session.csrf(), null, Map.of()), "text/html; charset=utf-8");
});
}));
}
private void jobsPage(HttpExchange exchange, String origin) throws IOException {
@@ -401,9 +401,9 @@ final class AdminConsole {
private void credentialsPage(HttpExchange exchange, String origin) throws IOException {
Session session = requireSession(exchange, "GET");
if (session == null) return;
operations.read(() -> {
operations.read(() -> withCredentials(() -> {
send(exchange, 200, AdminSettingsPages.credentialsPage(managedCredentials, store, session.csrf(), null), "text/html; charset=utf-8");
});
}));
}
private void download(HttpExchange exchange, String origin) throws IOException {
@@ -481,7 +481,11 @@ final class AdminConsole {
return;
}
String action = path.substring((PATH + "/action/").length());
StoreOperations.Action apply = () -> applyAction(exchange, session, action, form);
StoreOperations.Action apply = () -> {
if (Set.of("branding-name", "branding-reset", "default-theme").contains(action))
applyAction(exchange, session, action, form);
else withCredentials(() -> applyAction(exchange, session, action, form));
};
try {
if (action.equals("rename-bucket") || action.equals("delete-bucket")) {
operations.write(apply);
@@ -494,6 +498,15 @@ final class AdminConsole {
}
}
private void withCredentials(StoreOperations.Action action) throws IOException {
ManagedCredentials managed = managedCredentials;
if (managed == null) action.run();
else managed.withSnapshot(() -> {
refreshCredentials.run();
action.run();
});
}
private void applyAction(HttpExchange exchange, Session session, String action,
Map<String, String> form) throws IOException {
String peer = exchange.getRemoteAddress().getAddress().getHostAddress();
@@ -0,0 +1,108 @@
package cloud.lunarsky.store;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
final class ClusterCredentialStore implements ManagedCredentialStore {
private final ClusterMonitor.Connections connections;
ClusterCredentialStore(ClusterMonitor.Connections connections) {
this.connections = connections;
}
@Override public boolean shared() { return true; }
@Override public State read(long knownRevision) throws IOException {
try (Connection connection = connections.open();
PreparedStatement query = connection.prepareStatement(
"SELECT revision, CASE WHEN revision <> ? THEN encrypted END, " +
"NOT pg_is_in_recovery() AND current_setting('transaction_read_only') = 'off' " +
"FROM cluster_managed_credentials WHERE singleton=1")) {
query.setQueryTimeout(5);
query.setLong(1, knownRevision);
try (ResultSet rows = query.executeQuery()) {
if (!rows.next()) {
if (knownRevision >= 0) throw new IOException("Managed credential state is missing");
return new State(0, null);
}
if (!rows.getBoolean(3)) throw new IOException("Managed credentials require writable primary metadata");
return new State(rows.getLong(1), rows.getBytes(2));
}
} catch (SQLException error) {
throw unavailable(error);
}
}
@Override public State update(Change change) throws IOException {
try (Connection connection = connections.open()) {
connection.setAutoCommit(false);
try {
State current = lock(connection);
Mutation changed = change.apply(current);
replaceBuckets(connection, changed.buckets());
byte[] encrypted = changed.encrypted();
long revision = Math.addExact(current.revision(), 1);
try (PreparedStatement update = connection.prepareStatement(
"INSERT INTO cluster_managed_credentials (singleton, revision, encrypted) " +
"VALUES (1, ?, ?) ON CONFLICT (singleton) DO UPDATE " +
"SET revision=EXCLUDED.revision, encrypted=EXCLUDED.encrypted")) {
update.setLong(1, revision);
update.setBytes(2, encrypted);
update.executeUpdate();
}
connection.commit();
return new State(revision, encrypted);
} catch (SQLException | IOException | RuntimeException error) {
try { connection.rollback(); }
catch (SQLException rollback) { error.addSuppressed(rollback); }
throw error;
}
} catch (SQLException error) {
throw unavailable(error);
}
}
private static State lock(Connection connection) throws SQLException {
try (var statement = connection.createStatement()) {
statement.execute("SET LOCAL lock_timeout = '5s'");
statement.execute("SELECT pg_advisory_xact_lock(6834071092784)");
statement.execute("SELECT pg_advisory_xact_lock(6834071092785)");
try (ResultSet rows = statement.executeQuery(
"SELECT revision, encrypted FROM cluster_managed_credentials WHERE singleton=1 FOR UPDATE")) {
return rows.next() ? new State(rows.getLong(1), rows.getBytes(2)) : new State(0, null);
}
}
}
private static void replaceBuckets(Connection connection, java.util.Set<String> buckets) throws SQLException {
try (var statement = connection.createStatement()) {
statement.executeUpdate("DELETE FROM cluster_managed_credential_buckets");
}
try (PreparedStatement insert = connection.prepareStatement(
"INSERT INTO cluster_managed_credential_buckets SELECT name FROM cluster_buckets WHERE name=?")) {
for (String bucket : buckets) {
insert.setString(1, bucket);
if (insert.executeUpdate() != 1)
throw new StoreException(404, "NoSuchBucket", "Scoped credential bucket does not exist");
}
}
}
static void requireUnscopedBucket(Connection connection, String bucket) throws SQLException {
try (PreparedStatement query = connection.prepareStatement(
"SELECT 1 FROM cluster_managed_credential_buckets WHERE bucket=?")) {
query.setString(1, bucket);
try (ResultSet rows = query.executeQuery()) {
if (rows.next()) throw new StoreException(409, "BucketHasScopedKeys",
"Move or remove scoped access keys before renaming or deleting this bucket");
}
}
}
private static IOException unavailable(SQLException error) {
return new IOException("Managed credential metadata unavailable", error);
}
}
@@ -68,6 +68,8 @@ final class ClusterStore implements ObjectStorage, MultipartStorage {
private Connection connect() throws SQLException { return DriverManager.getConnection(jdbcUrl, user, password); }
ManagedCredentialStore managedCredentialStore() { return new ClusterCredentialStore(this::connect); }
@Override public Limits limits() { return new Limits(maxObject, maxTotal); }
@Override public void ensureBucket(String bucket) throws IOException {
@@ -244,6 +246,7 @@ final class ClusterStore implements ObjectStorage, MultipartStorage {
connection.setAutoCommit(false);
try {
lockUsage(connection, name);
ClusterCredentialStore.requireUnscopedBucket(connection, name);
try (PreparedStatement check = connection.prepareStatement(
"SELECT EXISTS (SELECT 1 FROM cluster_object_versions WHERE bucket=?) OR EXISTS " +
"(SELECT 1 FROM cluster_uploads WHERE bucket=?)")) {
@@ -288,6 +291,7 @@ final class ClusterStore implements ObjectStorage, MultipartStorage {
"cluster_uploads IN ACCESS EXCLUSIVE MODE");
}
lockUsage(connection, oldName);
ClusterCredentialStore.requireUnscopedBucket(connection, oldName);
try (PreparedStatement check = connection.prepareStatement(
"SELECT EXISTS (SELECT 1 FROM cluster_buckets WHERE name=?)")) {
check.setString(1, newName);
@@ -0,0 +1,59 @@
package cloud.lunarsky.store;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.SecureRandom;
import java.util.Arrays;
import javax.crypto.Cipher;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
final class CredentialCipher {
static final int MAX_BYTES = 65536;
private static final byte[] MAGIC = { 'O', 'S', 'K', '1' };
private static final SecureRandom RANDOM = new SecureRandom();
private final SecretKeySpec master;
CredentialCipher(byte[] master) {
this.master = new SecretKeySpec(master, "AES");
Arrays.fill(master, (byte) 0);
}
byte[] decrypt(byte[] bytes) throws IOException {
if (bytes == null) return new byte[0];
if (bytes.length < MAGIC.length + 12 + 16 || bytes.length > MAX_BYTES ||
!Arrays.equals(MAGIC, Arrays.copyOf(bytes, MAGIC.length)))
throw new IOException("Invalid managed credential store");
byte[] nonce = Arrays.copyOfRange(bytes, MAGIC.length, MAGIC.length + 12);
try {
Cipher cipher = cipher(Cipher.DECRYPT_MODE, nonce);
return cipher.doFinal(bytes, MAGIC.length + 12, bytes.length - MAGIC.length - 12);
} catch (GeneralSecurityException error) {
throw new IOException("Managed credential store could not be decrypted", error);
}
}
byte[] encrypt(byte[] plain) throws IOException {
byte[] nonce = new byte[12];
RANDOM.nextBytes(nonce);
try {
byte[] encrypted = cipher(Cipher.ENCRYPT_MODE, nonce).doFinal(plain);
byte[] result = new byte[MAGIC.length + nonce.length + encrypted.length];
System.arraycopy(MAGIC, 0, result, 0, MAGIC.length);
System.arraycopy(nonce, 0, result, MAGIC.length, nonce.length);
System.arraycopy(encrypted, 0, result, MAGIC.length + nonce.length, encrypted.length);
return result;
} catch (GeneralSecurityException error) {
throw new IOException("Could not encrypt managed credentials", error);
} finally {
Arrays.fill(plain, (byte) 0);
}
}
private Cipher cipher(int mode, byte[] nonce) throws GeneralSecurityException {
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
cipher.init(mode, master, new GCMParameterSpec(128, nonce));
cipher.updateAAD(MAGIC);
return cipher;
}
}
@@ -0,0 +1,54 @@
package cloud.lunarsky.store;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
final class CredentialCodec {
private CredentialCodec() { }
static Map<String, ManagedCredentials.Key> decode(byte[] plain, Set<String> reserved)
throws IOException {
try {
Map<String, ManagedCredentials.Key> loaded = new HashMap<>();
for (String line : new String(plain, StandardCharsets.UTF_8).split("\n")) {
if (line.isEmpty()) continue;
ManagedCredentials.Key key = entry(line, reserved);
if (loaded.size() >= 64 || loaded.putIfAbsent(key.id(), key) != null)
throw new IOException("Invalid managed credential entry");
}
return Map.copyOf(loaded);
} finally {
Arrays.fill(plain, (byte) 0);
}
}
private static ManagedCredentials.Key entry(String line, Set<String> reserved) throws IOException {
String[] fields = line.split("\t", -1);
if (fields.length != 6 || !fields[0].matches("[A-Za-z0-9]{16,128}") ||
fields[1].length() < 32 || !Set.of("true", "false").contains(fields[5]) ||
reserved.contains(fields[0]))
throw new IOException("Invalid managed credential entry");
try {
Set<String> actions = Set.of(fields[4].split(","));
ManagedCredentials.validateScope(fields[2], fields[3], actions);
return new ManagedCredentials.Key(fields[0], fields[1], fields[2], fields[3],
actions, Boolean.parseBoolean(fields[5]));
} catch (IllegalArgumentException | StoreException error) {
throw new IOException("Invalid managed credential entry", error);
}
}
static byte[] encode(Map<String, ManagedCredentials.Key> keys) {
StringBuilder contents = new StringBuilder();
keys.values().stream().sorted(java.util.Comparator.comparing(ManagedCredentials.Key::id))
.forEach(key -> contents.append(key.id()).append('\t').append(key.secret()).append('\t')
.append(key.bucket()).append('\t').append(key.prefix()).append('\t')
.append(String.join(",", key.actions().stream().sorted().toList())).append('\t')
.append(key.enabled()).append('\n'));
return contents.toString().getBytes(StandardCharsets.UTF_8);
}
}
@@ -0,0 +1,51 @@
package cloud.lunarsky.store;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
final class DiskCredentialStore implements ManagedCredentialStore {
private final Path path;
private long revision;
DiskCredentialStore(Path path) { this.path = path; }
@Override public boolean shared() { return false; }
@Override public State read(long knownRevision) throws IOException {
return new State(revision, knownRevision == revision ? null : load());
}
@Override public State update(Change change) throws IOException {
byte[] encrypted = change.apply(new State(revision, load())).encrypted();
Files.createDirectories(path.getParent());
Path temporary = Files.createTempFile(path.getParent(), "managed-credentials-", ".tmp");
try {
Files.setPosixFilePermissions(temporary,
java.nio.file.attribute.PosixFilePermissions.fromString("rw-------"));
try (FileChannel channel = FileChannel.open(temporary, StandardOpenOption.WRITE)) {
ByteBuffer buffer = ByteBuffer.wrap(encrypted);
while (buffer.hasRemaining()) channel.write(buffer);
channel.force(true);
}
Files.move(temporary, path, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
try (FileChannel directory = FileChannel.open(path.getParent(), StandardOpenOption.READ)) {
directory.force(true);
}
} finally {
Files.deleteIfExists(temporary);
}
return new State(++revision, encrypted);
}
private byte[] load() throws IOException {
if (!Files.exists(path)) return null;
if (Files.size(path) > CredentialCipher.MAX_BYTES)
throw new IOException("Invalid managed credential store");
return Files.readAllBytes(path);
}
}
+10 -2
View File
@@ -134,6 +134,8 @@ public final class Main {
void setManagedCredentials(ManagedCredentials managedCredentials) {
this.managedCredentials = managedCredentials;
access.setManagedCredentials(managedCredentials);
authentication.setManagedCredentials(managedCredentials);
refreshManagedCredentials();
if (adminConsole != null)
adminConsole.setManagedCredentials(managedCredentials, this::refreshManagedCredentials);
@@ -142,8 +144,6 @@ public final class Main {
private synchronized void refreshManagedCredentials() {
ManagedCredentials managed = managedCredentials;
if (managed == null) return;
access.setManagedPolicies(managed.policies());
authentication.setManagedIdentities(managed.identities());
if (adminConsole != null) adminConsole.setIdentities(authentication.identities());
}
@@ -229,6 +229,14 @@ public final class Main {
}
private void dispatch(HttpExchange exchange, RequestContext context) throws IOException {
ManagedCredentials managed = managedCredentials;
if (managed == null || anonymousRead(exchange) ||
authentication.usesConfiguredIdentity(exchange.getRequestURI(), exchange.getRequestHeaders()))
dispatchAuthenticated(exchange, context);
else managed.withSnapshot(() -> dispatchAuthenticated(exchange, context));
}
private void dispatchAuthenticated(HttpExchange exchange, RequestContext context) throws IOException {
SigV4.Verified verified = verifyRequest(exchange);
context.principal = verified.principal();
String path = SigV4.decode(exchange.getRequestURI().getRawPath());
@@ -0,0 +1,18 @@
package cloud.lunarsky.store;
import java.io.IOException;
interface ManagedCredentialStore {
record State(long revision, byte[] encrypted) { }
record Mutation(byte[] encrypted, java.util.Set<String> buckets) { }
@FunctionalInterface
interface Change {
Mutation apply(State previous) throws IOException;
}
State read(long knownRevision) throws IOException;
State update(Change change) throws IOException;
boolean shared();
}
+111 -139
View File
@@ -2,14 +2,8 @@ package cloud.lunarsky.store;
import com.sun.net.httpserver.Headers;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.security.GeneralSecurityException;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Base64;
@@ -18,36 +12,41 @@ import java.util.HexFormat;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.crypto.Cipher;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
final class ManagedCredentials {
record Key(String id, String secret, String bucket, String prefix,
Set<String> actions, boolean enabled) { }
private static final byte[] MAGIC = { 'O', 'S', 'K', '1' };
private static final SecureRandom RANDOM = new SecureRandom();
private static final Set<String> ACTIONS = Set.of("read", "write", "list");
private final Path path;
private final SecretKeySpec master;
private record Snapshot(long revision, Map<String, Key> keys,
Map<String, String> identities, Map<String, BucketPolicy> policies) { }
private final ManagedCredentialStore storage;
private final CredentialCipher cipher;
private final Set<String> reserved;
private volatile Map<String, Key> keys;
private final ThreadLocal<Snapshot> request = new ThreadLocal<>();
private volatile Snapshot snapshot;
private ManagedCredentials(Path path, byte[] master, Set<String> reserved) throws IOException {
this.path = path;
this.master = new SecretKeySpec(master, "AES");
ManagedCredentials(ManagedCredentialStore storage, byte[] master, Set<String> reserved)
throws IOException {
this.storage = storage;
this.cipher = new CredentialCipher(master);
this.reserved = Set.copyOf(reserved);
java.util.Arrays.fill(master, (byte) 0);
this.keys = load();
ManagedCredentialStore.State state = storage.read(-1);
if (state.encrypted() == null && storage.shared())
state = storage.update(existing -> {
Map<String, Key> keys = CredentialCodec.decode(cipher.decrypt(existing.encrypted()), reserved);
byte[] encrypted = existing.encrypted() == null ?
cipher.encrypt(CredentialCodec.encode(keys)) : existing.encrypted();
return new ManagedCredentialStore.Mutation(encrypted, buckets(keys));
});
snapshot = decode(state);
}
static ManagedCredentials fromEnvironment(Map<String, String> env, ObjectStorage store,
Set<String> reserved) throws IOException {
String configured = env.get("S3_MANAGED_KEYS_MASTER_FILE");
if (configured == null || configured.isBlank()) return null;
if (!(store instanceof DiskStore))
throw new IllegalArgumentException("Managed credentials require disk mode");
byte[] master;
try {
master = HexFormat.of().parseHex(Files.readString(Path.of(configured)).trim());
@@ -56,20 +55,53 @@ final class ManagedCredentials {
}
if (master.length != 32)
throw new IllegalArgumentException("Managed credentials master key must contain 32 bytes");
return new ManagedCredentials(Path.of(env.getOrDefault("DATA_DIR", "/data"))
.resolve("managed-credentials.bin"), master, reserved);
ManagedCredentialStore storage = store instanceof ClusterStore cluster ?
cluster.managedCredentialStore() : new DiskCredentialStore(
Path.of(env.getOrDefault("DATA_DIR", "/data")).resolve("managed-credentials.bin"));
return new ManagedCredentials(storage, master, reserved);
}
List<Key> list() { return keys.values().stream().sorted(java.util.Comparator.comparing(Key::id)).toList(); }
boolean contains(String principal) { return principal != null && keys.containsKey(principal); }
List<Key> list() { return current().keys().values().stream().sorted(java.util.Comparator.comparing(Key::id)).toList(); }
boolean contains(String principal) { return principal != null && current().keys().containsKey(principal); }
Map<String, String> identities() { return current().identities(); }
Map<String, BucketPolicy> policies() { return current().policies(); }
Map<String, String> identities() {
Map<String, String> active = new HashMap<>();
keys.values().stream().filter(Key::enabled).forEach(key -> active.put(key.id(), key.secret()));
return Map.copyOf(active);
void withSnapshot(StoreOperations.Action action) throws IOException {
Snapshot previous = request.get();
request.set(refresh());
try { action.run(); }
finally {
if (previous == null) request.remove();
else request.set(previous);
}
}
Map<String, BucketPolicy> policies() {
private Snapshot refresh() throws IOException {
Snapshot known = snapshot;
if (!storage.shared()) return known;
ManagedCredentialStore.State state = storage.read(known.revision());
if (state.revision() < known.revision())
throw new IOException("Managed credential metadata moved backwards; restore a current backup before restarting");
Snapshot loaded = state.revision() == known.revision() ? known : decode(state);
synchronized (this) {
if (loaded.revision() > snapshot.revision()) snapshot = loaded;
return snapshot;
}
}
private Snapshot current() {
Snapshot pinned = request.get();
return pinned == null ? snapshot : pinned;
}
private Snapshot decode(ManagedCredentialStore.State state) throws IOException {
Map<String, Key> keys = CredentialCodec.decode(cipher.decrypt(state.encrypted()), reserved);
Map<String, String> identities = new HashMap<>();
keys.values().stream().filter(Key::enabled).forEach(key -> identities.put(key.id(), key.secret()));
return new Snapshot(state.revision(), keys, Map.copyOf(identities), policies(keys));
}
private static Map<String, BucketPolicy> policies(Map<String, Key> keys) {
Map<String, BucketPolicy> active = new HashMap<>();
for (Key key : keys.values()) {
if (!key.enabled()) continue;
@@ -106,35 +138,35 @@ final class ManagedCredentials {
}
synchronized Key create(String bucket, String prefix, Set<String> actions) throws IOException {
if (keys.size() >= 64) invalid("Too many managed access keys");
validateScope(bucket, prefix, actions);
byte[] random = new byte[24];
String id;
do {
Key[] created = new Key[1];
mutate(keys -> {
if (keys.size() >= 64) invalid("Too many managed access keys");
byte[] random = new byte[24];
String id;
do {
RANDOM.nextBytes(random);
id = HexFormat.of().withUpperCase().formatHex(random, 0, 16);
} while (reserved.contains(id) || keys.containsKey(id));
RANDOM.nextBytes(random);
id = HexFormat.of().withUpperCase().formatHex(random, 0, 16);
} while (reserved.contains(id) || keys.containsKey(id));
RANDOM.nextBytes(random);
String secret = Base64.getUrlEncoder().withoutPadding().encodeToString(random) +
Base64.getUrlEncoder().withoutPadding().encodeToString(randomToken());
Key key = new Key(id, secret, bucket, prefix, Set.copyOf(actions), true);
Map<String, Key> updated = new HashMap<>(keys);
updated.put(id, key);
persist(updated);
keys = Map.copyOf(updated);
return key;
String secret = Base64.getUrlEncoder().withoutPadding().encodeToString(random) +
Base64.getUrlEncoder().withoutPadding().encodeToString(randomToken());
Key key = new Key(id, secret, bucket, prefix, Set.copyOf(actions), true);
keys.put(id, key);
created[0] = key;
});
return created[0];
}
synchronized void update(String id, String bucket, String prefix, Set<String> actions) throws IOException {
Key old = key(id);
validateScope(bucket, prefix, actions);
Map<String, Key> updated = new HashMap<>(keys);
updated.put(id, new Key(id, old.secret(), bucket, prefix, Set.copyOf(actions), old.enabled()));
persist(updated);
keys = Map.copyOf(updated);
mutate(keys -> {
Key old = key(keys, id);
keys.put(id, new Key(id, old.secret(), bucket, prefix, Set.copyOf(actions), old.enabled()));
});
}
private static void validateScope(String bucket, String prefix, Set<String> actions) {
static void validateScope(String bucket, String prefix, Set<String> actions) {
if (bucket == null || prefix == null || actions == null ||
!bucket.matches("[a-z0-9][a-z0-9-]{1,61}[a-z0-9]") ||
prefix.length() > 256 || !prefix.matches("[A-Za-z0-9/_-]*") ||
@@ -143,19 +175,35 @@ final class ManagedCredentials {
}
synchronized void setEnabled(String id, boolean enabled) throws IOException {
Key old = key(id);
Map<String, Key> updated = new HashMap<>(keys);
updated.put(id, new Key(id, old.secret(), old.bucket(), old.prefix(), old.actions(), enabled));
persist(updated);
keys = Map.copyOf(updated);
mutate(keys -> {
Key old = key(keys, id);
keys.put(id, new Key(id, old.secret(), old.bucket(), old.prefix(), old.actions(), enabled));
});
}
synchronized void remove(String id) throws IOException {
key(id);
Map<String, Key> updated = new HashMap<>(keys);
updated.remove(id);
persist(updated);
keys = Map.copyOf(updated);
mutate(keys -> {
key(keys, id);
keys.remove(id);
});
}
private void mutate(java.util.function.Consumer<Map<String, Key>> change) throws IOException {
ManagedCredentialStore.State state = storage.update(previous -> {
if (storage.shared() && previous.revision() < snapshot.revision())
throw new IOException("Managed credential metadata moved backwards");
Map<String, Key> updated = new HashMap<>(
CredentialCodec.decode(cipher.decrypt(previous.encrypted()), reserved));
change.accept(updated);
return new ManagedCredentialStore.Mutation(
cipher.encrypt(CredentialCodec.encode(updated)), buckets(updated));
});
snapshot = decode(state);
if (request.get() != null) request.set(snapshot);
}
private static Set<String> buckets(Map<String, Key> keys) {
return keys.values().stream().map(Key::bucket).collect(java.util.stream.Collectors.toUnmodifiableSet());
}
void checkBucket(String principal, String bucket, String method, Map<String, String> query) {
@@ -189,90 +237,14 @@ final class ManagedCredentials {
}
}
private Key key(String id) {
private Key key(String id) { return key(current().keys(), id); }
private static Key key(Map<String, Key> keys, String id) {
Key key = keys.get(id);
if (key == null) throw new StoreException(404, "NoSuchKey", "Access key not found");
return key;
}
private Map<String, Key> load() throws IOException {
if (!Files.exists(path)) return Map.of();
byte[] bytes = Files.readAllBytes(path);
if (bytes.length < MAGIC.length + 12 + 16 || bytes.length > 65536 ||
!java.util.Arrays.equals(MAGIC, java.util.Arrays.copyOf(bytes, MAGIC.length)))
throw new IOException("Invalid managed credential store");
byte[] nonce = java.util.Arrays.copyOfRange(bytes, MAGIC.length, MAGIC.length + 12);
byte[] plain;
try {
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, master, new GCMParameterSpec(128, nonce));
cipher.updateAAD(MAGIC);
plain = cipher.doFinal(bytes, MAGIC.length + 12, bytes.length - MAGIC.length - 12);
} catch (GeneralSecurityException error) {
throw new IOException("Managed credential store could not be decrypted", error);
}
Map<String, Key> loaded = new HashMap<>();
for (String line : new String(plain, StandardCharsets.UTF_8).split("\n")) {
if (line.isEmpty()) continue;
String[] fields = line.split("\t", -1);
if (fields.length != 6 || !fields[0].matches("[A-Za-z0-9]{16,128}") ||
fields[1].length() < 32 || !fields[2].matches("[a-z0-9][a-z0-9-]{1,61}[a-z0-9]") ||
!fields[3].matches("[A-Za-z0-9/_-]*") || fields[3].length() > 256 ||
!Set.of("true", "false").contains(fields[5]) || reserved.contains(fields[0]))
throw new IOException("Invalid managed credential entry");
Set<String> actions;
try { actions = Set.of(fields[4].split(",")); }
catch (IllegalArgumentException error) { throw new IOException("Invalid managed credential entry", error); }
if (actions.isEmpty() || !ACTIONS.containsAll(actions) || loaded.size() >= 64 ||
loaded.putIfAbsent(fields[0], new Key(fields[0], fields[1], fields[2], fields[3],
actions, Boolean.parseBoolean(fields[5]))) != null)
throw new IOException("Invalid managed credential entry");
}
java.util.Arrays.fill(plain, (byte) 0);
return Map.copyOf(loaded);
}
private void persist(Map<String, Key> updated) throws IOException {
StringBuilder contents = new StringBuilder();
updated.values().stream().sorted(java.util.Comparator.comparing(Key::id)).forEach(key ->
contents.append(key.id()).append('\t').append(key.secret()).append('\t')
.append(key.bucket()).append('\t').append(key.prefix()).append('\t')
.append(String.join(",", key.actions().stream().sorted().toList())).append('\t')
.append(key.enabled()).append('\n'));
byte[] nonce = randomToken();
byte[] encrypted;
try {
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, master, new GCMParameterSpec(128, nonce));
cipher.updateAAD(MAGIC);
encrypted = cipher.doFinal(contents.toString().getBytes(StandardCharsets.UTF_8));
} catch (GeneralSecurityException error) {
throw new IOException("Could not encrypt managed credentials", error);
}
Files.createDirectories(path.getParent());
Path temporary = Files.createTempFile(path.getParent(), "managed-credentials-", ".tmp");
try {
Files.setPosixFilePermissions(temporary, java.nio.file.attribute.PosixFilePermissions.fromString("rw-------"));
try (FileChannel channel = FileChannel.open(temporary, StandardOpenOption.WRITE)) {
writeAll(channel, MAGIC);
writeAll(channel, nonce);
writeAll(channel, encrypted);
channel.force(true);
}
Files.move(temporary, path, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
try (FileChannel directory = FileChannel.open(path.getParent(), StandardOpenOption.READ)) {
directory.force(true);
}
} finally {
Files.deleteIfExists(temporary);
}
}
private static void writeAll(FileChannel channel, byte[] bytes) throws IOException {
ByteBuffer buffer = ByteBuffer.wrap(bytes);
while (buffer.hasRemaining()) channel.write(buffer);
}
private static byte[] randomToken() {
byte[] nonce = new byte[12];
RANDOM.nextBytes(nonce);
+3 -2
View File
@@ -106,7 +106,7 @@ final class MultipartStore implements MultipartStorage {
if (length > store.maxObject()) throw new StoreException(413, "EntityTooLarge", "Part exceeds the object limit");
Path dir = upload(id, bucket, key), target = part(dir, number);
long previous = Files.exists(target) ? Files.size(target) : 0;
if (staged - previous + length > store.maxTotal())
if (length > store.maxTotal() - (staged - previous))
throw new StoreException(507, "InsufficientStorage", "Multipart staging limit reached");
Path pending = Files.createTempFile(store.root().resolve("pending"), "part-", ".part");
try {
@@ -152,8 +152,9 @@ final class MultipartStore implements MultipartStorage {
Path file = part(dir, part.number());
if (!Files.isRegularFile(file)) throw new StoreException(400, "InvalidPart", "Missing part");
long length = Files.size(file);
if (length > store.maxObject() - total)
throw new StoreException(413, "EntityTooLarge", "Object exceeds the configured size limit");
total += length;
if (total > store.maxObject()) throw new StoreException(413, "EntityTooLarge", "Object exceeds the configured size limit");
MessageDigest md5 = digest("MD5");
java.util.zip.CRC32 crc32 = new java.util.zip.CRC32();
try (var input = Files.newInputStream(file)) {
+11 -10
View File
@@ -8,7 +8,7 @@ final class S3Access {
private final ObjectStorage store;
private final String owner;
private final java.util.Map<String, BucketPolicy> configuredIdentityPolicies;
private volatile java.util.Map<String, BucketPolicy> identityPolicies;
private volatile ManagedCredentials managedCredentials;
private final ConcurrentHashMap<String, CachedPolicy> policies = new ConcurrentHashMap<>();
private record CachedPolicy(String source, BucketPolicy parsed) { }
@@ -20,15 +20,17 @@ final class S3Access {
this.store = store;
this.owner = owner;
this.configuredIdentityPolicies = java.util.Map.copyOf(identityPolicies);
this.identityPolicies = configuredIdentityPolicies;
}
synchronized void setManagedPolicies(java.util.Map<String, BucketPolicy> managed) {
var combined = new java.util.HashMap<>(configuredIdentityPolicies);
for (var entry : managed.entrySet())
if (combined.putIfAbsent(entry.getKey(), entry.getValue()) != null)
throw new IllegalArgumentException("Managed policy conflicts with a configured identity");
identityPolicies = java.util.Map.copyOf(combined);
void setManagedCredentials(ManagedCredentials managed) { managedCredentials = managed; }
private BucketPolicy identityPolicy(String principal) {
if (principal == null) return BucketPolicy.empty();
BucketPolicy configured = configuredIdentityPolicies.get(principal);
if (configured != null) return configured;
ManagedCredentials managed = managedCredentials;
return managed == null ? BucketPolicy.empty() :
managed.policies().getOrDefault(principal, BucketPolicy.empty());
}
String owner() {
@@ -83,8 +85,7 @@ final class S3Access {
String resource = "arn:aws:s3:::" + bucket.name() + (key == null ? "" : "/" + key);
BucketPolicy policy = policy(bucket);
int decision = policy.decide(principal, action, resource);
int identityDecision = principal == null ? 0 :
identityPolicies.getOrDefault(principal, BucketPolicy.empty()).decide(principal, action, resource);
int identityDecision = identityPolicy(principal).decide(principal, action, resource);
if (decision < 0) return new Decision(false, "Explicit bucket policy deny");
if (identityDecision < 0) return new Decision(false, "Explicit identity policy deny");
if (BucketSecurity.allowsAcl(bucket, acl, principal, owner, permission))
+9 -1
View File
@@ -21,7 +21,7 @@ final class SchemaMigrator {
result.next();
version = result.getInt(1);
}
if (version > 14) throw new IOException("Metadata schema is newer than this ObjectStore build");
if (version > 15) throw new IOException("Metadata schema is newer than this ObjectStore build");
if (version < 1) {
statement.execute("CREATE TABLE IF NOT EXISTS cluster_usage (bucket text PRIMARY KEY, used_bytes bigint NOT NULL CHECK (used_bytes >= 0))");
statement.execute("CREATE TABLE IF NOT EXISTS cluster_objects (bucket text NOT NULL, object_key text COLLATE \"C\" NOT NULL, generation uuid NOT NULL, length bigint NOT NULL, modified bigint NOT NULL, etag text NOT NULL, sha256 bytea NOT NULL, content_type text NOT NULL, PRIMARY KEY (bucket, object_key))");
@@ -129,6 +129,14 @@ final class SchemaMigrator {
"finished_at bigint NOT NULL)");
statement.execute("INSERT INTO cluster_schema_migrations VALUES (14)");
}
if (version < 15) {
statement.execute("CREATE TABLE cluster_managed_credentials (singleton integer PRIMARY KEY " +
"CHECK (singleton=1), revision bigint NOT NULL CHECK (revision > 0), " +
"encrypted bytea NOT NULL CHECK (octet_length(encrypted) BETWEEN 32 AND 65536))");
statement.execute("CREATE TABLE cluster_managed_credential_buckets " +
"(bucket text PRIMARY KEY REFERENCES cluster_buckets(name))");
statement.execute("INSERT INTO cluster_schema_migrations VALUES (15)");
}
statement.execute("INSERT INTO cluster_format SELECT 1, CASE WHEN EXISTS (SELECT 1 FROM cluster_segments WHERE replica_ids IS NULL) THEN 1 ELSE 2 END WHERE NOT EXISTS (SELECT 1 FROM cluster_format)");
}
try (PreparedStatement check = connection.prepareStatement(
+25 -13
View File
@@ -30,7 +30,7 @@ final class SigV4 {
private static final DateTimeFormatter DATE = DateTimeFormatter.ofPattern("uuuuMMdd'T'HHmmss'Z'").withZone(ZoneOffset.UTC);
private static final Pattern HEX = Pattern.compile("[0-9a-f]{64}");
private final Map<String, String> configuredIdentities;
private volatile Map<String, String> identities;
private volatile ManagedCredentials managedCredentials;
private final Map<String, SessionCredentials.Session> sessions;
private final String root;
private final String region;
@@ -47,10 +47,9 @@ final class SigV4 {
SigV4(Map<String, String> identities, Map<String, SessionCredentials.Session> sessions,
String root, String region, Clock clock) {
this.configuredIdentities = Map.copyOf(identities);
this.identities = configuredIdentities;
this.sessions = Map.copyOf(sessions);
if (!this.identities.containsKey(root)) throw new IllegalArgumentException("Missing root identity");
if (this.sessions.keySet().stream().anyMatch(this.identities::containsKey))
if (!configuredIdentities.containsKey(root)) throw new IllegalArgumentException("Missing root identity");
if (this.sessions.keySet().stream().anyMatch(configuredIdentities::containsKey))
throw new IllegalArgumentException("Session and permanent keys overlap");
this.root = root;
this.region = region;
@@ -62,19 +61,32 @@ final class SigV4 {
return principal != null &&
(configuredIdentities.containsKey(principal) || sessions.containsKey(principal));
}
synchronized void setManagedIdentities(Map<String, String> managed) {
Map<String, String> combined = new java.util.HashMap<>(configuredIdentities);
for (var entry : managed.entrySet())
if (combined.putIfAbsent(entry.getKey(), entry.getValue()) != null || sessions.containsKey(entry.getKey()))
throw new IllegalArgumentException("Managed access key conflicts with a configured identity");
identities = Map.copyOf(combined);
boolean usesConfiguredIdentity(URI uri, Headers headers) {
String credential = hasPresignedQuery(uri.getRawQuery()) ?
presignedQuery(uri.getRawQuery()).fields().get("X-Amz-Credential") :
authorizationFields(headers).get("Credential");
if (credential == null) denied("Missing credential scope");
return configuredIdentity(credential.split("/", -1)[0]);
}
void setManagedCredentials(ManagedCredentials managed) { managedCredentials = managed; }
Set<String> identities() {
var all = new java.util.HashSet<>(identities.keySet());
var all = new java.util.HashSet<>(configuredIdentities.keySet());
all.addAll(sessions.keySet());
ManagedCredentials managed = managedCredentials;
if (managed != null) all.addAll(managed.identities().keySet());
return Set.copyOf(all);
}
private String identitySecret(String accessKey) {
String secret = configuredIdentities.get(accessKey);
if (secret == null && managedCredentials != null)
secret = managedCredentials.identities().get(accessKey);
return secret;
}
String verify(String method, URI uri, Headers headers) {
return verifyRequest(method, uri, headers).payload();
}
@@ -197,13 +209,13 @@ final class SigV4 {
private String[] credentialScope(String value) {
String[] credential = value.split("/", -1);
if (credential.length != 5 || !(identities.containsKey(credential[0]) || sessions.containsKey(credential[0])) || !credential[2].equals(region)
if (credential.length != 5 || !(identitySecret(credential[0]) != null || sessions.containsKey(credential[0])) || !credential[2].equals(region)
|| !credential[3].equals("s3") || !credential[4].equals("aws4_request")) denied("Invalid credential scope");
return credential;
}
private String secret(String accessKey) {
String secret = identities.get(accessKey);
String secret = identitySecret(accessKey);
if (secret == null && sessions.containsKey(accessKey)) secret = sessions.get(accessKey).secret();
if (secret == null) denied("Invalid credential scope");
return secret;
+4 -2
View File
@@ -3,17 +3,19 @@ package cloud.lunarsky.store;
import java.util.Map;
final class StorageLimits {
static final long MAX_OBJECT_BYTES = 64L * 1024 * 1024 * 1024;
private StorageLimits() {}
static ObjectStorage.Limits fromEnvironment(Map<String, String> environment) {
try {
long maxObject = Long.parseLong(environment.getOrDefault("MAX_OBJECT_BYTES", "134217728"));
long maxTotal = Long.parseLong(environment.getOrDefault("MAX_TOTAL_BYTES", "2147483648"));
if (maxObject < 1 || maxObject > 1073741824L || maxTotal < maxObject)
if (maxObject < 1 || maxObject > MAX_OBJECT_BYTES || maxTotal < maxObject)
throw new NumberFormatException();
return new ObjectStorage.Limits(maxObject, maxTotal);
} catch (NumberFormatException error) {
throw new IllegalArgumentException("Invalid storage size limits", error);
throw new IllegalArgumentException("MAX_OBJECT_BYTES must be between 1 and " +
MAX_OBJECT_BYTES + "; MAX_TOTAL_BYTES must be at least MAX_OBJECT_BYTES", error);
}
}
}