Release ObjectStore 0.1.0

This commit is contained in:
admin committed 2026-10-25 07:42:20 +01:00
1 parent 0cf5c11202
commit 35bd1d5703
34 files changed
+1273 -87

No files matched your search

+6 -1
View File
@@ -65,6 +65,8 @@ final class Acl {
principal = entry.substring(4, entry.length() - 1);
else if (entry.startsWith("uri=\"") && entry.endsWith("\""))
principal = entry.substring(5, entry.length() - 1);
else if (entry.startsWith("emailAddress=\""))
throw new StoreException(405, "MethodNotAllowed", "Email ACL grantees are no longer supported");
else throw new StoreException(400, "InvalidArgument", "Invalid ACL grant");
if (!identities.contains(principal) && !principal.equals(ALL_USERS) &&
!principal.equals(AUTHENTICATED_USERS))
@@ -122,6 +124,8 @@ final class Acl {
String principal = switch (type) {
case "CanonicalUser" -> text(grantee, "ID");
case "Group" -> text(grantee, "URI");
case "AmazonCustomerByEmail" -> throw new StoreException(405, "MethodNotAllowed",
"Email ACL grantees are no longer supported");
default -> throw new IllegalArgumentException();
};
Integer permission = PERMISSIONS.get(text(grant, "Permission"));
@@ -130,7 +134,8 @@ final class Acl {
}
grants.remove(owner);
return validate(encoded(grants), identities);
} catch (Exception error) {
} catch (StoreException error) { throw error; }
catch (Exception error) {
throw new StoreException(400, "MalformedACLError", "Invalid access control policy");
}
}
+92 -6
View File
@@ -40,30 +40,105 @@ final class BucketHandler {
void handleBucket(HttpExchange exchange, Map<String, String> query, String hash,
String bucketName, String principal) throws IOException {
String method = exchange.getRequestMethod();
if (query.size() >= 1 && query.size() <= 2 &&
query.keySet().stream().allMatch(java.util.Set.of("ownershipControls", "x-id")::contains) &&
query.containsKey("ownershipControls") && query.get("ownershipControls").isEmpty()) {
access.requireOwner(principal);
if (method.equals("GET")) {
S3Request.requireEmptyBody(exchange, hash);
S3Xml.sendXml(exchange, 200, BucketSecurity.ownershipXml(store.bucket(bucketName).ownership()));
} else if (method.equals("PUT")) {
byte[] body = S3Request.signedBody(exchange, hash, 65536);
S3Request.verifyContentMd5(exchange.getRequestHeaders(), body);
store.setBucketOwnership(bucketName, BucketSecurity.parseOwnership(body));
exchange.sendResponseHeaders(200, -1);
} else if (method.equals("DELETE")) {
S3Request.requireEmptyBody(exchange, hash);
store.setBucketOwnership(bucketName, ObjectStorage.ObjectOwnership.OBJECT_WRITER);
exchange.sendResponseHeaders(204, -1);
} else S3Request.unsupported("Ownership controls operation");
return;
}
if (query.size() >= 1 && query.size() <= 2 &&
query.keySet().stream().allMatch(java.util.Set.of("publicAccessBlock", "x-id")::contains) &&
query.containsKey("publicAccessBlock") && query.get("publicAccessBlock").isEmpty()) {
access.requireOwner(principal);
if (method.equals("GET")) {
S3Request.requireEmptyBody(exchange, hash);
S3Xml.sendXml(exchange, 200, BucketSecurity.publicAccessXml(
store.bucket(bucketName).publicAccessBlock()));
} else if (method.equals("PUT")) {
byte[] body = S3Request.signedBody(exchange, hash, 65536);
S3Request.verifyContentMd5(exchange.getRequestHeaders(), body);
store.setPublicAccessBlock(bucketName, BucketSecurity.parsePublicAccess(body));
exchange.sendResponseHeaders(200, -1);
} else if (method.equals("DELETE")) {
S3Request.requireEmptyBody(exchange, hash);
store.setPublicAccessBlock(bucketName, ObjectStorage.PublicAccessBlock.open());
exchange.sendResponseHeaders(204, -1);
} else S3Request.unsupported("Public access block operation");
return;
}
if (query.size() >= 1 && query.size() <= 2 &&
query.keySet().stream().allMatch(java.util.Set.of("policy", "x-id")::contains) &&
query.containsKey("policy") && query.get("policy").isEmpty()) {
access.requireOwner(principal);
var current = store.bucket(bucketName);
if (method.equals("GET")) {
S3Request.requireEmptyBody(exchange, hash);
if (current.policy() == null)
throw new StoreException(404, "NoSuchBucketPolicy", "Bucket has no policy");
byte[] body = current.policy().getBytes(StandardCharsets.UTF_8);
exchange.getResponseHeaders().set("Content-Type", "application/json");
exchange.sendResponseHeaders(200, body.length);
exchange.getResponseBody().write(body);
} else if (method.equals("PUT")) {
byte[] body = S3Request.signedBody(exchange, hash, 20480);
S3Request.verifyContentMd5(exchange.getRequestHeaders(), body);
String policy = new String(body, StandardCharsets.UTF_8);
BucketPolicy parsed = BucketPolicy.parse(policy, bucketName);
if (current.publicAccessBlock().blockPublicPolicy() && parsed.publicAllow())
throw new StoreException(403, "AccessDenied", "Public bucket policies are blocked");
store.setBucketPolicy(bucketName, policy);
exchange.sendResponseHeaders(204, -1);
} else if (method.equals("DELETE")) {
S3Request.requireEmptyBody(exchange, hash);
store.setBucketPolicy(bucketName, null);
exchange.sendResponseHeaders(204, -1);
} else S3Request.unsupported("Bucket policy operation");
return;
}
if (query.containsKey("acl") && query.get("acl").isEmpty() &&
query.keySet().stream().allMatch(java.util.Set.of("acl", "x-id")::contains) &&
(!query.containsKey("x-id") ||
query.get("x-id").equals(method.equals("GET") ? "GetBucketAcl" : "PutBucketAcl")) &&
(method.equals("GET") || method.equals("PUT"))) {
var current = store.bucket(bucketName);
Acl.require(current.acl(), principal, owner,
access.requireBucket(bucketName, principal,
method.equals("GET") ? Acl.READ_ACP : Acl.WRITE_ACP);
if (method.equals("GET")) {
S3Request.requireEmptyBody(exchange, hash);
S3Xml.sendXml(exchange, 200, Acl.xml(current.acl(), owner));
S3Xml.sendXml(exchange, 200, Acl.xml(
current.ownership() == ObjectStorage.ObjectOwnership.BUCKET_OWNER_ENFORCED
? Map.of() : current.acl(), owner));
} else {
if (current.ownership() == ObjectStorage.ObjectOwnership.BUCKET_OWNER_ENFORCED)
throw new StoreException(400, "AccessControlListNotSupported", "ACLs are disabled for this bucket");
if (exchange.getRequestHeaders().containsKey("x-amz-acl") ||
exchange.getRequestHeaders().keySet().stream().anyMatch(
name -> name.toLowerCase(Locale.ROOT).startsWith("x-amz-grant-"))) {
S3Request.requireEmptyBody(exchange, hash);
S3Request.verifyContentMd5(exchange.getRequestHeaders(), new byte[0]);
store.setBucketAcl(bucketName, Acl.fromHeaders(exchange.getRequestHeaders(),
authentication.identities()));
Map<String, String> acl = Acl.fromHeaders(exchange.getRequestHeaders(),
authentication.identities());
BucketSecurity.checkAcl(current, exchange.getRequestHeaders(), acl, true);
store.setBucketAcl(bucketName, acl);
} else {
byte[] body = S3Request.signedBody(exchange, hash, 65536);
S3Request.verifyContentMd5(exchange.getRequestHeaders(), body);
store.setBucketAcl(bucketName, Acl.fromXml(body,
owner, authentication.identities()));
Map<String, String> acl = Acl.fromXml(body, owner, authentication.identities());
BucketSecurity.checkAcl(current, exchange.getRequestHeaders(), acl, true);
store.setBucketAcl(bucketName, acl);
}
exchange.sendResponseHeaders(200, -1);
}
@@ -81,9 +156,20 @@ final class BucketHandler {
switch (method) {
case "PUT" -> {
access.requireOwner(principal);
String requestedOwnership = SigV4.single(exchange.getRequestHeaders(), "x-amz-object-ownership");
ObjectStorage.ObjectOwnership ownership = requestedOwnership == null
? ObjectStorage.ObjectOwnership.BUCKET_OWNER_ENFORCED
: BucketSecurity.ownership(requestedOwnership);
Map<String, String> acl = Acl.fromHeaders(exchange.getRequestHeaders(),
authentication.identities());
BucketSecurity.checkAcl(new ObjectStorage.Bucket(bucketName, 0,
ObjectStorage.VersioningState.NEVER, Map.of(), ownership,
ObjectStorage.PublicAccessBlock.secure(), null),
exchange.getRequestHeaders(), acl, false);
store.createBucket(bucketName);
if (requestedOwnership != null &&
ownership != ObjectStorage.ObjectOwnership.BUCKET_OWNER_ENFORCED)
store.setBucketOwnership(bucketName, ownership);
if (!acl.isEmpty()) store.setBucketAcl(bucketName, acl);
exchange.getResponseHeaders().set("Location", "/" + bucketName);
exchange.sendResponseHeaders(200, -1);
+228
View File
@@ -0,0 +1,228 @@
package cloud.lunarsky.store;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
final class BucketPolicy {
private static final BucketPolicy EMPTY = new BucketPolicy(List.of());
private record Statement(boolean allow, List<String> principals, List<String> actions,
List<String> resources) {
boolean matches(String principal, String action, String resource) {
return (principals.contains("*") || principal != null && principals.contains(principal)) &&
actions.stream().anyMatch(pattern -> glob(pattern, action)) &&
resources.stream().anyMatch(pattern -> glob(pattern, resource));
}
}
private final List<Statement> statements;
private final boolean publicAllow;
private BucketPolicy(List<Statement> statements) {
this.statements = List.copyOf(statements);
this.publicAllow = statements.stream().anyMatch(
statement -> statement.allow() && statement.principals().contains("*"));
}
static BucketPolicy empty() { return EMPTY; }
boolean publicAllow() { return publicAllow; }
int decide(String principal, String action, String resource) {
boolean allowed = false;
for (Statement statement : statements) {
if (!statement.matches(principal, action, resource)) continue;
if (!statement.allow()) return -1;
allowed = true;
}
return allowed ? 1 : 0;
}
static BucketPolicy parse(String json, String bucket) {
return parse(json, bucket, false);
}
static BucketPolicy parseIdentity(String json) {
return parse(json, null, true);
}
private static BucketPolicy parse(String json, String bucket, boolean identity) {
if (json == null || json.isBlank() || json.getBytes(StandardCharsets.UTF_8).length > 20480)
throw invalid();
Object parsed = new Parser(json).parse();
Map<String, Object> policy = object(parsed);
if (!policy.keySet().stream().allMatch(Set.of("Version", "Id", "Statement")::contains) ||
!"2012-10-17".equals(policy.get("Version"))) throw invalid();
Object raw = policy.get("Statement");
if (raw == null) throw invalid();
List<?> entries = raw instanceof List<?> list ? list : List.of(raw);
if (entries.isEmpty() || entries.size() > 64) throw invalid();
List<Statement> statements = new ArrayList<>();
for (Object entry : entries) {
Map<String, Object> item = object(entry);
Set<String> keys = identity ? Set.of("Sid", "Effect", "Action", "Resource") :
Set.of("Sid", "Effect", "Principal", "Action", "Resource");
if (!item.keySet().stream().allMatch(keys::contains))
throw invalid();
boolean allow;
if ("Allow".equals(item.get("Effect"))) allow = true;
else if ("Deny".equals(item.get("Effect"))) allow = false;
else throw invalid();
Object principal = item.get("Principal");
List<String> principals = identity ? List.of("*") : principal instanceof Map<?, ?> map
? strings(object(map).get("AWS")) : strings(principal);
if (!identity && principal instanceof Map<?, ?> map && !map.keySet().equals(Set.of("AWS")))
throw invalid();
for (String name : principals)
if (!name.equals("*") && !name.matches("[A-Za-z0-9]{16,128}")) throw invalid();
List<String> actions = strings(item.get("Action"));
for (String action : actions)
if (!action.matches("s3:[A-Za-z*]+")) throw invalid();
List<String> resources = strings(item.get("Resource"));
String bucketArn = "arn:aws:s3:::" + bucket;
for (String resource : resources)
if (identity ? !resource.matches("arn:aws:s3:::[a-z0-9*?][a-z0-9*?.-]{0,62}(/[^\\p{Cntrl}]+)?") :
!resource.equals(bucketArn) && !resource.startsWith(bucketArn + "/")) throw invalid();
statements.add(new Statement(allow, principals, actions, resources));
}
return new BucketPolicy(statements);
}
private static List<String> strings(Object value) {
if (value == null) throw invalid();
List<?> values = value instanceof List<?> list ? list : List.of(value);
if (values.isEmpty() || values.size() > 64) throw invalid();
List<String> result = new ArrayList<>();
for (Object item : values) {
if (!(item instanceof String text) || text.isBlank() || text.length() > 1024)
throw invalid();
result.add(text);
}
return List.copyOf(result);
}
@SuppressWarnings("unchecked")
private static Map<String, Object> object(Object value) {
if (!(value instanceof Map<?, ?>)) throw invalid();
return (Map<String, Object>) value;
}
private static StoreException invalid() {
return new StoreException(400, "MalformedPolicy", "Unsupported or malformed bucket policy");
}
private static boolean glob(String pattern, String text) {
int p = 0, t = 0, star = -1, retry = 0;
while (t < text.length()) {
if (p < pattern.length() && pattern.charAt(p) == text.charAt(t)) { p++; t++; }
else if (p < pattern.length() && pattern.charAt(p) == '*') { star = p++; retry = t; }
else if (star >= 0) { p = star + 1; t = ++retry; }
else return false;
}
while (p < pattern.length() && pattern.charAt(p) == '*') p++;
return p == pattern.length();
}
private static final class Parser {
private final String input;
private int index;
Parser(String input) { this.input = input; }
Object parse() {
Object value = value(0);
space();
if (index != input.length()) throw invalid();
return value;
}
private Object value(int depth) {
if (depth > 16) throw invalid();
space();
if (index == input.length()) throw invalid();
return switch (input.charAt(index)) {
case '"' -> string();
case '{' -> object(depth + 1);
case '[' -> array(depth + 1);
default -> throw invalid();
};
}
private Map<String, Object> object(int depth) {
index++;
Map<String, Object> map = new LinkedHashMap<>();
space();
if (take('}')) return map;
do {
space();
if (index == input.length() || input.charAt(index) != '"') throw invalid();
String key = string();
space();
expect(':');
if (map.putIfAbsent(key, value(depth)) != null) throw invalid();
space();
if (take('}')) return map;
expect(',');
} while (true);
}
private List<Object> array(int depth) {
index++;
List<Object> list = new ArrayList<>();
space();
if (take(']')) return list;
do {
if (list.size() >= 64) throw invalid();
list.add(value(depth));
space();
if (take(']')) return list;
expect(',');
} while (true);
}
private String string() {
expect('"');
StringBuilder result = new StringBuilder();
while (index < input.length()) {
char c = input.charAt(index++);
if (c == '"') return result.toString();
if (c < 0x20) throw invalid();
if (c != '\\') { result.append(c); continue; }
if (index == input.length()) throw invalid();
char escape = input.charAt(index++);
switch (escape) {
case '"', '\\', '/' -> result.append(escape);
case 'b' -> result.append('\b');
case 'f' -> result.append('\f');
case 'n' -> result.append('\n');
case 'r' -> result.append('\r');
case 't' -> result.append('\t');
case 'u' -> {
if (index + 4 > input.length()) throw invalid();
try { result.append((char) Integer.parseInt(input.substring(index, index + 4), 16)); }
catch (NumberFormatException error) { throw invalid(); }
index += 4;
}
default -> throw invalid();
}
}
throw invalid();
}
private void space() {
while (index < input.length() && Character.isWhitespace(input.charAt(index))) index++;
}
private boolean take(char expected) {
if (index < input.length() && input.charAt(index) == expected) { index++; return true; }
return false;
}
private void expect(char expected) {
if (!take(expected)) throw invalid();
}
}
}
@@ -0,0 +1,149 @@
package cloud.lunarsky.store;
import com.sun.net.httpserver.Headers;
import java.io.ByteArrayInputStream;
import java.util.Map;
import java.util.Set;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Element;
final class BucketSecurity {
private BucketSecurity() { }
static String ownershipName(ObjectStorage.ObjectOwnership ownership) {
return switch (ownership) {
case BUCKET_OWNER_ENFORCED -> "BucketOwnerEnforced";
case BUCKET_OWNER_PREFERRED -> "BucketOwnerPreferred";
case OBJECT_WRITER -> "ObjectWriter";
};
}
static ObjectStorage.ObjectOwnership ownership(String value) {
return switch (value) {
case "BucketOwnerEnforced" -> ObjectStorage.ObjectOwnership.BUCKET_OWNER_ENFORCED;
case "BucketOwnerPreferred" -> ObjectStorage.ObjectOwnership.BUCKET_OWNER_PREFERRED;
case "ObjectWriter" -> ObjectStorage.ObjectOwnership.OBJECT_WRITER;
default -> throw new StoreException(400, "InvalidArgument", "Invalid object ownership setting");
};
}
static String ownershipXml(ObjectStorage.ObjectOwnership ownership) {
return "<OwnershipControls xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">" +
"<Rule><ObjectOwnership>" + ownershipName(ownership) +
"</ObjectOwnership></Rule></OwnershipControls>";
}
static ObjectStorage.ObjectOwnership parseOwnership(byte[] body) {
Element root = root(body, "OwnershipControls");
Element rule = onlyChild(root, "Rule");
return ownership(onlyChild(rule, "ObjectOwnership").getTextContent().trim());
}
static String publicAccessXml(ObjectStorage.PublicAccessBlock block) {
return "<PublicAccessBlockConfiguration xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">" +
"<BlockPublicAcls>" + block.blockPublicAcls() + "</BlockPublicAcls>" +
"<IgnorePublicAcls>" + block.ignorePublicAcls() + "</IgnorePublicAcls>" +
"<BlockPublicPolicy>" + block.blockPublicPolicy() + "</BlockPublicPolicy>" +
"<RestrictPublicBuckets>" + block.restrictPublicBuckets() +
"</RestrictPublicBuckets></PublicAccessBlockConfiguration>";
}
static ObjectStorage.PublicAccessBlock parsePublicAccess(byte[] body) {
Element root = root(body, "PublicAccessBlockConfiguration");
if (elements(root) != 4) malformed();
return new ObjectStorage.PublicAccessBlock(
bool(onlyNamedChild(root, "BlockPublicAcls")),
bool(onlyNamedChild(root, "IgnorePublicAcls")),
bool(onlyNamedChild(root, "BlockPublicPolicy")),
bool(onlyNamedChild(root, "RestrictPublicBuckets")));
}
static void checkAcl(ObjectStorage.Bucket bucket, Headers headers, Map<String, String> acl,
boolean aclOperation) {
if (bucket.ownership() == ObjectStorage.ObjectOwnership.BUCKET_OWNER_ENFORCED) {
String canned = SigV4.single(headers, "x-amz-acl");
if (aclOperation || !acl.isEmpty() ||
canned != null && !canned.equals("bucket-owner-full-control"))
throw new StoreException(400, "AccessControlListNotSupported", "ACLs are disabled for this bucket");
}
if (bucket.publicAccessBlock().blockPublicAcls() && isPublic(acl))
throw new StoreException(403, "AccessDenied", "Public ACLs are blocked for this bucket");
}
static boolean allowsAcl(ObjectStorage.Bucket bucket, Map<String, String> acl,
String principal, String owner, int permission) {
if (bucket.ownership() == ObjectStorage.ObjectOwnership.BUCKET_OWNER_ENFORCED)
return owner.equals(principal);
if (bucket.publicAccessBlock().ignorePublicAcls() && isPublicPrincipal(principal))
return false;
if (bucket.publicAccessBlock().ignorePublicAcls())
acl = acl.entrySet().stream()
.filter(entry -> !isPublicPrincipal(entry.getKey()))
.collect(java.util.stream.Collectors.toUnmodifiableMap(Map.Entry::getKey, Map.Entry::getValue));
return Acl.allows(acl, principal, owner, permission);
}
static boolean isPublic(Map<String, String> acl) {
return acl.containsKey(Acl.ALL_USERS) || acl.containsKey(Acl.AUTHENTICATED_USERS);
}
private static boolean isPublicPrincipal(String principal) {
return Acl.ALL_USERS.equals(principal) || Acl.AUTHENTICATED_USERS.equals(principal);
}
private static boolean bool(Element element) {
if (elements(element) != 0) malformed();
return switch (element.getTextContent().trim().toLowerCase(java.util.Locale.ROOT)) {
case "true" -> true;
case "false" -> false;
default -> throw new StoreException(400, "MalformedXML", "Invalid public access block setting");
};
}
private static Element root(byte[] body, String name) {
try {
var factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
factory.setExpandEntityReferences(false);
Element root = factory.newDocumentBuilder().parse(new ByteArrayInputStream(body)).getDocumentElement();
if (!name.equals(root.getLocalName())) malformed();
return root;
} catch (StoreException error) { throw error; }
catch (Exception error) { throw new StoreException(400, "MalformedXML", "Invalid bucket configuration"); }
}
private static Element onlyChild(Element parent, String name) {
if (elements(parent) != 1) malformed();
return onlyNamedChild(parent, name);
}
private static Element onlyNamedChild(Element parent, String name) {
var children = parent.getChildNodes();
Element found = null;
for (int i = 0; i < children.getLength(); i++) {
if (children.item(i) instanceof Element child && name.equals(child.getLocalName())) {
if (found != null) malformed();
found = child;
}
}
if (found == null) malformed();
return found;
}
private static int elements(Element parent) {
int count = 0;
var children = parent.getChildNodes();
for (int i = 0; i < children.getLength(); i++)
if (children.item(i) instanceof Element) count++;
return count;
}
private static void malformed() {
throw new StoreException(400, "MalformedXML", "Invalid bucket configuration");
}
}
+51 -5
View File
@@ -78,12 +78,16 @@ final class ClusterStore implements ObjectStorage, MultipartStorage {
@Override public Bucket bucket(String name) throws IOException {
try (Connection connection = connect(); PreparedStatement query = connection.prepareStatement(
"SELECT created_at, versioning_state, acl FROM cluster_buckets WHERE name=?")) {
"SELECT created_at, versioning_state, acl, object_ownership, block_public_acls, " +
"ignore_public_acls, block_public_policy, restrict_public_buckets, bucket_policy " +
"FROM cluster_buckets WHERE name=?")) {
query.setString(1, name);
try (ResultSet result = query.executeQuery()) {
if (!result.next()) throw new StoreException(404, "NoSuchBucket", "Bucket not found");
return new Bucket(name, result.getLong(1), VersioningState.valueOf(result.getString(2)),
ObjectAttributes.decode(result.getBytes(3)));
ObjectAttributes.decode(result.getBytes(3)), ObjectOwnership.valueOf(result.getString(4)),
new PublicAccessBlock(result.getBoolean(5), result.getBoolean(6),
result.getBoolean(7), result.getBoolean(8)), result.getString(9));
}
} catch (SQLException error) { throw databaseError(error); }
}
@@ -91,9 +95,14 @@ final class ClusterStore implements ObjectStorage, MultipartStorage {
@Override public List<Bucket> buckets() throws IOException {
List<Bucket> result = new ArrayList<>();
try (Connection connection = connect(); var query = connection.createStatement();
ResultSet rows = query.executeQuery("SELECT name, created_at, versioning_state, acl FROM cluster_buckets ORDER BY name")) {
ResultSet rows = query.executeQuery("SELECT name, created_at, versioning_state, acl, " +
"object_ownership, block_public_acls, ignore_public_acls, block_public_policy, " +
"restrict_public_buckets, bucket_policy FROM cluster_buckets ORDER BY name")) {
while (rows.next()) result.add(new Bucket(rows.getString(1), rows.getLong(2),
VersioningState.valueOf(rows.getString(3)), ObjectAttributes.decode(rows.getBytes(4))));
VersioningState.valueOf(rows.getString(3)), ObjectAttributes.decode(rows.getBytes(4)),
ObjectOwnership.valueOf(rows.getString(5)),
new PublicAccessBlock(rows.getBoolean(6), rows.getBoolean(7),
rows.getBoolean(8), rows.getBoolean(9)), rows.getString(10)));
return result;
} catch (SQLException error) { throw databaseError(error); }
}
@@ -133,6 +142,38 @@ final class ClusterStore implements ObjectStorage, MultipartStorage {
} catch (SQLException error) { throw databaseError(error); }
}
@Override public void setBucketOwnership(String bucket, ObjectOwnership ownership) throws IOException {
updateBucketAccess(bucket, "object_ownership", ownership.name());
}
@Override public void setPublicAccessBlock(String bucket, PublicAccessBlock block) throws IOException {
try (Connection connection = connect(); PreparedStatement update = connection.prepareStatement(
"UPDATE cluster_buckets SET block_public_acls=?, ignore_public_acls=?, " +
"block_public_policy=?, restrict_public_buckets=? WHERE name=?")) {
update.setBoolean(1, block.blockPublicAcls());
update.setBoolean(2, block.ignorePublicAcls());
update.setBoolean(3, block.blockPublicPolicy());
update.setBoolean(4, block.restrictPublicBuckets());
update.setString(5, bucket);
if (update.executeUpdate() == 0)
throw new StoreException(404, "NoSuchBucket", "Bucket not found");
} catch (SQLException error) { throw databaseError(error); }
}
@Override public void setBucketPolicy(String bucket, String policy) throws IOException {
updateBucketAccess(bucket, "bucket_policy", policy);
}
private void updateBucketAccess(String bucket, String column, String value) throws IOException {
try (Connection connection = connect(); PreparedStatement update = connection.prepareStatement(
"UPDATE cluster_buckets SET " + column + "=? WHERE name=?")) {
update.setString(1, value);
update.setString(2, bucket);
if (update.executeUpdate() == 0)
throw new StoreException(404, "NoSuchBucket", "Bucket not found");
} catch (SQLException error) { throw databaseError(error); }
}
private static VersioningState versioningState(Connection connection, String bucket) throws SQLException {
try (PreparedStatement query = connection.prepareStatement(
"SELECT versioning_state FROM cluster_buckets WHERE name=? FOR UPDATE")) {
@@ -171,7 +212,9 @@ final class ClusterStore implements ObjectStorage, MultipartStorage {
throw new StoreException(400, "TooManyBuckets", "Bucket limit reached");
}
try (PreparedStatement insert = connection.prepareStatement(
"INSERT INTO cluster_buckets (name, created_at) VALUES (?, ?) ON CONFLICT DO NOTHING")) {
"INSERT INTO cluster_buckets (name, created_at, object_ownership, block_public_acls, " +
"ignore_public_acls, block_public_policy, restrict_public_buckets) " +
"VALUES (?, ?, 'BUCKET_OWNER_ENFORCED', true, true, true, true) ON CONFLICT DO NOTHING")) {
insert.setString(1, name);
insert.setLong(2, Instant.now().toEpochMilli());
if (insert.executeUpdate() == 0)
@@ -599,17 +642,20 @@ final class ClusterStore implements ObjectStorage, MultipartStorage {
throw new StoreException(413, "EntityTooLarge", "Object exceeds the configured size limit");
total += part.length();
MessageDigest partHash = digest("MD5");
java.util.zip.CRC32 partCrc32 = new java.util.zip.CRC32();
for (Segment segment : part.segments()) {
byte[] bytes = readableSegment(segment);
if (bytes == null) throw new StoreException(503, "SlowDown", "A part has no verified replica");
fullHash.update(bytes);
crc64.update(bytes, 0, bytes.length);
partHash.update(bytes);
partCrc32.update(bytes, 0, bytes.length);
selected.add(segment);
}
byte[] md5 = partHash.digest();
if (!part.etag().equals(HexFormat.of().formatHex(md5)))
throw new StoreException(503, "SlowDown", "A part failed integrity verification");
requested.verifyCrc32(partCrc32.getValue());
etagHash.update(md5);
}
long replaced = state == VersioningState.ENABLED ? 0 : nullVersionLength(connection, bucket, key);
+62 -7
View File
@@ -32,6 +32,7 @@ final class DiskStore implements ObjectStorage {
private static final int BUCKET_MAGIC = 0x4c534243;
private static final int BUCKET_MAGIC_V2 = 0x4c534244;
private static final int BUCKET_MAGIC_V3 = 0x4c534245;
private static final int BUCKET_MAGIC_V4 = 0x4c534246;
private static final int VERSION_MAGIC = 0x4c53564d;
private final Path root, objects, temporary, catalog, versions;
private final FileChannel lockChannel;
@@ -94,7 +95,8 @@ final class DiskStore implements ObjectStorage {
if (Files.exists(catalog)) {
try (DataInputStream input = new DataInputStream(Files.newInputStream(catalog))) {
int magic = input.readInt();
if (magic != BUCKET_MAGIC && magic != BUCKET_MAGIC_V2 && magic != BUCKET_MAGIC_V3)
if (magic != BUCKET_MAGIC && magic != BUCKET_MAGIC_V2 &&
magic != BUCKET_MAGIC_V3 && magic != BUCKET_MAGIC_V4)
throw new IOException("Invalid bucket catalog");
int count = input.readInt();
if (count < 0 || count > 1000) throw new IOException("Invalid bucket catalog");
@@ -102,20 +104,35 @@ final class DiskStore implements ObjectStorage {
String name = input.readUTF();
long created = input.readLong();
VersioningState state = VersioningState.NEVER;
if (magic == BUCKET_MAGIC_V2 || magic == BUCKET_MAGIC_V3) {
if (magic != BUCKET_MAGIC) {
int ordinal = input.readUnsignedByte();
if (ordinal >= VersioningState.values().length)
throw new IOException("Invalid bucket versioning state");
state = VersioningState.values()[ordinal];
}
Map<String, String> acl = Map.of();
if (magic == BUCKET_MAGIC_V3) {
if (magic == BUCKET_MAGIC_V3 || magic == BUCKET_MAGIC_V4) {
int size = input.readUnsignedShort();
if (size > ACL_AREA) throw new IOException("Invalid bucket ACL");
acl = ObjectAttributes.decode(input.readNBytes(size));
}
ObjectOwnership ownership = ObjectOwnership.OBJECT_WRITER;
PublicAccessBlock block = PublicAccessBlock.open();
String policy = null;
if (magic == BUCKET_MAGIC_V4) {
int ordinal = input.readUnsignedByte();
int flags = input.readUnsignedByte();
if (ordinal >= ObjectOwnership.values().length || (flags & ~15) != 0)
throw new IOException("Invalid bucket access settings");
ownership = ObjectOwnership.values()[ordinal];
block = new PublicAccessBlock((flags & 1) != 0, (flags & 2) != 0,
(flags & 4) != 0, (flags & 8) != 0);
policy = input.readUTF();
if (policy.isEmpty()) policy = null;
}
if (!validBucket(name) || created < 0 ||
buckets.put(name, new Bucket(name, created, state, acl)) != null)
buckets.put(name, new Bucket(name, created, state, acl,
ownership, block, policy)) != null)
throw new IOException("Invalid bucket catalog");
}
if (input.read() != -1) throw new IOException("Invalid bucket catalog");
@@ -212,7 +229,7 @@ final class DiskStore implements ObjectStorage {
Path pending = Files.createTempFile(temporary, "buckets-", ".part");
try {
try (DataOutputStream output = new DataOutputStream(Files.newOutputStream(pending))) {
output.writeInt(BUCKET_MAGIC_V3);
output.writeInt(BUCKET_MAGIC_V4);
output.writeInt(next.size());
for (Bucket entry : next.values()) {
output.writeUTF(entry.name());
@@ -221,6 +238,13 @@ final class DiskStore implements ObjectStorage {
byte[] acl = ObjectAttributes.encode(entry.acl(), ACL_AREA);
output.writeShort(acl.length);
output.write(acl);
output.writeByte(entry.ownership().ordinal());
PublicAccessBlock block = entry.publicAccessBlock();
output.writeByte((block.blockPublicAcls() ? 1 : 0) |
(block.ignorePublicAcls() ? 2 : 0) |
(block.blockPublicPolicy() ? 4 : 0) |
(block.restrictPublicBuckets() ? 8 : 0));
output.writeUTF(entry.policy() == null ? "" : entry.policy());
}
}
try (FileChannel channel = FileChannel.open(pending, StandardOpenOption.WRITE)) { channel.force(true); }
@@ -237,7 +261,8 @@ final class DiskStore implements ObjectStorage {
if (old.versioning() == VersioningState.NEVER && state == VersioningState.SUSPENDED)
throw new StoreException(400, "InvalidArgument", "Enable versioning before suspending it");
NavigableMap<String, Bucket> next = new TreeMap<>(buckets);
next.put(name, new Bucket(name, old.created(), state, old.acl()));
next.put(name, new Bucket(name, old.created(), state, old.acl(),
old.ownership(), old.publicAccessBlock(), old.policy()));
saveBuckets(next);
buckets.clear();
buckets.putAll(next);
@@ -246,7 +271,37 @@ final class DiskStore implements ObjectStorage {
@Override public synchronized void setBucketAcl(String name, Map<String, String> acl) throws IOException {
Bucket old = bucket(name);
NavigableMap<String, Bucket> next = new TreeMap<>(buckets);
next.put(name, new Bucket(name, old.created(), old.versioning(), Map.copyOf(acl)));
next.put(name, new Bucket(name, old.created(), old.versioning(), Map.copyOf(acl),
old.ownership(), old.publicAccessBlock(), old.policy()));
saveBuckets(next);
buckets.clear();
buckets.putAll(next);
}
@Override public synchronized void setBucketOwnership(String name, ObjectOwnership ownership)
throws IOException {
Bucket old = bucket(name);
updateBucket(new Bucket(name, old.created(), old.versioning(), old.acl(),
ownership, old.publicAccessBlock(), old.policy()));
}
@Override public synchronized void setPublicAccessBlock(String name, PublicAccessBlock block)
throws IOException {
Bucket old = bucket(name);
updateBucket(new Bucket(name, old.created(), old.versioning(), old.acl(),
old.ownership(), block, old.policy()));
}
@Override public synchronized void setBucketPolicy(String name, String policy)
throws IOException {
Bucket old = bucket(name);
updateBucket(new Bucket(name, old.created(), old.versioning(), old.acl(),
old.ownership(), old.publicAccessBlock(), policy));
}
private void updateBucket(Bucket bucket) throws IOException {
NavigableMap<String, Bucket> next = new TreeMap<>(buckets);
next.put(bucket.name(), bucket);
saveBuckets(next);
buckets.clear();
buckets.putAll(next);
@@ -0,0 +1,33 @@
package cloud.lunarsky.store;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
final class IdentityPolicies {
private IdentityPolicies() { }
static Map<String, BucketPolicy> fromEnvironment(Map<String, String> env, String owner,
Set<String> identities)
throws IOException {
String configured = env.get("S3_IDENTITY_POLICIES_DIR");
if (configured == null || configured.isBlank()) return Map.of();
Map<String, BucketPolicy> policies = new HashMap<>();
try (var files = Files.newDirectoryStream(Path.of(configured), "*.json")) {
for (Path path : files) {
String name = path.getFileName().toString();
String key = name.substring(0, name.length() - 5);
if (!identities.contains(key) || key.equals(owner) || Files.isSymbolicLink(path) ||
Files.size(path) > 20480 || policies.size() >= 256)
throw new IllegalArgumentException("Invalid identity policy file");
String json = Files.readString(path, StandardCharsets.UTF_8);
policies.put(key, BucketPolicy.parseIdentity(json));
}
}
return Map.copyOf(policies);
}
}
+20 -2
View File
@@ -2,6 +2,7 @@ package cloud.lunarsky.store;
import com.sun.net.httpserver.HttpExchange;
import java.io.IOException;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.time.ZoneOffset;
@@ -62,12 +63,29 @@ public final class Main {
Main(ObjectStorage store, MultipartStorage multipart, SigV4 authentication, String bucket,
ClientLimits clientLimits, int maxInFlight, String virtualHostSuffix,
BrowserCors cors, KeyScopes keyScopes, RequestMetrics metrics) throws IOException {
this(store, multipart, authentication, bucket, clientLimits, maxInFlight, virtualHostSuffix,
cors, keyScopes, metrics, Map.of());
}
Main(ObjectStorage store, MultipartStorage multipart, SigV4 authentication, String bucket,
ClientLimits clientLimits, int maxInFlight, String virtualHostSuffix,
BrowserCors cors, KeyScopes keyScopes, RequestMetrics metrics,
Map<String, BucketPolicy> identityPolicies) throws IOException {
this(store, multipart, authentication, bucket, clientLimits, maxInFlight, virtualHostSuffix,
cors, keyScopes, metrics, identityPolicies, null);
}
Main(ObjectStorage store, MultipartStorage multipart, SigV4 authentication, String bucket,
ClientLimits clientLimits, int maxInFlight, String virtualHostSuffix,
BrowserCors cors, KeyScopes keyScopes, RequestMetrics metrics,
Map<String, BucketPolicy> identityPolicies, URI publicEndpoint) throws IOException {
if (maxInFlight < 1 || maxInFlight > 1024)
throw new IllegalArgumentException("MAX_IN_FLIGHT_REQUESTS must be between 1 and 1024");
this.store = store;
this.authentication = authentication;
this.access = new S3Access(store, authentication.root());
MultipartHandler multipartHandler = new MultipartHandler(store, multipart, authentication);
this.access = new S3Access(store, authentication.root(), identityPolicies);
MultipartHandler multipartHandler = new MultipartHandler(store, multipart, authentication, access,
publicEndpoint);
this.bucketHandler = new BucketHandler(store, multipart, multipartHandler,
authentication, access, bucket);
this.objectHandler = new ObjectHandler(store, multipartHandler, authentication, access);
+36 -5
View File
@@ -1,7 +1,9 @@
package cloud.lunarsky.store;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpsExchange;
import java.io.IOException;
import java.net.URI;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
@@ -12,13 +14,18 @@ final class MultipartHandler {
private final ObjectStorage store;
private final MultipartStorage multipart;
private final SigV4 authentication;
private final S3Access access;
private final String owner;
private final URI publicEndpoint;
MultipartHandler(ObjectStorage store, MultipartStorage multipart, SigV4 authentication) {
MultipartHandler(ObjectStorage store, MultipartStorage multipart, SigV4 authentication,
S3Access access, URI publicEndpoint) {
this.store = store;
this.multipart = multipart;
this.authentication = authentication;
this.access = access;
this.owner = authentication.root();
this.publicEndpoint = publicEndpoint;
}
void handleMultipart(HttpExchange exchange, String method, Map<String, String> query,
@@ -36,15 +43,24 @@ final class MultipartHandler {
headers.containsKey("x-amz-acl") || headers.keySet().stream().anyMatch(
name -> name.toLowerCase(Locale.ROOT).startsWith("x-amz-grant-"))))
S3Request.unsupported("Multipart object attributes belong on initiation");
boolean initiate = query.containsKey("uploads");
if (!method.equals("PUT") && (headers.containsKey("content-md5") ||
headers.containsKey("x-amz-sdk-checksum-algorithm") ||
headers.keySet().stream().anyMatch(name -> name.toLowerCase(Locale.ROOT).startsWith("x-amz-checksum-"))))
headers.keySet().stream().anyMatch(name -> {
String lower = name.toLowerCase(Locale.ROOT);
return lower.startsWith("x-amz-checksum-") &&
!(initiate && lower.equals("x-amz-checksum-algorithm"));
})))
S3Request.unsupported("Multipart checksum header");
if (query.containsKey("uploads")) {
if (initiate) {
String algorithm = SigV4.single(headers, "x-amz-checksum-algorithm");
if (algorithm != null && !algorithm.equals("CRC32"))
S3Request.unsupported("Multipart checksum algorithm");
S3Request.requireEmptyBody(exchange, hash);
Map<String, String> acl = Acl.fromHeaders(headers, authentication.identities());
BucketSecurity.checkAcl(store.bucket(bucketName), headers, acl, false);
if (!acl.isEmpty() && !owner.equals(verified.principal()))
Acl.require(store.bucket(bucketName).acl(), verified.principal(), owner, Acl.WRITE_ACP);
access.requireBucket(bucketName, verified.principal(), Acl.WRITE_ACP);
String id = multipart.create(bucketName, key, S3Request.contentType(headers),
ObjectAttributes.userMetadata(headers),
ObjectAttributes.tagsHeader(SigV4.single(headers, "x-amz-tagging")), acl);
@@ -77,7 +93,8 @@ final class MultipartHandler {
var meta = multipart.complete(id, bucketName, key, parts);
if (meta.versionId() != null)
exchange.getResponseHeaders().set("x-amz-version-id", meta.versionId());
S3Xml.sendXml(exchange, 200, "<CompleteMultipartUploadResult><Bucket>" + S3Xml.xml(bucketName) +
S3Xml.sendXml(exchange, 200, "<CompleteMultipartUploadResult><Location>" +
S3Xml.xml(location(exchange, bucketName, key)) + "</Location><Bucket>" + S3Xml.xml(bucketName) +
"</Bucket><Key>" + S3Xml.xml(key) + "</Key><ETag>&quot;" + meta.etag() +
"&quot;</ETag></CompleteMultipartUploadResult>");
}
@@ -94,6 +111,20 @@ final class MultipartHandler {
}
}
private String location(HttpExchange exchange, String bucket, String key) {
String host = SigV4.single(exchange.getRequestHeaders(), "host");
if (host == null) throw new StoreException(400, "InvalidRequest", "Missing Host header");
String scheme = exchange instanceof HttpsExchange ? "https" : "http";
return objectLocation(publicEndpoint, host, scheme, exchange.getRequestURI().getRawPath(), bucket, key);
}
static String objectLocation(URI endpoint, String host, String scheme, String rawPath,
String bucket, String key) {
if (endpoint != null)
return endpoint + "/" + bucket + "/" + SigV4.encode(key, true);
return URI.create(scheme + "://" + host + rawPath).toASCIIString();
}
private void listParts(HttpExchange exchange, String id, String key, Map<String, String> query,
String bucketName) throws IOException {
int marker = S3Request.boundedNumber(query.get("part-number-marker"), 0, 10000, 0);
+10 -1
View File
@@ -6,7 +6,16 @@ import java.util.List;
import java.util.Map;
interface MultipartStorage {
record Part(int number, String etag) {}
record Part(int number, String etag, String checksumCrc32) {
Part(int number, String etag) { this(number, etag, null); }
void verifyCrc32(long value) {
if (checksumCrc32 == null) return;
byte[] bytes = java.nio.ByteBuffer.allocate(4).putInt((int) value).array();
if (!checksumCrc32.equals(java.util.Base64.getEncoder().encodeToString(bytes)))
throw new StoreException(400, "BadDigest", "Part CRC32 checksum mismatch");
}
}
record PartInfo(int number, long length, String etag, long modified) {}
record PartPage(List<PartInfo> parts, int nextMarker, boolean truncated) {}
record UploadInfo(String id, String key, long created) {}
@@ -155,16 +155,19 @@ final class MultipartStore implements MultipartStorage {
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)) {
byte[] buffer = new byte[65536];
int n;
while ((n = input.read(buffer)) != -1) {
sha.update(buffer, 0, n);
md5.update(buffer, 0, n);
crc32.update(buffer, 0, n);
}
}
if (!SigV4.hex(md5.digest()).equals(part.etag().replace("\"", "")))
throw new StoreException(400, "InvalidPart", "Part ETag mismatch");
part.verifyCrc32(crc32.getValue());
paths.add(file);
}
ObjectStorage.Metadata result;
+34 -19
View File
@@ -42,15 +42,20 @@ final class ObjectHandler {
try (var object = store.open(bucketName, key, versionId)) {
var metadata = object.metadata();
if (method.equals("GET")) {
Acl.require(metadata.acl(), principal, owner, Acl.READ_ACP);
access.requireObject(bucketName, key, metadata, principal, Acl.READ_ACP,
versionId == null ? "s3:GetObjectAcl" : "s3:GetObjectVersionAcl");
S3Request.requireEmptyBody(exchange, hash);
S3Xml.sendXml(exchange, 200, Acl.xml(metadata.acl(), owner));
S3Xml.sendXml(exchange, 200, Acl.xml(
store.bucket(bucketName).ownership() == ObjectStorage.ObjectOwnership.BUCKET_OWNER_ENFORCED
? Map.of() : metadata.acl(), owner));
} else {
if (!owner.equals(principal)) {
if (metadata.versionId() == null || metadata.versionId().equals("null"))
throw new StoreException(403, "AccessDenied", "Access denied");
Acl.require(metadata.acl(), principal, owner, Acl.WRITE_ACP);
}
if (store.bucket(bucketName).ownership() == ObjectStorage.ObjectOwnership.BUCKET_OWNER_ENFORCED)
throw new StoreException(400, "AccessControlListNotSupported", "ACLs are disabled for this bucket");
if (!owner.equals(principal) &&
(metadata.versionId() == null || metadata.versionId().equals("null")))
throw new StoreException(403, "AccessDenied", "Access denied");
access.requireObject(bucketName, key, metadata, principal, Acl.WRITE_ACP,
versionId == null ? "s3:PutObjectAcl" : "s3:PutObjectVersionAcl");
Map<String, String> acl;
if (exchange.getRequestHeaders().containsKey("x-amz-acl") ||
exchange.getRequestHeaders().keySet().stream().anyMatch(
@@ -63,6 +68,7 @@ final class ObjectHandler {
S3Request.verifyContentMd5(exchange.getRequestHeaders(), body);
acl = Acl.fromXml(body, owner, authentication.identities());
}
BucketSecurity.checkAcl(store.bucket(bucketName), exchange.getRequestHeaders(), acl, true);
store.setObjectAcl(bucketName, key, metadata.versionId(), acl);
exchange.sendResponseHeaders(200, -1);
}
@@ -84,12 +90,18 @@ final class ObjectHandler {
return;
}
boolean multipartRequest = S3Request.multipartRequest(method, query);
boolean copy = exchange.getRequestHeaders().containsKey("x-amz-copy-source");
boolean versionRequest = (method.equals("GET") || method.equals("HEAD") || method.equals("DELETE")) &&
query.containsKey("versionId") && (query.size() == 1 || query.size() == 2 && query.containsKey("x-id"));
if (versionRequest && query.containsKey("x-id") &&
!(method.equals("GET") ? "GetObject" : method.equals("HEAD") ? "HeadObject" : "DeleteObject")
.equals(query.get("x-id"))) S3Request.unsupported("Version query operation");
if (!multipartRequest && !versionRequest && !query.isEmpty() && !(query.size() == 1 &&
boolean directUploadQuery = method.equals("PUT") && !copy &&
(query.get("x-id") == null || query.get("x-id").equals("PutObject")) &&
query.keySet().stream().allMatch(name -> name.equals("x-id") ||
name.equals("x-amz-sdk-checksum-algorithm") ||
name.startsWith("x-amz-checksum-") && name.equals(name.toLowerCase(Locale.ROOT)));
if (!multipartRequest && !versionRequest && !query.isEmpty() && !directUploadQuery && !(query.size() == 1 &&
("PutObject".equals(query.get("x-id")) || "CopyObject".equals(query.get("x-id")) ||
"GetObject".equals(query.get("x-id")) ||
"HeadObject".equals(query.get("x-id")) || "DeleteObject".equals(query.get("x-id")))))
@@ -97,11 +109,11 @@ final class ObjectHandler {
S3Request.validateObjectHeaders(exchange.getRequestHeaders());
if (multipartRequest) {
if (method.equals("GET")) access.requireOwner(principal);
else access.requireBucket(bucketName, principal, Acl.WRITE);
else access.requireWrite(bucketName, key, principal,
method.equals("DELETE") ? "s3:AbortMultipartUpload" : "s3:PutObject");
multipartHandler.handleMultipart(exchange, method, query, key, verified, bucketName);
return;
}
boolean copy = exchange.getRequestHeaders().containsKey("x-amz-copy-source");
if (!method.equals("PUT") && (copy || exchange.getRequestHeaders().containsKey("content-md5") ||
exchange.getRequestHeaders().containsKey("x-amz-metadata-directive") ||
exchange.getRequestHeaders().containsKey("x-amz-tagging") ||
@@ -114,13 +126,14 @@ final class ObjectHandler {
if (!method.equals("PUT") || copy) S3Request.requireEmptyBody(exchange, hash);
switch (method) {
case "PUT" -> {
access.requireBucket(bucketName, principal, Acl.WRITE);
access.requireWrite(bucketName, key, principal, "s3:PutObject");
if (copy) copyObject(exchange, key, bucketName, principal);
else putObject(exchange, key, verified, bucketName);
else putObject(exchange, key, verified, bucketName, query);
}
case "GET", "HEAD" -> readObject(exchange, key, bucketName, query.get("versionId"), principal);
case "DELETE" -> {
access.requireBucket(bucketName, principal, Acl.WRITE);
access.requireWrite(bucketName, key, principal,
query.get("versionId") == null ? "s3:DeleteObject" : "s3:DeleteObjectVersion");
deleteObject(exchange, key, bucketName, query.get("versionId"));
}
default -> S3Request.unsupported("HTTP method");
@@ -128,7 +141,7 @@ final class ObjectHandler {
}
private void putObject(HttpExchange exchange, String key, SigV4.Verified verified,
String bucketName) throws IOException {
String bucketName, Map<String, String> query) throws IOException {
var headers = exchange.getRequestHeaders();
String length = SigV4.single(headers, "content-length"), condition = SigV4.single(headers, "if-none-match");
if (condition != null && !condition.equals("*")) S3Request.unsupported("Write condition");
@@ -138,7 +151,7 @@ final class ObjectHandler {
if (!verified.streaming() && headers.containsKey("content-encoding")) S3Request.unsupported("Encoded payload");
if (headers.containsKey("x-amz-metadata-directive")) S3Request.unsupported("Copy metadata directive");
if (headers.containsKey("x-amz-tagging-directive")) S3Request.unsupported("Copy tagging directive");
UploadChecksums checksums = UploadChecksums.from(headers);
UploadChecksums checksums = S3Request.uploadChecksums(headers, query);
AwsChunkedInputStream chunked = verified.streaming() ? S3Request.chunkedBody(exchange, verified) : null;
if (chunked != null) bytes = S3Request.decodedLength(headers);
else if (headers.containsKey("x-amz-decoded-content-length") || headers.containsKey("x-amz-trailer"))
@@ -147,6 +160,7 @@ final class ObjectHandler {
Map<String, String> metadata = ObjectAttributes.userMetadata(headers);
Map<String, String> tags = ObjectAttributes.tagsHeader(SigV4.single(headers, "x-amz-tagging"));
Map<String, String> acl = Acl.fromHeaders(headers, authentication.identities());
BucketSecurity.checkAcl(store.bucket(bucketName), headers, acl, false);
if (!acl.isEmpty() && !owner.equals(verified.principal()))
access.requireBucket(bucketName, verified.principal(), Acl.WRITE_ACP);
ObjectStorage.Metadata data = store.put(bucketName, key,
@@ -197,8 +211,6 @@ final class ObjectHandler {
String directive = SigV4.single(headers, "x-amz-metadata-directive");
if (directive != null && !directive.equals("COPY") && !directive.equals("REPLACE"))
throw new StoreException(400, "InvalidArgument", "Invalid metadata directive");
if (!"REPLACE".equals(directive) && headers.containsKey("content-type"))
S3Request.unsupported("Content-Type requires REPLACE metadata directive");
String tagDirective = SigV4.single(headers, "x-amz-tagging-directive");
if (tagDirective != null && !tagDirective.equals("COPY") && !tagDirective.equals("REPLACE"))
throw new StoreException(400, "InvalidArgument", "Invalid tagging directive");
@@ -208,7 +220,8 @@ final class ObjectHandler {
S3Request.unsupported("User metadata requires REPLACE metadata directive");
try (var object = store.open(sourceBucket, sourceKey, sourceVersion)) {
var sourceMetadata = object.metadata();
Acl.require(sourceMetadata.acl(), principal, owner, Acl.READ);
access.requireObject(sourceBucket, sourceKey, sourceMetadata, principal, Acl.READ,
sourceVersion == null ? "s3:GetObject" : "s3:GetObjectVersion");
if (sourceMetadata.versionId() != null)
exchange.getResponseHeaders().set("x-amz-copy-source-version-id", sourceMetadata.versionId());
String type = "REPLACE".equals(directive) ? S3Request.contentType(headers) : sourceMetadata.contentType();
@@ -217,6 +230,7 @@ final class ObjectHandler {
Map<String, String> tags = "REPLACE".equals(tagDirective)
? ObjectAttributes.tagsHeader(SigV4.single(headers, "x-amz-tagging")) : sourceMetadata.tags();
Map<String, String> acl = Acl.fromHeaders(headers, authentication.identities());
BucketSecurity.checkAcl(store.bucket(bucketName), headers, acl, false);
if (!acl.isEmpty() && !owner.equals(principal))
access.requireBucket(bucketName, principal, Acl.WRITE_ACP);
var copied = store.put(bucketName, key, object.stream(), sourceMetadata.length(),
@@ -283,7 +297,8 @@ final class ObjectHandler {
headers.containsKey("if-unmodified-since")) S3Request.unsupported("Conditional read");
try (var object = store.open(bucketName, key, versionId)) {
var meta = object.metadata();
Acl.require(meta.acl(), principal, owner, Acl.READ);
access.requireObject(bucketName, key, meta, principal, Acl.READ,
versionId == null ? "s3:GetObject" : "s3:GetObjectVersion");
String etag = "\"" + meta.etag() + "\"";
String noneMatch = SigV4.single(headers, "if-none-match");
if (noneMatch != null && (noneMatch.equals("*") ||
+19 -2
View File
@@ -8,9 +8,23 @@ import java.util.Map;
/** Storage operations shared by the local and cluster gateways. */
interface ObjectStorage extends AutoCloseable {
enum VersioningState { NEVER, ENABLED, SUSPENDED }
enum ObjectOwnership { BUCKET_OWNER_ENFORCED, BUCKET_OWNER_PREFERRED, OBJECT_WRITER }
record PublicAccessBlock(boolean blockPublicAcls, boolean ignorePublicAcls,
boolean blockPublicPolicy, boolean restrictPublicBuckets) {
static PublicAccessBlock secure() { return new PublicAccessBlock(true, true, true, true); }
static PublicAccessBlock open() { return new PublicAccessBlock(false, false, false, false); }
}
record Limits(long maxObjectBytes, long maxTotalBytes) {}
record Bucket(String name, long created, VersioningState versioning, Map<String, String> acl) {
Bucket(String name, long created) { this(name, created, VersioningState.NEVER, Map.of()); }
record Bucket(String name, long created, VersioningState versioning, Map<String, String> acl,
ObjectOwnership ownership, PublicAccessBlock publicAccessBlock, String policy) {
Bucket(String name, long created) {
this(name, created, VersioningState.NEVER, Map.of(),
ObjectOwnership.BUCKET_OWNER_ENFORCED, PublicAccessBlock.secure(), null);
}
Bucket(String name, long created, VersioningState versioning, Map<String, String> acl) {
this(name, created, versioning, acl,
ObjectOwnership.OBJECT_WRITER, PublicAccessBlock.open(), null);
}
Bucket(String name, long created, VersioningState versioning) {
this(name, created, versioning, Map.of());
}
@@ -114,6 +128,9 @@ interface ObjectStorage extends AutoCloseable {
void createBucket(String bucket) throws IOException;
void deleteBucket(String bucket) throws IOException;
void setBucketAcl(String bucket, Map<String, String> acl) throws IOException;
void setBucketOwnership(String bucket, ObjectOwnership ownership) throws IOException;
void setPublicAccessBlock(String bucket, PublicAccessBlock block) throws IOException;
void setBucketPolicy(String bucket, String policy) throws IOException;
void setObjectAcl(String bucket, String key, String versionId, Map<String, String> acl) throws IOException;
Limits limits();
default boolean ready() { return true; }
@@ -44,12 +44,17 @@ final class ObjectStoreServer {
multipart = new MultipartStore(disk);
} else throw new IllegalArgumentException("Invalid STORE_MODE");
Map<String, String> identities = identities(env, access, secret);
var app = new Main(store, multipart, new SigV4(identities,
var sessions = SessionCredentials.fromEnvironment(env, identities.keySet());
var allIdentities = new java.util.HashSet<>(identities.keySet());
allIdentities.addAll(sessions.keySet());
var app = new Main(store, multipart, new SigV4(identities, sessions,
access, region, Clock.systemUTC()), bucket, ClientLimits.fromEnvironment(env),
positiveInt(env, "MAX_IN_FLIGHT_REQUESTS", 16, 1024),
env.getOrDefault("S3_VIRTUAL_HOST_SUFFIX", ""), BrowserCors.fromEnvironment(env),
KeyScopes.fromEnvironment(env, access, identities.keySet()),
new RequestMetrics(env.get("METRICS_BEARER_TOKEN")));
KeyScopes.fromEnvironment(env, access, allIdentities),
new RequestMetrics(env.get("METRICS_BEARER_TOKEN")),
IdentityPolicies.fromEnvironment(env, access, allIdentities),
publicEndpoint(env));
int port = Integer.parseInt(env.getOrDefault("PORT", "9000"));
var server = HttpServer.create(mode.equals("cluster")
? new InetSocketAddress(env.getOrDefault("BIND_ADDRESS", "127.0.0.1"), port)
@@ -88,6 +93,22 @@ final class ObjectStoreServer {
}
return values;
}
static URI publicEndpoint(Map<String, String> env) {
String configured = env.get("S3_PUBLIC_ENDPOINT");
if (configured == null || configured.isBlank()) return null;
URI uri;
try { uri = URI.create(configured); }
catch (IllegalArgumentException error) {
throw new IllegalArgumentException("Invalid S3_PUBLIC_ENDPOINT", error);
}
if (!"http".equals(uri.getScheme()) && !"https".equals(uri.getScheme()) ||
uri.getHost() == null || uri.getUserInfo() != null || uri.getRawQuery() != null ||
uri.getRawFragment() != null ||
!(uri.getRawPath().isEmpty() || uri.getRawPath().equals("/")))
throw new IllegalArgumentException("S3_PUBLIC_ENDPOINT must be an HTTP(S) origin");
return URI.create(configured.endsWith("/") ? configured.substring(0, configured.length() - 1) : configured);
}
private static void printStartup(DiskStore store, MultipartStorage multipart,
String bucket, String region, int port) {
System.out.println(" *");
+49 -1
View File
@@ -1,14 +1,23 @@
package cloud.lunarsky.store;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
final class S3Access {
private final ObjectStorage store;
private final String owner;
private final java.util.Map<String, BucketPolicy> identityPolicies;
private final ConcurrentHashMap<String, CachedPolicy> policies = new ConcurrentHashMap<>();
private record CachedPolicy(String source, BucketPolicy parsed) { }
S3Access(ObjectStorage store, String owner) {
this(store, owner, java.util.Map.of());
}
S3Access(ObjectStorage store, String owner, java.util.Map<String, BucketPolicy> identityPolicies) {
this.store = store;
this.owner = owner;
this.identityPolicies = java.util.Map.copyOf(identityPolicies);
}
String owner() {
@@ -20,6 +29,45 @@ final class S3Access {
}
void requireBucket(String bucket, String principal, int permission) throws IOException {
Acl.require(store.bucket(bucket).acl(), principal, owner, permission);
var current = store.bucket(bucket);
String action = permission == Acl.READ ? "s3:ListBucket" :
permission == Acl.READ_ACP ? "s3:GetBucketAcl" :
permission == Acl.WRITE_ACP ? "s3:PutBucketAcl" : "s3:PutObject";
require(current, current.acl(), principal, permission, action, null);
}
void requireWrite(String bucket, String key, String principal, String action) throws IOException {
var current = store.bucket(bucket);
require(current, current.acl(), principal, Acl.WRITE, action, key);
}
void requireObject(String bucket, String key, ObjectStorage.Metadata metadata,
String principal, int permission, String action) throws IOException {
require(store.bucket(bucket), metadata.acl(), principal, permission, action, key);
}
private void require(ObjectStorage.Bucket bucket, java.util.Map<String, String> acl,
String principal, int permission, String action, String key) {
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);
if (decision < 0 || identityDecision < 0 ||
!BucketSecurity.allowsAcl(bucket, acl, principal, owner, permission) &&
identityDecision <= 0 &&
!(decision > 0 && (principal != null || !bucket.publicAccessBlock().restrictPublicBuckets() ||
!policy.publicAllow())))
throw new StoreException(403, "AccessDenied", "Access denied");
}
private BucketPolicy policy(ObjectStorage.Bucket bucket) {
String source = bucket.policy();
if (source == null) return BucketPolicy.empty();
CachedPolicy cached = policies.get(bucket.name());
if (cached != null && cached.source().equals(source)) return cached.parsed();
BucketPolicy parsed = BucketPolicy.parse(source, bucket.name());
policies.put(bucket.name(), new CachedPolicy(source, parsed));
return parsed;
}
}
+15
View File
@@ -1,6 +1,7 @@
package cloud.lunarsky.store;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.Headers;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
@@ -15,6 +16,7 @@ final class S3Request {
for (String name : headers.keySet()) {
String lower = name.toLowerCase(java.util.Locale.ROOT);
if (lower.startsWith("x-amz-") && !lower.startsWith("x-amz-meta-") && !java.util.Set.of("x-amz-date", "x-amz-content-sha256",
"x-amz-security-token",
"x-amz-sdk-checksum-algorithm", "x-amz-user-agent", "x-amz-copy-source",
"x-amz-metadata-directive", "x-amz-tagging", "x-amz-tagging-directive",
"x-amz-decoded-content-length", "x-amz-trailer", "x-amz-checksum-mode",
@@ -40,6 +42,19 @@ final class S3Request {
throw new StoreException(400, "BadDigest", "Content-MD5 mismatch");
} catch (java.security.NoSuchAlgorithmException error) { throw new IllegalStateException(error); }
}
static UploadChecksums uploadChecksums(Headers headers, Map<String, String> query) {
if (query.keySet().stream().noneMatch(name -> name.startsWith("x-amz-checksum-") ||
name.equals("x-amz-sdk-checksum-algorithm"))) return UploadChecksums.from(headers);
Headers combined = new Headers();
headers.forEach((name, values) -> combined.put(name, java.util.List.copyOf(values)));
query.forEach((name, value) -> {
if (!name.startsWith("x-amz-checksum-") && !name.equals("x-amz-sdk-checksum-algorithm")) return;
if (combined.containsKey(name))
throw new StoreException(400, "InvalidRequest", "Duplicate checksum in query and header");
combined.set(name, value);
});
return UploadChecksums.from(combined);
}
static String contentType(com.sun.net.httpserver.Headers headers) {
String value = SigV4.single(headers, "content-type");
if (value == null) return "application/octet-stream";
+10 -4
View File
@@ -77,17 +77,23 @@ final class S3Xml {
for (int i = 0; i < nodes.getLength(); i++) {
if (!(nodes.item(i) instanceof org.w3c.dom.Element element)) continue;
if (!element.getTagName().equals("Part")) throw new IllegalArgumentException();
String number = null, etag = null;
String number = null, etag = null, checksumCrc32 = null;
var fields = element.getChildNodes();
for (int j = 0; j < fields.getLength(); j++) {
if (!(fields.item(j) instanceof org.w3c.dom.Element field)) continue;
if (field.getTagName().equals("PartNumber")) number = field.getTextContent().trim();
else if (field.getTagName().equals("ETag")) etag = field.getTextContent().trim();
if (field.getTagName().equals("PartNumber") && number == null)
number = field.getTextContent().trim();
else if (field.getTagName().equals("ETag") && etag == null)
etag = field.getTextContent().trim();
else if (field.getTagName().equals("ChecksumCRC32") && checksumCrc32 == null)
checksumCrc32 = field.getTextContent().trim();
else throw new IllegalArgumentException();
}
if (number == null || etag == null || !etag.matches("\"?[0-9a-f]{32}\"?"))
throw new IllegalArgumentException();
parts.add(new MultipartStorage.Part(Integer.parseInt(number), etag));
if (checksumCrc32 != null && java.util.Base64.getDecoder().decode(checksumCrc32).length != 4)
throw new IllegalArgumentException();
parts.add(new MultipartStorage.Part(Integer.parseInt(number), etag, checksumCrc32));
if (parts.size() > 10000) throw new IllegalArgumentException();
}
return parts;
+15 -2
View File
@@ -21,7 +21,7 @@ final class SchemaMigrator {
result.next();
version = result.getInt(1);
}
if (version > 10) throw new IOException("Metadata schema is newer than this ObjectStore build");
if (version > 11) 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))");
@@ -98,6 +98,17 @@ final class SchemaMigrator {
statement.execute("ALTER TABLE cluster_uploads ADD COLUMN acl bytea");
statement.execute("INSERT INTO cluster_schema_migrations VALUES (10)");
}
if (version < 11) {
statement.execute("ALTER TABLE cluster_buckets ADD COLUMN object_ownership text NOT NULL " +
"DEFAULT 'OBJECT_WRITER' CHECK (object_ownership IN " +
"('BUCKET_OWNER_ENFORCED', 'BUCKET_OWNER_PREFERRED', 'OBJECT_WRITER'))");
statement.execute("ALTER TABLE cluster_buckets ADD COLUMN block_public_acls boolean NOT NULL DEFAULT false");
statement.execute("ALTER TABLE cluster_buckets ADD COLUMN ignore_public_acls boolean NOT NULL DEFAULT false");
statement.execute("ALTER TABLE cluster_buckets ADD COLUMN block_public_policy boolean NOT NULL DEFAULT false");
statement.execute("ALTER TABLE cluster_buckets ADD COLUMN restrict_public_buckets boolean NOT NULL DEFAULT false");
statement.execute("ALTER TABLE cluster_buckets ADD COLUMN bucket_policy text");
statement.execute("INSERT INTO cluster_schema_migrations VALUES (11)");
}
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 insert = connection.prepareStatement("INSERT INTO cluster_usage VALUES (?, 0) ON CONFLICT DO NOTHING")) {
@@ -105,7 +116,9 @@ final class SchemaMigrator {
insert.executeUpdate();
}
try (PreparedStatement insert = connection.prepareStatement(
"INSERT INTO cluster_buckets (name, created_at) VALUES (?, ?) ON CONFLICT DO NOTHING")) {
"INSERT INTO cluster_buckets (name, created_at, object_ownership, block_public_acls, " +
"ignore_public_acls, block_public_policy, restrict_public_buckets) " +
"VALUES (?, ?, 'BUCKET_OWNER_ENFORCED', true, true, true, true) ON CONFLICT DO NOTHING")) {
insert.setString(1, bucket);
insert.setLong(2, System.currentTimeMillis());
insert.executeUpdate();
@@ -0,0 +1,39 @@
package cloud.lunarsky.store;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;
final class SessionCredentials {
record Session(String secret, String token, Instant expires) { }
private SessionCredentials() { }
static Map<String, Session> fromEnvironment(Map<String, String> env, java.util.Set<String> permanent)
throws IOException {
String file = env.get("S3_SESSION_CREDENTIALS_FILE");
if (file == null || file.isBlank()) return Map.of();
var lines = Files.readAllLines(Path.of(file), StandardCharsets.UTF_8);
if (lines.size() > 256) throw new IllegalArgumentException("Too many session credentials");
Map<String, Session> sessions = new HashMap<>();
for (String line : lines) {
if (line.isBlank() || line.startsWith("#")) continue;
String[] fields = line.split("\\t", -1);
if (fields.length != 4 || !fields[0].matches("[A-Za-z0-9]{16,128}") ||
permanent.contains(fields[0]) || fields[1].length() < 32 ||
fields[2].length() < 32 || fields[2].length() > 2048 ||
fields[2].indexOf('\n') >= 0 || fields[2].indexOf('\r') >= 0)
throw new IllegalArgumentException("Invalid session credential entry");
Instant expires;
try { expires = Instant.ofEpochSecond(Long.parseLong(fields[3])); }
catch (RuntimeException error) { throw new IllegalArgumentException("Invalid session expiry", error); }
if (sessions.putIfAbsent(fields[0], new Session(fields[1], fields[2], expires)) != null)
throw new IllegalArgumentException("Duplicate session credential");
}
return Map.copyOf(sessions);
}
}
+38 -5
View File
@@ -30,6 +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> identities;
private final Map<String, SessionCredentials.Session> sessions;
private final String root;
private final String region;
private final Clock clock;
@@ -39,15 +40,27 @@ final class SigV4 {
}
SigV4(Map<String, String> identities, String root, String region, Clock clock) {
this(identities, Map.of(), root, region, clock);
}
SigV4(Map<String, String> identities, Map<String, SessionCredentials.Session> sessions,
String root, String region, Clock clock) {
this.identities = Map.copyOf(identities);
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))
throw new IllegalArgumentException("Session and permanent keys overlap");
this.root = root;
this.region = region;
this.clock = clock;
}
String root() { return root; }
Set<String> identities() { return identities.keySet(); }
Set<String> identities() {
var all = new java.util.HashSet<>(identities.keySet());
all.addAll(sessions.keySet());
return Set.copyOf(all);
}
String verify(String method, URI uri, Headers headers) {
return verifyRequest(method, uri, headers).payload();
@@ -57,6 +70,7 @@ final class SigV4 {
if (hasPresignedQuery(uri.getRawQuery())) return verifyPresigned(method, uri, headers);
Map<String, String> fields = authorizationFields(headers);
String[] credential = credentialScope(fields.get("Credential"));
validateSession(credential[0], single(headers, "x-amz-security-token"));
String date = signingDate(headers, credential[1]);
String payload = payloadHash(headers);
String signedHeaders = fields.get("SignedHeaders");
@@ -76,11 +90,19 @@ final class SigV4 {
if (headers.containsKey("authorization")) denied("Use one authentication method");
PresignedQuery query = presignedQuery(uri.getRawQuery());
Map<String, String> fields = query.fields();
if (!fields.keySet().equals(Set.of("X-Amz-Algorithm", "X-Amz-Credential", "X-Amz-Date",
"X-Amz-Expires", "X-Amz-SignedHeaders", "X-Amz-Signature")) ||
Set<String> expected = Set.of("X-Amz-Algorithm", "X-Amz-Credential", "X-Amz-Date",
"X-Amz-Expires", "X-Amz-SignedHeaders", "X-Amz-Signature");
Set<String> allowed = new java.util.HashSet<>(expected);
allowed.add("X-Amz-Security-Token");
allowed.add("X-Amz-Content-Sha256");
if (!fields.keySet().containsAll(expected) || !allowed.containsAll(fields.keySet()) ||
fields.containsKey("X-Amz-Content-Sha256") &&
!"UNSIGNED-PAYLOAD".equals(fields.get("X-Amz-Content-Sha256")) ||
!"AWS4-HMAC-SHA256".equals(fields.get("X-Amz-Algorithm")))
denied("Invalid presigned parameters");
String[] credential = credentialScope(fields.get("X-Amz-Credential"));
if (headers.containsKey("x-amz-security-token")) denied("Presigned session token must be in the query");
validateSession(credential[0], fields.get("X-Amz-Security-Token"));
String date = fields.get("X-Amz-Date");
validatePresignedTime(date, credential[1], fields.get("X-Amz-Expires"));
String signedHeaders = fields.get("X-Amz-SignedHeaders");
@@ -162,17 +184,29 @@ final class SigV4 {
private String[] credentialScope(String value) {
String[] credential = value.split("/", -1);
if (credential.length != 5 || !identities.containsKey(credential[0]) || !credential[2].equals(region)
if (credential.length != 5 || !(identities.containsKey(credential[0]) || 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);
if (secret == null && sessions.containsKey(accessKey)) secret = sessions.get(accessKey).secret();
if (secret == null) denied("Invalid credential scope");
return secret;
}
private void validateSession(String accessKey, String token) {
SessionCredentials.Session session = sessions.get(accessKey);
if (session == null) {
if (token != null) denied("Unexpected session token");
return;
}
if (token == null || !MessageDigest.isEqual(token.getBytes(StandardCharsets.UTF_8),
session.token().getBytes(StandardCharsets.UTF_8)) || !clock.instant().isBefore(session.expires()))
denied("Invalid or expired session token");
}
private String signingDate(Headers headers, String credentialDate) {
String date = single(headers, "x-amz-date");
if (date == null || !credentialDate.matches("[0-9]{8}") || !date.matches("[0-9]{8}T[0-9]{6}Z") || !date.startsWith(credentialDate)) denied("Invalid signing date");
@@ -190,7 +224,6 @@ final class SigV4 {
payload.equals("STREAMING-AWS4-HMAC-SHA256-PAYLOAD") ||
payload.equals("STREAMING-AWS4-HMAC-SHA256-PAYLOAD-TRAILER")))
throw new StoreException(400, "NotImplemented", "Unsupported SHA-256 payload mode");
if (headers.containsKey("x-amz-security-token")) denied("Temporary credentials are unsupported");
return payload;
}
+1 -1
View File
@@ -1,7 +1,7 @@
package cloud.lunarsky.store;
final class Version {
static final String VALUE = "0.0.9";
static final String VALUE = "0.1.0";
private Version() {}
}