gunk-dev/the-valley

main.go

sourcec374b23ad1f3main's published tip history
19.4 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.
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.
70package main
71
72import (
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
91const 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
100One pass of the web publisher: check who may read each project and send
101the receiver a signed authorization, then read the valley's public
102projects 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 authorization and export to DIR, which
131 must not exist or must be empty, instead of
132 uploading: authorization, manifest, export.json,
133 and bundles/<project>.bundle
134 --principals FILE the display mapping: a JSON object from each
135 principal's name to the name an export shows; a
136 name it does not map is shown as contributor
137 --state DIR state directory holding the key, its verifier line,
138 the locks, the authorization counter, the last
139 signed authorization, and the last acknowledgement
140 (default
141 ${XDG_STATE_HOME:-$HOME/.local/state}/valley/web-publish)
142 --read-schema FILE schema/read.cue (default $VALLEY_READ_SCHEMA)
143 --identity-schema FILE
144 schema/identity.cue (default $VALLEY_IDENTITY_SCHEMA)
145 --registry-ref REF the ref of the instance repository whose tip carries
146 the identity registry, as the identity compiler
147 reads it: a full ref name (default refs/heads/main);
148 a pass reads the registry at the one commit it
149 fetched, and an instance repository with no REF
150 holds no registry, so every project is private
151 --registry-dir DIR the identity registry's directory in that commit
152 (default identity)
153 --recheck DURATION how long an acknowledgement is trusted: a pass skips
154 uploading content when the receiver acknowledged the
155 same digest within DURATION and still serves it in
156 full (default 1h)
157 --policy-only run only the policy path: check the policy and send
158 the authorization without reading plans, knots, or
159 bundles or taking the content lock; requires
160 --receiver
161 --max-bundles SIZE the most the bundles of one export may hold
162 together; a bundle is written only into what it
163 leaves, and a pass past it sends nothing
164 (default 1G)
165 --max-storage SIZE the most the state directory and the caches may
166 hold, checked before each repository cache write
167 and after collection; a bundle is written only into
168 what it leaves, and a pass past it sends nothing
169 (default 16G)
170
171A SIZE is a number of bytes, or a number with K, M, G or T for KiB, MiB,
172GiB or TiB.
173
174The cache is $XDG_CACHE_HOME (default $HOME/.cache): the valley CLI's
175clones under valley/, the publisher's repositories, mirrors and bundles
176under valley-web-publish/.`
177
178func main() {
179 os.Exit(run(context.Background(), os.Args[1:], os.Stdout, os.Stderr))
180}
181
182func run(ctx context.Context, args []string, stdout, stderr io.Writer) int {
183 cfg, err := parseArgs(args)
184 if errors.Is(err, flag.ErrHelp) {
185 fmt.Fprintln(stdout, usage)
186 return 0
187 }
188 if err != nil {
189 fmt.Fprintf(stderr, "valley-web-publish: %v\n%s\n", err, usage)
190 return 2
191 }
192 p, err := newPublisher(cfg, stdout, stderr)
193 if err == nil {
194 err = p.pass(ctx)
195 }
196 if err != nil {
197 fmt.Fprintf(stderr, "valley-web-publish: %v\n", err)
198 return 1
199 }
200 return 0
201}
202
203// config is a pass's flags.
204type config struct {
205 instanceRepo string
206 instance string
207 destination string
208 host string
209 receiver string
210 token string
211 out string
212 principals string
213 state string
214 readSchema string
215 idSchema string
216 registryRef string
217 registryDir string
218 recheck time.Duration
219 policyOnly bool
220 maxBundles byteSize
221 maxStorage byteSize
222}
223
224func parseArgs(args []string) (config, error) {
225 c := config{maxBundles: 1 << 30, maxStorage: 16 << 30}
226 fs := flag.NewFlagSet("valley-web-publish", flag.ContinueOnError)
227 fs.SetOutput(io.Discard)
228 fs.StringVar(&c.instanceRepo, "instance-repo", "", "")
229 fs.StringVar(&c.instance, "instance", "", "")
230 fs.StringVar(&c.destination, "destination", "", "")
231 fs.StringVar(&c.host, "host", "", "")
232 fs.StringVar(&c.receiver, "receiver", "", "")
233 fs.StringVar(&c.token, "receiver-token", "", "")
234 fs.StringVar(&c.out, "out", "", "")
235 fs.StringVar(&c.principals, "principals", "", "")
236 fs.StringVar(&c.state, "state", "", "")
237 fs.StringVar(&c.readSchema, "read-schema", os.Getenv("VALLEY_READ_SCHEMA"), "")
238 fs.StringVar(&c.idSchema, "identity-schema", os.Getenv("VALLEY_IDENTITY_SCHEMA"), "")
239 fs.StringVar(&c.registryRef, "registry-ref", "refs/heads/main", "")
240 fs.StringVar(&c.registryDir, "registry-dir", "identity", "")
241 fs.DurationVar(&c.recheck, "recheck", time.Hour, "")
242 fs.BoolVar(&c.policyOnly, "policy-only", false, "")
243 fs.Var(&c.maxBundles, "max-bundles", "")
244 fs.Var(&c.maxStorage, "max-storage", "")
245 if err := fs.Parse(args); err != nil {
246 return c, err
247 }
248 switch {
249 case fs.NArg() > 0:
250 return c, fmt.Errorf("unexpected argument %q", fs.Arg(0))
251 case c.instanceRepo == "":
252 return c, errors.New("--instance-repo is required")
253 case strings.ContainsFunc(c.instanceRepo, func(r rune) bool { return r == '#' || r < 0x20 || r == 0x7f }),
254 strings.TrimSpace(c.instanceRepo) != c.instanceRepo:
255 // The pointer repository names it in policy/valley, which the CLI
256 // reads up to a # and without the spaces around it.
257 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)
258 case !filepath.IsAbs(c.instanceRepo):
259 return c, errors.New("--instance-repo must be an absolute local path")
260 case !export.ValidName(c.instance):
261 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)
262 case !export.ValidName(c.destination):
263 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)
264 case c.host == "":
265 return c, errors.New("--host is required")
266 case (c.receiver == "") == (c.out == ""):
267 return c, errors.New("give exactly one of --receiver and --out")
268 case (c.receiver == "") != (c.token == ""):
269 return c, errors.New("--receiver-token goes with --receiver, and --receiver needs it")
270 case c.policyOnly && c.receiver == "":
271 return c, errors.New("--policy-only requires --receiver")
272 case !readaccess.ValidRef(c.registryRef):
273 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)
274 case c.readSchema == "" || c.idSchema == "":
275 return c, errors.New("no schema: give --read-schema and --identity-schema, or set VALLEY_READ_SCHEMA and VALLEY_IDENTITY_SCHEMA")
276 case c.recheck < 0:
277 return c, errors.New("--recheck is negative; give a duration of zero or more")
278 }
279 if c.receiver != "" {
280 if err := checkReceiver(c.receiver); err != nil {
281 return c, err
282 }
283 }
284 if c.state == "" {
285 base := os.Getenv("XDG_STATE_HOME")
286 if base == "" {
287 home, err := os.UserHomeDir()
288 if err != nil {
289 return c, errors.New("no state directory: give --state, or set XDG_STATE_HOME or HOME")
290 }
291 base = filepath.Join(home, ".local", "state")
292 }
293 c.state = filepath.Join(base, "valley", "web-publish")
294 }
295 return c, nil
296}
297
298// byteSize is a size flag's value in bytes. It is set from a number, or a
299// number with K, M, G or T for 1024 to the first to fourth power, as
300// systemd reads a size.
301type byteSize int64
302
303func (b *byteSize) Set(v string) error {
304 number, unit := v, int64(1)
305 if n := len(v); n > 1 {
306 if i := strings.IndexByte("KMGT", v[n-1]); i >= 0 {
307 number, unit = v[:n-1], 1<<(10*(i+1))
308 }
309 }
310 x, err := strconv.ParseInt(number, 10, 64)
311 if err != nil || x <= 0 || x > math.MaxInt64/unit {
312 return fmt.Errorf("%q is not a size: a positive number of bytes, or one with K, M, G or T", v)
313 }
314 *b = byteSize(x * unit)
315 return nil
316}
317
318func (b *byteSize) String() string { return strconv.FormatInt(int64(*b), 10) }
319
320// publisher is one pass's configuration and what it reads and writes
321// through: its state and cache directories, its key, the receiver, and
322// the clock.
323type publisher struct {
324 cfg config
325 stdout, stderr io.Writer
326
327 // cache is the publisher's own cache, under $XDG_CACHE_HOME. origin is
328 // its bare repository, whose origin is the instance repository. pointer
329 // is the repository whose main names the instance repository at
330 // policy/valley (preparePointer); the CLI calls it _pointer, which is
331 // no project's name.
332 collectionRoom int64
333 cache string
334 origin string
335 pointer string
336 // mirrors holds a mirror of each project's main that a pass reads.
337 // The policy path has its own origin and mirrors.
338 mirrors string
339 // signedAuthorization is the authorization the policy path signed,
340 // which --out writes beside the export.
341 signedAuthorization []byte
342
343 principals export.Principals
344 places webPlaces
345 signer string
346 key ed25519.PrivateKey
347 // token is the receiver's token, or "" with --out.
348 token string
349
350 // access reads the two consents to read access.
351 access readaccess.Reader
352
353 client *http.Client
354 now func() time.Time
355 sleep func(context.Context, time.Duration) error
356}
357
358func newPublisher(cfg config, stdout, stderr io.Writer) (*publisher, error) {
359 base := os.Getenv("XDG_CACHE_HOME")
360 if base == "" {
361 home, err := os.UserHomeDir()
362 if err != nil {
363 return nil, errors.New("no cache directory: set XDG_CACHE_HOME or HOME")
364 }
365 base = filepath.Join(home, ".cache")
366 }
367 if !filepath.IsAbs(base) {
368 return nil, fmt.Errorf("XDG_CACHE_HOME is %q, which is not an absolute path", base)
369 }
370 principals, err := readPrincipals(cfg.principals)
371 if err != nil {
372 return nil, err
373 }
374 places, err := readHost(cfg.host)
375 if err != nil {
376 return nil, err
377 }
378 var token string
379 if cfg.token != "" {
380 if token, err = export.ReadToken(cfg.token); err != nil {
381 return nil, fmt.Errorf("--receiver-token: %w", err)
382 }
383 }
384 cache := filepath.Join(base, "valley-web-publish")
385 return &publisher{
386 cfg: cfg, stdout: stdout, stderr: stderr,
387 cache: cache, origin: filepath.Join(cache, "origin.git"), pointer: filepath.Join(cache, "_pointer.git"),
388 mirrors: filepath.Join(cache, "repos"),
389 principals: principals,
390 places: places,
391 token: token,
392 signer: cfg.instance + "/web-export",
393 access: readaccess.Reader{ReadSchema: cfg.readSchema, IdentitySchema: cfg.idSchema, CueTimeout: cueTimeout},
394 client: newClient(),
395 now: time.Now,
396 sleep: sleepContext,
397 }, nil
398}
399
400// pass is one run of the publisher: the policy path, and then, unless
401// --policy-only is given, the content pass. The policy path sends an
402// authorization before any content work starts, so no failure of the
403// content pass holds up a withdrawal. An incomplete policy check sends its
404// authorization and then fails the pass before any content work.
405func (p *publisher) pass(ctx context.Context) error {
406 if err := os.MkdirAll(p.cfg.state, 0o700); err != nil {
407 return err
408 }
409 reply, err := p.authorize(ctx)
410 if err != nil || p.cfg.policyOnly {
411 return err
412 }
413 unlock, err := lockFile(filepath.Join(p.cfg.state, "lock"))
414 if err != nil {
415 return err
416 }
417 defer unlock()
418 if err := p.checkStorage(); err != nil {
419 return err
420 }
421 read, err := p.collect(ctx)
422 if err != nil {
423 return err
424 }
425 if err := p.checkStorage(); err != nil {
426 return err
427 }
428 digest, err := read.export.Digest()
429 if err != nil {
430 return err
431 }
432 p.sayVisibility(read)
433 if p.cfg.out != "" {
434 return p.writeOut(ctx, read)
435 }
436 ack, err := p.readAcknowledged()
437 if err != nil {
438 return err
439 }
440 if ack.covers(p.cfg, digest, p.now(), p.cfg.recheck) && reply.Serves(digest) {
441 p.say("the receiver acknowledged digest %s at %s, and nothing has changed since; nothing is sent", short(digest), ack.At)
442 return nil
443 }
444 return p.upload(ctx, read, digest, ack)
445}
446
447// sayVisibility says which projects this pass exports, and which it keeps
448// private.
449func (p *publisher) sayVisibility(r *reading) {
450 var public []string
451 for _, proj := range r.export.Projects {
452 public = append(public, proj.Name)
453 }
454 p.say("public: %s; private: %s", listNames(public), listNames(r.private))
455}
456
457func (p *publisher) say(format string, args ...any) {
458 fmt.Fprintf(p.stdout, "valley-web-publish: "+format+"\n", args...)
459}
460
461func (p *publisher) warn(format string, args ...any) {
462 fmt.Fprintf(p.stderr, "valley-web-publish: "+format+"\n", args...)
463}
464
465// short is the first twelve characters of a digest or an object ID, for
466// messages.
467func short(s string) string {
468 if len(s) > 12 {
469 return s[:12]
470 }
471 return s
472}
473
474func sleepContext(ctx context.Context, d time.Duration) error {
475 t := time.NewTimer(d)
476 defer t.Stop()
477 select {
478 case <-ctx.Done():
479 return ctx.Err()
480 case <-t.C:
481 return nil
482 }
483}