approval

package
v0.0.13 Latest Latest
Warning

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

Go to latest
Published: Oct 8, 2026 License: Apache-2.0 Imports: 17 Imported by: 0

Documentation

Overview

Package approval holds writes made with an agent's credential until a human says yes.

The gate is on the API, not in any one client. An agent driving `abx` from someone's laptop and an agent driving it from a sandbox this platform started are the same caller as far as this package is concerned: both arrive with a tenant API key, and the key is what says whether its holder may act unattended. Nothing here knows the assistant exists.

A person clicking in the console is exempt, and that is the whole idea rather than an oversight: they authenticate with a session JWT, and the click IS the approval. Only credentials that can act while nobody is watching are gated.

Index

Constants

View Source
const (
	// How long a refused request stays answerable. Short because the caller is
	// waiting: an approval nobody acted on should fall away rather than sit in
	// the list, and the client can always ask again.
	RequestTTL = 15 * time.Minute
	// How long a session-scoped grant lasts. Long enough to cover a working
	// session, short enough that walking away ends it.
	SessionGrantTTL = 2 * time.Hour
)
View Source
const (
	// SessionHeader names the conversation, shell session or run this call
	// belongs to. It is the unit "approve for this session" is about, and it is
	// the caller's to declare: the platform cannot infer it, because the same
	// key legitimately serves many sessions at once.
	//
	// A caller that omits it is not refused — it simply cannot be granted
	// anything wider than one call, which is the safe direction to fail in.
	SessionHeader = "X-AgentBox-Session-Id"

	// BizErrApprovalRequired tells a client that the call is well-formed and
	// permitted, and is waiting on a person. It is a distinct code from any
	// permission error because the remedy is different: not "get access", but
	// "go and click this".
	BizErrApprovalRequired domain.BusinessErrorCode = "APPROVAL_REQUIRED"

	// BizErrForbiddenForAgent tells a client the call will never be permitted
	// for this credential and there is nothing to wait for.
	//
	// Distinct from APPROVAL_REQUIRED because the remedies are opposite: one
	// says "a person is about to decide, ask again shortly", the other says
	// "stop asking, and hand this to a person". An agent that cannot tell them
	// apart polls forever for an approval nobody will ever be shown.
	BizErrForbiddenForAgent domain.BusinessErrorCode = "FORBIDDEN_FOR_AGENT"

	// StatusApprovalRequired is 428 Precondition Required.
	//
	// Not 403: a client cannot tell a real permission failure from a pending
	// one, and every SDK in front of us maps 403 to a terminal error. Not 202
	// either — the Python SDK treats anything under 400 as success, so a 202
	// would read as "created" and the caller would carry on with nothing.
	StatusApprovalRequired = http.StatusPreconditionRequired
)

Variables

This section is empty.

Functions

func Fingerprint

func Fingerprint(method, path string, body []byte) string

Fingerprint identifies one call closely enough that approving it cannot authorise a different one.

The body is in it deliberately: "create an environment" is not the unit a person agrees to — "create the environment called foo" is. Without the body, a one-time approval for a harmless call would authorise any other call to the same route.

The path is in it for the same reason and has to be the CONCRETE path: a request like `DELETE /v1/envs/:name` carries no body, so keying on the route template made every delete from one credential share one fingerprint — and one pending request, labelled with whichever env happened to ask first.

func IsWrite

func IsWrite(method string) bool

IsWrite reports whether a method changes anything. Used only to skip the lookup early; the map is the authority on what is gated.

func New

func New(store *Store, identity IdentityFunc, consoleURL ConsoleURLFunc, pageURL PageURLFunc) gin.HandlerFunc

New returns the gate.

It must run AFTER authentication (it needs the principal) and after routing (it needs the route template, not the concrete URL). Both hold when it is appended to the generated router's middleware slice, which is where it goes.

Types

type ConsoleURLFunc

type ConsoleURLFunc func(approvalID string) string

ConsoleURLFunc builds the page a person opens to decide. Empty when the deployment has no console configured — the CLI still works from `pollUrl`, and a link to nowhere is worse than no link.

type Detail

type Detail struct {
	ApprovalID string `json:"approvalId"`
	Operation  string `json:"operation"`
	Summary    string `json:"summary"`
	// OnceOnly is here so a client can say "this one cannot be approved for the
	// session" without having to know the catalogue.
	OnceOnly  bool   `json:"onceOnly"`
	URL       string `json:"url,omitempty"`
	PollURL   string `json:"pollUrl"`
	ExpiresAt string `json:"expiresAt"`
}

Detail is the structured half of a 428. It is what the CLI renders as its `approval:` trailer and what the console deep-links from.

type ErrNotDecidable

