gunk-dev/the-valley

main.go

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