~bigbes/sr-ht-spec

ref: 6d7dbdb5560f52652c1ce20f153a964b5d6fc88d sr-ht-spec/authn/resolver_test.go -rw-r--r-- 12.7 KiB
6d7dbdb5 — Eugene Blikh ci: publish this build's own coverage and benchmarks 2 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
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
package authn

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

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"sourcecraft.dev/bigbes/sr-ht-ecore/bearer"
)

// newTestResolver builds a resolver whose agent plane is wired to a daemon that
// answers "live" — the production shape. The cookie tests present no bearer
// credential and so never reach it.
func newTestResolver(t *testing.T) *Resolver {
	t.Helper()
	return newPlaneFixture(t, http.StatusNoContent).rs
}

func TestNewResolver_RejectsBadWiring(t *testing.T) {
	if _, err := NewResolver(""); err == nil {
		t.Fatal("empty owner must be rejected")
	}
	if _, err := NewResolver("Not A Name"); err == nil {
		t.Fatal("unusable owner must be rejected")
	}
	// The canonical "~user" spelling is accepted and normalised.
	rs, err := NewResolver("~bigbes")
	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) {
	f := newPlaneFixture(t, http.StatusNoContent)

	p, err := f.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 f.users.calls != 0 || f.daemon.hits != 0 {
		t.Fatal("the cookie path must not touch the agent credential plane")
	}
}

func TestResolve_AbsentCookieIsAnonymousNotAnError(t *testing.T) {
	rs := newTestResolver(t)
	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)
	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)
	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")
	}
}

// The validator seam. login decodes the cookie, and what this service supplies
// is core.ValidateOwner as the rule for what may count as a name — the same rule
// every repository path under [spec.sr.ht] repos is built against. Each of these
// is a well-sealed cookie carrying a name meta.sr.ht could not have issued, and
// each must read as anonymous rather than reach filepath.Join.
//
// login ships a conservative default of its own, so this is not the difference
// between validating and not validating; it pins that the rule in force is ours,
// which is what stops the two grammars from drifting apart on the day one of
// them is widened.
func TestResolve_CookieNameIsHeldToValidateOwner(t *testing.T) {
	rs := newTestResolver(t)
	for _, name := range []string{
		"",
		"..",
		"../../etc/passwd",
		"has space",
		"Uppercase",
		"-leading-dash",
	} {
		t.Run(name, func(t *testing.T) {
			p, err := rs.Resolve(context.Background(), request(sealCookie(t, name), nil))
			require.NoError(t, err, "an unusable cookie name must never error")
			assert.True(t, p.IsAnonymous(), "principal = %+v, want anonymous", p)
			assert.Empty(t, p.CookieUser, "an unusable name must not survive as a viewer name either")
		})
	}
}

