gunk-dev/the-valley

record.go

sourceb160a3fca731main's published tip history
9.4 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 (bin/valley), on a workstation.
101 "approve.start": true, "approve.policy": true, "approve.coverage": true,
102 "approve.checks": true, "approve.request": true, "approve.end": true,
103 // The integrator (integrator/timing.go).
104 "decision": true,
105 // The collector, about a report.
106 "report.gap": true,
107}
108
109// ClientType reports whether a report may carry records of type t: what a workstation or a
110// remote component says about its own runs.
111func ClientType(t string) bool {
112 for _, prefix := range []string{"approve.", "run.", "eval.", "check.", "evidence."} {
113 if strings.HasPrefix(t, prefix) {
114 return recordTypes[t]
115 }
116 }
117 return false
118}
119
120// Bounds on one record. The text of a check.output record may be longer
121// than another string, up to OutputChunk before it is made safe to show.
122const (
123 MaxRecordBytes = 8 << 10
124 maxDataKeys = 32
125 maxString = 512
126 maxList = 64
127 OutputChunk = 1024
128)
129
130// Untrusted reports whether a record carries a check's own output, which a
131// reader sees only when it asks for logs.
132func (r *Record) Untrusted() bool { return r.Type == "check.output" }
133
134var (
135 nameRE = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._/@+-]{0,127}$`)
136 hexRE = regexp.MustCompile(`^[0-9a-f]{7,64}$`)
137 treeRE = regexp.MustCompile(`^[a-z0-9-]{1,16}:[0-9a-f]{16,128}$|^[0-9a-f]{16,128}$`)
138 keyRE = regexp.MustCompile(`^[a-z][a-z0-9_]{0,31}$`)
139 runRE = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$`)
140 epochRE = regexp.MustCompile(`^[0-9a-f]{16}$`)
141 stampRE = regexp.MustCompile(`^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d{1,9})?Z$`)
142)
143
144// Validate holds a record to its shape: a known type, a UTC time, names
145// and digests in their alphabets, and data of plain keys holding short
146// strings, numbers, booleans or short lists of strings, within
147// MaxRecordBytes in all.
148func (r *Record) Validate() error {
149 if !recordTypes[r.Type] {
150 return fmt.Errorf("unknown record type %q", clip(r.Type))
151 }
152 if !stampRE.MatchString(r.Time) {
153 return fmt.Errorf("time %q is not a UTC timestamp", clip(r.Time))
154 }
155 for field, v := range map[string]string{"project": r.Project, "change": r.Change, "check": r.Check} {
156 if v != "" && !nameRE.MatchString(v) {
157 return fmt.Errorf("%s %q is not a name", field, clip(v))
158 }
159 }
160 if r.Run != "" && !runRE.MatchString(r.Run) {
161 return fmt.Errorf("run %q is not a run ID", clip(r.Run))
162 }
163 if r.Head != "" && !hexRE.MatchString(r.Head) {
164 return fmt.Errorf("head %q is not an object ID", clip(r.Head))
165 }
166 if r.Tree != "" && !treeRE.MatchString(r.Tree) {
167 return fmt.Errorf("tree %q is not a tree digest", clip(r.Tree))
168 }
169 if r.Version < 0 || r.Version > 1<<20 {
170 return errors.New("version out of range")
171 }
172 if len(r.Data) > maxDataKeys {
173 return fmt.Errorf("%d data keys; at most %d", len(r.Data), maxDataKeys)
174 }
175 for k, v := range r.Data {
176 if !keyRE.MatchString(k) {
177 return fmt.Errorf("data key %q is not a plain name", clip(k))
178 }
179 if s, ok := v.(string); ok && k == "text" && r.Untrusted() && len(s) <= 6*OutputChunk && utf8.ValidString(s) {
180 continue
181 }
182 if err := plainValue(v); err != nil {
183 return fmt.Errorf("data %s: %w", k, err)
184 }
185 }
186 if p := r.Producer; p != nil {
187 if !nameRE.MatchString(p.Name) || len(p.Exe) > maxString || len(p.Version) > 64 || !utf8.ValidString(p.Exe+p.Version) {
188 return errors.New("producer is not a name, an executable and a version")
189 }
190 }
191 data, err := json.Marshal(r)
192 if err != nil {
193 return err
194 }
195 if len(data) > MaxRecordBytes {
196 return fmt.Errorf("record is %d bytes; at most %d", len(data), MaxRecordBytes)
197 }
198 return nil
199}
200
201func plainValue(v any) error {
202 switch v := v.(type) {
203 case nil, bool, float64, int, int64:
204 return nil
205 case string:
206 if len(v) > maxString || !utf8.ValidString(v) {
207 return errors.New("string too long or not UTF-8")
208 }
209 return nil
210 case []any:
211 if len(v) > maxList {
212 return errors.New("list too long")
213 }
214 for _, e := range v {
215 if s, ok := e.(string); !ok || len(s) > 128 || !utf8.ValidString(s) {
216 return errors.New("a list holds short strings only")
217 }
218 }
219 return nil
220 case []string:
221 if len(v) > maxList {
222 return errors.New("list too long")
223 }
224 for _, s := range v {
225 if len(s) > 128 || !utf8.ValidString(s) {
226 return errors.New("a list holds short strings only")
227 }
228 }
229 return nil
230 }
231 return fmt.Errorf("a %T is not a plain value", v)
232}
233
234// clip shortens what an error quotes back.
235func clip(s string) string {
236 if len(s) > 40 {
237 return s[:40] + "…"
238 }
239 return s
240}
241
242// Stamp is a time as records write it: UTC, to the millisecond.
243func Stamp(t time.Time) string { return t.UTC().Format("2006-01-02T15:04:05.000Z") }
244
245// DecodeRecord reads one record as a sender wrote it. A field the format
246// does not have is refused, not ignored.
247func DecodeRecord(line []byte) (Record, error) {
248 var r Record
249 d := json.NewDecoder(bytes.NewReader(line))
250 d.DisallowUnknownFields()
251 d.UseNumber()
252 if err := d.Decode(&r); err != nil {
253 return r, err
254 }
255 if d.More() {
256 return r, errors.New("trailing data after the record")
257 }
258 for k, v := range r.Data {
259 if n, ok := v.(json.Number); ok {
260 f, err := n.Float64()
261 if err != nil {
262 return r, fmt.Errorf("data %s: %w", k, err)
263 }
264 r.Data[k] = f
265 }
266 }
267 return r, nil
268}
269
270// Sanitize makes untrusted text safe to show: invalid UTF-8 is replaced,
271// and every control character but newline and tab, escape included, is
272// written as a visible \x.. sequence, so a log line cannot move a
273// terminal's cursor, change its colours or end a quoted field.
274func Sanitize(s string) string {
275 var b strings.Builder
276 for i := 0; i < len(s); {
277 r, size := utf8.DecodeRuneInString(s[i:])
278 switch {
279 case r == utf8.RuneError && size <= 1:
280 b.WriteString(`\ufffd`)
281 case r == '\n' || r == '\t':
282 b.WriteRune(r)
283 case r < 0x20 || r == 0x7f || (r >= 0x80 && r < 0xa0) || r == 0x2028 || r == 0x2029:
284 fmt.Fprintf(&b, `\x%02x`, r)
285 default:
286 b.WriteString(s[i : i+size])
287 }
288 i += size
289 }
290 return b.String()
291}