High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
feat(session): make agent-session grants settable, so eleven enforced capability groups finally have an ingress (PIN-272)
Luigi Agosti5423ebb5ad60
diff --git a/cmd/pinchtab/capability_remedy_executable_test.go b/cmd/pinchtab/capability_remedy_executable_test.goindex b1a85bb8..b92d5170 100644--- a/cmd/pinchtab/capability_remedy_executable_test.go+++ b/cmd/pinchtab/capability_remedy_executable_test.go@@ -73,20 +73,39 @@ func assertRemedyRuns(t *testing.T, line string) {continue}- var args, flags []string- for _, word := range words[1:] {+ // The command path is the words before the first flag; everything after is+ // split by the RESOLVED command's own flag table rather than by the shape of+ // the token, because a flag's separate value does not start with a dash and+ // would otherwise be counted as a positional argument — which rejects every+ // remedy of the form `--flag <value>` however correct it is.+ path := words[1:]+ for i, word := range path {if strings.HasPrefix(word, "-") {- flags = append(flags, word)- continue+ path = path[:i]+ break}- args = append(args, word)}-- found, rest, err := rootCmd.Find(args)+ found, rest, err := rootCmd.Find(path)if err != nil {t.Errorf("remedy command %v does not resolve: %v", words, err)continue}++ args := append([]string(nil), rest...)+ var flags []string+ tail := words[1+len(path):]+ for i := 0; i < len(tail); i++ {+ word := tail[i]+ if !strings.HasPrefix(word, "-") {+ args = append(args, word)+ continue+ }+ flags = append(flags, word)+ if i+1 < len(tail) && !strings.HasPrefix(tail[i+1], "-") && remedyFlagTakesAValue(found, word) {+ i+++ }+ }+ rest = argsif !found.Runnable() || printsGroupHelp(found) {t.Errorf("remedy command %v resolves to %q, which is a command group and only prints help when run",words, found.CommandPath())@@ -109,6 +128,18 @@ func assertRemedyRuns(t *testing.T, line string) {}}+// remedyFlagTakesAValue mirrors cobra's own binding rule rather than a hand list of+// value-taking flags: a flag with no implicit value (everything but a bool) consumes+// the next word. An unknown flag consumes nothing and is reported by the check below.+func remedyFlagTakesAValue(cmd *cobra.Command, word string) bool {+ name, _, _ := strings.Cut(strings.TrimLeft(word, "-"), "=")+ flag := cmd.Flags().Lookup(name)+ if flag == nil {+ flag = cmd.InheritedFlags().Lookup(name)+ }+ return flag != nil && flag.NoOptDefVal == ""+}+// printsGroupHelp reports whether the command's only action is the help the unknown-subcommand// guard installs on groups. Runnable() alone stopped answering this question when that guard// landed: every group is now runnable, and a remedy naming one still does nothing.@@ -128,6 +159,10 @@ func TestTheRemedyGuardRedsOnACommandThatCannotRun(t *testing.T) {"pinchtab config get security.allowedDomains && pinchtab unclog","pinchtab session","pinchtab back --wait-nav",+ // Splitting a flag's value off the positional list must not blind the+ // argument check: revoke takes exactly one id, and this line hands it two+ // past a flag that consumes neither.+ "pinchtab session revoke --json ses_one ses_two",} {fake := &testing.T{}assertRemedyRuns(fake, line)diff --git a/cmd/pinchtab/cmd_session.go b/cmd/pinchtab/cmd_session.goindex 8db456a7..0cc6c17d 100644--- a/cmd/pinchtab/cmd_session.go+++ b/cmd/pinchtab/cmd_session.go@@ -4,11 +4,13 @@ import ("encoding/json""fmt""os"+ "strings""github.com/pinchtab/pinchtab/internal/cli""github.com/pinchtab/pinchtab/internal/cli/apiclient""github.com/pinchtab/pinchtab/internal/cli/output""github.com/pinchtab/pinchtab/internal/server"+ "github.com/pinchtab/pinchtab/internal/session""github.com/spf13/cobra")@@ -69,15 +71,26 @@ func init() {Run: func(cmd *cobra.Command, args []string) {agentID, _ := cmd.Flags().GetString("agent-id")label, _ := cmd.Flags().GetString("label")+ grants, _ := cmd.Flags().GetStringSlice("grant")jsonOutput, _ := cmd.Flags().GetBool("json")if agentID == "" {fmt.Fprintln(os.Stderr, "Error: --agent-id is required")os.Exit(1)}+ // Validated here as well as by the server so a typo costs no round trip+ // and the message can name the whole vocabulary.+ grants, err := session.ValidateGrants(grants)+ if err != nil {+ fmt.Fprintf(os.Stderr, "Error: %v\n", err)+ os.Exit(1)+ }body := map[string]any{"agentId": agentID}if label != "" {body["label"] = label}+ if len(grants) > 0 {+ body["grants"] = grants+ }// Auto-start the control plane first: the documented "create a session// before any browser command" order otherwise fails cold on a fresh// machine (only browser commands start the server).@@ -107,6 +120,8 @@ func init() {}createCmd.Flags().String("agent-id", "", "Agent ID to associate with the session (required)")createCmd.Flags().String("label", "", "Optional human-readable label")+ createCmd.Flags().StringSlice("grant", nil,+ "Limit the session to one capability group; repeatable. Without it the session reaches every non-admin route. Valid: "+strings.Join(session.GrantNames(), ", "))addJSONFlag(createCmd)revokeCmd := &cobra.Command{diff --git a/docs/guides/agent-identity.md b/docs/guides/agent-identity.mdindex 0cf4226b..b398dc78 100644--- a/docs/guides/agent-identity.md+++ b/docs/guides/agent-identity.md@@ -145,7 +145,7 @@ curl -X POST http://localhost:9867/sessions/ses_e6ac8132fe7e7016/revoke \| `sessions.agent.idleTimeoutSec` | `1800` (30m) | Session expires after this many seconds of inactivity || `sessions.agent.maxLifetimeSec` | `86400` (24h) | Hard session expiry |-If a session record carries explicit grants, those grants narrow which endpoint groups the session may call. If a session has no explicit grants, it can use the normal non-admin automation API by default, while dashboard/admin routes remain blocked. That default is meant for trusted automation only.+If a session record carries explicit grants, those grants narrow which endpoint groups the session may call. Grants are set when the session is created — `pinchtab session create --agent-id <id> --grant browse`, or the `grants` field on `POST /sessions` — and are reported by `session list` and `session info`. If a session has no explicit grants, it can use the normal non-admin automation API by default, while dashboard/admin routes remain blocked. That default is meant for trusted automation only. A grant never widens: server-level capability gates still apply on top of it.## Choosing the Right Leveldiff --git a/docs/guides/security.md b/docs/guides/security.mdindex b512c6eb..dd4243f2 100644--- a/docs/guides/security.md+++ b/docs/guides/security.md@@ -179,8 +179,9 @@ CLI commands use the configured local server settings by default, and `PINCHTAB_Agent sessions are reduced-distribution credentials for trusted automation, not a sandbox for untrusted clients.- session-authenticated callers are blocked from dashboard/admin endpoint families such as config, session management, profile management, instance management, dashboard agent listings, and cache controls-- session records can optionally carry explicit grants that narrow access further+- session records can optionally carry explicit grants that narrow access further — set them at creation with `pinchtab session create --agent-id <id> --grant browse` or the `grants` field on `POST /sessions` (see [sessions](../reference/sessions.md#session-grants))- sessions without explicit grants can still use the normal non-admin automation API by default+- a grant only narrows: every server-level capability gate still applies on top, so `--grant evaluate` does not re-enable `security.allowEvaluate` and no grant reaches an admin routeThat means agent sessions are appropriate for controlled environments where the caller is already trusted to drive browser automation but should not receive the full dashboard bearer token. They are not sufficient for hostile multi-tenant sharing or public internet exposure. For that kind of isolation, run separate PinchTab instances behind separate network and credential boundaries.diff --git a/docs/reference/sessions.md b/docs/reference/sessions.mdindex fd589e1f..08ffa07e 100644--- a/docs/reference/sessions.md+++ b/docs/reference/sessions.md@@ -74,7 +74,32 @@ When a session record contains explicit `grants`, PinchTab enforces them in middThe built-in grant groups are: `browse`, `network`, `media`, `cookies`, `clipboard`, `evaluate`, `storage`, `console`, `solve`, `tasks`, and `activity`.-The `cookies` grant only authorizes session access to cookie routes; cookie operations still require the server-level `security.allowCookies` gate.+Set them when the session is created, on the API or on the CLI:++```bash+curl -X POST "$BASE/sessions" -H "Authorization: Bearer $PINCHTAB_TOKEN" \+ -d '{"agentId":"reader","grants":["browse","network"]}'++pinchtab session create --agent-id reader --grant browse --grant network+```++An unrecognised grant is refused with `invalid_grant` and no session is created, so+a typo cannot leave you holding a credential you believe is scoped. `"*"` is the+explicit spelling of "not scoped" and means the same as omitting the field. Grants+are reported by `pinchtab session list` and `pinchtab session info`, and they+survive a restart. There is no route that changes the grants of an existing+session: create a new one with the scope you want and revoke the old.++A request refused for scope answers `session_scope_forbidden` with a hint naming+the grants the session holds and the grant that would have covered the route. The+same code also answers an admin verb, where no grant applies at all — the hint says+which of the two fired, because the remedies differ: a different session, or the+server token.++**Grants narrow; they never widen.** A grant authorizes session access to a group+of routes, and every server-level gate still applies on top: `evaluate` does not+re-enable `security.allowEvaluate`, `cookies` does not re-enable+`security.allowCookies`, and no grant reaches an admin route.That default is a convenience for trusted automation, not a sandbox. If you need hard isolation between agents or tenants, use separate PinchTab instances.@@ -83,6 +108,9 @@ That default is a convenience for trusted automation, not a sandbox. If you need```bash# Create a new session (prints the session token to stdout; use --json for a full JSON object)pinchtab session create --agent-id agent-1++# Create one limited to a capability group (repeatable; see Session Grants)+pinchtab session create --agent-id reader --grant browseexport PINCHTAB_SESSION=$(pinchtab session create --agent-id agent-1)# CLI automatically uses session auth when PINCHTAB_SESSION is setdiff --git a/internal/dashboard/agent_session_api.go b/internal/dashboard/agent_session_api.goindex b1b2c935..179d3524 100644--- a/internal/dashboard/agent_session_api.go+++ b/internal/dashboard/agent_session_api.go@@ -88,9 +88,10 @@ func (a *SessionAPI) handlerFor(pattern string) http.HandlerFunc {func (a *SessionAPI) handleCreate(w http.ResponseWriter, r *http.Request) {var req struct {- AgentID string `json:"agentId"`- Label string `json:"label,omitempty"`- Browser string `json:"browser,omitempty"`+ AgentID string `json:"agentId"`+ Label string `json:"label,omitempty"`+ Browser string `json:"browser,omitempty"`+ Grants []string `json:"grants,omitempty"`}if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4<<10)).Decode(&req); err != nil {httpx.ErrorCode(w, http.StatusBadRequest, "bad_request", "invalid request body", false, nil)@@ -107,11 +108,22 @@ func (a *SessionAPI) handleCreate(w http.ResponseWriter, r *http.Request) {}}+ grants, err := session.ValidateGrants(req.Grants)+ if err != nil {+ httpx.ErrorCode(w, http.StatusBadRequest, "invalid_grant", err.Error(), false, nil)+ return+ }+sessionID, token, err := a.store.Create(req.AgentID, req.Label, req.Browser)if err != nil {httpx.ErrorCode(w, http.StatusInternalServerError, "create_failed", "failed to create session", false, nil)return}+ // Scoped before the token is published: nothing else knows the token yet, so+ // the session cannot authenticate anything between the two writes.+ if len(grants) > 0 {+ a.store.SetGrants(sessionID, grants)+ }sess, _ := a.store.Get(sessionID)@@ -133,6 +145,11 @@ func (a *SessionAPI) handleCreate(w http.ResponseWriter, r *http.Request) {if sess.Browser != "" {resp["browser"] = sess.Browser}+ // Echoed so the caller can see the scope it asked for was applied. A silently+ // dropped grants key is what let an unscoped session look scoped.+ if len(sess.Grants) > 0 {+ resp["grants"] = sess.Grants+ }httpx.JSON(w, http.StatusCreated, resp)}diff --git a/internal/dashboard/agent_session_api_test.go b/internal/dashboard/agent_session_api_test.goindex 411f4cd6..8a8fb83f 100644--- a/internal/dashboard/agent_session_api_test.go+++ b/internal/dashboard/agent_session_api_test.go@@ -529,3 +529,82 @@ func TestAgentSessionAPI_RegisterHandlers_NoOpsWhenDisabled(t *testing.T) {t.Fatalf("status = %d, want %d", w.Code, http.StatusNotFound)}}++// The grants key used to be discarded silently, which is what made an unscoped+// session look scoped: the caller asked for a narrowing, got a 201, and held a+// credential that reached every non-admin route.+func TestAgentSessionAPI_CreateAppliesAndEchoesGrants(t *testing.T) {+ store := newTestSessionStore()+ mux := newTestSessionMux(store)++ req := httptest.NewRequest("POST", "/sessions", strings.NewReader(`{"agentId":"agent-1","grants":["browse"," Network "]}`))+ w := httptest.NewRecorder()+ mux.ServeHTTP(w, req)++ if w.Code != http.StatusCreated {+ t.Fatalf("status = %d: %s", w.Code, w.Body.String())+ }+ resp := decodeSessionResponse(t, w)+ echoed, _ := resp["grants"].([]any)+ if len(echoed) != 2 || echoed[0] != session.GrantBrowse || echoed[1] != session.GrantNetwork {+ t.Fatalf("grants echoed as %v, want the normalized pair", resp["grants"])+ }++ // Echoed is not enough: the store is what the middleware reads.+ id, _ := resp["id"].(string)+ stored, ok := store.Get(id)+ if !ok {+ t.Fatalf("session %q is not in the store", id)+ }+ if len(stored.Grants) != 2 || stored.Grants[0] != session.GrantBrowse {+ t.Errorf("stored grants = %v, want the pair the caller asked for", stored.Grants)+ }+}++// An unknown grant is refused rather than dropped, and the refusal carries the+// offender and the vocabulary — the whole point of not being silent.+func TestAgentSessionAPI_CreateRefusesAnUnknownGrant(t *testing.T) {+ store := newTestSessionStore()+ mux := newTestSessionMux(store)++ req := httptest.NewRequest("POST", "/sessions", strings.NewReader(`{"agentId":"agent-1","grants":["brows"]}`))+ w := httptest.NewRecorder()+ mux.ServeHTTP(w, req)++ if w.Code != http.StatusBadRequest {+ t.Fatalf("status = %d, want 400: %s", w.Code, w.Body.String())+ }+ resp := decodeSessionResponse(t, w)+ if resp["code"] != "invalid_grant" {+ t.Errorf("code = %v, want invalid_grant", resp["code"])+ }+ if msg, _ := resp["error"].(string); !strings.Contains(msg, "brows") || !strings.Contains(msg, "browse") {+ t.Errorf("error = %q, want the offender and the valid names", msg)+ }+ if len(store.List()) != 0 {+ t.Error("a session was created despite the refused grant; a half-applied scope is worse than none")+ }+}++// A session's scope must be readable, not only writable: list and get carry it, so+// an operator can audit what a credential can reach.+func TestAgentSessionAPI_ListAndGetReportGrants(t *testing.T) {+ store := newTestSessionStore()+ mux := newTestSessionMux(store)++ create := httptest.NewRecorder()+ mux.ServeHTTP(create, httptest.NewRequest("POST", "/sessions", strings.NewReader(`{"agentId":"agent-1","grants":["browse"]}`)))+ id, _ := decodeSessionResponse(t, create)["id"].(string)++ get := httptest.NewRecorder()+ mux.ServeHTTP(get, httptest.NewRequest("GET", "/sessions/"+id, nil))+ if !strings.Contains(get.Body.String(), `"grants":["browse"]`) {+ t.Errorf("GET /sessions/{id} does not report the scope: %s", get.Body.String())+ }++ list := httptest.NewRecorder()+ mux.ServeHTTP(list, httptest.NewRequest("GET", "/sessions", nil))+ if !strings.Contains(list.Body.String(), `"grants":["browse"]`) {+ t.Errorf("GET /sessions does not report the scope: %s", list.Body.String())+ }+}diff --git a/internal/handlers/middleware.go b/internal/handlers/middleware.goindex 8b07d4b1..a0c8bed8 100644--- a/internal/handlers/middleware.go+++ b/internal/handlers/middleware.go@@ -15,6 +15,7 @@ import ("github.com/pinchtab/pinchtab/internal/browsersession""github.com/pinchtab/pinchtab/internal/config""github.com/pinchtab/pinchtab/internal/httpx"+ "github.com/pinchtab/pinchtab/internal/remedy""github.com/pinchtab/pinchtab/internal/session")@@ -147,10 +148,10 @@ func AuthMiddlewareWithSessions(live *config.Live, sessions *browsersession.Manahttpx.ErrorCode(w, 401, "bad_session", "invalid or expired agent session", false, nil)return}- if !sessionRequestAllowed(r, sess) {- httpx.ErrorCode(w, http.StatusForbidden, "session_scope_forbidden", "agent session is not allowed to access this endpoint", false, map[string]any{- "safeControlledEnvironmentOnly": true,- })+ if refusal, refused := sessionRequestRefusal(r, sess); refused {+ details := remedy.Details(refusal.hint, refusal.remedy)+ details["safeControlledEnvironmentOnly"] = true+ httpx.ErrorCode(w, http.StatusForbidden, "session_scope_forbidden", "agent session is not allowed to access this endpoint", false, details)return}if !agentSessions.Touch(sess.ID) {diff --git a/internal/handlers/middleware_session_grants.go b/internal/handlers/middleware_session_grants.goindex 4aed6f8c..f52d3f8a 100644--- a/internal/handlers/middleware_session_grants.go+++ b/internal/handlers/middleware_session_grants.go@@ -1,36 +1,103 @@package handlersimport (+ "fmt""net/http"+ "sort""strings"+ "github.com/pinchtab/pinchtab/internal/remedy""github.com/pinchtab/pinchtab/internal/session")+// sessionScopeRefusal says WHICH of the two causes refused the request. The 403+// presented two causes and could only ever have one, so it carried neither; with+// grants reachable an operator has to be able to tell "this credential may never+// do that" from "this session was not given that grant", because the remedies are+// a different credential and a different session.+type sessionScopeRefusal struct {+ hint string+ remedy remedy.Remedy+}++// The admin case has no remedy line: the fix is to send a different credential on+// whatever verb the caller wanted, which is not one command, and a remedy naming a+// command the caller did not ask for is worse than none. The scope case has one — a+// session that carries the grant — so that one is published as a command.+var (+ grantedSessionCmd = remedy.Declare("pinchtab session create --agent-id <id> --grant <grant>")+ adminRouteFormat = "admin verbs are not available to an agent session whatever its grants: this request authenticated with PINCHTAB_SESSION, and %s %s needs the server token"+ outsideGrantsFormat = "this session holds %s, and %s %s is outside them"+ coveringGrantFormat = "; the grant that covers it is %q"+ noCoveringGrantMsg = "; no grant covers it, so it is reachable only with the server token"+)+func sessionRequestAllowed(r *http.Request, sess *session.Session) bool {+ _, refused := sessionRequestRefusal(r, sess)+ return !refused+}++// sessionRequestRefusal is the one decision and its reason. Returning the reason+// beside the verdict is what stops the two from drifting: a refusal that has to be+// re-derived by the caller describes the rule as the caller remembers it.+func sessionRequestRefusal(r *http.Request, sess *session.Session) (sessionScopeRefusal, bool) {method := strings.ToUpper(strings.TrimSpace(r.Method))path := strings.TrimSpace(r.URL.Path)if method == http.MethodPost && sessionRevokePath(path) {- return true+ return sessionScopeRefusal{}, false}if sessionAdminRoute(method, path) {- return false+ return sessionScopeRefusal{+ hint: fmt.Sprintf(adminRouteFormat, method, path),+ remedy: remedy.None,+ }, true}if sess == nil {- return false+ return sessionScopeRefusal{hint: fmt.Sprintf(adminRouteFormat, method, path), remedy: remedy.None}, true}grants := normalizedSessionGrants(sess.Grants)- if len(grants) == 0 || grants["*"] {- return true+ if len(grants) == 0 || grants[session.GrantAll] {+ return sessionScopeRefusal{}, false}for grant := range grants {if sessionGrantAllows(grant, method, path) {- return true+ return sessionScopeRefusal{}, false}}- return false+ return sessionScopeRefusal{+ hint: outsideGrantsRefusalHint(grants, method, path),+ remedy: grantedSessionCmd.Remedy(),+ }, true+}++// outsideGrantsRefusalHint names the grants the session holds and, when one exists, the+// grant that would have covered the route — the caller cannot look that mapping up+// from outside, and a refusal they cannot act on is retried unchanged.+func outsideGrantsRefusalHint(held map[string]bool, method, path string) string {+ names := make([]string, 0, len(held))+ for grant := range held {+ names = append(names, grant)+ }+ sort.Strings(names)++ hint := fmt.Sprintf(outsideGrantsFormat, strings.Join(names, ", "), method, path)+ if covering := grantCovering(method, path); covering != "" {+ return hint + fmt.Sprintf(coveringGrantFormat, covering)+ }+ return hint + noCoveringGrantMsg+}++// grantCovering returns the first grant whose matcher admits this route, walking+// the canonical list so the answer cannot name a grant the API would refuse.+func grantCovering(method, path string) string {+ for _, grant := range session.GrantNames() {+ if sessionGrantAllows(grant, method, path) {+ return grant+ }+ }+ return ""}func normalizedSessionGrants(grants []string) map[string]bool {@@ -88,33 +155,27 @@ func sessionRevokePath(path string) bool {return strings.Trim(sessionID, "/") != ""}+// sessionGrantMatchers binds each grant NAME to the routes it admits. It is a map+// keyed by the vocabulary's own constants rather than a switch over string+// literals, so the enforced set can be compared with the settable set instead of+// being trusted to match it.+var sessionGrantMatchers = map[string]func(method, path string) bool{+ session.GrantBrowse: sessionBrowseGrantAllows,+ session.GrantNetwork: sessionNetworkGrantAllows,+ session.GrantMedia: sessionMediaGrantAllows,+ session.GrantCookies: sessionCookiesGrantAllows,+ session.GrantClipboard: sessionClipboardGrantAllows,+ session.GrantEvaluate: sessionEvaluateGrantAllows,+ session.GrantStorage: sessionStorageGrantAllows,+ session.GrantConsole: sessionConsoleGrantAllows,+ session.GrantSolve: sessionSolveGrantAllows,+ session.GrantTasks: sessionTasksGrantAllows,+ session.GrantActivity: sessionActivityGrantAllows,+}+func sessionGrantAllows(grant, method, path string) bool {- switch grant {- case "browse":- return sessionBrowseGrantAllows(method, path)- case "network":- return sessionNetworkGrantAllows(method, path)- case "media":- return sessionMediaGrantAllows(method, path)- case "cookies":- return sessionCookiesGrantAllows(method, path)- case "clipboard":- return sessionClipboardGrantAllows(method, path)- case "evaluate":- return sessionEvaluateGrantAllows(method, path)- case "storage":- return sessionStorageGrantAllows(method, path)- case "console":- return sessionConsoleGrantAllows(method, path)- case "solve":- return sessionSolveGrantAllows(method, path)- case "tasks":- return sessionTasksGrantAllows(method, path)- case "activity":- return sessionActivityGrantAllows(method, path)- default:- return false- }+ matcher, ok := sessionGrantMatchers[grant]+ return ok && matcher(method, path)}func sessionBrowseGrantAllows(method, path string) bool {diff --git a/internal/handlers/middleware_session_grants_test.go b/internal/handlers/middleware_session_grants_test.gonew file mode 100644index 00000000..c7d68b07--- /dev/null+++ b/internal/handlers/middleware_session_grants_test.go@@ -0,0 +1,202 @@+package handlers++import (+ "net/http"+ "net/http/httptest"+ "slices"+ "sort"+ "strings"+ "testing"+ "time"++ "github.com/pinchtab/pinchtab/internal/config"+ "github.com/pinchtab/pinchtab/internal/session"+)++// grantRoutes names, for every grant, one route inside its group. The table is the+// per-grant coverage the middleware never had: eleven matchers existed and one was+// exercised, because nothing could set the other ten.+var grantRoutes = map[string]struct {+ method string+ path string+}{+ session.GrantBrowse: {http.MethodGet, "/snapshot"},+ session.GrantNetwork: {http.MethodGet, "/network"},+ session.GrantMedia: {http.MethodGet, "/pdf"},+ session.GrantCookies: {http.MethodGet, "/cookies"},+ session.GrantClipboard: {http.MethodGet, "/clipboard/read"},+ session.GrantEvaluate: {http.MethodPost, "/evaluate"},+ session.GrantStorage: {http.MethodGet, "/storage"},+ session.GrantConsole: {http.MethodGet, "/console"},+ session.GrantSolve: {http.MethodGet, "/solvers"},+ session.GrantTasks: {http.MethodGet, "/tasks"},+ session.GrantActivity: {http.MethodGet, "/api/activity"},+}++func requestFor(method, path string) *http.Request {+ return httptest.NewRequest(method, path, nil)+}++// The settable set and the enforced set are one vocabulary. A twelfth grant added+// to either side alone reds here, which is what stops a grant being enforceable+// but unsettable — the shape that let eleven matchers sit behind a field with no+// ingress at all.+func TestEveryGrantNameHasAMatcherAndEveryMatcherHasAName(t *testing.T) {+ enforced := make([]string, 0, len(sessionGrantMatchers))+ for name := range sessionGrantMatchers {+ enforced = append(enforced, name)+ }+ sort.Strings(enforced)++ settable := session.GrantNames()+ sort.Strings(settable)++ if !slices.Equal(enforced, settable) {+ t.Fatalf("the middleware enforces %v and the API accepts %v; one vocabulary, two lists", enforced, settable)+ }+ for name, route := range grantRoutes {+ if _, ok := sessionGrantMatchers[name]; !ok {+ t.Errorf("%s is covered by this test table and is not a grant; the table is describing something that no longer exists", name)+ }+ if !sessionGrantAllows(name, route.method, route.path) {+ t.Errorf("%s does not admit %s %s, so the row below cannot mean what it says", name, route.method, route.path)+ }+ }+ for _, name := range settable {+ if _, ok := grantRoutes[name]; !ok {+ t.Errorf("%s has no route in this table, so it is settable, enforced, and untested", name)+ }+ }+}++// Each grant admits its own group and is refused on every other group's routes.+// Deleting any single matcher arm reds exactly its own row.+func TestEachGrantAdmitsItsOwnGroupAndRefusesTheOthers(t *testing.T) {+ for _, grant := range session.GrantNames() {+ t.Run(grant, func(t *testing.T) {+ sess := &session.Session{Grants: []string{grant}}+ own := grantRoutes[grant]++ if !sessionRequestAllowed(requestFor(own.method, own.path), sess) {+ t.Errorf("a session granted %q was refused %s %s, inside its own group", grant, own.method, own.path)+ }+ for other, route := range grantRoutes {+ if other == grant {+ continue+ }+ if sessionRequestAllowed(requestFor(route.method, route.path), sess) {+ t.Errorf("a session granted only %q reached %s %s, which belongs to %q", grant, route.method, route.path, other)+ }+ }+ })+ }+}++// The two states that admit everything, kept explicit: no grants is "not scoped"+// and "*" is the same thing said out loud.+func TestAnUngrantedSessionIsNotNarrowed(t *testing.T) {+ for name, sess := range map[string]*session.Session{+ "no grants": {},+ "the wildcard": {Grants: []string{session.GrantAll}},+ "wildcard plus": {Grants: []string{session.GrantBrowse, session.GrantAll}},+ } {+ for _, route := range grantRoutes {+ if !sessionRequestAllowed(requestFor(route.method, route.path), sess) {+ t.Errorf("%s: %s %s was refused; an unscoped session is narrowed by nothing", name, route.method, route.path)+ }+ }+ }+}++// A grant narrows and never widens: the admin denylist answers before any grant is+// consulted, so no grant can hand a session an admin verb.+func TestNoGrantReachesAnAdminRoute(t *testing.T) {+ admin := []struct {+ method string+ path string+ }{+ {http.MethodPut, "/api/config"},+ {http.MethodPost, "/shutdown"},+ {http.MethodGet, "/sessions"},+ {http.MethodGet, "/instances"},+ {http.MethodPost, "/cache/clear"},+ }+ all := append(session.GrantNames(), session.GrantAll)+ for _, route := range admin {+ for _, grant := range all {+ sess := &session.Session{Grants: []string{grant}}+ if sessionRequestAllowed(requestFor(route.method, route.path), sess) {+ t.Errorf("grant %q reached the admin route %s %s", grant, route.method, route.path)+ }+ }+ }+}++// The 403 presented two causes and could carry neither. They have different+// remedies — a different credential, or a session with the grant — so the refusal+// has to say which one fired.+func TestTheScopeRefusalNamesWhichCauseFired(t *testing.T) {+ scoped := &session.Session{Grants: []string{session.GrantBrowse}}++ outside, refused := sessionRequestRefusal(requestFor(http.MethodGet, "/clipboard/read"), scoped)+ if !refused {+ t.Fatal("a browse-only session reached the clipboard")+ }+ for _, want := range []string{"browse", "/clipboard/read", "clipboard"} {+ if !strings.Contains(outside.hint, want) {+ t.Errorf("the scope refusal %q does not carry %q — it must name what is held and what would cover the route", outside.hint, want)+ }+ }+ if !strings.Contains(outside.remedy.String(), "--grant") {+ t.Errorf("the scope refusal prescribes %q, not a session carrying the grant", outside.remedy)+ }++ admin, refused := sessionRequestRefusal(requestFor(http.MethodPut, "/api/config"), scoped)+ if !refused {+ t.Fatal("a session reached PUT /api/config")+ }+ if !strings.Contains(admin.hint, "PINCHTAB_SESSION") || !strings.Contains(admin.hint, "server token") {+ t.Errorf("the admin refusal %q does not say which credential arrived or which one is needed", admin.hint)+ }+ if !admin.remedy.Empty() {+ t.Errorf("the admin refusal prescribes %q; the fix is a different credential on whatever verb the caller wanted, which is not one command", admin.remedy)+ }+}++// Grants narrow; server-level gates stay absolute. A grant that appeared to+// re-enable a boot-time capability would be the worst possible outcome of making+// grants reachable, so the composition is asserted rather than reasoned about: the+// middleware admits the route on the grant, and the handler still refuses it.+func TestAGrantDoesNotReopenADisabledServerCapability(t *testing.T) {+ store := session.NewStore(session.Config{Enabled: true, IdleTimeout: 30 * time.Minute, MaxLifetime: 24 * time.Hour})+ sessionID, token, _ := store.Create("test-agent", "", "")+ if !store.SetGrants(sessionID, []string{session.GrantEvaluate}) {+ t.Fatal("the session vanished before it could be scoped")+ }++ h := New(&mockBridge{}, &config.RuntimeConfig{Token: "server-token", AllowEvaluate: false}, nil, nil, nil)+ handler := AuthMiddlewareWithSessions(config.NewLive(h.Config), nil, store, http.HandlerFunc(h.HandleEvaluate))++ req := httptest.NewRequest(http.MethodPost, "/evaluate", strings.NewReader(`{"expression":"1+1"}`))+ req.Header.Set("Authorization", "Session "+token)+ rr := httptest.NewRecorder()+ handler.ServeHTTP(rr, req)++ if rr.Code == http.StatusOK {+ t.Fatal("the evaluate grant reached a handler whose server capability is off")+ }+ if strings.Contains(rr.Body.String(), "session_scope_forbidden") {+ t.Fatalf("the request was refused by SCOPE, not by the server gate, so this test never reached the composition it is about: %s", rr.Body.String())+ }++ // The control: with the capability on, the same grant does reach the handler,+ // so the refusal above is the gate and not the grant.+ h.Config.AllowEvaluate = true+ rr = httptest.NewRecorder()+ req = httptest.NewRequest(http.MethodPost, "/evaluate", strings.NewReader(`{"expression":"1+1"}`))+ req.Header.Set("Authorization", "Session "+token)+ handler.ServeHTTP(rr, req)+ if strings.Contains(rr.Body.String(), "capability") && rr.Code == http.StatusForbidden {+ t.Errorf("with the capability on the request was still refused by the gate: %s", rr.Body.String())+ }+}diff --git a/internal/server/agent_session_grants_test.go b/internal/server/agent_session_grants_test.gonew file mode 100644index 00000000..af7d63f5--- /dev/null+++ b/internal/server/agent_session_grants_test.go@@ -0,0 +1,168 @@+package server++import (+ "bytes"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "os"+ "strings"+ "testing"+ "time"++ "github.com/pinchtab/pinchtab/internal/session"+)++// createSessionWithGrants drives the real POST /sessions through the real chain+// with the server token, which is the only way a scope can be requested. Nothing+// here calls SetGrants: the point of this test is the ingress that did not exist.+func (f frontDoor) createSessionWithGrants(t *testing.T, grants []string) (*httptest.ResponseRecorder, string) {+ t.Helper()+ body, err := json.Marshal(map[string]any{"agentId": "grant-test", "grants": grants})+ if err != nil {+ t.Fatal(err)+ }+ req := httptest.NewRequest(http.MethodPost, "/sessions", bytes.NewReader(body))+ req.Header.Set("Authorization", "Bearer "+frontDoorLiveToken)+ w := httptest.NewRecorder()+ f.handler.ServeHTTP(w, req)+ if w.Code != http.StatusCreated {+ return w, ""+ }+ var created struct {+ Token string `json:"sessionToken"`+ }+ if err := json.Unmarshal(w.Body.Bytes(), &created); err != nil {+ t.Fatalf("decode created session: %v (body %s)", err, w.Body.String())+ }+ return w, created.Token+}++func (f frontDoor) requestAs(t *testing.T, token, method, path string) *httptest.ResponseRecorder {+ t.Helper()+ req := httptest.NewRequest(method, path, nil)+ req.Header.Set("Authorization", "Session "+token)+ w := httptest.NewRecorder()+ f.handler.ServeHTTP(w, req)+ return w+}++// The whole capability, end to end and over HTTP: a session asked for browse and+// only browse, and the front door holds it to that. Every layer used to agree that+// it could not — the DTO dropped the key, so eleven matchers never ran.+func TestASessionScopedAtCreationIsHeldToItsGrants(t *testing.T) {+ f := newFrontDoor(t, nil)++ _, token := f.createSessionWithGrants(t, []string{"browse"})+ if token == "" {+ t.Fatal("no session token came back")+ }++ if inside := f.requestAs(t, token, http.MethodGet, "/tabs"); inside.Code != http.StatusOK {+ t.Fatalf("a browse session was refused GET /tabs (%d: %s)", inside.Code, inside.Body.String())+ }++ outside := f.requestAs(t, token, http.MethodGet, "/clipboard/read")+ if outside.Code != http.StatusForbidden {+ t.Fatalf("a browse-only session reached GET /clipboard/read (%d: %s)", outside.Code, outside.Body.String())+ }+ var refusal struct {+ Code string `json:"code"`+ Details struct {+ Hint string `json:"hint"`+ Remedy string `json:"remedy"`+ } `json:"details"`+ }+ if err := json.Unmarshal(outside.Body.Bytes(), &refusal); err != nil {+ t.Fatalf("decode refusal: %v (body %s)", err, outside.Body.String())+ }+ if refusal.Code != "session_scope_forbidden" {+ t.Errorf("code = %q, want session_scope_forbidden", refusal.Code)+ }+ for _, want := range []string{"browse", "clipboard"} {+ if !strings.Contains(refusal.Details.Hint, want) {+ t.Errorf("hint = %q, want it to name %q", refusal.Details.Hint, want)+ }+ }+ if !strings.Contains(refusal.Details.Remedy, "--grant") {+ t.Errorf("remedy = %q, want the command that creates a session carrying the grant", refusal.Details.Remedy)+ }++ // The control: an unscoped session reaches the same route, so the refusal above+ // is the grant and not the route being unreachable.+ _, open := f.createSessionWithGrants(t, nil)+ if w := f.requestAs(t, open, http.MethodGet, "/clipboard/read"); w.Code != http.StatusOK {+ t.Errorf("an unscoped session was refused GET /clipboard/read (%d: %s)", w.Code, w.Body.String())+ }+}++// The admin denylist answers before any grant, so its refusal must name the other+// cause: a different credential, not a different session.+func TestAnAdminRouteRefusalNamesTheCredentialRatherThanAGrant(t *testing.T) {+ f := newFrontDoor(t, nil)+ _, token := f.createSessionWithGrants(t, []string{"browse"})++ w := f.requestAs(t, token, http.MethodGet, "/api/config")+ if w.Code != http.StatusForbidden {+ t.Fatalf("a session reached GET /api/config (%d: %s)", w.Code, w.Body.String())+ }+ var refusal struct {+ Details struct {+ Hint string `json:"hint"`+ Remedy string `json:"remedy"`+ } `json:"details"`+ }+ if err := json.Unmarshal(w.Body.Bytes(), &refusal); err != nil {+ t.Fatal(err)+ }+ if !strings.Contains(refusal.Details.Hint, "PINCHTAB_SESSION") || !strings.Contains(refusal.Details.Hint, "server token") {+ t.Errorf("hint = %q, want it to say which credential arrived and which is needed", refusal.Details.Hint)+ }+ if strings.Contains(refusal.Details.Remedy, "--grant") {+ t.Errorf("the admin refusal prescribes a grant (%q); no grant reaches an admin route", refusal.Details.Remedy)+ }+}++// A mistyped grant is refused at the door with the vocabulary, and no session is+// created — a half-applied scope would be worse than none.+func TestAnUnknownGrantIsRefusedAtCreation(t *testing.T) {+ f := newFrontDoor(t, nil)++ w, _ := f.createSessionWithGrants(t, []string{"brows"})+ if w.Code != http.StatusBadRequest {+ t.Fatalf("status = %d, want 400: %s", w.Code, w.Body.String())+ }+ if !strings.Contains(w.Body.String(), "brows") || !strings.Contains(w.Body.String(), "browse") {+ t.Errorf("the refusal does not name the offender and the vocabulary: %s", w.Body.String())+ }+}++// The store already round-tripped Grants; with an ingress that is finally+// checkable. A scope that evaporated on restart would be a security control that+// silently widens.+func TestGrantsSurviveARestart(t *testing.T) {+ dir := t.TempDir()+ path := dir + "/sessions.json"+ cfg := session.Config{Enabled: true, IdleTimeout: 30 * time.Minute, MaxLifetime: 24 * time.Hour, PersistPath: path}++ before := session.NewStore(cfg)+ id, _, err := before.Create("grant-test", "", "")+ if err != nil {+ t.Fatal(err)+ }+ if !before.SetGrants(id, []string{session.GrantBrowse, session.GrantNetwork}) {+ t.Fatal("the session vanished before it could be scoped")+ }+ if _, err := os.Stat(path); err != nil {+ t.Fatalf("nothing was persisted (%v), so the reload below would prove nothing", err)+ }++ after := session.NewStore(cfg)+ reloaded, ok := after.Get(id)+ if !ok {+ t.Fatal("the session did not survive the restart")+ }+ if len(reloaded.Grants) != 2 || reloaded.Grants[0] != session.GrantBrowse || reloaded.Grants[1] != session.GrantNetwork {+ t.Errorf("grants after restart = %v, want the pair set before it", reloaded.Grants)+ }+}diff --git a/internal/server/front_door_live_config_test.go b/internal/server/front_door_live_config_test.goindex 681428db..c7031de2 100644--- a/internal/server/front_door_live_config_test.go+++ b/internal/server/front_door_live_config_test.go@@ -69,6 +69,11 @@ func newFrontDoor(t *testing.T, boot func(*config.FileConfig)) frontDoor {mux.HandleFunc("/tabs", func(w http.ResponseWriter, _ *http.Request) {_, _ = w.Write([]byte(`{"tabs":[]}`))})+ // A second route in a different grant group, so a scoped session can be shown+ // reaching one and refused the other through the real chain.+ mux.HandleFunc("/clipboard/read", func(w http.ResponseWriter, _ *http.Request) {+ _, _ = w.Write([]byte(`{"text":""}`))+ })api.RegisterHandlers(mux)if agentSessions.Enabled() {dashboard.NewSessionAPI(agentSessions, cfg.BrowsersAvailable).RegisterHandlers(mux)diff --git a/internal/session/grants.go b/internal/session/grants.gonew file mode 100644index 00000000..9e6e8533--- /dev/null+++ b/internal/session/grants.go@@ -0,0 +1,80 @@+package session++import (+ "fmt"+ "slices"+ "strings"+)++// The grant names a session may hold. This is the ONE definition, beside the+// route list and for the same reason: the middleware's per-grant matchers and the+// API's validator both derive from it, so a twelfth grant cannot be enforceable+// but unsettable, or settable but unenforced — which is exactly how eleven+// matchers came to exist behind a field nothing could write.+const (+ GrantBrowse = "browse"+ GrantNetwork = "network"+ GrantMedia = "media"+ GrantCookies = "cookies"+ GrantClipboard = "clipboard"+ GrantEvaluate = "evaluate"+ GrantStorage = "storage"+ GrantConsole = "console"+ GrantSolve = "solve"+ GrantTasks = "tasks"+ GrantActivity = "activity"++ // GrantAll is the explicit spelling of "no narrowing", accepted so a caller+ // can say it rather than having to omit the field. It means what an empty+ // grant list means, and it is not a matcher: nothing enforces it, because+ // there is nothing to narrow.+ GrantAll = "*"+)++var grantNames = []string{+ GrantBrowse,+ GrantNetwork,+ GrantMedia,+ GrantCookies,+ GrantClipboard,+ GrantEvaluate,+ GrantStorage,+ GrantConsole,+ GrantSolve,+ GrantTasks,+ GrantActivity,+}++// GrantNames returns the grants that narrow a session, in a stable order. The+// copy is deliberate: a caller that mutated the slice would change what one+// process enforces without changing what it accepts.+func GrantNames() []string { return slices.Clone(grantNames) }++// NormalizeGrant is how a grant name is read everywhere: case folded and+// trimmed, so a capitalised grant scopes the session rather than silently+// matching no route at all.+func NormalizeGrant(grant string) string {+ return strings.ToLower(strings.TrimSpace(grant))+}++// ValidateGrants normalizes a requested grant list and refuses an unknown name.+// Refusing is the point: a mistyped grant that is dropped silently produces a+// session the caller believes is scoped and which is not, which is a worse+// outcome than the request failing.+func ValidateGrants(grants []string) ([]string, error) {+ out := make([]string, 0, len(grants))+ for _, raw := range grants {+ grant := NormalizeGrant(raw)+ if grant == "" {+ continue+ }+ if grant != GrantAll && !slices.Contains(grantNames, grant) {+ return nil, fmt.Errorf("unknown grant %q (valid grants: %s, or %q for all)",+ raw, strings.Join(grantNames, ", "), GrantAll)+ }+ if !slices.Contains(out, grant) {+ out = append(out, grant)+ }+ }+ return out, nil+}diff --git a/internal/session/grants_test.go b/internal/session/grants_test.gonew file mode 100644index 00000000..a70305a4--- /dev/null+++ b/internal/session/grants_test.go@@ -0,0 +1,56 @@+package session++import (+ "slices"+ "strings"+ "testing"+)++// A mistyped grant that is dropped silently produces a session the caller believes+// is scoped and which is not — the failure mode this whole card exists to end, one+// layer up from the field that could not be written at all.+func TestValidateGrantsRefusesAnUnknownName(t *testing.T) {+ if _, err := ValidateGrants([]string{"browse", "brows"}); err == nil {+ t.Fatal("a mistyped grant was accepted; the session would look scoped and be unscoped")+ } else {+ for _, want := range []string{"brows", "browse", "activity"} {+ if !strings.Contains(err.Error(), want) {+ t.Errorf("the refusal %q does not carry %q — it must name the offender and the whole vocabulary", err, want)+ }+ }+ }+}++// Case and surrounding space are read the way every other vocabulary here is read,+// so a capitalised grant scopes the session rather than matching no route at all.+func TestValidateGrantsNormalizesAndDeduplicates(t *testing.T) {+ got, err := ValidateGrants([]string{" Browse ", "BROWSE", "", "network"})+ if err != nil {+ t.Fatal(err)+ }+ if !slices.Equal(got, []string{GrantBrowse, GrantNetwork}) {+ t.Errorf("ValidateGrants = %v, want the normalized pair once each", got)+ }+}++// "*" is the explicit spelling of "no narrowing" and must stay settable: the+// middleware already reads it, so refusing it here would make the two disagree.+func TestValidateGrantsAcceptsTheAllWildcard(t *testing.T) {+ got, err := ValidateGrants([]string{GrantAll})+ if err != nil || !slices.Equal(got, []string{GrantAll}) {+ t.Fatalf("ValidateGrants(*) = %v, %v", got, err)+ }+}++// The copy is the point: a caller that mutated the returned slice would change+// what one process enforces without changing what it accepts.+func TestGrantNamesHandsOutACopy(t *testing.T) {+ names := GrantNames()+ if len(names) == 0 {+ t.Fatal("no grant names")+ }+ names[0] = "mutated"+ if GrantNames()[0] == "mutated" {+ t.Error("GrantNames returns the backing array; one caller could rewrite the vocabulary")+ }+}