gunk-dev/the-valley

main.go

sourceb115ae7362ffmain's published tip history
9.8 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 resolves --registry-ref once, by
109// its exact name with readaccess.ResolveRef, and reads the registry at the
110// commit that ref held. It reads each project's main the same way.
111func (c *config) report(ctx context.Context, stdout, stderr io.Writer, now time.Time) error {
112 r := &c.access
113 if err := r.CheckSchemas(ctx); err != nil {
114 return err
115 }
116 var grants readaccess.Grants
117 oid, ok, err := readaccess.ResolveRef(ctx, c.instanceRepo, c.registryRef)
118 if err != nil {
119 return err
120 }
121 if ok {
122 var tip string
123 if tip, err = commitOf(ctx, c.instanceRepo, oid); err != nil {
124 return fmt.Errorf("%s in the instance repository is not a commit: %w", c.registryRef, err)
125 }
126 grants, err = r.Grants(ctx, c.instanceRepo, tip, c.registryDir, c.destination, now)
127 } else {
128 fmt.Fprintf(stderr, "valley-read-coverage: the instance repository holds no %s, so it has no registry, and grants no read\n", c.registryRef)
129 }
130 var bad *readaccess.InvalidError
131 switch {
132 case errors.Is(err, readaccess.ErrMissing):
133 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)
134 case errors.As(err, &bad):
135 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)
136 case err != nil:
137 return fmt.Errorf("could not read the registry: %w", err)
138 }
139
140 list, ok, err := readaccess.ResolveRef(ctx, c.instanceRepo, "refs/the-valley/projects")
141 if err != nil {
142 return err
143 } else if !ok {
144 return fmt.Errorf("%s publishes no refs/the-valley/projects", c.instanceRepo)
145 }
146 names, err := git(ctx, c.instanceRepo, "cat-file", "blob", list)
147 if err != nil {
148 return err
149 }
150 parent, base := filepath.Split(strings.TrimRight(c.instanceRepo, "/"))
151 suffix := ""
152 if strings.HasSuffix(base, ".git") {
153 suffix = ".git"
154 }
155
156 total, readable := 0, 0
157 for _, name := range strings.Split(string(names), "\n") {
158 if name == "" {
159 continue
160 }
161 if strings.ContainsAny(name, "/\\") || name == "." || name == ".." {
162 return fmt.Errorf("refs/the-valley/projects lists %q, which is not a project name", name)
163 }
164 total++
165 consent, why, err := c.consent(ctx, filepath.Join(parent, name+suffix), name)
166 if err != nil {
167 return fmt.Errorf("%s: %w", name, err)
168 }
169 var lacks []string
170 if consent == nil {
171 lacks = append(lacks, "no project consent ("+why+")")
172 } else if !consent.Names(c.reader) {
173 lacks = append(lacks, fmt.Sprintf("no project consent (its policy/read does not name %s)", c.reader))
174 }
175 switch {
176 case consent != nil && !grants.Covers(c.reader, name, consent.Identity):
177 lacks = append(lacks, fmt.Sprintf("no instance grant (no read grant of %s at %s covers %s with the identity %s)",
178 c.reader, c.destination, name, consent.Identity))
179 case consent == nil && !grants.Selects(c.reader, name):
180 lacks = append(lacks, fmt.Sprintf("no instance grant (no read grant of %s at %s names %s)", c.reader, c.destination, name))
181 }
182 if len(lacks) == 0 {
183 readable++
184 continue
185 }
186 fmt.Fprintf(stdout, "%s: %s\n", name, strings.Join(lacks, "; "))
187 }
188 fmt.Fprintf(stdout, "%s may read %d of %d projects at %s\n", c.reader, readable, total, c.destination)
189 return nil
190}
191
192// consent reads a project's consent at its main. A project with no main,
193// no policy/read or an invalid one has none, and why says so. Any other
194// failure is an error.
195func (c *config) consent(ctx context.Context, repo, name string) (*readaccess.Consent, string, error) {
196 oid, ok, err := readaccess.ResolveRef(ctx, repo, "refs/heads/main")
197 if err != nil {
198 return nil, "", err
199 } else if !ok {
200 return nil, "it has no main", nil
201 }
202 tip, err := commitOf(ctx, repo, oid)
203 if err != nil {
204 return nil, "", fmt.Errorf("its main is not a commit: %w", err)
205 }
206 consent, err := c.access.Consent(ctx, repo, tip, name)
207 var bad *readaccess.InvalidError
208 switch {
209 case errors.Is(err, readaccess.ErrMissing):
210 return nil, "its main holds no " + readaccess.PolicyDir, nil
211 case errors.As(err, &bad):
212 return nil, "its " + readaccess.PolicyDir + " is not valid: " + err.Error(), nil
213 case err != nil:
214 return nil, "", err
215 }
216 return &consent, "", nil
217}
218
219// commitOf peels the object oid to the commit it names in repo. oid is an
220// object ID that readaccess.ResolveRef read, never a ref name: rev-parse
221// given a name reads other refs where repo holds none of that name.
222func commitOf(ctx context.Context, repo, oid string) (string, error) {
223 out, err := git(ctx, repo, "rev-parse", "--verify", "--end-of-options", oid+"^{commit}")
224 if err != nil {
225 return "", err
226 }
227 return strings.TrimSpace(string(out)), nil
228}
229
230// git runs git in repo with replacement refs off, and without the
231// variables that would point it at another repository.
232func git(ctx context.Context, repo string, args ...string) ([]byte, error) {
233 cmd := exec.CommandContext(ctx, "git", append([]string{"--no-replace-objects", "-C", repo}, args...)...)
234 for _, kv := range os.Environ() {
235 switch name, _, _ := strings.Cut(kv, "="); name {
236 case "GIT_DIR", "GIT_WORK_TREE", "GIT_COMMON_DIR", "GIT_OBJECT_DIRECTORY", "GIT_ALTERNATE_OBJECT_DIRECTORIES", "GIT_NAMESPACE":
237 continue
238 }
239 cmd.Env = append(cmd.Env, kv)
240 }
241 var stderr bytes.Buffer
242 cmd.Stderr = &stderr
243 out, err := cmd.Output()
244 if err != nil {
245 return nil, fmt.Errorf("git %s in %s: %w: %s", args[0], repo, err, strings.TrimSpace(stderr.String()))
246 }
247 return out, nil
248}