gunk-dev/the-valley

main.go

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