internal/control/identity.go

8dcfa45a8ac03a5ff9c36828274d05acadcf846c
gitbay/internal/control/identity.go history · blame · raw

254 lines · 7547 bytes

  1package control
  2
  3import (
  4	"errors"
  5	"fmt"
  6	"io"
  7	"strings"
  8	"time"
  9	"unicode"
 10
 11	"golang.org/x/crypto/ssh"
 12
 13	"gitbay.org/gitbay/internal/protocol"
 14	"gitbay.org/gitbay/internal/store"
 15)
 16
 17func init() {
 18	register(Command{
 19		Path:     []string{"whoami"},
 20		Summary:  "show the authenticated account",
 21		Usage:    "whoami",
 22		Examples: []string{"whoami"},
 23		ReadOnly: true,
 24		Run:      runWhoami,
 25	})
 26	register(Command{
 27		Path:     []string{"keys", "list"},
 28		Summary:  "list registered SSH keys",
 29		Usage:    "keys list",
 30		Examples: []string{"keys list"},
 31		ReadOnly: true,
 32		Run:      runKeysList,
 33	})
 34	register(Command{
 35		Path:    []string{"keys", "add"},
 36		Summary: "register an SSH public key (authorized_keys format)",
 37		Usage:   "keys add [--scope full|git|runner] [--label <text>] [--ttl 30d|720h] < key.pub",
 38		Flags: []Flag{
 39			{"--scope", "full|git|runner", "what the key may do", "full"},
 40			{"--label", "<text>", "a name for the key", ""},
 41			{"--ttl", "30d|720h", "how long the key authenticates; an expiring key cannot mint credentials", "never expires"},
 42		},
 43		Examples:        []string{"keys add --label laptop < key.pub", "keys add --scope git --ttl 90d < ci.pub"},
 44		ReadsStdin:      true,
 45		MintsCredential: true,
 46		Run:             runKeysAdd,
 47	})
 48	register(Command{
 49		Path:     []string{"keys", "label"},
 50		Summary:  "name a key; an empty label clears it",
 51		Usage:    "keys label <fingerprint> [<text>]",
 52		Examples: []string{`keys label SHA256:abcd1234 "work laptop"`},
 53		Run:      runKeysLabel,
 54	})
 55	register(Command{
 56		Path:     []string{"keys", "remove"},
 57		Summary:  "remove an SSH key by fingerprint",
 58		Usage:    "keys remove <fingerprint>",
 59		Examples: []string{"keys remove SHA256:abcd1234"},
 60		Run:      runKeysRemove,
 61	})
 62}
 63
 64func runWhoami(c *Ctx, args []string) int {
 65	if len(args) != 0 {
 66		return c.usage()
 67	}
 68	type out struct {
 69		Username string `json:"username"`
 70		Admin    bool   `json:"admin"`
 71		KeyScope string `json:"key_scope"`
 72	}
 73	d := out{Username: c.User.Username, Admin: c.User.IsAdmin, KeyScope: c.Scope}
 74	return c.emit(d, func(w io.Writer) {
 75		fmt.Fprintln(w, d.Username)
 76	})
 77}
 78
 79func runKeysList(c *Ctx, args []string) int {
 80	if len(args) != 0 {
 81		return c.usage()
 82	}
 83	keys, err := c.Store.ListSSHKeys(c.User.ID)
 84	if err != nil {
 85		return c.fail(protocol.ExitFailure, "listing keys: %v", err)
 86	}
 87	type out struct {
 88		Fingerprint string     `json:"fingerprint"`
 89		Algo        string     `json:"algo"`
 90		Scope       string     `json:"scope"`
 91		Label       string     `json:"label"`
 92		CreatedBy   string     `json:"created_by,omitempty"`
 93		LastUsedAt  string     `json:"last_used_at,omitempty"`
 94		ExpiresAt   *time.Time `json:"expires_at,omitempty"`
 95	}
 96	var ds []out
 97	for _, k := range keys {
 98		ds = append(ds, out{k.Fingerprint, k.Algo, k.Scope, k.Label, k.CreatedBy, k.LastUsedAt, k.ExpiresAt})
 99	}
100	now := time.Now()
101	return c.emit(ds, func(w io.Writer) {
102		tb := c.table(w, "FINGERPRINT", "ALGO", "SCOPE", "LABEL", "USED", "EXPIRES")
103		for _, d := range ds {
104			tb.row(cFlex(d.Fingerprint), cText(d.Algo), cState(d.Scope), cText(d.Label),
105				cText(c.usedText(d.LastUsedAt)), cText(expiresText(d.ExpiresAt, now)))
106		}
107		tb.flush()
108	})
109}
110
111// maxKeyLabel bounds a key's name. Labels are display text, one line.
112const maxKeyLabel = 64
113
114// keyLabel normalises a label: surrounding space trimmed, control
115// characters refused, length capped. An empty result is a valid "no
116// label".
117func keyLabel(s string) (string, error) {
118	s = strings.TrimSpace(s)
119	if len(s) > maxKeyLabel {
120		return "", fmt.Errorf("label is longer than %d bytes", maxKeyLabel)
121	}
122	for _, r := range s {
123		if unicode.IsControl(r) {
124			return "", errors.New("label must be a single line of printable text")
125		}
126	}
127	return s, nil
128}
129
130// usedText is a key's last use as a USED cell shows it.
131func (c *Ctx) usedText(ts string) string {
132	switch {
133	case ts == "":
134		return "never"
135	case c.Term.Cols == 0:
136		return stamp(ts)
137	}
138	return relAge(ts, termNow())
139}
140
141// expiresText is a credential's expiry as an EXPIRES cell shows it. It
142// is absolute at a terminal too: relAge reads only the past.
143func expiresText(t *time.Time, now time.Time) string {
144	if t == nil {
145		return "never"
146	}
147	s := stamp(t.UTC().Format(time.RFC3339Nano))
148	if !t.After(now) {
149		return "expired " + s
150	}
151	return s
152}
153
154func runKeysAdd(c *Ctx, args []string) int {
155	f, err := c.parseArgs(args, flagSpec{Values: []string{"--scope", "--label", "--ttl"}, MaxPos: 0, Usage: c.Cmd.Usage})
156	if err != nil {
157		return c.fail(protocol.ExitUsage, "%v", err)
158	}
159	scope := "full"
160	if f.Has("--scope") {
161		scope = f.Value("--scope")
162	}
163	if scope != "full" && scope != "git" && scope != "runner" {
164		// deploy:* scopes are granted via repo settings, not self-service.
165		return c.fail(protocol.ExitUsage, "scope must be full, git or runner")
166	}
167	expires, code := c.ttlFlag(f)
168	if code >= 0 {
169		return code
170	}
171	raw, err := io.ReadAll(io.LimitReader(c.Stdin, 64<<10))
172	if err != nil {
173		return c.fail(protocol.ExitFailure, "reading key: %v", err)
174	}
175	pub, comment, _, _, err := ssh.ParseAuthorizedKey(raw)
176	if err != nil {
177		return c.fail(protocol.ExitUsage, "not a valid public key in authorized_keys format: %v", err)
178	}
179	// The key's own comment is the label unless --label says otherwise.
180	label := comment
181	if f.Has("--label") {
182		label = f.Value("--label")
183	}
184	if label, err = keyLabel(label); err != nil {
185		return c.fail(protocol.ExitUsage, "%v", err)
186	}
187	fp := ssh.FingerprintSHA256(pub)
188	if err := c.Store.AddSSHKeyFrom(c.User.ID, fp, pub.Type(), pub.Marshal(), scope, label, store.KeyOrigin{CreatedByToken: c.TokenID, ExpiresAt: expires}); err != nil {
189		if errors.Is(err, store.ErrDuplicateKey) {
190			return c.failErr(err)
191		}
192		return c.fail(protocol.ExitFailure, "adding key: %v", err)
193	}
194	type out struct {
195		Fingerprint string     `json:"fingerprint"`
196		Scope       string     `json:"scope"`
197		Label       string     `json:"label"`
198		ExpiresAt   *time.Time `json:"expires_at,omitempty"`
199	}
200	d := out{fp, scope, label, expires}
201	return c.emit(d, func(w io.Writer) {
202		line := fmt.Sprintf("added %s (%s)", d.Fingerprint, d.Scope)
203		if d.Label != "" {
204			line += " " + d.Label
205		}
206		if d.ExpiresAt != nil {
207			line += ", expires " + expiresText(d.ExpiresAt, time.Now())
208		}
209		fmt.Fprintln(w, line)
210	})
211}
212
213func runKeysLabel(c *Ctx, args []string) int {
214	if len(args) < 1 || len(args) > 2 {
215		return c.usage()
216	}
217	label := ""
218	if len(args) == 2 {
219		label = args[1]
220	}
221	label, err := keyLabel(label)
222	if err != nil {
223		return c.fail(protocol.ExitUsage, "%v", err)
224	}
225	if err := c.Store.SetSSHKeyLabel(c.User.ID, args[0], label); err != nil {
226		if errors.Is(err, store.ErrNotFound) {
227			return c.fail(protocol.ExitNotFound, "no key with fingerprint %s on your account", args[0])
228		}
229		return c.fail(protocol.ExitFailure, "labelling key: %v", err)
230	}
231	d := map[string]string{"fingerprint": args[0], "label": label}
232	return c.emit(d, func(w io.Writer) {
233		if label == "" {
234			fmt.Fprintf(w, "cleared label on %s\n", args[0])
235			return
236		}
237		fmt.Fprintf(w, "%s is now %q\n", args[0], label)
238	})
239}
240
241func runKeysRemove(c *Ctx, args []string) int {
242	if len(args) != 1 {
243		return c.usage()
244	}
245	if err := c.Store.RemoveSSHKey(c.User.ID, args[0]); err != nil {
246		if errors.Is(err, store.ErrNotFound) {
247			return c.fail(protocol.ExitNotFound, "no key with fingerprint %s on your account", args[0])
248		}
249		return c.fail(protocol.ExitFailure, "removing key: %v", err)
250	}
251	return c.emit(map[string]string{"removed": args[0]}, func(w io.Writer) {
252		fmt.Fprintf(w, "removed %s\n", args[0])
253	})
254}