internal/control/keyexpiry_test.go
68 lines · 2110 bytes
1package control
2
3import (
4 "bytes"
5 "crypto/ed25519"
6 "crypto/rand"
7 "strings"
8 "testing"
9 "time"
10
11 "golang.org/x/crypto/ssh"
12
13 "gitbay.org/gitbay/internal/protocol"
14 "gitbay.org/gitbay/internal/store"
15)
16
17// authorizedKey is a fresh public key as an authorized_keys line.
18func authorizedKey(t *testing.T, comment string) string {
19 t.Helper()
20 pub, _, err := ed25519.GenerateKey(rand.Reader)
21 if err != nil {
22 t.Fatal(err)
23 }
24 sp, err := ssh.NewPublicKey(pub)
25 if err != nil {
26 t.Fatal(err)
27 }
28 return strings.TrimSpace(string(ssh.MarshalAuthorizedKey(sp))) + " " + comment + "\n"
29}
30
31func TestKeysAddTTLAndList(t *testing.T) {
32 st, repo, uid := newQueueTestRepo(t)
33 user := store.User{ID: uid, Username: "alice"}
34 run := func(stdin string, argv ...string) (string, string, int) {
35 c, errOut := pruneCtx(st, t.TempDir(), user)
36 c.Cfg.Limits.WriteRate = -1
37 c.Stdin = strings.NewReader(stdin)
38 code := Dispatch(c, argv)
39 return c.Stdout.(*bytes.Buffer).String(), errOut.String(), code
40 }
41 if _, errOut, code := run(authorizedKey(t, "laptop"), "keys", "add", "--ttl", "1h"); code != protocol.ExitOK {
42 t.Fatalf("keys add --ttl: %d %s", code, errOut)
43 }
44 if _, errOut, code := run(authorizedKey(t, "ci"), "repo", "deploy-key", "add", repo.Path(), "--ttl", "2d"); code != protocol.ExitOK {
45 t.Fatalf("deploy-key add --ttl: %d %s", code, errOut)
46 }
47 if _, _, code := run(authorizedKey(t, "x"), "keys", "add", "--ttl", "soon"); code != protocol.ExitUsage {
48 t.Fatalf("bad ttl: exit %d", code)
49 }
50
51 keys, err := st.ListSSHKeys(uid)
52 if err != nil || len(keys) != 2 {
53 t.Fatalf("keys: %+v %v", keys, err)
54 }
55 for _, k := range keys {
56 if k.ExpiresAt == nil || k.ExpiresAt.Before(time.Now()) || k.ExpiresAt.After(time.Now().Add(49*time.Hour)) {
57 t.Errorf("%s expires %v", k.Label, k.ExpiresAt)
58 }
59 }
60 out, _, _ := run("", "keys", "list")
61 if !strings.Contains(out, "\tlaptop\tnever used\texpires ") {
62 t.Fatalf("keys list:\n%s", out)
63 }
64 out, _, _ = run("", "repo", "deploy-key", "list", repo.Path())
65 if !strings.Contains(out, "\tci\tnever used\texpires ") {
66 t.Fatalf("deploy-key list:\n%s", out)
67 }
68}