1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
//! HTTP message signatures (RFC 9421) as spaces use them: a credential holder
//! signs each request it authorizes with a space credential, and a repo host
//! MACs the commits and records it returns (see `mac.zig`).
//!
//! A signature is found by its `tag`, never its label: labels carry no meaning
//! (RFC 9421 §7.2.5). Mirrors `@atproto/space` `http-signature.ts`.
const std = @import("std");
const sf = @import("structured_fields.zig");
const jwt = @import("../crypto/jwt.zig");
const multicodec = @import("../crypto/multicodec.zig");
const Keypair = @import("../crypto/keypair.zig").Keypair;
pub const Error = error{ BadSpaceSignature, OutOfMemory };
/// A covered component, e.g. `"authorization"` or `"atproto-space-commit";sf`.
pub const Component = struct {
name: []const u8,
structured: bool = false,
};
/// What a verifier requires of the signature it checks (RFC 9421 §3.2.1).
pub const Requirements = struct {
tag: []const u8,
/// Exactly the components it must cover, in order.
components: []const Component,
/// Required when the signature names an `alg`.
alg: []const u8,
/// Required when the signature names a `keyid`.
key_id: []const u8,
};
pub const Found = struct {
/// The signature's parameters, serialized canonically: what its base covers.
signature_params: []const u8,
signature: []const u8,
};
pub const TaggedMember = struct { label: []const u8, params: sf.InnerList };
/// The inner-list members of a `Signature-Input` or `Accept-Signature`
/// dictionary whose `tag` parameter is `tag`.
pub fn membersWithTag(allocator: std.mem.Allocator, members: sf.Dictionary, tag: []const u8) ![]const TaggedMember {
var out: std.ArrayList(TaggedMember) = .empty;
for (members) |entry| switch (entry.member) {
.inner_list => |list| {
const value = sf.param(list.params, "tag") orelse continue;
if (value == .string and std.mem.eql(u8, value.string, tag)) try out.append(allocator, .{ .label = entry.key, .params = list });
},
.item => {},
};
return out.items;
}
/// Whether `list` covers exactly `components`, in order, with no others.
pub fn coversExactly(list: sf.InnerList, components: []const Component) bool {
if (list.items.len != components.len) return false;
for (list.items, components) |it, component| {
if (it.bare != .string or !std.mem.eql(u8, it.bare.string, component.name)) return false;
const expected_params: usize = if (component.structured) 1 else 0;
if (it.params.len != expected_params) return false;
if (component.structured) {
const flag = sf.param(it.params, "sf") orelse return false;
if (flag != .boolean or !flag.boolean) return false;
}
}
return true;
}
/// The serialized inner list `(components...);params...`.
pub fn formatSignatureParams(allocator: std.mem.Allocator, components: []const Component, params: []const sf.Parameter) error{OutOfMemory}![]u8 {
var items: std.ArrayList(sf.Item) = .empty;
defer items.deinit(allocator);
for (components) |component| try items.append(allocator, componentItem(component));
var out: std.Io.Writer.Allocating = .init(allocator);
errdefer out.deinit();
sf.writeInnerList(&out.writer, .{ .items = items.items, .params = params }) catch return error.OutOfMemory;
return out.toOwnedSlice();
}
fn componentItem(component: Component) sf.Item {
const structured = &[_]sf.Parameter{.{ .key = "sf", .value = .{ .boolean = true } }};
return .{ .bare = .{ .string = component.name }, .params = if (component.structured) structured else &.{} };
}
/// The signature base (RFC 9421 §2.5) over `components`, whose values are
/// given in order, under the serialized `signature_params`.
pub fn signatureBase(allocator: std.mem.Allocator, components: []const Component, values: []const []const u8, signature_params: []const u8) error{OutOfMemory}![]u8 {
std.debug.assert(components.len == values.len);
var out: std.Io.Writer.Allocating = .init(allocator);
errdefer out.deinit();
writeBase(&out.writer, components, values, signature_params) catch return error.OutOfMemory;
return out.toOwnedSlice();
}
fn writeBase(writer: *std.Io.Writer, components: []const Component, values: []const []const u8, signature_params: []const u8) !void {
for (components, values) |component, value| {
try sf.writeItem(writer, componentItem(component));
try writer.print(": {s}\n", .{std.mem.trim(u8, value, " \t")});
}
try writer.print("\"@signature-params\": {s}", .{signature_params});
}
/// Find the one signature tagged `required.tag` in a message's `Signature-Input`
/// and `Signature` fields, and check it meets `required`. Other parameters, like
/// `created`, are covered by the signature but not interpreted. Allocations
/// belong to `arena`.
pub fn findSignature(arena: std.mem.Allocator, input_field: ?[]const u8, signature_field: ?[]const u8, required: Requirements) Error!Found {
const inputs = sf.parseDictionary(arena, input_field orelse return error.BadSpaceSignature) catch return error.BadSpaceSignature;
const signatures = sf.parseDictionary(arena, signature_field orelse return error.BadSpaceSignature) catch return error.BadSpaceSignature;
const tagged = try membersWithTag(arena, inputs, required.tag);
if (tagged.len != 1) return error.BadSpaceSignature;
const signature = switch (sf.get(signatures, tagged[0].label) orelse return error.BadSpaceSignature) {
.item => |it| if (it.bare == .bytes and it.params.len == 0) it.bare.bytes else return error.BadSpaceSignature,
.inner_list => return error.BadSpaceSignature,
};
const params = tagged[0].params;
if (!coversExactly(params, required.components)) return error.BadSpaceSignature;
if (sf.param(params.params, "alg")) |alg| {
if (alg != .string or !std.mem.eql(u8, alg.string, required.alg)) return error.BadSpaceSignature;
}
if (sf.param(params.params, "keyid")) |key_id| {
if (key_id != .string or !std.mem.eql(u8, key_id.string, required.key_id)) return error.BadSpaceSignature;
}
var out: std.Io.Writer.Allocating = .init(arena);
sf.writeInnerList(&out.writer, params) catch return error.OutOfMemory;
return .{ .signature_params = out.written(), .signature = signature };
}
// ---- credential use ----
pub const credential_tag = "atproto-space-credential";
pub const credential_alg = "ecdsa-p256-sha256";
const credential_label = "sig";
/// A credential use covers the credential and its audience DID, in that order.
pub const credential_components = [_]Component{ .{ .name = "authorization" }, .{ .name = "atproto-space-audience" } };
/// The request headers a holder sends with a space credential.
pub const CredentialHeaders = struct {
signature_input: []const u8,
signature: []const u8,
};
/// Sign a request authorized by `authorization` for `audience` with the
/// holder's P-256 key. The caller also sends `authorization` and
/// `atproto-space-audience` as given.
pub fn signCredentialUse(allocator: std.mem.Allocator, keypair: *const Keypair, authorization: []const u8, audience: []const u8) !CredentialHeaders {
if (keypair.algorithm() != .ES256) return error.BadSpaceSignature;
const params = try formatSignatureParams(allocator, &credential_components, &.{.{ .key = "tag", .value = .{ .string = credential_tag } }});
defer allocator.free(params);
const base = try signatureBase(allocator, &credential_components, &.{ authorization, audience }, params);
defer allocator.free(base);
const signature = try keypair.sign(base);
const input = try std.fmt.allocPrint(allocator, credential_label ++ "={s}", .{params});
errdefer allocator.free(input);
var encoded: [88]u8 = undefined;
const sig = try std.fmt.allocPrint(allocator, credential_label ++ "=:{s}:", .{std.base64.standard.Encoder.encode(&encoded, &signature.bytes)});
return .{ .signature_input = input, .signature = sig };
}
/// Verify the signature on a request authorized by a space credential against
/// the P-256 did:key the credential is bound to (its `cnf.kid`). High-S
/// signatures are accepted.
pub fn verifyCredentialUse(
allocator: std.mem.Allocator,
authorization: []const u8,
audience: []const u8,
signature_input: ?[]const u8,
signature: ?[]const u8,
key_id: []const u8,
) Error!void {
if (authorization.len == 0 or audience.len == 0) return error.BadSpaceSignature;
var arena = std.heap.ArenaAllocator.init(allocator);
defer arena.deinit();
const a = arena.allocator();
const found = try findSignature(a, signature_input, signature, .{
.tag = credential_tag,
.components = &credential_components,
.alg = credential_alg,
.key_id = key_id,
});
const key = multicodec.parseDidKey(a, key_id) catch return error.BadSpaceSignature;
if (key.key_type != .p256 or found.signature.len != 64) return error.BadSpaceSignature;
const base = try signatureBase(a, &credential_components, &.{ authorization, audience }, found.signature_params);
jwt.verifyJose(.ES256, base, found.signature, key.raw) catch return error.BadSpaceSignature;
}
test "a credential use signs under any label and verifies by tag, accepting high-S" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
var key = try Keypair.fromSecretKey(.p256, @splat(0x42));
const kid = try key.did(a);
const auth = "Atproto-Space-Credential credential";
const audience = "did:plc:alice";
const signed = try signCredentialUse(a, &key, auth, audience);
try std.testing.expectEqualStrings("sig=(\"authorization\" \"atproto-space-audience\");tag=\"atproto-space-credential\"", signed.signature_input);
try verifyCredentialUse(a, auth, audience, signed.signature_input, signed.signature, kid);
const params = "(\"authorization\" \"atproto-space-audience\");tag=\"atproto-space-credential\";alg=\"ecdsa-p256-sha256\";created=123";
const base = try signatureBase(a, &credential_components, &.{ auth, audience }, params);
const low = try key.sign(base);
var high = low.bytes;
high[32..64].* = try std.crypto.ecc.P256.scalar.neg(low.bytes[32..64].*, .big);
for ([_][64]u8{ low.bytes, high }) |sig| {
var encoded: [88]u8 = undefined;
const b64 = std.base64.standard.Encoder.encode(&encoded, &sig);
const input = try std.fmt.allocPrint(a, "other=(\"date\"), whatever={s}", .{params});
const signature = try std.fmt.allocPrint(a, "other=:YWJj:, whatever=:{s}:", .{b64});
for (0..2) |_| try verifyCredentialUse(a, auth, audience, input, signature, kid);
try std.testing.expectError(error.BadSpaceSignature, verifyCredentialUse(a, "Atproto-Space-Credential changed", audience, input, signature, kid));
try std.testing.expectError(error.BadSpaceSignature, verifyCredentialUse(a, auth, "did:plc:bob", input, signature, kid));
try std.testing.expectError(error.BadSpaceSignature, verifyCredentialUse(a, auth, audience, input, "whatever=:YWJj:", kid));
// unpadded base64
const unpadded = try std.fmt.allocPrint(a, "whatever=:{s}:", .{std.mem.trimEnd(u8, b64, "=")});
try verifyCredentialUse(a, auth, audience, input, unpadded, kid);
}
}
test "a credential use must carry the tag, both components in order, and the bound key" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
var key = try Keypair.fromSecretKey(.p256, @splat(0x42));
const kid = try key.did(a);
var other = try Keypair.fromSecretKey(.p256, @splat(0x43));
const auth = "Atproto-Space-Credential credential";
const audience = "did:plc:alice";
const cases = [_][]const u8{
"(\"authorization\" \"atproto-space-audience\")",
"(\"authorization\" \"atproto-space-audience\");tag=\"atproto-space\"",
"(\"authorization\");tag=\"atproto-space-credential\"",
"(\"atproto-space-audience\" \"authorization\");tag=\"atproto-space-credential\"",
"(\"authorization\" \"atproto-space-audience\";sf);tag=\"atproto-space-credential\"",
"(\"authorization\" \"atproto-space-audience\");tag=\"atproto-space-credential\";alg=\"hmac-sha256\"",
try std.fmt.allocPrint(a, "(\"authorization\" \"atproto-space-audience\");tag=\"atproto-space-credential\";keyid=\"{s}\"", .{try other.did(a)}),
};
for (cases) |params| {
const base = try std.fmt.allocPrint(a, "\"authorization\": {s}\n\"atproto-space-audience\": {s}\n\"@signature-params\": {s}", .{ auth, audience, params });
const sig = try key.sign(base);
var encoded: [88]u8 = undefined;
const input = try std.fmt.allocPrint(a, "sig={s}", .{params});
const signature = try std.fmt.allocPrint(a, "sig=:{s}:", .{std.base64.standard.Encoder.encode(&encoded, &sig.bytes)});
try std.testing.expectError(error.BadSpaceSignature, verifyCredentialUse(a, auth, audience, input, signature, kid));
}
// two signatures with the credential tag
const signed = try signCredentialUse(a, &key, auth, audience);
const doubled_input = try std.fmt.allocPrint(a, "{s}, b={s}", .{ signed.signature_input, signed.signature_input["sig=".len..] });
const doubled_sig = try std.fmt.allocPrint(a, "{s}, b={s}", .{ signed.signature, signed.signature["sig=".len..] });
try std.testing.expectError(error.BadSpaceSignature, verifyCredentialUse(a, auth, audience, doubled_input, doubled_sig, kid));
// a key other than the bound one
try std.testing.expectError(error.BadSpaceSignature, verifyCredentialUse(a, auth, audience, signed.signature_input, signed.signature, try other.did(a)));
}