~bigbes/sr-ht-spec

ref: 8374a1ef0826d0422d3db4685cfea15842c2096d sr-ht-spec/authn/resolver_test.go -rw-r--r-- 10.2 KiB
8374a1ef — Eugene Blikh feat(graph): GraphQL-native webhook surface (Phase 5a) 25 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
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
package authn

import (
	"context"
	"errors"
	"net/http"
	"net/http/httptest"
	"testing"
)

func newTestResolver(t *testing.T, store TokenStore) *Resolver {
	t.Helper()
	rs, err := NewResolver("bigbes", store)
	if err != nil {
		t.Fatalf("NewResolver: %v", err)
	}
	return rs
}

func TestNewResolver_RejectsBadWiring(t *testing.T) {
	if _, err := NewResolver("bigbes", nil); err == nil {
		t.Fatal("nil store must be rejected")
	}
	if _, err := NewResolver("", newStubStore()); err == nil {
		t.Fatal("empty owner must be rejected")
	}
	if _, err := NewResolver("Not A Name", newStubStore()); err == nil {
		t.Fatal("unusable owner must be rejected")
	}
	// The canonical "~user" spelling is accepted and normalised.
	rs, err := NewResolver("~bigbes", newStubStore())
	if err != nil {
		t.Fatalf("NewResolver(~bigbes): %v", err)
	}
	if rs.Owner() != "bigbes" {
		t.Fatalf("Owner() = %q, want %q", rs.Owner(), "bigbes")
	}
}

func TestResolve_OwnerCookie(t *testing.T) {
	store := newStubStore()
	rs := newTestResolver(t, store)

	p, err := rs.Resolve(context.Background(), request(sealCookie(t, "bigbes"), nil))
	if err != nil {
		t.Fatalf("Resolve: %v", err)
	}
	if !p.IsOwner() {
		t.Fatalf("principal = %+v, want the owner", p)
	}
	if p.IsAnonymous() || p.IsAgent() {
		t.Fatalf("owner classified as anonymous/agent: %+v", p)
	}
	if p.Owner != "bigbes" {
		t.Fatalf("Owner = %q, want %q", p.Owner, "bigbes")
	}
	if store.calls != 0 {
		t.Fatalf("cookie path consulted the token store %d times, want 0", store.calls)
	}
}

func TestResolve_AbsentCookieIsAnonymousNotAnError(t *testing.T) {
	rs := newTestResolver(t, newStubStore())
	p, err := rs.Resolve(context.Background(), request("", nil))
	if err != nil {
		t.Fatalf("an anonymous request must never error: %v", err)
	}
	if !p.IsAnonymous() {
		t.Fatalf("principal = %+v, want anonymous", p)
	}
}

func TestResolve_BrokenCookiesAreAnonymousNotErrors(t *testing.T) {
	rs := newTestResolver(t, newStubStore())
	for name, value := range map[string]string{
		"tampered":    tamper(t, sealCookie(t, "bigbes")),
		"garbage":     "not-a-valid-fernet-token",
		"foreign key": sealCookieWithKey(t, &rotatedKey, "bigbes"),
	} {
		t.Run(name, func(t *testing.T) {
			p, err := rs.Resolve(context.Background(), request(value, nil))
			if err != nil {
				t.Fatalf("a broken cookie must never error: %v", err)
			}
			if !p.IsAnonymous() {
				t.Fatalf("principal = %+v, want anonymous", p)
			}
		})
	}
}

// Single-user: a real user who is not bigbes has nothing granted to them, so
// they read exactly as an anonymous viewer does. The name survives for logs
// only, and must not be mistaken for authority.
func TestResolve_NonOwnerCookieIsAnonymous(t *testing.T) {
	rs := newTestResolver(t, newStubStore())
	p, err := rs.Resolve(context.Background(), request(sealCookie(t, "someone"), nil))
	if err != nil {
		t.Fatalf("Resolve: %v", err)
	}
	if !p.IsAnonymous() {
		t.Fatalf("principal = %+v, want anonymous", p)
	}
	if p.IsOwner() {
		t.Fatal("a non-owner cookie must not yield the owner")
	}
	if p.Owner != "" {
		t.Fatalf("Owner = %q, want empty for a non-owner", p.Owner)
	}
	if p.CookieUser != "someone" {
		t.Fatalf("CookieUser = %q, want %q", p.CookieUser, "someone")
	}
}

