apikeys

package
v1.5.0 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2026 License: AGPL-3.0 Imports: 22 Imported by: 0

Documentation

Overview

Package apikeys manages API keys and MCP agents (A5 §3.9, §5.13). Keys never exceed their creator's permissions and are shown exactly once. Expired keys stay listed for 90 days with the calls that still try to use them.

Index

Constants

View Source
const (
	KindAPIKey = "api_key"
	KindAgent  = "mcp_agent"
)

Kinds of keys.

View Source
const (
	PresetSendOnly = "send_only"
	PresetSMTP     = "smtp"
)

Send-only key presets.

Variables

This section is empty.

Functions

func ClientLabel

func ClientLabel(ua string) string

ClientLabel turns a User-Agent into a short label for the keys list: "GitHub Actions runner", "Claude Desktop", "curl", "python-requests".

func PickedFirst

func PickedFirst(picked []string, set authz.Set) []string

PickedFirst stores the picked keys in their order, then the implied ones.

func RecordRejection

func RecordRejection(ctx context.Context, q *store.Queries, keyID uuid.UUID, ip *netip.Addr, userAgent, reason string)

RecordRejection counts a call refused because a key expired or was revoked, so the expired-key card can show what still uses it. The REST middleware and the MCP endpoint call it.

func Register

func Register(h huma.API, s *Service)

Register adds the API key and MCP agent operations.

func StoredOrder

func StoredOrder(keys []string) []string

StoredOrder returns the keys the creator picked, in the order picked, without the view permissions that were added automatically.

Types

type APIKeyCategoryRef

type APIKeyCategoryRef struct {
	ID   string `json:"id"`
	Name string `json:"name"`
}

APIKeyCategoryRef names a transactional category.

type APIKeyCreateInput

type APIKeyCreateInput struct {
	Name        string   `json:"name" minLength:"1" maxLength:"80"`
	Description string   `json:"description,omitempty" maxLength:"120" doc:"Client label, e.g. Claude Desktop"`
	Permissions []string `json:"permissions" minItems:"1" maxItems:"60"`
	// Lists restricts the key to these lists (empty = all lists).
	Lists     []string   `json:"lists,omitempty" maxItems:"100"`
	ExpiresAt *time.Time `json:"expiresAt,omitempty"`
	// Transactional makes a send-only, test-mode or SMTP key; its only
	// permission is then transactional:send.
	Transactional *APIKeyTransactionalInput `json:"transactional,omitempty"`
}

APIKeyCreateInput creates a key or agent.

type APIKeyCreated

type APIKeyCreated struct {
	Key    APIKeyView `json:"key"`
	Secret string     `json:"secret" doc:"The full key. Shown only in this response."`
	// Usage is "Authorization: Bearer rc_live_… against https://…/api/v1".
	Endpoint string `json:"endpoint"`
}

APIKeyCreated is shown exactly once.

type APIKeyCreator

type APIKeyCreator struct {
	ID          string `json:"id,omitempty"`
	Name        string `json:"name"`
	AvatarColor string `json:"avatarColor"`
}

APIKeyCreator is who created a key.

type APIKeyList

type APIKeyList struct {
	Items []APIKeyView `json:"items"`
	// Permissions, Held, Locked and Lists feed the create dialog.
	Permissions []access.PermissionInfo  `json:"permissions"`
	Groups      []string                 `json:"groups"`
	Held        []string                 `json:"held"`
	Locked      []APIKeyLockedPermission `json:"locked"`
	Lists       []access.ScopedList      `json:"lists"`
	// Endpoint is the API base URL (or the MCP endpoint for agents).
	Endpoint string `json:"endpoint"`
}

APIKeyList is the API keys or MCP agents card.

type APIKeyLockedPermission

type APIKeyLockedPermission struct {
	Key    string `json:"key"`
	Reason string `json:"reason"`
}

APIKeyLockedPermission is a permission the caller can't put on a key.

type APIKeyRejections

type APIKeyRejections struct {
	Calls  int64      `json:"calls" doc:"In the last 7 days"`
	Since  *time.Time `json:"since,omitempty" doc:"First rejected call"`
	IP     string     `json:"ip,omitempty" doc:"Busiest client address"`
	Client string     `json:"client,omitempty" doc:"Client label of that address"`
}

APIKeyRejections counts calls refused because the key expired or was revoked.

type APIKeyTransactional

type APIKeyTransactional struct {
	Preset        string              `json:"preset" enum:"send_only,smtp"`
	Mode          string              `json:"mode" enum:"live,test"`
	Templates     []string            `json:"templates" doc:"Template IDs it may send; empty for all, including ones published later"`
	Categories    []APIKeyCategoryRef `json:"categories" doc:"Categories it may send (SMTP credentials); empty for all"`
	TestAddresses []string            `json:"testAddresses" doc:"Allowed test addresses besides the members (qa+*@acme.io)"`
	RatePerSecond int                 `json:"ratePerSecond"`
	// Username is an SMTP credential's user name: the key's ID.
	Username string `json:"username,omitempty"`
}

