gunk-dev/the-valley

authorization.go

sourcee2dd787b4f4fmain's published tip history
21.4 KiB
1package export
2
3import (
4 "bytes"
5 "crypto/ed25519"
6 "fmt"
7 "io"
8 "slices"
9 "sort"
10 "strings"
11 "time"
12
13 "the-valley/note"
14)
15
16const (
17 // AuthorizationType is the first line of every authorization's text.
18 AuthorizationType = "the-valley/web-authorization/v1"
19
20 // MaxAuthorization is the most bytes of a signed authorization a
21 // receiver reads, and a server reads of the stored one. Sign signs
22 // nothing larger.
23 MaxAuthorization = 256 << 10
24
25 // FallbackRoom is the room a publisher leaves under MaxAuthorization
26 // when it signs an authorization in full, so that a fallback narrowed
27 // from it (Narrow) fits with nothing more dropped. The fallback's
28 // records are some of that authorization's, under the same instance
29 // and destination. Only two of its records can be longer: its
30 // sequence, by at most 18 digits, and a basis record it may add, at
31 // most 26 bytes. The room is no guarantee: a receiver may hold an
32 // authorization signed without it. So a publisher measures every
33 // fallback, and restricts one over the limit further (Fit).
34 FallbackRoom = 64
35
36 // Anyone is the reader every visitor is, signed in or not.
37 Anyone = "anyone"
38)
39
40// Authorization is the signed statement of who may read which project at
41// one destination. The publisher's policy path alone writes it, with the
42// same key as content manifests, and the receiver stores the newest one it
43// admitted. A server serves a project only while the stored authorization
44// names it, by name and publication identity, with a reader the request
45// is. Content manifests carry nothing of it, so no content upload can
46// grant or restore access.
47//
48// Its text is the type line and then one record per line, each a keyword
49// and its fields separated by single spaces:
50//
51// the-valley/web-authorization/v1
52// instance valley-host
53// destination example.org
54// sequence 42
55// checked 2026-10-29T01:03:00Z
56// project app 9da6809f038df92138c131cd16bed76d
57// reader app anyone
58// binding lk-0123456789abcdef alice 3a6eb0790f39ac87c94f3856b2dd2c5d110e6811602261a9a923d3bb23adc8b7
59//
60// The sequence is the publisher's own counter, independent of any clock:
61// each authorization it signs has a sequence greater than every one before.
62// A receiver admits an authorization by its sequence alone, never by its
63// age. Checked is when the publisher last finished a policy check in full;
64// pages show it, and nothing decides access by it. A project has one or
65// more reader records.
66//
67// An authorization may carry a basis record, basis <sequence>, after the
68// checked record. It names the authorization the receiver must hold for
69// this one to be stored: the publisher writes it when a project keeps
70// access it could not check again, which it keeps only from the
71// authorization the receiver last said it stored. A receiver that holds
72// another refuses it as stale-basis, so access kept from a stale record
73// never reaches the edge.
74//
75// A binding record carries one active read link the host issued: its
76// credential ID, the principal it identifies and its verifier (Binding).
77// A credential with no binding is revoked. The authorization never
78// carries a link's secret.
79type Authorization struct {
80 Instance string
81 Destination string
82 Sequence int64
83 Checked time.Time
84 // Basis is the sequence of the authorization the receiver must hold,
85 // or 0 for none.
86 Basis int64
87 Projects []AuthorizedProject
88 // Bindings are the active read links, sorted by ID.
89 Bindings []Binding
90}
91
92// Binding is one active read link an authorization carries. ID is the
93// credential's ID, lk- and 16 lowercase hex digits. Principal is the one
94// registry principal it identifies, never anyone. Verifier is the
95// lowercase hex SHA-256 of the link's 32 secret bytes.
96type Binding struct {
97 ID string
98 Principal string
99 Verifier string
100}
101
102// MaxBindings is the most bindings an authorization carries, which keeps
103// it well inside MaxAuthorization.
104const MaxBindings = 1000
105
106// ValidLinkID reports whether s is a read link's credential ID: lk- and 16
107// lowercase hex digits.
108func ValidLinkID(s string) bool {
109 return len(s) == 19 && strings.HasPrefix(s, "lk-") && lowerHex(s[3:])
110}
111
112// ValidVerifier reports whether s is a link verifier: 64 lowercase hex
113// digits.
114func ValidVerifier(s string) bool {
115 return len(s) == 64 && lowerHex(s)
116}
117
118func lowerHex(s string) bool {
119 for _, c := range []byte(s) {
120 if !('0' <= c && c <= '9' || 'a' <= c && c <= 'f') {
121 return false
122 }
123 }
124 return s != ""
125}
126
127// AuthorizedProject is one project an authorization names: its name, its
128// publication identity, and its effective readers, sorted.
129type AuthorizedProject struct {
130 Name string
131 Identity string
132 Readers []string
133}
134
135// Text is the authorization's text: the type line, the instance,
136// destination, sequence and checked records, then each project's records
137// in name order, its readers sorted, then the bindings in ID order.
138func (a *Authorization) Text() []byte {
139 var b bytes.Buffer
140 fmt.Fprintf(&b, "%s\ninstance %s\ndestination %s\nsequence %d\nchecked %s\n",
141 AuthorizationType, a.Instance, a.Destination, a.Sequence, a.Checked.UTC().Format(time.RFC3339))
142 if a.Basis > 0 {
143 fmt.Fprintf(&b, "basis %d\n", a.Basis)
144 }
145 projects := append([]AuthorizedProject{}, a.Projects...)
146 sort.Slice(projects, func(i, j int) bool { return projects[i].Name < projects[j].Name })
147 for _, p := range projects {
148 fmt.Fprintf(&b, "project %s %s\n", p.Name, p.Identity)
149 readers := append([]string{}, p.Readers...)
150 sort.Strings(readers)
151 for _, r := range readers {
152 fmt.Fprintf(&b, "reader %s %s\n", p.Name, r)
153 }
154 }
155 bindings := append([]Binding{}, a.Bindings...)
156 sort.Slice(bindings, func(i, j int) bool { return bindings[i].ID < bindings[j].ID })
157 for _, l := range bindings {
158 fmt.Fprintf(&b, "binding %s %s %s\n", l.ID, l.Principal, l.Verifier)
159 }
160 return b.Bytes()
161}
162
163// Sign is the authorization signed as a note by the publisher's export
164// key, called name. It is checked against ParseAuthorization and its size
165// against MaxAuthorization first, so the publisher never signs what a
166// receiver would refuse to read. One too large is refused with
167// CodeTooLarge.
168func (a *Authorization) Sign(name string, key ed25519.PrivateKey) ([]byte, error) {
169 text := a.Text()
170 if _, err := ParseAuthorization(text); err != nil {
171 return nil, err
172 }
173 if n := note.SignedSize(text, name); n > MaxAuthorization {
174 return nil, refuse(CodeTooLarge, "authorization %d would be %d bytes signed, and a receiver reads at most %d", a.Sequence, n, MaxAuthorization)
175 }
176 return note.Sign(text, name, key)
177}
178
179// SignedSize is how many bytes Sign writes for the authorization signed by
180// the key called name.
181func (a *Authorization) SignedSize(name string) int {
182 return note.SignedSize(a.Text(), name)
183}
184
185// Narrow is the bounded fallback a publisher sends when cur is too large
186// to sign: prev, the last authorization the receiver acknowledged, less
187// every access cur does not give. It keeps each of prev's projects that
188// cur names under the same publication identity, with those of its
189// readers cur names for it, and each of prev's bindings that cur carries
190// unchanged. It takes cur's instance, destination, sequence, checked time
191// and basis. It adds nothing prev does not give, so it is never larger
192// than prev but for its sequence and basis records (FallbackRoom). A nil
193// prev gives an authorization that names no project and carries no
194// binding.
195func Narrow(prev, cur *Authorization) *Authorization {
196 n := &Authorization{Instance: cur.Instance, Destination: cur.Destination,
197 Sequence: cur.Sequence, Checked: cur.Checked, Basis: cur.Basis}
198 if prev == nil {
199 return n
200 }
201 for _, old := range prev.Projects {
202 now, ok := cur.Project(old.Name)
203 if !ok || now.Identity != old.Identity {
204 continue
205 }
206 kept := AuthorizedProject{Name: old.Name, Identity: old.Identity}
207 for _, r := range old.Readers {
208 if slices.Contains(now.Readers, r) {
209 kept.Readers = append(kept.Readers, r)
210 }
211 }
212 if len(kept.Readers) > 0 {
213 n.Projects = append(n.Projects, kept)
214 }
215 }
216 for _, b := range prev.Bindings {
217 if slices.Contains(cur.Bindings, b) {
218 n.Bindings = append(n.Bindings, b)
219 }
220 }
221 return n
222}
223
224// Fit is a restricted until it is at most limit bytes signed by the key
225// called name. A publisher sends it in place of a bounded fallback that is
226// itself over the limit. onBasis names the projects a keeps only on its
227// basis, as when their policy could not be read. Fit returns a when a
228// fits. Otherwise it drops access one step at a time, in this order, and
229// stops at the first step after which the authorization, measured, fits:
230//
231// 1. each project kept on the basis, whole, in name order;
232// 2. each reader of the other projects, one at a time: the reader that
233// sorts last, of the project with the most readers left, the first
234// by name of those with as many, so a project goes with its last
235// reader;
236// 3. each binding, in ID order.
237//
238// The basis record stays only while a project kept on it does. Every step
239// only removes access, so Fit allows nothing a does not. After the last
240// step it grants nothing: no project, no binding and no basis, a few
241// hundred bytes for any instance and destination name, which always fits
242// within MaxAuthorization.
243func Fit(a *Authorization, onBasis []string, name string, limit int) *Authorization {
244 if a.SignedSize(name) <= limit {
245 return a
246 }
247 // A cut is one step: a project, whole, when reader is empty; one
248 // reader of a project; or one binding, by its ID.
249 type cut struct{ project, reader, binding string }
250 projects := slices.Clone(a.Projects)
251 slices.SortFunc(projects, func(x, y AuthorizedProject) int { return strings.Compare(x.Name, y.Name) })
252 var cuts []cut
253 for _, p := range projects {
254 if slices.Contains(onBasis, p.Name) {
255 cuts = append(cuts, cut{project: p.Name})
256 }
257 }
258 // A project's reader at index i goes when the project has i+1 readers
259 // left, so the readers go in descending index; the projects are in
260 // name order, and the stable sort keeps them so among equal indexes.
261 type indexed struct {
262 cut
263 i int
264 }
265 var readers []indexed
266 for _, p := range projects {
267 if slices.Contains(onBasis, p.Name) {
268 continue
269 }
270 for i, r := range slices.Sorted(slices.Values(p.Readers)) {
271 readers = append(readers, indexed{cut{project: p.Name, reader: r}, i})
272 }
273 }
274 slices.SortStableFunc(readers, func(x, y indexed) int { return y.i - x.i })
275 for _, r := range readers {
276 cuts = append(cuts, r.cut)
277 }
278 bindings := slices.Clone(a.Bindings)
279 slices.SortFunc(bindings, func(x, y Binding) int { return strings.Compare(x.ID, y.ID) })
280 for _, b := range bindings {
281 cuts = append(cuts, cut{binding: b.ID})
282 }
283
284 // without is a less its first k cuts. Each cut only removes records,
285 // so its size falls as k grows, and the first k that fits is found
286 // by measuring a few of them.
287 without := func(k int) *Authorization {
288 gone := map[cut]bool{}
289 for _, c := range cuts[:k] {
290 gone[c] = true
291 }
292 n := &Authorization{Instance: a.Instance, Destination: a.Destination, Sequence: a.Sequence, Checked: a.Checked}
293 for _, p := range a.Projects {
294 if gone[cut{project: p.Name}] {
295 continue
296 }
297 kept := AuthorizedProject{Name: p.Name, Identity: p.Identity}
298 for _, r := range p.Readers {
299 if !gone[cut{project: p.Name, reader: r}] {
300 kept.Readers = append(kept.Readers, r)
301 }
302 }
303 if len(kept.Readers) == 0 {
304 continue
305 }
306 n.Projects = append(n.Projects, kept)
307 if slices.Contains(onBasis, p.Name) {
308 n.Basis = a.Basis
309 }
310 }
311 for _, b := range a.Bindings {
312 if !gone[cut{binding: b.ID}] {
313 n.Bindings = append(n.Bindings, b)
314 }
315 }
316 return n
317 }
318 k := sort.Search(len(cuts)+1, func(k int) bool { return without(k).SignedSize(name) <= limit })
319 return without(min(k, len(cuts)))
320}
321
322// Allows reports whether the authorization lets reader read the project
323// called name with the publication identity given.
324func (a *Authorization) Allows(reader, name, identity string) bool {
325 if a == nil {
326 return false
327 }
328 for _, p := range a.Projects {
329 if p.Name == name && p.Identity == identity {
330 for _, r := range p.Readers {
331 if r == reader {
332 return true
333 }
334 }
335 }
336 }
337 return false
338}
339
340// Names reports whether the authorization names the project called name
341// with the publication identity given, for any reader.
342func (a *Authorization) Names(name, identity string) bool {
343 p, ok := a.Project(name)
344 return ok && p.Identity == identity
345}
346
347// Project is the authorization's project called name.
348func (a *Authorization) Project(name string) (AuthorizedProject, bool) {
349 if a == nil {
350 return AuthorizedProject{}, false
351 }
352 for _, p := range a.Projects {
353 if p.Name == name {
354 return p, true
355 }
356 }
357 return AuthorizedProject{}, false
358}
359
360// AuthorizationAdmission is what a receiver admits an authorization
361// against: the pinned verifier keys, the instance and destination it is
362// configured with, and the sequence of the authorization it stores. It
363// holds no clock: an authorization is never refused for its age.
364type AuthorizationAdmission struct {
365 Verifiers []note.VerifierKey
366 Instance string
367 Destination string
368 HighWater int64
369}
370
371// VerifyAuthorization admits a signed authorization, in this order, each
372// step its own:
373//
374// 1. read at most MaxAuthorization bytes;
375// 2. open the note with the pinned verifier keys;
376// 3. require the type line, then read the records;
377// 4. require the configured instance and destination;
378// 5. require a sequence greater than the stored authorization's;
379// 6. require a basis, when it has one, equal to the stored
380// authorization's sequence.
381//
382// There is no step for its age or its checked time: a valid narrowing
383// above the stored sequence is admitted however old it is, and however far
384// the clocks disagree. Every refusal is an *Error.
385func VerifyAuthorization(r io.Reader, a AuthorizationAdmission) (*Authorization, error) {
386 signed, err := io.ReadAll(io.LimitReader(r, MaxAuthorization+1))
387 if err != nil {
388 return nil, refuse(CodeUnreadable, "the authorization could not be read: %v", err)
389 }
390 if len(signed) > MaxAuthorization {
391 return nil, refuse(CodeTooLarge, "an authorization is at most %d bytes", MaxAuthorization)
392 }
393 text, _, err := note.Open(signed, a.Verifiers)
394 if err != nil {
395 return nil, refuse(CodeBadSignature, "the authorization does not open under the pinned key: %v", err)
396 }
397 auth, err := ParseAuthorization(text)
398 if err != nil {
399 return nil, err
400 }
401 if auth.Instance != a.Instance {
402 return nil, refuse(CodeWrongInstance, "the authorization is from instance %s, and this receiver takes %s", auth.Instance, a.Instance)
403 }
404 if auth.Destination != a.Destination {
405 return nil, refuse(CodeWrongDestination, "the authorization is for %s, and this receiver is %s", auth.Destination, a.Destination)
406 }
407 if err := auth.admissible(a.HighWater); err != nil {
408 return nil, err
409 }
410 return auth, nil
411}
412
413// admissible is steps 5 and 6 of VerifyAuthorization against the stored
414// authorization's sequence, hw. Store.Authorize takes them again under its
415// lock.
416func (a *Authorization) admissible(hw int64) error {
417 if a.Sequence <= hw {
418 e := refuse(CodeReplayed, "the authorization's sequence %d is not greater than %d, the stored authorization's", a.Sequence, hw)
419 e.HighWater = hw
420 return e
421 }
422 if a.Basis > 0 && a.Basis != hw {
423 e := refuse(CodeStaleBasis, "the authorization keeps access from authorization %d, and this receiver holds %d", a.Basis, hw)
424 e.HighWater = hw
425 return e
426 }
427 return nil
428}
429
430// ReadStoredAuthorization reads an authorization a receiver stored: the
431// signed note it admitted. The receiver verified the signature before it
432// stored it, so this reads the text without verifying it again, and holds
433// it to ParseAuthorization.
434func ReadStoredAuthorization(signed []byte) (*Authorization, error) {
435 if len(signed) > MaxAuthorization {
436 return nil, fmt.Errorf("the stored authorization is larger than %d bytes", MaxAuthorization)
437 }
438 text, _, err := note.Split(signed)
439 if err != nil {
440 return nil, fmt.Errorf("the stored authorization is not a signed note: %w", err)
441 }
442 return ParseAuthorization(text)
443}
444
445// ParseAuthorization reads an authorization's text, step 3 of
446// VerifyAuthorization. The first line is exactly AuthorizationType. Each
447// record after it is a keyword and exactly its fields. The instance,
448// destination, sequence and checked records appear once each, a project at
449// most once, and every project has one or more readers, each named once.
450// A reader record names a project that has a project record. A binding
451// names each credential ID once, at most MaxBindings of them. Records may
452// come in any order; Text writes them in one.
453func ParseAuthorization(text []byte) (*Authorization, error) {
454 bad := func(format string, args ...any) error { return refuse(CodeBadManifest, format, args...) }
455 if len(text) == 0 || text[len(text)-1] != '\n' {
456 return nil, bad("an authorization's text ends with a newline")
457 }
458 lines := strings.Split(strings.TrimSuffix(string(text), "\n"), "\n")
459 if lines[0] != AuthorizationType {
460 return nil, bad("the authorization opens with %q, not %q", lines[0], AuthorizationType)
461 }
462 arity := map[string]int{"instance": 1, "destination": 1, "sequence": 1, "checked": 1, "basis": 1, "project": 2, "reader": 2, "binding": 3}
463 a := &Authorization{}
464 seen := map[string]bool{}
465 projects := map[string]*AuthorizedProject{}
466 readers := map[string]map[string]bool{}
467 bindings := map[string]bool{}
468 for i, line := range lines[1:] {
469 n := i + 2
470 fields := strings.Split(line, " ")
471 key, args := fields[0], fields[1:]
472 want, known := arity[key]
473 switch {
474 case !known:
475 return nil, bad("line %d is %q; no record opens with %q", n, line, key)
476 case len(args) != want:
477 return nil, bad("line %d is %q; a %s record has %d fields", n, line, key, want)
478 }
479 for _, f := range args {
480 if f == "" {
481 return nil, bad("line %d is %q; fields are separated by one space", n, line)
482 }
483 }
484 switch key {
485 case "instance", "destination", "sequence", "checked", "basis":
486 if seen[key] {
487 return nil, bad("line %d is a second %s record", n, key)
488 }
489 seen[key] = true
490 }
491 switch key {
492 case "instance", "destination":
493 if !ValidName(args[0]) {
494 return nil, bad("line %d names %s %q, which is not a name", n, key, args[0])
495 }
496 if key == "instance" {
497 a.Instance = args[0]
498 } else {
499 a.Destination = args[0]
500 }
501 case "sequence":
502 seq, ok := decimal(args[0])
503 if !ok || seq == 0 {
504 return nil, bad("line %d gives sequence %q; a sequence is a positive decimal", n, args[0])
505 }
506 a.Sequence = seq
507 case "basis":
508 basis, ok := decimal(args[0])
509 if !ok || basis == 0 {
510 return nil, bad("line %d gives basis %q; a basis is a positive decimal", n, args[0])
511 }
512 a.Basis = basis
513 case "checked":
514 at, err := time.Parse(time.RFC3339, args[0])
515 if err != nil || at.UTC().Format(time.RFC3339) != args[0] {
516 return nil, bad("line %d gives checked %q; it is a time in RFC 3339, in UTC, to the second", n, args[0])
517 }
518 a.Checked = at.UTC()
519 case "project":
520 name, id := args[0], args[1]
521 if !ValidName(name) {
522 return nil, bad("line %d names project %q, which is not a project name", n, name)
523 }
524 if projects[name] != nil {
525 return nil, bad("line %d is a second project record for %s", n, name)
526 }
527 if !ValidIdentity(id) {
528 return nil, bad("line %d gives %s identity %q, which is not 32 lowercase hex digits", n, name, id)
529 }
530 projects[name] = &AuthorizedProject{Name: name, Identity: id}
531 case "reader":
532 name, reader := args[0], args[1]
533 if !ValidName(name) || !ValidName(reader) {
534 return nil, bad("line %d is %q; a reader record names a project and a principal", n, line)
535 }
536 if readers[name][reader] {
537 return nil, bad("line %d names reader %s of %s a second time", n, reader, name)
538 }
539 if readers[name] == nil {
540 readers[name] = map[string]bool{}
541 }
542 readers[name][reader] = true
543 case "binding":
544 id, principal, verifier := args[0], args[1], args[2]
545 switch {
546 case !ValidLinkID(id):
547 return nil, bad("line %d gives credential ID %q, which is not lk- and 16 lowercase hex digits", n, id)
548 case !ValidName(principal) || principal == Anyone:
549 return nil, bad("line %d binds %s to %q, which is not a principal", n, id, principal)
550 case !ValidVerifier(verifier):
551 return nil, bad("line %d gives %s the verifier %q, which is not 64 lowercase hex digits", n, id, verifier)
552 case bindings[id]:
553 return nil, bad("line %d binds %s a second time", n, id)
554 case len(bindings) == MaxBindings:
555 return nil, bad("line %d is a binding past the most an authorization carries, %d", n, MaxBindings)
556 }
557 bindings[id] = true
558 a.Bindings = append(a.Bindings, Binding{ID: id, Principal: principal, Verifier: verifier})
559 }
560 }
561 for _, key := range []string{"instance", "destination", "sequence", "checked"} {
562 if !seen[key] {
563 return nil, bad("the authorization has no %s record", key)
564 }
565 }
566 if a.Basis >= a.Sequence {
567 return nil, bad("the authorization's basis %d is not less than its sequence %d", a.Basis, a.Sequence)
568 }
569 sort.Slice(a.Bindings, func(i, j int) bool { return a.Bindings[i].ID < a.Bindings[j].ID })
570 for name, rs := range readers {
571 p := projects[name]
572 if p == nil {
573 return nil, bad("the authorization has a reader of %s and no project record for it", name)
574 }
575 for r := range rs {
576 p.Readers = append(p.Readers, r)
577 }
578 sort.Strings(p.Readers)
579 }
580 var names []string
581 for name, p := range projects {
582 if len(p.Readers) == 0 {
583 return nil, bad("project %s has no reader record", name)
584 }
585 names = append(names, name)
586 }
587 sort.Strings(names)
588 for _, name := range names {
589 a.Projects = append(a.Projects, *projects[name])
590 }
591 return a, nil
592}