gunk-dev/the-valley

main.go

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