Skip to content

Package approvals ​

Go module github.com/bide-ai/bide; all packages.

github.com/bide-ai/bide/approvals · pkg.go.dev · Stability: core

Package approvals is the intake an application serves so that approvers can decide on gated calls over HTTP: an http.Handler that shows a pending call from the journal, and takes an approver's signed decision, verifies it against the recorded call, and records it through the application's own journal.

Constants

  • const StateWaiting = "waiting": StateWaiting: the run is paused at the gate and takes decisions.
  • const StateDecided = "decided": StateDecided: the gate has an outcome (a tally, or the call has a result); it takes no more.
  • const StateEnded = "ended": StateEnded: the run ended; it takes no more.
  • const StateSingle = "single": StateSingle: a one-decision gate (agent.Approve), which takes no signed decision.
  • const StateExpired = "expired": StateExpired: the gate's deadline (agent.ApprovalPolicy.Timeout) has passed, by the handler's clock, or its recorded outcome is the expiry; it takes no more decisions, and the call never runs.
  • const StateError = "error": StateError: the gate would refuse to evaluate (an invalid policy, approvers on one key, a requester the run does not record): the run fails at the call, and the intake takes no decision.
  • const DefaultMaxBodyBytes = 64 << 10: DefaultMaxBodyBytes bounds a request body: a hybrid signature in base64 is about 4.7 KiB.
  • const DefaultReadTimeout = 10 * time.Second: DefaultReadTimeout bounds how long a POST may take to send its body.
  • const DefaultMaxReaders = 32: DefaultMaxReaders and DefaultMaxReadersPerClient bound the request bodies being read at once.
  • const DefaultMaxReadersPerClient = 4: Defaults of the handler's bounds.
  • const DefaultRate = 2.0: DefaultRate and DefaultBurst are the per-client request rate and burst.
  • const DefaultBurst = 10: Defaults of the handler's bounds.
  • const DefaultGlobalRate = 50.0: DefaultGlobalRate and DefaultGlobalBurst are the limit over all clients together.
  • const DefaultGlobalBurst = 100: Defaults of the handler's bounds.
  • const DefaultMaxClients = 10000: DefaultMaxClients bounds the per-client buckets kept.
  • const DefaultMaxInFlight = 16: DefaultMaxInFlight bounds the requests that read or write the journal at once, and the OnRecorded hooks running at once.

Variables

  • var ErrUnauthenticated = errors.New("approvals: unauthenticated"): ErrUnauthenticated is what a WithAuth hook returns for a request with no valid credentials: the handler answers 401.
  • var ErrForbidden = errors.New("approvals: forbidden"): ErrForbidden is what a WithAuth hook returns for an authenticated request it refuses: the handler answers 403.

Functions

  • func PageCSP(intakeOrigin string) string: PageCSP returns the Content-Security-Policy a host of the page should send with it, for an intake at intakeOrigin ("" when the intake is the page's own origin): the policy WithPage serves, with connect-src naming the intake.
  • func PageFiles() map[string][]byte: PageFiles returns the files of the approve page by name: index.html, page.js and app.css.
  • func PageSHA256() map[string]string: PageSHA256 returns the SHA-256 of each file of PageFiles, in lowercase hex: what a release publishes and a deployment verifies before it serves the page.

type Access ​

go
type Access struct {
	Phase     Phase
	Method    string
	RunID     string
	ToolUseID string
	Approver  string
}

Access is what an authorization hook (WithAuth) is asked to allow.

type Gate ​

go
type Gate struct {
	Need      int            `json:"need"`
	Approvers []string       `json:"approvers"`
	Approved  int            `json:"approved"`
	Denied    int            `json:"denied"`
	Pending   []string       `json:"pending,omitempty"`
	Excluded  []string       `json:"excluded,omitempty"`
	Passed    bool           `json:"passed"`
	Failed    bool           `json:"failed"`
	Expired   bool           `json:"expired,omitempty"`
	Decisions []GateDecision `json:"decisions,omitempty"`

	Identity map[string]string `json:"identity,omitempty"`
}

Gate is the standing of an m-of-n gate, counted as the gate counts: only decisions that verify under the enrolled keys, the first of each approver.

type GateDecision ​

go
type GateDecision struct {
	Approver string `json:"approver"`
	Approved bool   `json:"approved"`
	Counted  bool   `json:"counted"`
	Reason   string `json:"reason,omitempty"`

	Tier        string `json:"tier,omitempty"`
	Provisional bool   `json:"provisional,omitempty"`
	Basis       string `json:"basis,omitempty"`
}

GateDecision is one decision record the gate read.

type Handler ​

go
type Handler struct {
	// contains filtered or unexported fields
}

Handler is the intake.

Constructors and functions

  • func New(j *agent.Journal, verifierFor agent.ApproverVerifierFor, opts ...Option) (*Handler, error): New returns the intake handler over j, the application's own journal: for decisions to be signed as they are written, j's store must be the audit.AuditedStore (or wrap it).

Methods

  • func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request): ServeHTTP serves GET /pending and POST /decisions.
  • func (h *Handler) Wait(): Wait blocks until the OnRecorded hooks running now have returned, for a graceful shutdown: stop the server, then Wait.

type Option ​

go
type Option func(*Handler) error

Option configures New.

