internal/control/keyexpiry_test.go
78 lines · 2518 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 if _, _, code := run(authorizedKey(t, "x"), "keys", "add", "--ttl", "0h"); code != protocol.ExitUsage {
51 t.Fatalf("zero ttl: exit %d", code)
52 }
53 if _, _, code := run(authorizedKey(t, "x"), "keys", "add", "--ttl", "-1h"); code != protocol.ExitUsage {
54 t.Fatalf("negative ttl: exit %d", code)
55 }
56
57 keys, err := st.ListSSHKeys(uid)
58 if err != nil || len(keys) != 2 {
59 t.Fatalf("keys: %+v %v", keys, err)
60 }
61 for _, k := range keys {
62 if k.ExpiresAt == nil || k.ExpiresAt.Before(time.Now()) || k.ExpiresAt.After(time.Now().Add(49*time.Hour)) {
63 t.Errorf("%s expires %v", k.Label, k.ExpiresAt)
64 }
65 }
66 exp := map[string]string{}
67 for _, k := range keys {
68 exp[k.Label] = k.ExpiresAt.UTC().Format("2006-01-02")
69 }
70 out, _, _ := run("", "keys", "list")
71 if !strings.Contains(out, "\tlaptop\tnever\t"+exp["laptop"]) {
72 t.Fatalf("keys list:\n%s", out)
73 }
74 out, _, _ = run("", "repo", "deploy-key", "list", repo.Path())
75 if !strings.Contains(out, "\tci\tnever\t"+exp["ci"]) {
76 t.Fatalf("deploy-key list:\n%s", out)
77 }
78}