gunk-dev/the-valley

valley.go

sourcef5567cb33daemain's published tip history
23.8 KiB
1package main
2
3import (
4 "bytes"
5 "compress/zlib"
6 "context"
7 "crypto/sha1"
8 "crypto/sha256"
9 "encoding/hex"
10 "encoding/json"
11 "errors"
12 "fmt"
13 "io"
14 "os"
15 "os/exec"
16 "path/filepath"
17 "slices"
18 "sort"
19 "strings"
20
21 "the-valley/webui/export"
22)
23
24// readAttempts is how many times a pass reads the valley before it gives
25// up on inputs that keep changing under it.
26const readAttempts = 3
27
28// The bounds on what a pass holds of a program's output. A program that
29// prints more than its bound to stdout fails, and what it prints to stderr
30// past its bound is dropped.
31const (
32 maxValleyOutput = 64 << 20
33 maxGitOutput = 4 << 20
34 maxStderr = 64 << 10
35)
36
37// reading is what a pass read: the export, each exported project's mirror,
38// and the projects it keeps private.
39type reading struct {
40 export *export.Export
41 json []byte
42 mirrors map[string]string
43 private []string
44}
45
46// collect reads the valley and builds the export. It fetches the instance
47// repository once, and every read of the pass reads the instance at that
48// fetch. Each knot's detail is read after the plan, so a write to the graph
49// in between makes the two disagree; export.Build says so with
50// ErrInconsistent, and collect reads everything again.
51func (p *publisher) collect(ctx context.Context) (*reading, error) {
52 if err := checkSchema(ctx, p.cfg.schema); err != nil {
53 return nil, err
54 }
55 inst, err := p.fetchInstance(ctx)
56 if err != nil {
57 return nil, err
58 }
59 if err := p.prepareCLICaches(ctx, inst.projects); err != nil {
60 return nil, err
61 }
62 if err := p.preparePointer(ctx); err != nil {
63 return nil, err
64 }
65 for attempt := 1; attempt <= readAttempts; attempt++ {
66 var r *reading
67 r, err = p.read(ctx, inst)
68 if err == nil {
69 return r, nil
70 }
71 if !errors.Is(err, export.ErrInconsistent) {
72 return nil, err
73 }
74 p.warn("%v; reading the valley again", err)
75 }
76 return nil, fmt.Errorf("the valley changed under every one of %d reads: %w", readAttempts, err)
77}
78
79// planListing and pendingListing are what the publisher reads of the
80// valley's JSON itself: which projects there are, each project's knots,
81// and where each can be read. export.Build reads the rest.
82type (
83 planListing struct {
84 Projects []struct {
85 Project string `json:"project"`
86 Knots []struct {
87 ID string `json:"id"`
88 } `json:"knots"`
89 } `json:"projects"`
90 }
91 pendingListing struct {
92 Repos []pendingRepo `json:"repos"`
93 }
94 pendingRepo struct {
95 Repo string `json:"repo"`
96 URL string `json:"url"`
97 Error *string `json:"error"`
98 }
99)
100
101// read is one read of the valley, with the instance as fetchInstance read
102// it. A project is private when the instance does not allow it, or when its
103// own declaration is missing, invalid or private. Any other failure to read
104// a project the instance allows ends the pass: an export without it would
105// take it off the web.
106func (p *publisher) read(ctx context.Context, inst instanceRead) (*reading, error) {
107 allowed := map[string]bool{}
108 decl, err := readDeclaration(ctx, p.origin, inst.tip, p.cfg.schema)
109 var bad *invalidDeclaration
110 switch {
111 case errors.Is(err, errNoDeclaration):
112 case errors.As(err, &bad):
113 p.warn("the instance's policy/web at %s is not a valid declaration, so every project is private: %v", short(inst.tip), err)
114 case err != nil:
115 return nil, fmt.Errorf("could not read the instance's policy/web at %s: %w", short(inst.tip), err)
116 case decl.Instance != nil:
117 for name, d := range decl.Instance.Projects {
118 allowed[name] = d.Visibility == string(export.Public)
119 }
120 }
121
122 planJSON, err := p.valley(ctx, p.pointer, "plan", "--all", "--json")
123 if err != nil {
124 return nil, err
125 }
126 pendingJSON, err := p.valley(ctx, p.pointer, "pending", "--all", "--json")
127 if err != nil {
128 return nil, err
129 }
130 var plan planListing
131 if err := json.Unmarshal(planJSON, &plan); err != nil {
132 return nil, fmt.Errorf("valley plan --all --json: %w", err)
133 }
134 var pending pendingListing
135 if err := json.Unmarshal(pendingJSON, &pending); err != nil {
136 return nil, fmt.Errorf("valley pending --all --json: %w", err)
137 }
138 // The CLI lists what the instance repository publishes, and nothing
139 // else. When discovery fails it lists the repository it runs in alone,
140 // which would publish an export without the other projects.
141 var planned, listed []string
142 for _, proj := range plan.Projects {
143 planned = append(planned, proj.Project)
144 }
145 repos := map[string]pendingRepo{}
146 for _, r := range pending.Repos {
147 listed = append(listed, r.Repo)
148 repos[r.Repo] = r
149 }
150 for _, l := range []struct {
151 command string
152 names []string
153 }{{"valley plan --all", planned}, {"valley pending --all", listed}} {
154 sort.Strings(l.names)
155 if !slices.Equal(l.names, inst.projects) {
156 return nil, fmt.Errorf("%s lists %s, and the instance repository publishes %s at %s, so nothing is published",
157 l.command, listNames(l.names), listNames(inst.projects), projectsRef)
158 }
159 }
160
161 r := &reading{mirrors: map[string]string{}}
162 in := export.Inputs{
163 Plan: planJSON, Pending: pendingJSON,
164 Visibility: map[string]export.Visibility{}, SourceTips: map[string]string{},
165 Principals: p.principals,
166 }
167 for _, proj := range plan.Projects {
168 name := proj.Project
169 public := false
170 if allowed[name] {
171 if public, err = p.projectVisibility(ctx, name, repos[name], in.SourceTips, r.mirrors); err != nil {
172 return nil, err
173 }
174 }
175 if !public {
176 r.private = append(r.private, name)
177 continue
178 }
179 in.Visibility[name] = export.Public
180 for _, k := range proj.Knots {
181 detail, err := p.valley(ctx, p.origin, "knot", "show", "--project", name, k.ID, "--json")
182 if err != nil {
183 return nil, err
184 }
185 in.Details = append(in.Details, detail)
186 }
187 }
188 sort.Strings(r.private)
189 if r.export, err = export.Build(in); err != nil {
190 return nil, err
191 }
192 if r.json, err = r.export.Encode(); err != nil {
193 return nil, err
194 }
195 return r, nil
196}
197
198// listNames is a list of projects for a message.
199func listNames(list []string) string {
200 if len(list) == 0 {
201 return "none"
202 }
203 return strings.Join(list, ", ")
204}
205
206// projectVisibility decides whether a project the instance allows is
207// public: its own policy/web on main says public. For a public project it
208// records main's tip and the mirror it was fetched into. A project with no
209// main, or whose declaration is missing, invalid or private, is private,
210// and an invalid declaration is said. A project that cannot be read is an
211// error.
212func (p *publisher) projectVisibility(ctx context.Context, name string, repo pendingRepo,
213 tips, mirrors map[string]string) (bool, error) {
214 if !export.ValidName(name) {
215 p.warn("%q is not a project name, so it is private", name)
216 return false, nil
217 }
218 if repo.Error != nil {
219 return false, fmt.Errorf("%s: the pending listing could not read it: %s", name, *repo.Error)
220 }
221 if repo.URL == "" {
222 return false, fmt.Errorf("%s: the pending listing gives no URL to read it from", name)
223 }
224 mirror, tip, err := p.fetchMain(ctx, name, repo.URL)
225 if errors.Is(err, errNoMain) {
226 return false, nil
227 }
228 if err != nil {
229 return false, fmt.Errorf("%s: could not read main: %w", name, err)
230 }
231 decl, err := readDeclaration(ctx, mirror, tip, p.cfg.schema)
232 var bad *invalidDeclaration
233 switch {
234 case errors.Is(err, errNoDeclaration):
235 return false, nil
236 case errors.As(err, &bad):
237 p.warn("%s: its policy/web at %s is not a valid declaration, so it is private: %v", name, short(tip), err)
238 return false, nil
239 case err != nil:
240 return false, fmt.Errorf("%s: could not read its policy/web at %s: %w", name, short(tip), err)
241 case decl.Project == nil || decl.Project.Visibility != string(export.Public):
242 return false, nil
243 }
244 tips[name], mirrors[name] = tip, mirror
245 return true, nil
246}
247
248// preparePointer makes the repository valley plan and valley pending run
249// in: a bare repository whose origin is itself, and whose main holds one
250// file, policy/valley, naming the instance repository. The CLI finds the
251// instance at policy/valley on origin's main, as it does from any project,
252// and follows it no further. So it reads the projects and the signers the
253// instance repository publishes, and never reads the instance repository's
254// main, where a policy/valley could land and be taken away again while the
255// pass reads. Only the publisher writes to this repository, and main's
256// commit is the same in every pass for the same --instance-repo.
257func (p *publisher) preparePointer(ctx context.Context) error {
258 files, err := sharedFiles(ctx, p.cfg.instanceRepo, nil)
259 if err != nil {
260 return err
261 }
262 // Build the four small Git objects in memory so their compressed sizes
263 // are known before any cache file is written.
264 object := func(kind string, data []byte) []byte {
265 raw := append([]byte(fmt.Sprintf("%s %d\x00", kind, len(data))), data...)
266 h := sha1.New()
267 if strings.Contains(files["config"], "objectformat = sha256") {
268 h = sha256.New()
269 }
270 h.Write(raw)
271 digest := h.Sum(nil)
272 name := hex.EncodeToString(digest)
273 var compressed bytes.Buffer
274 w := zlib.NewWriter(&compressed)
275 _, _ = w.Write(raw)
276 _ = w.Close()
277 files["objects/"+name[:2]+"/"+name[2:]] = compressed.String()
278 return digest
279 }
280 blob := object("blob", []byte(p.cfg.instanceRepo+"\n"))
281 policy := object("tree", append([]byte("100644 valley\x00"), blob...))
282 tree := object("tree", append([]byte("40000 policy\x00"), policy...))
283 commit := object("commit", []byte(fmt.Sprintf("tree %x\nauthor valley-web-publish <operator@example.org> 0 +0000\ncommitter valley-web-publish <operator@example.org> 0 +0000\n\npolicy/valley: the instance the publisher reads\n", tree)))
284 files["refs/heads/main"] = hex.EncodeToString(commit) + "\n"
285 files["config"] = strings.Replace(files["config"], quoteGit(p.cfg.instanceRepo), quoteGit(p.pointer), 1)
286 return p.stageFiles(p.pointer, files)
287}
288
289// prepareCLICaches uses the CLI's URL hash and .git layout (status/list.go).
290// Both the project and instance objects are borrowed: the CLI reads the
291// instance's signers while inspecting each project's records.
292func (p *publisher) prepareCLICaches(ctx context.Context, names []string) error {
293 instance, err := sharedFiles(ctx, p.cfg.instanceRepo, nil)
294 if err != nil {
295 return err
296 }
297 for _, name := range names {
298 if !export.ValidName(name) {
299 return fmt.Errorf("invalid project name %q", name)
300 }
301 u := strings.TrimRight(p.cfg.instanceRepo, "/")
302 cut := strings.LastIndex(u, "/") + 1
303 suffix := ""
304 if strings.HasSuffix(u[cut:], ".git") {
305 suffix = ".git"
306 }
307 url := u[:cut] + name + suffix
308 files, err := sharedFiles(ctx, url, nil)
309 if err != nil {
310 return fmt.Errorf("%s: could not prepare CLI cache: %w", name, err)
311 }
312 files["config"] = strings.Replace(files["config"], "bare = true", "bare = false", 1) + "[core]\n\tlogallrefupdates = false\n"
313 files["objects/info/alternates"] += instance["objects/info/alternates"]
314 wrapped := map[string]string{}
315 for path, data := range files {
316 wrapped[".git/"+path] = data
317 }
318 sum := sha256.Sum256([]byte(url))
319 dir := filepath.Join(filepath.Dir(p.cache), "valley", "repos", hex.EncodeToString(sum[:8])+"-"+name)
320 if err := p.stageFiles(dir, wrapped); err != nil {
321 return err
322 }
323 }
324 // Each CLI cache can write main and its lock file. Leave room for
325 // those bounded metadata writes before invoking any collection command.
326 p.collectionRoom = int64(len(names)+1) * 4096
327 return p.reserveStorage(p.collectionRoom)
328}
329
330// The instance repository's project list, and where the publisher's
331// repository keeps what it fetched of the instance.
332const (
333 projectsRef = "refs/the-valley/projects"
334 originMain = "refs/remotes/origin/main"
335 originProjects = "refs/remotes/origin/projects"
336)
337
338// instanceRead is the instance repository as a pass found it: main's tip,
339// the project list it publishes, and the projects that list names.
340type instanceRead struct {
341 tip, list string
342 projects []string
343}
344
345// fetchInstance fetches the instance repository's main and its project
346// list into the publisher's repository, once a pass. A repository whose
347// main carries no policy/instance is not an instance repository. One whose
348// main carries policy/valley is refused too: it names another instance as
349// its own.
350func (p *publisher) fetchInstance(ctx context.Context) (instanceRead, error) {
351 var r instanceRead
352 if err := p.shareRepository(ctx, p.origin, p.cfg.instanceRepo, map[string]string{
353 originMain: "refs/heads/main", originProjects: projectsRef,
354 }); err != nil {
355 return r, fmt.Errorf("could not read main and %s in the instance repository: %w", projectsRef, err)
356 }
357 var err error
358 if r.tip, err = revParse(ctx, p.origin, originMain+"^{commit}"); err != nil {
359 return r, err
360 }
361 if _, err := git(ctx, p.origin, "cat-file", "-e", r.tip+":policy/instance"); err != nil {
362 return r, fmt.Errorf("%s holds no policy/instance on main, so it is not an instance repository", p.cfg.instanceRepo)
363 }
364 if _, err := git(ctx, p.origin, "cat-file", "-e", r.tip+":policy/valley"); err == nil {
365 return r, fmt.Errorf("%s holds policy/valley on main, which names another instance; an instance repository the publisher reads holds policy/instance and no policy/valley", p.cfg.instanceRepo)
366 }
367 if r.list, err = revParse(ctx, p.origin, originProjects); err != nil {
368 return r, err
369 }
370 list, err := git(ctx, p.origin, "cat-file", "blob", r.list)
371 if err != nil {
372 return r, fmt.Errorf("%s in the instance repository is not a list of projects: %w", projectsRef, err)
373 }
374 for _, name := range strings.Split(string(list), "\n") {
375 if name != "" {
376 r.projects = append(r.projects, name)
377 }
378 }
379 sort.Strings(r.projects)
380 return r, nil
381}
382
383// errNoMain is fetchMain's error for a project with no main.
384var errNoMain = errors.New("no main")
385
386// fetchMain reads main into a cache that borrows the local repository's
387// objects. Borrowing keeps repository history outside the storage budget:
388// the publisher can read the host's objects but cannot write them.
389func (p *publisher) fetchMain(ctx context.Context, name, url string) (string, string, error) {
390 if !filepath.IsAbs(url) {
391 return "", "", fmt.Errorf("repository must be an absolute local path: %q", url)
392 }
393 heads, err := git(ctx, url, "ls-remote", "--end-of-options", url, "refs/heads/main")
394 if err != nil {
395 return "", "", err
396 }
397 if !listsRef(heads, "refs/heads/main") {
398 return "", "", errNoMain
399 }
400
401 mirror := filepath.Join(p.cache, "repos", name+".git")
402 if err := p.shareRepository(ctx, mirror, url, map[string]string{"refs/heads/main": "refs/heads/main"}); err != nil {
403 return "", "", err
404 }
405 tip, err := revParse(ctx, mirror, "refs/heads/main^{commit}")
406 return mirror, tip, err
407}
408
409// shareRepository replaces a disposable cache with refs and an alternate.
410// No fetch transport runs, so even objects added concurrently cannot be
411// copied. All bytes to be written are known before staging starts. Old
412// caches remain counted until the replacement is complete.
413func (p *publisher) shareRepository(ctx context.Context, dir, source string, refs map[string]string) error {
414 files, err := sharedFiles(ctx, source, refs)
415 if err != nil {
416 return err
417 }
418 return p.stageFiles(dir, files)
419}
420
421func quoteGit(s string) string {
422 return strings.NewReplacer("\\", "\\\\", "\"", "\\\"", "\t", "\\t").Replace(s)
423}
424
425func sharedFiles(ctx context.Context, source string, refs map[string]string) (map[string]string, error) {
426 if !filepath.IsAbs(source) || strings.ContainsAny(source, "\n\r") {
427 return nil, fmt.Errorf("repository must be an absolute local path: %q", source)
428 }
429 objects, err := git(ctx, source, "rev-parse", "--path-format=absolute", "--git-path", "objects")
430 if err != nil {
431 return nil, err
432 }
433 format, err := git(ctx, source, "rev-parse", "--show-object-format")
434 if err != nil {
435 return nil, err
436 }
437 config := "[core]\n\tbare = true\n\trepositoryformatversion = 0\n"
438 switch strings.TrimSpace(string(format)) {
439 case "sha1":
440 case "sha256":
441 config = "[core]\n\tbare = true\n\trepositoryformatversion = 1\n[extensions]\n\tobjectformat = sha256\n"
442 default:
443 return nil, fmt.Errorf("unsupported object format %q", format)
444 }
445 quoted := quoteGit(source)
446 config += "[remote \"origin\"]\n\turl = \"" + quoted + "\"\n"
447 files := map[string]string{
448 "HEAD": "ref: refs/heads/main\n", "config": config,
449 "objects/info/alternates": strings.TrimSpace(string(objects)) + "\n",
450 }
451 for dest, ref := range refs {
452 tip, err := revParse(ctx, source, ref)
453 if err != nil {
454 return nil, err
455 }
456 files[dest] = tip + "\n"
457 }
458 return files, nil
459}
460
461func (p *publisher) reserveStorage(added int64) error {
462 used, err := p.storageUsed()
463 if err != nil {
464 return err
465 }
466 if used > int64(p.cfg.maxStorage)-added {
467 return p.overStorage(used + added)
468 }
469 return nil
470}
471
472func (p *publisher) stageFiles(dir string, files map[string]string) error {
473 used, err := p.storageUsed()
474 if err != nil {
475 return err
476 }
477 var added int64
478 for _, content := range files {
479 added += int64(len(content))
480 }
481 if used > int64(p.cfg.maxStorage)-added {
482 return p.overStorage(used + added)
483 }
484 if err := os.MkdirAll(filepath.Dir(dir), 0o700); err != nil {
485 return err
486 }
487 stage, err := os.MkdirTemp(filepath.Dir(dir), ".shared-")
488 if err != nil {
489 return err
490 }
491 defer os.RemoveAll(stage)
492 prefix := stage
493 if _, ok := files[".git/HEAD"]; ok {
494 prefix = filepath.Join(stage, ".git")
495 }
496 if err := os.MkdirAll(filepath.Join(prefix, "refs"), 0o700); err != nil {
497 return err
498 }
499 for name, content := range files {
500 path := filepath.Join(stage, name)
501 if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
502 return err
503 }
504 if err := os.WriteFile(path, []byte(content), 0o600); err != nil {
505 return err
506 }
507 }
508 if err := p.checkStorage(); err != nil {
509 return err
510 }
511 if err := os.RemoveAll(dir); err != nil {
512 return err
513 }
514 return os.Rename(stage, dir)
515}
516
517// listsRef reports whether ls-remote's output lists the ref. ls-remote
518// matches a pattern against the tail of a ref name, so each name listed
519// is compared whole.
520func listsRef(out []byte, ref string) bool {
521 for _, line := range strings.Split(string(out), "\n") {
522 if _, name, ok := strings.Cut(line, "\t"); ok && name == ref {
523 return true
524 }
525 }
526 return false
527}
528
529func revParse(ctx context.Context, repo, rev string) (string, error) {
530 out, err := git(ctx, repo, "rev-parse", "--verify", "--end-of-options", rev)
531 if err != nil {
532 return "", err
533 }
534 return strings.TrimSpace(string(out)), nil
535}
536
537// valley runs one of the CLI's JSON commands in dir, one of the
538// publisher's repositories, and returns what it printed, up to
539// maxValleyOutput. What it says on stderr is passed on.
540func (p *publisher) valley(ctx context.Context, dir string, args ...string) ([]byte, error) {
541 if err := p.reserveStorage(p.collectionRoom); err != nil {
542 return nil, err
543 }
544 cmd := exec.CommandContext(ctx, "valley", args...)
545 cmd.Dir = dir
546 cmd.Env = valleyEnvironment(os.Environ())
547 stdout := &bounded{max: maxValleyOutput, strict: true}
548 cmd.Stdout = stdout
549 cmd.Stderr = p.stderr
550 err := cmd.Run()
551 if budget := p.checkStorage(); budget != nil {
552 return nil, budget
553 }
554 if stdout.over {
555 return nil, fmt.Errorf("valley %s: %w", strings.Join(args, " "), errTooLong)
556 }
557 if err != nil {
558 return nil, fmt.Errorf("valley %s: %w", strings.Join(args, " "), err)
559 }
560 return stdout.Bytes(), nil
561}
562
563// valleyEnvironment is the environment the valley CLI runs in: the
564// caller's, without the variables that would point git at another
565// repository, and without the ones that would give the CLI verification
566// material of their own. The CLI then reads the signers the host publishes,
567// as it reads the projects.
568func valleyEnvironment(environ []string) []string {
569 var env []string
570 for _, kv := range environ {
571 name, _, _ := strings.Cut(kv, "=")
572 if redirectsGit(name) || name == "VALLEY_KNOWN_SIGNERS" || name == "VALLEY_INTEGRATOR_SIGNER" {
573 continue
574 }
575 env = append(env, kv)
576 }
577 return env
578}
579
580// git runs git in repo, unless it is "", and returns what it printed, up
581// to maxGitOutput.
582func git(ctx context.Context, repo string, args ...string) ([]byte, error) {
583 return gitInput(ctx, repo, "", args...)
584}
585
586// gitInput is git with input on its stdin. With no input, stdin is the
587// null device.
588func gitInput(ctx context.Context, repo, input string, args ...string) ([]byte, error) {
589 var stdin io.Reader
590 if input != "" {
591 stdin = strings.NewReader(input)
592 }
593 stdout := &bounded{max: maxGitOutput, strict: true}
594 err := gitStream(ctx, repo, stdin, stdout, args...)
595 if stdout.over {
596 return nil, fmt.Errorf("git %s: %w", gitVerb(args), errTooLong)
597 }
598 if err != nil {
599 return nil, err
600 }
601 return stdout.Bytes(), nil
602}
603
604// gitStream runs git in repo, unless it is "", with stdin and stdout
605// given: with replacement refs off, git held to the transports a URL from
606// data may use, no prompt, and a fixed date for any commit it writes. It
607// keeps the caller's GIT_CONFIG_* variables, which carry the
608// safe.directory entries a host gives the publisher for repositories it
609// does not own.
610func gitStream(ctx context.Context, repo string, stdin io.Reader, stdout io.Writer, args ...string) error {
611 if repo != "" {
612 args = append([]string{"-C", repo}, args...)
613 }
614 cmd := exec.CommandContext(ctx, "git", append([]string{"--no-replace-objects"}, args...)...)
615 cmd.Env = gitEnvironment(os.Environ())
616 stderr := &bounded{max: maxStderr}
617 cmd.Stdin, cmd.Stdout, cmd.Stderr = stdin, stdout, stderr
618 if err := cmd.Run(); err != nil {
619 return fmt.Errorf("git %s: %w: %s", gitVerb(args), err, strings.TrimSpace(stderr.String()))
620 }
621 return nil
622}
623
624// gitVerb is the git command args run, for messages: the first argument
625// after -C and the options git takes before its command.
626func gitVerb(args []string) string {
627 for i := 0; i < len(args); i++ {
628 switch args[i] {
629 case "-C", "-c":
630 i++
631 default:
632 return args[i]
633 }
634 }
635 return "git"
636}
637
638// errTooLong is the error for a program that printed more than its bound.
639var errTooLong = errors.New("it printed more than the publisher holds of it")
640
641// bounded holds what a program prints, up to max bytes. Past max, a write
642// fails when strict is set, which ends the program at its next write, and
643// is dropped when it is not. It is no io.ReaderFrom, so os/exec copies
644// through Write.
645type bounded struct {
646 buf bytes.Buffer
647 max int
648 strict bool
649 over bool
650}
651
652func (b *bounded) Write(p []byte) (int, error) {
653 room := max(b.max-b.buf.Len(), 0)
654 if len(p) <= room {
655 return b.buf.Write(p)
656 }
657 b.over = true
658 b.buf.Write(p[:room])
659 if b.strict {
660 return room, errTooLong
661 }
662 return len(p), nil
663}
664
665func (b *bounded) Bytes() []byte { return b.buf.Bytes() }
666func (b *bounded) String() string { return b.buf.String() }
667
668func gitEnvironment(environ []string) []string {
669 var env []string
670 for _, kv := range environ {
671 name, _, _ := strings.Cut(kv, "=")
672 switch {
673 case redirectsGit(name), name == "GIT_ALLOW_PROTOCOL", name == "GIT_TERMINAL_PROMPT",
674 name == "GIT_AUTHOR_DATE", name == "GIT_COMMITTER_DATE":
675 continue
676 }
677 env = append(env, kv)
678 }
679 return append(env,
680 "GIT_ALLOW_PROTOCOL=ssh:git:https:file",
681 "GIT_TERMINAL_PROMPT=0",
682 "GIT_NO_REPLACE_OBJECTS=1",
683 "GIT_AUTHOR_DATE=@0 +0000",
684 "GIT_COMMITTER_DATE=@0 +0000",
685 )
686}
687
688// redirectsGit reports whether the variable points git at another
689// repository, another object store or another work tree than the one it
690// is run in.
691func redirectsGit(name string) bool {
692 switch name {
693 case "GIT_DIR", "GIT_WORK_TREE", "GIT_COMMON_DIR", "GIT_INDEX_FILE", "GIT_PREFIX",
694 "GIT_NAMESPACE", "GIT_OBJECT_DIRECTORY", "GIT_ALTERNATE_OBJECT_DIRECTORIES":
695 return true
696 }
697 return false
698}
699
700// readPrincipals reads the display mapping: a JSON object from principal
701// names to the names an export shows. No file is an empty mapping, under
702// which every principal is shown as export.Unmapped.
703func readPrincipals(path string) (export.Principals, error) {
704 if path == "" {
705 return export.Principals{}, nil
706 }
707 data, err := os.ReadFile(path)
708 if err != nil {
709 return nil, err
710 }
711 dec := json.NewDecoder(bytes.NewReader(data))
712 var m export.Principals
713 if err := dec.Decode(&m); err != nil {
714 return nil, fmt.Errorf("the display mapping %s is not a JSON object of names: %w", path, err)
715 }
716 if err := dec.Decode(&json.RawMessage{}); err != io.EOF {
717 return nil, fmt.Errorf("the display mapping %s holds more than its one object", path)
718 }
719 if m == nil {
720 m = export.Principals{}
721 }
722 return m, nil
723}