gunk-dev/the-valley

main.go

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