internal/control/control.go

f8c1e35051a416f451bc97dd49f0253c6673c765
gitbay/internal/control/control.go

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