type ErrNotDecidable struct{ Reason string }

ErrNotDecidable explains why a decision was refused.

func (*ErrNotDecidable) Error

func (e *ErrNotDecidable) Error() string

type Grant

type Grant struct {
	ID        string    `json:"id"`
	Principal Principal `json:"principal"`
	Scope     Scope     `json:"scope"`
	SessionID string    `json:"sessionId,omitempty"`
	Operation string    `json:"operation"`
	CreatedAt time.Time `json:"createdAt"`
	// Zero for ScopeKey: it ends when someone revokes it.
	ExpiresAt time.Time `json:"expiresAt,omitzero"`
	GrantedBy string    `json:"grantedBy"`
}

Grant is a standing permission.

type Identity

type Identity struct {
	// Gated is false for anyone who should never be asked: console sessions,
	// admin keys, and every credential not marked as acting unattended.
	Gated     bool
	Principal Principal
	// KeyApprovals are the operations this credential is already allowed to
	// perform, as recorded on the credential itself.
	//
	// Read from the caller's own metadata rather than from the gate's memory so
	// that a permission survives a restart of this process: the memory is a
	// cache of decisions made since it started, and after a rollout it is
	// simply empty.
	KeyApprovals []string
}

Identity is what the middleware needs to know about the caller. It is a function rather than a direct read of the auth context so the two API surfaces — which populate that context slightly differently — can each say what a gated caller looks like without this package importing either.

type IdentityFunc

type IdentityFunc func(c *gin.Context) Identity

IdentityFunc extracts the caller from a request.

type KeyGrant

type KeyGrant struct {
	KeyID     string
	Operation string
	GrantedAt time.Time
	GrantedBy string
}

KeyGrant is one standing permission as the credential records it.

type KeyGrantStore

type KeyGrantStore interface {
	// GrantOperation records a standing approval on a key.
	GrantOperation(ctx context.Context, keyID, operation, by string) error
	// RevokeOperation withdraws one. Withdrawing an absent one is not an error.
	RevokeOperation(ctx context.Context, keyID, operation string) error
	// KeyGrants lists every standing approval held by this person's keys, so
	// the console can show and withdraw permissions this process did not itself
	// grant — which after a restart is all of them.
	KeyGrants(ctx context.Context, team, user string) ([]KeyGrant, error)
}

KeyGrantStore is where key-scoped approvals outlive this process.

Only the KEY scope has one, and the asymmetry is deliberate. A once-approval is spent within minutes and a session grant dies with the session, so losing either to a restart costs one extra question. A key grant is the one a person gave in order to STOP being asked — losing it silently undoes the thing they asked for, and it goes missing exactly when it is being relied on, since a rollout is most disruptive during a long unattended run.

Implemented by the API key store, because the key is where the permission belongs: a person can find it there, read who granted it, and take it back.

func NewKeyGrantStore

func NewKeyGrantStore(keys keyBackend) KeyGrantStore

NewKeyGrantStore persists key-scoped approvals on the credentials themselves.

The credential is where a standing permission belongs. It is the durable identity of an agent's work, so the permission outlives this process, follows the key rather than a conversation, and appears somewhere a person can find it and take it back — none of which is true of a map in memory.

type Op

type Op struct {
	// ID is what a grant is written against, so it is the unit a person is
	// really deciding about: "let this agent create environments", not "let it
	// call PATCH on that route".
	ID string
	// OnceOnly withholds the session and key scopes. Two kinds of call earn it:
	// those that destroy something, and those that mint a credential. Neither is
	// something a person should be able to authorise in advance and in bulk.
	OnceOnly bool
	// Forbidden refuses the call outright for a gated credential — no approval
	// is created, because there is nothing here a person should be able to wave
	// through from a prompt.
	//
	// The distinction from OnceOnly is the point. A once-only approval still
	// ends with the agent holding what it asked for; for these, what it asked
	// for is the ability to stop being gated. Issuing a credential can issue one
	// WITHOUT the restriction, and what the approval card would say — "create an
	// API key" — is not what is being decided. So the answer is a console link
	// and the person does it as themselves.
	Forbidden bool
	// Summary is what the approval card says. Written for the person deciding,
	// not for the log: it names the thing, because "create a pool" and "create a
	// pool in prod" are different questions.
	Summary string
}

Op is what one route means to a person being asked about it.

func Lookup

func Lookup(method, routeTemplate string) (Op, bool)

Lookup returns what this route does, and whether it is gated at all.

type PageURLFunc

type PageURLFunc func(page string) string

PageURLFunc builds a link to a console PAGE rather than to one approval.