APIKeyTransactional describes a send-only key: its preset (send_only, or smtp for an SMTP relay credential), its mode (test keys deliver only to the workspace's members and the allowed test addresses), the templates or categories it is limited to, and its send rate.

type APIKeyTransactionalInput

type APIKeyTransactionalInput struct {
	Preset string `json:"preset" enum:"send_only,smtp"`
	Mode   string `json:"mode,omitempty" enum:"live,test" default:"live"`
	// Templates limits the key to these template IDs (empty: all, including
	// ones published later).
	Templates []string `json:"templates,omitempty" maxItems:"200"`
	// Categories limits the key to these categories (SMTP credentials).
	Categories []string `json:"categories,omitempty" maxItems:"50"`
	// TestAddresses are allowed besides the workspace's members (test mode):
	// addresses or patterns such as qa+*@acme.io.
	TestAddresses []string `json:"testAddresses,omitempty" maxItems:"50"`
	RatePerSecond int      `json:"ratePerSecond,omitempty" minimum:"1" maximum:"10000" doc:"Messages per second (50 by default)"`
}

APIKeyTransactionalInput is the "Send-only key" preset of the create dialog, and an SMTP credential.

type APIKeyView

type APIKeyView struct {
	ID          string              `json:"id"`
	Kind        string              `json:"kind" enum:"api_key,mcp_agent"`
	Name        string              `json:"name"`
	Description string              `json:"description" doc:"Client label for agents (Claude Desktop)"`
	Masked      string              `json:"masked" example:"rc_live_8f2c…a91d"`
	Permissions []string            `json:"permissions"`
	Sensitive   []string            `json:"sensitive" doc:"The ⚑ permissions among them"`
	Scope       access.ScopeSummary `json:"scope"`
	CreatedBy   APIKeyCreator       `json:"createdBy"`
	CreatedAt   time.Time           `json:"createdAt"`
	ExpiresAt   *time.Time          `json:"expiresAt,omitempty"`
	LastUsedAt  *time.Time          `json:"lastUsedAt,omitempty"`
	LastUsedIP  string              `json:"lastUsedIp,omitempty"`
	// LastUsedClient labels the caller ("nightly job", "GitHub Actions runner").
	LastUsedClient string `json:"lastUsedClient,omitempty"`
	// LastCall is the MCP tool of an agent's last call.
	LastCall   string            `json:"lastCall,omitempty"`
	Status     string            `json:"status" enum:"active,expired"`
	Rejections *APIKeyRejections `json:"rejections,omitempty"`
	// Transactional is set for send-only, test-mode and SMTP keys.
	Transactional *APIKeyTransactional `json:"transactional,omitempty"`
}

APIKeyView is an API key or MCP agent as listed. The secret is never returned.

type KeyPathInput

type KeyPathInput struct {
	api.WorkspaceInput
	KeyID string `path:"keyId" format:"uuid"`
}

KeyPathInput is a path or query input shared by several operations.

type MCPAgentAction

type MCPAgentAction struct {
	ID         string    `json:"id"`
	OccurredAt time.Time `json:"occurredAt"`
	AgentID    string    `json:"agentId,omitempty"`
	Agent      string    `json:"agent"`
	Tool       string    `json:"tool"`
	Target     string    `json:"target"`
	Result     string    `json:"result" enum:"allowed,denied,error"`
	// Note is "campaigns:pause" for an allowed call or "needs campaigns:send ·
	// proposal recorded for Linh Nguyen" for a denied one.
	Note string `json:"note,omitempty"`
	// Proposal tells that a denied call was proposed to a member to review.
	Proposal bool `json:"proposal"`
	// Summary is what the tool returned or did ("Paused October Product Update · Outlook route").
	Summary string `json:"summary,omitempty"`
}

MCPAgentAction is one recent MCP tool call.

type MCPAgentActionList

type MCPAgentActionList struct {
	Items []MCPAgentAction `json:"items"`
}

MCPAgentActionList is the recent agent actions card.

type Service

type Service struct {
	Pool      *pgxpool.Pool
	Q         *store.Queries
	Audit     *audit.Logger
	PublicURL func(context.Context) string
	Now       func() time.Time
}

func (*Service) AgentActions

func (s *Service) AgentActions(ctx context.Context, ws *store.Workspace, limit int) (MCPAgentActionList, error)

AgentActions lists the latest MCP calls from the audit log, their details, notes and outcomes in the reader's language when the agent's call kept them (internal/mcpserver).

func (*Service) Create

Create makes a key or agent with permissions the caller holds.

func (*Service) Delete

func (s *Service) Delete(ctx context.Context, ws *store.Workspace, kind string, id uuid.UUID) error

Delete removes an expired or revoked key from the list.

func (*Service) Get

func (s *Service) Get(ctx context.Context, ws *store.Workspace, kind string, id uuid.UUID) (APIKeyView, error)

Get returns one key with its rejected calls.

func (*Service) List

func (s *Service) List(ctx context.Context, ws *store.Workspace, p *authz.Principal, kind string) (APIKeyList, error)

List returns the keys (or agents) of the workspace.

func (*Service) Revoke

func (s *Service) Revoke(ctx context.Context, ws *store.Workspace, kind string, id uuid.UUID) error

Revoke stops a key immediately.

func (*Service) Rotate

func (s *Service) Rotate(ctx context.Context, ws *store.Workspace, p *authz.Principal, kind string, id uuid.UUID) (APIKeyCreated, error)

Rotate replaces a key (active or expired) with a new secret that has the same name, permissions and scope. The old one stops working at once.

Jump to

Keyboard shortcuts

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