Просмотр исходного кода

fix(auth): enforce API token scopes (#1587)

Read tokens are limited to safe methods, write tokens cannot reach
admin routes, and only an admin session or admin token can mint an
admin token.

Closes #1586
Nacho 1 месяц назад
Родитель
Сommit
2b4d356267

+ 1 - 1
docs/manual.en.md

@@ -541,7 +541,7 @@ This is the largest screen. Main sections:
 - **Agent adoption**: pairing token and server fingerprint.
 - **AdGuard Home**: configuration of the read-only connection to the router's AdGuard panel.
 - **My profile**: name, language, password and sign out.
-- **API Tokens**: bearer tokens for integrations.
+- **API Tokens**: bearer tokens for integrations. A `read` token only allows `GET`, `HEAD` and `OPTIONS`, a `write` token can also mutate non-admin resources, and only an `admin` token reaches administration routes and the database download.
 - **About**: version, links, push/PWA, Telegram and system data.
 
 ### Design decisions

+ 1 - 1
docs/manual.es.md

@@ -541,7 +541,7 @@ Es la pantalla más grande. Secciones principales:
 - **Adopción de agentes**: token de emparejamiento y huella del servidor.
 - **AdGuard Home**: configuración de la conexión de solo lectura al panel AdGuard del router.
 - **Mi perfil**: nombre, idioma, contraseña y salir.
-- **API Tokens**: tokens bearer para integraciones.
+- **API Tokens**: tokens bearer para integraciones. Un token `read` solo permite `GET`, `HEAD` y `OPTIONS`, un token `write` puede además mutar recursos que no son de administración, y solo un token `admin` alcanza las rutas de administración y la descarga de la base de datos.
 - **Acerca de**: versión, enlaces, push/PWA, Telegram y datos del sistema.
 
 ### Decisiones de diseño

+ 5 - 5
server-go/internal/apitoken/store.go

@@ -15,9 +15,9 @@ import (
 
 const (
 	TokenPrefix = "np_"
-	ScopeRead   = "read"
-	ScopeWrite  = "write"
-	ScopeAdmin  = "admin"
+	ScopeRead   = auth.ScopeRead
+	ScopeWrite  = auth.ScopeWrite
+	ScopeAdmin  = auth.ScopeAdmin
 )
 
 type Token struct {
@@ -45,8 +45,8 @@ func randomHex(n int) string {
 	return hex.EncodeToString(b)
 }
 
-func newID() string    { return randomHex(16) }
-func newRaw() string    { return randomHex(24) }
+func newID() string  { return randomHex(16) }
+func newRaw() string { return randomHex(24) }
 
 type Store struct {
 	db     *db.DB

+ 34 - 0
server-go/internal/auth/middleware.go

@@ -37,6 +37,14 @@ type TokenValidator interface {
 	ValidateBearer(raw string) (*User, string)
 }
 
+// Scopes de los API tokens. Un token read solo puede usar métodos seguros,
+// write puede mutar rutas no admin y admin alcanza también RequireAdmin.
+const (
+	ScopeRead  = "read"
+	ScopeWrite = "write"
+	ScopeAdmin = "admin"
+)
+
 // APITokenFromContext devuelve el scope del token API usado ("" si no es token).
 func APITokenFromContext(ctx context.Context) string {
 	s, _ := ctx.Value(ctxAPIToken).(string)
@@ -113,6 +121,10 @@ func RequireAuth(d *db.DB, secret string, tv TokenValidator, next http.Handler)
 		if tv != nil {
 			if raw := bearerToken(r); raw != "" {
 				if user, scope := tv.ValidateBearer(raw); user != nil {
+					if !scopeAllowsMethod(scope, r.Method) {
+						WriteError(w, http.StatusForbidden, "insufficient_scope")
+						return
+					}
 					ctx := context.WithValue(r.Context(), ctxUser, user)
 					ctx = context.WithValue(ctx, ctxAPIToken, scope)
 					next.ServeHTTP(w, r.WithContext(ctx))
@@ -142,7 +154,25 @@ func bearerToken(r *http.Request) string {
 	return strings.TrimPrefix(v, "Bearer ")
 }
 
+// scopeAllowsMethod aplica el contrato de los scopes al método HTTP. Un token
+// read es de solo lectura: GET, HEAD y OPTIONS. write y admin pueden mutar,
+// pero solo admin supera además RequireAdmin.
+func scopeAllowsMethod(scope, method string) bool {
+	switch scope {
+	case ScopeWrite, ScopeAdmin:
+		return true
+	case ScopeRead:
+		switch method {
+		case http.MethodGet, http.MethodHead, http.MethodOptions:
+			return true
+		}
+	}
+	return false
+}
+
 // RequireAdmin exige role === 'admin' (tras RequireAuth) → 403 {error:'forbidden'}.
+// Con un API token exige además scope admin: un token read o write emitido por
+// un admin no hereda el rol y no entra en rutas de administración.
 func RequireAdmin(next http.Handler) http.Handler {
 	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
 		user := UserFromContext(r.Context())
@@ -150,6 +180,10 @@ func RequireAdmin(next http.Handler) http.Handler {
 			WriteError(w, http.StatusForbidden, "forbidden")
 			return
 		}
+		if scope := APITokenFromContext(r.Context()); scope != "" && scope != ScopeAdmin {
+			WriteError(w, http.StatusForbidden, "insufficient_scope")
+			return
+		}
 		next.ServeHTTP(w, r)
 	})
 }

+ 81 - 0
server-go/internal/auth/middleware_scope_test.go

@@ -0,0 +1,81 @@
+package auth
+
+import (
+	"net/http"
+	"net/http/httptest"
+	"testing"
+)
+
+type fakeTokenValidator struct {
+	user  *User
+	scope string
+}
+
+func (f fakeTokenValidator) ValidateBearer(string) (*User, string) {
+	return f.user, f.scope
+}
+
+func scopeHandler(scope string, admin bool) http.Handler {
+	var next http.Handler = http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+		w.WriteHeader(http.StatusOK)
+	})
+	if admin {
+		next = RequireAdmin(next)
+	}
+	return RequireAuth(nil, "secret", fakeTokenValidator{
+		user:  &User{ID: 1, Username: "admin", Role: "admin"},
+		scope: scope,
+	}, next)
+}
+
+func TestScopeAllowsMethodFailClosed(t *testing.T) {
+	admin := &User{ID: 1, Username: "admin", Role: "admin"}
+	for _, tc := range []struct {
+		name   string
+		scope  string
+		method string
+		want   int
+	}{
+		{"read get", ScopeRead, http.MethodGet, http.StatusOK},
+		{"read head", ScopeRead, http.MethodHead, http.StatusOK},
+		{"read post", ScopeRead, http.MethodPost, http.StatusForbidden},
+		{"read delete", ScopeRead, http.MethodDelete, http.StatusForbidden},
+		{"write post", ScopeWrite, http.MethodPost, http.StatusOK},
+		{"admin post", ScopeAdmin, http.MethodPost, http.StatusOK},
+		{"unknown scope get", "bogus", http.MethodGet, http.StatusForbidden},
+		{"empty scope get", "", http.MethodGet, http.StatusForbidden},
+	} {
+		t.Run(tc.name, func(t *testing.T) {
+			h := RequireAuth(nil, "secret", fakeTokenValidator{user: admin, scope: tc.scope},
+				http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) }))
+			req := httptest.NewRequest(tc.method, "/api/overview", nil)
+			req.Header.Set("Authorization", "Bearer np_test")
+			rec := httptest.NewRecorder()
+			h.ServeHTTP(rec, req)
+			if rec.Code != tc.want {
+				t.Fatalf("got %d want %d (body %s)", rec.Code, tc.want, rec.Body.String())
+			}
+		})
+	}
+}
+
+func TestRequireAdminRejectsNonAdminTokenScope(t *testing.T) {
+	for _, tc := range []struct {
+		scope string
+		want  int
+	}{
+		{ScopeRead, http.StatusForbidden},
+		{ScopeWrite, http.StatusForbidden},
+		{ScopeAdmin, http.StatusOK},
+	} {
+		t.Run(tc.scope, func(t *testing.T) {
+			req := httptest.NewRequest(http.MethodGet, "/api/settings/backup", nil)
+			req.Header.Set("Authorization", "Bearer np_test")
+			rec := httptest.NewRecorder()
+			scopeHandler(tc.scope, true).ServeHTTP(rec, req)
+			if rec.Code != tc.want {
+				t.Fatalf("got %d want %d (body %s)", rec.Code, tc.want, rec.Body.String())
+			}
+		})
+	}
+}

+ 169 - 0
server-go/internal/httpapi/token_scope_test.go

@@ -0,0 +1,169 @@
+package httpapi_test
+
+import (
+	"bytes"
+	"encoding/json"
+	"net/http"
+	"strings"
+	"testing"
+)
+
+// mintToken crea un API token con la cookie de sesión dada y devuelve el raw.
+func mintToken(t *testing.T, base, cookie, scope string) string {
+	t.Helper()
+	body, _ := json.Marshal(map[string]any{"name": "scope-test", "scope": scope})
+	req, _ := http.NewRequest("POST", base+"/api/tokens", bytes.NewReader(body))
+	req.Header.Set("Content-Type", "application/json")
+	req.Header.Set("Cookie", "session="+cookie)
+	res, err := http.DefaultClient.Do(req)
+	if err != nil {
+		t.Fatalf("crear token %s: %v", scope, err)
+	}
+	defer res.Body.Close()
+	if res.StatusCode != http.StatusCreated {
+		t.Fatalf("crear token %s: got %d want 201", scope, res.StatusCode)
+	}
+	var out struct {
+		Token string `json:"token"`
+	}
+	if err := json.NewDecoder(res.Body).Decode(&out); err != nil {
+		t.Fatalf("crear token %s: %v", scope, err)
+	}
+	if out.Token == "" {
+		t.Fatalf("crear token %s: raw vacío", scope)
+	}
+	return out.Token
+}
+
+// tokenRequest hace una petición autenticada con Bearer.
+func tokenRequest(t *testing.T, method, base, path, token, body string) *http.Response {
+	t.Helper()
+	req, _ := http.NewRequest(method, base+path, strings.NewReader(body))
+	req.Header.Set("Content-Type", "application/json")
+	req.Header.Set("Authorization", "Bearer "+token)
+	res, err := http.DefaultClient.Do(req)
+	if err != nil {
+		t.Fatalf("%s %s: %v", method, path, err)
+	}
+	return res
+}
+
+// sessionRequest hace una petición autenticada con cookie de sesión.
+func sessionRequest(t *testing.T, method, base, path, cookie, body string) *http.Response {
+	t.Helper()
+	req, _ := http.NewRequest(method, base+path, strings.NewReader(body))
+	req.Header.Set("Content-Type", "application/json")
+	req.Header.Set("Cookie", "session="+cookie)
+	res, err := http.DefaultClient.Do(req)
+	if err != nil {
+		t.Fatalf("%s %s: %v", method, path, err)
+	}
+	return res
+}
+
+func requireStatus(t *testing.T, res *http.Response, want int, label string) {
+	t.Helper()
+	defer res.Body.Close()
+	if res.StatusCode != want {
+		t.Fatalf("%s: got %d want %d", label, res.StatusCode, want)
+	}
+}
+
+func requireScopeError(t *testing.T, res *http.Response, label string) {
+	t.Helper()
+	defer res.Body.Close()
+	if res.StatusCode != http.StatusForbidden {
+		t.Fatalf("%s: got %d want 403", label, res.StatusCode)
+	}
+	var body struct {
+		Error string `json:"error"`
+	}
+	_ = json.NewDecoder(res.Body).Decode(&body)
+	if body.Error != "insufficient_scope" {
+		t.Fatalf("%s: error %q want insufficient_scope", label, body.Error)
+	}
+}
+
+func TestReadTokenIsReadOnly(t *testing.T) {
+	ts := makeTestServer(t)
+	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
+	token := mintToken(t, ts.URL, cookie, "read")
+
+	requireStatus(t, tokenRequest(t, "GET", ts.URL, "/api/overview", token, ""), 200, "GET overview")
+
+	for _, rt := range []struct{ method, path, body string }{
+		{"PUT", "/api/settings/backup", `{}`},
+		{"POST", "/api/agents", `{"slug":"rt-scope"}`},
+		{"DELETE", "/api/devices/aa:bb:cc:dd:ee:ff", ""},
+	} {
+		requireScopeError(t, tokenRequest(t, rt.method, ts.URL, rt.path, token, rt.body),
+			rt.method+" "+rt.path)
+	}
+
+	// Las lecturas admin tampoco están disponibles para un token read.
+	for _, path := range []string{"/api/settings/backup", "/api/backup/download"} {
+		requireScopeError(t, tokenRequest(t, "GET", ts.URL, path, token, ""), "GET "+path)
+	}
+}
+
+func TestWriteTokenCannotReachAdminRoutes(t *testing.T) {
+	ts := makeTestServer(t)
+	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
+	token := mintToken(t, ts.URL, cookie, "write")
+
+	// Una mutación no admin sí está permitida: es el contrato de write.
+	requireStatus(t, tokenRequest(t, "PUT", ts.URL, "/api/users/me/language", token, `{"language":"es"}`), 204,
+		"PUT users/me/language")
+
+	for _, rt := range []struct{ method, path, body string }{
+		{"PUT", "/api/settings/backup", `{}`},
+		{"GET", "/api/settings/backup", ""},
+		{"POST", "/api/agents", `{"slug":"rt-scope"}`},
+	} {
+		requireScopeError(t, tokenRequest(t, rt.method, ts.URL, rt.path, token, rt.body),
+			rt.method+" "+rt.path)
+	}
+}
+
+func TestAdminTokenKeepsAdminAccess(t *testing.T) {
+	ts := makeTestServer(t)
+	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
+	token := mintToken(t, ts.URL, cookie, "admin")
+
+	requireStatus(t, tokenRequest(t, "GET", ts.URL, "/api/settings/backup", token, ""), 200, "GET settings/backup")
+	requireStatus(t, tokenRequest(t, "PUT", ts.URL, "/api/settings/backup", token, `{}`), 200, "PUT settings/backup")
+}
+
+func TestWriteTokenCannotCreateAdminToken(t *testing.T) {
+	ts := makeTestServer(t)
+	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
+	token := mintToken(t, ts.URL, cookie, "write")
+
+	requireScopeError(t,
+		tokenRequest(t, "POST", ts.URL, "/api/tokens", token, `{"name":"admin-esc","scope":"admin"}`),
+		"write crea token admin")
+
+	requireStatus(t,
+		tokenRequest(t, "POST", ts.URL, "/api/tokens", token, `{"name":"read-child","scope":"read"}`),
+		201, "write crea token read")
+}
+
+func TestReadTokenCannotCreateTokens(t *testing.T) {
+	ts := makeTestServer(t)
+	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
+	token := mintToken(t, ts.URL, cookie, "read")
+
+	requireScopeError(t,
+		tokenRequest(t, "POST", ts.URL, "/api/tokens", token, `{"name":"nope","scope":"read"}`),
+		"read crea token")
+}
+
+func TestSessionWithoutAdminScopeStillCannotCreateAdminToken(t *testing.T) {
+	ts := makeTestServer(t)
+	_, adminCookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
+	viewerCookie := createUserAndLogin(t, ts.URL, adminCookie, "viewer2", "clave12345", "user")
+
+	requireStatus(t,
+		sessionRequest(t, "POST", ts.URL, "/api/tokens", viewerCookie, `{"name":"admin-esc","scope":"admin"}`),
+		403, "viewer crea token admin")
+}

+ 16 - 3
server-go/internal/httpapi/tokens_api.go

@@ -3,6 +3,7 @@ package httpapi
 import (
 	"net/http"
 
+	"github.com/gnacho/netpulse/server-go/internal/apitoken"
 	"github.com/gnacho/netpulse/server-go/internal/auth"
 )
 
@@ -51,9 +52,9 @@ func (s *server) handleTokensCreate(w http.ResponseWriter, r *http.Request) {
 		return
 	}
 	var body struct {
-		Name       string `json:"name"`
-		Scope      string `json:"scope"`
-		ExpiresIn  int    `json:"expiresInDays"`
+		Name      string `json:"name"`
+		Scope     string `json:"scope"`
+		ExpiresIn int    `json:"expiresInDays"`
 	}
 	if status := readJSONBody(w, r, &body); status != 0 {
 		writeBodyError(w, status, "invalid_body", "")
@@ -63,6 +64,18 @@ func (s *server) handleTokensCreate(w http.ResponseWriter, r *http.Request) {
 		writeError(w, http.StatusBadRequest, "invalid_input", "name and scope required")
 		return
 	}
+	// Un token no puede elevarse por encima de sí mismo: solo un admin con
+	// sesión (o un token admin) puede emitir otro token admin.
+	if body.Scope == apitoken.ScopeAdmin {
+		if user.Role != "admin" {
+			writeError(w, http.StatusForbidden, "forbidden")
+			return
+		}
+		if scope := auth.APITokenFromContext(r.Context()); scope != "" && scope != apitoken.ScopeAdmin {
+			writeError(w, http.StatusForbidden, "insufficient_scope")
+			return
+		}
+	}
 	id, raw, err := s.tokenStore.Create(body.Name, body.Scope, user.ID, body.ExpiresIn)
 	if err != nil {
 		writeError(w, http.StatusBadRequest, "create_failed", err.Error())