gunk-dev/the-valley

authorization.go

sourcefe48b06af1c9main's published tip history
15.3 KiB
1package export
2
3import (
4 "bytes"
5 "crypto/ed25519"
6 "fmt"
7 "io"
8 "sort"
9 "strings"
10 "time"
11
12 "the-valley/note"
13)
14
15const (
16 // AuthorizationType is the first line of every authorization's text.
17 AuthorizationType = "the-valley/web-authorization/v1"
18
19 // MaxAuthorization is the most bytes of a signed authorization a
20 // receiver reads, and a server reads of the stored one.
21 MaxAuthorization = 256 << 10
22
23 // Anyone is the reader every visitor is, signed in or not.
24 Anyone = "anyone"
25)
26
27// Authorization is the signed statement of who may read which project at
28// one destination. The publisher's policy path alone writes it, with the
29// same key as content manifests, and the receiver stores the newest one it
30// admitted. A server serves a project only while the stored authorization
31// names it, by name and publication identity, with a reader the request
32// is. Content manifests carry nothing of it, so no content upload can
33// grant or restore access.
34//
35// Its text is the type line and then one record per line, each a keyword
36// and its fields separated by single spaces:
37//
38// the-valley/web-authorization/v1
39// instance valley-host
40// destination example.org
41// sequence 42
42// checked 2026-10-29T01:03:00Z
43// project app 9da6809f038df92138c131cd16bed76d
44// reader app anyone
45// binding lk-0123456789abcdef alice 3a6eb0790f39ac87c94f3856b2dd2c5d110e6811602261a9a923d3bb23adc8b7
46//
47// The sequence is the publisher's own counter, independent of any clock:
48// each authorization it signs has a sequence greater than every one before.
49// A receiver admits an authorization by its sequence alone, never by its
50// age. Checked is when the publisher last finished a policy check in full;
51// pages show it, and nothing decides access by it. A project has one or
52// more reader records.
53//
54// An authorization may carry a basis record, basis <sequence>, after the
55// checked record. It names the authorization the receiver must hold for
56// this one to be stored: the publisher writes it when a project keeps
57// access it could not check again, which it keeps only from the
58// authorization the receiver last said it stored. A receiver that holds
59// another refuses it as stale-basis, so access kept from a stale record
60// never reaches the edge.
61//
62// A binding record carries one active read link the host issued: its
63// credential ID, the principal it identifies and its verifier (Binding).
64// A credential with no binding is revoked. The authorization never
65// carries a link's secret.
66type Authorization struct {
67 Instance string
68 Destination string
69 Sequence int64
70 Checked time.Time
71 // Basis is the sequence of the authorization the receiver must hold,
72 // or 0 for none.
73 Basis int64
74 Projects []AuthorizedProject
75 // Bindings are the active read links, sorted by ID.
76 Bindings []Binding
77}
78
79// Binding is one active read link an authorization carries. ID is the
80// credential's ID, lk- and 16 lowercase hex digits. Principal is the one
81// registry principal it identifies, never anyone. Verifier is the
82// lowercase hex SHA-256 of the link's 32 secret bytes.
83type Binding struct {
84 ID string
85 Principal string
86 Verifier string
87}
88
89// MaxBindings is the most bindings an authorization carries, which keeps
90// it well inside MaxAuthorization.
91const MaxBindings = 1000
92
93// ValidLinkID reports whether s is a read link's credential ID: lk- and 16
94// lowercase hex digits.
95func ValidLinkID(s string) bool {
96 return len(s) == 19 && strings.HasPrefix(s, "lk-") && lowerHex(s[3:])
97}
98
99// ValidVerifier reports whether s is a link verifier: 64 lowercase hex
100// digits.
101func ValidVerifier(s string) bool {
102 return len(s) == 64 && lowerHex(s)
103}
104
105func lowerHex(s string) bool {
106 for _, c := range []byte(s) {
107 if !('0' <= c && c <= '9' || 'a' <= c && c <= 'f') {
108 return false
109 }
110 }
111 return s != ""
112}
113
114// AuthorizedProject is one project an authorization names: its name, its
115// publication identity, and its effective readers, sorted.
116type AuthorizedProject struct {
117 Name string
118 Identity string
119 Readers []string
120}
121
122// Text is the authorization's text: the type line, the instance,
123// destination, sequence and checked records, then each project's records
124// in name order, its readers sorted, then the bindings in ID order.
125func (a *Authorization) Text() []byte {
126 var b bytes.Buffer
127 fmt.Fprintf(&b, "%s\ninstance %s\ndestination %s\nsequence %d\nchecked %s\n",
128 AuthorizationType, a.Instance, a.Destination, a.Sequence, a.Checked.UTC().Format(time.RFC3339))
129 if a.Basis > 0 {
130 fmt.Fprintf(&b, "basis %d\n", a.Basis)
131 }
132 projects := append([]AuthorizedProject{}, a.Projects...)
133 sort.Slice(projects, func(i, j int) bool { return projects[i].Name < projects[j].Name })
134 for _, p := range projects {
135 fmt.Fprintf(&b, "project %s %s\n", p.Name, p.Identity)
136 readers := append([]string{}, p.Readers...)
137 sort.Strings(readers)
138 for _, r := range readers {
139 fmt.Fprintf(&b, "reader %s %s\n", p.Name, r)
140 }
141 }
142 bindings := append([]Binding{}, a.Bindings...)
143 sort.Slice(bindings, func(i, j int) bool { return bindings[i].ID < bindings[j].ID })
144 for _, l := range bindings {
145 fmt.Fprintf(&b, "binding %s %s %s\n", l.ID, l.Principal, l.Verifier)
146 }
147 return b.Bytes()
148}
149
150// Sign is the authorization signed as a note by the publisher's export
151// key. It is checked against ParseAuthorization first, so the publisher
152// never signs what a receiver would refuse to read.
153func (a *Authorization) Sign(name string, key ed25519.PrivateKey) ([]byte, error) {
154 text := a.Text()
155 if _, err := ParseAuthorization(text); err != nil {
156 return nil, err
157 }
158 return note.Sign(text, name, key)
159}
160
161// Allows reports whether the authorization lets reader read the project
162// called name with the publication identity given.
163func (a *Authorization) Allows(reader, name, identity string) bool {
164 if a == nil {
165 return false
166 }
167 for _, p := range a.Projects {
168 if p.Name == name && p.Identity == identity {
169 for _, r := range p.Readers {
170 if r == reader {
171 return true
172 }
173 }
174 }
175 }
176 return false
177}
178
179// Names reports whether the authorization names the project called name
180// with the publication identity given, for any reader.
181func (a *Authorization) Names(name, identity string) bool {
182 p, ok := a.Project(name)
183 return ok && p.Identity == identity
184}
185
186// Project is the authorization's project called name.
187func (a *Authorization) Project(name string) (AuthorizedProject, bool) {
188 if a == nil {
189 return AuthorizedProject{}, false
190 }
191 for _, p := range a.Projects {
192 if p.Name == name {
193 return p, true
194 }
195 }
196 return AuthorizedProject{}, false
197}
198
199// AuthorizationAdmission is what a receiver admits an authorization
200// against: the pinned verifier keys, the instance and destination it is
201// configured with, and the sequence of the authorization it stores. It
202// holds no clock: an authorization is never refused for its age.
203type AuthorizationAdmission struct {
204 Verifiers []note.VerifierKey
205 Instance string
206 Destination string
207 HighWater int64
208}
209
210// VerifyAuthorization admits a signed authorization, in this order, each
211// step its own:
212//
213// 1. read at most MaxAuthorization bytes;
214// 2. open the note with the pinned verifier keys;
215// 3. require the type line, then read the records;
216// 4. require the configured instance and destination;
217// 5. require a sequence greater than the stored authorization's;
218// 6. require a basis, when it has one, equal to the stored
219// authorization's sequence.
220//
221// There is no step for its age or its checked time: a valid narrowing
222// above the stored sequence is admitted however old it is, and however far
223// the clocks disagree. Every refusal is an *Error.
224func VerifyAuthorization(r io.Reader, a AuthorizationAdmission) (*Authorization, error) {
225 signed, err := io.ReadAll(io.LimitReader(r, MaxAuthorization+1))
226 if err != nil {
227 return nil, refuse(CodeUnreadable, "the authorization could not be read: %v", err)
228 }
229 if len(signed) > MaxAuthorization {
230 return nil, refuse(CodeTooLarge, "an authorization is at most %d bytes", MaxAuthorization)
231 }
232 text, _, err := note.Open(signed, a.Verifiers)
233 if err != nil {
234 return nil, refuse(CodeBadSignature, "the authorization does not open under the pinned key: %v", err)
235 }
236 auth, err := ParseAuthorization(text)
237 if err != nil {
238 return nil, err
239 }
240 if auth.Instance != a.Instance {
241 return nil, refuse(CodeWrongInstance, "the authorization is from instance %s, and this receiver takes %s", auth.Instance, a.Instance)
242 }
243 if auth.Destination != a.Destination {
244 return nil, refuse(CodeWrongDestination, "the authorization is for %s, and this receiver is %s", auth.Destination, a.Destination)
245 }
246 if err := auth.admissible(a.HighWater); err != nil {
247 return nil, err
248 }
249 return auth, nil
250}
251
252// admissible is steps 5 and 6 of VerifyAuthorization against the stored
253// authorization's sequence, hw. Store.Authorize takes them again under its
254// lock.
255func (a *Authorization) admissible(hw int64) error {
256 if a.Sequence <= hw {
257 e := refuse(CodeReplayed, "the authorization's sequence %d is not greater than %d, the stored authorization's", a.Sequence, hw)
258 e.HighWater = hw
259 return e
260 }
261 if a.Basis > 0 && a.Basis != hw {
262 e := refuse(CodeStaleBasis, "the authorization keeps access from authorization %d, and this receiver holds %d", a.Basis, hw)
263 e.HighWater = hw
264 return e
265 }
266 return nil
267}
268
269// ReadStoredAuthorization reads an authorization a receiver stored: the
270// signed note it admitted. The receiver verified the signature before it
271// stored it, so this reads the text without verifying it again, and holds
272// it to ParseAuthorization.
273func ReadStoredAuthorization(signed []byte) (*Authorization, error) {
274 if len(signed) > MaxAuthorization {
275 return nil, fmt.Errorf("the stored authorization is larger than %d bytes", MaxAuthorization)
276 }
277 text, _, err := note.Split(signed)
278 if err != nil {
279 return nil, fmt.Errorf("the stored authorization is not a signed note: %w", err)
280 }
281 return ParseAuthorization(text)
282}
283
284// ParseAuthorization reads an authorization's text, step 3 of
285// VerifyAuthorization. The first line is exactly AuthorizationType. Each
286// record after it is a keyword and exactly its fields. The instance,
287// destination, sequence and checked records appear once each, a project at
288// most once, and every project has one or more readers, each named once.
289// A reader record names a project that has a project record. A binding
290// names each credential ID once, at most MaxBindings of them. Records may
291// come in any order; Text writes them in one.
292func ParseAuthorization(text []byte) (*Authorization, error) {
293 bad := func(format string, args ...any) error { return refuse(CodeBadManifest, format, args...) }
294 if len(text) == 0 || text[len(text)-1] != '\n' {
295 return nil, bad("an authorization's text ends with a newline")
296 }
297 lines := strings.Split(strings.TrimSuffix(string(text), "\n"), "\n")
298 if lines[0] != AuthorizationType {
299 return nil, bad("the authorization opens with %q, not %q", lines[0], AuthorizationType)
300 }
301 arity := map[string]int{"instance": 1, "destination": 1, "sequence": 1, "checked": 1, "basis": 1, "project": 2, "reader": 2, "binding": 3}
302 a := &Authorization{}
303 seen := map[string]bool{}
304 projects := map[string]*AuthorizedProject{}
305 readers := map[string]map[string]bool{}
306 bindings := map[string]bool{}
307 for i, line := range lines[1:] {
308 n := i + 2
309 fields := strings.Split(line, " ")
310 key, args := fields[0], fields[1:]
311 want, known := arity[key]
312 switch {
313 case !known:
314 return nil, bad("line %d is %q; no record opens with %q", n, line, key)
315 case len(args) != want:
316 return nil, bad("line %d is %q; a %s record has %d fields", n, line, key, want)
317 }
318 for _, f := range args {
319 if f == "" {
320 return nil, bad("line %d is %q; fields are separated by one space", n, line)
321 }
322 }
323 switch key {
324 case "instance", "destination", "sequence", "checked", "basis":
325 if seen[key] {
326 return nil, bad("line %d is a second %s record", n, key)
327 }
328 seen[key] = true
329 }
330 switch key {
331 case "instance", "destination":
332 if !ValidName(args[0]) {
333 return nil, bad("line %d names %s %q, which is not a name", n, key, args[0])
334 }
335 if key == "instance" {
336 a.Instance = args[0]
337 } else {
338 a.Destination = args[0]
339 }
340 case "sequence":
341 seq, ok := decimal(args[0])
342 if !ok || seq == 0 {
343 return nil, bad("line %d gives sequence %q; a sequence is a positive decimal", n, args[0])
344 }
345 a.Sequence = seq
346 case "basis":
347 basis, ok := decimal(args[0])
348 if !ok || basis == 0 {
349 return nil, bad("line %d gives basis %q; a basis is a positive decimal", n, args[0])
350 }
351 a.Basis = basis
352 case "checked":
353 at, err := time.Parse(time.RFC3339, args[0])
354 if err != nil || at.UTC().Format(time.RFC3339) != args[0] {
355 return nil, bad("line %d gives checked %q; it is a time in RFC 3339, in UTC, to the second", n, args[0])
356 }
357 a.Checked = at.UTC()
358 case "project":
359 name, id := args[0], args[1]
360 if !ValidName(name) {
361 return nil, bad("line %d names project %q, which is not a project name", n, name)
362 }
363 if projects[name] != nil {
364 return nil, bad("line %d is a second project record for %s", n, name)
365 }
366 if !ValidIdentity(id) {
367 return nil, bad("line %d gives %s identity %q, which is not 32 lowercase hex digits", n, name, id)
368 }
369 projects[name] = &AuthorizedProject{Name: name, Identity: id}
370 case "reader":
371 name, reader := args[0], args[1]
372 if !ValidName(name) || !ValidName(reader) {
373 return nil, bad("line %d is %q; a reader record names a project and a principal", n, line)
374 }
375 if readers[name][reader] {
376 return nil, bad("line %d names reader %s of %s a second time", n, reader, name)
377 }
378 if readers[name] == nil {
379 readers[name] = map[string]bool{}
380 }
381 readers[name][reader] = true
382 case "binding":
383 id, principal, verifier := args[0], args[1], args[2]
384 switch {
385 case !ValidLinkID(id):
386 return nil, bad("line %d gives credential ID %q, which is not lk- and 16 lowercase hex digits", n, id)
387 case !ValidName(principal) || principal == Anyone:
388 return nil, bad("line %d binds %s to %q, which is not a principal", n, id, principal)
389 case !ValidVerifier(verifier):
390 return nil, bad("line %d gives %s the verifier %q, which is not 64 lowercase hex digits", n, id, verifier)
391 case bindings[id]:
392 return nil, bad("line %d binds %s a second time", n, id)
393 case len(bindings) == MaxBindings:
394 return nil, bad("line %d is a binding past the most an authorization carries, %d", n, MaxBindings)
395 }
396 bindings[id] = true
397 a.Bindings = append(a.Bindings, Binding{ID: id, Principal: principal, Verifier: verifier})
398 }
399 }
400 for _, key := range []string{"instance", "destination", "sequence", "checked"} {
401 if !seen[key] {
402 return nil, bad("the authorization has no %s record", key)
403 }
404 }
405 if a.Basis >= a.Sequence {
406 return nil, bad("the authorization's basis %d is not less than its sequence %d", a.Basis, a.Sequence)
407 }
408 sort.Slice(a.Bindings, func(i, j int) bool { return a.Bindings[i].ID < a.Bindings[j].ID })
409 for name, rs := range readers {
410 p := projects[name]
411 if p == nil {
412 return nil, bad("the authorization has a reader of %s and no project record for it", name)
413 }
414 for r := range rs {
415 p.Readers = append(p.Readers, r)
416 }
417 sort.Strings(p.Readers)
418 }
419 var names []string
420 for name, p := range projects {
421 if len(p.Readers) == 0 {
422 return nil, bad("project %s has no reader record", name)
423 }
424 names = append(names, name)
425 }
426 sort.Strings(names)
427 for _, name := range names {
428 a.Projects = append(a.Projects, *projects[name])
429 }
430 return a, nil
431}