permbridge

package
v0.41.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 17, 2026 License: MIT Imports: 6 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package permbridge is an in-memory registry of pending tool-approval requests for the Streamrunner interactive permission bridge. A non-YOLO headless claude spawned with --permission-prompt-tool synchronously blocks on a registered MCP tool's allow/deny JSON for the full duration of a pending approval, so a parked request is real owed-silence of unbounded length. The registry parks such a request under an opaque id, hands the blocked caller a Pending completer to Await, and lets a resolver satisfy it with an allow or deny Verdict.

Fail-closed is the security-critical core: allow is reachable only through an explicit Resolve(id, Allow(...)) that wins the one-shot; every other terminal path — a window that elapses with nobody able to answer, a lost caller, an unknown id — yields deny. Each entry arms a registry-owned window that resolves it to deny, and the window is spent only on approvals nobody can answer: an AnswerableFunc installed with SetAnswerable may report that somebody is still able to answer the approval, which buys exactly one more window and is re-asked at every expiry, so no entry outlives a window that reads unanswerable. With no report installed — the default — the window is the hard deadline it has always been. No allow can ever land after a deny.

The registry therefore trusts two inputs: its caller (see Resolve), and the injected report's honesty about whether anybody is still waiting.

The package is self-contained: it imports only the standard library and nothing from internal/, so no import cycle is possible (contrast modalbridge, which must document a relay-import hazard). It is also log-free — a pure data structure that emits nothing, so it cannot leak a Request's input, an id, or a deny message into logs; content-free decision logging is the consumer's job (the control-socket verb and the pyry mcp-approve subcommand).

Index

Constants

View Source
const (
	BehaviorAllow = "allow"
	BehaviorDeny  = "deny"
)

Behavior discriminants claude accepts on a verdict (T1 spike contract).

Variables

View Source
var ErrDuplicateID = errors.New("permbridge: duplicate or empty approval id")

ErrDuplicateID rejects a Register whose id cannot open a fresh pending slot: an id already live in the registry, or an empty id (not a usable correlation key). Matchable with errors.Is; the caller default-denies. Mapping it to a wire error is the consumer's job.

Functions

This section is empty.

Types

type AlwaysAllow

type AlwaysAllow struct {
	// contains filtered or unexported fields
}

AlwaysAllow is an immutable, validated always-allow offer. Its slices are package-owned; accessors return clones so outstanding modal state cannot be changed by a later caller. It holds either Claude rule updates or a harness session grant (SessionGrant), never both.

func ParseAlwaysAllow

func ParseAlwaysAllow(raw json.RawMessage, suppressed bool) AlwaysAllow

ParseAlwaysAllow validates the rule grants in a bounded Claude-authored suggestion batch. Directory and mode alternatives are omitted, never granted. Any invalid rule grant rejects the whole offer; rules are never truncated.

func SessionGrant added in v0.27.0

func SessionGrant(label string) AlwaysAllow

SessionGrant builds an offer that carries no Claude rule updates: the harness itself remembers the approval for the session when AllowAlways marks the verdict ForSession. label is the one rule the modal shows. An empty label, or one longer than a rendered Claude rule may be, yields no offer, so a grant is never offered without its scope on screen.

func (AlwaysAllow) Offered

func (a AlwaysAllow) Offered() bool

Offered reports whether the value contains a complete validated offer.

func (AlwaysAllow) Rules

func (a AlwaysAllow) Rules() []string

Rules returns rendered display rules in source order.

func (AlwaysAllow) Updates

func (a AlwaysAllow) Updates() []PermissionUpdate

Updates returns a deep copy of the validated updates in source order.

type AnswerableFunc

type AnswerableFunc func(id string, req Request) bool

AnswerableFunc reports whether the exact approval generation parked under id still has somebody able to answer it. req is the immutable request captured by that registration. It is consulted only when a window elapses on a live entry, and a true reading buys exactly one more window before the question is asked again — so it is read as a level, never latched as an edge.

The contract a report must satisfy: answer false once nobody is waiting on this approval. A report that always answers true removes the fail-closed bound entirely, including for a caller that registered and never Awaited.

It is called with no registry lock held and must not panic; the registry has no recovery, and mapping a panic to "not answerable" would make a wiring bug read as every approval silently denying. Guarding a not-yet-wired report is the injection site's job.

type Pending

type Pending struct {
	// contains filtered or unexported fields
}

Pending is the caller's handle on a parked request: block on Await for the verdict.

func (*Pending) Await

func (p *Pending) Await() Verdict

Await blocks until the request is resolved and returns its verdict. With no AnswerableFunc installed — the default — it is guaranteed to return within the Register timeout, because the registry-owned timer always delivers a deny if nothing else resolves the entry first. With one installed the bound is conditional on that report: Await returns within one window of the first reading that says nobody can answer this approval.

type PermissionRule

type PermissionRule struct {
	ToolName    string  `json:"toolName"`
	RuleContent *string `json:"ruleContent,omitempty"`
}

PermissionRule is one validated rule from claude's permission suggestions. RuleContent distinguishes an absent value from a present empty string because the latter renders as toolName().

type PermissionUpdate

type PermissionUpdate struct {
	Type        string           `json:"type"`
	Rules       []PermissionRule `json:"rules"`
	Behavior    string           `json:"behavior"`
	Destination string           `json:"destination,omitempty"`
}

