clearance

package
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Oct 3, 2026 License: MIT Imports: 21 Imported by: 0

Documentation

Overview

Package clearance implements `authio clearance`: a local MCP stdio server that fronts the hosted Clearance data-plane and wraps local tools (shell commands, stdio MCP servers) so every call — hosted or local — is judged by the same central policy and lands in the same audit trail.

Index

Constants

View Source
const (
	ScopeTools = "tools:read tools:call"
)

Variables

View Source
var ErrAgentRequired = errors.New("--agent <agent_id> is required")

ErrAgentRequired is returned when --agent is missing.

View Source
var ErrNotLoggedIn = errors.New("not logged in")

ErrNotLoggedIn is returned when no credential exists for the agent.

View Source
var ErrReloginRequired = errors.New("refresh token rejected; run `authio clearance login` again")

Functions

func AwaitCallback

func AwaitCallback(ctx context.Context, ln net.Listener, state string) (string, error)

AwaitCallback serves the loopback redirect once and returns the code. It refuses a state mismatch and surfaces provider errors.

func ChallengeS256

func ChallengeS256(verifier string) string

func Humanize

func Humanize(err error, agentID string) string

Humanize turns the common failures into actionable sentences.

func LoopbackListener

func LoopbackListener(port int) (net.Listener, string, error)

LoopbackListener binds 127.0.0.1 on an ephemeral port (or a fixed one) and returns the redirect URI to register with the flow.

func NewCodeVerifier

func NewCodeVerifier() (string, error)

func NewState

func NewState() (string, error)

func Root

func Root() (string, error)

Root returns the sidecar's working tree: the current directory.

func SetIntent

func SetIntent(s string)

SetIntent records the intent the local client declared so a hosted (re)initialize can carry it.

Types

type APIError

type APIError struct {
	Status  int
	Code    string
	Message string
}

APIError is a structured error from Clearance's REST routes.

func (*APIError) Error

func (e *APIError) Error() string

type AgentCredential

type AgentCredential struct {
	AgentID      string    `json:"agent_id"`
	ProjectID    string    `json:"project_id"`
	ClientID     string    `json:"client_id"`
	AuthCoreURL  string    `json:"auth_core_url"`
	ClearanceURL string    `json:"clearance_url"`
	Scope        string    `json:"scope"`
	AccessToken  string    `json:"access_token"`
	ExpiresAt    time.Time `json:"expires_at"`
	RefreshToken string    `json:"refresh_token"`
	SavedAt      time.Time `json:"saved_at"`
}

AgentCredential is what `authio clearance login` saves per agent: the Connect client the agent is bound to and its rotating refresh token. It lives beside ~/.authio/credentials.toml, one JSON file per agent, mode 0600, because the project-key TOML has a fixed schema and this is a different kind of secret (a user-delegated OAuth grant, not an sk_ key).

type ExecArgs

type ExecArgs struct {
	Command   string   `json:"command"`
	Args      []string `json:"args"`
	Cwd       string   `json:"cwd,omitempty"`
	TimeoutMS int      `json:"timeout_ms,omitempty"`
}

ExecArgs is the exec.run input.

func (ExecArgs) CommandLine

func (a ExecArgs) CommandLine() string

CommandLine is the policy string: argv joined by single spaces, so `exec:git push*` matches ["git","push","origin"].

type Hosted

type Hosted struct {
	BaseURL string
	AgentID string
	Tokens  *TokenSource
	HTTP    *http.Client
	// contains filtered or unexported fields
}

Hosted is the client for one agent's hosted Clearance surface: the MCP data-plane (proxied tools), /evaluate (local-tool verdicts) and /policy (--explain).

func (*Hosted) CallTool

func (h *Hosted) CallTool(ctx context.Context, name string, args json.RawMessage, meta map[string]any) (json.RawMessage, *rpcError, error)

CallTool forwards a tools/call verbatim and returns the raw result.

func (*Hosted) Evaluate

func (h *Hosted) Evaluate(ctx context.Context, provider, tool string, args map[string]any, intent string) (*Verdict, error)

Evaluate judges a local tool call.

func (*Hosted) Initialize

func (h *Hosted) Initialize(ctx context.Context, intent string) error

Initialize opens the hosted session, forwarding the local client's declared intent when present.

func (*Hosted) ListTools

func (h *Hosted) ListTools(ctx context.Context) ([]Tool, error)

ListTools returns the hosted tool surface.

func (*Hosted) Policy

func (h *Hosted) Policy(ctx context.Context) (json.RawMessage, error)

Policy fetches the agent's resolved rule chain (raw JSON, printed as-is).

func (*Hosted) SessionID

func (h *Hosted) SessionID() string

SessionID returns the hosted session id (for evaluate binding / whoami).

type OAuthClient

type OAuthClient struct {
	AuthCoreURL string
	ProjectID   string
	ClientID    string
	Resource    string // RFC 8707 resource indicator (the Clearance origin)
	HTTP        *http.Client
}

