internal/lfs/lfs_test.go

v1.43.1
gitbay/internal/lfs/lfs_test.go history · blame · raw

57 lines · 1940 bytes

 1package lfs
 2
 3import (
 4	"crypto/hmac"
 5	"crypto/sha256"
 6	"encoding/base64"
 7	"fmt"
 8	"testing"
 9	"time"
10)
11
12func TestTokenCarriesTheKey(t *testing.T) {
13	secret := []byte("secret")
14	now := time.Now()
15	tok := Sign(secret, 7, 42, "SHA256:k", "upload", now)
16	g, ok := Verify(secret, tok, now)
17	if !ok || g != (Grant{RepoID: 7, KeyID: 42, KeyPin: KeyPin("SHA256:k"), Op: "upload"}) {
18		t.Fatalf("Verify = %+v, %v", g, ok)
19	}
20	if _, ok := Verify(secret, tok, now.Add(TokenTTL+time.Second)); ok {
21		t.Error("an expired token verified")
22	}
23	if _, ok := Verify([]byte("other"), tok, now); ok {
24		t.Error("a token verified under another secret")
25	}
26	if g, ok := Verify(secret, Sign(secret, 7, 0, "", "download", now), now); !ok || g.KeyID != 0 || g.KeyPin != "" {
27		t.Errorf("anonymous grant = %+v, %v", g, ok)
28	}
29}
30
31// A token minted before tokens named their key has three fields. It is
32// refused, not read as a grant bound to no key (#285).
33func TestUnboundTokenRefused(t *testing.T) {
34	secret := []byte("secret")
35	payload := fmt.Sprintf("%d:%s:%d", 7, "upload", time.Now().Add(TokenTTL).Unix())
36	mac := hmac.New(sha256.New, secret)
37	mac.Write([]byte(payload))
38	tok := base64.RawURLEncoding.EncodeToString([]byte(payload)) + "." +
39		base64.RawURLEncoding.EncodeToString(mac.Sum(nil))
40	if g, ok := Verify(secret, tok, time.Now()); ok {
41		t.Fatalf("a pre-upgrade token verified: %+v", g)
42	}
43}
44
45// A token minted before tokens carried the key's fingerprint has four
46// fields. It is refused (#303).
47func TestUnpinnedTokenRefused(t *testing.T) {
48	secret := []byte("secret")
49	payload := fmt.Sprintf("%d:%d:%s:%d", 7, 42, "upload", time.Now().Add(TokenTTL).Unix())
50	mac := hmac.New(sha256.New, secret)
51	mac.Write([]byte(payload))
52	tok := base64.RawURLEncoding.EncodeToString([]byte(payload)) + "." +
53		base64.RawURLEncoding.EncodeToString(mac.Sum(nil))
54	if g, ok := Verify(secret, tok, time.Now()); ok {
55		t.Fatalf("an unpinned token verified: %+v", g)
56	}
57}