gunk-dev/the-valley

main.go

source6ee9fbfcf100main's published tip history
9.5 KiB
1// valley-read-coverage lists the projects a principal cannot read at a
2// destination, and which of the two consents each lacks: the project's own
3// policy/read, or a read grant in the instance's identity registry. It reads
4// the instance repository's registry ref and each project's main on a valley
5// host, and changes nothing. It repairs no project and bypasses no policy.
6package main
7
8import (
9 "bytes"
10 "context"
11 "errors"
12 "flag"
13 "fmt"
14 "io"
15 "os"
16 "os/exec"
17 "path/filepath"
18 "strings"
19 "time"
20
21 "the-valley/readaccess"
22)
23
24const usage = `usage: valley-read-coverage --instance-repo DIR --destination NAME
25 --reader PRINCIPAL [--registry-ref REF]
26 [--registry-dir DIR] [--read-schema FILE]
27 [--identity-schema FILE]
28
29List the projects PRINCIPAL cannot read at the destination NAME, and the
30consent each lacks: the project's own, its policy/read on its main, or the
31instance's, a read grant in the identity registry at the instance
32repository's REF.
33
34 --instance-repo DIR an absolute local path to the instance repository,
35 whose refs/the-valley/projects lists the projects;
36 each project's repository is beside it, named
37 <project>.git when DIR ends in .git, and <project>
38 otherwise
39 --destination NAME the destination of the edge read boundary
40 --reader PRINCIPAL the principal, or anyone for a reader with no
41 credential
42 --registry-ref REF the ref of the instance repository whose tip
43 carries the registry, as the identity compiler and
44 the web publisher read it: a full ref name
45 (default refs/heads/main); an instance repository
46 with no REF holds no registry, so it grants no read
47 --registry-dir DIR the registry's directory in that tip (default
48 identity)
49 --read-schema FILE schema/read.cue (default $VALLEY_READ_SCHEMA)
50 --identity-schema FILE
51 schema/identity.cue (default
52 $VALLEY_IDENTITY_SCHEMA)
53
54It prints one line for each project PRINCIPAL cannot read, then how many
55projects PRINCIPAL may read. It exits 0 when it read every project, whether
56or not any lacks a consent, 1 when it could not read one, and 2 for invalid
57flags.`
58
59func main() {
60 os.Exit(run(context.Background(), os.Args[1:], os.Stdout, os.Stderr, time.Now()))
61}
62
63type config struct {
64 instanceRepo, destination, reader, registryRef, registryDir string
65 access readaccess.Reader
66}
67
68func run(ctx context.Context, args []string, stdout, stderr io.Writer, now time.Time) int {
69 var c config
70 fs := flag.NewFlagSet("valley-read-coverage", flag.ContinueOnError)
71 fs.SetOutput(io.Discard)
72 fs.StringVar(&c.instanceRepo, "instance-repo", "", "")
73 fs.StringVar(&c.destination, "destination", "", "")
74 fs.StringVar(&c.reader, "reader", "", "")
75 fs.StringVar(&c.registryRef, "registry-ref", "refs/heads/main", "")
76 fs.StringVar(&c.registryDir, "registry-dir", "identity", "")
77 fs.StringVar(&c.access.ReadSchema, "read-schema", os.Getenv("VALLEY_READ_SCHEMA"), "")
78 fs.StringVar(&c.access.IdentitySchema, "identity-schema", os.Getenv("VALLEY_IDENTITY_SCHEMA"), "")
79 err := fs.Parse(args)
80 switch {
81 case errors.Is(err, flag.ErrHelp):
82 fmt.Fprintln(stdout, usage)
83 return 0
84 case err != nil:
85 case fs.NArg() > 0:
86 err = fmt.Errorf("unexpected argument %q", fs.Arg(0))
87 case !filepath.IsAbs(c.instanceRepo):
88 err = errors.New("--instance-repo must be an absolute local path")
89 case c.destination == "" || c.reader == "":
90 err = errors.New("--destination and --reader are required")
91 case !readaccess.ValidRef(c.registryRef):
92 err = fmt.Errorf("--registry-ref %q is not a full ref name: it opens with refs/, and git check-ref-format accepts it", c.registryRef)
93 case c.access.ReadSchema == "" || c.access.IdentitySchema == "":
94 err = errors.New("no schema: give --read-schema and --identity-schema, or set VALLEY_READ_SCHEMA and VALLEY_IDENTITY_SCHEMA")
95 }
96 if err != nil {
97 fmt.Fprintf(stderr, "valley-read-coverage: %v\n%s\n", err, usage)
98 return 2
99 }
100 if err := c.report(ctx, stdout, stderr, now); err != nil {
101 fmt.Fprintf(stderr, "valley-read-coverage: %v\n", err)
102 return 1
103 }
104 return 0
105}
106
107// report reads the registry and every project's policy/read, and says
108// which consents each project lacks. It reads the registry at the commit
109// it resolves --registry-ref to once, as the identity compiler does.
110func (c *config) report(ctx context.Context, stdout, stderr io.Writer, now time.Time) error {
111 r := &c.access
112 if err := r.CheckSchemas(ctx); err != nil {
113 return err
114 }
115 var grants readaccess.Grants
116 tip, ok, err := revParse(ctx, c.instanceRepo, c.registryRef+"^{commit}")
117 if err != nil {
118 return err
119 } else if !ok {
120 fmt.Fprintf(stderr, "valley-read-coverage: the instance repository holds no %s, so it has no registry, and grants no read\n", c.registryRef)
121 } else {
122 grants, err = r.Grants(ctx, c.instanceRepo, tip, c.registryDir, c.destination, now)
123 }
124 var bad *readaccess.InvalidError
125 switch {
126 case errors.Is(err, readaccess.ErrMissing):
127 fmt.Fprintf(stderr, "valley-read-coverage: the instance repository's %s holds no registry in %s/, so it grants no read\n", c.registryRef, c.registryDir)
128 case errors.As(err, &bad):
129 fmt.Fprintf(stderr, "valley-read-coverage: the registry in %s/ at %s is not valid, so it grants no read: %v\n", c.registryDir, c.registryRef, err)
130 case err != nil:
131 return fmt.Errorf("could not read the registry: %w", err)
132 }
133
134 list, ok, err := revParse(ctx, c.instanceRepo, "refs/the-valley/projects")
135 if err != nil {
136 return err
137 } else if !ok {
138 return fmt.Errorf("%s publishes no refs/the-valley/projects", c.instanceRepo)
139 }
140 names, err := git(ctx, c.instanceRepo, "cat-file", "blob", list)
141 if err != nil {
142 return err
143 }
144 parent, base := filepath.Split(strings.TrimRight(c.instanceRepo, "/"))
145 suffix := ""
146 if strings.HasSuffix(base, ".git") {
147 suffix = ".git"
148 }
149
150 total, readable := 0, 0
151 for _, name := range strings.Split(string(names), "\n") {
152 if name == "" {
153 continue
154 }
155 if strings.ContainsAny(name, "/\\") || name == "." || name == ".." {
156 return fmt.Errorf("refs/the-valley/projects lists %q, which is not a project name", name)
157 }
158 total++
159 consent, why, err := c.consent(ctx, filepath.Join(parent, name+suffix), name)
160 if err != nil {
161 return fmt.Errorf("%s: %w", name, err)
162 }
163 var lacks []string
164 if consent == nil {
165 lacks = append(lacks, "no project consent ("+why+")")
166 } else if !consent.Names(c.reader) {
167 lacks = append(lacks, fmt.Sprintf("no project consent (its policy/read does not name %s)", c.reader))
168 }
169 switch {
170 case consent != nil && !grants.Covers(c.reader, name, consent.Identity):
171 lacks = append(lacks, fmt.Sprintf("no instance grant (no read grant of %s at %s covers %s with the identity %s)",
172 c.reader, c.destination, name, consent.Identity))
173 case consent == nil && !grants.Selects(c.reader, name):
174 lacks = append(lacks, fmt.Sprintf("no instance grant (no read grant of %s at %s names %s)", c.reader, c.destination, name))
175 }
176 if len(lacks) == 0 {
177 readable++
178 continue
179 }
180 fmt.Fprintf(stdout, "%s: %s\n", name, strings.Join(lacks, "; "))
181 }
182 fmt.Fprintf(stdout, "%s may read %d of %d projects at %s\n", c.reader, readable, total, c.destination)
183 return nil
184}
185
186// consent reads a project's consent at its main. A project with no main,
187// no policy/read or an invalid one has none, and why says so. Any other
188// failure is an error.
189func (c *config) consent(ctx context.Context, repo, name string) (*readaccess.Consent, string, error) {
190 tip, ok, err := revParse(ctx, repo, "refs/heads/main^{commit}")
191 if err != nil {
192 return nil, "", err
193 } else if !ok {
194 return nil, "it has no main", nil
195 }
196 consent, err := c.access.Consent(ctx, repo, tip, name)
197 var bad *readaccess.InvalidError
198 switch {
199 case errors.Is(err, readaccess.ErrMissing):
200 return nil, "its main holds no " + readaccess.PolicyDir, nil
201 case errors.As(err, &bad):
202 return nil, "its " + readaccess.PolicyDir + " is not valid: " + err.Error(), nil
203 case err != nil:
204 return nil, "", err
205 }
206 return &consent, "", nil
207}
208
209// revParse resolves rev in repo. ok is false when the repository holds no
210// such ref; an error is a repository git could not read.
211func revParse(ctx context.Context, repo, rev string) (string, bool, error) {
212 out, err := git(ctx, repo, "rev-parse", "--verify", "--quiet", "--end-of-options", rev)
213 var exit *exec.ExitError
214 if errors.As(err, &exit) && exit.ExitCode() == 1 {
215 return "", false, nil
216 }
217 if err != nil {
218 return "", false, err
219 }
220 return strings.TrimSpace(string(out)), true, nil
221}
222
223// git runs git in repo with replacement refs off, and without the
224// variables that would point it at another repository.
225func git(ctx context.Context, repo string, args ...string) ([]byte, error) {
226 cmd := exec.CommandContext(ctx, "git", append([]string{"--no-replace-objects", "-C", repo}, args...)...)
227 for _, kv := range os.Environ() {
228 switch name, _, _ := strings.Cut(kv, "="); name {
229 case "GIT_DIR", "GIT_WORK_TREE", "GIT_COMMON_DIR", "GIT_OBJECT_DIRECTORY", "GIT_ALTERNATE_OBJECT_DIRECTORIES", "GIT_NAMESPACE":
230 continue
231 }
232 cmd.Env = append(cmd.Env, kv)
233 }
234 var stderr bytes.Buffer
235 cmd.Stderr = &stderr
236 out, err := cmd.Output()
237 if err != nil {
238 var exit *exec.ExitError
239 if errors.As(err, &exit) && exit.ExitCode() == 1 {
240 return nil, err
241 }
242 return nil, fmt.Errorf("git %s in %s: %w: %s", args[0], repo, err, strings.TrimSpace(stderr.String()))
243 }
244 return out, nil
245}