feat: declare API errors and authentication with developer tooling

This commit is contained in:
2026-09-23 18:17:43 +08:00
parent ab8eac5fc4
commit 2913e94a0a
35 changed files with 2246 additions and 107 deletions

View File

@@ -33,3 +33,31 @@ func TestAuthFailsClosedAndDoesNotLeakKey(t *testing.T) {
}
}
}
func TestReadOnlyTokenCanReadButCannotWrite(t *testing.T) {
admin := "admin-012345678901234567890123456789"
read := "read-012345678901234567890123456789"
t.Setenv("USER_SERVICE_API_TOKEN", admin)
t.Setenv("USER_SERVICE_READ_TOKEN", read)
middleware, err := NewAuthFromEnv()
if err != nil {
t.Fatal(err)
}
for _, method := range []string{"GET", "POST", "PUT", "DELETE"} {
called := false
r := httptest.NewRequest(method, "/api/v1/users", nil)
r.Header.Set("Authorization", "Bearer "+read)
err = middleware(func(*httpx.Context) error { called = true; return nil })(httpx.NewContext(r, httptest.NewRecorder(), nil))
if method == "GET" {
if err != nil || !called {
t.Fatal("read token rejected on GET")
}
} else if err == nil || called || apierrors.From(err).Status != 403 {
t.Fatal("read token reached a write")
}
}
t.Setenv("USER_SERVICE_READ_TOKEN", admin)
if _, err = NewAuthFromEnv(); err == nil {
t.Fatal("identical privilege tokens accepted")
}
}