gunk-dev/the-valley

main.go

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