func TestResolve_AgentTokenAccepted(t *testing.T) {
	store := newStubStore()
	store.add("live-token", "laptop")
	rs := newTestResolver(t, store)

	p, err := rs.Resolve(context.Background(), request("", map[string]string{
		"Authorization":    "Bearer live-token",
		HeaderAgent:        "claude-code/spec-writer",
		HeaderAgentSession: "8fb9c9a4-b078-4af1-89eb-d97c522f9921",
	}))
	if err != nil {
		t.Fatalf("Resolve: %v", err)
	}
	if !p.IsAgent() {
		t.Fatalf("principal = %+v, want an agent", p)
	}
	if p.IsOwner() || p.IsAnonymous() {
		t.Fatalf("agent classified as owner/anonymous: %+v", p)
	}
	if p.Agent != "claude-code/spec-writer" || p.Session != "8fb9c9a4-b078-4af1-89eb-d97c522f9921" {
		t.Fatalf("provenance not carried onto the principal: %+v", p)
	}
	if p.Owner != "bigbes" {
		t.Fatalf("agent acts for %q, want %q", p.Owner, "bigbes")
	}
	if p.TokenName != "laptop" {
		t.Fatalf("TokenName = %q, want %q", p.TokenName, "laptop")
	}
}

func TestResolve_AgentTokenRevokedAndUnknown(t *testing.T) {
	store := newStubStore()
	store.add("live-token", "laptop")
	store.revoke("dead-token", "cron")
	rs := newTestResolver(t, store)

	cases := map[string]struct {
		token string
		want  error
	}{
		"revoked": {"dead-token", ErrRevokedToken},
		"unknown": {"never-issued", ErrUnknownToken},
	}
	for name, c := range cases {
		t.Run(name, func(t *testing.T) {
			p, err := rs.Resolve(context.Background(), request("",
				map[string]string{"Authorization": "Bearer " + c.token}))
			if !errors.Is(err, c.want) {
				t.Fatalf("error = %v, want %v", err, c.want)
			}
			if !p.IsAnonymous() {
				t.Fatalf("a refused token must yield no authority: %+v", p)
			}
		})
	}
}

// A bearer token wins over a cookie. Letting a stale browser cookie promote a
// token-bearing request to the owner would hand an agent the approved branch.
func TestResolve_BearerBeatsCookie(t *testing.T) {
	store := newStubStore()
	store.add("live-token", "laptop")
	rs := newTestResolver(t, store)

	p, err := rs.Resolve(context.Background(), request(sealCookie(t, "bigbes"),
		map[string]string{"Authorization": "Bearer live-token"}))
	if err != nil {
		t.Fatalf("Resolve: %v", err)
	}
	if !p.IsAgent() {
		t.Fatalf("principal = %+v, want an agent", p)
	}
	if p.IsOwner() {
		t.Fatal("an owner cookie must not promote a token-bearing request")
	}
}

// A bad token is a hard failure even when a valid owner cookie is present: an
// agent silently downgraded to a reader fails confusingly at its first write
// instead of clearly at the door.
func TestResolve_BadTokenFailsEvenWithOwnerCookie(t *testing.T) {
	store := newStubStore()
	rs := newTestResolver(t, store)

	_, err := rs.Resolve(context.Background(), request(sealCookie(t, "bigbes"),
		map[string]string{"Authorization": "Bearer never-issued"}))
	if !errors.Is(err, ErrUnknownToken) {
		t.Fatalf("error = %v, want ErrUnknownToken", err)
	}
}

func runMiddleware(t *testing.T, rs *Resolver, r *http.Request) (Principal, int, bool) {
	t.Helper()
	var got Principal
	var reached bool
	h := rs.Middleware()(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		reached = true
		got = PrincipalFromContext(r.Context())
	}))
	rec := httptest.NewRecorder()
	h.ServeHTTP(rec, r)
	return got, rec.Code, reached
}

