gunk-dev/the-valley

main.go

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