gunk-dev/the-valley

record.go

sourceb8e46aa6aaccmain's published tip history
9.5 KiB
1// Package telemetry holds the valley's diagnostic records: what a
2// component was doing, said by the code that was doing it.
3//
4// A record is an observation and nothing more. It is never signed, never
5// stored at a ref and never read to decide anything. Evidence, requests
6// and outcomes stay where they are, and keep their meaning.
7//
8// Records come only from producer code, through a stream (store.go) or a
9// report (protocol.go). A line a check prints is never read as a record,
10// whatever it looks like: a check author can print anything.
11package telemetry
12
13import (
14 "bytes"
15 "encoding/json"
16 "errors"
17 "fmt"
18 "os"
19 "path/filepath"
20 "regexp"
21 "strings"
22 "time"
23 "unicode/utf8"
24)
25
26// Format names the record and wire format these types describe.
27const Format = "valley-telemetry/v1"
28
29// Record is one observation.
30type Record struct {
31 // Stream and Seq place the record: the stream that holds it and its
32 // number there. Both are set when a stream stores the record.
33 Stream string `json:"stream,omitempty"`
34 Seq int64 `json:"seq,omitempty"`
35
36 Type string `json:"type"`
37 // Time is the producer's clock when it made the record, in UTC. A
38 // clock on another machine can disagree with this host's, so two
39 // machines' times are never subtracted.
40 Time string `json:"time"`
41
42 // What the record is about. Run names one invocation of a producer
43 // (a worker pass, an attest run, an approval), and every record that
44 // invocation makes carries it.
45 Run string `json:"run,omitempty"`
46 Project string `json:"project,omitempty"`
47 Change string `json:"change,omitempty"`
48 Version int `json:"version,omitempty"`
49 Head string `json:"head,omitempty"`
50 Tree string `json:"tree,omitempty"`
51 Check string `json:"check,omitempty"`
52
53 Data map[string]any `json:"data,omitempty"`
54 Producer *Producer `json:"producer,omitempty"`
55
56 // Set by the collector on a reported record, from the session that
57 // delivered it, and never taken from the sender. ClientID is the
58 // sender's own name for the record, which makes a retried report
59 // harmless.
60 Principal string `json:"principal,omitempty"`
61 Received string `json:"received,omitempty"`
62 ClientID string `json:"client_id,omitempty"`
63}
64
65// Producer is the program that made a record, as it observed itself: its
66// executable, its version when it knows one, and its process. A version
67// a program cannot observe is left empty and reads as unknown.
68type Producer struct {
69 Name string `json:"name"`
70 Exe string `json:"exe,omitempty"`
71 Version string `json:"version,omitempty"`
72 PID int `json:"pid,omitempty"`
73}
74
75// Self is the running program as a producer named name.
76func Self(name, version string) *Producer {
77 p := &Producer{Name: name, Version: version, PID: os.Getpid()}
78 if exe, err := os.Executable(); err == nil {
79 if real, err := filepath.EvalSymlinks(exe); err == nil {
80 exe = real
81 }
82 p.Exe = exe
83 }
84 return p
85}
86
87// The record types. A stream and a report take these and no other.
88var recordTypes = map[string]bool{
89 // The check worker (status/worker.go).
90 "pass.start": true, "pass.end": true, "pass.interrupted": true,
91 "change.seen": true, "batch.start": true, "batch.end": true,
92 "backoff": true, "publish.start": true, "publish.end": true,
93 // attest run (attest/run.go), on the host or a workstation.
94 "run.start": true, "run.end": true, "eval.start": true, "eval.end": true,
95 "check.queued": true, "check.build-start": true, "check.build-end": true,
96 "check.start": true, "check.result": true, "evidence.stored": true,
97 // A piece of a check's output, which a workstation sends from its
98 // spool's logs (Untrusted).
99 "check.output": true,
100 // valley approve (status/approve.go), on a workstation.
101 "approve.start": true, "approve.policy": true, "approve.coverage": true,
102 "approve.checks": true, "approve.request": true, "approve.end": true,
103 // One valley invocation, on a workstation (status/command.go).
104 "command": true,
105 // The integrator (integrator/timing.go).
106 "decision": true,
107 // The collector, about a report.
108 "report.gap": true,
109}
110
111// ClientType reports whether a report may carry records of type t: what a workstation or a
112// remote component says about its own runs.
113func ClientType(t string) bool {
114 if t == "command" {
115 return true
116 }
117 for _, prefix := range []string{"approve.", "run.", "eval.", "check.", "evidence."} {
118 if strings.HasPrefix(t, prefix) {
119 return recordTypes[t]
120 }
121 }
122 return false
123}
124
125// Bounds on one record. The text of a check.output record may be longer
126// than another string, up to OutputChunk before it is made safe to show.
127const (
128 MaxRecordBytes = 8 << 10
129 maxDataKeys = 32
130 maxString = 512
131 maxList = 64
132 OutputChunk = 1024
133)
134
135// Untrusted reports whether a record carries a check's own output, which a
136// reader sees only when it asks for logs.
137func (r *Record) Untrusted() bool { return r.Type == "check.output" }
138
139var (
140 nameRE = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._/@+-]{0,127}$`)
141 hexRE = regexp.MustCompile(`^[0-9a-f]{7,64}$`)
142 treeRE = regexp.MustCompile(`^[a-z0-9-]{1,16}:[0-9a-f]{16,128}$|^[0-9a-f]{16,128}$`)
143 keyRE = regexp.MustCompile(`^[a-z][a-z0-9_]{0,31}$`)
144 runRE = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$`)
145 epochRE = regexp.MustCompile(`^[0-9a-f]{16}$`)
146 stampRE = regexp.MustCompile(`^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d{1,9})?Z$`)
147)
148
149// Validate holds a record to its shape: a known type, a UTC time, names
150// and digests in their alphabets, and data of plain keys holding short
151// strings, numbers, booleans or short lists of strings, within
152// MaxRecordBytes in all.
153func (r *Record) Validate() error {
154 if !recordTypes[r.Type] {
155 return fmt.Errorf("unknown record type %q", clip(r.Type))
156 }
157 if !stampRE.MatchString(r.Time) {
158 return fmt.Errorf("time %q is not a UTC timestamp", clip(r.Time))
159 }
160 for field, v := range map[string]string{"project": r.Project, "change": r.Change, "check": r.Check} {
161 if v != "" && !nameRE.MatchString(v) {
162 return fmt.Errorf("%s %q is not a name", field, clip(v))
163 }
164 }
165 if r.Run != "" && !runRE.MatchString(r.Run) {
166 return fmt.Errorf("run %q is not a run ID", clip(r.Run))
167 }
168 if r.Head != "" && !hexRE.MatchString(r.Head) {
169 return fmt.Errorf("head %q is not an object ID", clip(r.Head))
170 }
171 if r.Tree != "" && !treeRE.MatchString(r.Tree) {
172 return fmt.Errorf("tree %q is not a tree digest", clip(r.Tree))
173 }
174 if r.Version < 0 || r.Version > 1<<20 {
175 return errors.New("version out of range")
176 }
177 if len(r.Data) > maxDataKeys {
178 return fmt.Errorf("%d data keys; at most %d", len(r.Data), maxDataKeys)
179 }
180 for k, v := range r.Data {
181 if !keyRE.MatchString(k) {
182 return fmt.Errorf("data key %q is not a plain name", clip(k))
183 }
184 if s, ok := v.(string); ok && k == "text" && r.Untrusted() && len(s) <= 6*OutputChunk && utf8.ValidString(s) {
185 continue
186 }
187 if err := plainValue(v); err != nil {
188 return fmt.Errorf("data %s: %w", k, err)
189 }
190 }
191 if p := r.Producer; p != nil {
192 if !nameRE.MatchString(p.Name) || len(p.Exe) > maxString || len(p.Version) > 64 || !utf8.ValidString(p.Exe+p.Version) {
193 return errors.New("producer is not a name, an executable and a version")
194 }
195 }
196 data, err := json.Marshal(r)
197 if err != nil {
198 return err
199 }
200 if len(data) > MaxRecordBytes {
201 return fmt.Errorf("record is %d bytes; at most %d", len(data), MaxRecordBytes)
202 }
203 return nil
204}
205
206func plainValue(v any) error {
207 switch v := v.(type) {
208 case nil, bool, float64, int, int64:
209 return nil
210 case string:
211 if len(v) > maxString || !utf8.ValidString(v) {
212 return errors.New("string too long or not UTF-8")
213 }
214 return nil
215 case []any:
216 if len(v) > maxList {
217 return errors.New("list too long")
218 }
219 for _, e := range v {
220 if s, ok := e.(string); !ok || len(s) > 128 || !utf8.ValidString(s) {
221 return errors.New("a list holds short strings only")
222 }
223 }
224 return nil
225 case []string:
226 if len(v) > maxList {
227 return errors.New("list too long")
228 }
229 for _, s := range v {
230 if len(s) > 128 || !utf8.ValidString(s) {
231 return errors.New("a list holds short strings only")
232 }
233 }
234 return nil
235 }
236 return fmt.Errorf("a %T is not a plain value", v)
237}
238
239// clip shortens what an error quotes back.
240func clip(s string) string {
241 if len(s) > 40 {
242 return s[:40] + "…"
243 }
244 return s
245}
246
247// Stamp is a time as records write it: UTC, to the millisecond.
248func Stamp(t time.Time) string { return t.UTC().Format("2006-01-02T15:04:05.000Z") }
249
250// DecodeRecord reads one record as a sender wrote it. A field the format
251// does not have is refused, not ignored.
252func DecodeRecord(line []byte) (Record, error) {
253 var r Record
254 d := json.NewDecoder(bytes.NewReader(line))
255 d.DisallowUnknownFields()
256 d.UseNumber()
257 if err := d.Decode(&r); err != nil {
258 return r, err
259 }
260 if d.More() {
261 return r, errors.New("trailing data after the record")
262 }
263 for k, v := range r.Data {
264 if n, ok := v.(json.Number); ok {
265 f, err := n.Float64()
266 if err != nil {
267 return r, fmt.Errorf("data %s: %w", k, err)
268 }
269 r.Data[k] = f
270 }
271 }
272 return r, nil
273}
274
275// Sanitize makes untrusted text safe to show: invalid UTF-8 is replaced,
276// and every control character but newline and tab, escape included, is
277// written as a visible \x.. sequence, so a log line cannot move a
278// terminal's cursor, change its colours or end a quoted field.
279func Sanitize(s string) string {
280 var b strings.Builder
281 for i := 0; i < len(s); {
282 r, size := utf8.DecodeRuneInString(s[i:])
283 switch {
284 case r == utf8.RuneError && size <= 1:
285 b.WriteString(`\ufffd`)
286 case r == '\n' || r == '\t':
287 b.WriteRune(r)
288 case r < 0x20 || r == 0x7f || (r >= 0x80 && r < 0xa0) || r == 0x2028 || r == 0x2029:
289 fmt.Fprintf(&b, `\x%02x`, r)
290 default:
291 b.WriteString(s[i : i+size])
292 }
293 i += size
294 }
295 return b.String()
296}