internal/control/control.go
335 lines · 11125 bytes
1// Package control implements the forge control commands executed over SSH.
2// Every command here is reachable from bare OpenSSH: argv in, JSON or plain
3// text on stdout, diagnostics on stderr, exit code out.
4package control
5
6import (
7 "encoding/json"
8 "errors"
9 "fmt"
10 "io"
11 "reflect"
12 "slices"
13 "strings"
14 "time"
15
16 "gitbay.org/gitbay/internal/config"
17 "gitbay.org/gitbay/internal/protocol"
18 "gitbay.org/gitbay/internal/store"
19)
20
21type Ctx struct {
22 User store.User
23 Scope string // scope of the key that authenticated this session
24 Store *store.Store
25 Cfg config.Config
26 Stdin io.Reader
27 Stdout io.Writer
28 Stderr io.Writer
29 JSON bool
30 // ViaAPI marks requests arriving over the HTTP token API. Some
31 // commands (token management) are SSH-only: an API token must never
32 // mint further credentials.
33 ViaAPI bool
34 // ReadOnly is set for read-scoped API tokens.
35 ReadOnly bool
36 // Source identifies the credential behind this session for the audit
37 // log: an SSH key fingerprint, or "api" for token requests.
38 Source string
39 // Cmd is the command being run, set by Dispatch, so a usage error can
40 // print the registered usage rather than a copy of it.
41 Cmd Command
42}
43
44// usage reports a bad invocation with the command's registered usage,
45// the one source of it.
46func (c *Ctx) usage() int {
47 return c.fail(protocol.ExitUsage, "usage: %s", c.Cmd.Usage)
48}
49
50type Command struct {
51 Path []string // e.g. ["keys", "add"]
52 // Summary is one line of prose: what the command does, no argument
53 // syntax. Usage is the argument syntax, opening with the command path.
54 // help renders them separately, so neither may carry the other's job.
55 Summary string
56 Usage string
57 ReadsStdin bool
58 ReadOnly bool // safe for read-scoped API tokens
59 SSHOnly bool // refused over the HTTP API (credential minting)
60 Run func(c *Ctx, args []string) int
61}
62
63var registry []Command
64
65func register(cmd Command) { registry = append(registry, cmd) }
66
67// Commands returns the registry, for the bare-ssh reachability test.
68func Commands() []Command { return registry }
69
70// Lookup resolves argv to a command by longest path match, returning the
71// command and the remaining arguments.
72func Lookup(argv []string) (Command, []string, bool) {
73 best := -1
74 var found Command
75 for _, cmd := range registry {
76 if len(cmd.Path) <= len(argv) && slices.Equal(cmd.Path, argv[:len(cmd.Path)]) && len(cmd.Path) > best {
77 best = len(cmd.Path)
78 found = cmd
79 }
80 }
81 if best < 0 {
82 return Command{}, nil, false
83 }
84 return found, argv[best:], true
85}
86
87// Dispatch runs argv for an authenticated session. The dispatcher — not the
88// handlers — enforces key scope: control commands require a full-scope key.
89func Dispatch(c *Ctx, argv []string) int {
90 if len(argv) == 0 {
91 return c.fail(protocol.ExitUsage, "no command given; try: ssh <host> help")
92 }
93 cmd, rest, ok := Lookup(argv)
94 c.Cmd = cmd
95 if !ok {
96 return c.fail(protocol.ExitUsage, "unknown command %q", argv[0])
97 }
98 // Strip the global --json flag wherever it appears, before any
99 // refusal below: a scripted caller needs the envelope most when it is
100 // being told no (#109).
101 args := rest[:0:0]
102 for _, a := range rest {
103 if a == "--json" {
104 c.JSON = true
105 continue
106 }
107 args = append(args, a)
108 }
109 // A runner-scoped key reaches the runner protocol and nothing else, so
110 // the key a CI host holds cannot administer the instance.
111 if c.Scope != "full" && !(c.Scope == "runner" && cmd.Path[0] == "runner") {
112 return c.fail(protocol.ExitDenied, "this key's scope (%s) does not allow control commands; use a key added with --scope full", c.Scope)
113 }
114 if c.ViaAPI && cmd.SSHOnly {
115 return c.fail(protocol.ExitDenied, "%s is only available over SSH", joinPath(cmd.Path))
116 }
117 if c.ReadOnly && !cmd.ReadOnly {
118 return c.fail(protocol.ExitDenied, "this token is read-only; %s modifies state — mint one with --scope full", joinPath(cmd.Path))
119 }
120 // The SSH listener refuses a disabled account before it gets here; the
121 // API and the web reach Dispatch directly, so the check lives here too.
122 if c.User.Disabled {
123 return c.fail(protocol.ExitDenied, "this account is disabled; ask an instance admin to enable it")
124 }
125 // The admin noun is gated here as well as in each handler, so a new
126 // admin command that forgets requireInstanceAdmin is still refused.
127 if cmd.Path[0] == "admin" && !c.User.IsAdmin {
128 return c.fail(protocol.ExitDenied, "admin commands are for instance admins; ask one")
129 }
130 if c.User.Pending && !pendingAllowed(cmd.Path) {
131 return c.fail(protocol.ExitDenied,
132 "your account is not active yet: verify your email first (email verify <code>, or ask for the mail again with email add)")
133 }
134 if code := limitWrites(c, cmd); code >= 0 {
135 return code
136 }
137 if !cmd.ReadsStdin {
138 c.Stdin = emptyReader{}
139 }
140 code := cmd.Run(c, args)
141 // Every successful mutating command lands in the audit log.
142 if code == protocol.ExitOK && !cmd.ReadOnly {
143 c.Store.Audit(c.User.ID, "cmd "+joinPath(cmd.Path), map[string]any{
144 "argv": auditArgs(args),
145 "source": c.Source,
146 })
147 }
148 return code
149}
150
151// auditArgs is argv with flag values dropped. Secrets never reach argv —
152// they travel on stdin — but prose does: `issue create a/b --title x
153// --body <the whole issue>` used to store the body verbatim, in a table
154// nothing pruned, for a repository that may be private. The identifiers
155// are positional, so keeping those and the flag names says what was done
156// without copying what was written (#122).
157func auditArgs(args []string) []string {
158 out := make([]string, 0, len(args))
159 for i := 0; i < len(args); i++ {
160 a := args[i]
161 if !strings.HasPrefix(a, "--") {
162 out = append(out, a)
163 continue
164 }
165 out = append(out, a)
166 // "--" ends flag parsing; everything after it is positional.
167 if a == "--" {
168 out = append(out, args[i+1:]...)
169 break
170 }
171 // A flag's value is the next argument unless that is itself a
172 // flag, which is how a switch is told from one that takes a value
173 // without consulting the command's spec.
174 if i+1 < len(args) && !strings.HasPrefix(args[i+1], "--") {
175 i++
176 }
177 }
178 return out
179}
180
181// pendingAllowed lists what an unverified self-registered account may do.
182// limitWrites spends one token of the account's write budget, and refuses
183// with the wait when it is empty. Returns -1 when the command may run.
184//
185// Exempt: read-only commands, which cost the instance nothing to serve
186// twice; the runner protocol, which streams a build's log in many small
187// writes and would throttle CI; and the host CLI on the server, which has
188// no account to key on and is already root-equivalent.
189func limitWrites(c *Ctx, cmd Command) int {
190 if cmd.ReadOnly || cmd.Path[0] == "runner" || c.Source == "host" || c.User.ID == 0 {
191 return -1
192 }
193 perMinute := c.Cfg.Limits.WriteRate
194 if perMinute == 0 {
195 perMinute = config.DefaultWriteRate
196 }
197 if perMinute < 0 {
198 return -1
199 }
200 if ok, wait := writes.allow(c.User.ID, perMinute); !ok {
201 return c.fail(protocol.ExitDenied,
202 "too many writes: %d a minute per account; try again in %s",
203 perMinute, wait.Round(time.Second))
204 }
205 return -1
206}
207
208func pendingAllowed(path []string) bool {
209 key := joinPath(path)
210 return key == "email verify" || key == "email add" || key == "whoami" || key == "help"
211}
212
213type emptyReader struct{}
214
215func (emptyReader) Read([]byte) (int, error) { return 0, io.EOF }
216
217// emit writes data as the command result: a JSON envelope under --json,
218// otherwise via the plain formatter.
219func (c *Ctx) emit(data any, plain func(w io.Writer)) int {
220 // A nil slice would serialize as null; consumers should see [].
221 v := reflect.ValueOf(data)
222 if v.Kind() == reflect.Slice && v.IsNil() {
223 data = reflect.MakeSlice(v.Type(), 0, 0).Interface()
224 }
225 // An empty list prints nothing a script would read; the person at
226 // the terminal hears about it on stderr.
227 if !c.JSON && v.Kind() == reflect.Slice && v.Len() == 0 {
228 fmt.Fprintln(c.Stderr, "nothing to list")
229 return protocol.ExitOK
230 }
231 if c.JSON {
232 enc := json.NewEncoder(c.Stdout)
233 enc.SetEscapeHTML(false)
234 if err := enc.Encode(protocol.Envelope{ProtocolVersion: protocol.Version, Data: data}); err != nil {
235 return protocol.ExitFailure
236 }
237 return protocol.ExitOK
238 }
239 plain(c.Stdout)
240 return protocol.ExitOK
241}
242
243// failErr reports an error from a store call: not-found is not-found,
244// and anything else — the database failing, a duplicate, a state that
245// does not allow the change — is a failure. An error about the caller's
246// own arguments goes through failInput instead; this used to default to
247// usage, which turned every refusal into exit 2 (#211).
248func (c *Ctx) failErr(err error) int {
249 if errors.Is(err, store.ErrNotFound) {
250 return c.fail(protocol.ExitNotFound, "%v", err)
251 }
252 return c.fail(protocol.ExitFailure, "%v", err)
253}
254
255// failInput reports an error about the caller's input — a name that does
256// not validate, a flag value out of range, a body that could not be read
257// — as a usage error, unless the database or I/O failed underneath it.
258// A SQLite I/O error used to be a usage error and an HTTP 400 (#107).
259func (c *Ctx) failInput(err error) int {
260 switch {
261 case errors.Is(err, store.ErrNotFound):
262 return c.fail(protocol.ExitNotFound, "%v", err)
263 case store.IsInternal(err):
264 return c.fail(protocol.ExitFailure, "%v", err)
265 }
266 return c.fail(protocol.ExitUsage, "%v", err)
267}
268
269func (c *Ctx) fail(code int, format string, args ...any) int {
270 msg := fmt.Sprintf(format, args...)
271 if c.JSON {
272 enc := json.NewEncoder(c.Stdout)
273 enc.SetEscapeHTML(false)
274 enc.Encode(protocol.Envelope{ProtocolVersion: protocol.Version, Error: msg})
275 } else {
276 fmt.Fprintln(c.Stderr, msg)
277 }
278 return code
279}
280
281func init() {
282 register(Command{
283 Path: []string{"help"},
284 Summary: "list available commands",
285 Usage: "help [<prefix>...]",
286 ReadOnly: true,
287 Run: runHelp,
288 })
289}
290
291// helpEntry is one row of the registry as help reports it.
292type helpEntry struct {
293 Path string `json:"path"`
294 Summary string `json:"summary"`
295 Usage string `json:"usage"`
296}
297
298// runHelp lists the registry, sorted, so a noun's commands sit together.
299// A prefix narrows the listing and adds each command's argument syntax —
300// the only place flags are written down. The unfiltered listing stays one
301// line per command.
302func runHelp(c *Ctx, args []string) int {
303 prefix := joinPath(args)
304 var matched []helpEntry
305 for _, cmd := range registry {
306 p := joinPath(cmd.Path)
307 if prefix != "" && p != prefix && !strings.HasPrefix(p, prefix+" ") {
308 continue
309 }
310 matched = append(matched, helpEntry{Path: p, Summary: cmd.Summary, Usage: cmd.Usage})
311 }
312 if len(matched) == 0 {
313 return c.fail(protocol.ExitNotFound, "no command matches %q; try: help", prefix)
314 }
315 slices.SortFunc(matched, func(a, b helpEntry) int { return strings.Compare(a.Path, b.Path) })
316 return c.emit(matched, func(w io.Writer) {
317 for _, e := range matched {
318 fmt.Fprintf(w, "%-24s %s\n", e.Path, e.Summary)
319 if prefix != "" {
320 fmt.Fprintf(w, " %s\n", e.Usage)
321 }
322 }
323 })
324}
325
326func joinPath(p []string) string {
327 out := ""
328 for i, s := range p {
329 if i > 0 {
330 out += " "
331 }
332 out += s
333 }
334 return out
335}