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