gunk-dev/the-valley

main.go

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