gunk-dev/the-valley

main.go

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