func TestMiddleware_AttachesPrincipal(t *testing.T) {
	store := newStubStore()
	store.add("live-token", "laptop")
	rs := newTestResolver(t, store)

	t.Run("owner", func(t *testing.T) {
		p, code, reached := runMiddleware(t, rs, request(sealCookie(t, "bigbes"), nil))
		if !reached || code != http.StatusOK {
			t.Fatalf("reached=%v code=%d, want true/200", reached, code)
		}
		if !p.IsOwner() {
			t.Fatalf("principal = %+v, want the owner", p)
		}
	})

	t.Run("anonymous", func(t *testing.T) {
		p, code, reached := runMiddleware(t, rs, request("", nil))
		if !reached || code != http.StatusOK {
			t.Fatalf("reached=%v code=%d, want true/200", reached, code)
		}
		if !p.IsAnonymous() {
			t.Fatalf("principal = %+v, want anonymous", p)
		}
	})

	t.Run("agent", func(t *testing.T) {
		p, code, reached := runMiddleware(t, rs, request("", map[string]string{
			"Authorization":    "Bearer live-token",
			HeaderAgent:        "claude-code/spec-writer",
			HeaderAgentSession: "sess-1",
		}))
		if !reached || code != http.StatusOK {
			t.Fatalf("reached=%v code=%d, want true/200", reached, code)
		}
		if !p.IsAgent() || p.Agent != "claude-code/spec-writer" {
			t.Fatalf("principal = %+v, want the agent", p)
		}
	})
}

func TestMiddleware_RejectsBadToken(t *testing.T) {
	rs := newTestResolver(t, newStubStore())
	_, code, reached := runMiddleware(t, rs, request("",
		map[string]string{"Authorization": "Bearer never-issued"}))
	if reached {
		t.Fatal("a refused token must not reach the handler")
	}
	if code != http.StatusUnauthorized {
		t.Fatalf("code = %d, want 401", code)
	}
}

func TestMiddleware_StoreOutageIs503(t *testing.T) {
	store := newStubStore()
	store.err = errors.New("connection refused")
	rs := newTestResolver(t, store)

	_, code, reached := runMiddleware(t, rs, request("",
		map[string]string{"Authorization": "Bearer live-token"}))
	if reached {
		t.Fatal("a store outage must fail closed, not reach the handler")
	}
	if code != http.StatusServiceUnavailable {
		t.Fatalf("code = %d, want 503", code)
	}
}

// A handler reached without the middleware must degrade to less authority, not
// more.
func TestPrincipalFromContext_BareContextIsAnonymous(t *testing.T) {
	p := PrincipalFromContext(context.Background())
	if !p.IsAnonymous() || p.IsOwner() || p.IsAgent() {
		t.Fatalf("bare context yielded %+v, want anonymous", p)
	}
	if p.Kind != KindAnonymous {
		t.Fatalf("Kind = %q, want %q", p.Kind, KindAnonymous)
	}
}

func TestPrincipalFromContext_RoundTrip(t *testing.T) {
	want := Principal{Kind: KindAgent, Owner: "bigbes", Agent: "a", Session: "s"}
	if got := PrincipalFromContext(WithPrincipal(context.Background(), want)); got != want {
		t.Fatalf("round trip = %+v, want %+v", got, want)
	}
}

// The zero Principal must be the anonymous one — an unrecognised Kind is denied
// rather than accidentally admitted.
func TestPrincipal_ZeroValueIsAnonymous(t *testing.T) {
	var p Principal
	if !p.IsAnonymous() || p.IsOwner() || p.IsAgent() {
		t.Fatalf("zero Principal = %+v, want anonymous", p)
	}
	if p2 := (Principal{Kind: Kind("nonsense")}); !p2.IsAnonymous() {
		t.Fatal("an unrecognised Kind must be anonymous")
	}
}

func TestPrincipal_String(t *testing.T) {
	cases := map[Principal]string{
		Anonymous(): "anonymous",
		{Kind: KindAnonymous, CookieUser: "someone"}:                                         "anonymous (cookie user ~someone)",
		{Kind: KindOwner, Owner: "bigbes"}:                                                   "owner ~bigbes",
		{Kind: KindAgent, Owner: "bigbes", Agent: "claude-code/spec-writer", Session: "s-1"}: "agent claude-code/spec-writer session s-1 for ~bigbes",
		{Kind: KindAgent, Owner: "bigbes"}:                                                   "agent (unnamed) session (no session) for ~bigbes",
	}
	for p, want := range cases {
		if got := p.String(); got != want {
			t.Fatalf("String() = %q, want %q", got, want)
		}
	}
}