gunk-dev/the-valley

protocol.go

source9a7e5066fc08main's published tip history
8.4 KiB
1package telemetry
2
3// The telemetry command, as a session sends it over ssh, and the request
4// the git user's shell passes to the collector for it.
5//
6// The command is a closed grammar: the word valley-telemetry, an
7// operation, and the flags that operation takes, each written --flag=value
8// and separated by single spaces. There is no quoting, no path, no unit
9// name and no pattern in it. Anything else is refused whole, and the
10// shell never hands a refused command to git-shell or to anything else.
11//
12// valley-telemetry sources
13// valley-telemetry snapshot
14// valley-telemetry read [--source=NAME] [--since=CURSOR] [--limit=N] [--logs]
15// valley-telemetry follow [--source=NAME] [--since=CURSOR] [--seconds=N] [--logs]
16// valley-telemetry report
17//
18// report is the one operation that sends records: they follow on standard
19// input, one JSON line each. Every other operation only reads.
20
21import (
22 "encoding/json"
23 "errors"
24 "fmt"
25 "regexp"
26 "sort"
27 "strconv"
28 "strings"
29)
30
31// CommandName is the first word of every telemetry command.
32const CommandName = "valley-telemetry"
33
34// The operations, and the grant each needs.
35const (
36 OpSources = "sources"
37 OpSnapshot = "snapshot"
38 OpRead = "read"
39 OpFollow = "follow"
40 OpReport = "report"
41
42 // GrantObserve reads every source on the host: shared logs span every
43 // project, so reading them is a host-wide grant, apart from any
44 // project's read consent. GrantReport sends records about the
45 // sender's own runs.
46 GrantObserve = "observe"
47 GrantReport = "report"
48)
49
50// Limits the collector holds every request to, whatever it asks for.
51const (
52 DefaultReadLimit = 200
53 MaxReadLimit = 1000
54 DefaultFollowSeconds = 60
55 MaxFollowSeconds = 300
56 MaxResponseBytes = 4 << 20
57 MaxReportBytes = 1 << 20
58 MaxReportRecords = 1000
59 LogTailBytes = 64 << 10
60 MaxCommandBytes = 4096
61)
62
63// Request is what the shell passes to the collector: the operation and
64// its flags as the command gave them, and the principal the shell derived
65// from the key sshd authenticated. Nothing in the command names it.
66type Request struct {
67 V int `json:"v"`
68 Principal string `json:"principal"`
69 Op string `json:"op"`
70 Source string `json:"source,omitempty"`
71 Cursor string `json:"cursor,omitempty"`
72 Limit int `json:"limit,omitempty"`
73 Seconds int `json:"seconds,omitempty"`
74 Logs bool `json:"logs,omitempty"`
75}
76
77// Grant is the grant the request's operation needs.
78func (r Request) Grant() string {
79 if r.Op == OpReport {
80 return GrantReport
81 }
82 return GrantObserve
83}
84
85var (
86 sourceRE = regexp.MustCompile(`^[a-z0-9][a-z0-9._@-]{0,95}$`)
87 cursorRE = regexp.MustCompile(`^[a-z0-9._@-]{1,96}=[0-9a-f]{16}:[0-9]{1,18}$`)
88 principalRE = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$`)
89)
90
91// ValidPrincipal reports whether s is a principal name, as the push
92// policy reads one.
93func ValidPrincipal(s string) bool { return principalRE.MatchString(s) }
94
95// ValidSource reports whether s is a source or stream name.
96func ValidSource(s string) bool { return sourceRE.MatchString(s) }
97
98// IsCommand reports whether a session's command is meant as a telemetry
99// command: anything that starts with the command's name. Such a command
100// is the telemetry interface's to accept or refuse, and nothing else's.
101func IsCommand(cmd string) bool { return strings.HasPrefix(cmd, CommandName) }
102
103var opFlags = map[string]map[string]bool{
104 OpSources: {},
105 OpSnapshot: {},
106 OpRead: {"source": true, "since": true, "limit": true, "logs": true},
107 OpFollow: {"source": true, "since": true, "seconds": true, "logs": true},
108 OpReport: {},
109}
110
111// ParseCommand reads a telemetry command. principal is not part of it.
112func ParseCommand(cmd string) (Request, error) {
113 r := Request{V: 1}
114 if len(cmd) > MaxCommandBytes {
115 return r, errors.New("the command is too long")
116 }
117 for i := 0; i < len(cmd); i++ {
118 if cmd[i] < 0x21 && cmd[i] != ' ' || cmd[i] > 0x7e {
119 return r, errors.New("the command holds a character it may not")
120 }
121 }
122 words := strings.Split(cmd, " ")
123 if len(words) < 2 || words[0] != CommandName {
124 return r, fmt.Errorf("usage: %s sources|snapshot|read|follow|report [--flag=value]...", CommandName)
125 }
126 r.Op = words[1]
127 allowed, ok := opFlags[r.Op]
128 if !ok {
129 return r, fmt.Errorf("%q is not a telemetry operation", clip(r.Op))
130 }
131 seen := map[string]bool{}
132 for _, w := range words[2:] {
133 if !strings.HasPrefix(w, "--") {
134 return r, fmt.Errorf("%q is not a flag", clip(w))
135 }
136 name, value, hasValue := strings.Cut(w[2:], "=")
137 if !allowed[name] {
138 return r, fmt.Errorf("%s takes no --%s", r.Op, clip(name))
139 }
140 if seen[name] {
141 return r, fmt.Errorf("--%s is given twice", name)
142 }
143 seen[name] = true
144 if name == "logs" {
145 if hasValue {
146 return r, errors.New("--logs takes no value")
147 }
148 r.Logs = true
149 continue
150 }
151 if !hasValue || value == "" {
152 return r, fmt.Errorf("--%s needs a value", name)
153 }
154 switch name {
155 case "source":
156 if !ValidSource(value) {
157 return r, fmt.Errorf("%q is not a source name", clip(value))
158 }
159 r.Source = value
160 case "since":
161 if _, err := ParseCursor(value); err != nil {
162 return r, err
163 }
164 r.Cursor = value
165 case "limit", "seconds":
166 n, err := strconv.Atoi(value)
167 if err != nil || n < 1 || n > 1_000_000 || strconv.Itoa(n) != value {
168 return r, fmt.Errorf("--%s=%s is not a positive number", name, clip(value))
169 }
170 if name == "limit" {
171 r.Limit = n
172 } else {
173 r.Seconds = n
174 }
175 }
176 }
177 return r, nil
178}
179
180// Command is the command that asks for r: the inverse of ParseCommand.
181func (r Request) Command() string {
182 words := []string{CommandName, r.Op}
183 if r.Source != "" {
184 words = append(words, "--source="+r.Source)
185 }
186 if r.Cursor != "" {
187 words = append(words, "--since="+r.Cursor)
188 }
189 if r.Limit > 0 {
190 words = append(words, "--limit="+strconv.Itoa(r.Limit))
191 }
192 if r.Seconds > 0 {
193 words = append(words, "--seconds="+strconv.Itoa(r.Seconds))
194 }
195 if r.Logs {
196 words = append(words, "--logs")
197 }
198 return strings.Join(words, " ")
199}
200
201// Check holds a request the collector received to what ParseCommand
202// could have produced, and clamps its limits. The collector checks every
203// request again, whatever passed it on.
204func (r *Request) Check() error {
205 if r.V != 1 {
206 return fmt.Errorf("request version %d is not 1", r.V)
207 }
208 if !ValidPrincipal(r.Principal) {
209 return errors.New("the request names no principal")
210 }
211 parsed, err := ParseCommand(r.Command())
212 if err != nil {
213 return err
214 }
215 parsed.Principal = r.Principal
216 if parsed != *r {
217 return errors.New("the request is not one a command asks for")
218 }
219 if r.Limit <= 0 {
220 r.Limit = DefaultReadLimit
221 }
222 r.Limit = min(r.Limit, MaxReadLimit)
223 if r.Seconds <= 0 {
224 r.Seconds = DefaultFollowSeconds
225 }
226 r.Seconds = min(r.Seconds, MaxFollowSeconds)
227 return nil
228}
229
230// DecodeRequest reads the one line the shell sends.
231func DecodeRequest(line []byte) (Request, error) {
232 var r Request
233 d := json.NewDecoder(strings.NewReader(string(line)))
234 d.DisallowUnknownFields()
235 if err := d.Decode(&r); err != nil {
236 return r, fmt.Errorf("the request does not read: %w", err)
237 }
238 return r, nil
239}
240
241// A cursor says how far a reader has read: for each stream, its epoch and
242// the number of the last record read, as stream=epoch:seq separated by
243// commas. A stream made again has another epoch, and a cursor naming the
244// old one reads it from its start, with the reset said.
245type Cursor map[string]Position
246
247// Position is how far one stream has been read.
248type Position struct {
249 Epoch string
250 Seq int64
251}
252
253// ParseCursor reads a cursor.
254func ParseCursor(s string) (Cursor, error) {
255 c := Cursor{}
256 if s == "" {
257 return c, nil
258 }
259 parts := strings.Split(s, ",")
260 if len(parts) > 64 {
261 return nil, errors.New("the cursor names too many streams")
262 }
263 for _, p := range parts {
264 if !cursorRE.MatchString(p) {
265 return nil, fmt.Errorf("%q is not a cursor", clip(p))
266 }
267 name, rest, _ := strings.Cut(p, "=")
268 epoch, seq, _ := strings.Cut(rest, ":")
269 n, err := strconv.ParseInt(seq, 10, 64)
270 if err != nil {
271 return nil, fmt.Errorf("%q is not a cursor", clip(p))
272 }
273 if _, dup := c[name]; dup {
274 return nil, fmt.Errorf("the cursor names %s twice", name)
275 }
276 c[name] = Position{epoch, n}
277 }
278 return c, nil
279}
280
281func (c Cursor) String() string {
282 names := make([]string, 0, len(c))
283 for n := range c {
284 names = append(names, n)
285 }
286 sort.Strings(names)
287 parts := make([]string, len(names))
288 for i, n := range names {
289 parts[i] = fmt.Sprintf("%s=%s:%d", n, c[n].Epoch, c[n].Seq)
290 }
291 return strings.Join(parts, ",")
292}