zat.dev/zds
atproto pds · mirror of https://tangled.org/zat.dev/zds
zds 0.25.1 Latest 2 packages, all images
0
0
//! The few S3 calls the blob mirror makes (PUT, GET and DELETE of one
//! object), signed with AWS Signature Version 4. Works with AWS and with
//! S3-compatible stores such as Cloudflare R2.
const std = @import("std");
const zat = @import("zat");
const log = @import("../core/log.zig");
const Sha256 = std.crypto.hash.sha2.Sha256;
const HmacSha256 = std.crypto.auth.hmac.sha2.HmacSha256;
pub const empty_payload_sha256 = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
pub const Config = struct {
/// scheme and authority only, such as `https://<account_id>.r2.cloudflarestorage.com`.
endpoint: []const u8,
bucket: []const u8,
region: []const u8,
access_key_id: []const u8,
secret_access_key: []const u8,
session_token: ?[]const u8 = null,
/// `endpoint/bucket/key` instead of `bucket.endpoint/key`.
path_style: bool = false,
};
pub const ConfigError = error{ InvalidEndpoint, InvalidBucket };
/// Checks what `objectUrl` relies on, so a bad setting fails at startup
/// rather than on the first upload.
pub fn validate(config: Config) ConfigError!void {
const authority = endpointAuthority(config.endpoint) orelse return error.InvalidEndpoint;
if (authority.len == 0) return error.InvalidEndpoint;
for (authority) |c| if (c == '/' or c == '?' or c == '#' or c == '@' or c <= 0x20) return error.InvalidEndpoint;
if (config.bucket.len < 3 or config.bucket.len > 63) return error.InvalidBucket;
for (config.bucket) |c| switch (c) {
'a'...'z', '0'...'9', '-', '.' => {},
else => return error.InvalidBucket,
};
}
fn endpointScheme(endpoint: []const u8) ?[]const u8 {
if (std.mem.startsWith(u8, endpoint, "https://")) return "https://";
if (std.mem.startsWith(u8, endpoint, "http://")) return "http://";
return null;
}
fn endpointAuthority(endpoint: []const u8) ?[]const u8 {
const scheme = endpointScheme(endpoint) orelse return null;
return std.mem.trimEnd(u8, endpoint[scheme.len..], "/");
}
pub const ObjectUrl = struct {
url: []const u8,
/// the Host header as std.http sends it: the URL's authority.
host: []const u8,
/// the URL's path, already percent-encoded, which SigV4 signs as is.
path: []const u8,
};
pub fn objectUrl(allocator: std.mem.Allocator, config: Config, key: []const u8) !ObjectUrl {
const scheme = endpointScheme(config.endpoint) orelse return error.InvalidEndpoint;
const authority = endpointAuthority(config.endpoint) orelse return error.InvalidEndpoint;
var out: std.Io.Writer.Allocating = .init(allocator);
errdefer out.deinit();
const w = &out.writer;
try w.writeAll(scheme);
const host_start = w.end;
if (!config.path_style) try w.print("{s}.", .{config.bucket});
try w.writeAll(authority);
const host_end = w.end;
if (config.path_style) try w.print("/{s}", .{config.bucket});
try w.writeByte('/');
try writeEncodedKey(w, key);
const url = try out.toOwnedSlice();
return .{ .url = url, .host = url[host_start..host_end], .path = url[host_end..] };
}
/// S3's URI encoding: every byte but the unreserved set is %XX, except the
/// `/` between key segments.
fn writeEncodedKey(w: *std.Io.Writer, key: []const u8) !void {
for (key) |c| switch (c) {
'A'...'Z', 'a'...'z', '0'...'9', '-', '_', '.', '~', '/' => try w.writeByte(c),
else => try w.print("%{X:0>2}", .{c}),
};
}
/// `YYYYMMDDTHHMMSSZ` for a Unix time.
pub fn amzDate(seconds: i64) [16]u8 {
const epoch: std.time.epoch.EpochSeconds = .{ .secs = @intCast(@max(seconds, 0)) };
const year_day = epoch.getEpochDay().calculateYearDay();
const month_day = year_day.calculateMonthDay();
const day_seconds = epoch.getDaySeconds();
var out: [16]u8 = undefined;
_ = std.fmt.bufPrint(&out, "{d:0>4}{d:0>2}{d:0>2}T{d:0>2}{d:0>2}{d:0>2}Z", .{
year_day.year,
month_day.month.numeric(),
@as(u8, month_day.day_index) + 1,
day_seconds.getHoursIntoDay(),
day_seconds.getMinutesIntoHour(),
day_seconds.getSecondsIntoMinute(),
}) catch unreachable;
return out;
}
pub const SignInput = struct {
method: []const u8,
host: []const u8,
path: []const u8,
payload_sha256: *const [64]u8,
amz_date: *const [16]u8,
};
/// The Authorization header value for a request that sends exactly the
/// headers SigV4 signs here: host, x-amz-content-sha256, x-amz-date and,
/// with a session token, x-amz-security-token. The request has no query.
pub fn authorization(allocator: std.mem.Allocator, config: Config, input: SignInput) ![]u8 {
const date = input.amz_date[0..8];
const signed_headers = if (config.session_token != null)
"host;x-amz-content-sha256;x-amz-date;x-amz-security-token"
else
"host;x-amz-content-sha256;x-amz-date";
var canonical: std.Io.Writer.Allocating = .init(allocator);
defer canonical.deinit();
const cw = &canonical.writer;
try cw.print("{s}\n{s}\n\nhost:{s}\nx-amz-content-sha256:{s}\nx-amz-date:{s}\n", .{
input.method, input.path, input.host, input.payload_sha256, input.amz_date,
});
if (config.session_token) |token| try cw.print("x-amz-security-token:{s}\n", .{token});
try cw.print("\n{s}\n{s}", .{ signed_headers, input.payload_sha256 });
var canonical_hash: [Sha256.digest_length]u8 = undefined;
Sha256.hash(canonical.written(), &canonical_hash, .{});
const string_to_sign = try std.fmt.allocPrint(allocator, "AWS4-HMAC-SHA256\n{s}\n{s}/{s}/s3/aws4_request\n{s}", .{
input.amz_date, date, config.region, &std.fmt.bytesToHex(canonical_hash, .lower),
});
defer allocator.free(string_to_sign);
const secret = try std.fmt.allocPrint(allocator, "AWS4{s}", .{config.secret_access_key});
defer {
std.crypto.secureZero(u8, secret);
allocator.free(secret);
}
var key: [HmacSha256.mac_length]u8 = undefined;
defer std.crypto.secureZero(u8, &key);
HmacSha256.create(&key, date, secret);
HmacSha256.create(&key, config.region, &key);
HmacSha256.create(&key, "s3", &key);
HmacSha256.create(&key, "aws4_request", &key);
var signature: [HmacSha256.mac_length]u8 = undefined;
HmacSha256.create(&signature, string_to_sign, &key);
return std.fmt.allocPrint(allocator, "AWS4-HMAC-SHA256 Credential={s}/{s}/{s}/s3/aws4_request, SignedHeaders={s}, Signature={s}", .{
config.access_key_id, date, config.region, signed_headers, &std.fmt.bytesToHex(signature, .lower),
});
}
pub const Error = error{ UnexpectedStatus, ObjectTooLarge };
pub const Client = struct {
config: Config,
transport: *zat.HttpTransport,
/// Unix seconds; tests pin it.
now: *const fn () i64,
const Prepared = struct {
object: ObjectUrl,
authorization: []u8,
amz_date: [16]u8,
headers: [3]std.http.Header,
header_count: usize,
fn extraHeaders(self: *const Prepared) []const std.http.Header {
return self.headers[0..self.header_count];
}
};
fn prepare(
self: Client,
allocator: std.mem.Allocator,
method: []const u8,
key: []const u8,
payload_sha256: *const [64]u8,
out: *Prepared,
) !void {
out.object = try objectUrl(allocator, self.config, key);
out.amz_date = amzDate(self.now());
out.authorization = try authorization(allocator, self.config, .{
.method = method,
.host = out.object.host,
.path = out.object.path,
.payload_sha256 = payload_sha256,
.amz_date = &out.amz_date,
});
out.headers[0] = .{ .name = "x-amz-content-sha256", .value = payload_sha256 };
out.headers[1] = .{ .name = "x-amz-date", .value = &out.amz_date };
out.header_count = 2;
if (self.config.session_token) |token| {
out.headers[2] = .{ .name = "x-amz-security-token", .value = token };
out.header_count = 3;
}
}
/// Uploads `data`, whose SHA-256 the caller already knows (a blob's CID
/// carries it). The store recomputes it and refuses a body that does not
/// match, so a corrupted local file never replaces a good copy.
pub fn put(self: Client, allocator: std.mem.Allocator, key: []const u8, data: []const u8, sha256_hex: *const [64]u8) !void {
var prepared: Prepared = undefined;
try self.prepare(allocator, "PUT", key, sha256_hex, &prepared);
// the head deadline also covers sending the body: allow 1 MB/s on top
// of the usual 10 seconds.
const head_deadline_ns = (10 + data.len / 1_000_000) * std.time.ns_per_s;
var result = try self.transport.fetch(.{
.url = prepared.object.url,
.method = .PUT,
.payload = data,
.content_type = "application/octet-stream",
.authorization = prepared.authorization,
.extra_headers = prepared.extraHeaders(),
.head_deadline_ns = head_deadline_ns,
.max_response_size = 64 * 1024,
.on_redirect = .refuse,
});
defer result.deinit(self.transport.allocator);
if (result.status != .ok) return unexpected("PUT", key, result.status);
}
/// Streams the object into `sink`. Returns null when there is no such
/// object, else its length; error.ObjectTooLarge past `max_bytes`.
pub fn get(self: Client, allocator: std.mem.Allocator, key: []const u8, sink: *std.Io.Writer, max_bytes: usize) !?u64 {
var prepared: Prepared = undefined;
try self.prepare(allocator, "GET", key, empty_payload_sha256, &prepared);
const response = try self.transport.open(.{
.url = prepared.object.url,
.authorization = prepared.authorization,
.accept_encoding = "identity",
.extra_headers = prepared.extraHeaders(),
.on_redirect = .refuse,
});
defer response.deinit();
switch (response.status) {
.ok => {},
.not_found => return null,
else => return unexpected("GET", key, response.status),
}
return response.stream(sink, .{ .max_bytes = max_bytes }) catch |err| switch (err) {
error.ResponseTooLarge => error.ObjectTooLarge,
else => err,
};
}
/// Deletes the object. S3 answers 204 whether or not it existed.
pub fn delete(self: Client, allocator: std.mem.Allocator, key: []const u8) !void {
var prepared: Prepared = undefined;
try self.prepare(allocator, "DELETE", key, empty_payload_sha256, &prepared);
var result = try self.transport.fetch(.{
.url = prepared.object.url,
.method = .DELETE,
.authorization = prepared.authorization,
.extra_headers = prepared.extraHeaders(),
.max_response_size = 64 * 1024,
.on_redirect = .refuse,
});
defer result.deinit(self.transport.allocator);
switch (result.status) {
.ok, .no_content, .not_found => {},
else => return unexpected("DELETE", key, result.status),
}
}
};
fn unexpected(method: []const u8, key: []const u8, status: std.http.Status) error{UnexpectedStatus} {
log.err("s3 {s} key={s} status={d}\n", .{ method, key, @backingInt(status) });
return error.UnexpectedStatus;
}
// The expected signatures below come from botocore's S3SigV4Auth (the R2
// one from a stdlib signer that reproduces botocore's for the same request
// on another host), so they check this signer against an independent one.
const test_config: Config = .{
.endpoint = "https://0123456789abcdef0123456789abcdef.r2.cloudflarestorage.com",
.bucket = "zds-blobs",
.region = "auto",
.access_key_id = "AKIAIOSFODNN7EXAMPLE",
.secret_access_key = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
};
test "virtual-hosted object URLs encode the key and sign its path" {
const a = std.testing.allocator;
const object = try objectUrl(a, test_config, "blobs/did:plc:abc123/bafkreihello");
defer a.free(object.url);
try std.testing.expectEqualStrings("https://zds-blobs.0123456789abcdef0123456789abcdef.r2.cloudflarestorage.com/blobs/did%3Aplc%3Aabc123/bafkreihello", object.url);
try std.testing.expectEqualStrings("zds-blobs.0123456789abcdef0123456789abcdef.r2.cloudflarestorage.com", object.host);
try std.testing.expectEqualStrings("/blobs/did%3Aplc%3Aabc123/bafkreihello", object.path);
const auth = try authorization(a, test_config, .{
.method = "PUT",
.host = object.host,
.path = object.path,
.payload_sha256 = "e997afd18e5f6be004fc193aed2c90291e68ab2c7599a62538c935b7fca6ab0f",
.amz_date = "20261123T064709Z",
});
defer a.free(auth);
try std.testing.expectEqualStrings(
"AWS4-HMAC-SHA256 Credential=AKIAIOSFODNN7EXAMPLE/20261123/auto/s3/aws4_request, SignedHeaders=host;x-amz-content-sha256;x-amz-date, Signature=22709d4aac5703eade315f3e71e4e0a4caaa24255248654fa01734c511758d83",
auth,
);
}
test "path-style object URLs keep the endpoint's port in the signed host" {
const a = std.testing.allocator;
var config = test_config;
config.endpoint = "http://127.0.0.1:2588/";
config.region = "us-east-1";
config.path_style = true;
const object = try objectUrl(a, config, "blobs/did:web:example.com/bafkreiabc");
defer a.free(object.url);
try std.testing.expectEqualStrings("http://127.0.0.1:2588/zds-blobs/blobs/did%3Aweb%3Aexample.com/bafkreiabc", object.url);
try std.testing.expectEqualStrings("127.0.0.1:2588", object.host);
const auth = try authorization(a, config, .{
.method = "GET",
.host = object.host,
.path = object.path,
.payload_sha256 = empty_payload_sha256,
.amz_date = "20261123T064709Z",
});
defer a.free(auth);
try std.testing.expectEqualStrings(
"AWS4-HMAC-SHA256 Credential=AKIAIOSFODNN7EXAMPLE/20261123/us-east-1/s3/aws4_request, SignedHeaders=host;x-amz-content-sha256;x-amz-date, Signature=82f1b90330f32b7625d3951fe3dd859c0dd762297a5a1cd56c74776c0debddb7",
auth,
);
}
test "a session token is signed as x-amz-security-token" {
const a = std.testing.allocator;
const config: Config = .{
.endpoint = "https://s3.us-east-1.amazonaws.com",
.bucket = "zds-blobs",
.region = "us-east-1",
.access_key_id = "AKID",
.secret_access_key = "secret",
.session_token = "sessiontoken",
.path_style = true,
};
const object = try objectUrl(a, config, "blobs/did:plc:x/bafkreiq");
defer a.free(object.url);
const auth = try authorization(a, config, .{
.method = "DELETE",
.host = object.host,
.path = object.path,
.payload_sha256 = empty_payload_sha256,
.amz_date = "20261123T064709Z",
});
defer a.free(auth);
try std.testing.expectEqualStrings(
"AWS4-HMAC-SHA256 Credential=AKID/20261123/us-east-1/s3/aws4_request, SignedHeaders=host;x-amz-content-sha256;x-amz-date;x-amz-security-token, Signature=9ac12430ccdea3fd75de59756faf51e66c1a9cb34b73655396371bffb7e96eaf",
auth,
);
}
test "amz dates are UTC and zero-padded" {
try std.testing.expectEqualStrings("20261123T064709Z", &amzDate(1795416429));
try std.testing.expectEqualStrings("19700101T000000Z", &amzDate(0));
}
test "endpoints and buckets are checked before use" {
var config = test_config;
try validate(config);
config.endpoint = "0123456789abcdef0123456789abcdef.r2.cloudflarestorage.com";
try std.testing.expectError(error.InvalidEndpoint, validate(config));
config.endpoint = "https://0123456789abcdef0123456789abcdef.r2.cloudflarestorage.com/some/path";
try std.testing.expectError(error.InvalidEndpoint, validate(config));
config.endpoint = "https://0123456789abcdef0123456789abcdef.r2.cloudflarestorage.com";
config.bucket = "Has_Upper";
try std.testing.expectError(error.InvalidBucket, validate(config));
}