~bigbes/sr-ht-dolt

ref: 0b1e119ae61a069e9844a127236e365e7a79041a sr-ht-dolt/authn/token_test.go -rw-r--r-- 7.3 KiB
0b1e119a — Eugene Blikh chimw: take the chi helpers from ecore 9 days ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
package authn

import (
	"context"
	"crypto/sha512"
	"errors"
	"testing"
	"time"

	"sourcecraft.dev/bigbes/sr-ht-core/auth"

	"sourcecraft.dev/bigbes/sr-ht-dolt/core"
)

func TestResolveBasic_ValidToken(t *testing.T) {
	withStubBackend(t, &stubBackend{users: map[string]auth.AuthContext{
		"bigbes": sampleUser(1, "bigbes", auth.USER_TYPE_USER),
	}})
	pat := forgePAT("bigbes", "", time.Now().Add(time.Hour))

	ac, err := ResolveBasic(testCtx(), "bigbes", pat)
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if ac.Username != "bigbes" || ac.UserID != 1 {
		t.Fatalf("wrong user resolved: %+v", ac)
	}
	if ac.AuthMethod != auth.AUTH_OAUTH2 {
		t.Fatalf("AuthMethod = %q, want %q", ac.AuthMethod, auth.AUTH_OAUTH2)
	}
	if ac.TokenHash != sha512.Sum512([]byte(pat)) {
		t.Fatal("TokenHash must be sha512(password)")
	}
}

func TestResolveBasic_UsernameTildeAndCaseInsensitive(t *testing.T) {
	withStubBackend(t, &stubBackend{users: map[string]auth.AuthContext{
		"bigbes": sampleUser(1, "bigbes", auth.USER_TYPE_USER),
	}})
	pat := forgePAT("bigbes", "", time.Now().Add(time.Hour))

	// Presented username differs by a leading "~" and case; must still match.
	if _, err := ResolveBasic(testCtx(), "~BigBes", pat); err != nil {
		t.Fatalf("expected match for ~BigBes, got %v", err)
	}
}

func TestResolveBasic_UsernameMismatch(t *testing.T) {
	withStubBackend(t, &stubBackend{users: map[string]auth.AuthContext{
		"bigbes": sampleUser(1, "bigbes", auth.USER_TYPE_USER),
		"mallory": sampleUser(2, "mallory", auth.USER_TYPE_USER),
	}})
	pat := forgePAT("bigbes", "", time.Now().Add(time.Hour))

	_, err := ResolveBasic(testCtx(), "mallory", pat)
	if !errors.Is(err, ErrInvalidToken) {
		t.Fatalf("username mismatch must wrap ErrInvalidToken, got %v", err)
	}
}

func TestResolveBasic_ExpiredToken(t *testing.T) {
	withStubBackend(t, &stubBackend{users: map[string]auth.AuthContext{
		"bigbes": sampleUser(1, "bigbes", auth.USER_TYPE_USER),
	}})
	pat := forgePAT("bigbes", "", time.Now().Add(-time.Minute))

	_, err := ResolveBasic(testCtx(), "bigbes", pat)
	if !errors.Is(err, ErrInvalidToken) {
		t.Fatalf("expired token must wrap ErrInvalidToken, got %v", err)
	}
}

func TestResolveBasic_GarbageToken(t *testing.T) {
	withStubBackend(t, &stubBackend{users: map[string]auth.AuthContext{}})
	_, err := ResolveBasic(testCtx(), "bigbes", "this-is-not-a-token")
	if !errors.Is(err, ErrInvalidToken) {
		t.Fatalf("garbage token must wrap ErrInvalidToken, got %v", err)
	}
}

func TestResolveBasic_Revoked(t *testing.T) {
	pat := forgePAT("bigbes", "", time.Now().Add(time.Hour))
	hash := sha512.Sum512([]byte(pat))
	withStubBackend(t, &stubBackend{
		users:   map[string]auth.AuthContext{"bigbes": sampleUser(1, "bigbes", auth.USER_TYPE_USER)},
		revoked: map[[64]byte]bool{hash: true},
	})

	_, err := ResolveBasic(testCtx(), "bigbes", pat)
	if !errors.Is(err, ErrInvalidToken) {
		t.Fatalf("revoked token must wrap ErrInvalidToken, got %v", err)
	}
}

func TestResolveBasic_BackendDownIsTransient(t *testing.T) {
	withStubBackend(t, &stubBackend{lookupErr: errBackendDown})
	pat := forgePAT("bigbes", "", time.Now().Add(time.Hour))

	_, err := ResolveBasic(testCtx(), "bigbes", pat)
	if err == nil {
		t.Fatal("expected an error")
	}
	if errors.Is(err, ErrInvalidToken) {
		t.Fatalf("backend failure must NOT be a permanent rejection, got %v", err)
	}
}