PermissionUpdate is one supported permission suggestion. ParseAlwaysAllow admits only addRules/allow updates, but the discriminants remain explicit for the grant path that will serialize the retained updates back to claude.

type Registry

type Registry struct {
	// contains filtered or unexported fields
}

Registry is the in-memory pending-approval store, keyed by an opaque id (a tool-use id — a correlation key, not a credential). mu protects pending entries and the answerable report, never spanning channel sends or report calls. Diagnostic observation only attempts a nonblocking recorder lock under mu.

func New

func New() *Registry

New returns an empty Registry ready for use, with no AnswerableFunc installed: every window is a hard fail-closed deadline until SetAnswerable says otherwise.

func (*Registry) Lookup

func (r *Registry) Lookup(id string) (Request, bool)

Lookup returns the parked Request for id without resolving it — the read seam #1080 uses to build Allow(req.Input). An unknown id yields (Request{}, false), a safe no-op.

func (*Registry) Register

func (r *Registry) Register(id string, req Request, timeout time.Duration) (*Pending, error)

Register parks req under id, arms the fail-closed deadline, and returns the caller's handle. It rejects an empty id and a duplicate live id with ErrDuplicateID (the caller then default-denies). A non-positive timeout fires the timer ≈immediately, which is safe: the entry simply resolves to deny.

The whole insert — arming the timer and writing the map — happens under mu, so even a 0-duration timer that fires instantly blocks in expire on mu.Lock() until the entry is fully installed: there is no fire-before-install race, and the lock establishes the happens-before for the timer's later Stop.

timeout is a re-check interval rather than a hard deadline whenever an AnswerableFunc is installed: expire re-arms this same window for as long as the report says the approval can still be answered. It stays the only knob — an extension re-arms the duration Register was handed, never a different one.

func (*Registry) Resolve

func (r *Registry) Resolve(id string, v Verdict) bool

Resolve satisfies the pending request id with v and returns true if it resolved a live entry, or false if the id is unknown or already resolved (a safe no-op — AC-4). Delegates to the shared one-shot; the winning caller is the sole writer of the verdict.

func (*Registry) SetAnswerable

func (r *Registry) SetAnswerable(ask AnswerableFunc)

SetAnswerable installs the liveness report, or clears it with nil. It is a setter rather than a New option because a composition root builds the registry long before whatever can answer the question exists; the report is read at expiry, not captured at Register, so calling it while entries are already parked is safe and takes effect on their next window. nil is a meaningful value, not an error — an absent report reads as "nobody can answer", which is the fail-closed direction.

type Request

type Request struct {
	ToolName                string          `json:"tool_name"`
	Input                   json.RawMessage `json:"input"`
	ToolUseID               string          `json:"tool_use_id"`
	DecisionReason          json.RawMessage `json:"decision_reason,omitempty"`
	DecisionReasonType      string          `json:"decision_reason_type,omitempty"`
	BlockedPath             string          `json:"blocked_path,omitempty"`
	Description             string          `json:"description,omitempty"`
	DefaultToNo             bool            `json:"default_to_no,omitempty"`
	RequiresUserInteraction bool            `json:"-"`
	AlwaysAllow             AlwaysAllow     `json:"-"`
	SessionID               string          `json:"-"`
}

Request is the tool-approval request claude sends (T1 spike contract). Input is the opaque tool-input object, carried as json.RawMessage so it round-trips byte-verbatim — an allow echoes it back as Verdict.UpdatedInput. The remaining optional fields are copied only from the corresponding can_use_tool ask fields; they are never derived from Input. RequiresUserInteraction is daemon-internal answer eligibility rather than display data and is therefore excluded from JSON. SessionID is the pool session of the runner that parked the request, set by that runner's handler and excluded from JSON for the same reason; empty means no session is known. None of these fields changes the registry's verdict arbitration.

type Verdict

type Verdict struct {
	Behavior           string          `json:"behavior"`
	UpdatedInput       json.RawMessage `json:"updatedInput,omitempty"`       // allow only
	UpdatedPermissions json.RawMessage `json:"updatedPermissions,omitempty"` // session allow only
	Message            string          `json:"message,omitempty"`            // deny only
	ForSession         bool            `json:"-"`                            // session-grant allow only
}

Verdict is the allow/deny decision claude accepts. The omitempty tags give the two disjoint wire shapes: allow → {"behavior":"allow","updatedInput":{…}} with optional session-scoped updatedPermissions; deny → {"behavior":"deny","message":"…"}. Construct via Allow, AllowAlways, or Deny. ForSession is never on the wire: it marks an allow that accepted a SessionGrant, for a harness that answers in its own vocabulary.

func Allow

func Allow(updatedInput json.RawMessage) Verdict

Allow builds an allow verdict echoing updatedInput (the request's Input, possibly modified by the resolver — a #1080 policy decision).

func AllowAlways

func AllowAlways(updatedInput json.RawMessage, offer AlwaysAllow) Verdict

AllowAlways builds an allow verdict from a daemon-retained validated offer. Every destination is rewritten to session; an unavailable offer preserves the plain allow shape. A SessionGrant keeps the plain allow bytes and sets ForSession. The typed updates contain only strings, so marshal failure is unreachable with the current value, but falling back grants no rule if that contract changes.

func Deny

func Deny(message string) Verdict

Deny builds a deny verdict carrying a human-readable reason.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL