gunk-dev/the-valley

main.go

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