func TestResolveBasic_RevocationBackendDownIsTransient(t *testing.T) {
	withStubBackend(t, &stubBackend{
		users:     map[string]auth.AuthContext{"bigbes": sampleUser(1, "bigbes", auth.USER_TYPE_USER)},
		revokeErr: errBackendDown,
	})
	pat := forgePAT("bigbes", "", time.Now().Add(time.Hour))

	_, err := ResolveBasic(testCtx(), "bigbes", pat)
	if err == nil {
		t.Fatal("expected an error")
	}
	if errors.Is(err, ErrInvalidToken) {
		t.Fatalf("revocation backend failure must be transient, got %v", err)
	}
}

// countingBackend records how many times LookupUser is called, to observe caching.
type countingBackend struct {
	*stubBackend
	lookups int
}

func (c *countingBackend) LookupUser(ctx context.Context, username string, out *auth.AuthContext) error {
	c.lookups++
	return c.stubBackend.LookupUser(ctx, username, out)
}

func TestResolveBasic_PositiveCache(t *testing.T) {
	cb := &countingBackend{stubBackend: &stubBackend{
		users: map[string]auth.AuthContext{"bigbes": sampleUser(1, "bigbes", auth.USER_TYPE_USER)},
	}}
	withStubBackend(t, cb)
	pat := forgePAT("bigbes", "", time.Now().Add(time.Hour))

	for i := 0; i < 3; i++ {
		if _, err := ResolveBasic(testCtx(), "bigbes", pat); err != nil {
			t.Fatalf("call %d: %v", i, err)
		}
	}
	if cb.lookups != 1 {
		t.Fatalf("expected 1 backend lookup (rest cached), got %d", cb.lookups)
	}
}

func TestResolveBasic_CacheExpires(t *testing.T) {
	cb := &countingBackend{stubBackend: &stubBackend{
		users: map[string]auth.AuthContext{"bigbes": sampleUser(1, "bigbes", auth.USER_TYPE_USER)},
	}}
	withStubBackend(t, cb)

	base := time.Now()
	nowFn = func() time.Time { return base }
	pat := forgePAT("bigbes", "", base.Add(time.Hour))

	if _, err := ResolveBasic(testCtx(), "bigbes", pat); err != nil {
		t.Fatal(err)
	}
	// Advance past the TTL; the entry must be re-resolved.
	nowFn = func() time.Time { return base.Add(tokenCacheTTL + time.Second) }
	if _, err := ResolveBasic(testCtx(), "bigbes", pat); err != nil {
		t.Fatal(err)
	}
	if cb.lookups != 2 {
		t.Fatalf("expected 2 lookups across the TTL boundary, got %d", cb.lookups)
	}
}

func TestResolveBasic_NegativeNotCached(t *testing.T) {
	cb := &countingBackend{stubBackend: &stubBackend{
		users: map[string]auth.AuthContext{"bigbes": sampleUser(1, "bigbes", auth.USER_TYPE_USER)},
	}}
	withStubBackend(t, cb)
	// A token for an unknown user: LookupUser errors each time (uncached).
	pat := forgePAT("ghost", "", time.Now().Add(time.Hour))

	for i := 0; i < 2; i++ {
		if _, err := ResolveBasic(testCtx(), "ghost", pat); err == nil {
			t.Fatalf("call %d: expected error for unknown user", i)
		}
	}
	if cb.lookups != 2 {
		t.Fatalf("negative results must not be cached, got %d lookups", cb.lookups)
	}
}

func TestTokenGrantsAllow(t *testing.T) {
	ctx := testCtx()

	mustGrants := func(s string) auth.Grants {
		g, err := auth.DecodeGrants(ctx, s)
		if err != nil {
			t.Fatalf("DecodeGrants(%q): %v", s, err)
		}
		return g
	}

	patAC := func(grants string) *auth.AuthContext {
		return &auth.AuthContext{
			AuthMethod:  auth.AUTH_OAUTH2,
			BearerToken: &auth.BearerToken{},
			Grants:      mustGrants(grants),
		}
	}

	cases := []struct {
		name    string
		ac      *auth.AuthContext
		mode    core.AccessMode
		want    bool
	}{
		{"nil caller passes", nil, core.AccessRW, true},
		{"cookie (no bearer) passes", &auth.AuthContext{AuthMethod: auth.AUTH_COOKIE}, core.AccessRW, true},
		{"empty grants RO", patAC(""), core.AccessRO, true},
		{"empty grants RW", patAC(""), core.AccessRW, true},
		{"repos:RO allows read", patAC("dolt.sr.ht/repos:RO"), core.AccessRO, true},
		{"repos:RO denies write", patAC("dolt.sr.ht/repos:RO"), core.AccessRW, false},
		{"repos:RW allows read", patAC("dolt.sr.ht/repos:RW"), core.AccessRO, true},
		{"repos:RW allows write", patAC("dolt.sr.ht/repos:RW"), core.AccessRW, true},
		{"unrelated scope denies read", patAC("git.sr.ht/repos:RW"), core.AccessRO, false},
	}
	for _, tc := range cases {
		t.Run(tc.name, func(t *testing.T) {
			if got := TokenGrantsAllow(tc.ac, tc.mode); got != tc.want {
				t.Fatalf("TokenGrantsAllow = %v, want %v", got, tc.want)
			}
		})
	}
}