gunk-dev/the-valley

manifest.go

sourcef626522c2906main's published tip history
15.4 KiB
1package export
2
3import (
4 "bytes"
5 "crypto/ed25519"
6 "crypto/sha256"
7 "encoding/hex"
8 "fmt"
9 "io"
10 "os"
11 "sort"
12 "strconv"
13 "strings"
14 "time"
15
16 "the-valley/note"
17)
18
19const (
20 // ManifestType is the first line of every manifest's text.
21 ManifestType = "the-valley/web-export/v1"
22
23 // MaxManifest is the most bytes of a signed manifest a receiver reads.
24 MaxManifest = 64 << 10
25
26 // ExportFile is export.json's name, in a manifest and in a generation.
27 ExportFile = "export.json"
28
29 // MaxAge and MaxAhead bound a manifest's signing time, its sequence,
30 // against the receiver's clock: no older than three days, and no more
31 // than a minute ahead. They bound how long a replayed manifest can be
32 // admitted after the receiver loses its high-water mark. They do not
33 // expire an export that was accepted.
34 MaxAge = 72 * time.Hour
35 MaxAhead = time.Minute
36)
37
38// Body is one upload body a manifest declares: its name, the SHA-256 of
39// its bytes in hex, and its size in bytes. export.json's name is
40// ExportFile, and a bundle's is its project's.
41type Body struct {
42 Name string
43 SHA256 string
44 Size int64
45}
46
47// BodyOf is the body data makes under name.
48func BodyOf(name string, data []byte) Body {
49 sum := sha256.Sum256(data)
50 return Body{Name: name, SHA256: hex.EncodeToString(sum[:]), Size: int64(len(data))}
51}
52
53// FileBody is the body the file at path makes under name, read once.
54func FileBody(name, path string) (Body, error) {
55 f, err := os.Open(path)
56 if err != nil {
57 return Body{}, err
58 }
59 defer f.Close()
60 h := sha256.New()
61 n, err := io.Copy(h, f)
62 if err != nil {
63 return Body{}, err
64 }
65 return Body{Name: name, SHA256: hex.EncodeToString(h.Sum(nil)), Size: n}, nil
66}
67
68// Manifest is the signed statement an upload is admitted by. It names the
69// valley instance that signed it and the destination it is for, its
70// sequence, export.json's hash and size, and for each project its
71// visibility, its graph and source tips, and its bundle's hash and size.
72//
73// Its text is the type line and then one record per line, each a keyword
74// and its fields separated by single spaces:
75//
76// the-valley/web-export/v1
77// instance valley-host
78// destination example.org
79// sequence 1792929600000000000
80// file export.json <sha256> <size>
81// project app public <graph-tip> <source-tip>
82// bundle app <sha256> <size>
83//
84// The sequence is the signing time in Unix nanoseconds. A project with no
85// plan graph has - for its graph tip. Every project has one bundle.
86type Manifest struct {
87 Instance string
88 Destination string
89 Sequence int64
90 File Body
91 Projects []ManifestProject
92}
93
94// ManifestProject is one project's two records.
95type ManifestProject struct {
96 Name string
97 Visibility Visibility
98 // GraphTip is "" for a project with no plan graph.
99 GraphTip string
100 SourceTip string
101 Bundle Body
102}
103
104// NewManifest is the manifest for an export: its bytes, exportJSON, and
105// each project's bundle, by project name.
106func NewManifest(instance, destination string, sequence int64, e *Export, exportJSON []byte, bundles map[string]Body) (*Manifest, error) {
107 m := &Manifest{Instance: instance, Destination: destination, Sequence: sequence,
108 File: BodyOf(ExportFile, exportJSON)}
109 for _, p := range e.Projects {
110 b, ok := bundles[p.Name]
111 if !ok {
112 return nil, fmt.Errorf("project %s has no bundle", p.Name)
113 }
114 b.Name = p.Name
115 m.Projects = append(m.Projects, ManifestProject{Name: p.Name, Visibility: p.Visibility,
116 GraphTip: p.GraphTip, SourceTip: p.SourceTip, Bundle: b})
117 }
118 if len(bundles) != len(m.Projects) {
119 return nil, fmt.Errorf("%d bundles for %d projects", len(bundles), len(m.Projects))
120 }
121 if _, err := ParseManifest(m.Text()); err != nil {
122 return nil, err
123 }
124 return m, nil
125}
126
127// Text is the manifest's text: the type line, then the instance,
128// destination, sequence and file records, then each project's two records
129// in name order.
130func (m *Manifest) Text() []byte {
131 var b bytes.Buffer
132 fmt.Fprintf(&b, "%s\ninstance %s\ndestination %s\nsequence %d\n", ManifestType, m.Instance, m.Destination, m.Sequence)
133 fmt.Fprintf(&b, "file %s %s %d\n", m.File.Name, m.File.SHA256, m.File.Size)
134 projects := append([]ManifestProject{}, m.Projects...)
135 sort.Slice(projects, func(i, j int) bool { return projects[i].Name < projects[j].Name })
136 for _, p := range projects {
137 graph := p.GraphTip
138 if graph == "" {
139 graph = "-"
140 }
141 fmt.Fprintf(&b, "project %s %s %s %s\n", p.Name, p.Visibility, graph, p.SourceTip)
142 fmt.Fprintf(&b, "bundle %s %s %d\n", p.Bundle.Name, p.Bundle.SHA256, p.Bundle.Size)
143 }
144 return b.Bytes()
145}
146
147// Sign is the manifest signed as a note by the publisher's export key.
148func (m *Manifest) Sign(name string, key ed25519.PrivateKey) ([]byte, error) {
149 return note.Sign(m.Text(), name, key)
150}
151
152// SignedAt is the manifest's signing time: its sequence.
153func (m *Manifest) SignedAt() time.Time { return time.Unix(0, m.Sequence).UTC() }
154
155// Bodies are every body the manifest declares: export.json, then each
156// bundle in project order.
157func (m *Manifest) Bodies() []Body {
158 bodies := []Body{m.File}
159 for _, p := range m.Projects {
160 bodies = append(bodies, p.Bundle)
161 }
162 return bodies
163}
164
165// Project is the manifest's project called name.
166func (m *Manifest) Project(name string) (ManifestProject, bool) {
167 for _, p := range m.Projects {
168 if p.Name == name {
169 return p, true
170 }
171 }
172 return ManifestProject{}, false
173}
174
175// Admission is what a receiver admits a manifest against: the pinned
176// verifier keys, the instance and destination it is configured with, the
177// greatest sequence it has accepted, and its clock.
178type Admission struct {
179 Verifiers []note.VerifierKey
180 Instance string
181 Destination string
182 HighWater int64
183 Now time.Time
184}
185
186// VerifyManifest admits a signed manifest, in this order, each step its
187// own:
188//
189// 1. read at most MaxManifest bytes;
190// 2. open the note with the pinned verifier keys;
191// 3. require the type line, then read the records;
192// 4. require the configured instance and destination;
193// 5. require a sequence greater than the high-water mark;
194// 6. require a signing time no older than MaxAge and no more than
195// MaxAhead ahead.
196//
197// Every refusal is an *Error, whose Code the upload's reply carries.
198func VerifyManifest(r io.Reader, a Admission) (*Manifest, error) {
199 signed, err := readManifest(r)
200 if err != nil {
201 return nil, err
202 }
203 text, err := openManifest(signed, a.Verifiers)
204 if err != nil {
205 return nil, err
206 }
207 m, err := ParseManifest(text)
208 if err != nil {
209 return nil, err
210 }
211 if err := checkDestination(m, a); err != nil {
212 return nil, err
213 }
214 if err := checkSequence(m, a.HighWater); err != nil {
215 return nil, err
216 }
217 if err := checkSigningTime(m, a.Now); err != nil {
218 return nil, err
219 }
220 return m, nil
221}
222
223// readManifest is step 1: at most MaxManifest bytes.
224func readManifest(r io.Reader) ([]byte, error) {
225 b, err := io.ReadAll(io.LimitReader(r, MaxManifest+1))
226 if err != nil {
227 return nil, refuse(CodeUnreadable, "the manifest could not be read: %v", err)
228 }
229 if len(b) > MaxManifest {
230 return nil, refuse(CodeTooLarge, "a manifest is at most %d bytes", MaxManifest)
231 }
232 return b, nil
233}
234
235// openManifest is step 2: the note opens under a pinned key.
236func openManifest(signed []byte, verifiers []note.VerifierKey) ([]byte, error) {
237 text, _, err := note.Open(signed, verifiers)
238 if err != nil {
239 return nil, refuse(CodeBadSignature, "the manifest does not open under the pinned key: %v", err)
240 }
241 return text, nil
242}
243
244// checkDestination is step 4.
245func checkDestination(m *Manifest, a Admission) error {
246 if m.Instance != a.Instance {
247 return refuse(CodeWrongInstance, "the manifest is from instance %s, and this receiver takes %s", m.Instance, a.Instance)
248 }
249 if m.Destination != a.Destination {
250 return refuse(CodeWrongDestination, "the manifest is for %s, and this receiver is %s", m.Destination, a.Destination)
251 }
252 return nil
253}
254
255// checkSequence is step 5. A manifest at the high-water mark is a replay,
256// and one below it is older than what was accepted.
257func checkSequence(m *Manifest, highWater int64) error {
258 if m.Sequence <= highWater {
259 e := refuse(CodeReplayed, "the manifest's sequence %d is not greater than %d, the greatest accepted", m.Sequence, highWater)
260 e.HighWater = highWater
261 return e
262 }
263 return nil
264}
265
266// checkSigningTime is step 6.
267func checkSigningTime(m *Manifest, now time.Time) error {
268 at := m.SignedAt()
269 switch {
270 case now.Sub(at) > MaxAge:
271 return refuse(CodeOutOfWindow, "the manifest was signed at %s, more than %s before %s", at.Format(time.RFC3339), MaxAge, now.UTC().Format(time.RFC3339))
272 case at.Sub(now) > MaxAhead:
273 return refuse(CodeOutOfWindow, "the manifest was signed at %s, more than %s after %s", at.Format(time.RFC3339), MaxAhead, now.UTC().Format(time.RFC3339))
274 }
275 return nil
276}
277
278// ParseManifest reads a manifest's text, step 3 of VerifyManifest. The
279// first line is exactly ManifestType. Each record after it is a keyword and
280// exactly its fields. The instance, destination, sequence and file records
281// appear once each, a project at most once, and each project has exactly
282// one bundle record. Names are project names, which hold no path character
283// and are never a dot segment. Records may come in any order; Text writes
284// them in one.
285func ParseManifest(text []byte) (*Manifest, error) {
286 bad := func(format string, args ...any) error { return refuse(CodeBadManifest, format, args...) }
287 if len(text) == 0 || text[len(text)-1] != '\n' {
288 return nil, bad("a manifest's text ends with a newline")
289 }
290 lines := strings.Split(strings.TrimSuffix(string(text), "\n"), "\n")
291 if lines[0] != ManifestType {
292 return nil, bad("the manifest opens with %q, not %q", lines[0], ManifestType)
293 }
294 arity := map[string]int{"instance": 1, "destination": 1, "sequence": 1, "file": 3, "project": 4, "bundle": 3}
295 m := &Manifest{}
296 seen := map[string]bool{}
297 projects := map[string]*ManifestProject{}
298 bundles := map[string]Body{}
299 for i, line := range lines[1:] {
300 n := i + 2
301 fields := strings.Split(line, " ")
302 key, args := fields[0], fields[1:]
303 want, known := arity[key]
304 switch {
305 case !known:
306 return nil, bad("line %d is %q; no record opens with %q", n, line, key)
307 case len(args) != want:
308 return nil, bad("line %d is %q; a %s record has %d fields", n, line, key, want)
309 }
310 for _, f := range args {
311 if f == "" {
312 return nil, bad("line %d is %q; fields are separated by one space", n, line)
313 }
314 }
315 switch key {
316 case "instance", "destination", "sequence", "file":
317 if seen[key] {
318 return nil, bad("line %d is a second %s record", n, key)
319 }
320 seen[key] = true
321 }
322 switch key {
323 case "instance", "destination":
324 if !ValidName(args[0]) {
325 return nil, bad("line %d names %s %q, which is not a name", n, key, args[0])
326 }
327 if key == "instance" {
328 m.Instance = args[0]
329 } else {
330 m.Destination = args[0]
331 }
332 case "sequence":
333 seq, ok := decimal(args[0])
334 if !ok || seq == 0 {
335 return nil, bad("line %d gives sequence %q; a sequence is a positive decimal", n, args[0])
336 }
337 m.Sequence = seq
338 case "file":
339 if args[0] != ExportFile {
340 return nil, bad("line %d declares file %q; the only file is %s", n, args[0], ExportFile)
341 }
342 b, err := body(args)
343 if err != nil {
344 return nil, bad("line %d: %v", n, err)
345 }
346 m.File = b
347 case "project":
348 name, vis, graph, source := args[0], Visibility(args[1]), args[2], args[3]
349 if !ValidName(name) {
350 return nil, bad("line %d names project %q, which is not a project name", n, name)
351 }
352 if projects[name] != nil {
353 return nil, bad("line %d is a second project record for %s", n, name)
354 }
355 if vis != Public {
356 return nil, bad("line %d gives %s visibility %q; v1 exports public projects alone", n, name, vis)
357 }
358 if graph == "-" {
359 graph = ""
360 } else if !ValidObjectID(graph) {
361 return nil, bad("line %d gives %s graph tip %q, which is not an object ID or -", n, name, graph)
362 }
363 if !ValidObjectID(source) {
364 return nil, bad("line %d gives %s source tip %q, which is not an object ID", n, name, source)
365 }
366 projects[name] = &ManifestProject{Name: name, Visibility: vis, GraphTip: graph, SourceTip: source}
367 case "bundle":
368 if !ValidName(args[0]) {
369 return nil, bad("line %d names bundle %q, which is not a project name", n, args[0])
370 }
371 if _, twice := bundles[args[0]]; twice {
372 return nil, bad("line %d is a second bundle record for %s", n, args[0])
373 }
374 b, err := body(args)
375 if err != nil {
376 return nil, bad("line %d: %v", n, err)
377 }
378 bundles[args[0]] = b
379 }
380 }
381 for _, key := range []string{"instance", "destination", "sequence", "file"} {
382 if !seen[key] {
383 return nil, bad("the manifest has no %s record", key)
384 }
385 }
386 for name, b := range bundles {
387 p := projects[name]
388 if p == nil {
389 return nil, bad("the manifest has a bundle for %s and no project record for it", name)
390 }
391 p.Bundle = b
392 }
393 var names []string
394 for name, p := range projects {
395 if p.Bundle.Name == "" {
396 return nil, bad("project %s has no bundle record", name)
397 }
398 names = append(names, name)
399 }
400 sort.Strings(names)
401 for _, name := range names {
402 m.Projects = append(m.Projects, *projects[name])
403 }
404 sizes := map[string]int64{}
405 for _, b := range m.Bodies() {
406 if size, ok := sizes[b.SHA256]; ok && size != b.Size {
407 return nil, bad("two bodies with SHA-256 %s declare sizes %d and %d", b.SHA256, size, b.Size)
408 }
409 sizes[b.SHA256] = b.Size
410 }
411 return m, nil
412}
413
414// body reads a file or bundle record's name, hash and size.
415func body(args []string) (Body, error) {
416 name, sum, written := args[0], args[1], args[2]
417 if len(sum) != 64 || !isHex(sum) {
418 return Body{}, fmt.Errorf("%q is not a SHA-256 in lowercase hex", sum)
419 }
420 size, ok := decimal(written)
421 if !ok || size == 0 {
422 return Body{}, fmt.Errorf("size %q is not a positive decimal", written)
423 }
424 return Body{Name: name, SHA256: sum, Size: size}, nil
425}
426
427// decimal reads a non-negative int64 written in decimal, with no sign and
428// no leading zero.
429func decimal(s string) (int64, bool) {
430 if s == "" || len(s) > 1 && s[0] == '0' || strings.TrimLeft(s, "0123456789") != "" {
431 return 0, false
432 }
433 n, err := strconv.ParseInt(s, 10, 64)
434 return n, err == nil
435}
436
437// CheckExport holds export.json to the manifest: its bytes have the
438// declared hash and size, it is a valid export, and it names the same
439// projects with the same visibility and tips. It returns the export.
440func (m *Manifest) CheckExport(data []byte) (*Export, error) {
441 if got := BodyOf(ExportFile, data); got != m.File {
442 return nil, refuse(CodeHashMismatch, "export.json has SHA-256 %s and %d bytes; the manifest declares %s and %d", got.SHA256, got.Size, m.File.SHA256, m.File.Size)
443 }
444 e, err := Decode(data)
445 if err != nil {
446 return nil, refuse(CodeBadExport, "%v", err)
447 }
448 if len(e.Projects) != len(m.Projects) {
449 return nil, refuse(CodeBadExport, "export.json holds %d projects, and the manifest %d", len(e.Projects), len(m.Projects))
450 }
451 for i, p := range e.Projects {
452 mp := m.Projects[i]
453 switch {
454 case p.Name != mp.Name:
455 return nil, refuse(CodeBadExport, "export.json holds project %s where the manifest has %s", p.Name, mp.Name)
456 case p.Visibility != mp.Visibility:
457 return nil, refuse(CodeBadExport, "project %s is %s in export.json and %s in the manifest", p.Name, p.Visibility, mp.Visibility)
458 case p.GraphTip != mp.GraphTip:
459 return nil, refuse(CodeBadExport, "project %s has graph tip %q in export.json and %q in the manifest", p.Name, p.GraphTip, mp.GraphTip)
460 case p.SourceTip != mp.SourceTip:
461 return nil, refuse(CodeBadExport, "project %s has source tip %s in export.json and %s in the manifest", p.Name, p.SourceTip, mp.SourceTip)
462 }
463 }
464 return e, nil
465}