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