internal/control/identity.go
284 lines · 8263 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, NeedsRecentSignIn: 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 if c.Term.Cols == 0 {
76 fmt.Fprintln(w, d.Username)
77 return
78 }
79 // At a terminal: where, and with what.
80 role := ""
81 if d.Admin {
82 role = "admin"
83 }
84 // The key's label, or the start of its fingerprint: keys list
85 // has the whole of it.
86 via := c.Source
87 if k, err := c.Store.SSHKeyByFingerprint(c.Source); err == nil && k.Label != "" {
88 via = k.Label
89 } else if len(via) > 20 {
90 via = via[:19] + "…"
91 }
92 v := c.view(w)
93 v.title(d.Username, "", role)
94 v.fields(
95 "instance", c.Cfg.Server.SiteURL,
96 "key", via,
97 "scope", d.KeyScope,
98 )
99 })
100}
101
102func runKeysList(c *Ctx, args []string) int {
103 if len(args) != 0 {
104 return c.usage()
105 }
106 keys, err := c.Store.ListSSHKeys(c.User.ID)
107 if err != nil {
108 return c.fail(protocol.ExitFailure, "listing keys: %v", err)
109 }
110 type out struct {
111 Fingerprint string `json:"fingerprint"`
112 Algo string `json:"algo"`
113 Scope string `json:"scope"`
114 Label string `json:"label"`
115 CreatedBy string `json:"created_by,omitempty"`
116 LastUsedAt string `json:"last_used_at,omitempty"`
117 ExpiresAt *time.Time `json:"expires_at,omitempty"`
118 }
119 var ds []out
120 for _, k := range keys {
121 ds = append(ds, out{k.Fingerprint, k.Algo, k.Scope, k.Label, k.CreatedBy, k.LastUsedAt, k.ExpiresAt})
122 }
123 now := time.Now()
124 return c.emit(ds, func(w io.Writer) {
125 tb := c.table(w, "FINGERPRINT", "ALGO", "SCOPE", "LABEL", "USED", "EXPIRES")
126 for _, d := range ds {
127 used := cText(c.usedText(d.LastUsedAt))
128 if c.Term.Cols > 0 && d.Fingerprint == c.Source {
129 used = cMark("this session", sgrGreen)
130 }
131 tb.row(cFlex(d.Fingerprint), cText(d.Algo), cState(d.Scope), cText(d.Label),
132 used, cText(c.expiresText(d.ExpiresAt, now)))
133 }
134 tb.flush()
135 })
136}
137
138// maxKeyLabel bounds a key's name. Labels are display text, one line.
139const maxKeyLabel = 64
140
141// keyLabel normalises a label: surrounding space trimmed, control
142// characters refused, length capped. An empty result is a valid "no
143// label".
144func keyLabel(s string) (string, error) {
145 s = strings.TrimSpace(s)
146 if len(s) > maxKeyLabel {
147 return "", fmt.Errorf("label is longer than %d bytes", maxKeyLabel)
148 }
149 for _, r := range s {
150 if unicode.IsControl(r) {
151 return "", errors.New("label must be a single line of printable text")
152 }
153 }
154 return s, nil
155}
156
157// usedText is a key's last use as a USED cell shows it.
158func (c *Ctx) usedText(ts string) string {
159 switch {
160 case ts == "":
161 return "never"
162 case c.Term.Cols == 0:
163 return stamp(ts)
164 }
165 return relAge(ts, termNow())
166}
167
168// expiresText is a credential's expiry as an EXPIRES cell shows it:
169// RFC3339 in plain output, relative at a terminal.
170func (c *Ctx) expiresText(t *time.Time, now time.Time) string {
171 if t == nil {
172 return "never"
173 }
174 s := stamp(t.UTC().Format(time.RFC3339Nano))
175 if c.Term.Cols > 0 {
176 s = relAge(s, now)
177 }
178 if !t.After(now) {
179 return "expired " + s
180 }
181 return s
182}
183
184func runKeysAdd(c *Ctx, args []string) int {
185 f, err := c.parseArgs(args, flagSpec{Values: []string{"--scope", "--label", "--ttl"}, MaxPos: 0, Usage: c.Cmd.Usage})
186 if err != nil {
187 return c.fail(protocol.ExitUsage, "%v", err)
188 }
189 scope := "full"
190 if f.Has("--scope") {
191 scope = f.Value("--scope")
192 }
193 if scope != "full" && scope != "git" && scope != "runner" {
194 // deploy:* scopes are granted via repo settings, not self-service.
195 return c.fail(protocol.ExitUsage, "scope must be full, git or runner")
196 }
197 expires, code := c.ttlFlag(f)
198 if code >= 0 {
199 return code
200 }
201 raw, err := io.ReadAll(io.LimitReader(c.Stdin, 64<<10))
202 if err != nil {
203 return c.fail(protocol.ExitFailure, "reading key: %v", err)
204 }
205 pub, comment, _, _, err := ssh.ParseAuthorizedKey(raw)
206 if err != nil {
207 return c.fail(protocol.ExitUsage, "not a valid public key in authorized_keys format: %v", err)
208 }
209 // The key's own comment is the label unless --label says otherwise.
210 label := comment
211 if f.Has("--label") {
212 label = f.Value("--label")
213 }
214 if label, err = keyLabel(label); err != nil {
215 return c.fail(protocol.ExitUsage, "%v", err)
216 }
217 fp := ssh.FingerprintSHA256(pub)
218 if err := c.Store.AddSSHKeyFrom(c.User.ID, fp, pub.Type(), pub.Marshal(), scope, label, store.KeyOrigin{CreatedByToken: c.TokenID, ExpiresAt: expires}); err != nil {
219 if errors.Is(err, store.ErrDuplicateKey) {
220 return c.failErr(err)
221 }
222 return c.fail(protocol.ExitFailure, "adding key: %v", err)
223 }
224 type out struct {
225 Fingerprint string `json:"fingerprint"`
226 Scope string `json:"scope"`
227 Label string `json:"label"`
228 ExpiresAt *time.Time `json:"expires_at,omitempty"`
229 }
230 d := out{fp, scope, label, expires}
231 return c.emit(d, func(w io.Writer) {
232 line := fmt.Sprintf("added %s (%s)", d.Fingerprint, d.Scope)
233 if d.Label != "" {
234 line += " " + d.Label
235 }
236 if d.ExpiresAt != nil {
237 line += ", expires " + c.expiresText(d.ExpiresAt, time.Now())
238 }
239 fmt.Fprintln(w, line)
240 })
241}
242
243func runKeysLabel(c *Ctx, args []string) int {
244 if len(args) < 1 || len(args) > 2 {
245 return c.usage()
246 }
247 label := ""
248 if len(args) == 2 {
249 label = args[1]
250 }
251 label, err := keyLabel(label)
252 if err != nil {
253 return c.fail(protocol.ExitUsage, "%v", err)
254 }
255 if err := c.Store.SetSSHKeyLabel(c.User.ID, args[0], label); err != nil {
256 if errors.Is(err, store.ErrNotFound) {
257 return c.fail(protocol.ExitNotFound, "no key with fingerprint %s on your account", args[0])
258 }
259 return c.fail(protocol.ExitFailure, "labelling key: %v", err)
260 }
261 d := map[string]string{"fingerprint": args[0], "label": label}
262 return c.emit(d, func(w io.Writer) {
263 if label == "" {
264 fmt.Fprintf(w, "cleared label on %s\n", args[0])
265 return
266 }
267 fmt.Fprintf(w, "%s is now %q\n", args[0], label)
268 })
269}
270
271func runKeysRemove(c *Ctx, args []string) int {
272 if len(args) != 1 {
273 return c.usage()
274 }
275 if err := c.Store.RemoveSSHKey(c.User.ID, args[0]); err != nil {
276 if errors.Is(err, store.ErrNotFound) {
277 return c.fail(protocol.ExitNotFound, "no key with fingerprint %s on your account", args[0])
278 }
279 return c.fail(protocol.ExitFailure, "removing key: %v", err)
280 }
281 return c.emit(map[string]string{"removed": args[0]}, func(w io.Writer) {
282 fmt.Fprintf(w, "removed %s\n", args[0])
283 })
284}