gunk-dev/the-valley

grants.go

source70805f590deemain's published tip history
1.8 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
15func (g grants) holds(principal, grant string) bool {
16 return g[principal][grant]
17}
18
19// read adds what one grants file grants. Its lines are a grant and a
20// principal, separated by space; blank lines and lines starting with # are
21// skipped. Two writers produce these files: the identity compiler, from the
22// registry (identity/), and the NixOS module, from what the host declares
23// by hand. Holdings add up across files, the way the compiled
24// authorized_keys adds to the declared keys.
25//
26// A file that does not exist grants nothing. The compiled file is missing
27// until the first compilation, and the hook then refuses what only a grant
28// opens, which is the direction a missing grant has to default in.
29//
30// A grant this program does not check is kept and never consulted, so a
31// compiled file that names a grant from a newer registry costs nothing. A
32// line that is not a grant and a principal fails the read, and the hook
33// then refuses the push: a file it cannot parse is a file it cannot vouch
34// for.
35func (g grants) read(path string) error {
36 f, err := os.Open(path)
37 if errors.Is(err, fs.ErrNotExist) {
38 return nil
39 }
40 if err != nil {
41 return err
42 }
43 defer f.Close()
44
45 lines := bufio.NewScanner(f)
46 for n := 1; lines.Scan(); n++ {
47 line := strings.TrimSpace(lines.Text())
48 if line == "" || strings.HasPrefix(line, "#") {
49 continue
50 }
51 fields := strings.Fields(line)
52 if len(fields) != 2 {
53 return fmt.Errorf("%s:%d: %q is not a grant and a principal", path, n, line)
54 }
55 grant, principal := fields[0], fields[1]
56 if g[principal] == nil {
57 g[principal] = map[string]bool{}
58 }
59 g[principal][grant] = true
60 }
61 return lines.Err()
62}