gunk-dev/the-valley

main.go

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