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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
const std = @import("std");
const hegel = @import("hegel");
const scopes = @import("zat").oauth.permissions;
const collections = [_][]const u8{ "app.example.post", "app.example.like", "app.example.profile" };
const actions = [_]scopes.RepoAction{ .create, .update, .delete };
const methods = [_][]const u8{ "app.example.getPost", "app.example.newPost", "app.example.deletePost" };
const audiences = [_][]const u8{
"did:web:api.example.com#svc_appview",
"did:web:api.example.com#svc_chat",
"did:web:localhost%3A8443#svc_chat",
};
const mime_types = [_][]const u8{ "image/png", "image/svg+xml", "video/mp4", "text/html", "imageevil/png" };
fn selected(mask: u8, i: usize) bool {
return mask & (@as(u8, 1) << @intCast(i)) != 0;
}
fn format(scope: *const scopes.Scope, a: std.mem.Allocator) ![]const u8 {
var out: std.Io.Writer.Allocating = .init(a);
errdefer out.deinit();
try scope.write(&out.writer);
return out.toOwnedSlice();
}
fn assertCanonical(a: std.mem.Allocator, scope: *const scopes.Scope, case: *hegel.TestCase) !*const scopes.Scope {
const wire = try format(scope, a);
case.note("canonical scope {s}", .{wire});
const reparsed = try scopes.parse(a, wire);
if (!std.mem.eql(u8, wire, try format(reparsed, a))) return case.fail("canonical scope encoding changed after parsing");
return reparsed;
}
fn repoRelation(_: void, case: *hegel.TestCase) !void {
var arena: std.heap.ArenaAllocator = .init(std.heap.page_allocator);
defer arena.deinit();
const a = arena.allocator();
const masks = [2]u8{ try case.int(u8, 1, 8), try case.int(u8, 1, 8) };
const action_masks = [2]u8{ try case.int(u8, 1, 7), try case.int(u8, 1, 7) };
case.note("repo selectors {any}, actions {any}", .{ masks, action_masks });
var permissions: [2]*const scopes.Permission = undefined;
for (masks, action_masks, &permissions) |mask, action_mask, *permission| {
var names: std.ArrayList([]const u8) = .empty;
for (collections, 0..) |_, i| {
const index = collections.len - 1 - i;
if (selected(mask, index)) try names.append(a, collections[index]);
}
var repo_actions: scopes.RepoActions = .empty;
for (actions, 0..) |action, i| {
if (selected(action_mask, i)) repo_actions.insert(action);
}
const scope = try scopes.init(a, .{ .repo = .{
.collections = if (mask == 8) .all else .{ .named = names.items },
.actions = repo_actions,
} });
permission.* = (try assertCanonical(a, scope, case)).value().permission;
}
for (collections, 0..) |collection, i| {
for (actions, 0..) |action, j| {
const requirement: scopes.Requirement = .{ .repo = .{ .collection = collection, .action = action } };
const expected_first = (masks[0] == 8 or selected(masks[0], i)) and selected(action_masks[0], j);
const expected_second = (masks[1] == 8 or selected(masks[1], i)) and selected(action_masks[1], j);
if (permissions[0].matches(requirement) != expected_first or
permissions[1].matches(requirement) != expected_second) return case.fail("repo grant diverged from collection/action relation");
}
}
case.event("repo relation checked");
}
fn rpcRelation(_: void, case: *hegel.TestCase) !void {
var arena: std.heap.ArenaAllocator = .init(std.heap.page_allocator);
defer arena.deinit();
const a = arena.allocator();
const audience = try case.int(usize, 0, audiences.len);
const mask = try case.int(u8, 1, @as(u8, if (audience == audiences.len) 7 else 8));
const audiences_wire = [_][]const u8{
"did:web:api.example.com%23svc_appview",
"did%3Aweb%3Aapi.example.com%23svc_chat",
"did:web:localhost%253A8443%23svc_chat",
"%2A",
};
var wire: std.Io.Writer.Allocating = .init(a);
try wire.writer.print("rpc?aud={s}", .{audiences_wire[audience]});
if (mask == 8) {
try wire.writer.writeAll("&lxm=%2A");
} else {
for (methods, 0..) |method, index| {
if (selected(mask, index)) try wire.writer.print("&lxm={s}", .{method});
}
}
case.note("rpc scope {s}", .{wire.written()});
const scope = try scopes.parse(a, wire.written());
const reparsed = try assertCanonical(a, scope, case);
const bare_dids = [_][]const u8{ "did:web:api.example.com", "did:plc:ewvi7nxzyoun6zhxrhs64oiz", "did:web:localhost%3A8443" };
const invalid = [_][]const u8{ "*", "did:key:123", "did:plc:short", "did:web:api.example.com#", "did:web:api.example.com#svc#other" };
const targets = audiences ++ bare_dids ++ invalid;
if (audience == audiences.len) case.event("wildcard checked against bare and malformed audiences");
if (audience < audiences.len) case.event("specific service checked against sibling and bare audiences");
for (methods, 0..) |method, i| {
for (targets, 0..) |target, j| {
const valid_target = j < audiences.len + bare_dids.len;
const expected = (mask == 8 or selected(mask, i)) and valid_target and
(audience == audiences.len or audience == j);
const requirement: scopes.Requirement = .{ .rpc = .{ .method = method, .audience = target } };
if (scope.value().permission.matches(requirement) != expected or
reparsed.value().permission.matches(requirement) != expected)
{
case.note("RPC method={s} audience={s} expected={}", .{ method, target, expected });
return case.fail("RPC audience/method relation changed");
}
}
}
if (audience == 2) case.event("nested DID escape checked");
case.event("rpc relation checked");
}
fn blobRelation(_: void, case: *hegel.TestCase) !void {
var arena: std.heap.ArenaAllocator = .init(std.heap.page_allocator);
defer arena.deinit();
const a = arena.allocator();
const mask = try case.int(u8, 1, 63);
const patterns = [_][]const u8{ "IMAGE/*", "image/png", "image/svg+xml", "video/mp4", "text/html", "*/*" };
var wire: std.Io.Writer.Allocating = .init(a);
try wire.writer.writeAll("blob");
var separator: u8 = '?';
for (patterns, 0..) |pattern, i| {
if (!selected(mask, i)) continue;
try wire.writer.print("{c}accept={s}", .{ separator, pattern });
separator = '&';
}
const scope = try scopes.parse(a, wire.written());
const reparsed = try assertCanonical(a, scope, case);
for (mime_types, 0..) |mime, i| {
const expected = selected(mask, 5) or (i < 2 and selected(mask, 0)) or (i < 4 and selected(mask, i + 1));
const requirement: scopes.Requirement = .{ .blob = mime };
if (scope.value().permission.matches(requirement) != expected or
reparsed.value().permission.matches(requirement) != expected) return case.fail("blob accept changed the media relation");
}
if (selected(mask, 0) and selected(mask, 1)) case.event("redundant allow checked");
case.event("blob relation checked");
}
fn accountIdentity(_: void, case: *hegel.TestCase) !void {
var arena: std.heap.ArenaAllocator = .init(std.heap.page_allocator);
defer arena.deinit();
const a = arena.allocator();
const attr = try case.int(usize, 0, 1);
const action = try case.int(usize, 0, 2);
const auth = [_][]const u8{ "email", "repo" };
const attrs = [_]scopes.AccountAttribute{ .email, .repo };
const suffixes = [_][]const u8{ "", "&action=read", "&action=manage" };
const account = try scopes.parse(a, try std.fmt.allocPrint(a, "account?attr={s}{s}", .{ auth[attr], suffixes[action] }));
const permission = (try assertCanonical(a, account, case)).value().permission;
for (attrs, 0..) |attribute, i| {
if (permission.matches(.{ .account = .{ .attribute = attribute, .action = .read } }) != (attr == i and i == 0) or
permission.matches(.{ .account = .{ .attribute = attribute, .action = .manage } }) != (attr == i and action == 2)) return case.fail("account action or attribute widened");
}
const all = try case.boolean();
const identity = try scopes.parse(a, if (all) "identity:*?" else "identity?attr=handle");
const ident = (try assertCanonical(a, identity, case)).value().permission;
if (!ident.matches(.{ .identity = .handle }) or ident.matches(.{ .identity = .all }) != all) return case.fail("identity selector widened");
if (action == 0) case.event("account default checked");
}
const Rejection = enum {
unknown_attenuator,
duplicate_singleton,
positional_and_named,
escaped_delimiter,
malformed_escape,
double_escape,
double_rpc_wildcard,
bare_scope_audience,
invalid_wildcard_companion,
};
const Mutation = struct { valid: []const u8, malformed: []const u8 };
fn malformedMutation(a: std.mem.Allocator, case: *hegel.TestCase, kind: Rejection) !Mutation {
const id = try case.int(u16, 0, 65535);
const collection = try std.fmt.allocPrint(a, "app.example.record{d}", .{id});
const alternate = try case.boolean();
const escaped_aud = "did:web:api.example.com%23svc";
return switch (kind) {
.unknown_attenuator => blk: {
const forms = [_][]const u8{
"repo:app.example.post?action=create",
"blob?accept=image/png",
"account:email?action=read",
"identity?attr=handle",
"rpc:app.example.getPost?aud=*",
"include:app.example.auth?aud=" ++ escaped_aud,
};
const valid = forms[try case.int(usize, 0, forms.len - 1)];
const field = if (alternate) "%66uture" else "future";
break :blk .{ .valid = valid, .malformed = try std.fmt.allocPrint(a, "{s}&{s}{d}=narrower", .{ valid, field, id }) };
},
.duplicate_singleton => blk: {
const fields = [_]struct { prefix: []const u8, key: []const u8, first: []const u8, second: []const u8 }{
.{ .prefix = "rpc:app.example.getPost", .key = "aud", .first = escaped_aud, .second = "*" },
.{ .prefix = "include:app.example.auth", .key = "aud", .first = escaped_aud, .second = "did:web:other.example.com%23svc" },
.{ .prefix = "account:email", .key = "action", .first = "read", .second = "manage" },
.{ .prefix = "identity", .key = "attr", .first = "handle", .second = "*" },
};
const field = fields[try case.int(usize, 0, fields.len - 1)];
const fallback = if (try case.boolean()) field.first else field.second;
const first = if (alternate) fallback else field.first;
const second = if (alternate) field.first else fallback;
const alias = try std.fmt.allocPrint(a, "%{X:0>2}{s}", .{ field.key[0], field.key[1..] });
const key = if (try case.boolean()) alias else field.key;
const valid = try std.fmt.allocPrint(a, "{s}?{s}={s}", .{ field.prefix, field.key, first });
break :blk .{ .valid = valid, .malformed = try std.fmt.allocPrint(a, "{s}&{s}={s}", .{ valid, key, second }) };
},
.positional_and_named => blk: {
const valid = try std.fmt.allocPrint(a, "repo:{s}?action=create", .{collection});
const key = if (alternate) "%63ollection" else "collection";
const selector = if (try case.boolean()) collection else "*";
break :blk .{ .valid = valid, .malformed = try std.fmt.allocPrint(a, "{s}&{s}={s}", .{ valid, key, selector }) };
},
.escaped_delimiter, .malformed_escape, .double_escape => blk: {
const prefix = try std.fmt.allocPrint(a, "repo?collection={s}&action=", .{collection});
const suffix = switch (kind) {
.escaped_delimiter => if (alternate) "create%26action%3Ddelete" else "create%26action=update",
.malformed_escape => bad: {
const escapes = [_][]const u8{ "%", "%6", "%+A", "%-0", "%G1", "%1G" };
break :bad escapes[try case.int(usize, 0, escapes.len - 1)];
},
.double_escape => if (alternate) "%2563reate" else "cre%2561te",
else => unreachable,
};
break :blk .{
.valid = try std.fmt.allocPrint(a, "{s}%63reate", .{prefix}),
.malformed = try std.fmt.allocPrint(a, "{s}{s}", .{ prefix, suffix }),
};
},
.double_rpc_wildcard => blk: {
const selector = if (alternate) "rpc:*?aud=" else "rpc?lxm=%2a&aud=";
const wildcard = if (try case.boolean()) "*" else "%2A";
break :blk .{
.valid = try std.fmt.allocPrint(a, "{s}{s}{d}", .{ selector, escaped_aud, id }),
.malformed = try std.fmt.allocPrint(a, "{s}{s}", .{ selector, wildcard }),
};
},
.bare_scope_audience => blk: {
const prefix = if (alternate) "rpc:app.example.getPost?aud=" else "include:app.example.auth?aud=";
const did = try std.fmt.allocPrint(a, "did:web:api{d}.example.com", .{id});
break :blk .{
.valid = try std.fmt.allocPrint(a, "{s}{s}%23svc", .{ prefix, did }),
.malformed = try std.fmt.allocPrint(a, "{s}{s}", .{ prefix, did }),
};
},
.invalid_wildcard_companion => blk: {
const wildcard = if (alternate) "*" else "%2a";
const key = if (try case.boolean()) "%63ollection" else "collection";
const prefix = try std.fmt.allocPrint(a, "repo?collection={s}&{s}=", .{ wildcard, key });
const bad = if (try case.boolean()) "app.example.partial%2A" else "invalid";
break :blk .{
.valid = try std.fmt.allocPrint(a, "{s}{s}", .{ prefix, collection }),
.malformed = try std.fmt.allocPrint(a, "{s}{s}", .{ prefix, bad }),
};
},
};
}
fn invalidScopes(_: void, case: *hegel.TestCase) !void {
var arena: std.heap.ArenaAllocator = .init(std.heap.page_allocator);
defer arena.deinit();
const allocator = arena.allocator();
const kinds = std.enums.values(Rejection);
const kind = kinds[try case.int(usize, 0, kinds.len - 1)];
const mutation = try malformedMutation(allocator, case, kind);
case.note("{s}: valid={s}, malformed={s}", .{ @tagName(kind), mutation.valid, mutation.malformed });
const valid = try scopes.parse(allocator, mutation.valid);
defer valid.deinit();
switch (kind) {
inline else => |family| case.event(@tagName(family)),
}
if (scopes.parse(allocator, mutation.malformed)) |scope| {
defer scope.deinit();
return case.fail("a malformed mutation of a valid scope was accepted");
} else |err| switch (err) {
error.InvalidScope => {},
else => return err,
}
}
fn wireAliases(_: void, case: *hegel.TestCase) !void {
var arena: std.heap.ArenaAllocator = .init(std.heap.page_allocator);
defer arena.deinit();
const a = arena.allocator();
const id = try case.int(u16, 0, 65535);
const mime = try std.fmt.allocPrint(a, "image/x{d}+json", .{id});
const mixed = try std.fmt.allocPrint(a, "IMAGE/X{d}+JSON", .{id});
const raw = try std.fmt.allocPrint(a, "blob?accept={s}", .{mixed});
const escaped = try std.fmt.allocPrint(a, "blob:image/x{d}%2bjson", .{id});
const duplicate = try std.fmt.allocPrint(a, "blob?accept={s}&accept={s}", .{ mixed, mime });
const expected = try std.fmt.allocPrint(a, "blob:image/x{d}%2Bjson", .{id});
for ([_][]const u8{ raw, escaped, duplicate }) |wire| {
const scope = try scopes.parse(a, wire);
if (!std.mem.eql(u8, expected, try format(scope, a))) return case.fail("wire aliases yielded different canonical bytes");
if (!scope.value().permission.matches(.{ .blob = mime })) return case.fail("wire alias lost the literal plus");
}
case.event("equivalent wire spellings checked");
}
fn arbitraryBytes(_: void, case: *hegel.TestCase) !void {
var buffer: [768]u8 = undefined;
const bytes = try case.bytes(&buffer, 0, buffer.len);
case.event("arbitrary bytes checked");
const a = std.heap.page_allocator;
if (scopes.parse(a, bytes)) |scope| {
defer scope.deinit();
var arena: std.heap.ArenaAllocator = .init(a);
defer arena.deinit();
_ = try assertCanonical(arena.allocator(), scope, case);
} else |err| switch (err) {
error.InvalidScope, error.UnsupportedScope => {},
error.OutOfMemory => return err,
}
}
pub fn main() !void {
try hegel.run(.{ .key = "permission-repo" }, {}, repoRelation);
try hegel.run(.{ .key = "permission-rpc" }, {}, rpcRelation);
try hegel.run(.{ .key = "permission-blob" }, {}, blobRelation);
try hegel.run(.{ .key = "permission-account-identity" }, {}, accountIdentity);
try hegel.run(.{ .key = "permission-rejection" }, {}, invalidScopes);
try hegel.run(.{ .key = "permission-wire-aliases" }, {}, wireAliases);
try hegel.run(.{ .key = "permission-arbitrary-bytes" }, {}, arbitraryBytes);
}