Constructors and functions

  • func OnRecorded(fn func(context.Context, Recorded)) Option: OnRecorded sets the function called, in a goroutine of its own and with a context that outlives the request, once for each decision this handler wrote (never for a replay or a refusal).
  • func WithAuth(fn func(*http.Request, Access) error) Option: WithAuth sets a hook that runs for every request, after the rate limit and before the journal is read or written, with what the request asks for.
  • func WithCORS(origin string) Option: WithCORS lets a page hosted at origin (an exact origin such as "https://approve.example.com", never "*") call the intake from a browser: it answers the CORS preflight (OPTIONS) before any authentication, since a preflight carries no credentials and a browser can never reach an endpoint that refuses it, and adds the Access-Control headers to responses to that origin.
  • func WithCORSCredentials() Option: WithCORSCredentials lets the page send credentials cross-origin (fetch's credentials mode "include", which config.json asks for): cookies, HTTP authentication and, for mutual TLS, the browser's client certificate, which a browser does not present on a cross-origin request made with credentials omitted.
  • func WithClientKey(fn func(*http.Request) string) Option: WithClientKey names the client a request is limited as (and the client whose concurrent body reads are capped).
  • func WithClock(now func() time.Time) Option: WithClock sets the clock the rate limits run on and the decision's recorded_at is read from.
  • func WithGatePolicy(fn func(tool string) (*agent.ApprovalPolicy, bool)) Option: WithGatePolicy gives the handler each gated tool's live approval policy, as the application's agent is built with it (the ToolSpec's Approval).
  • func WithGlobalRateLimit(rate float64, burst int) Option: WithGlobalRateLimit sets the request rate and burst over all clients together; DefaultGlobalRate and DefaultGlobalBurst by default.
  • func WithMaxBodyBytes(n int64) Option: WithMaxBodyBytes bounds a request body (DefaultMaxBodyBytes by default).
  • func WithMaxClients(n int) Option: WithMaxClients bounds how many clients' buckets are kept (DefaultMaxClients).
  • func WithMaxInFlight(n int) Option: WithMaxInFlight bounds the requests working on the journal at once, and the OnRecorded hooks running at once (DefaultMaxInFlight).
  • func WithMaxReaders(total, perClient int) Option: WithMaxReaders bounds the request bodies being read at once, overall and for one client (DefaultMaxReaders, DefaultMaxReadersPerClient).
  • func WithOnError(fn func(error)) Option: WithOnError sets the function the handler tells of what it does not show a caller: a store error, a refused hook.
  • func WithPage() Option: WithPage makes the handler serve the approve page under /page/: an approver opens <mount>/page/#run=<id>&call=<id> and signs in the browser.
  • func WithRateLimit(rate float64, burst int) Option: WithRateLimit sets the per-client request rate (a second) and burst; DefaultRate and DefaultBurst by default.
  • func WithReadTimeout(d time.Duration) Option: WithReadTimeout bounds how long a POST /decisions may take to send its body (DefaultReadTimeout).

type Pending ​

go
type Pending struct {
	Run            string          `json:"run"`
	Call           string          `json:"call"`
	Tool           string          `json:"tool"`
	Args           json.RawMessage `json:"args,omitempty"`
	ArgsText       string          `json:"args_text,omitempty"`
	ArgsSHA256     string          `json:"args_sha256"`
	DecisionFormat string          `json:"decision_format"`
	State          string          `json:"state"`
	AskedAt        string          `json:"asked_at,omitempty"`

	ExpiresAt string `json:"expires_at,omitempty"`

	Reason string `json:"reason,omitempty"`

	Why  []agent.GateReason `json:"why,omitempty"`
	Gate Gate               `json:"gate"`
}

Pending is the body of GET /pending: a gated call, from the journal.

type Phase ​

go
type Phase int

Phase is which call of the authorization hook (WithAuth) an Access belongs to.

Constants

  • const PhaseRequest Phase: PhaseRequest is the hook's call with everything the request asks for: the method, and for a call, a decision or a page the run, call and approver it names.
  • const PhaseIdentity Phase: PhaseIdentity is the call a POST /decisions gets first, before its body is read: RunID, ToolUseID and Approver are empty, and the hook must only authenticate (who is this, from the headers and the connection: a bearer token, a client certificate), never decide on what the request asks for, which it does not yet know.

type Recorded ​

go
type Recorded struct {
	RunID     string
	RootRunID string
	ToolUseID string
	Approver  string
	Approved  bool
	Record    string
	Index     int

	Decided bool
}

Recorded is what OnRecorded is told about a decision this handler wrote.

type Request ​

go
type Request struct {
	Run       string `json:"run"`
	Call      string `json:"call"`
	Approver  string `json:"approver"`
	Approved  bool   `json:"approved"`
	DecidedAt string `json:"decided_at"`
	Alg       string `json:"alg"`
	Signature []byte `json:"signature"`

	Cert [][]byte `json:"cert,omitempty"`
}

Request is the body of POST /decisions: one approver's signed decision.

type Response ​

go
type Response struct {
	Recorded   bool   `json:"recorded"`
	Record     string `json:"record"`
	Index      int    `json:"index"`
	RecordedAt string `json:"recorded_at"`
	Gate       Gate   `json:"gate"`

	Counted bool   `json:"counted"`
	Reason  string `json:"reason,omitempty"`

	Anchored *bool `json:"anchored,omitempty"`

	Receipt *audit.DecisionReceipt `json:"receipt,omitempty"`
}

Response is the body of a successful POST /decisions.

Apache-2.0 licensed.