| 1 | // valley-web-publish publishes a valley host's public projects to a web |
| 2 | // receiver: the projects anyone may read there. One run is one pass. It reads the valley through the CLI's JSON |
| 3 | // commands, projects what it read onto the public export (package export), |
| 4 | // signs a manifest for it, and uploads it by the protocol package export |
| 5 | // defines. The receiver never connects to the host; its replies are all the |
| 6 | // publisher hears from it. |
| 7 | // |
| 8 | // Before a pass, it reads the host declaration (--host): the groups, and |
| 9 | // each project's group and short aliases. A declaration whose names |
| 10 | // collide is refused, and no pass runs. |
| 11 | // |
| 12 | // Every pass runs the policy path first (policy.go), which alone writes |
| 13 | // authorizations. Under the authorization lock in the state directory, it |
| 14 | // reads the export key, or makes one on the first start; reads the |
| 15 | // instance's read grants and each selected project's policy/read, into |
| 16 | // caches of its own; allocates the next sequence from a durable counter; |
| 17 | // and signs an authorization that names each project anyone may read. It |
| 18 | // then sends the authorization to the receiver, outside the lock. It reads |
| 19 | // no plan and no knot, so no project's graph holds up a withdrawal. With |
| 20 | // --policy-only the pass ends there, and takes no other lock. |
| 21 | // |
| 22 | // The content pass then runs, in order: |
| 23 | // |
| 24 | // 1. take the lock in the state directory, so two content passes never |
| 25 | // overlap; |
| 26 | // 2. hold the state and the caches to --max-storage before anything is |
| 27 | // fetched; |
| 28 | // 3. fetch main, refs/the-valley/projects and --registry-ref of the |
| 29 | // instance repository into the publisher's own bare repository, whose |
| 30 | // origin it is, once for the whole pass, refuse a main that carries |
| 31 | // policy/valley, and read the read grants at --destination from the |
| 32 | // identity registry at the --registry-ref it fetched; |
| 33 | // 4. prepare the valley CLI's clone of each project a read grant to |
| 34 | // anyone names and that is in a group, and of no other, so the CLI |
| 35 | // reads no other project; |
| 36 | // 5. run valley plan --all --json and valley pending --all --json in the |
| 37 | // pointer repository, whose main names the instance repository at |
| 38 | // policy/valley, so they discover the projects and the signers through |
| 39 | // the instance repository's own publications and never read its main; |
| 40 | // and hold both listings to the project list it fetched. A project no |
| 41 | // grant names has no clone, so both list it as one they could not |
| 42 | // read, and the pass keeps it private; |
| 43 | // 6. for each of those projects, fetch main into a mirror under the |
| 44 | // cache and read the project's own policy/read there; |
| 45 | // 7. run valley knot show --project P <id> --json for every knot of every |
| 46 | // public project, in the publisher's repository, and build the export |
| 47 | // with export.Build, reading again when the inputs were read at |
| 48 | // different graph tips; then hold the state and the caches to |
| 49 | // --max-storage again; |
| 50 | // 8. bundle each public project's main, writing each bundle only into |
| 51 | // what --max-bundles and --max-storage leave; |
| 52 | // 9. upload it, unless the receiver acknowledged the same content digest |
| 53 | // less than --recheck ago and its reply to the authorization says it |
| 54 | // serves that digest with every repository the authorization names, |
| 55 | // or write it to --out instead. |
| 56 | // |
| 57 | // The export carries no visibility: a project is exported when anyone may |
| 58 | // read it, and the authorization alone says who may. A project is public |
| 59 | // when anyone may read it and it has a web URL: its |
| 60 | // own policy/read names anyone (schema/read.cue), a read grant to anyone at |
| 61 | // the destination covers it (schema/identity.cue), and the host declaration |
| 62 | // places it in a group. Package readaccess reads and evaluates the two |
| 63 | // consents. The export carries each public project's group and short |
| 64 | // aliases, and the groups public projects belong to. A policy or registry |
| 65 | // that is missing, or that its schema refuses, consents to nothing, so the |
| 66 | // project is private. A project a grant names |
| 67 | // that cannot be read fails the pass, which then sends nothing: an export |
| 68 | // without it would take it off the web. A project no grant names is |
| 69 | // private whether or not it can be read. |
| 70 | package main |
| 71 | |
| 72 | import ( |
| 73 | "context" |
| 74 | "crypto/ed25519" |
| 75 | "errors" |
| 76 | "flag" |
| 77 | "fmt" |
| 78 | "io" |
| 79 | "math" |
| 80 | "net/http" |
| 81 | "os" |
| 82 | "path/filepath" |
| 83 | "strconv" |
| 84 | "strings" |
| 85 | "time" |
| 86 | |
| 87 | "the-valley/readaccess" |
| 88 | "the-valley/web/export" |
| 89 | ) |
| 90 | |
| 91 | const usage = `usage: valley-web-publish --instance-repo URL --instance NAME --destination NAME |
| 92 | --host FILE (--receiver URL --receiver-token FILE | --out DIR) |
| 93 | [--principals FILE] |
| 94 | [--state DIR] [--read-schema FILE] |
| 95 | [--identity-schema FILE] [--registry-ref REF] |
| 96 | [--registry-dir DIR] [--recheck DURATION] |
| 97 | [--policy-only] |
| 98 | [--max-bundles SIZE] [--max-storage SIZE] |
| 99 | |
| 100 | One pass of the web publisher: check who may read each project and send |
| 101 | the receiver a signed authorization, then read the valley's public |
| 102 | projects and upload them to the receiver at URL, or write both to DIR. |
| 103 | |
| 104 | --instance-repo URL absolute local path to the instance repository |
| 105 | (used as origin of the publisher's cached bare |
| 106 | repository so the valley CLI discovers projects |
| 107 | and signers through it); its main must hold |
| 108 | policy/instance and no policy/valley; URL must |
| 109 | contain no #, control character, or leading or |
| 110 | trailing space |
| 111 | --instance NAME the instance the manifest names, and the export |
| 112 | key's signing name, NAME/web-export |
| 113 | --destination NAME the receiver the manifest is for, and the destination |
| 114 | of the edge read boundary whose read grants decide |
| 115 | what anyone may read there |
| 116 | --host FILE JSON host declaration from cue export under |
| 117 | schema/valley.cue, defining groups and each |
| 118 | project's group, web name, former names, and |
| 119 | aliases; colliding names are refused, and a |
| 120 | project in no group is private |
| 121 | --receiver URL the receiver's base URL, http or https; uploads |
| 122 | connect directly to URL and ignore HTTP_PROXY, |
| 123 | HTTPS_PROXY, and all other proxy settings |
| 124 | --receiver-token FILE |
| 125 | the receiver's token, which every request of an |
| 126 | upload carries in its Authorization header: one |
| 127 | line of 32 to 256 visible ASCII characters, the |
| 128 | same file the receiver's --token-file names; |
| 129 | required with --receiver |
| 130 | --out DIR write the export to DIR, which must not exist or be |
| 131 | empty, instead of uploading it: authorization, |
| 132 | manifest, export.json and bundles/<project>.bundle |
| 133 | --principals FILE the display mapping: a JSON object from each |
| 134 | principal's name to the name an export shows; a |
| 135 | name it does not map is shown as contributor |
| 136 | --state DIR the key, its verifier line, the locks, the |
| 137 | authorization counter, the last authorization |
| 138 | signed and the last acknowledgement (default |
| 139 | ${XDG_STATE_HOME:-$HOME/.local/state}/valley/web-publish) |
| 140 | --read-schema FILE schema/read.cue (default $VALLEY_READ_SCHEMA) |
| 141 | --identity-schema FILE |
| 142 | schema/identity.cue (default $VALLEY_IDENTITY_SCHEMA) |
| 143 | --registry-ref REF the ref of the instance repository whose tip carries |
| 144 | the identity registry, as the identity compiler |
| 145 | reads it: a full ref name (default refs/heads/main); |
| 146 | a pass reads the registry at the one commit it |
| 147 | fetched, and an instance repository with no REF |
| 148 | holds no registry, so every project is private |
| 149 | --registry-dir DIR the identity registry's directory in that commit |
| 150 | (default identity) |
| 151 | --recheck DURATION how long an acknowledgement is trusted: a pass whose |
| 152 | digest the receiver acknowledged less than this ago, |
| 153 | and that the receiver still serves whole, uploads no |
| 154 | content (default 1h) |
| 155 | --policy-only check the policy and send the authorization alone: |
| 156 | no plan, knot or bundle is read, and the content |
| 157 | pass's lock is not taken, so a stalled content pass |
| 158 | does not hold it up; needs --receiver |
| 159 | --max-bundles SIZE the most the bundles of one export may hold |
| 160 | together; a bundle is written only into what it |
| 161 | leaves, and a pass past it sends nothing |
| 162 | (default 1G) |
| 163 | --max-storage SIZE the most the state directory and the caches may |
| 164 | hold, checked before each repository cache write |
| 165 | and after collection; a bundle is written only into |
| 166 | what it leaves, and a pass past it sends nothing |
| 167 | (default 16G) |
| 168 | |
| 169 | A SIZE is a number of bytes, or a number with K, M, G or T for KiB, MiB, |
| 170 | GiB or TiB. |
| 171 | |
| 172 | The cache is $XDG_CACHE_HOME (default $HOME/.cache): the valley CLI's |
| 173 | clones under valley/, the publisher's repositories, mirrors and bundles |
| 174 | under valley-web-publish/.` |
| 175 | |
| 176 | func main() { |
| 177 | os.Exit(run(context.Background(), os.Args[1:], os.Stdout, os.Stderr)) |
| 178 | } |
| 179 | |
| 180 | func run(ctx context.Context, args []string, stdout, stderr io.Writer) int { |
| 181 | cfg, err := parseArgs(args) |
| 182 | if errors.Is(err, flag.ErrHelp) { |
| 183 | fmt.Fprintln(stdout, usage) |
| 184 | return 0 |
| 185 | } |
| 186 | if err != nil { |
| 187 | fmt.Fprintf(stderr, "valley-web-publish: %v\n%s\n", err, usage) |
| 188 | return 2 |
| 189 | } |
| 190 | p, err := newPublisher(cfg, stdout, stderr) |
| 191 | if err == nil { |
| 192 | err = p.pass(ctx) |
| 193 | } |
| 194 | if err != nil { |
| 195 | fmt.Fprintf(stderr, "valley-web-publish: %v\n", err) |
| 196 | return 1 |
| 197 | } |
| 198 | return 0 |
| 199 | } |
| 200 | |
| 201 | // config is a pass's flags. |
| 202 | type config struct { |
| 203 | instanceRepo string |
| 204 | instance string |
| 205 | destination string |
| 206 | host string |
| 207 | receiver string |
| 208 | token string |
| 209 | out string |
| 210 | principals string |
| 211 | state string |
| 212 | readSchema string |
| 213 | idSchema string |
| 214 | registryRef string |
| 215 | registryDir string |
| 216 | recheck time.Duration |
| 217 | policyOnly bool |
| 218 | maxBundles byteSize |
| 219 | maxStorage byteSize |
| 220 | } |
| 221 | |
| 222 | func parseArgs(args []string) (config, error) { |
| 223 | c := config{maxBundles: 1 << 30, maxStorage: 16 << 30} |
| 224 | fs := flag.NewFlagSet("valley-web-publish", flag.ContinueOnError) |
| 225 | fs.SetOutput(io.Discard) |
| 226 | fs.StringVar(&c.instanceRepo, "instance-repo", "", "") |
| 227 | fs.StringVar(&c.instance, "instance", "", "") |
| 228 | fs.StringVar(&c.destination, "destination", "", "") |
| 229 | fs.StringVar(&c.host, "host", "", "") |
| 230 | fs.StringVar(&c.receiver, "receiver", "", "") |
| 231 | fs.StringVar(&c.token, "receiver-token", "", "") |
| 232 | fs.StringVar(&c.out, "out", "", "") |
| 233 | fs.StringVar(&c.principals, "principals", "", "") |
| 234 | fs.StringVar(&c.state, "state", "", "") |
| 235 | fs.StringVar(&c.readSchema, "read-schema", os.Getenv("VALLEY_READ_SCHEMA"), "") |
| 236 | fs.StringVar(&c.idSchema, "identity-schema", os.Getenv("VALLEY_IDENTITY_SCHEMA"), "") |
| 237 | fs.StringVar(&c.registryRef, "registry-ref", "refs/heads/main", "") |
| 238 | fs.StringVar(&c.registryDir, "registry-dir", "identity", "") |
| 239 | fs.DurationVar(&c.recheck, "recheck", time.Hour, "") |
| 240 | fs.BoolVar(&c.policyOnly, "policy-only", false, "") |
| 241 | fs.Var(&c.maxBundles, "max-bundles", "") |
| 242 | fs.Var(&c.maxStorage, "max-storage", "") |
| 243 | if err := fs.Parse(args); err != nil { |
| 244 | return c, err |
| 245 | } |
| 246 | switch { |
| 247 | case fs.NArg() > 0: |
| 248 | return c, fmt.Errorf("unexpected argument %q", fs.Arg(0)) |
| 249 | case c.instanceRepo == "": |
| 250 | return c, errors.New("--instance-repo is required") |
| 251 | case strings.ContainsFunc(c.instanceRepo, func(r rune) bool { return r == '#' || r < 0x20 || r == 0x7f }), |
| 252 | strings.TrimSpace(c.instanceRepo) != c.instanceRepo: |
| 253 | // The pointer repository names it in policy/valley, which the CLI |
| 254 | // reads up to a # and without the spaces around it. |
| 255 | return c, fmt.Errorf("--instance-repo %q holds a #, a control character or a space at either end, which policy/valley cannot name", c.instanceRepo) |
| 256 | case !filepath.IsAbs(c.instanceRepo): |
| 257 | return c, errors.New("--instance-repo must be an absolute local path") |
| 258 | case !export.ValidName(c.instance): |
| 259 | return c, fmt.Errorf("--instance %q is not a name: it is 1 to 64 letters, digits, dots, dashes and underscores, opening with a letter or a digit", c.instance) |
| 260 | case !export.ValidName(c.destination): |
| 261 | return c, fmt.Errorf("--destination %q is not a name: it is 1 to 64 letters, digits, dots, dashes and underscores, opening with a letter or a digit", c.destination) |
| 262 | case c.host == "": |
| 263 | return c, errors.New("--host is required") |
| 264 | case (c.receiver == "") == (c.out == ""): |
| 265 | return c, errors.New("give exactly one of --receiver and --out") |
| 266 | case (c.receiver == "") != (c.token == ""): |
| 267 | return c, errors.New("--receiver-token goes with --receiver, and --receiver needs it") |
| 268 | case c.policyOnly && c.receiver == "": |
| 269 | return c, errors.New("--policy-only sends an authorization, so it needs --receiver") |
| 270 | case !readaccess.ValidRef(c.registryRef): |
| 271 | return c, fmt.Errorf("--registry-ref %q is not a full ref name: it opens with refs/, and git check-ref-format accepts it", c.registryRef) |
| 272 | case c.readSchema == "" || c.idSchema == "": |
| 273 | return c, errors.New("no schema: give --read-schema and --identity-schema, or set VALLEY_READ_SCHEMA and VALLEY_IDENTITY_SCHEMA") |
| 274 | case c.recheck < 0: |
| 275 | return c, errors.New("--recheck is negative; give a duration of zero or more") |
| 276 | } |
| 277 | if c.receiver != "" { |
| 278 | if err := checkReceiver(c.receiver); err != nil { |
| 279 | return c, err |
| 280 | } |
| 281 | } |
| 282 | if c.state == "" { |
| 283 | base := os.Getenv("XDG_STATE_HOME") |
| 284 | if base == "" { |
| 285 | home, err := os.UserHomeDir() |
| 286 | if err != nil { |
| 287 | return c, errors.New("no state directory: give --state, or set XDG_STATE_HOME or HOME") |
| 288 | } |
| 289 | base = filepath.Join(home, ".local", "state") |
| 290 | } |
| 291 | c.state = filepath.Join(base, "valley", "web-publish") |
| 292 | } |
| 293 | return c, nil |
| 294 | } |
| 295 | |
| 296 | // byteSize is a size flag's value in bytes. It is set from a number, or a |
| 297 | // number with K, M, G or T for 1024 to the first to fourth power, as |
| 298 | // systemd reads a size. |
| 299 | type byteSize int64 |
| 300 | |
| 301 | func (b *byteSize) Set(v string) error { |
| 302 | number, unit := v, int64(1) |
| 303 | if n := len(v); n > 1 { |
| 304 | if i := strings.IndexByte("KMGT", v[n-1]); i >= 0 { |
| 305 | number, unit = v[:n-1], 1<<(10*(i+1)) |
| 306 | } |
| 307 | } |
| 308 | x, err := strconv.ParseInt(number, 10, 64) |
| 309 | if err != nil || x <= 0 || x > math.MaxInt64/unit { |
| 310 | return fmt.Errorf("%q is not a size: a positive number of bytes, or one with K, M, G or T", v) |
| 311 | } |
| 312 | *b = byteSize(x * unit) |
| 313 | return nil |
| 314 | } |
| 315 | |
| 316 | func (b *byteSize) String() string { return strconv.FormatInt(int64(*b), 10) } |
| 317 | |
| 318 | // publisher is one pass's configuration and what it reads and writes |
| 319 | // through: its state and cache directories, its key, the receiver, and |
| 320 | // the clock. |
| 321 | type publisher struct { |
| 322 | cfg config |
| 323 | stdout, stderr io.Writer |
| 324 | |
| 325 | // cache is the publisher's own cache, under $XDG_CACHE_HOME. origin is |
| 326 | // its bare repository, whose origin is the instance repository. pointer |
| 327 | // is the repository whose main names the instance repository at |
| 328 | // policy/valley (preparePointer); the CLI calls it _pointer, which is |
| 329 | // no project's name. |
| 330 | collectionRoom int64 |
| 331 | cache string |
| 332 | origin string |
| 333 | pointer string |
| 334 | // mirrors holds a mirror of each project's main that a pass reads. |
| 335 | // The policy path has its own origin and mirrors. |
| 336 | mirrors string |
| 337 | // signedAuthorization is the authorization the policy path signed, |
| 338 | // which --out writes beside the export. |
| 339 | signedAuthorization []byte |
| 340 | |
| 341 | principals export.Principals |
| 342 | places webPlaces |
| 343 | signer string |
| 344 | key ed25519.PrivateKey |
| 345 | // token is the receiver's token, or "" with --out. |
| 346 | token string |
| 347 | |
| 348 | // access reads the two consents to read access. |
| 349 | access readaccess.Reader |
| 350 | |
| 351 | client *http.Client |
| 352 | now func() time.Time |
| 353 | sleep func(context.Context, time.Duration) error |
| 354 | } |
| 355 | |
| 356 | func newPublisher(cfg config, stdout, stderr io.Writer) (*publisher, error) { |
| 357 | base := os.Getenv("XDG_CACHE_HOME") |
| 358 | if base == "" { |
| 359 | home, err := os.UserHomeDir() |
| 360 | if err != nil { |
| 361 | return nil, errors.New("no cache directory: set XDG_CACHE_HOME or HOME") |
| 362 | } |
| 363 | base = filepath.Join(home, ".cache") |
| 364 | } |
| 365 | if !filepath.IsAbs(base) { |
| 366 | return nil, fmt.Errorf("XDG_CACHE_HOME is %q, which is not an absolute path", base) |
| 367 | } |
| 368 | principals, err := readPrincipals(cfg.principals) |
| 369 | if err != nil { |
| 370 | return nil, err |
| 371 | } |
| 372 | places, err := readHost(cfg.host) |
| 373 | if err != nil { |
| 374 | return nil, err |
| 375 | } |
| 376 | var token string |
| 377 | if cfg.token != "" { |
| 378 | if token, err = export.ReadToken(cfg.token); err != nil { |
| 379 | return nil, fmt.Errorf("--receiver-token: %w", err) |
| 380 | } |
| 381 | } |
| 382 | cache := filepath.Join(base, "valley-web-publish") |
| 383 | return &publisher{ |
| 384 | cfg: cfg, stdout: stdout, stderr: stderr, |
| 385 | cache: cache, origin: filepath.Join(cache, "origin.git"), pointer: filepath.Join(cache, "_pointer.git"), |
| 386 | mirrors: filepath.Join(cache, "repos"), |
| 387 | principals: principals, |
| 388 | places: places, |
| 389 | token: token, |
| 390 | signer: cfg.instance + "/web-export", |
| 391 | access: readaccess.Reader{ReadSchema: cfg.readSchema, IdentitySchema: cfg.idSchema, CueTimeout: cueTimeout}, |
| 392 | client: newClient(), |
| 393 | now: time.Now, |
| 394 | sleep: sleepContext, |
| 395 | }, nil |
| 396 | } |
| 397 | |
| 398 | // pass is one run of the publisher: the policy path, and then, unless |
| 399 | // --policy-only is given, the content pass. The policy path sends an |
| 400 | // authorization before any content work starts, so no failure of the |
| 401 | // content pass holds up a withdrawal. An incomplete policy check sends its |
| 402 | // authorization and then fails the pass before any content work. |
| 403 | func (p *publisher) pass(ctx context.Context) error { |
| 404 | if err := os.MkdirAll(p.cfg.state, 0o700); err != nil { |
| 405 | return err |
| 406 | } |
| 407 | reply, err := p.authorize(ctx) |
| 408 | if err != nil || p.cfg.policyOnly { |
| 409 | return err |
| 410 | } |
| 411 | unlock, err := lockFile(filepath.Join(p.cfg.state, "lock")) |
| 412 | if err != nil { |
| 413 | return err |
| 414 | } |
| 415 | defer unlock() |
| 416 | if err := p.checkStorage(); err != nil { |
| 417 | return err |
| 418 | } |
| 419 | read, err := p.collect(ctx) |
| 420 | if err != nil { |
| 421 | return err |
| 422 | } |
| 423 | if err := p.checkStorage(); err != nil { |
| 424 | return err |
| 425 | } |
| 426 | digest, err := read.export.Digest() |
| 427 | if err != nil { |
| 428 | return err |
| 429 | } |
| 430 | p.sayVisibility(read) |
| 431 | if p.cfg.out != "" { |
| 432 | return p.writeOut(ctx, read) |
| 433 | } |
| 434 | ack, err := p.readAcknowledged() |
| 435 | if err != nil { |
| 436 | return err |
| 437 | } |
| 438 | if ack.covers(p.cfg, digest, p.now(), p.cfg.recheck) && reply.Serves(digest) { |
| 439 | p.say("the receiver acknowledged digest %s at %s, and nothing has changed since; nothing is sent", short(digest), ack.At) |
| 440 | return nil |
| 441 | } |
| 442 | return p.upload(ctx, read, digest, ack) |
| 443 | } |
| 444 | |
| 445 | // sayVisibility says which projects this pass exports, and which it keeps |
| 446 | // private. |
| 447 | func (p *publisher) sayVisibility(r *reading) { |
| 448 | var public []string |
| 449 | for _, proj := range r.export.Projects { |
| 450 | public = append(public, proj.Name) |
| 451 | } |
| 452 | p.say("public: %s; private: %s", listNames(public), listNames(r.private)) |
| 453 | } |
| 454 | |
| 455 | func (p *publisher) say(format string, args ...any) { |
| 456 | fmt.Fprintf(p.stdout, "valley-web-publish: "+format+"\n", args...) |
| 457 | } |
| 458 | |
| 459 | func (p *publisher) warn(format string, args ...any) { |
| 460 | fmt.Fprintf(p.stderr, "valley-web-publish: "+format+"\n", args...) |
| 461 | } |
| 462 | |
| 463 | // short is the first twelve characters of a digest or an object ID, for |
| 464 | // messages. |
| 465 | func short(s string) string { |
| 466 | if len(s) > 12 { |
| 467 | return s[:12] |
| 468 | } |
| 469 | return s |
| 470 | } |
| 471 | |
| 472 | func sleepContext(ctx context.Context, d time.Duration) error { |
| 473 | t := time.NewTimer(d) |
| 474 | defer t.Stop() |
| 475 | select { |
| 476 | case <-ctx.Done(): |
| 477 | return ctx.Err() |
| 478 | case <-t.C: |
| 479 | return nil |
| 480 | } |
| 481 | } |