| 1 | package export |
| 2 | |
| 3 | import ( |
| 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 | |
| 19 | const ( |
| 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. |
| 41 | type Body struct { |
| 42 | Name string |
| 43 | SHA256 string |
| 44 | Size int64 |
| 45 | } |
| 46 | |
| 47 | // BodyOf is the body data makes under name. |
| 48 | func 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. |
| 54 | func 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. |
| 86 | type 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. |
| 95 | type 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. |
| 106 | func 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. |
| 130 | func (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. |
| 148 | func (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. |
| 153 | func (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. |
| 157 | func (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 | // CheckSizes holds the bodies the manifest declares to a receiver's caps: |
| 166 | // each body at most maxBody bytes, and every body together at most |
| 167 | // maxUpload. A body declared twice, under one SHA-256, is staged once and |
| 168 | // counted once. A refusal is too-large. |
| 169 | func (m *Manifest) CheckSizes(maxBody, maxUpload int64) error { |
| 170 | var total int64 |
| 171 | counted := map[string]bool{} |
| 172 | for _, b := range m.Bodies() { |
| 173 | if b.Size > maxBody { |
| 174 | return refuse(CodeTooLarge, "%s declares %d bytes, more than this receiver's cap of %d on one body", b.Name, b.Size, maxBody) |
| 175 | } |
| 176 | if counted[b.SHA256] { |
| 177 | continue |
| 178 | } |
| 179 | counted[b.SHA256] = true |
| 180 | // Compared before it is added, so the sum never overflows. |
| 181 | if b.Size > maxUpload-total { |
| 182 | return refuse(CodeTooLarge, "the manifest declares more than this receiver's cap of %d bytes of bodies on one upload", maxUpload) |
| 183 | } |
| 184 | total += b.Size |
| 185 | } |
| 186 | return nil |
| 187 | } |
| 188 | |
| 189 | // Project is the manifest's project called name. |
| 190 | func (m *Manifest) Project(name string) (ManifestProject, bool) { |
| 191 | for _, p := range m.Projects { |
| 192 | if p.Name == name { |
| 193 | return p, true |
| 194 | } |
| 195 | } |
| 196 | return ManifestProject{}, false |
| 197 | } |
| 198 | |
| 199 | // Admission is what a receiver admits a manifest against: the pinned |
| 200 | // verifier keys, the instance and destination it is configured with, the |
| 201 | // greatest sequence it has accepted, and its clock. |
| 202 | type Admission struct { |
| 203 | Verifiers []note.VerifierKey |
| 204 | Instance string |
| 205 | Destination string |
| 206 | HighWater int64 |
| 207 | Now time.Time |
| 208 | } |
| 209 | |
| 210 | // VerifyManifest admits a signed manifest, in this order, each step its |
| 211 | // own: |
| 212 | // |
| 213 | // 1. read at most MaxManifest 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 high-water mark; |
| 218 | // 6. require a signing time no older than MaxAge and no more than |
| 219 | // MaxAhead ahead. |
| 220 | // |
| 221 | // Every refusal is an *Error, whose Code the upload's reply carries. |
| 222 | func VerifyManifest(r io.Reader, a Admission) (*Manifest, error) { |
| 223 | signed, err := readManifest(r) |
| 224 | if err != nil { |
| 225 | return nil, err |
| 226 | } |
| 227 | text, err := openManifest(signed, a.Verifiers) |
| 228 | if err != nil { |
| 229 | return nil, err |
| 230 | } |
| 231 | m, err := ParseManifest(text) |
| 232 | if err != nil { |
| 233 | return nil, err |
| 234 | } |
| 235 | if err := checkDestination(m, a); err != nil { |
| 236 | return nil, err |
| 237 | } |
| 238 | if err := checkSequence(m, a.HighWater); err != nil { |
| 239 | return nil, err |
| 240 | } |
| 241 | if err := checkSigningTime(m, a.Now); err != nil { |
| 242 | return nil, err |
| 243 | } |
| 244 | return m, nil |
| 245 | } |
| 246 | |
| 247 | // readManifest is step 1: at most MaxManifest bytes. |
| 248 | func readManifest(r io.Reader) ([]byte, error) { |
| 249 | b, err := io.ReadAll(io.LimitReader(r, MaxManifest+1)) |
| 250 | if err != nil { |
| 251 | return nil, refuse(CodeUnreadable, "the manifest could not be read: %v", err) |
| 252 | } |
| 253 | if len(b) > MaxManifest { |
| 254 | return nil, refuse(CodeTooLarge, "a manifest is at most %d bytes", MaxManifest) |
| 255 | } |
| 256 | return b, nil |
| 257 | } |
| 258 | |
| 259 | // openManifest is step 2: the note opens under a pinned key. |
| 260 | func openManifest(signed []byte, verifiers []note.VerifierKey) ([]byte, error) { |
| 261 | text, _, err := note.Open(signed, verifiers) |
| 262 | if err != nil { |
| 263 | return nil, refuse(CodeBadSignature, "the manifest does not open under the pinned key: %v", err) |
| 264 | } |
| 265 | return text, nil |
| 266 | } |
| 267 | |
| 268 | // checkDestination is step 4. |
| 269 | func checkDestination(m *Manifest, a Admission) error { |
| 270 | if m.Instance != a.Instance { |
| 271 | return refuse(CodeWrongInstance, "the manifest is from instance %s, and this receiver takes %s", m.Instance, a.Instance) |
| 272 | } |
| 273 | if m.Destination != a.Destination { |
| 274 | return refuse(CodeWrongDestination, "the manifest is for %s, and this receiver is %s", m.Destination, a.Destination) |
| 275 | } |
| 276 | return nil |
| 277 | } |
| 278 | |
| 279 | // checkSequence is step 5. A manifest at the high-water mark is a replay, |
| 280 | // and one below it is older than what was accepted. |
| 281 | func checkSequence(m *Manifest, highWater int64) error { |
| 282 | if m.Sequence <= highWater { |
| 283 | e := refuse(CodeReplayed, "the manifest's sequence %d is not greater than %d, the greatest accepted", m.Sequence, highWater) |
| 284 | e.HighWater = highWater |
| 285 | return e |
| 286 | } |
| 287 | return nil |
| 288 | } |
| 289 | |
| 290 | // checkSigningTime is step 6. |
| 291 | func checkSigningTime(m *Manifest, now time.Time) error { |
| 292 | at := m.SignedAt() |
| 293 | switch { |
| 294 | case now.Sub(at) > MaxAge: |
| 295 | return refuse(CodeOutOfWindow, "the manifest was signed at %s, more than %s before %s", at.Format(time.RFC3339), MaxAge, now.UTC().Format(time.RFC3339)) |
| 296 | case at.Sub(now) > MaxAhead: |
| 297 | return refuse(CodeOutOfWindow, "the manifest was signed at %s, more than %s after %s", at.Format(time.RFC3339), MaxAhead, now.UTC().Format(time.RFC3339)) |
| 298 | } |
| 299 | return nil |
| 300 | } |
| 301 | |
| 302 | // ParseManifest reads a manifest's text, step 3 of VerifyManifest. The |
| 303 | // first line is exactly ManifestType. Each record after it is a keyword and |
| 304 | // exactly its fields. The instance, destination, sequence and file records |
| 305 | // appear once each, a project at most once, and each project has exactly |
| 306 | // one bundle record. Names are project names, which hold no path character |
| 307 | // and are never a dot segment. Records may come in any order; Text writes |
| 308 | // them in one. |
| 309 | func ParseManifest(text []byte) (*Manifest, error) { |
| 310 | bad := func(format string, args ...any) error { return refuse(CodeBadManifest, format, args...) } |
| 311 | if len(text) == 0 || text[len(text)-1] != '\n' { |
| 312 | return nil, bad("a manifest's text ends with a newline") |
| 313 | } |
| 314 | lines := strings.Split(strings.TrimSuffix(string(text), "\n"), "\n") |
| 315 | if lines[0] != ManifestType { |
| 316 | return nil, bad("the manifest opens with %q, not %q", lines[0], ManifestType) |
| 317 | } |
| 318 | arity := map[string]int{"instance": 1, "destination": 1, "sequence": 1, "file": 3, "project": 4, "bundle": 3} |
| 319 | m := &Manifest{} |
| 320 | seen := map[string]bool{} |
| 321 | projects := map[string]*ManifestProject{} |
| 322 | bundles := map[string]Body{} |
| 323 | for i, line := range lines[1:] { |
| 324 | n := i + 2 |
| 325 | fields := strings.Split(line, " ") |
| 326 | key, args := fields[0], fields[1:] |
| 327 | want, known := arity[key] |
| 328 | switch { |
| 329 | case !known: |
| 330 | return nil, bad("line %d is %q; no record opens with %q", n, line, key) |
| 331 | case len(args) != want: |
| 332 | return nil, bad("line %d is %q; a %s record has %d fields", n, line, key, want) |
| 333 | } |
| 334 | for _, f := range args { |
| 335 | if f == "" { |
| 336 | return nil, bad("line %d is %q; fields are separated by one space", n, line) |
| 337 | } |
| 338 | } |
| 339 | switch key { |
| 340 | case "instance", "destination", "sequence", "file": |
| 341 | if seen[key] { |
| 342 | return nil, bad("line %d is a second %s record", n, key) |
| 343 | } |
| 344 | seen[key] = true |
| 345 | } |
| 346 | switch key { |
| 347 | case "instance", "destination": |
| 348 | if !ValidName(args[0]) { |
| 349 | return nil, bad("line %d names %s %q, which is not a name", n, key, args[0]) |
| 350 | } |
| 351 | if key == "instance" { |
| 352 | m.Instance = args[0] |
| 353 | } else { |
| 354 | m.Destination = args[0] |
| 355 | } |
| 356 | case "sequence": |
| 357 | seq, ok := decimal(args[0]) |
| 358 | if !ok || seq == 0 { |
| 359 | return nil, bad("line %d gives sequence %q; a sequence is a positive decimal", n, args[0]) |
| 360 | } |
| 361 | m.Sequence = seq |
| 362 | case "file": |
| 363 | if args[0] != ExportFile { |
| 364 | return nil, bad("line %d declares file %q; the only file is %s", n, args[0], ExportFile) |
| 365 | } |
| 366 | b, err := body(args) |
| 367 | if err != nil { |
| 368 | return nil, bad("line %d: %v", n, err) |
| 369 | } |
| 370 | m.File = b |
| 371 | case "project": |
| 372 | name, vis, graph, source := args[0], Visibility(args[1]), args[2], args[3] |
| 373 | if !ValidName(name) { |
| 374 | return nil, bad("line %d names project %q, which is not a project name", n, name) |
| 375 | } |
| 376 | if projects[name] != nil { |
| 377 | return nil, bad("line %d is a second project record for %s", n, name) |
| 378 | } |
| 379 | if vis != Public { |
| 380 | return nil, bad("line %d gives %s visibility %q; v1 exports public projects alone", n, name, vis) |
| 381 | } |
| 382 | if graph == "-" { |
| 383 | graph = "" |
| 384 | } else if !ValidObjectID(graph) { |
| 385 | return nil, bad("line %d gives %s graph tip %q, which is not an object ID or -", n, name, graph) |
| 386 | } |
| 387 | if !ValidObjectID(source) { |
| 388 | return nil, bad("line %d gives %s source tip %q, which is not an object ID", n, name, source) |
| 389 | } |
| 390 | projects[name] = &ManifestProject{Name: name, Visibility: vis, GraphTip: graph, SourceTip: source} |
| 391 | case "bundle": |
| 392 | if !ValidName(args[0]) { |
| 393 | return nil, bad("line %d names bundle %q, which is not a project name", n, args[0]) |
| 394 | } |
| 395 | if _, twice := bundles[args[0]]; twice { |
| 396 | return nil, bad("line %d is a second bundle record for %s", n, args[0]) |
| 397 | } |
| 398 | b, err := body(args) |
| 399 | if err != nil { |
| 400 | return nil, bad("line %d: %v", n, err) |
| 401 | } |
| 402 | bundles[args[0]] = b |
| 403 | } |
| 404 | } |
| 405 | for _, key := range []string{"instance", "destination", "sequence", "file"} { |
| 406 | if !seen[key] { |
| 407 | return nil, bad("the manifest has no %s record", key) |
| 408 | } |
| 409 | } |
| 410 | for name, b := range bundles { |
| 411 | p := projects[name] |
| 412 | if p == nil { |
| 413 | return nil, bad("the manifest has a bundle for %s and no project record for it", name) |
| 414 | } |
| 415 | p.Bundle = b |
| 416 | } |
| 417 | var names []string |
| 418 | for name, p := range projects { |
| 419 | if p.Bundle.Name == "" { |
| 420 | return nil, bad("project %s has no bundle record", name) |
| 421 | } |
| 422 | names = append(names, name) |
| 423 | } |
| 424 | sort.Strings(names) |
| 425 | for _, name := range names { |
| 426 | m.Projects = append(m.Projects, *projects[name]) |
| 427 | } |
| 428 | sizes := map[string]int64{} |
| 429 | for _, b := range m.Bodies() { |
| 430 | if size, ok := sizes[b.SHA256]; ok && size != b.Size { |
| 431 | return nil, bad("two bodies with SHA-256 %s declare sizes %d and %d", b.SHA256, size, b.Size) |
| 432 | } |
| 433 | sizes[b.SHA256] = b.Size |
| 434 | } |
| 435 | return m, nil |
| 436 | } |
| 437 | |
| 438 | // body reads a file or bundle record's name, hash and size. |
| 439 | func body(args []string) (Body, error) { |
| 440 | name, sum, written := args[0], args[1], args[2] |
| 441 | if len(sum) != 64 || !isHex(sum) { |
| 442 | return Body{}, fmt.Errorf("%q is not a SHA-256 in lowercase hex", sum) |
| 443 | } |
| 444 | size, ok := decimal(written) |
| 445 | if !ok || size == 0 { |
| 446 | return Body{}, fmt.Errorf("size %q is not a positive decimal", written) |
| 447 | } |
| 448 | return Body{Name: name, SHA256: sum, Size: size}, nil |
| 449 | } |
| 450 | |
| 451 | // decimal reads a non-negative int64 written in decimal, with no sign and |
| 452 | // no leading zero. |
| 453 | func decimal(s string) (int64, bool) { |
| 454 | if s == "" || len(s) > 1 && s[0] == '0' || strings.TrimLeft(s, "0123456789") != "" { |
| 455 | return 0, false |
| 456 | } |
| 457 | n, err := strconv.ParseInt(s, 10, 64) |
| 458 | return n, err == nil |
| 459 | } |
| 460 | |
| 461 | // CheckExport holds export.json to the manifest: its bytes have the |
| 462 | // declared hash and size, it is a valid export, and it names the same |
| 463 | // projects with the same visibility and tips. It returns the export. |
| 464 | func (m *Manifest) CheckExport(data []byte) (*Export, error) { |
| 465 | if got := BodyOf(ExportFile, data); got != m.File { |
| 466 | 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) |
| 467 | } |
| 468 | e, err := Decode(data) |
| 469 | if err != nil { |
| 470 | return nil, refuse(CodeBadExport, "%v", err) |
| 471 | } |
| 472 | if len(e.Projects) != len(m.Projects) { |
| 473 | return nil, refuse(CodeBadExport, "export.json holds %d projects, and the manifest %d", len(e.Projects), len(m.Projects)) |
| 474 | } |
| 475 | for i, p := range e.Projects { |
| 476 | mp := m.Projects[i] |
| 477 | switch { |
| 478 | case p.Name != mp.Name: |
| 479 | return nil, refuse(CodeBadExport, "export.json holds project %s where the manifest has %s", p.Name, mp.Name) |
| 480 | case p.Visibility != mp.Visibility: |
| 481 | return nil, refuse(CodeBadExport, "project %s is %s in export.json and %s in the manifest", p.Name, p.Visibility, mp.Visibility) |
| 482 | case p.GraphTip != mp.GraphTip: |
| 483 | return nil, refuse(CodeBadExport, "project %s has graph tip %q in export.json and %q in the manifest", p.Name, p.GraphTip, mp.GraphTip) |
| 484 | case p.SourceTip != mp.SourceTip: |
| 485 | return nil, refuse(CodeBadExport, "project %s has source tip %s in export.json and %s in the manifest", p.Name, p.SourceTip, mp.SourceTip) |
| 486 | } |
| 487 | } |
| 488 | return e, nil |
| 489 | } |