gunk-dev/the-valley

main.go

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