oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package thin
2
3import (
4 "amadan.net/oficina/equipo/internal/release"
5 "amadan.net/oficina/equipo/internal/runner"
6 "amadan.net/oficina/equipo/internal/wire"
7 "context"
8 "crypto/sha256"
9 "encoding/hex"
10 "encoding/json"
11 "errors"
12 "fmt"
13 "net/url"
14 "os"
15 "os/exec"
16 "path/filepath"
17 "runtime"
18 "strconv"
19 "strings"
20 "time"
21)
22
23const previewHeadersTemplate = "/*\n Content-Security-Policy: default-src 'none'; connect-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; media-src 'self'; form-action 'none'; frame-src 'none'; base-uri 'none'; object-src 'none'; frame-ancestors %s\n X-Content-Type-Options: nosniff\n Referrer-Policy: no-referrer\n X-DNS-Prefetch-Control: off\n"
24
25func previewHeaders(origin string) string {
26 ancestor := "'none'"
27 u, err := url.Parse(origin)
28 if err == nil && u.Host != "" && u.User == nil && u.Path == "" && u.RawQuery == "" && !u.ForceQuery && u.Fragment == "" && !strings.ContainsAny(u.Host, "* ;\r\n\t'\"\\") && (u.Scheme == "https" || u.Scheme == "http" && u.Hostname() == "127.0.0.1") {
29 ancestor = u.Scheme + "://" + u.Host
30 }
31 return fmt.Sprintf(previewHeadersTemplate, ancestor)
32}
33
34func previewCSP(origin string) string {
35 _, value, _ := strings.Cut(strings.Split(previewHeaders(origin), "\n")[1], ": ")
36 return value
37}
38
39const previewSecretRules = `[extend]
40useDefault = true
41[[rules]]
42id = "equipo-github-token"
43regex = '''(?:ghs_|ghu_|gho_|ghr_)[A-Za-z0-9_]{20,}'''
44[[rules]]
45id = "equipo-private-key-header"
46regex = '''-----BEGIN (?:[A-Z0-9]+ )?PRIVATE KEY-----'''
47`
48
49const previewScanner = "github.com/zricethezav/gitleaks/v8@" + release.GitleaksVersion
50
51var previewScannerTool = func(c runner.Config) (string, string) {
52 return filepath.Join(filepath.Dir(c.Executable), "gitleaks"), release.GitleaksSHA256()
53}
54
55// previewToolHealth is whether the preview scanner is installed and is the
56// pinned build, as scanPreview checks it before every scan: a fixed state
57// for the coordinator's status, never the path or the pin.
58func previewToolHealth(c runner.Config) *wire.ToolHealth {
59 binary, pin := previewScannerTool(c)
60 state := wire.ToolHealthy
61 switch info, err := os.Lstat(binary); {
62 case !filepath.IsAbs(binary) || err != nil || !info.Mode().IsRegular():
63 state = wire.ToolMissing
64 case pin == "":
65 state = wire.ToolUnpinned
66 case !release.VerifyGitleaks(binary, pin):
67 state = wire.ToolMismatch
68 }
69 return &wire.ToolHealth{Scanner: state}
70}
71
72func (e *Engineer) scanPreview(ctx context.Context, stage string) string {
73 found, err := e.gitleaks(ctx, stage)
74 switch {
75 case found:
76 return "preview_secrets"
77 case err != nil:
78 return "preview_scanner"
79 }
80 return ""
81}
82
83// errScanner: the pinned gitleaks could not say (missing, not the pinned
84// build, failed, timed out or wrote no readable report).
85var errScanner = errors.New("the secret scanner could not scan")
86
87// gitleaks runs the pinned scanner with the trusted rules over the files
88// under stage, offline and confined (sandbox-exec deny-default on a Mac,
89// bubblewrap with nothing shared on Linux): found when it reported any
90// finding, else errScanner when it could not tell. Its report is read
91// for a count only: no finding's text is kept.
92func (e *Engineer) gitleaks(ctx context.Context, stage string) (bool, error) {
93 return e.gitleaksWith(ctx, stage, previewSecretRules)
94}
95
96// gitleaksWith is gitleaks with the trusted rules given.
97func (e *Engineer) gitleaksWith(ctx context.Context, stage, rules string) (bool, error) {
98 binary, pin := previewScannerTool(e.O.Runner)
99 return e.gitleaksAt(ctx, binary, pin, stage, rules)
100}
101
102// gitleaksAt is gitleaksWith with the scanner binary and its pin given
103// (the test build's fake Mac worker names its own).
104func (e *Engineer) gitleaksAt(ctx context.Context, binary, pin, stage, rules string) (bool, error) {
105 if !release.VerifyGitleaks(binary, pin) {
106 return false, errScanner
107 }
108 dir, err := os.MkdirTemp(filepath.Dir(stage), "preview-scan-")
109 if err != nil {
110 return false, errScanner
111 }
112 defer os.RemoveAll(dir)
113 config := filepath.Join(dir, "trusted.toml")
114 ignore := filepath.Join(dir, "empty.ignore")
115 report := filepath.Join(dir, "findings.json")
116 if os.WriteFile(config, []byte(rules), 0600) != nil || os.WriteFile(ignore, nil, 0600) != nil {
117 return false, errScanner
118 }
119 args := func(bin, cfg, ign, rep, files string) []string {
120 return []string{bin, "dir", "--config", cfg, "--gitleaks-ignore-path", ign, "--ignore-gitleaks-allow", "--no-banner", "--redact", "--log-level", "error", "--max-archive-depth", "10", "--max-decode-depth", "5", "--report-format", "json", "--report-path", rep, files}
121 }
122 var command string
123 var argv []string
124 if runtime.GOOS == "darwin" {
125 command = "/usr/bin/sandbox-exec"
126 profile := fmt.Sprintf(`(version 1)(deny default)(allow process*)(allow sysctl-read)(allow file-read* (subpath "/System") (subpath "/usr/lib") (subpath %s) (subpath %s) (literal %s) (literal "/dev/null"))(allow file-write* (literal %s) (literal "/dev/null"))`, strconv.Quote(stage), strconv.Quote(dir), strconv.Quote(binary), strconv.Quote(report))
127 argv = append([]string{"-p", profile}, args(binary, config, ignore, report, stage)...)
128 } else {
129 command = firstNonEmpty(e.O.Runner.BwrapPath, "/usr/bin/bwrap")
130 argv = []string{"--unshare-all", "--die-with-parent", "--new-session", "--cap-drop", "ALL", "--ro-bind", binary, "/scanner", "--ro-bind", stage, "/files", "--bind", dir, "/output", "--proc", "/proc", "--dev", "/dev", "--tmpfs", "/tmp", "--chdir", "/tmp", "--clearenv", "--setenv", "HOME", "/tmp", "--setenv", "PATH", "/nonexistent"}
131 argv = append(argv, args("/scanner", "/output/trusted.toml", "/output/empty.ignore", "/output/findings.json", "/files")...)
132 }
133 scanCtx, cancel := context.WithTimeout(ctx, 2*time.Minute)
134 defer cancel()
135 cmd := exec.CommandContext(scanCtx, command, argv...)
136 cmd.Dir = dir
137 cmd.Env = []string{"PATH=/usr/bin:/bin", "HOME=" + dir}
138 _, clipped, scanErr := boundedOutput(cmd, 4096)
139 if clipped || scanCtx.Err() != nil {
140 return false, errScanner
141 }
142 found, err := readFindings(report)
143 if err != nil || found {
144 return found, err
145 }
146 if scanErr != nil {
147 return false, errScanner
148 }
149 return false, nil
150}
151
152// readFindings reads a gitleaks report for whether it has any finding;
153// errScanner when it is missing, too large or not a report. No
154// finding's text is kept.
155func readFindings(report string) (bool, error) {
156 info, err := os.Stat(report)
157 if err != nil || !info.Mode().IsRegular() || info.Size() > 2<<20 {
158 return false, errScanner
159 }
160 raw, err := os.ReadFile(report)
161 var findings []json.RawMessage
162 if err != nil || json.Unmarshal(raw, &findings) != nil || findings == nil {
163 return false, errScanner
164 }
165 return len(findings) > 0, nil
166}
167
168// workerLeaks is the worker's scanner off a Mac (the test build's fake
169// worker on Linux): the preview scanner's bubblewrap with the worker's
170// trusted rules; marker and record are not needed there.
171func (e *Engineer) workerLeaks(ctx context.Context, stage, _ string, _ func(string) error) (bool, error) {
172 return e.gitleaksWith(ctx, stage, workerSecretRules())
173}
174
175type previewRefusalError struct{ reason string }
176
177func (e *previewRefusalError) Error() string { return e.reason }
178
179func previewPublishFailure(out string) string {
180 if strings.Contains(out, "_headers:") && strings.Contains(out, "is not supported yet") {
181 return "preview_headers"
182 }
183 return "preview_failed"
184}
185
186func previewSecurityStamp(origin string) string {
187 sum := sha256.Sum256([]byte("preview/v1\n" + previewHeaders(origin) + previewScanner))
188 return hex.EncodeToString(sum[:])
189}
190