gunk-dev/the-valley

authorization.go

source53bd156eeb1bmain's published tip history
12.6 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//
46// The sequence is the publisher's own counter, independent of any clock:
47// each authorization it signs has a sequence greater than every one before.
48// A receiver admits an authorization by its sequence alone, never by its
49// age. Checked is when the publisher last finished a policy check in full;
50// pages show it, and nothing decides access by it. A project has one or
51// more reader records.
52//
53// An authorization may carry a basis record, basis <sequence>, after the
54// checked record. It names the authorization the receiver must hold for
55// this one to be stored: the publisher writes it when a project keeps
56// access it could not check again, which it keeps only from the
57// authorization the receiver last said it stored. A receiver that holds
58// another refuses it as stale-basis, so access kept from a stale record
59// never reaches the edge.
60type Authorization struct {
61 Instance string
62 Destination string
63 Sequence int64
64 Checked time.Time
65 // Basis is the sequence of the authorization the receiver must hold,
66 // or 0 for none.
67 Basis int64
68 Projects []AuthorizedProject
69}
70
71// AuthorizedProject is one project an authorization names: its name, its
72// publication identity, and its effective readers, sorted.
73type AuthorizedProject struct {
74 Name string
75 Identity string
76 Readers []string
77}
78
79// Text is the authorization's text: the type line, the instance,
80// destination, sequence and checked records, then each project's records
81// in name order, its readers sorted.
82func (a *Authorization) Text() []byte {
83 var b bytes.Buffer
84 fmt.Fprintf(&b, "%s\ninstance %s\ndestination %s\nsequence %d\nchecked %s\n",
85 AuthorizationType, a.Instance, a.Destination, a.Sequence, a.Checked.UTC().Format(time.RFC3339))
86 if a.Basis > 0 {
87 fmt.Fprintf(&b, "basis %d\n", a.Basis)
88 }
89 projects := append([]AuthorizedProject{}, a.Projects...)
90 sort.Slice(projects, func(i, j int) bool { return projects[i].Name < projects[j].Name })
91 for _, p := range projects {
92 fmt.Fprintf(&b, "project %s %s\n", p.Name, p.Identity)
93 readers := append([]string{}, p.Readers...)
94 sort.Strings(readers)
95 for _, r := range readers {
96 fmt.Fprintf(&b, "reader %s %s\n", p.Name, r)
97 }
98 }
99 return b.Bytes()
100}
101
102// Sign is the authorization signed as a note by the publisher's export
103// key. It is checked against ParseAuthorization first, so the publisher
104// never signs what a receiver would refuse to read.
105func (a *Authorization) Sign(name string, key ed25519.PrivateKey) ([]byte, error) {
106 text := a.Text()
107 if _, err := ParseAuthorization(text); err != nil {
108 return nil, err
109 }
110 return note.Sign(text, name, key)
111}
112
113// Allows reports whether the authorization lets reader read the project
114// called name with the publication identity given.
115func (a *Authorization) Allows(reader, name, identity string) bool {
116 if a == nil {
117 return false
118 }
119 for _, p := range a.Projects {
120 if p.Name == name && p.Identity == identity {
121 for _, r := range p.Readers {
122 if r == reader {
123 return true
124 }
125 }
126 }
127 }
128 return false
129}
130
131// Names reports whether the authorization names the project called name
132// with the publication identity given, for any reader.
133func (a *Authorization) Names(name, identity string) bool {
134 p, ok := a.Project(name)
135 return ok && p.Identity == identity
136}
137
138// Project is the authorization's project called name.
139func (a *Authorization) Project(name string) (AuthorizedProject, bool) {
140 if a == nil {
141 return AuthorizedProject{}, false
142 }
143 for _, p := range a.Projects {
144 if p.Name == name {
145 return p, true
146 }
147 }
148 return AuthorizedProject{}, false
149}
150
151// AuthorizationAdmission is what a receiver admits an authorization
152// against: the pinned verifier keys, the instance and destination it is
153// configured with, and the sequence of the authorization it stores. It
154// holds no clock: an authorization is never refused for its age.
155type AuthorizationAdmission struct {
156 Verifiers []note.VerifierKey
157 Instance string
158 Destination string
159 HighWater int64
160}
161
162// VerifyAuthorization admits a signed authorization, in this order, each
163// step its own:
164//
165// 1. read at most MaxAuthorization bytes;
166// 2. open the note with the pinned verifier keys;
167// 3. require the type line, then read the records;
168// 4. require the configured instance and destination;
169// 5. require a sequence greater than the stored authorization's;
170// 6. require a basis, when it has one, equal to the stored
171// authorization's sequence.
172//
173// There is no step for its age or its checked time: a valid narrowing
174// above the stored sequence is admitted however old it is, and however far
175// the clocks disagree. Every refusal is an *Error.
176func VerifyAuthorization(r io.Reader, a AuthorizationAdmission) (*Authorization, error) {
177 signed, err := io.ReadAll(io.LimitReader(r, MaxAuthorization+1))
178 if err != nil {
179 return nil, refuse(CodeUnreadable, "the authorization could not be read: %v", err)
180 }
181 if len(signed) > MaxAuthorization {
182 return nil, refuse(CodeTooLarge, "an authorization is at most %d bytes", MaxAuthorization)
183 }
184 text, _, err := note.Open(signed, a.Verifiers)
185 if err != nil {
186 return nil, refuse(CodeBadSignature, "the authorization does not open under the pinned key: %v", err)
187 }
188 auth, err := ParseAuthorization(text)
189 if err != nil {
190 return nil, err
191 }
192 if auth.Instance != a.Instance {
193 return nil, refuse(CodeWrongInstance, "the authorization is from instance %s, and this receiver takes %s", auth.Instance, a.Instance)
194 }
195 if auth.Destination != a.Destination {
196 return nil, refuse(CodeWrongDestination, "the authorization is for %s, and this receiver is %s", auth.Destination, a.Destination)
197 }
198 if err := auth.admissible(a.HighWater); err != nil {
199 return nil, err
200 }
201 return auth, nil
202}
203
204// admissible is steps 5 and 6 of VerifyAuthorization against the stored
205// authorization's sequence, hw. Store.Authorize takes them again under its
206// lock.
207func (a *Authorization) admissible(hw int64) error {
208 if a.Sequence <= hw {
209 e := refuse(CodeReplayed, "the authorization's sequence %d is not greater than %d, the stored authorization's", a.Sequence, hw)
210 e.HighWater = hw
211 return e
212 }
213 if a.Basis > 0 && a.Basis != hw {
214 e := refuse(CodeStaleBasis, "the authorization keeps access from authorization %d, and this receiver holds %d", a.Basis, hw)
215 e.HighWater = hw
216 return e
217 }
218 return nil
219}
220
221// ReadStoredAuthorization reads an authorization a receiver stored: the
222// signed note it admitted. The receiver verified the signature before it
223// stored it, so this reads the text without verifying it again, and holds
224// it to ParseAuthorization.
225func ReadStoredAuthorization(signed []byte) (*Authorization, error) {
226 if len(signed) > MaxAuthorization {
227 return nil, fmt.Errorf("the stored authorization is larger than %d bytes", MaxAuthorization)
228 }
229 text, _, err := note.Split(signed)
230 if err != nil {
231 return nil, fmt.Errorf("the stored authorization is not a signed note: %w", err)
232 }
233 return ParseAuthorization(text)
234}
235
236// ParseAuthorization reads an authorization's text, step 3 of
237// VerifyAuthorization. The first line is exactly AuthorizationType. Each
238// record after it is a keyword and exactly its fields. The instance,
239// destination, sequence and checked records appear once each, a project at
240// most once, and every project has one or more readers, each named once.
241// A reader record names a project that has a project record. Records may
242// come in any order; Text writes them in one.
243func ParseAuthorization(text []byte) (*Authorization, error) {
244 bad := func(format string, args ...any) error { return refuse(CodeBadManifest, format, args...) }
245 if len(text) == 0 || text[len(text)-1] != '\n' {
246 return nil, bad("an authorization's text ends with a newline")
247 }
248 lines := strings.Split(strings.TrimSuffix(string(text), "\n"), "\n")
249 if lines[0] != AuthorizationType {
250 return nil, bad("the authorization opens with %q, not %q", lines[0], AuthorizationType)
251 }
252 arity := map[string]int{"instance": 1, "destination": 1, "sequence": 1, "checked": 1, "basis": 1, "project": 2, "reader": 2}
253 a := &Authorization{}
254 seen := map[string]bool{}
255 projects := map[string]*AuthorizedProject{}
256 readers := map[string]map[string]bool{}
257 for i, line := range lines[1:] {
258 n := i + 2
259 fields := strings.Split(line, " ")
260 key, args := fields[0], fields[1:]
261 want, known := arity[key]
262 switch {
263 case !known:
264 return nil, bad("line %d is %q; no record opens with %q", n, line, key)
265 case len(args) != want:
266 return nil, bad("line %d is %q; a %s record has %d fields", n, line, key, want)
267 }
268 for _, f := range args {
269 if f == "" {
270 return nil, bad("line %d is %q; fields are separated by one space", n, line)
271 }
272 }
273 switch key {
274 case "instance", "destination", "sequence", "checked", "basis":
275 if seen[key] {
276 return nil, bad("line %d is a second %s record", n, key)
277 }
278 seen[key] = true
279 }
280 switch key {
281 case "instance", "destination":
282 if !ValidName(args[0]) {
283 return nil, bad("line %d names %s %q, which is not a name", n, key, args[0])
284 }
285 if key == "instance" {
286 a.Instance = args[0]
287 } else {
288 a.Destination = args[0]
289 }
290 case "sequence":
291 seq, ok := decimal(args[0])
292 if !ok || seq == 0 {
293 return nil, bad("line %d gives sequence %q; a sequence is a positive decimal", n, args[0])
294 }
295 a.Sequence = seq
296 case "basis":
297 basis, ok := decimal(args[0])
298 if !ok || basis == 0 {
299 return nil, bad("line %d gives basis %q; a basis is a positive decimal", n, args[0])
300 }
301 a.Basis = basis
302 case "checked":
303 at, err := time.Parse(time.RFC3339, args[0])
304 if err != nil || at.UTC().Format(time.RFC3339) != args[0] {
305 return nil, bad("line %d gives checked %q; it is a time in RFC 3339, in UTC, to the second", n, args[0])
306 }
307 a.Checked = at.UTC()
308 case "project":
309 name, id := args[0], args[1]
310 if !ValidName(name) {
311 return nil, bad("line %d names project %q, which is not a project name", n, name)
312 }
313 if projects[name] != nil {
314 return nil, bad("line %d is a second project record for %s", n, name)
315 }
316 if !ValidIdentity(id) {
317 return nil, bad("line %d gives %s identity %q, which is not 32 lowercase hex digits", n, name, id)
318 }
319 projects[name] = &AuthorizedProject{Name: name, Identity: id}
320 case "reader":
321 name, reader := args[0], args[1]
322 if !ValidName(name) || !ValidName(reader) {
323 return nil, bad("line %d is %q; a reader record names a project and a principal", n, line)
324 }
325 if readers[name][reader] {
326 return nil, bad("line %d names reader %s of %s a second time", n, reader, name)
327 }
328 if readers[name] == nil {
329 readers[name] = map[string]bool{}
330 }
331 readers[name][reader] = true
332 }
333 }
334 for _, key := range []string{"instance", "destination", "sequence", "checked"} {
335 if !seen[key] {
336 return nil, bad("the authorization has no %s record", key)
337 }
338 }
339 if a.Basis >= a.Sequence {
340 return nil, bad("the authorization's basis %d is not less than its sequence %d", a.Basis, a.Sequence)
341 }
342 for name, rs := range readers {
343 p := projects[name]
344 if p == nil {
345 return nil, bad("the authorization has a reader of %s and no project record for it", name)
346 }
347 for r := range rs {
348 p.Readers = append(p.Readers, r)
349 }
350 sort.Strings(p.Readers)
351 }
352 var names []string
353 for name, p := range projects {
354 if len(p.Readers) == 0 {
355 return nil, bad("project %s has no reader record", name)
356 }
357 names = append(names, name)
358 }
359 sort.Strings(names)
360 for _, name := range names {
361 a.Projects = append(a.Projects, *projects[name])
362 }
363 return a, nil
364}