gunk-dev/the-valley

grants.go

source499d9e61dfeemain's published tip history
2.1 KiB
1package main
2
3import (
4 "bufio"
5 "errors"
6 "fmt"
7 "io/fs"
8 "os"
9 "strings"
10)
11
12// grants maps a principal to the grants it holds.
13type grants map[string]map[string]bool
14
15// holds reports whether principal holds grant. The approve grant is held
16// under either of its names, so a line naming request grants exactly what
17// a line naming approve does, and holding both is holding it once.
18func (g grants) holds(principal, grant string) bool {
19 if grant == grantApprove && g[principal][grantRequest] {
20 return true
21 }
22 return g[principal][grant]
23}
24
25// read adds what one grants file grants. Its lines are a grant and a
26// principal, separated by space; blank lines and lines starting with # are
27// skipped. Two writers produce these files: the identity compiler, from the
28// registry (identity/), and the NixOS module, from what the host declares
29// by hand. Holdings add up across files, the way the compiled
30// authorized_keys adds to the declared keys.
31//
32// A file that does not exist grants nothing. The compiled file is missing
33// until the first compilation, and the hook then refuses what only a grant
34// opens, which is the direction a missing grant has to default in.
35//
36// A grant this program does not check is kept and never consulted, so a
37// compiled file that names a grant from a newer registry costs nothing. A
38// line that is not a grant and a principal fails the read, and the hook
39// then refuses the push: a file it cannot parse is a file it cannot vouch
40// for.
41func (g grants) read(path string) error {
42 f, err := os.Open(path)
43 if errors.Is(err, fs.ErrNotExist) {
44 return nil
45 }
46 if err != nil {
47 return err
48 }
49 defer f.Close()
50
51 lines := bufio.NewScanner(f)
52 for n := 1; lines.Scan(); n++ {
53 line := strings.TrimSpace(lines.Text())
54 if line == "" || strings.HasPrefix(line, "#") {
55 continue
56 }
57 fields := strings.Fields(line)
58 if len(fields) != 2 {
59 return fmt.Errorf("%s:%d: %q is not a grant and a principal", path, n, line)
60 }
61 grant, principal := fields[0], fields[1]
62 if g[principal] == nil {
63 g[principal] = map[string]bool{}
64 }
65 g[principal][grant] = true
66 }
67 return lines.Err()
68}