func TestResolve_AgentTokenAccepted(t *testing.T) {
	f := newPlaneFixture(t, http.StatusNoContent)

	p, err := f.rs.Resolve(context.Background(), request("", map[string]string{
		"Authorization":    "Bearer " + instanceToken("spec:propose spec:read"),
		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 != "tokens.sr.ht (stateless)" {
		t.Fatalf("TokenName = %q, want the tokens.sr.ht label", p.TokenName)
	}
}

// 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) {
	f := newPlaneFixture(t, http.StatusNoContent)

	p, err := f.rs.Resolve(context.Background(), request(sealCookie(t, "bigbes"),
		map[string]string{"Authorization": "Bearer " + instanceToken("spec:propose")}))
	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) {
	f := newPlaneFixture(t, http.StatusNoContent)

	_, err := f.rs.Resolve(context.Background(), request(sealCookie(t, "bigbes"),
		map[string]string{"Authorization": "Bearer never-issued"}))
	if !errors.Is(err, bearer.ErrInvalid) {
		t.Fatalf("error = %v, want bearer.ErrInvalid", 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) {
	rs := newTestResolver(t)

	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 " + instanceToken("spec:propose spec:read"),
			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)
	_, 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)
	}
}

// A 401 out of this middleware names the scheme and the realm, which is what an
// agent library reads to know which credential was refused — and what a 503 must
// not carry, since nothing about the credential was decided.
func TestMiddleware_RefusalCarriesTheChallenge(t *testing.T) {
	rs := newTestResolver(t)

	h := rs.Middleware()(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))
	rec := httptest.NewRecorder()
	h.ServeHTTP(rec, request("", map[string]string{"Authorization": "Bearer never-issued"}))
	require.Equal(t, http.StatusUnauthorized, rec.Code)
	assert.Equal(t, Challenge(), rec.Header().Get("WWW-Authenticate"))

	f := newPlaneFixture(t, http.StatusNoContent)
	f.users.err = errors.New("connection refused")
	h = f.rs.Middleware()(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))
	rec = httptest.NewRecorder()
	h.ServeHTTP(rec, request("", map[string]string{
		"Authorization": "Bearer " + instanceToken("spec:read"),
	}))
	require.Equal(t, http.StatusServiceUnavailable, rec.Code)
	assert.Empty(t, rec.Header().Get("WWW-Authenticate"),
		"a backend outage says nothing about the credential")
}

// A user lookup that cannot answer is a backend outage, not a bad credential:
// fail closed with a 503 rather than telling a live agent its token is bad.
func TestMiddleware_BackendOutageIs503(t *testing.T) {
	f := newPlaneFixture(t, http.StatusNoContent)
	f.users.err = errors.New("connection refused")

	_, code, reached := runMiddleware(t, f.rs, request("",
		map[string]string{"Authorization": "Bearer " + instanceToken("spec:read")}))
	if reached {
		t.Fatal("a backend 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)
	}
}

// Principal is not comparable with == — it carries a grant set — so the round
// trip is asserted with reflect.DeepEqual, which also covers the grants.
func TestPrincipalFromContext_RoundTrip(t *testing.T) {
	want := Principal{
		Kind: KindAgent, Owner: "bigbes", Agent: "a", Session: "s",
		Plane: PlaneInstance, Grants: mustGrants(t, "spec:read spec:propose"), UserID: 3,
	}
	got := PrincipalFromContext(WithPrincipal(context.Background(), want))
	if !reflect.DeepEqual(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) {
	// A slice and not a map keyed by Principal: it carries a grant set and is
	// therefore not comparable.
	cases := []struct {
		p    Principal
		want string
	}{
		{Anonymous(), "anonymous"},
		{Principal{Kind: KindAnonymous, CookieUser: "someone"}, "anonymous (cookie user ~someone)"},
		{Principal{Kind: KindOwner, Owner: "bigbes"}, "owner ~bigbes"},
		{
			Principal{Kind: KindAgent, Owner: "bigbes", Agent: "claude-code/spec-writer", Session: "s-1"},
			"agent claude-code/spec-writer session s-1 for ~bigbes",
		},
		{Principal{Kind: KindAgent, Owner: "bigbes"}, "agent (unnamed) session (no session) for ~bigbes"},
		// An agent a local process asserted (the CLI) carries no credential and
		// so no grant set: the annotation appears only where there is something
		// to say.
		{
			Principal{Kind: KindAgent, Owner: "bigbes", Agent: "a", Session: "s-1"},
			"agent a session s-1 for ~bigbes",
		},
		{
			Principal{
				Kind: KindAgent, Owner: "bigbes", Agent: "a", Session: "s-1",
				Plane: PlaneInstance, Grants: mustGrants(t, "spec:propose"),
			},
			"agent a session s-1 for ~bigbes (tokens.sr.ht: spec:propose)",
		},
	}
	for _, c := range cases {
		if got := c.p.String(); got != c.want {
			t.Fatalf("String() = %q, want %q", got, c.want)
		}
	}
}