internal/control/control.go

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