A forbidden operation has no approval to link to — the whole answer is "do this yourself, over there" — so the refusal needs an address for the page that does it. May be nil, and may return "" for the same reason as ConsoleURLFunc: the console's address arrives after this server is serving.

type Principal

type Principal struct {
	Team  string `json:"team"`
	User  string `json:"user"`
	KeyID string `json:"keyId"`
}

Principal is who is asking. `KeyID` is part of the identity because a key grant belongs to one credential, not to everything the person owns: revoking a key must take its grants with it.

type Request

type Request struct {
	ID        string    `json:"id"`
	Principal Principal `json:"principal"`
	// Empty when the caller sent no session header. Such a caller can only ever
	// be granted ScopeOnce — there is nothing to attach a longer grant to, and
	// inventing one would make "for this session" mean "forever".
	SessionID string `json:"sessionId,omitempty"`
	Operation string `json:"operation"`
	// OnceOnly refuses the wider scopes for this operation. Destructive and
	// credential-minting calls are approved one at a time or not at all: a
	// standing permission to delete is not a thing a person should be able to
	// grant by clicking the wrong button once.
	OnceOnly    bool      `json:"onceOnly"`
	Method      string    `json:"method"`
	Path        string    `json:"path"`
	Summary     string    `json:"summary"`
	Fingerprint string    `json:"-"`
	CreatedAt   time.Time `json:"createdAt"`
	ExpiresAt   time.Time `json:"expiresAt"`
	Status      Status    `json:"status"`
	Scope       Scope     `json:"scope,omitempty"`
	DecidedBy   string    `json:"decidedBy,omitempty"`
	DecidedAt   time.Time `json:"decidedAt,omitzero"`
	// contains filtered or unexported fields
}

Request is one refused call, waiting for an answer.

type Scope

type Scope string

Scope is how widely one decision reaches.

const (
	// ScopeOnce authorises exactly the request that was refused, identified by
	// its fingerprint, and is spent the first time it is used.
	ScopeOnce Scope = "once"
	// ScopeSession authorises an operation for the rest of a session.
	ScopeSession Scope = "session"
	// ScopeKey authorises an operation for a credential until revoked. It
	// survives sessions, so it is the only scope a person can hold indefinitely
	// without noticing — hence the listing and revoke endpoints.
	ScopeKey Scope = "key"
)

type Status

type Status string

Status is where a request has got to.

const (
	StatusPending  Status = "pending"
	StatusApproved Status = "approved"
	StatusDenied   Status = "denied"
	StatusExpired  Status = "expired"
)

type Store

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

Store is the whole state of the gate.

Requests and session grants are in memory on purpose: both are short-lived, and losing either fails CLOSED — the next call asks again. Key grants are persisted through KeyGrantStore, and are also mirrored here so a decision takes effect on the very next call rather than after the key cache turns over.

func NewStore

func NewStore(done <-chan struct{}, keys KeyGrantStore) *Store

NewStore returns a store and starts its collector, which runs until done is closed.

`keys` may be nil, in which case key-scoped grants live only as long as this process — which is what the tests want, and what a deployment with no key store could offer anyway.

func (*Store) Allow

func (s *Store) Allow(
	p Principal,
	keyApprovals []string,
	sessionID, operation, fingerprint string,
) bool

Allow reports whether this call may proceed, spending a one-time approval if that is what authorises it.

Checked widest-first so a session or key grant is not consumed by being shadowed: a standing permission should keep a one-time approval in reserve rather than the other way round.

func (*Store) Challenge

func (s *Store) Challenge(r Request) *Request

Challenge returns the request to point the caller at.

An identical call that is already waiting gets the SAME request back rather than a new one. A client that polls and retries would otherwise mint an approval per attempt and bury the one the person is looking at under a pile of duplicates of itself.

func (*Store) Decide

func (s *Store) Decide(
	ctx context.Context,
	id string,
	approve bool,
	scope Scope,
	decidedBy string,
) (Request, error)

Decide answers a pending request, creating a grant when the answer reaches beyond this one call.

func (*Store) Get

func (s *Store) Get(id string) (Request, bool)

Get returns a request by id, reporting expiry as a status rather than as absence — a caller polling a request that timed out deserves to be told which of the two happened.

func (*Store) List

func (s *Store) List(ctx context.Context, p Principal) ([]Request, []Grant)

List returns what an owner has outstanding: requests waiting on them, and the standing permissions they have already given.

Scoped to team+user rather than to the key, because the person deciding is the owner of every key they hold — and because the console shows this list to a human, not to a credential.

func (*Store) Revoke

func (s *Store) Revoke(ctx context.Context, p Principal, grantID string) bool

Revoke withdraws a standing permission. Only its owner can.

Jump to

Keyboard shortcuts

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