-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathloader_test.go
More file actions
410 lines (353 loc) · 10.3 KB
/
loader_test.go
File metadata and controls
410 lines (353 loc) · 10.3 KB
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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
package httpauth
import (
"os"
"path/filepath"
"strings"
"testing"
)
// writeAuthYAML drops a YAML config in t.TempDir and returns its
// path. Failure here is a test-infra problem, never a Policy
// concern, so we t.Fatalf rather than t.Error.
func writeAuthYAML(t *testing.T, content string) string {
t.Helper()
dir := t.TempDir()
path := filepath.Join(dir, "auth.yaml")
err := os.WriteFile(path, []byte(content), 0o600)
if err != nil {
t.Fatalf("write tempfile: %v", err)
}
return path
}
// TestLoadFromEnv_Legacy pins the backwards-compat shortcut: when
// only HYPERCACHE_AUTH_TOKEN is set, the loader synthesizes a
// single all-scopes TokenIdentity. This is the legacy path every
// pre-v2 deployment relies on; if it ever breaks, every operator
// upgrading hits the wall on day one.
func TestLoadFromEnv_Legacy(t *testing.T) {
// Cannot t.Parallel() — mutates process env. Same constraint
// applies to every test in this file that touches Setenv.
t.Setenv(EnvAuthConfig, "")
t.Setenv(EnvAuthToken, "legacy-token")
p, err := LoadFromEnv()
if err != nil {
t.Fatalf("LoadFromEnv: %v", err)
}
if len(p.Tokens) != 1 {
t.Fatalf("len(Tokens) = %d, want 1", len(p.Tokens))
}
t0 := p.Tokens[0]
if t0.ID != "default" {
t.Errorf("ID = %q, want %q", t0.ID, "default")
}
if t0.Token != "legacy-token" {
t.Errorf("Token = %q, want %q", t0.Token, "legacy-token")
}
want := []Scope{ScopeRead, ScopeWrite, ScopeAdmin}
if len(t0.Scopes) != len(want) {
t.Fatalf("Scopes = %v, want %v", t0.Scopes, want)
}
}
// TestLoadFromEnv_BothCoexist verifies the loader treats
// EnvAuthConfig and EnvAuthToken as orthogonal — config wins for
// the client API, and EnvAuthToken stays available for the dist
// transport's symmetric peer auth. Concretely: when CONFIG points
// at a valid file, the returned Policy mirrors the file (it does
// NOT also include the legacy token), and no error fires.
//
// This is the standard production shape: a multi-tenant client API
// (config-driven) on top of a single-trust-domain cluster (one
// shared peer token).
func TestLoadFromEnv_BothCoexist(t *testing.T) {
yaml := `
tokens:
- id: from-file
token: file-token
scopes: [read]
`
path := writeAuthYAML(t, yaml)
t.Setenv(EnvAuthConfig, path)
t.Setenv(EnvAuthToken, "dist-peer-token")
p, err := LoadFromEnv()
if err != nil {
t.Fatalf("LoadFromEnv: %v", err)
}
if len(p.Tokens) != 1 || p.Tokens[0].ID != "from-file" {
t.Fatalf("policy = %+v, want one token sourced from CONFIG (file wins)", p)
}
for _, tok := range p.Tokens {
if tok.Token == "dist-peer-token" {
t.Fatalf("legacy EnvAuthToken leaked into Policy.Tokens: %+v", tok)
}
}
}
// TestLoadFromEnv_Neither returns the zero Policy with no error
// when neither env is set. The hypercache-server caller is
// responsible for emitting the "running with no auth" warning.
func TestLoadFromEnv_Neither(t *testing.T) {
t.Setenv(EnvAuthConfig, "")
t.Setenv(EnvAuthToken, "")
p, err := LoadFromEnv()
if err != nil {
t.Fatalf("LoadFromEnv: %v", err)
}
if p.IsConfigured() {
t.Errorf("zero policy should not be configured: %+v", p)
}
}
// TestLoadFromFile_Happy parses a complete config with both tokens
// and cert identities and pins each field through to the Policy.
func TestLoadFromFile_Happy(t *testing.T) {
yaml := `
tokens:
- id: app-prod
token: app-prod-secret
scopes: [read, write]
- id: ops
token: ops-secret
scopes: [admin]
cert_identities:
- subject_cn: app.internal
scopes: [read]
allow_anonymous: false
`
path := writeAuthYAML(t, yaml)
t.Setenv(EnvAuthConfig, path)
t.Setenv(EnvAuthToken, "")
p, err := LoadFromEnv()
if err != nil {
t.Fatalf("LoadFromEnv: %v", err)
}
if len(p.Tokens) != 2 {
t.Errorf("len(Tokens) = %d, want 2", len(p.Tokens))
}
if len(p.CertIdentities) != 1 {
t.Errorf("len(CertIdentities) = %d, want 1", len(p.CertIdentities))
}
if p.AllowAnonymous {
t.Errorf("AllowAnonymous = true, want false")
}
}
// loadFailureCase is one row of the loader failure-mode table.
// Hoisted to package scope so the test body stays under the
// function-length lint threshold and adding a new failure case
// is a single literal append.
type loadFailureCase struct {
name string
content string
setup func(t *testing.T) string
}
// loadFailureCases enumerates every input the loader must reject.
// The "secret-leak-canary" token body in every YAML is the
// regression target: each test asserts the resulting error message
// does NOT contain that substring, so a future wrap-error change
// that accidentally chains the file body into the message gets
// caught by the suite (not by the security audit).
//
//nolint:gochecknoglobals // test-only fixture table; sharing across subtests is the point
var loadFailureCases = []loadFailureCase{
{
name: "missing file",
setup: func(_ *testing.T) string {
return "/path/that/does/not/exist/auth.yaml"
},
},
{
name: "malformed YAML",
content: "tokens:\n - id: app\n token: x\n bad-indent",
},
{
name: "unknown field rejected (typo guard)",
content: `
tokens:
- id: x
token: secret-leak-canary
scopes: [read]
unknown_field: typo
`,
},
{
name: "unknown scope name",
content: `
tokens:
- id: x
token: secret-leak-canary
scopes: [readonly]
`,
},
{
name: "empty scopes list",
content: `
tokens:
- id: x
token: secret-leak-canary
scopes: []
`,
},
{
name: "empty token field",
content: `
tokens:
- id: x
token: ""
scopes: [read]
`,
},
{
name: "empty ID field",
content: `
tokens:
- id: ""
token: secret-leak-canary
scopes: [read]
`,
},
{
name: "empty cert subject_cn",
content: `
cert_identities:
- subject_cn: ""
scopes: [read]
`,
},
}
// TestLoadFromFile_FailureModes covers the load-time errors the
// loader is meant to fail-closed on. Each row asserts the error
// is non-nil AND the message does NOT include any token body —
// regression coverage for accidental secret leaks via wrap-error
// chains.
func TestLoadFromFile_FailureModes(t *testing.T) {
for _, tc := range loadFailureCases {
t.Run(tc.name, func(t *testing.T) {
var path string
if tc.setup != nil {
path = tc.setup(t)
} else {
path = writeAuthYAML(t, tc.content)
}
t.Setenv(EnvAuthConfig, path)
t.Setenv(EnvAuthToken, "")
_, err := LoadFromEnv()
if err == nil {
t.Fatalf("expected an error")
}
if strings.Contains(err.Error(), "secret-leak-canary") {
t.Fatalf("error leaks token body: %q", err.Error())
}
})
}
}
// TestLoadFromFile_PrecedenceOverLegacy confirms the file path wins
// when EnvAuthConfig is set — except that "both set" is its own
// failure mode (TestLoadFromEnv_Both), so this only exercises
// "config set, token unset".
func TestLoadFromFile_PrecedenceOverLegacy(t *testing.T) {
yaml := `
tokens:
- id: from-file
token: file-token
scopes: [read]
`
path := writeAuthYAML(t, yaml)
t.Setenv(EnvAuthConfig, path)
t.Setenv(EnvAuthToken, "")
p, err := LoadFromEnv()
if err != nil {
t.Fatalf("LoadFromEnv: %v", err)
}
if len(p.Tokens) != 1 || p.Tokens[0].ID != "from-file" {
t.Fatalf("policy = %+v, want one token from file", p)
}
}
// TestLoadFromEnv_UsersBlock verifies the new users: YAML block is
// parsed into Policy.BasicIdentities with the bcrypt hash carried
// through verbatim. The fixture uses a pre-generated bcrypt hash for
// `pw-alice` at cost 4 so the test runtime stays sub-second; the
// actual bcrypt verification path is exercised in policy_test.go.
func TestLoadFromEnv_UsersBlock(t *testing.T) {
// Pre-computed bcrypt hash of "pw-alice" at cost 4. Stable enough
// to bake into the test fixture since bcrypt's $2a$ format is
// part of the on-disk contract we're pinning.
hash := "$2a$04$sc9cmgQ9AkudxNVW.B.jYOLEALRQdSuwTj94lblllSFCKGPQ4oG9y"
yaml := `
users:
- id: svc-alice
username: alice
password_bcrypt: "` + hash + `"
scopes: [read, write]
allow_basic_without_tls: true
`
path := writeAuthYAML(t, yaml)
t.Setenv(EnvAuthConfig, path)
t.Setenv(EnvAuthToken, "")
p, err := LoadFromEnv()
if err != nil {
t.Fatalf("LoadFromEnv: %v", err)
}
if len(p.BasicIdentities) != 1 {
t.Fatalf("len(BasicIdentities) = %d, want 1", len(p.BasicIdentities))
}
b := p.BasicIdentities[0]
if b.Username != userAlice {
t.Errorf("Username = %q, want %s", b.Username, userAlice)
}
if b.ID != "svc-alice" {
t.Errorf("ID = %q, want svc-alice", b.ID)
}
if string(b.PasswordBcrypt) != hash {
t.Errorf("PasswordBcrypt: got %q, want %q", b.PasswordBcrypt, hash)
}
wantScopes := []Scope{ScopeRead, ScopeWrite}
if len(b.Scopes) != len(wantScopes) {
t.Fatalf("Scopes = %v, want %v", b.Scopes, wantScopes)
}
if !p.AllowBasicWithoutTLS {
t.Errorf("AllowBasicWithoutTLS = false, want true")
}
}
// TestLoadFromEnv_UsersBlockRejectsBadBcrypt pins the loader's
// fail-loud-at-boot contract: a structurally invalid bcrypt hash
// must fail Validate() and bubble up as an error from LoadFromEnv,
// rather than silently rejecting every Basic auth attempt at
// runtime.
func TestLoadFromEnv_UsersBlockRejectsBadBcrypt(t *testing.T) {
yaml := `
users:
- id: svc-alice
username: alice
password_bcrypt: "this-is-not-a-bcrypt-hash"
scopes: [read]
`
path := writeAuthYAML(t, yaml)
t.Setenv(EnvAuthConfig, path)
t.Setenv(EnvAuthToken, "")
_, err := LoadFromEnv()
if err == nil {
t.Fatalf("LoadFromEnv must reject malformed bcrypt hash; got no error")
}
if !strings.Contains(err.Error(), "password_bcrypt") {
t.Errorf("error message should reference password_bcrypt; got %q", err.Error())
}
}
// TestLoadFromEnv_UsersBlockRejectsEmptyUsername pins another
// Validate rule: even a valid bcrypt hash must be paired with a
// non-empty username, since username is the wire selector that
// keys into the BasicIdentities slice at resolve time.
func TestLoadFromEnv_UsersBlockRejectsEmptyUsername(t *testing.T) {
yaml := `
users:
- id: svc-alice
username: ""
password_bcrypt: "$2a$04$sc9cmgQ9AkudxNVW.B.jYOLEALRQdSuwTj94lblllSFCKGPQ4oG9y"
scopes: [read]
`
path := writeAuthYAML(t, yaml)
t.Setenv(EnvAuthConfig, path)
t.Setenv(EnvAuthToken, "")
_, err := LoadFromEnv()
if err == nil {
t.Fatalf("LoadFromEnv must reject empty username; got no error")
}
if !strings.Contains(err.Error(), "username") {
t.Errorf("error message should reference username; got %q", err.Error())
}
}