OAuthClient talks to auth-core for one agent credential.

func (*OAuthClient) AuthorizeURL

func (o *OAuthClient) AuthorizeURL(redirectURI, state, challenge, scope string) string

AuthorizeURL builds the browser URL for the loopback flow.

func (*OAuthClient) Exchange

func (o *OAuthClient) Exchange(ctx context.Context, code, redirectURI, verifier string) (*tokenResponse, error)

Exchange redeems an authorization code.

func (*OAuthClient) Refresh

func (o *OAuthClient) Refresh(ctx context.Context, refreshToken string) (*tokenResponse, error)

Refresh rotates a refresh token.

type OAuthError

type OAuthError struct {
	Code        string
	Description string
	Status      int
}

OAuthError is an RFC 6749 §5.2 error from the token endpoint.

func (*OAuthError) Error

func (e *OAuthError) Error() string

type Server

type Server struct {
	Hosted    *Hosted
	Root      string // launch directory; exec cwd is confined to it
	Providers []StdioProvider
	Log       io.Writer // diagnostics (stderr); never the token
	// contains filtered or unexported fields
}

Server is the local MCP stdio server. Its tool surface is the union of the hosted agent's tools (proxied verbatim), `exec.run`, and the tools of every wrapped stdio provider (namespaced `<provider>.<tool>`). Every local call is judged by Hosted.Evaluate before it runs.

func (*Server) Serve

func (s *Server) Serve(ctx context.Context, in io.Reader, out io.Writer) error

Serve reads JSON-RPC from in and writes responses to out until EOF.

type SidecarConfig

type SidecarConfig struct {
	Providers []StdioProvider
}

SidecarConfig is the subset of authio.yaml the sidecar reads: local providers to wrap. Policy for them lives in Clearance (imported from the same file's `clearance:` block by `authio apply`), never here.

clearance:
  providers:
    filesystem:
      type: stdio
      command: npx
      args: ["-y", "@modelcontextprotocol/server-filesystem", "/workspace"]
      env: { LOG_LEVEL: warn }

func LoadSidecarConfig

func LoadSidecarConfig(path string) (*SidecarConfig, error)

LoadSidecarConfig reads authio.yaml; a missing file yields an empty config (hosted tools + exec only). Unknown keys elsewhere in the file are fine — `authio apply` owns the rest of the schema.

type StdioProvider

type StdioProvider struct {
	Name    string
	Command string
	Args    []string
	Env     map[string]string
}

StdioProvider is a `clearance.providers.<name>` entry of type stdio.

type TokenSource

type TokenSource struct {
	Store *TokenStore
	Cred  *AgentCredential
	OAuth *OAuthClient
	Now   func() time.Time
}

TokenSource returns a valid access token, refreshing (and persisting) when the cached one is within refreshSkew of expiry. A refresh failure with invalid_grant means the family was revoked or expired — the caller should tell the user to log in again.

func (*TokenSource) Token

func (t *TokenSource) Token(ctx context.Context) (string, error)

type TokenStore

type TokenStore struct{ Dir string }

TokenStore persists AgentCredentials under dir (default ~/.authio/clearance).

func DefaultTokenStore

func DefaultTokenStore() (*TokenStore, error)

func (*TokenStore) Delete

func (s *TokenStore) Delete(agentID string) error

func (*TokenStore) Load

func (s *TokenStore) Load(agentID string) (*AgentCredential, error)

func (*TokenStore) Save

func (s *TokenStore) Save(c AgentCredential) error

type Tool

type Tool struct {
	Name        string         `json:"name"`
	Title       string         `json:"title,omitempty"`
	Description string         `json:"description,omitempty"`
	InputSchema map[string]any `json:"inputSchema"`
}

Tool is an MCP tool descriptor.

type ToolContent

type ToolContent struct {
	Type string `json:"type"`
	Text string `json:"text"`
}

type ToolResult

type ToolResult struct {
	Content           []ToolContent  `json:"content"`
	StructuredContent any            `json:"structuredContent,omitempty"`
	IsError           bool           `json:"isError,omitempty"`
	Meta              map[string]any `json:"_meta,omitempty"`
}

ToolResult is the tools/call result shape. Verdict metadata rides in Meta so a client can act on approval ids programmatically.

func RunExec

func RunExec(ctx context.Context, root string, a ExecArgs) (*ToolResult, error)

RunExec executes an already-cleared command: argv exactly as given, no shell, capped output and time.

type Verdict

type Verdict struct {
	VerdictID  string     `json:"verdict_id"`
	Verdict    string     `json:"verdict"`
	ReasonCode string     `json:"reason_code"`
	PolicyID   string     `json:"policy_id,omitempty"`
	Rule       string     `json:"rule,omitempty"`
	ApprovalID string     `json:"approval_id,omitempty"`
	ExpiresAt  *time.Time `json:"approval_expires_at,omitempty"`
}

Verdict is Clearance's evaluate envelope (the parts the sidecar uses).

Jump to

Keyboard shortcuts

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