Skip to content

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

fix: session revoke rejects the token create returns, with a bare 404 that never mentions the session id is a different value (PIN-108)

Luigi Agosti73fef0d376ff
diff --git a/cmd/pinchtab/cmd_session.go b/cmd/pinchtab/cmd_session.go
index 7682fa8c..cbf34fa0 100644
--- a/cmd/pinchtab/cmd_session.go
+++ b/cmd/pinchtab/cmd_session.go
@@ -11,6 +11,24 @@ import (
"github.com/spf13/cobra"
)
+type sessionCreateResult struct {
+ ID string `json:"id"`
+ Token string `json:"sessionToken"`
+ Status string `json:"status"`
+}
+
+// printSessionCreated splits the two values by stream on purpose. The token is the only
+// thing on stdout, because the documented usage captures it with $(...). The id goes to
+// stderr as a hint: it is the handle `session revoke` takes, and withholding it is why
+// revoking your own session used to need a list-and-correlate detour through
+// `session list`.
+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)
+ }
+}
+
func init() {
sessionCmd := &cobra.Command{
Use: "session",
@@ -76,10 +94,7 @@ func init() {
if statusCode >= 400 {
apiclient.ExitWithAPIError(statusCode, rawBody)
}
- var result struct {
- Token string `json:"sessionToken"`
- Status string `json:"status"`
- }
+ var result sessionCreateResult
if err := json.Unmarshal(rawBody, &result); err != nil {
fmt.Fprintf(os.Stderr, "Error: failed to parse session response\n")
os.Exit(1)
@@ -89,7 +104,7 @@ func init() {
output.Hint("create a new session: pinchtab session create --agent-id <id>")
os.Exit(1)
}
- fmt.Println(result.Token)
+ printSessionCreated(result)
})
},
}
diff --git a/cmd/pinchtab/cmd_session_test.go b/cmd/pinchtab/cmd_session_test.go
index 5cbce491..ae922ad0 100644
--- a/cmd/pinchtab/cmd_session_test.go
+++ b/cmd/pinchtab/cmd_session_test.go
@@ -180,3 +180,37 @@ func TestSessionCLI_Info_SendsSessionAuthHeader(t *testing.T) {
t.Fatalf("Authorization = %q, want %q", gotAuth, "Session "+sessionToken)
}
}
+
+// `session create` is documented as `export PINCHTAB_SESSION=$(pinchtab session create
+// ...)`, so stdout must stay the token alone — anything else lands in the variable. The
+// id is the handle `session revoke` takes, so it goes to stderr where the capture cannot
+// swallow it: withholding it is what forced a list-and-correlate detour.
+func TestSessionCreatePrintsTheTokenOnStdoutAndTheIDOnStderr(t *testing.T) {
+ stdout, stderr := captureStdoutStderr(t, func() {
+ printSessionCreated(sessionCreateResult{ID: "ses_0123456789abcdef", Token: "ses_thetoken", Status: "active"})
+ })
+
+ if stdout != "ses_thetoken\n" {
+ t.Errorf("stdout = %q, want the token alone; $(...) captures this", stdout)
+ }
+ if !strings.Contains(stderr, "ses_0123456789abcdef") {
+ t.Errorf("stderr = %q, want the session id", stderr)
+ }
+ if !strings.Contains(stderr, "session revoke") {
+ t.Errorf("stderr = %q, want it to name the verb the id is for", stderr)
+ }
+}
+
+// A response without an id gets no hint rather than a hint naming nothing.
+func TestSessionCreateSaysNothingExtraWithoutAnID(t *testing.T) {
+ stdout, stderr := captureStdoutStderr(t, func() {
+ printSessionCreated(sessionCreateResult{Token: "ses_thetoken", Status: "active"})
+ })
+
+ if stdout != "ses_thetoken\n" {
+ t.Errorf("stdout = %q, want the token alone", stdout)
+ }
+ if stderr != "" {
+ t.Errorf("stderr = %q, want nothing when the response carries no id", stderr)
+ }
+}
diff --git a/internal/dashboard/agent_session_api.go b/internal/dashboard/agent_session_api.go
index ad5f69ce..c5bd63ea 100644
--- a/internal/dashboard/agent_session_api.go
+++ b/internal/dashboard/agent_session_api.go
@@ -106,12 +106,41 @@ func (a *SessionAPI) handleGet(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
sess, ok := a.store.Get(id)
if !ok {
- httpx.ErrorCode(w, http.StatusNotFound, "session_not_found", "session not found", false, nil)
+ respondSessionNotFound(w, id)
return
}
httpx.JSON(w, http.StatusOK, sess)
}
+// tokenSuppliedForIDDetails explains the one mistake these endpoints cannot otherwise
+// explain: `session create` hands the caller a TOKEN and every id-taking endpoint here
+// rejects it, so the refusal reads as already-gone and the likely next action is to
+// shrug and leave a live session running. The two values are distinguishable exactly,
+// so the refusal names which one arrived rather than guessing.
+//
+// callerSessionID is the id of the session the request is authenticated AS, when it is
+// authenticated as one at all. Handing that back is safe — the caller already holds
+// that session's secret — and it is the whole remedy, so they need no second command.
+// Returns nil for anything that is not a token, leaving the plain refusal alone.
+func tokenSuppliedForIDDetails(supplied, callerSessionID string) map[string]any {
+ if !session.LooksLikeToken(supplied) {
+ return nil
+ }
+ remedy := "pinchtab session info (with PINCHTAB_SESSION set) prints the id, or pinchtab session list"
+ if callerSessionID != "" {
+ remedy = "pinchtab session revoke " + callerSessionID
+ }
+ return map[string]any{
+ "hint": "that is a session TOKEN, not a session id — these endpoints take the id so an operator can end a session without holding its secret",
+ "remedy": remedy,
+ }
+}
+
+func respondSessionNotFound(w http.ResponseWriter, supplied string) {
+ httpx.ErrorCode(w, http.StatusNotFound, "session_not_found", "session not found", false,
+ tokenSuppliedForIDDetails(supplied, ""))
+}
+
func (a *SessionAPI) handleMe(w http.ResponseWriter, r *http.Request) {
creds := authn.CredentialsFromRequest(r)
if creds.Method != authn.MethodSession {
@@ -137,7 +166,12 @@ func (a *SessionAPI) handleRevoke(w http.ResponseWriter, r *http.Request) {
return
}
if sess.ID != id {
- httpx.ErrorCode(w, http.StatusForbidden, "forbidden", "session callers may only revoke their own session", false, nil)
+ // The path a caller following the product's own instructions takes: with
+ // PINCHTAB_SESSION exported, revoking "$PINCHTAB_SESSION" lands HERE rather
+ // than on the 404, and "may only revoke their own session" is then actively
+ // misleading — this IS their own session, named by the wrong value.
+ httpx.ErrorCode(w, http.StatusForbidden, "forbidden", "session callers may only revoke their own session", false,
+ tokenSuppliedForIDDetails(id, sess.ID))
return
}
case authn.MethodHeader, authn.MethodCookie:
@@ -151,7 +185,7 @@ func (a *SessionAPI) handleRevoke(w http.ResponseWriter, r *http.Request) {
remainingTabIDs = append(remainingTabIDs, a.sessionTabIDs(id)...)
}
if !a.store.Revoke(id) {
- httpx.ErrorCode(w, http.StatusNotFound, "session_not_found", "session not found", false, nil)
+ respondSessionNotFound(w, id)
return
}
httpx.JSON(w, http.StatusOK, map[string]any{
diff --git a/internal/dashboard/agent_session_api_test.go b/internal/dashboard/agent_session_api_test.go
index 56a159dc..1c03af48 100644
--- a/internal/dashboard/agent_session_api_test.go
+++ b/internal/dashboard/agent_session_api_test.go
@@ -288,6 +288,121 @@ func TestAgentSessionAPI_Revoke_NotFound(t *testing.T) {
}
}
+// The defect this covers: `session create` returns a token, every id-taking endpoint
+// here rejects it, and the refusal said only "session not found" — which reads as
+// already-gone, so the caller shrugs and leaves a live session running. Both id-taking
+// endpoints are covered, because the same value reaches both by the same mistake.
+func TestSupplyingATokenWhereAnIDGoesExplainsTheDifference(t *testing.T) {
+ store := newTestSessionStore()
+ mux := newTestSessionMux(store)
+
+ _, token, _ := store.Create("agent-1", "", "")
+
+ for _, tc := range []struct {
+ name string
+ req *http.Request
+ }{
+ {"revoke", httptest.NewRequest("POST", "/sessions/"+token+"/revoke", nil)},
+ {"get", httptest.NewRequest("GET", "/sessions/"+token, nil)},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ tc.req.Header.Set("Authorization", "Bearer dashboard-token")
+ w := httptest.NewRecorder()
+ mux.ServeHTTP(w, tc.req)
+
+ if w.Code != http.StatusNotFound {
+ t.Fatalf("status = %d, want %d", w.Code, http.StatusNotFound)
+ }
+ details := errorDetails(t, w)
+ if !strings.Contains(details["hint"], "TOKEN") || !strings.Contains(details["hint"], "not a session id") {
+ t.Errorf("hint does not name the id/token distinction: %q", details["hint"])
+ }
+ for _, want := range []string{"session info", "session list"} {
+ if !strings.Contains(details["remedy"], want) {
+ t.Errorf("remedy %q does not point at %q, so the id is unreachable without already knowing it", details["remedy"], want)
+ }
+ }
+ })
+ }
+}
+
+// The path a caller following the product's own instructions actually takes: with
+// PINCHTAB_SESSION exported, revoking "$PINCHTAB_SESSION" authenticates AS that session
+// and lands on the 403, whose message — "may only revoke their own session" — is
+// actively misleading, because this IS their own session named by the wrong value. The
+// caller already holds this session's secret, so the remedy can hand them the id itself.
+func TestRevokingYourOwnSessionByTokenNamesYourID(t *testing.T) {
+ store := newTestSessionStore()
+ mux := newTestSessionMux(store)
+
+ id, token, _ := store.Create("agent-1", "", "")
+ sess, ok := store.Get(id)
+ if !ok || sess == nil {
+ t.Fatal("expected session to exist")
+ }
+
+ req := httptest.NewRequest("POST", "/sessions/"+token+"/revoke", nil)
+ req.Header.Set("Authorization", "Session "+token)
+ req = session.WithSession(req, sess)
+ w := httptest.NewRecorder()
+ mux.ServeHTTP(w, req)
+
+ if w.Code != http.StatusForbidden {
+ t.Fatalf("status = %d, want %d", w.Code, http.StatusForbidden)
+ }
+ details := errorDetails(t, w)
+ if !strings.Contains(details["hint"], "TOKEN") {
+ t.Errorf("hint does not name the id/token distinction: %q", details["hint"])
+ }
+ if want := "pinchtab session revoke " + id; details["remedy"] != want {
+ t.Errorf("remedy = %q, want %q — the caller holds this session's secret, so the id is the whole remedy", details["remedy"], want)
+ }
+ if strings.Contains(details["remedy"], token) {
+ t.Error("the remedy repeats the token, which is the value that does not work here")
+ }
+}
+
+// An unknown ID keeps the plain refusal. The hint claims the caller supplied a token,
+// so offering it for anything else would be a guess — and a wrong one for the ordinary
+// case of a session that really is gone.
+func TestAnUnknownIDGetsNoTokenHint(t *testing.T) {
+ store := newTestSessionStore()
+ mux := newTestSessionMux(store)
+
+ // Shaped like an id the store could have minted, but never minted — a session that
+ // really is gone, which is the case the bare refusal is right for.
+ const id = "ses_0123456789abcdef"
+ if !session.LooksLikeID(id) || session.LooksLikeToken(id) {
+ t.Fatalf("precondition: %q must read as an id, or this proves nothing", id)
+ }
+
+ req := httptest.NewRequest("POST", "/sessions/"+id+"/revoke", nil)
+ req.Header.Set("Authorization", "Bearer dashboard-token")
+ w := httptest.NewRecorder()
+ mux.ServeHTTP(w, req)
+
+ if w.Code != http.StatusNotFound {
+ t.Fatalf("status = %d, want %d", w.Code, http.StatusNotFound)
+ }
+ if _, ok := decodeSessionResponse(t, w)["details"]; ok {
+ t.Error("an already-revoked session id was told it had supplied a token")
+ }
+}
+
+func errorDetails(t *testing.T, w *httptest.ResponseRecorder) map[string]string {
+ t.Helper()
+ raw, ok := decodeSessionResponse(t, w)["details"].(map[string]any)
+ if !ok {
+ t.Fatal("the refusal carries no details, so it explains nothing")
+ }
+ out := map[string]string{}
+ for key, value := range raw {
+ text, _ := value.(string)
+ out[key] = text
+ }
+ return out
+}
+
func TestAgentSessionAPI_Revoke_SessionOwnerAllowed(t *testing.T) {
store := newTestSessionStore()
mux := newTestSessionMux(store)
diff --git a/internal/session/identifiers.go b/internal/session/identifiers.go
new file mode 100644
index 00000000..88eeedac
--- /dev/null
+++ b/internal/session/identifiers.go
@@ -0,0 +1,44 @@
+package session
+
+import "strings"
+
+// IDPrefix marks both values this package mints. They share it because they are both
+// session-scoped, which is also why one reads like the other to a caller holding only
+// the token.
+const IDPrefix = "ses_"
+
+// The two random widths. An id is a HANDLE — safe to name in a revoke request, in a log
+// line, in a dashboard URL. A token is a CREDENTIAL. The split is deliberate: revoking
+// by id lets an operator end another agent's session without possessing its secret.
+const (
+ idRandomBytes = 8
+ tokenRandomBytes = 24
+)
+
+// LooksLikeID and LooksLikeToken tell the two apart EXACTLY rather than heuristically:
+// both are the prefix plus a fixed number of hex characters, sized here from the same
+// constants the generators read, and the two widths do not overlap. A caller that
+// changes a width without changing these has a test to answer to — a hint that names
+// the wrong kind of value is worse than the bare "not found" it replaces.
+func LooksLikeID(value string) bool {
+ return isPrefixedHex(value, idRandomBytes*2)
+}
+
+func LooksLikeToken(value string) bool {
+ return isPrefixedHex(value, tokenRandomBytes*2)
+}
+
+func isPrefixedHex(value string, hexLen int) bool {
+ rest, ok := strings.CutPrefix(strings.TrimSpace(value), IDPrefix)
+ if !ok || len(rest) != hexLen {
+ return false
+ }
+ for _, r := range rest {
+ switch {
+ case r >= '0' && r <= '9', r >= 'a' && r <= 'f':
+ default:
+ return false
+ }
+ }
+ return true
+}
diff --git a/internal/session/identifiers_test.go b/internal/session/identifiers_test.go
new file mode 100644
index 00000000..d5d10cf9
--- /dev/null
+++ b/internal/session/identifiers_test.go
@@ -0,0 +1,77 @@
+package session
+
+import "testing"
+
+// The predicates are only worth anything if they match what the generators actually
+// mint: a hint that names the wrong kind of value is worse than the bare "not found" it
+// replaces. Driven from the generators rather than from literals, so changing a random
+// width reds here instead of quietly corrupting the hint.
+func TestThePredicatesMatchWhatTheGeneratorsMint(t *testing.T) {
+ id, err := generateSessionID()
+ if err != nil {
+ t.Fatal(err)
+ }
+ token, err := generateToken()
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ if !LooksLikeID(id) {
+ t.Errorf("LooksLikeID(%q) = false for a generated session id", id)
+ }
+ if !LooksLikeToken(token) {
+ t.Errorf("LooksLikeToken(%q) = false for a generated token", token)
+ }
+ if LooksLikeToken(id) {
+ t.Errorf("LooksLikeToken(%q) = true for a session id; the hint would name the wrong value", id)
+ }
+ if LooksLikeID(token) {
+ t.Errorf("LooksLikeID(%q) = true for a token; the hint would name the wrong value", token)
+ }
+ if len(id) == len(token) {
+ t.Fatalf("id and token are both %d characters, so nothing can tell them apart", len(id))
+ }
+}
+
+// Neither predicate may guess. Everything that is not exactly the prefix plus its own
+// width of lowercase hex is neither, so an unknown id keeps the plain refusal.
+func TestNeitherPredicateMatchesAnythingElse(t *testing.T) {
+ id, _ := generateSessionID()
+ token, _ := generateToken()
+
+ for _, value := range []string{
+ "",
+ IDPrefix,
+ "ses_notevenhex11",
+ "ses_" + "0123456789abcde", // one short of an id
+ "ses_" + "0123456789abcdef0", // one over
+ id + "0",
+ token[:len(token)-1],
+ "tok_0123456789abcdef",
+ id[len(IDPrefix):], // right width, no prefix
+ "SES_0123456789ABCDEF", // uppercase: not what the generators emit
+ "ses_0123456789ABCDEF", // uppercase hex
+ "ses_0123456789abcdef ses_0123456789", // two values
+ } {
+ if LooksLikeID(value) {
+ t.Errorf("LooksLikeID(%q) = true", value)
+ }
+ if LooksLikeToken(value) {
+ t.Errorf("LooksLikeToken(%q) = true", value)
+ }
+ }
+}
+
+// Surrounding whitespace comes from a shell or a copy-paste, not from a different kind
+// of value, so it must not turn a token into "neither" and cost the caller the hint.
+func TestSurroundingWhitespaceStillIdentifiesTheValue(t *testing.T) {
+ id, _ := generateSessionID()
+ token, _ := generateToken()
+
+ if !LooksLikeID(" " + id + "\n") {
+ t.Error("a padded session id is no longer recognised")
+ }
+ if !LooksLikeToken("\t" + token + " ") {
+ t.Error("a padded token is no longer recognised")
+ }
+}
diff --git a/internal/session/store.go b/internal/session/store.go
index 85236b70..27e00301 100644
--- a/internal/session/store.go
+++ b/internal/session/store.go
@@ -678,19 +678,19 @@ func (s *Store) writeSnapshot(job snapshotJob) {
}
func generateSessionID() (string, error) {
- buf := make([]byte, 8)
- if _, err := rand.Read(buf); err != nil {
- return "", err
- }
- return "ses_" + hex.EncodeToString(buf), nil
+ return generatePrefixedHex(idRandomBytes)
}
func generateToken() (string, error) {
- buf := make([]byte, 24)
+ return generatePrefixedHex(tokenRandomBytes)
+}
+
+func generatePrefixedHex(size int) (string, error) {
+ buf := make([]byte, size)
if _, err := rand.Read(buf); err != nil {
return "", err
}
- return "ses_" + hex.EncodeToString(buf), nil
+ return IDPrefix + hex.EncodeToString(buf), nil
}
func hashToken(token string) [32]byte {