Skip to content

High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.

fix(session): refuse a grant entry that names nothing, at the API and at the flag, and test the CLI ingress (PIN-272)

Luigi Agosti8a4a1ab3faa4
diff --git a/cmd/pinchtab/capability_remedy_executable_test.go b/cmd/pinchtab/capability_remedy_executable_test.go
index b92d5170..e59bdc01 100644
--- a/cmd/pinchtab/capability_remedy_executable_test.go
+++ b/cmd/pinchtab/capability_remedy_executable_test.go
@@ -119,8 +119,10 @@ func assertRemedyRuns(t *testing.T, line string) {
}
// A flag the resolved command does not define is the same dead end as a missing
// verb, and it is the likelier one: a remedy naming --wait-nav outlives a rename.
+ // The name is cut at "=" the way remedyFlagTakesAValue cuts it, or the day a
+ // remedy is written --flag=value this reports the flag as undefined.
for _, flag := range flags {
- name := strings.TrimLeft(flag, "-")
+ name, _, _ := strings.Cut(strings.TrimLeft(flag, "-"), "=")
if found.Flags().Lookup(name) == nil && found.InheritedFlags().Lookup(name) == nil {
t.Errorf("remedy command %v names flag %q, which %q does not define", words, flag, found.CommandPath())
}
@@ -172,6 +174,19 @@ func TestTheRemedyGuardRedsOnACommandThatCannotRun(t *testing.T) {
}
}
+// The joined flag form, which no remedy uses today and which the undefined-flag check
+// would have reported as undefined: the name has to be cut at "=" or every --flag=value
+// reads as a flag the command never defined. This is a POSITIVE shape on purpose — the
+// broken version reds a line that runs, and a reds-list row cannot see that, since an
+// undefined flag is reported either way.
+func TestTheRemedyGuardAcceptsADefinedFlagWrittenWithAnEquals(t *testing.T) {
+ fake := &testing.T{}
+ assertRemedyRuns(fake, "pinchtab session create --agent-id=a")
+ if fake.Failed() {
+ t.Error("the guard rejects `pinchtab session create --agent-id=a`, a line that runs; a remedy written in the joined form would be unpublishable")
+ }
+}
+
// The other half of executable: `config set <path> true` is only real if the
// config editor accepts that path. A setting present in the schema but missing
// from the editor's field table dead-ends every message that cites it.
diff --git a/cmd/pinchtab/cmd_session.go b/cmd/pinchtab/cmd_session.go
index 0cc6c17d..c5c403dc 100644
--- a/cmd/pinchtab/cmd_session.go
+++ b/cmd/pinchtab/cmd_session.go
@@ -15,9 +15,10 @@ import (
)
type sessionCreateResult struct {
- ID string `json:"id"`
- Token string `json:"sessionToken"`
- Status string `json:"status"`
+ ID string `json:"id"`
+ Token string `json:"sessionToken"`
+ Status string `json:"status"`
+ Grants []string `json:"grants,omitempty"`
}
// printSessionCreated splits the two values by stream on purpose. The token is the only
@@ -28,10 +29,22 @@ type sessionCreateResult struct {
func printSessionCreated(result sessionCreateResult) {
fmt.Println(result.Token)
if result.ID != "" {
- output.Hint("session id " + result.ID + " — revoke takes the id: pinchtab session revoke " + result.ID)
+ output.Hint("session id " + result.ID + " " + sessionScopeSummary(result.Grants) +
+ " — revoke takes the id: pinchtab session revoke " + result.ID)
}
}
+// sessionScopeSummary renders the scope the SERVER applied, read back from the create
+// response rather than from the flags, so a request whose grants did not take effect is
+// visible at the surface a human uses. Without it the one output that most needs the echo
+// — the default, non-JSON create — printed the token and nothing about scope at all.
+func sessionScopeSummary(grants []string) string {
+ if len(grants) == 0 {
+ return "(unscoped: reaches every non-admin route)"
+ }
+ return "(grants: " + strings.Join(grants, ", ") + ")"
+}
+
func init() {
sessionCmd := &cobra.Command{
Use: "session",
@@ -77,6 +90,15 @@ func init() {
fmt.Fprintln(os.Stderr, "Error: --agent-id is required")
os.Exit(1)
}
+ // pflag parses an empty --grant value into an EMPTY slice, so the entry
+ // that names nothing never reaches the validator and the flag reads as
+ // absent: `--grant ""` exited 0 with a session that reaches every
+ // non-admin route. Changed() is what tells the two apart, and the empty
+ // name is handed to the one owner rather than a second refusal message
+ // being written here.
+ if cmd.Flags().Changed("grant") && len(grants) == 0 {
+ grants = []string{""}
+ }
// 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)
diff --git a/cmd/pinchtab/cmd_session_grants_test.go b/cmd/pinchtab/cmd_session_grants_test.go
new file mode 100644
index 00000000..ed4b81ab
--- /dev/null
+++ b/cmd/pinchtab/cmd_session_grants_test.go
@@ -0,0 +1,170 @@
+package main
+
+import (
+ "encoding/json"
+ "errors"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "os/exec"
+ "strings"
+ "sync/atomic"
+ "testing"
+)
+
+// The CLI half of the grants ingress, driven through the REAL command tree in a child
+// process, because that is the only way the repeatable flag, the local validation and the
+// os.Exit are all the shipped ones. A test that calls apiclient directly — which is what
+// the create tests beside this one do — proves the server contract and says nothing about
+// whether --grant reaches it.
+func runSessionCreateCLI(t *testing.T, args ...string) (string, int, int32) {
+ t.Helper()
+
+ if os.Getenv("PINCHTAB_GRANT_HELPER") == "1" {
+ rootCmd.SetArgs(append([]string{"--server", os.Getenv("PINCHTAB_GRANT_SERVER")}, strings.Split(os.Getenv("PINCHTAB_GRANT_ARGS"), "\x1f")...))
+ if err := rootCmd.Execute(); err != nil {
+ os.Exit(commandExitCode(err))
+ }
+ os.Exit(0)
+ }
+
+ var requests atomic.Int32
+ var body atomic.Value
+ body.Store("")
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ if r.URL.Path == "/health" {
+ _, _ = w.Write([]byte(`{"status":"ok"}`))
+ return
+ }
+ requests.Add(1)
+ raw, _ := io.ReadAll(r.Body)
+ body.Store(string(raw))
+ // The stub echoes the grants back the way the real API does — from what it
+ // stored, not from a canned literal — so the CLI's scope line is read from a
+ // response rather than from the flags the caller typed.
+ var sent struct {
+ Grants []string `json:"grants"`
+ }
+ _ = json.Unmarshal(raw, &sent)
+ reply := map[string]any{"id": "ses_abc", "sessionToken": "ses_token", "status": "active"}
+ if len(sent.Grants) > 0 {
+ reply["grants"] = sent.Grants
+ }
+ w.WriteHeader(http.StatusCreated)
+ _ = json.NewEncoder(w).Encode(reply)
+ }))
+ t.Cleanup(srv.Close)
+
+ child := exec.Command(os.Args[0], "-test.run=^"+t.Name()+"$", "-test.timeout=60s") // #nosec G204 -- re-executes this test binary with fixed arguments.
+ child.Env = append(os.Environ(),
+ "PINCHTAB_GRANT_HELPER=1",
+ "PINCHTAB_GRANT_SERVER="+srv.URL,
+ "PINCHTAB_GRANT_ARGS="+strings.Join(args, "\x1f"),
+ "PINCHTAB_TOKEN=test-token",
+ "HOME="+t.TempDir(),
+ "XDG_STATE_HOME="+t.TempDir(),
+ )
+ out, err := child.CombinedOutput()
+
+ code := 0
+ var exitErr *exec.ExitError
+ if errors.As(err, &exitErr) {
+ code = exitErr.ExitCode()
+ } else if err != nil {
+ t.Fatalf("running the CLI failed with %v; output:\n%s", err, out)
+ }
+ return string(out) + body.Load().(string), code, requests.Load()
+}
+
+func TestSessionCreateSendsEveryRepeatedGrantToTheAPI(t *testing.T) {
+ out, code, requests := runSessionCreateCLI(t,
+ "session", "create", "--agent-id", "agent-1", "--grant", "browse", "--grant", "console")
+ if os.Getenv("PINCHTAB_GRANT_HELPER") == "1" {
+ return
+ }
+
+ if code != 0 {
+ t.Fatalf("exit code = %d, want 0; output:\n%s", code, out)
+ }
+ if requests != 1 {
+ t.Fatalf("the CLI made %d create requests, want 1", requests)
+ }
+ var sent struct {
+ AgentID string `json:"agentId"`
+ Grants []string `json:"grants"`
+ }
+ payload := out[strings.LastIndex(out, "{"):]
+ if err := json.Unmarshal([]byte(payload), &sent); err != nil {
+ t.Fatalf("the request body is not JSON (%v): %s", err, payload)
+ }
+ if sent.AgentID != "agent-1" {
+ t.Errorf("agentId = %q, want agent-1", sent.AgentID)
+ }
+ if strings.Join(sent.Grants, ",") != "browse,console" {
+ t.Errorf("grants = %v, want both repeats of the flag; a session scoped to fewer groups than asked for is the failure this reports", sent.Grants)
+ }
+ // The echo where a human reads it. The API answers with the grants it applied, so
+ // this is the line that would disagree with the request if the scope had not taken.
+ if !strings.Contains(out, "grants: browse, console") {
+ t.Errorf("the default create output does not report the scope the server applied:\n%s", out)
+ }
+}
+
+// The same disclosure for the session that narrows nothing: silence there would read as
+// "scope unknown" on the very output the scoped case uses to report one.
+func TestSessionCreateReportsAnUnscopedSessionAsUnscoped(t *testing.T) {
+ out, code, _ := runSessionCreateCLI(t, "session", "create", "--agent-id", "agent-1")
+ if os.Getenv("PINCHTAB_GRANT_HELPER") == "1" {
+ return
+ }
+
+ if code != 0 {
+ t.Fatalf("exit code = %d, want 0; output:\n%s", code, out)
+ }
+ if !strings.Contains(out, "unscoped") {
+ t.Errorf("the default create output does not say the session is unscoped:\n%s", out)
+ }
+}
+
+// The local validation the flag's help promises: a typo must cost no round trip, and the
+// message must name the offender and the whole vocabulary, because the caller cannot guess
+// eleven names from a rejection.
+func TestSessionCreateRefusesAMistypedGrantBeforeTheWire(t *testing.T) {
+ out, code, requests := runSessionCreateCLI(t,
+ "session", "create", "--agent-id", "agent-1", "--grant", "brows")
+ if os.Getenv("PINCHTAB_GRANT_HELPER") == "1" {
+ return
+ }
+
+ if code != 1 {
+ t.Fatalf("exit code = %d, want 1; output:\n%s", code, out)
+ }
+ if requests != 0 {
+ t.Errorf("the CLI issued %d request(s) for a grant it could reject locally", requests)
+ }
+ for _, want := range []string{"brows", "browse", "activity"} {
+ if !strings.Contains(out, want) {
+ t.Errorf("the refusal does not carry %q — it must name the offender and the whole vocabulary:\n%s", want, out)
+ }
+ }
+}
+
+// An entry naming nothing, at the surface a human types it on. Before the refusal existed
+// this exited 0 with an UNSCOPED session, which is the outcome the caller was trying to
+// avoid by passing the flag at all.
+func TestSessionCreateRefusesAGrantThatNamesNothing(t *testing.T) {
+ out, code, requests := runSessionCreateCLI(t,
+ "session", "create", "--agent-id", "agent-1", "--grant", "")
+ if os.Getenv("PINCHTAB_GRANT_HELPER") == "1" {
+ return
+ }
+
+ if code != 1 {
+ t.Fatalf("exit code = %d, want 1; an empty --grant created a session that reaches every non-admin route:\n%s", code, out)
+ }
+ if requests != 0 {
+ t.Errorf("the CLI issued %d request(s) for an empty grant", requests)
+ }
+}
diff --git a/internal/session/grants.go b/internal/session/grants.go
index 9e6e8533..52a58fe6 100644
--- a/internal/session/grants.go
+++ b/internal/session/grants.go
@@ -57,18 +57,21 @@ 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.
+// ValidateGrants normalizes a requested grant list and refuses any entry that is
+// not a grant. 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.
+//
+// An entry naming NOTHING is refused for that same reason and not skipped. An
+// absent field and an empty list both mean "do not narrow", which is a caller
+// saying nothing about grants; "" inside the list is a caller who asked to be
+// scoped and named no scope, and dropping it silently hands back the unscoped
+// session they were trying not to create.
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) {
+ if grant == "" || (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)
}
diff --git a/internal/session/grants_test.go b/internal/session/grants_test.go
index a70305a4..cb44279d 100644
--- a/internal/session/grants_test.go
+++ b/internal/session/grants_test.go
@@ -23,8 +23,11 @@ func TestValidateGrantsRefusesAnUnknownName(t *testing.T) {
// 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.
+// The empty entry this list used to carry moved to the refusal test below: it was
+// dropped silently here, which is the accept-and-discard shape this whole card
+// exists to remove.
func TestValidateGrantsNormalizesAndDeduplicates(t *testing.T) {
- got, err := ValidateGrants([]string{" Browse ", "BROWSE", "", "network"})
+ got, err := ValidateGrants([]string{" Browse ", "BROWSE", "network"})
if err != nil {
t.Fatal(err)
}
@@ -33,6 +36,35 @@ func TestValidateGrantsNormalizesAndDeduplicates(t *testing.T) {
}
}
+// An entry that names nothing is the quiet half of the same defect: skipping it
+// answered 201 with a session that reaches every non-admin route, for a caller who
+// asked to be scoped. Saying nothing about grants is still allowed — that is the
+// absent field and the empty list, both of which mean "do not narrow".
+func TestValidateGrantsRefusesAnEntryThatNamesNothing(t *testing.T) {
+ for _, entry := range []string{"", " ", "\t"} {
+ got, err := ValidateGrants([]string{entry})
+ if err == nil {
+ t.Errorf("ValidateGrants([%q]) = %v, nil; an entry naming no grant produced an UNSCOPED session with no refusal", entry, got)
+ continue
+ }
+ if !strings.Contains(err.Error(), "browse") {
+ t.Errorf("the refusal %q does not name the vocabulary", err)
+ }
+ }
+ for _, entry := range []string{"", " "} {
+ if _, err := ValidateGrants([]string{entry, GrantBrowse}); err == nil {
+ t.Errorf("ValidateGrants([%q, browse]) was accepted; one good name must not excuse an empty one", entry)
+ }
+ }
+
+ for name, grants := range map[string][]string{"absent": nil, "empty list": {}} {
+ got, err := ValidateGrants(grants)
+ if err != nil || len(got) != 0 {
+ t.Errorf("%s grants = %v, %v; want the unscoped session, which is what saying nothing means", name, got, err)
+ }
+ }
+}
+
// "*" 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) {