diff --git a/CLAUDE.md b/CLAUDE.md index 0b28a788..5693d1f2 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -55,6 +55,7 @@ Main config file (YAML): - `coordinator` - max concurrent tests, retention - `web` - server host/port, API/frontend toggles - `web.frontend.pprof` mounts Go pprof on `/debug/pprof/`. With an `authProviderUrl` it needs the login: a bearer header (tools) or the `assertoor_debug_token` cookie, which the SPA's gate page (`web-ui/src/pages/DebugLogin.tsx`) sets from the session for a browser. Profile downloads are logged with the user; the index page is not. + - Features (`pkg/web/auth/handler.go`): `write` (schedule, cancel and delete test runs, edit the dashboard config, start AI chats), `test_registry` (register, delete and reschedule tests) and `pprof` need an explicit `assertoor:` grant in the token's services claim; basic access is read-only. A token without the claim (an authenticatoor without grants) keeps every feature. - `endpoints` - array of {name, executionUrl, consensusUrl} - `validatorNames` - inventory for mapping validator indices to names - `globalVars` - variables available to all tests diff --git a/go.mod b/go.mod index 10e93395..e412c8b0 100644 --- a/go.mod +++ b/go.mod @@ -8,7 +8,7 @@ require ( github.com/ethereum/go-ethereum v1.17.4 github.com/ethpandaops/ethwallclock v0.4.0 github.com/ethpandaops/go-eth2-client v0.1.6 - github.com/ethpandaops/service-authenticatoor v0.0.2 + github.com/ethpandaops/service-authenticatoor v0.0.4-0.20261116121942-b69364b3c7ff github.com/ethpandaops/spamoor v1.2.2 github.com/glebarez/go-sqlite v1.22.0 github.com/golang-jwt/jwt/v5 v5.3.1 diff --git a/go.sum b/go.sum index 6c066795..fe8b2894 100644 --- a/go.sum +++ b/go.sum @@ -81,8 +81,8 @@ github.com/ethpandaops/ethwallclock v0.4.0 h1:+sgnhf4pk6hLPukP076VxkiLloE4L0Yk1y github.com/ethpandaops/ethwallclock v0.4.0/go.mod h1:y0Cu+mhGLlem19vnAV2x0hpFS5KZ7oOi2SWYayv9l24= github.com/ethpandaops/go-eth2-client v0.1.6 h1:lG7Xz767YQQ+mN1ldzqJlj9Klg6zOElcemjXbCgJV5o= github.com/ethpandaops/go-eth2-client v0.1.6/go.mod h1:97Oq3omOQSGPPYgrbsOIIw2Pc4T5Ph21f8ZRyHJQBHU= -github.com/ethpandaops/service-authenticatoor v0.0.2 h1:0rqHA2Rw64+NG0HVGRfqVhJEkRZRzH3qhX2SkBr2u+w= -github.com/ethpandaops/service-authenticatoor v0.0.2/go.mod h1:nIInMlq5O7YQDLVCL5gf0TeVAvVd9Q50k3sm3abTeG0= +github.com/ethpandaops/service-authenticatoor v0.0.4-0.20261116121942-b69364b3c7ff h1:eqnByos7MzNpDEf2djrnicQDfSlAlQllCYJEiGT4eKM= +github.com/ethpandaops/service-authenticatoor v0.0.4-0.20261116121942-b69364b3c7ff/go.mod h1:dPfMbnEE1VNUkD74mP2ad4C323jisbGdYK3R6srD7Xo= github.com/ethpandaops/spamoor v1.2.2 h1:hkTVJA8jRTWsR0IvH1WsQcq5cWOui4ikOya7mYZ7B6g= github.com/ethpandaops/spamoor v1.2.2/go.mod h1:gnsi2XbsfQNtRq7Je/lV46Y37gTssPU/ZoJ4qxgezd0= github.com/ferranbt/fastssz v0.1.4 h1:OCDB+dYDEQDvAgtAGnTSidK1Pe2tW3nFV40XyMkTeDY= diff --git a/pkg/web/api/ai_handler.go b/pkg/web/api/ai_handler.go index df8e4637..6fe55e23 100644 --- a/pkg/web/api/ai_handler.go +++ b/pkg/web/api/ai_handler.go @@ -198,9 +198,14 @@ type AIChatStartResponse struct { func (h *AIHandler) Chat(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", contentTypeJSON) - if !h.checkAuth(r) { + switch h.authHandler.FeatureStatus(r, auth.FeatureWrite) { + case http.StatusOK: + case http.StatusUnauthorized: h.sendUnauthorizedResponse(w, "/api/v1/ai/chat") return + default: + h.sendErrorResponse(w, "/api/v1/ai/chat", "forbidden: this login lacks the assertoor feature "+auth.FeatureWrite, http.StatusForbidden) + return } if h.client == nil { diff --git a/pkg/web/api/dashboard_config_api.go b/pkg/web/api/dashboard_config_api.go index c4c3dc97..2cf7ad99 100644 --- a/pkg/web/api/dashboard_config_api.go +++ b/pkg/web/api/dashboard_config_api.go @@ -7,6 +7,7 @@ import ( "io" "net/http" + "github.com/ethpandaops/assertoor/pkg/web/auth" "github.com/jmoiron/sqlx" ) @@ -68,14 +69,13 @@ func (ah *APIHandler) GetDashboardConfig(w http.ResponseWriter, r *http.Request) // @Success 200 {object} Response "Saved" // @Failure 400 {object} Response "Bad Request" // @Failure 401 {object} Response "Unauthorized" +// @Failure 403 {object} Response "Login lacks the write feature" // @Failure 500 {object} Response "Server Error" // @Router /api/v1/dashboard_config [put] func (ah *APIHandler) PutDashboardConfig(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", contentTypeJSON) - if !ah.checkAuth(r) { - ah.sendUnauthorizedResponse(w, r.URL.String()) - + if !ah.requireFeature(w, r, auth.FeatureWrite) { return } diff --git a/pkg/web/api/docs/docs.go b/pkg/web/api/docs/docs.go index e15e2c2a..b1af3169 100644 --- a/pkg/web/api/docs/docs.go +++ b/pkg/web/api/docs/docs.go @@ -124,6 +124,12 @@ const docTemplate = `{ "$ref": "#/definitions/web_api.Response" } }, + "403": { + "description": "Login lacks the write feature", + "schema": { + "$ref": "#/definitions/web_api.Response" + } + }, "500": { "description": "Server Error", "schema": { @@ -662,6 +668,12 @@ const docTemplate = `{ "$ref": "#/definitions/web_api.Response" } }, + "403": { + "description": "Login lacks the test_registry feature", + "schema": { + "$ref": "#/definitions/web_api.Response" + } + }, "404": { "description": "Test not found", "schema": { @@ -884,6 +896,18 @@ const docTemplate = `{ "$ref": "#/definitions/web_api.Response" } }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/web_api.Response" + } + }, + "403": { + "description": "Login lacks the write feature", + "schema": { + "$ref": "#/definitions/web_api.Response" + } + }, "500": { "description": "Server Error", "schema": { @@ -1296,6 +1320,18 @@ const docTemplate = `{ "$ref": "#/definitions/web_api.Response" } }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/web_api.Response" + } + }, + "403": { + "description": "Login lacks the write feature", + "schema": { + "$ref": "#/definitions/web_api.Response" + } + }, "500": { "description": "Server Error", "schema": { @@ -1352,6 +1388,18 @@ const docTemplate = `{ "$ref": "#/definitions/web_api.Response" } }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/web_api.Response" + } + }, + "403": { + "description": "Login lacks the write feature", + "schema": { + "$ref": "#/definitions/web_api.Response" + } + }, "500": { "description": "Server Error", "schema": { @@ -1460,6 +1508,18 @@ const docTemplate = `{ "$ref": "#/definitions/web_api.Response" } }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/web_api.Response" + } + }, + "403": { + "description": "Login lacks the test_registry feature", + "schema": { + "$ref": "#/definitions/web_api.Response" + } + }, "500": { "description": "Server Error", "schema": { @@ -1520,6 +1580,18 @@ const docTemplate = `{ "$ref": "#/definitions/web_api.Response" } }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/web_api.Response" + } + }, + "403": { + "description": "Login lacks the test_registry feature", + "schema": { + "$ref": "#/definitions/web_api.Response" + } + }, "500": { "description": "Server Error", "schema": { @@ -1579,6 +1651,18 @@ const docTemplate = `{ "$ref": "#/definitions/web_api.Response" } }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/web_api.Response" + } + }, + "403": { + "description": "Login lacks the test_registry feature", + "schema": { + "$ref": "#/definitions/web_api.Response" + } + }, "500": { "description": "Server Error", "schema": { diff --git a/pkg/web/api/docs/swagger.json b/pkg/web/api/docs/swagger.json index e2fc22d9..f8fd4dae 100644 --- a/pkg/web/api/docs/swagger.json +++ b/pkg/web/api/docs/swagger.json @@ -116,6 +116,12 @@ "$ref": "#/definitions/web_api.Response" } }, + "403": { + "description": "Login lacks the write feature", + "schema": { + "$ref": "#/definitions/web_api.Response" + } + }, "500": { "description": "Server Error", "schema": { @@ -654,6 +660,12 @@ "$ref": "#/definitions/web_api.Response" } }, + "403": { + "description": "Login lacks the test_registry feature", + "schema": { + "$ref": "#/definitions/web_api.Response" + } + }, "404": { "description": "Test not found", "schema": { @@ -876,6 +888,18 @@ "$ref": "#/definitions/web_api.Response" } }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/web_api.Response" + } + }, + "403": { + "description": "Login lacks the write feature", + "schema": { + "$ref": "#/definitions/web_api.Response" + } + }, "500": { "description": "Server Error", "schema": { @@ -1288,6 +1312,18 @@ "$ref": "#/definitions/web_api.Response" } }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/web_api.Response" + } + }, + "403": { + "description": "Login lacks the write feature", + "schema": { + "$ref": "#/definitions/web_api.Response" + } + }, "500": { "description": "Server Error", "schema": { @@ -1344,6 +1380,18 @@ "$ref": "#/definitions/web_api.Response" } }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/web_api.Response" + } + }, + "403": { + "description": "Login lacks the write feature", + "schema": { + "$ref": "#/definitions/web_api.Response" + } + }, "500": { "description": "Server Error", "schema": { @@ -1452,6 +1500,18 @@ "$ref": "#/definitions/web_api.Response" } }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/web_api.Response" + } + }, + "403": { + "description": "Login lacks the test_registry feature", + "schema": { + "$ref": "#/definitions/web_api.Response" + } + }, "500": { "description": "Server Error", "schema": { @@ -1512,6 +1572,18 @@ "$ref": "#/definitions/web_api.Response" } }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/web_api.Response" + } + }, + "403": { + "description": "Login lacks the test_registry feature", + "schema": { + "$ref": "#/definitions/web_api.Response" + } + }, "500": { "description": "Server Error", "schema": { @@ -1571,6 +1643,18 @@ "$ref": "#/definitions/web_api.Response" } }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/web_api.Response" + } + }, + "403": { + "description": "Login lacks the test_registry feature", + "schema": { + "$ref": "#/definitions/web_api.Response" + } + }, "500": { "description": "Server Error", "schema": { diff --git a/pkg/web/api/docs/swagger.yaml b/pkg/web/api/docs/swagger.yaml index 2af42556..23e5f0c7 100644 --- a/pkg/web/api/docs/swagger.yaml +++ b/pkg/web/api/docs/swagger.yaml @@ -789,6 +789,10 @@ paths: description: Unauthorized schema: $ref: '#/definitions/web_api.Response' + "403": + description: Login lacks the write feature + schema: + $ref: '#/definitions/web_api.Response' "500": description: Server Error schema: @@ -1152,6 +1156,10 @@ paths: description: Unauthorized schema: $ref: '#/definitions/web_api.Response' + "403": + description: Login lacks the test_registry feature + schema: + $ref: '#/definitions/web_api.Response' "404": description: Test not found schema: @@ -1296,6 +1304,14 @@ paths: description: Failure schema: $ref: '#/definitions/web_api.Response' + "401": + description: Unauthorized + schema: + $ref: '#/definitions/web_api.Response' + "403": + description: Login lacks the write feature + schema: + $ref: '#/definitions/web_api.Response' "500": description: Server Error schema: @@ -1563,6 +1579,14 @@ paths: description: Failure schema: $ref: '#/definitions/web_api.Response' + "401": + description: Unauthorized + schema: + $ref: '#/definitions/web_api.Response' + "403": + description: Login lacks the write feature + schema: + $ref: '#/definitions/web_api.Response' "500": description: Server Error schema: @@ -1597,6 +1621,14 @@ paths: description: Failure schema: $ref: '#/definitions/web_api.Response' + "401": + description: Unauthorized + schema: + $ref: '#/definitions/web_api.Response' + "403": + description: Login lacks the write feature + schema: + $ref: '#/definitions/web_api.Response' "500": description: Server Error schema: @@ -1664,6 +1696,14 @@ paths: description: Failure schema: $ref: '#/definitions/web_api.Response' + "401": + description: Unauthorized + schema: + $ref: '#/definitions/web_api.Response' + "403": + description: Login lacks the test_registry feature + schema: + $ref: '#/definitions/web_api.Response' "500": description: Server Error schema: @@ -1701,6 +1741,14 @@ paths: description: Failure schema: $ref: '#/definitions/web_api.Response' + "401": + description: Unauthorized + schema: + $ref: '#/definitions/web_api.Response' + "403": + description: Login lacks the test_registry feature + schema: + $ref: '#/definitions/web_api.Response' "500": description: Server Error schema: @@ -1737,6 +1785,14 @@ paths: description: Failure schema: $ref: '#/definitions/web_api.Response' + "401": + description: Unauthorized + schema: + $ref: '#/definitions/web_api.Response' + "403": + description: Login lacks the test_registry feature + schema: + $ref: '#/definitions/web_api.Response' "500": description: Server Error schema: diff --git a/pkg/web/api/handler.go b/pkg/web/api/handler.go index 2f14f07f..08f212d2 100644 --- a/pkg/web/api/handler.go +++ b/pkg/web/api/handler.go @@ -56,6 +56,22 @@ func (ah *APIHandler) checkAuth(r *http.Request) bool { return true } +// requireFeature is checkAuth for an endpoint behind a feature (auth.Feature*): +// it answers 401 without a valid login and 403 when the login lacks the +// feature, and returns false in both cases. +func (ah *APIHandler) requireFeature(w http.ResponseWriter, r *http.Request, feature string) bool { + switch ah.authHandler.FeatureStatus(r, feature) { + case http.StatusOK: + return true + case http.StatusUnauthorized: + ah.sendUnauthorizedResponse(w, r.URL.String()) + default: + ah.sendErrorResponse(w, r.URL.String(), "forbidden: this login lacks the assertoor feature "+feature, http.StatusForbidden) + } + + return false +} + func (ah *APIHandler) sendUnauthorizedResponse(w http.ResponseWriter, route string) { ah.sendErrorResponse(w, route, "unauthorized", http.StatusUnauthorized) } diff --git a/pkg/web/api/post_test_run_api.go b/pkg/web/api/post_test_run_api.go index 2e732e1c..46cf39f9 100644 --- a/pkg/web/api/post_test_run_api.go +++ b/pkg/web/api/post_test_run_api.go @@ -6,6 +6,7 @@ import ( "net/http" "github.com/ethpandaops/assertoor/pkg/types" + "github.com/ethpandaops/assertoor/pkg/web/auth" "gopkg.in/yaml.v3" ) @@ -69,13 +70,14 @@ type PostTestRunsScheduleResponse struct { // @Param runOptions body PostTestRunsScheduleRequest true "Rest run options" // @Success 200 {object} Response{data=PostTestRunsScheduleResponse} "Success" // @Failure 400 {object} Response "Failure" +// @Failure 401 {object} Response "Unauthorized" +// @Failure 403 {object} Response "Login lacks the write feature" // @Failure 500 {object} Response "Server Error" // @Router /api/v1/test_runs/schedule [post] func (ah *APIHandler) PostTestRunsSchedule(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", contentTypeJSON) - if !ah.checkAuth(r) { - ah.sendUnauthorizedResponse(w, r.URL.String()) + if !ah.requireFeature(w, r, auth.FeatureWrite) { return } diff --git a/pkg/web/api/post_test_run_cancel_api.go b/pkg/web/api/post_test_run_cancel_api.go index a2e67ddc..e72324db 100644 --- a/pkg/web/api/post_test_run_cancel_api.go +++ b/pkg/web/api/post_test_run_cancel_api.go @@ -6,6 +6,7 @@ import ( "net/http" "strconv" + "github.com/ethpandaops/assertoor/pkg/web/auth" "github.com/gorilla/mux" "gopkg.in/yaml.v3" ) @@ -31,13 +32,14 @@ type PostTestRunCancelResponse struct { // @Param cancelOptions body PostTestRunCancelRequest true "Test cancellation options" // @Success 200 {object} Response{data=PostTestRunCancelResponse} "Success" // @Failure 400 {object} Response "Failure" +// @Failure 401 {object} Response "Unauthorized" +// @Failure 403 {object} Response "Login lacks the write feature" // @Failure 500 {object} Response "Server Error" // @Router /api/v1/test_run/{runId}/cancel [post] func (ah *APIHandler) PostTestRunCancel(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", contentTypeJSON) - if !ah.checkAuth(r) { - ah.sendUnauthorizedResponse(w, r.URL.String()) + if !ah.requireFeature(w, r, auth.FeatureWrite) { return } diff --git a/pkg/web/api/post_test_runs_delete_api.go b/pkg/web/api/post_test_runs_delete_api.go index 97d9ac30..2b9d965d 100644 --- a/pkg/web/api/post_test_runs_delete_api.go +++ b/pkg/web/api/post_test_runs_delete_api.go @@ -5,6 +5,7 @@ import ( "fmt" "net/http" + "github.com/ethpandaops/assertoor/pkg/web/auth" "gopkg.in/yaml.v3" ) @@ -27,13 +28,14 @@ type PostTestRunsDeleteResponse struct { // @Param testConfig body PostTestRunsDeleteRequest true "Test configuration (json or yaml)" // @Success 200 {object} Response{data=PostTestRunsDeleteResponse} "Success" // @Failure 400 {object} Response "Failure" +// @Failure 401 {object} Response "Unauthorized" +// @Failure 403 {object} Response "Login lacks the write feature" // @Failure 500 {object} Response "Server Error" // @Router /api/v1/test_runs/delete [post] func (ah *APIHandler) PostTestRunsDelete(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", contentTypeJSON) - if !ah.checkAuth(r) { - ah.sendUnauthorizedResponse(w, r.URL.String()) + if !ah.requireFeature(w, r, auth.FeatureWrite) { return } diff --git a/pkg/web/api/post_tests_delete_api.go b/pkg/web/api/post_tests_delete_api.go index c1d8d9fa..6b232c8c 100644 --- a/pkg/web/api/post_tests_delete_api.go +++ b/pkg/web/api/post_tests_delete_api.go @@ -5,6 +5,7 @@ import ( "fmt" "net/http" + "github.com/ethpandaops/assertoor/pkg/web/auth" "gopkg.in/yaml.v3" ) @@ -27,13 +28,14 @@ type PostTestsDeleteResponse struct { // @Param testConfig body PostTestsDeleteRequest true "Test configuration (json or yaml)" // @Success 200 {object} Response{data=PostTestsDeleteResponse} "Success" // @Failure 400 {object} Response "Failure" +// @Failure 401 {object} Response "Unauthorized" +// @Failure 403 {object} Response "Login lacks the test_registry feature" // @Failure 500 {object} Response "Server Error" // @Router /api/v1/tests/delete [post] func (ah *APIHandler) PostTestsDelete(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", contentTypeJSON) - if !ah.checkAuth(r) { - ah.sendUnauthorizedResponse(w, r.URL.String()) + if !ah.requireFeature(w, r, auth.FeatureTestRegistry) { return } diff --git a/pkg/web/api/post_tests_register_api.go b/pkg/web/api/post_tests_register_api.go index 8a688c1f..786b7c8a 100644 --- a/pkg/web/api/post_tests_register_api.go +++ b/pkg/web/api/post_tests_register_api.go @@ -9,6 +9,7 @@ import ( "github.com/ethpandaops/assertoor/pkg/helper" "github.com/ethpandaops/assertoor/pkg/types" + "github.com/ethpandaops/assertoor/pkg/web/auth" "gopkg.in/yaml.v3" ) @@ -39,13 +40,14 @@ type PostTestsRegisterResponse struct { // @Param testConfig body PostTestsRegisterRequest true "Test configuration (json or yaml)" // @Success 200 {object} Response{data=PostTestsRegisterResponse} "Success" // @Failure 400 {object} Response "Failure" +// @Failure 401 {object} Response "Unauthorized" +// @Failure 403 {object} Response "Login lacks the test_registry feature" // @Failure 500 {object} Response "Server Error" // @Router /api/v1/tests/register [post] func (ah *APIHandler) PostTestsRegister(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", contentTypeJSON) - if !ah.checkAuth(r) { - ah.sendUnauthorizedResponse(w, r.URL.String()) + if !ah.requireFeature(w, r, auth.FeatureTestRegistry) { return } diff --git a/pkg/web/api/post_tests_register_external_api.go b/pkg/web/api/post_tests_register_external_api.go index fb8b2b4b..3ad6dd3c 100644 --- a/pkg/web/api/post_tests_register_external_api.go +++ b/pkg/web/api/post_tests_register_external_api.go @@ -8,6 +8,7 @@ import ( "github.com/ethpandaops/assertoor/pkg/helper" "github.com/ethpandaops/assertoor/pkg/types" + "github.com/ethpandaops/assertoor/pkg/web/auth" "gopkg.in/yaml.v3" ) @@ -36,13 +37,14 @@ type PostTestsRegisterExternalResponse struct { // @Param externalTestConfig body PostTestsRegisterExternalRequest true "Test configuration (json or yaml)" // @Success 200 {object} Response{data=PostTestsRegisterExternalResponse} "Success" // @Failure 400 {object} Response "Failure" +// @Failure 401 {object} Response "Unauthorized" +// @Failure 403 {object} Response "Login lacks the test_registry feature" // @Failure 500 {object} Response "Server Error" // @Router /api/v1/tests/register_external [post] func (ah *APIHandler) PostTestsRegisterExternal(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", contentTypeJSON) - if !ah.checkAuth(r) { - ah.sendUnauthorizedResponse(w, r.URL.String()) + if !ah.requireFeature(w, r, auth.FeatureTestRegistry) { return } diff --git a/pkg/web/api/put_test_schedule_api.go b/pkg/web/api/put_test_schedule_api.go index 01d70f63..22778cff 100644 --- a/pkg/web/api/put_test_schedule_api.go +++ b/pkg/web/api/put_test_schedule_api.go @@ -7,6 +7,7 @@ import ( "time" "github.com/ethpandaops/assertoor/pkg/types" + "github.com/ethpandaops/assertoor/pkg/web/auth" "github.com/gorhill/cronexpr" "github.com/gorilla/mux" ) @@ -34,14 +35,14 @@ type PutTestScheduleRequest struct { // @Success 200 {object} Response "Saved" // @Failure 400 {object} Response "Bad Request" // @Failure 401 {object} Response "Unauthorized" +// @Failure 403 {object} Response "Login lacks the test_registry feature" // @Failure 404 {object} Response "Test not found" // @Failure 500 {object} Response "Server Error" // @Router /api/v1/test/{testId}/schedule [put] func (ah *APIHandler) PutTestSchedule(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", contentTypeJSON) - if !ah.checkAuth(r) { - ah.sendUnauthorizedResponse(w, r.URL.String()) + if !ah.requireFeature(w, r, auth.FeatureTestRegistry) { return } diff --git a/pkg/web/auth/check.go b/pkg/web/auth/check.go index 14c9b9c0..bf577a10 100644 --- a/pkg/web/auth/check.go +++ b/pkg/web/auth/check.go @@ -1,6 +1,7 @@ package auth import ( + "net/http" "strings" "github.com/golang-jwt/jwt/v5" @@ -75,6 +76,33 @@ func TokenSubject(token *jwt.Token) string { return "" } +// HasFeature reports whether a token returned by CheckAuthToken allows a +// privileged feature (FeatureTestRegistry, FeaturePprof). Features need an +// explicit grant ("assertoor:" or "assertoor:all") in the token's +// services claim. In open mode every feature is allowed. +func (h *Handler) HasFeature(token *jwt.Token, feature string) bool { + if h.verifier == nil { + return true + } + + if token == nil || !token.Valid { + return false + } + + claims, ok := token.Claims.(*authpkg.Claims) + if !ok { + return false + } + + // An authenticatoor without grants mints no services claim; its logins + // keep the full access they had before features existed. + if claims.Services == "" { + return true + } + + return claims.HasFeature(serviceName, feature, authpkg.FeatureDefaultDeny) +} + // StripPort removes a trailing ":port" from a request Host header value // so it can be passed to CheckAuthToken. Handles bracketed IPv6 hosts. func StripPort(host string) string { @@ -96,3 +124,23 @@ func StripPort(host string) string { return host } + +// FeatureStatus answers whether the request may use a feature: http.StatusOK, +// http.StatusUnauthorized without a valid login, or http.StatusForbidden when +// the login lacks the feature. Open mode always answers http.StatusOK. +func (h *Handler) FeatureStatus(r *http.Request, feature string) int { + if h == nil || h.IsOpen() { + return http.StatusOK + } + + token := h.CheckAuthToken(r.Header.Get("Authorization"), StripPort(r.Host)) + if token == nil || !token.Valid { + return http.StatusUnauthorized + } + + if !h.HasFeature(token, feature) { + return http.StatusForbidden + } + + return http.StatusOK +} diff --git a/pkg/web/auth/check_test.go b/pkg/web/auth/check_test.go new file mode 100644 index 00000000..6abf91cc --- /dev/null +++ b/pkg/web/auth/check_test.go @@ -0,0 +1,153 @@ +package auth + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/ethpandaops/service-authenticatoor/pkg/issuer" +) + +const ( + testIssuer = "https://auth.test.example" + testAudience = "test.example" + testHost = "assertoor.test.example" +) + +// TestHasFeature runs real tokens through the verifier and the feature +// check: the services claim is what an authenticatoor would mint. +func TestHasFeature(t *testing.T) { + t.Parallel() + + key, err := issuer.GenerateRSAKey() + if err != nil { + t.Fatalf("generate key: %v", err) + } + + newIssuer := func(services string) *issuer.RS256Issuer { + iss, issErr := issuer.NewRS256Issuer(issuer.Config{ + ActiveKey: key, + Issuer: testIssuer, + DefaultAudience: []string{testAudience}, + Scope: "*." + testAudience, + Services: services, + TTL: time.Minute, + }) + if issErr != nil { + t.Fatalf("new issuer: %v", issErr) + } + + return iss + } + + jwks, err := newIssuer("").JWKS() + if err != nil { + t.Fatalf("jwks: %v", err) + } + + mux := http.NewServeMux() + srv := httptest.NewServer(mux) + t.Cleanup(srv.Close) + + mux.HandleFunc("/.well-known/openid-configuration", func(w http.ResponseWriter, _ *http.Request) { + _ = json.NewEncoder(w).Encode(map[string]string{"issuer": testIssuer, "jwks_uri": srv.URL + "/jwks.json"}) + }) + mux.HandleFunc("/jwks.json", func(w http.ResponseWriter, _ *http.Request) { + _, _ = w.Write(jwks) + }) + + handler, err := NewAuthHandler(context.Background(), nil, srv.URL, testAudience) + if err != nil { + t.Fatalf("new auth handler: %v", err) + } + + tests := []struct { + name string + services string + wantService bool // passes the verifier's "assertoor" service gate + wantRegistry bool + wantPprof bool + wantWrite bool + }{ + {"no services claim (authenticatoor without grants)", "", true, true, true, true}, + {"staff: every service and feature", "+all,+all:all", true, true, true, true}, + {"basic access only: read-only", "-all,+assertoor", true, false, false, false}, + {"write granted", "-all,+assertoor,+assertoor:write", true, false, false, true}, + {"test_registry granted", "-all,+assertoor,+assertoor:test_registry", true, true, false, false}, + {"all assertoor features", "-all,+assertoor,+assertoor:all", true, true, true, true}, + {"all but pprof", "-all,+assertoor,+assertoor:all:-pprof", true, true, false, true}, + {"faucet only", "-all,+faucet,+faucet:drop_100eth", false, false, false, false}, + {"no grant at all", "-all", false, false, false, false}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + tokenStr, _, err := newIssuer(tt.services).Issue("alice@example.com", "alice@example.com", nil) + if err != nil { + t.Fatalf("issue: %v", err) + } + + token := handler.CheckAuthToken("Bearer "+tokenStr, testHost) + if got := token != nil && token.Valid; got != tt.wantService { + t.Fatalf("service gate: valid = %v, want %v", got, tt.wantService) + } + + if got := handler.HasFeature(token, FeatureTestRegistry); got != tt.wantRegistry { + t.Errorf("HasFeature(%s) = %v, want %v", FeatureTestRegistry, got, tt.wantRegistry) + } + + if got := handler.HasFeature(token, FeaturePprof); got != tt.wantPprof { + t.Errorf("HasFeature(%s) = %v, want %v", FeaturePprof, got, tt.wantPprof) + } + + if got := handler.HasFeature(token, FeatureWrite); got != tt.wantWrite { + t.Errorf("HasFeature(%s) = %v, want %v", FeatureWrite, got, tt.wantWrite) + } + + req := httptest.NewRequest(http.MethodPost, "http://"+testHost+"/api/v1/test_runs/schedule", http.NoBody) + req.Header.Set("Authorization", "Bearer "+tokenStr) + + wantStatus := http.StatusOK + + switch { + case !tt.wantService: + wantStatus = http.StatusUnauthorized + case !tt.wantWrite: + wantStatus = http.StatusForbidden + } + + if got := handler.FeatureStatus(req, FeatureWrite); got != wantStatus { + t.Errorf("FeatureStatus(%s) = %d, want %d", FeatureWrite, got, wantStatus) + } + }) + } +} + +func TestHasFeatureOpenMode(t *testing.T) { + t.Parallel() + + handler, err := NewAuthHandler(context.Background(), nil, "", "") + if err != nil { + t.Fatalf("new auth handler: %v", err) + } + + token := handler.CheckAuthToken("", testHost) + if !handler.HasFeature(token, FeatureTestRegistry) || !handler.HasFeature(token, FeaturePprof) || !handler.HasFeature(token, FeatureWrite) { + t.Fatal("open mode must allow every feature") + } + + req := httptest.NewRequest(http.MethodPost, "http://"+testHost+"/api/v1/test_runs/schedule", http.NoBody) + if got := handler.FeatureStatus(req, FeatureWrite); got != http.StatusOK { + t.Fatalf("open mode FeatureStatus = %d, want %d", got, http.StatusOK) + } + + var nilHandler *Handler + if got := nilHandler.FeatureStatus(req, FeatureWrite); got != http.StatusOK { + t.Fatalf("nil handler FeatureStatus = %d, want %d", got, http.StatusOK) + } +} diff --git a/pkg/web/auth/handler.go b/pkg/web/auth/handler.go index 8ad11701..bd80aebe 100644 --- a/pkg/web/auth/handler.go +++ b/pkg/web/auth/handler.go @@ -20,6 +20,19 @@ import ( // name are rejected. const serviceName = "assertoor" +// Privileged features, granted per login as "assertoor:" in the +// token's services claim. Everything else needs basic access only. +const ( + // FeatureTestRegistry registers, deletes and reschedules test + // definitions. Tests can run shell tasks, so this is code execution. + FeatureTestRegistry = "test_registry" + // FeatureWrite schedules, cancels and deletes test runs, edits the + // dashboard config and starts AI chats. Without it a login can only read. + FeatureWrite = "write" + // FeaturePprof downloads Go runtime profiles from /debug/pprof. + FeaturePprof = "pprof" +) + // Handler validates incoming bearer tokens. When verifier is nil the API // is treated as open (no authentication required); CheckAuthToken always // returns a non-nil "valid" token. diff --git a/pkg/web/pprof.go b/pkg/web/pprof.go index 0e3d9b7e..a8c957c2 100644 --- a/pkg/web/pprof.go +++ b/pkg/web/pprof.go @@ -22,6 +22,10 @@ const debugTokenCookie = "assertoor_debug_token" //nolint:gosec // G101: the coo // prefix) for a request bound to host; see auth.Handler.CheckAuthToken. type tokenChecker func(tokenStr, host string) *jwt.Token +// featureChecker reports whether a token from a tokenChecker allows a +// feature; see auth.Handler.HasFeature. +type featureChecker func(token *jwt.Token, feature string) bool + // pprofHandler gates the pprof pages behind the login. A profile exposes // the process memory (RPC credentials, private keys, ...) and costs CPU to // collect, so unlike the rest of the UI it is never public once an auth @@ -31,11 +35,13 @@ type tokenChecker func(tokenStr, host string) *jwt.Token // pprof) or from debugTokenCookie (a browser). A browser without a valid // login gets the web UI instead, whose page for this path sets the cookie // from the session and reloads, or asks for a login; everything else gets -// a 401. Every profile download is logged with the requesting user; the -// index page with its counts is not. +// a 401. A login without the pprof feature gets a 403. Every profile +// download is logged with the requesting user; the index page with its +// counts is not. type pprofHandler struct { logger logrus.FieldLogger checkToken tokenChecker + hasFeature featureChecker gate http.Handler // the web UI; nil when the frontend is disabled next http.Handler } @@ -44,10 +50,11 @@ var _ http.Handler = (*pprofHandler)(nil) // newPprofHandler wraps next (the pprof mux) in the login gate. gate is the // web UI served to a browser without a login, or nil when there is none. -func newPprofHandler(logger logrus.FieldLogger, checkToken tokenChecker, gate, next http.Handler) http.Handler { +func newPprofHandler(logger logrus.FieldLogger, checkToken tokenChecker, hasFeature featureChecker, gate, next http.Handler) http.Handler { return &pprofHandler{ logger: logger, checkToken: checkToken, + hasFeature: hasFeature, gate: gate, next: next, } @@ -63,6 +70,12 @@ func (h *pprofHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { } if token := h.checkToken(tokenStr, auth.StripPort(r.Host)); token != nil && token.Valid { + if !h.hasFeature(token, auth.FeaturePprof) { + http.Error(w, "forbidden: this login lacks the assertoor feature "+auth.FeaturePprof, http.StatusForbidden) + + return + } + h.serveProfile(w, r, token) return diff --git a/pkg/web/pprof_test.go b/pkg/web/pprof_test.go index f3b26128..8f05614f 100644 --- a/pkg/web/pprof_test.go +++ b/pkg/web/pprof_test.go @@ -13,6 +13,9 @@ const ( testToken = "valid-token" bodyPprof = "pprof" bodyGate = "gate" + pathIndex = "/debug/pprof/" + hdrAccept = "Accept" + mimeHTML = "text/html" ) // acceptToken accepts testToken, bare or as a bearer header. @@ -28,6 +31,10 @@ func openMode(_, _ string) *jwt.Token { return &jwt.Token{Valid: true} } +func allowFeature(_ *jwt.Token, _ string) bool { return true } + +func denyFeature(_ *jwt.Token, _ string) bool { return false } + func TestPprofHandler(t *testing.T) { t.Parallel() @@ -41,6 +48,7 @@ func TestPprofHandler(t *testing.T) { tests := []struct { name string checkToken tokenChecker + hasFeature featureChecker gate http.Handler method string path string @@ -75,6 +83,25 @@ func TestPprofHandler(t *testing.T) { wantStatus: http.StatusOK, wantBody: bodyPprof, }, + { + name: "login without the pprof feature gets 403", + checkToken: acceptToken, + hasFeature: denyFeature, + gate: gate, + path: "/debug/pprof/heap", + cookie: testToken, + wantStatus: http.StatusForbidden, + }, + { + name: "browser login without the pprof feature gets 403, not the gate", + checkToken: acceptToken, + hasFeature: denyFeature, + gate: gate, + path: pathIndex, + header: http.Header{hdrAccept: {mimeHTML}}, + cookie: testToken, + wantStatus: http.StatusForbidden, + }, { name: "invalid header is not rescued by cookie", checkToken: acceptToken, @@ -89,15 +116,15 @@ func TestPprofHandler(t *testing.T) { checkToken: acceptToken, gate: gate, path: "/debug/pprof/heap", - header: http.Header{"Accept": {"*/*"}}, + header: http.Header{hdrAccept: {"*/*"}}, wantStatus: http.StatusUnauthorized, }, { name: "browser without token gets the gate", checkToken: acceptToken, gate: gate, - path: "/debug/pprof/", - header: http.Header{"Accept": {"text/html,application/xhtml+xml"}}, + path: pathIndex, + header: http.Header{hdrAccept: {"text/html,application/xhtml+xml"}}, wantStatus: http.StatusOK, wantBody: bodyGate, }, @@ -106,15 +133,15 @@ func TestPprofHandler(t *testing.T) { checkToken: acceptToken, gate: gate, method: http.MethodPost, - path: "/debug/pprof/", - header: http.Header{"Accept": {"text/html"}}, + path: pathIndex, + header: http.Header{hdrAccept: {mimeHTML}}, wantStatus: http.StatusUnauthorized, }, { name: "browser without gate gets 401", checkToken: acceptToken, - path: "/debug/pprof/", - header: http.Header{"Accept": {"text/html"}}, + path: pathIndex, + header: http.Header{hdrAccept: {mimeHTML}}, wantStatus: http.StatusUnauthorized, }, } @@ -123,7 +150,12 @@ func TestPprofHandler(t *testing.T) { t.Run(tt.name, func(t *testing.T) { t.Parallel() - handler := newPprofHandler(logrus.New(), tt.checkToken, tt.gate, pprofMux) + hasFeature := tt.hasFeature + if hasFeature == nil { + hasFeature = allowFeature + } + + handler := newPprofHandler(logrus.New(), tt.checkToken, hasFeature, tt.gate, pprofMux) method := tt.method if method == "" { diff --git a/pkg/web/server.go b/pkg/web/server.go index 834c1d4e..1d7740c9 100644 --- a/pkg/web/server.go +++ b/pkg/web/server.go @@ -211,6 +211,7 @@ func (ws *Server) ConfigureRoutes(webConfig *types.WebConfig, aiConfig *types.AI ws.router.PathPrefix(pprofPathPrefix + "/").Handler(newPprofHandler( ws.logger.WithField("module", "pprof"), authHandler.CheckAuthToken, + authHandler.HasFeature, spaHandler, http.DefaultServeMux, ))