Documentation
¶
Overview ¶
Package lumoauth is the official Go SDK for LumoAuth — authentication and authorization for applications and AI agents.
It exposes four entry points, one per kind of caller:
Client — the general-purpose API client. Permission checks (RBAC, ReBAC, ABAC), agent identity, delegation, JIT permissions, approvals, and MCP tokens, credentialed with an API key or a bearer token.
Agent — for AI agents acting under their own identity. Wraps Client with an OAuth 2.0 client-credentials token it refreshes transparently, plus preflight authorization (Ask), capabilities, and budgets.
AAuthClient — for the AAuth protocol: cryptographic agent identity, proof-of-possession tokens, and RFC 9421 HTTP message signing. VerifyAuthToken is the resource-server side of the same protocol.
WebAuth — browser sign-in. Wires the OAuth 2.1 Authorization Code + PKCE flow into any net/http-compatible router, with sessions in a signed cookie.
Client ¶
client, err := lumoauth.New(
lumoauth.WithAPIKey(os.Getenv("LUMOAUTH_API_KEY")),
lumoauth.WithOrgID("acme-corp"),
)
if err != nil {
return err
}
ok, err := client.Permissions.Check(ctx, "document.edit", nil)
ok, err = client.Zanzibar.IsViewer(ctx, "document:readme", "user:bob")
An organization API key works only on the admin API, client registration and the permission checks. ABAC, agent and JIT routes refuse it. Call ABAC with a user access token that has the abac:read scope (abac:write for writes):
userClient, err := lumoauth.New(
lumoauth.WithAccessToken(userAccessToken), // has abac:read
lumoauth.WithOrgID("acme-corp"),
)
decision, err := userClient.Abac.Check(ctx, lumoauth.AbacCheckParams{
ResourceType: "document",
Action: "read",
ResourceID: "doc-123",
})
Resource namespaces cover the surface an application reaches for. For the rest of the REST API — admin endpoints, SCIM, audit logs — use Client.Do, or hand Client.APIConfig to the generated OpenAPI client.
Agent ¶
agent, err := lumoauth.NewAgent(lumoauth.AgentConfig{}) // reads env vars
if err != nil {
return err
}
if err := agent.RequireCapability(ctx, "tool:search_web"); err != nil {
return err
}
allowed, err := agent.IsAllowed(ctx, "document.read", map[string]any{"id": "doc_99"})
Before an irreversible action, ask a human:
approval, err := agent.Approvals.Require(ctx, lumoauth.ApprovalParams{
TaskID: "wire-2026-05-07-001",
Reason: "Wire $4,500 to vendor INV-7741",
Impact: lumoauth.ImpactHigh,
OnBehalfOf: "ada@acme.com",
}, nil)
if err != nil {
return err // denied, expired, timed out, or not delivered to a device
}
For narrowly scoped, short-lived permissions, open a JITContext; for acting on behalf of a user, use a DelegationChain.
Web sign-in ¶
auth, err := lumoauth.NewWebAuth(lumoauth.WebConfig{
Organization: os.Getenv("LUMO_ORG_ID"),
ClientID: os.Getenv("LUMO_CLIENT_ID"),
ClientSecret: os.Getenv("LUMO_CLIENT_SECRET"),
SessionSecret: os.Getenv("SESSION_SECRET"),
})
if err != nil {
return err
}
mux := http.NewServeMux()
mux.Handle("/auth/", auth.Router())
mux.Handle("/", auth.Middleware(auth.RequireAuth(dashboard)))
// In a handler:
user := lumoauth.UserFromContext(req.Context())
Errors ¶
Every error this package returns is matched with the standard library rather than by type switch:
if errors.Is(err, lumoauth.ErrPermissionDenied) {
// 403
}
var apiErr *lumoauth.APIError
if errors.As(err, &apiErr) {
log.Printf("HTTP %d: %v", apiErr.StatusCode, apiErr.Body)
}
The sentinels are ErrAuthentication, ErrPermissionDenied, ErrNotFound, ErrRateLimited, ErrValidation, ErrConfig, ErrNetwork, ErrApprovalDenied, ErrApprovalTimeout, and ErrBudgetExceeded; ErrAPI matches any non-2xx response and ErrLumoAuth matches all of them. The names and codes are shared with the JS and Python SDKs.
Configuration ¶
Options fall back to the environment:
LUMOAUTH_URL instance URL (default https://app.lumoauth.dev) LUMOAUTH_ORG_ID organization slug LUMOAUTH_API_KEY tenant API key (sent as X-API-Key) AGENT_CLIENT_ID agent OAuth client (Agent only) AGENT_CLIENT_SECRET agent OAuth secret (Agent only)
Every endpoint this SDK calls is registered in Routes; a drift test checks the registry against the server's OpenAPI spec, so a renamed route fails the build rather than 404ing in production.
Example (ErrorHandling) ¶
Errors are matched with the standard library.
package main
import (
"context"
"errors"
"fmt"
"log"
"os"
lumoauth "github.com/lumoauth/lumo-auth-go"
)
func main() {
client, err := lumoauth.New(
lumoauth.WithAPIKey(os.Getenv("LUMOAUTH_API_KEY")),
lumoauth.WithOrgID("acme-corp"),
)
if err != nil {
log.Fatal(err)
}
_, err = client.Permissions.Check(context.Background(), "document.edit", nil)
switch {
case err == nil:
// allowed or denied — check the returned bool
case errors.Is(err, lumoauth.ErrAuthentication):
fmt.Println("the credential is invalid or expired")
case errors.Is(err, lumoauth.ErrRateLimited):
var apiErr *lumoauth.APIError
errors.As(err, &apiErr)
fmt.Println("retry after", apiErr.RetryAfter)
case errors.Is(err, lumoauth.ErrNetwork):
fmt.Println("could not reach LumoAuth:", err)
default:
fmt.Println("unexpected:", err)
}
}
Output:
Index ¶
- Constants
- Variables
- func Bool(b bool) *bool
- func BuildPath(template string, params map[string]string) (string, error)
- func BuildSignatureBase(components []string, values map[string]string, created int64, nonce string) string
- func ContentDigestSHA256(body []byte) string
- func ErrorCode(err error) string
- func GenerateNonce() (string, error)
- func LoadPrivateKey(pemData string) (crypto.Signer, error)
- func ParseActorChain(token string) ([]string, error)
- func RouteNames() []string
- func RoutePath(name string, params map[string]string) (string, error)
- func SignRequest(privateKeyPEM, method, targetURL string, opts SignOptions) (map[string]string, error)
- func SignSignatureBase(signatureBase string, key crypto.Signer) (string, error)
- func SignatureParams(components []string, created int64, nonce string) string
- func StatusCode(err error) int
- func TokenSubject(token string) (string, error)
- func VerifySignatureBase(signatureBase, signatureB64URL string, key crypto.PublicKey) bool
- type AAuthAgentMetadata
- type AAuthClaims
- type AAuthClient
- func (c *AAuthClient) AgentIdentifier() string
- func (c *AAuthClient) BaseURL() string
- func (c *AAuthClient) ConsentURL(requestToken string) (string, error)
- func (c *AAuthClient) DiscoverAgents(ctx context.Context) ([]AAuthAgentMetadata, error)
- func (c *AAuthClient) DiscoverIssuer(ctx context.Context) (*AAuthIssuerMetadata, error)
- func (c *AAuthClient) DiscoverResource(ctx context.Context, resourceURL string) ([]AAuthResourceMetadata, error)
- func (c *AAuthClient) ExchangeCode(ctx context.Context, code, redirectURI, agentToken string) (*AAuthTokenResponse, error)
- func (c *AAuthClient) ExchangeToken(ctx context.Context, authToken, resourceToken, agentToken string) (*AAuthTokenResponse, error)
- func (c *AAuthClient) Issuer() string
- func (c *AAuthClient) JWKS(ctx context.Context) (*JWKS, error)
- func (c *AAuthClient) OrgID() string
- func (c *AAuthClient) PublicJWK() (JWK, error)
- func (c *AAuthClient) PublicJWKThumbprint() (string, error)
- func (c *AAuthClient) Refresh(ctx context.Context, params RefreshParams) (*AAuthTokenResponse, error)
- func (c *AAuthClient) RequestAuthToken(ctx context.Context, params AuthTokenParams) (*AAuthTokenResponse, error)
- func (c *AAuthClient) Revoke(ctx context.Context, token, tokenType, agentToken string) error
- func (c *AAuthClient) SignRequest(method, targetURL string, opts SignOptions) (map[string]string, error)
- func (c *AAuthClient) SignedRequest(ctx context.Context, method, targetURL, authToken string, body any) (*http.Response, error)
- type AAuthConfig
- type AAuthIssuerMetadata
- type AAuthResourceMetadata
- type AAuthTokenResponse
- type APIConfig
- type APIError
- type AbacAttributeDefinition
- type AbacBulkDecision
- type AbacCheckParams
- type AbacDecision
- type AbacMatchedPolicy
- type AbacResource
- func (r *AbacResource) AttributeDefinitions(ctx context.Context, attributeType string) ([]AbacAttributeDefinition, error)
- func (r *AbacResource) Check(ctx context.Context, params AbacCheckParams) (*AbacDecision, error)
- func (r *AbacResource) CheckBulk(ctx context.Context, checks []AbacCheckParams) ([]AbacDecision, error)
- func (r *AbacResource) IsAllowed(ctx context.Context, params AbacCheckParams) (bool, error)
- func (r *AbacResource) MyAttributes(ctx context.Context) (map[string]any, error)
- func (r *AbacResource) ResourceAttributes(ctx context.Context, resourceType, resourceID string) (map[string]any, error)
- func (r *AbacResource) SetResourceAttribute(ctx context.Context, resourceType, resourceID, attributeSlug string, value any) error
- func (r *AbacResource) SetUserAttribute(ctx context.Context, userID, attributeSlug string, value any) error
- type Agent
- func (a *Agent) AccessToken(ctx context.Context) (string, error)
- func (a *Agent) Ask(ctx context.Context, action string, actionContext map[string]any) (*AgentAskResult, error)
- func (a *Agent) Authenticate(ctx context.Context, scopes ...string) (string, error)
- func (a *Agent) BaseURL() string
- func (a *Agent) Budget(ctx context.Context) (*AgentBudget, error)
- func (a *Agent) Capabilities(ctx context.Context) ([]string, error)
- func (a *Agent) CheckBudget(ctx context.Context) error
- func (a *Agent) Client() *Client
- func (a *Agent) ClientID() string
- func (a *Agent) ClientSecret() string
- func (a *Agent) Do(ctx context.Context, method, path string, body, out any) error
- func (a *Agent) DoRaw(ctx context.Context, method, path string, body any) (*http.Response, error)
- func (a *Agent) HasCapability(ctx context.Context, capability string) (bool, error)
- func (a *Agent) Identity(ctx context.Context, refresh bool) (*AgentIdentity, error)
- func (a *Agent) Info(ctx context.Context, refresh bool) (*UserInfo, error)
- func (a *Agent) IsAllowed(ctx context.Context, action string, actionContext map[string]any) (bool, error)
- func (a *Agent) MCPToken(ctx context.Context, serverID string) (string, error)
- func (a *Agent) OrgID() string
- func (a *Agent) RedirectURI() string
- func (a *Agent) Register(ctx context.Context, params RegisterParams) (*AgentRegistration, error)
- func (a *Agent) RequireCapability(ctx context.Context, capability string) error
- func (a *Agent) TokenScopes() []string
- type AgentAskResult
- type AgentBudget
- type AgentConfig
- type AgentIdentity
- type AgentRegistration
- type AgentsResource
- func (r *AgentsResource) Ask(ctx context.Context, action string, actionContext map[string]any) (*AgentAskResult, error)
- func (r *AgentsResource) Budget(ctx context.Context) (*AgentBudget, error)
- func (r *AgentsResource) Capabilities(ctx context.Context) ([]string, error)
- func (r *AgentsResource) Info(ctx context.Context) (*UserInfo, error)
- func (r *AgentsResource) IsAllowed(ctx context.Context, action string, actionContext map[string]any) (bool, error)
- func (r *AgentsResource) Me(ctx context.Context) (*AgentIdentity, error)
- func (r *AgentsResource) Register(ctx context.Context, params RegisterParams) (*AgentRegistration, error)
- type ApprovalError
- type ApprovalImpact
- type ApprovalParams
- type ApprovalResult
- type ApprovalsResource
- func (r *ApprovalsResource) Create(ctx context.Context, params ApprovalParams) (*ApprovalResult, error)
- func (r *ApprovalsResource) Require(ctx context.Context, params ApprovalParams, opts *WaitOptions) (*ApprovalResult, error)
- func (r *ApprovalsResource) Status(ctx context.Context, approvalToken string) (*ApprovalResult, error)
- func (r *ApprovalsResource) Wait(ctx context.Context, approvalToken string, opts *WaitOptions) (*ApprovalResult, error)
- type Approver
- type AuthResource
- func (r *AuthResource) AuthorizationURL(params AuthorizationURLParams) (string, error)
- func (r *AuthResource) ClientCredentials(ctx context.Context, clientID, clientSecret string, scopes ...string) (*TokenResponse, error)
- func (r *AuthResource) ExchangeCode(ctx context.Context, params ExchangeCodeParams) (*TokenResponse, error)
- func (r *AuthResource) RefreshToken(ctx context.Context, params RefreshTokenParams) (*TokenResponse, error)
- func (r *AuthResource) Revoke(ctx context.Context, params RevokeParams) error
- func (r *AuthResource) TokenExchange(ctx context.Context, params TokenExchangeParams) (*TokenResponse, error)
- func (r *AuthResource) UserInfo(ctx context.Context, accessToken string) (*UserInfo, error)
- type AuthTokenParams
- type AuthorizationURLParams
- type BaseError
- type BudgetError
- type CheckOptions
- type Client
- func (c *Client) APIConfig(ctx context.Context) (*APIConfig, error)
- func (c *Client) BaseURL() string
- func (c *Client) Do(ctx context.Context, method, path string, body, out any) error
- func (c *Client) DoRaw(ctx context.Context, method, path string, body any) (*http.Response, error)
- func (c *Client) OrgID() string
- func (c *Client) OrgPath(path string) (string, error)
- type ConfidentialClient
- type ConfigError
- type ConsentURLParams
- type CreateTaskParams
- type DelegationChain
- func (c *DelegationChain) ActiveSessions() []string
- func (c *DelegationChain) ActorChain(token string) ([]string, error)
- func (c *DelegationChain) ConsentURL(sessionID string, scopes []string, state string) (string, error)
- func (c *DelegationChain) DelegateToSubAgent(ctx context.Context, sessionID, subAgentToken string, scopes ...string) (string, error)
- func (c *DelegationChain) DelegateToSubAgentForResource(ctx context.Context, sessionID, subAgentToken, resource string, ...) (string, error)
- func (c *DelegationChain) DelegatedToken(ctx context.Context, sessionID string) (string, error)
- func (c *DelegationChain) Do(ctx context.Context, sessionID, method, path string, body, out any) error
- func (c *DelegationChain) DoRaw(ctx context.Context, sessionID, method, path string, body any) (*http.Response, error)
- func (c *DelegationChain) Exchange(ctx context.Context, sessionID string, scopes ...string) (string, error)
- func (c *DelegationChain) ExchangeForResource(ctx context.Context, sessionID, resource string, scopes ...string) (string, error)
- func (c *DelegationChain) HandleConsentCallback(ctx context.Context, sessionID, authorizationCode string) error
- func (c *DelegationChain) HasDelegation(sessionID string) bool
- func (c *DelegationChain) Revoke(ctx context.Context, sessionID string) error
- func (c *DelegationChain) RevokeAll(ctx context.Context) error
- func (c *DelegationChain) SetUserToken(sessionID, accessToken string) error
- type DelegationResource
- func (r *DelegationResource) ConsentURL(params ConsentURLParams) (string, error)
- func (r *DelegationResource) Exchange(ctx context.Context, subjectToken, actorToken string, scopes ...string) (*TokenResponse, error)
- func (r *DelegationResource) ExchangeCode(ctx context.Context, params ExchangeCodeParams) (*TokenResponse, error)
- func (r *DelegationResource) ExchangeForResource(ctx context.Context, subjectToken, actorToken, resource string, ...) (*TokenResponse, error)
- func (r *DelegationResource) ParseActorChain(token string) ([]string, error)
- func (r *DelegationResource) RefreshUserToken(ctx context.Context, params RefreshTokenParams) (*TokenResponse, error)
- func (r *DelegationResource) Revoke(ctx context.Context, params RevokeParams) error
- func (r *DelegationResource) Subject(token string) (string, error)
- type EvaluateTaskParams
- type ExchangeCodeParams
- type ID
- type JITContext
- func (j *JITContext) CaepSessionID() string
- func (j *JITContext) Call(ctx context.Context, jitToken, method, url string, body any) (*http.Response, error)
- func (j *JITContext) CallWithEscalation(ctx context.Context, method, url string, body any, ...) (*http.Response, error)
- func (j *JITContext) Close(ctx context.Context) error
- func (j *JITContext) CompleteTask(ctx context.Context) error
- func (j *JITContext) CreateTask(ctx context.Context, params CreateTaskParams) (*JitTask, error)
- func (j *JITContext) DelegateOnBehalfOf(ctx context.Context, userToken string) error
- func (j *JITContext) EvaluateTask(ctx context.Context, taskID string, params EvaluateTaskParams) (map[string]any, error)
- func (j *JITContext) PendingRequests(ctx context.Context) ([]JitRequest, error)
- func (j *JITContext) RequestPermission(ctx context.Context, authorizationDetails map[string]any, ...) (*JitRequest, error)
- func (j *JITContext) Status(ctx context.Context, requestID string) (*JitRequest, error)
- func (j *JITContext) TaskID() string
- func (j *JITContext) Token(ctx context.Context, requestID string) (string, error)
- type JITContextOption
- type JWK
- type JWKS
- type JWKSCache
- type JitRequest
- type JitResource
- func (r *JitResource) CompleteTask(ctx context.Context, taskID string) error
- func (r *JitResource) CreateTask(ctx context.Context, params CreateTaskParams) (*JitTask, error)
- func (r *JitResource) EvaluateTask(ctx context.Context, taskID string, params EvaluateTaskParams) (map[string]any, error)
- func (r *JitResource) Pending(ctx context.Context) ([]JitRequest, error)
- func (r *JitResource) Request(ctx context.Context, params RequestPermissionParams) (*JitRequest, error)
- func (r *JitResource) Status(ctx context.Context, requestID string) (*JitRequest, error)
- func (r *JitResource) Token(ctx context.Context, requestID string) (*TokenResponse, error)
- type JitTask
- type Keypair
- type McpResource
- type McpToken
- type NetworkError
- type Option
- func WithAPIKey(apiKey string) Option
- func WithAccessToken(token string) Option
- func WithBaseURL(baseURL string) Option
- func WithHTTPClient(httpClient *http.Client) Option
- func WithHeader(name, value string) Option
- func WithOrgID(orgID string) Option
- func WithSkipCertValidation() Option
- func WithTimeout(timeout time.Duration) Option
- func WithTokenProvider(provider TokenProvider) Option
- func WithUserAgent(userAgent string) Option
- type Permission
- type PermissionBulkCheck
- type PermissionCheck
- type PermissionList
- type PermissionMultiCheck
- type PermissionsResource
- func (r *PermissionsResource) Check(ctx context.Context, permission string, opts *CheckOptions) (bool, error)
- func (r *PermissionsResource) CheckAll(ctx context.Context, permissions []string, opts *CheckOptions) (bool, error)
- func (r *PermissionsResource) CheckAllDetailed(ctx context.Context, permissions []string, opts *CheckOptions) (*PermissionMultiCheck, error)
- func (r *PermissionsResource) CheckAny(ctx context.Context, permissions []string, opts *CheckOptions) (bool, error)
- func (r *PermissionsResource) CheckAnyDetailed(ctx context.Context, permissions []string, opts *CheckOptions) (*PermissionMultiCheck, error)
- func (r *PermissionsResource) CheckBulk(ctx context.Context, permissions []string, opts *CheckOptions) (*PermissionBulkCheck, error)
- func (r *PermissionsResource) CheckDetailed(ctx context.Context, permission string, opts *CheckOptions) (*PermissionCheck, error)
- func (r *PermissionsResource) List(ctx context.Context) (*PermissionList, error)
- func (r *PermissionsResource) ListSlugs(ctx context.Context) ([]string, error)
- type RefreshParams
- type RefreshTokenParams
- type RegisterParams
- type RequestPermissionOptions
- type RequestPermissionParams
- type RevokeParams
- type Route
- type SessionTokens
- type SignOptions
- type TokenExchangeParams
- type TokenProvider
- type TokenResponse
- type TokenSource
- type User
- type UserInfo
- type ValidationError
- type VerifyOptions
- type WaitOptions
- type WebAuth
- func (w *WebAuth) CallbackHandler() http.HandlerFunc
- func (w *WebAuth) Client() *Client
- func (w *WebAuth) ClientForRequest(req *http.Request) (*Client, error)
- func (w *WebAuth) LoginHandler() http.HandlerFunc
- func (w *WebAuth) LogoutHandler() http.HandlerFunc
- func (w *WebAuth) Middleware(next http.Handler) http.Handler
- func (w *WebAuth) RefreshSession(rw http.ResponseWriter, req *http.Request) (bool, error)
- func (w *WebAuth) RequireAuth(next http.Handler) http.Handler
- func (w *WebAuth) RequireAuthRedirect(loginPath string) func(http.Handler) http.Handler
- func (w *WebAuth) Router() http.Handler
- func (w *WebAuth) Tokens(req *http.Request) (*SessionTokens, error)
- func (w *WebAuth) User(req *http.Request) (*User, error)
- type WebConfig
- type ZanzibarCheck
- type ZanzibarResource
- func (r *ZanzibarResource) Check(ctx context.Context, object, relation, subject string) (bool, error)
- func (r *ZanzibarResource) CheckDetailed(ctx context.Context, object, relation, subject string) (*ZanzibarCheck, error)
- func (r *ZanzibarResource) Expand(ctx context.Context, object, relation string) (*ZanzibarUsersetNode, error)
- func (r *ZanzibarResource) IsAdmin(ctx context.Context, object, subject string) (bool, error)
- func (r *ZanzibarResource) IsEditor(ctx context.Context, object, subject string) (bool, error)
- func (r *ZanzibarResource) IsMember(ctx context.Context, object, subject string) (bool, error)
- func (r *ZanzibarResource) IsOwner(ctx context.Context, object, subject string) (bool, error)
- func (r *ZanzibarResource) IsViewer(ctx context.Context, object, subject string) (bool, error)
- type ZanzibarUsersetNode
Examples ¶
Constants ¶
const ( AAuthTokenTypeAuth = "auth_token" AAuthTokenTypeRefresh = "refresh_token" )
Token types accepted by Revoke.
const ( EnvAgentClientID = "AGENT_CLIENT_ID" EnvAgentClientSecret = "AGENT_CLIENT_SECRET" )
Environment variables read by NewAgent when the corresponding field is left empty.
const ( EnvBaseURL = "LUMOAUTH_URL" EnvOrgID = "LUMOAUTH_ORG_ID" EnvAPIKey = "LUMOAUTH_API_KEY" )
Environment variables read when the corresponding option is not passed.
const ( CodeError = "LUMOAUTH_ERROR" CodeAPI = "API_ERROR" CodeAuthentication = "AUTHENTICATION_ERROR" CodePermissionDenied = "PERMISSION_DENIED" CodeNotFound = "NOT_FOUND" CodeRateLimited = "RATE_LIMITED" CodeValidation = "VALIDATION_ERROR" CodeConfig = "CONFIG_ERROR" CodeNetwork = "NETWORK_ERROR" CodeApprovalDenied = "APPROVAL_DENIED" CodeApprovalTimeout = "APPROVAL_TIMEOUT" // CodeApprovalNotDelivered marks an ApprovalError for a request that // never reached a push device; see ApprovalError.Reason. CodeApprovalNotDelivered = "APPROVAL_NOT_DELIVERED" CodeBudgetExceeded = "BUDGET_EXCEEDED" )
Error codes, identical to the JS and Python SDKs.
const ( // ApprovalReasonEmailFallbackSent means the user has no enrolled push // device, so the server sent an email notice instead. The email holds no // approval link. The server gives the same answer for an unknown user. ApprovalReasonEmailFallbackSent = "email_fallback_sent" // ApprovalReasonNoEnrolledDevice means the user has no enrolled push // device and the server could not send the email notice either. ApprovalReasonNoEnrolledDevice = "no_enrolled_device" )
Reasons carried by an ApprovalError with Code CodeApprovalNotDelivered.
const ( DefaultJitPollInterval = 5 * time.Second DefaultJitPollTimeout = 5 * time.Minute )
Defaults for human-in-the-loop approval polling on JIT requests.
const ( AttributeTypeUser = "user" AttributeTypeResource = "resource" AttributeTypeEnvironment = "environment" )
Attribute definition types accepted by AttributeDefinitions.
const ( DefaultApprovalPollInterval = 1500 * time.Millisecond DefaultApprovalTimeout = 90 * time.Second )
Defaults for approval polling. The server's push-approval request TTL is 120s, so the default deadline sits just inside it.
const ( GrantTypeTokenExchange = "urn:ietf:params:oauth:grant-type:token-exchange" // TokenTypeAccessToken is an opaque or at+jwt access token issued by the // organization — the default subject/actor type. TokenTypeAccessToken = "urn:ietf:params:oauth:token-type:access_token" // TokenTypeJWT is an at+jwt access token, or an external workload identity // token (Kubernetes, AWS, GCP, Azure, GitHub, SPIFFE) presented by a // registered agent. TokenTypeJWT = "urn:ietf:params:oauth:token-type:jwt" // TokenTypeIDToken is an OpenID Connect ID token issued by the organization // to the exchanging client. TokenTypeIDToken = "urn:ietf:params:oauth:token-type:id_token" // TokenTypeRefreshToken is a refresh token issued to the exchanging client. // It is refused as the subject when an agent acts on a user's behalf // (ActorToken is an agent access token): 400 invalid_request. TokenTypeRefreshToken = "urn:ietf:params:oauth:token-type:refresh_token" )
RFC 8693 token-exchange constants.
const ( RelationViewer = "viewer" RelationEditor = "editor" RelationOwner = "owner" RelationMember = "member" RelationAdmin = "admin" )
Common relation names, provided so the helpers below and hand-written checks agree on spelling.
const ( // ── Permissions (RBAC) — bearer-scoped, unprefixed ──────────────── RoutePermissionsCheck = "permissions.check" RoutePermissionsCheckBulk = "permissions.checkBulk" RoutePermissionsCheckAny = "permissions.checkAny" RoutePermissionsCheckAll = "permissions.checkAll" RoutePermissionsList = "permissions.list" // ── Zanzibar (ReBAC) ────────────────────────────────────────────── RouteZanzibarCheck = "zanzibar.check" RouteZanzibarExpand = "zanzibar.expand" // ── ABAC — org-scoped ───────────────────────────────────────────── RouteAbacCheck = "abac.check" RouteAbacCheckBulk = "abac.checkBulk" RouteAbacMyAttributes = "abac.myAttributes" RouteAbacSetUserAttribute = "abac.setUserAttribute" RouteAbacResourceAttributes = "abac.resourceAttributes" RouteAbacSetResourceAttribute = "abac.setResourceAttribute" RouteAbacAttributeDefinitions = "abac.attributeDefinitions" // ── OAuth 2.1 / OIDC ────────────────────────────────────────────── RouteOAuthAuthorize = "oauth.authorize" RouteOAuthToken = "oauth.token" RouteOAuthRevoke = "oauth.revoke" RouteOAuthUserInfo = "oauth.userinfo" RouteOAuthLogout = "oauth.logout" RouteOAuthLoginJSON = "oauth.loginJson" // ── Web (HTML) routes used by identifier-first sign-in ──────────── RouteWebCheckEmail = "web.checkEmail" RouteWebMagicLink = "web.magicLink" // ── Agents (identity) ───────────────────────────────────────────── RouteAgentsAsk = "agents.ask" RouteAgentsMe = "agents.me" RouteAgentsRegister = "agents.register" // ── Approvals (push-approval-for-actions) ───────────────────────── RouteApprovalsCreate = "approvals.create" RouteApprovalsStatus = "approvals.status" // ── JIT (just-in-time permissions) ──────────────────────────────── RouteJitCreateTask = "jit.createTask" RouteJitCompleteTask = "jit.completeTask" RouteJitEvaluateTask = "jit.evaluateTask" RouteJitRequest = "jit.request" RouteJitRequestStatus = "jit.requestStatus" RouteJitToken = "jit.token" RouteJitPending = "jit.pending" // ── AAuth (agent auth protocol) ─────────────────────────────────── RouteAAuthAgentToken = "aauth.agentToken" RouteAAuthAgentAuth = "aauth.agentAuth" RouteAAuthTokenRevoke = "aauth.tokenRevoke" RouteAAuthJWKS = "aauth.jwks" RouteAAuthIssuerMetadata = "aauth.issuerMetadata" RouteAAuthAgentMetadata = "aauth.agentMetadata" // ── Root discovery ──────────────────────────────────────────────── RouteWellKnownAAuthIssuer = "wellknown.aauthIssuer" )
Route names. Using constants rather than bare strings means a typo is a compile error, and every call site is greppable.
const ( JitStatusApproved = "approved" JitStatusPending = "pending" JitStatusDenied = "denied" )
JIT request statuses.
const ( TaskResultCompleted = "completed" TaskResultFailed = "failed" TaskResultCancelled = "cancelled" )
Task outcomes accepted by JitResource.EvaluateTask.
const ( ApprovalPending = "pending" ApprovalApproved = "approved" ApprovalDenied = "denied" ApprovalExpired = "expired" // ApprovalEmailFallbackSent is the status Create returns when the user // has no enrolled push device. The server sent an email notice with no // approval link instead. The result has no Token and nothing to poll. ApprovalEmailFallbackSent = "email_fallback_sent" )
Approval statuses.
const AbacMaxBulkRequests = 100
AbacMaxBulkRequests is the server's cap on one bulk check.
const DefaultBaseURL = "https://app.lumoauth.dev"
DefaultBaseURL is the LumoAuth cloud instance, used when neither WithBaseURL nor LUMOAUTH_URL supplies one.
const DefaultKid = "key-1"
DefaultKid is the key ID used when none is given, matching the JS and Python SDKs.
const JitDefaultTTL = 300 // seconds
JitDefaultTTL is the requested lifetime when a call does not specify one.
const JitMaxTTL = 900 // seconds (15 min)
JitMaxTTL is the longest lifetime the server will grant a JIT token.
const MaxDelegationDepth = 3
MaxDelegationDepth is the deepest delegation chain LumoAuth will issue tokens for (user → agent → sub-agent).
const Version = "1.0.0"
Version is the SDK version reported in the User-Agent header.
Variables ¶
var ( // ErrLumoAuth matches every error produced by this SDK. ErrLumoAuth = errors.New("lumoauth error") // ErrAPI matches any non-2xx HTTP response, including the four below. ErrAPI = errors.New("lumoauth: API error") // ErrAuthentication matches HTTP 401 responses. ErrAuthentication = errors.New("lumoauth: authentication failed") // ErrPermissionDenied matches HTTP 403 responses. ErrPermissionDenied = errors.New("lumoauth: permission denied") // ErrNotFound matches HTTP 404 responses. ErrNotFound = errors.New("lumoauth: not found") // ErrRateLimited matches HTTP 429 responses. ErrRateLimited = errors.New("lumoauth: rate limited") // ErrValidation matches client-side validation failures. ErrValidation = errors.New("lumoauth: validation failed") // ErrConfig matches missing or invalid configuration. ErrConfig = errors.New("lumoauth: configuration error") // ErrNetwork matches transport failures (no HTTP response was received). ErrNetwork = errors.New("lumoauth: network error") // ErrApprovalDenied matches an approval a human explicitly denied. ErrApprovalDenied = errors.New("lumoauth: approval denied") // ErrApprovalTimeout matches an approval that expired before a response. ErrApprovalTimeout = errors.New("lumoauth: approval timed out") // ErrApprovalNotDelivered matches an approval request that no push // device received, so nobody can approve it in this call. ErrApprovalNotDelivered = errors.New("lumoauth: approval not delivered") // ErrBudgetExceeded matches an exhausted agent budget. ErrBudgetExceeded = errors.New("lumoauth: budget exceeded") )
Sentinel errors for errors.Is. Every error returned by this SDK matches ErrLumoAuth; each also matches exactly one of the specific sentinels.
var AAuthCoveredComponents = []string{
"@method",
"@authority",
"@path",
"signature-key",
"content-digest",
"content-type",
"authorization",
}
AAuthCoveredComponents are the components the agent token endpoint requires, in order. @query is inserted after @path when the target URI carries a query string.
var Routes = map[string]Route{ RoutePermissionsCheck: {"POST", "/api/v1/authz/check"}, RoutePermissionsCheckBulk: {"POST", "/api/v1/authz/check-bulk"}, RoutePermissionsCheckAny: {"POST", "/api/v1/authz/check-any"}, RoutePermissionsCheckAll: {"POST", "/api/v1/authz/check-all"}, RoutePermissionsList: {"GET", "/api/v1/authz/permissions"}, RouteZanzibarCheck: {"POST", "/api/v1/authz/zanzibar/check"}, RouteZanzibarExpand: {"POST", "/api/v1/authz/zanzibar/expand"}, RouteAbacCheck: {"POST", orgBase + "/abac/check"}, RouteAbacCheckBulk: {"POST", orgBase + "/abac/check-bulk"}, RouteAbacMyAttributes: {"GET", orgBase + "/abac/my-attributes"}, RouteAbacSetUserAttribute: {"PUT", orgBase + "/abac/users/{userId}/attributes/{attributeSlug}"}, RouteAbacResourceAttributes: {"GET", orgBase + "/abac/resources/{resourceType}/{resourceId}/attributes"}, RouteAbacSetResourceAttribute: {"PUT", orgBase + "/abac/resources/{resourceType}/{resourceId}/attributes/{attributeSlug}"}, RouteAbacAttributeDefinitions: {"GET", orgBase + "/abac/attribute-definitions"}, RouteOAuthAuthorize: {"GET", orgBase + "/oauth/authorize"}, RouteOAuthToken: {"POST", orgBase + "/oauth/token"}, RouteOAuthRevoke: {"POST", orgBase + "/oauth/revoke"}, RouteOAuthUserInfo: {"GET", orgBase + "/oauth/userinfo"}, RouteOAuthLogout: {"GET", orgBase + "/oauth/logout"}, RouteOAuthLoginJSON: {"POST", orgBase + "/oauth/login/json"}, RouteWebCheckEmail: {"POST", "/orgs/{orgId}/check-email"}, RouteWebMagicLink: {"POST", "/orgs/{orgId}/magic-link"}, RouteAgentsAsk: {"POST", orgBase + "/agents/ask"}, RouteAgentsMe: {"GET", orgBase + "/agents/me"}, RouteAgentsRegister: {"POST", orgBase + "/agents/register"}, RouteApprovalsCreate: {"POST", orgBase + "/agents/me/approvals"}, RouteApprovalsStatus: {"GET", orgBase + "/agents/me/approvals/{token}/status"}, RouteJitCreateTask: {"POST", orgBase + "/jit/task"}, RouteJitCompleteTask: {"POST", orgBase + "/jit/task/{taskId}/complete"}, RouteJitEvaluateTask: {"POST", orgBase + "/jit/task/{taskId}/evaluate"}, RouteJitRequest: {"POST", orgBase + "/jit/request"}, RouteJitRequestStatus: {"GET", orgBase + "/jit/request/{requestId}/status"}, RouteJitToken: {"POST", orgBase + "/jit/request/{requestId}/token"}, RouteJitPending: {"GET", orgBase + "/jit/pending"}, RouteAAuthAgentToken: {"POST", orgBase + "/aauth/agent/token"}, RouteAAuthAgentAuth: {"GET", orgBase + "/aauth/agent/auth"}, RouteAAuthTokenRevoke: {"POST", orgBase + "/aauth/token/revoke"}, RouteAAuthJWKS: {"GET", orgBase + "/aauth/jwks.json"}, RouteAAuthIssuerMetadata: {"GET", orgBase + "/.well-known/aauth-issuer"}, RouteAAuthAgentMetadata: {"GET", orgBase + "/.well-known/aauth-agent"}, RouteWellKnownAAuthIssuer: {"GET", "/.well-known/aauth-issuer"}, }
Routes maps every route name to its method and path template.
Functions ¶
func BuildPath ¶
BuildPath fills `{param}` placeholders in a path template. Values are URL-escaped.
BuildPath("/orgs/{orgId}/api/v1/abac/check", map[string]string{"orgId": "acme-corp"})
// → "/orgs/acme-corp/api/v1/abac/check"
A missing or empty placeholder value is a ConfigError rather than a server-side 404: an absent org ID should fail loudly at the call site.
func BuildSignatureBase ¶
func BuildSignatureBase(components []string, values map[string]string, created int64, nonce string) string
BuildSignatureBase assembles the RFC 9421 signature base: one `"<component>": <value>` line per covered component in order, then the "@signature-params" line carrying created and nonce.
func ContentDigestSHA256 ¶
ContentDigestSHA256 computes an RFC 9530 Content-Digest header value over exact body bytes, using standard base64 (the server base64-decodes it).
func ErrorCode ¶
ErrorCode returns the LumoAuth error code carried by err (one of the Code* constants, or a server-supplied code), or "" for errors from elsewhere.
func GenerateNonce ¶
GenerateNonce returns a fresh signature nonce: base64url of 16 random bytes (128 bits), comfortably above the 12-byte floor the profile sets.
func LoadPrivateKey ¶
LoadPrivateKey parses a PEM private key for AAuth signing. Ed25519 and RSA keys are supported, matching the algorithms the server accepts.
func ParseActorChain ¶
ParseActorChain returns the `sub` of each nested `act` claim in a delegated JWT, outermost first — the direct actor, then progressively deeper sub-agents.
The token is decoded WITHOUT signature verification: this is for display and audit, never for an authorization decision.
func RouteNames ¶
func RouteNames() []string
RouteNames returns every registered route name, sorted. Useful for diagnostics and for the drift test.
func SignRequest ¶
func SignRequest(privateKeyPEM, method, targetURL string, opts SignOptions) (map[string]string, error)
SignRequest builds the RFC 9421 signature headers for a request under the AAuth profile: Content-Digest, Content-Type, Signature-Input, Signature, and — when an agent token is supplied — Agent-Auth.
headers, err := lumoauth.SignRequest(privateKeyPEM, "POST", url, lumoauth.SignOptions{
Body: body,
AgentToken: agentToken,
})
func SignSignatureBase ¶
SignSignatureBase signs a signature base and returns the base64url signature. Ed25519 keys sign directly; RSA keys use RSA-PSS with SHA-512 and a digest-length salt, matching the server's dispatch.
func SignatureParams ¶
SignatureParams renders the `(…);created=…;nonce="…"` string shared by the signature base and the Signature-Input header.
func StatusCode ¶
StatusCode returns the HTTP status carried by err, or 0 if the error did not come from an HTTP response.
func TokenSubject ¶
TokenSubject returns a JWT's `sub` (principal) claim.
The token is decoded WITHOUT signature verification — display and audit only.
Types ¶
type AAuthAgentMetadata ¶
type AAuthAgentMetadata struct {
Agent string `json:"agent"`
JWKSURI string `json:"jwks_uri,omitempty"`
RedirectURIs []string `json:"redirect_uris,omitempty"`
Name string `json:"name,omitempty"`
}
AAuthAgentMetadata describes a registered agent.
type AAuthClaims ¶
type AAuthClaims struct {
Issuer string `json:"iss"`
Audience string `json:"aud"`
Expires int64 `json:"exp"`
IssuedAt int64 `json:"iat"`
JTI string `json:"jti"`
Subject string `json:"sub,omitempty"`
// Agent identifies the agent the token was issued to.
Agent string `json:"agent,omitempty"`
// AgentDelegate is set when the agent acts for another agent.
AgentDelegate string `json:"agent_delegate,omitempty"`
Scope string `json:"scope,omitempty"`
// Confirmation binds the token to the holder's key (RFC 7800).
Confirmation struct {
JWK JWK `json:"jwk"`
} `json:"cnf"`
// Act records the delegation chain, when there is one.
Act map[string]any `json:"act,omitempty"`
// Raw is every claim in the token, including ones not modelled above.
Raw map[string]any `json:"-"`
}
AAuthClaims are the claims carried by an `auth+jwt`.
func VerifyAuthToken ¶
func VerifyAuthToken(ctx context.Context, token string, opts VerifyOptions) (*AAuthClaims, error)
VerifyAuthToken verifies an AAuth auth token against the issuing organization's JWKS and returns its claims.
claims, err := lumoauth.VerifyAuthToken(ctx, bearer, lumoauth.VerifyOptions{
Issuer: "https://app.lumoauth.dev/orgs/acme-corp/api/v1",
Resource: "https://api.example.com",
})
if err != nil {
return err
}
// Then enforce proof-of-possession over the incoming request:
if err := claims.VerifyProofOfPossession(r, body); err != nil {
return err
}
HMAC and "none" algorithms are always rejected, and the algorithm must match the key type published in the JWKS.
Example ¶
The resource-server side: verify the token, then prove the caller holds the key it is bound to.
package main
import (
"fmt"
"net/http"
lumoauth "github.com/lumoauth/lumo-auth-go"
)
func main() {
handler := func(w http.ResponseWriter, r *http.Request, body []byte) {
token := r.Header.Get("Authorization")[len("Bearer "):]
claims, err := lumoauth.VerifyAuthToken(r.Context(), token, lumoauth.VerifyOptions{
Issuer: "https://app.lumoauth.dev/orgs/acme-corp/api/v1",
Resource: "https://api.example.com",
})
if err != nil {
http.Error(w, "invalid token", http.StatusUnauthorized)
return
}
// AAuth tokens are proof-of-possession: verifying the JWT alone
// would let a stolen token through.
if err := claims.VerifyProofOfPossession(r, body); err != nil {
http.Error(w, "invalid signature", http.StatusUnauthorized)
return
}
if !claims.HasScope("read") {
http.Error(w, "insufficient scope", http.StatusForbidden)
return
}
fmt.Fprintf(w, "hello %s", claims.Agent)
}
_ = handler
}
Output:
func (*AAuthClaims) HasScope ¶
func (c *AAuthClaims) HasScope(scope string) bool
HasScope reports whether the token carries a scope.
func (*AAuthClaims) Scopes ¶
func (c *AAuthClaims) Scopes() []string
Scopes splits the space-separated scope claim.
func (*AAuthClaims) VerifyProofOfPossession ¶
func (c *AAuthClaims) VerifyProofOfPossession(r *http.Request, body []byte) error
VerifyProofOfPossession checks that an incoming request was signed by the key the token is bound to (cnf.jwk) — the second half of AAuth verification, without which a stolen token would be replayable.
body must be the exact bytes the request carried, since Content-Digest is computed over them.
type AAuthClient ¶
type AAuthClient struct {
// contains filtered or unexported fields
}
AAuthClient speaks the AAuth (Agent Auth) protocol, which extends OAuth 2.1 with cryptographic agent identity, proof-of-possession tokens, and RFC 9421 HTTP message signing.
client, err := lumoauth.NewAAuthClient(lumoauth.AAuthConfig{
AgentIdentifier: "https://my-agent.example.com",
PrivateKeyPEM: os.Getenv("AGENT_PRIVATE_KEY"),
OrgID: "acme-corp",
})
if err != nil {
return err
}
result, err := client.RequestAuthToken(ctx, lumoauth.AuthTokenParams{
ResourceToken: resourceToken,
Scope: "read write",
AgentToken: agentToken,
})
if err != nil {
return err
}
if result.AuthorizationRequired {
// Redirect the user to result.AuthorizationURI, then ExchangeCode.
}
For OAuth client-credentials agents (no signing key) use Agent instead.
func NewAAuthClient ¶
func NewAAuthClient(cfg AAuthConfig) (*AAuthClient, error)
NewAAuthClient builds an AAuth client and parses the agent's private key.
Example ¶
An AAuth agent signs its requests with its own key.
package main
import (
"context"
"fmt"
"log"
"net/http"
"os"
lumoauth "github.com/lumoauth/lumo-auth-go"
)
func main() {
client, err := lumoauth.NewAAuthClient(lumoauth.AAuthConfig{
AgentIdentifier: "https://my-agent.example.com",
PrivateKeyPEM: os.Getenv("AGENT_PRIVATE_KEY"),
OrgID: "acme-corp",
})
if err != nil {
log.Fatal(err)
}
result, err := client.RequestAuthToken(context.Background(), lumoauth.AuthTokenParams{
ResourceToken: os.Getenv("RESOURCE_TOKEN"),
Scope: "read write",
AgentToken: os.Getenv("AGENT_TOKEN"),
})
if err != nil {
log.Fatal(err)
}
if result.AuthorizationRequired {
fmt.Println("send the user to:", result.AuthorizationURI)
return
}
response, err := client.SignedRequest(context.Background(),
http.MethodGet, "https://api.example.com/v1/data", result.AuthToken, nil)
if err != nil {
log.Fatal(err)
}
defer response.Body.Close()
}
Output:
func (*AAuthClient) AgentIdentifier ¶
func (c *AAuthClient) AgentIdentifier() string
AgentIdentifier returns the agent's identity URL.
func (*AAuthClient) BaseURL ¶
func (c *AAuthClient) BaseURL() string
BaseURL returns the LumoAuth instance URL.
func (*AAuthClient) ConsentURL ¶
func (c *AAuthClient) ConsentURL(requestToken string) (string, error)
ConsentURL builds the user-consent URL for a pending request token. Prefer the AuthorizationURI returned by RequestAuthToken when present.
func (*AAuthClient) DiscoverAgents ¶
func (c *AAuthClient) DiscoverAgents(ctx context.Context) ([]AAuthAgentMetadata, error)
DiscoverAgents fetches metadata for the organization's active agents.
func (*AAuthClient) DiscoverIssuer ¶
func (c *AAuthClient) DiscoverIssuer(ctx context.Context) (*AAuthIssuerMetadata, error)
DiscoverIssuer fetches the organization's AAuth issuer metadata.
func (*AAuthClient) DiscoverResource ¶
func (c *AAuthClient) DiscoverResource(ctx context.Context, resourceURL string) ([]AAuthResourceMetadata, error)
DiscoverResource fetches a resource server's AAuth metadata from {resourceURL}/.well-known/aauth-resource.
func (*AAuthClient) ExchangeCode ¶
func (c *AAuthClient) ExchangeCode(ctx context.Context, code, redirectURI, agentToken string) (*AAuthTokenResponse, error)
ExchangeCode trades an authorization code for tokens after user consent (request_type=code).
redirectURI must be the exact URI the code was delivered to; the server redeems codes atomically and rejects a mismatch.
func (*AAuthClient) ExchangeToken ¶
func (c *AAuthClient) ExchangeToken(ctx context.Context, authToken, resourceToken, agentToken string) (*AAuthTokenResponse, error)
ExchangeToken performs a multi-hop exchange (request_type=exchange): trade an upstream auth token plus a downstream resource token for a new auth token carrying an `act` actor chain. The agent must be permitted to exchange tokens.
func (*AAuthClient) Issuer ¶
func (c *AAuthClient) Issuer() string
Issuer returns the organization's AAuth issuer URL — {baseURL}/orgs/{orgID}/api/v1 — which is the `iss` value in issued tokens and the base for JWKS discovery.
func (*AAuthClient) JWKS ¶
func (c *AAuthClient) JWKS(ctx context.Context) (*JWKS, error)
JWKS fetches the organization's AAuth signing keys — the keys that verify issued auth tokens.
func (*AAuthClient) OrgID ¶
func (c *AAuthClient) OrgID() string
OrgID returns the organization slug.
func (*AAuthClient) PublicJWK ¶
func (c *AAuthClient) PublicJWK() (JWK, error)
PublicJWK returns the agent's public key as a JWK, tagged with its kid.
func (*AAuthClient) PublicJWKThumbprint ¶
func (c *AAuthClient) PublicJWKThumbprint() (string, error)
PublicJWKThumbprint returns the RFC 7638 thumbprint of the agent's public key — the `jkt` value that binds tokens to this key.
func (*AAuthClient) Refresh ¶
func (c *AAuthClient) Refresh(ctx context.Context, params RefreshParams) (*AAuthTokenResponse, error)
Refresh renews an auth token (request_type=refresh). Refresh tokens are not rotated, so the same one stays valid for the grant's lifetime.
func (*AAuthClient) RequestAuthToken ¶
func (c *AAuthClient) RequestAuthToken(ctx context.Context, params AuthTokenParams) (*AAuthTokenResponse, error)
RequestAuthToken asks for an auth token (AAuth Flow 2, direct authorization).
When the server requires user consent it returns a response with AuthorizationRequired set: redirect the user to AuthorizationURI, then call ExchangeCode with the code delivered to your redirect URI.
func (*AAuthClient) Revoke ¶
func (c *AAuthClient) Revoke(ctx context.Context, token, tokenType, agentToken string) error
Revoke invalidates an auth token (by its `jti`) or a refresh token (by value). It succeeds whether or not the token existed — the server does not reveal that.
func (*AAuthClient) SignRequest ¶
func (c *AAuthClient) SignRequest(method, targetURL string, opts SignOptions) (map[string]string, error)
SignRequest builds RFC 9421 signature headers with this agent's key.
func (*AAuthClient) SignedRequest ¶
func (c *AAuthClient) SignedRequest(ctx context.Context, method, targetURL, authToken string, body any) (*http.Response, error)
SignedRequest makes a signed, authenticated request to a protected resource.
The request carries the auth token as a Bearer credential AND an RFC 9421 signature proving possession of the key bound in the token's cnf.jwk. The signature covers the authorization component, so the resource server verifies both together.
The caller owns the returned response and must close its body.
type AAuthConfig ¶
type AAuthConfig struct {
// AgentIdentifier is the HTTPS URL uniquely identifying the agent,
// e.g. "https://my-agent.example.com". Required.
AgentIdentifier string
// PrivateKeyPEM is the agent's Ed25519 (PKCS#8) or RSA private key.
// Required.
PrivateKeyPEM string
// BaseURL is the LumoAuth instance. Defaults to $LUMOAUTH_URL, then
// DefaultBaseURL.
BaseURL string
// OrgID is the organization slug. Defaults to $LUMOAUTH_ORG_ID.
OrgID string
// Kid identifies the key in the JWKS registered with LumoAuth.
// Defaults to DefaultKid.
Kid string
// Timeout is the per-request timeout. Default: 30s.
Timeout time.Duration
// HTTPClient overrides the *http.Client used for every request.
HTTPClient *http.Client
// SkipCertValidation disables TLS verification. Local development only.
SkipCertValidation bool
}
AAuthConfig configures an AAuthClient.
type AAuthIssuerMetadata ¶
type AAuthIssuerMetadata struct {
Issuer string `json:"issuer"`
AAuthVersion string `json:"aauth_version,omitempty"`
JWKSURI string `json:"jwks_uri,omitempty"`
AgentTokenEndpoint string `json:"agent_token_endpoint,omitempty"`
AgentAuthEndpoint string `json:"agent_auth_endpoint,omitempty"`
AgentSigningAlgsSupported []string `json:"agent_signing_algs_supported,omitempty"`
TokenSigningAlgsSupported []string `json:"token_signing_algs_supported,omitempty"`
RequestTypesSupported []string `json:"request_types_supported,omitempty"`
ScopesSupported []string `json:"scopes_supported,omitempty"`
}
AAuthIssuerMetadata describes an AAuth authorization server.
type AAuthResourceMetadata ¶
type AAuthResourceMetadata struct {
Resource string `json:"resource"`
JWKSURI string `json:"jwks_uri,omitempty"`
ResourceTokenEndpoint string `json:"resource_token_endpoint,omitempty"`
SupportedScopes []string `json:"supported_scopes,omitempty"`
}
AAuthResourceMetadata describes a protected resource server.
type AAuthTokenResponse ¶
type AAuthTokenResponse struct {
// RequestType echoes the flow: auth, code, exchange, or refresh.
RequestType string
// AuthToken is the `auth+jwt` to present to the resource.
AuthToken string
// ExpiresIn is the token's lifetime in seconds.
ExpiresIn int
// TokenType is normally "auth+jwt".
TokenType string
// RefreshToken is present when the grant includes one.
RefreshToken string
// AuthorizationRequired reports that a human must consent first.
AuthorizationRequired bool
// RequestToken identifies the pending request (600s TTL).
RequestToken string
// AuthorizationURI is the consent page to redirect the user to.
AuthorizationURI string
}
AAuthTokenResponse is a successful response from the agent token endpoint. When the server requires user consent instead, AuthorizationRequired is set and the token fields are empty.
type APIConfig ¶
type APIConfig struct {
// BaseURL is the server URL, without a trailing slash.
BaseURL string
// DefaultHeader holds exactly one credential header — X-API-Key or
// Authorization — never both.
DefaultHeader map[string]string
// HTTPClient is this client's underlying *http.Client.
HTTPClient *http.Client
}
APIConfig carries everything needed to point the generated OpenAPI client (github.com/lumoauth/api-clients/go) at this instance.
type APIError ¶
type APIError struct {
*BaseError
// StatusCode is the HTTP status of the response.
StatusCode int
// Body is the decoded response body: map[string]any for JSON objects,
// a string for anything else, nil for an empty body.
Body any
// RetryAfter carries the Retry-After hint on 429 responses (0 if absent).
RetryAfter time.Duration
// RequiredScopes lists the scopes a 403 scope refusal names in
// details.required_scopes; nil when the body has none. The server sends
//
// {"error":"forbidden","message":"Insufficient scope: …","status":403,
// "details":{"required_scopes":["authz:read"],"granted_scopes":[…]}}
//
// when the credential lacks a user-delegated scope the route needs.
RequiredScopes []string
}
APIError is returned when the server responds with a non-2xx status.
func AsAPIError ¶
AsAPIError extracts the *APIError from an error chain, reporting whether one was present. Shorthand for errors.As.
type AbacAttributeDefinition ¶
type AbacAttributeDefinition struct {
ID string `json:"id"`
Name string `json:"name"`
Slug string `json:"slug"`
Description string `json:"description,omitempty"`
AttributeType string `json:"attributeType,omitempty"` // user | resource | environment
DataType string `json:"dataType,omitempty"` // string | number | boolean | array | date
ValidationRules map[string]any `json:"validationRules,omitempty"`
IsActive bool `json:"isActive,omitempty"`
}
AbacAttributeDefinition describes an attribute the org has defined.
type AbacBulkDecision ¶
type AbacBulkDecision struct {
Results []AbacDecision `json:"results"`
}
AbacBulkDecision is the result of a bulk ABAC check, in request order.
type AbacCheckParams ¶
type AbacCheckParams struct {
// ResourceType is the kind of thing being accessed ("document"). Required.
ResourceType string
// Action is the operation ("read", "delete"). Required.
Action string
// ResourceID identifies the specific instance, when there is one.
ResourceID string
// Context supplies environment attributes for the evaluation. The SDK
// sends it as the request's "environment" object, which the policy
// engine reads. The keys ip, userAgent, requestMethod and requestPath
// always describe the request that LumoAuth received; values that you
// pass under those names are kept under "pep" instead, so forward the
// end user's IP as {"pep": {"ip": "10.0.0.1"}}.
//
// In CheckBulk the server applies one environment to every check, so
// every entry must carry the same Context (or none).
Context map[string]any
}
AbacCheckParams describes one ABAC evaluation.
type AbacDecision ¶
type AbacDecision struct {
Allowed bool `json:"allowed"`
Reason string `json:"reason,omitempty"`
// MatchedPolicies lists the policies that applied. A caller without the
// policies.view permission receives only each policy's ID and Name.
MatchedPolicies []AbacMatchedPolicy `json:"matchedPolicies,omitempty"`
// ResourceType, Action and ResourceID echo the evaluated target.
ResourceType string `json:"resourceType,omitempty"`
Action string `json:"action,omitempty"`
ResourceID string `json:"resourceId,omitempty"`
// Index is the position of this result in a bulk request (0 for a
// single check).
Index int `json:"index,omitempty"`
// Error is set on a bulk result whose entry the server could not
// evaluate; Allowed is then false.
Error string `json:"error,omitempty"`
// Raw is the complete decoded decision, including the evaluation
// context the server echoed back.
Raw map[string]any `json:"-"`
}
AbacDecision is the outcome of evaluating ABAC policies for one resource/action pair.
func (*AbacDecision) UnmarshalJSON ¶
func (d *AbacDecision) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes the typed fields and retains the whole object.
type AbacMatchedPolicy ¶
type AbacMatchedPolicy struct {
ID string `json:"id"`
Name string `json:"name"`
Effect string `json:"effect"` // "allow" or "deny"
Priority int `json:"priority"`
}
AbacMatchedPolicy is a policy that contributed to an ABAC decision.
type AbacResource ¶
type AbacResource struct {
// contains filtered or unexported fields
}
AbacResource covers attribute-based access control: policy evaluation from user, resource, and environment attributes, plus attribute management.
ABAC is org-scoped, so the client needs an org ID.
A user access token needs the abac:read scope for checks and attribute reads, and abac:write to set attributes. Organization API keys are not accepted on the ABAC routes.
Note the wire format uses camelCase keys (resourceType, resourceId); this resource takes Go-shaped params and translates.
func (*AbacResource) AttributeDefinitions ¶
func (r *AbacResource) AttributeDefinitions(ctx context.Context, attributeType string) ([]AbacAttributeDefinition, error)
AttributeDefinitions lists the org's attribute definitions. Pass an empty attributeType for all of them.
func (*AbacResource) Check ¶
func (r *AbacResource) Check(ctx context.Context, params AbacCheckParams) (*AbacDecision, error)
Check evaluates the policies for one resource/action pair and returns the full decision, including the policies that matched.
Example ¶
ABAC decisions carry the policies that produced them. ABAC routes refuse an organization API key: they need a user access token with the abac:read scope (abac:write for writes).
package main
import (
"context"
"fmt"
"log"
"os"
lumoauth "github.com/lumoauth/lumo-auth-go"
)
func main() {
client, _ := lumoauth.New(
lumoauth.WithAccessToken(os.Getenv("LUMOAUTH_ACCESS_TOKEN")), // a user token with abac:read
lumoauth.WithOrgID("acme-corp"),
)
decision, err := client.Abac.Check(context.Background(), lumoauth.AbacCheckParams{
ResourceType: "document",
Action: "read",
ResourceID: "doc-123",
Context: map[string]any{
"pep": map[string]any{"ip": "10.0.0.1"}, // sent as the request's environment
},
})
if err != nil {
log.Fatal(err)
}
if !decision.Allowed {
fmt.Println("denied:", decision.Reason)
return
}
for _, policy := range decision.MatchedPolicies {
fmt.Printf("matched %s (%s)\n", policy.Name, policy.Effect)
}
}
Output:
func (*AbacResource) CheckBulk ¶
func (r *AbacResource) CheckBulk(ctx context.Context, checks []AbacCheckParams) ([]AbacDecision, error)
CheckBulk evaluates up to AbacMaxBulkRequests pairs in one round trip. Results come back in request order.
The server applies one environment to every check in a bulk call. Give every entry the same Context, or none; entries with different Context values return a ValidationError before any request is sent.
func (*AbacResource) IsAllowed ¶
func (r *AbacResource) IsAllowed(ctx context.Context, params AbacCheckParams) (bool, error)
IsAllowed is Check reduced to a boolean.
func (*AbacResource) MyAttributes ¶
MyAttributes returns every ABAC attribute for the authenticated user, built-in and custom.
func (*AbacResource) ResourceAttributes ¶
func (r *AbacResource) ResourceAttributes(ctx context.Context, resourceType, resourceID string) (map[string]any, error)
ResourceAttributes returns the ABAC attributes attached to one resource.
func (*AbacResource) SetResourceAttribute ¶
func (r *AbacResource) SetResourceAttribute(ctx context.Context, resourceType, resourceID, attributeSlug string, value any) error
SetResourceAttribute sets one attribute value on a resource.
func (*AbacResource) SetUserAttribute ¶
func (r *AbacResource) SetUserAttribute(ctx context.Context, userID, attributeSlug string, value any) error
SetUserAttribute sets one attribute value on a user.
type Agent ¶
type Agent struct {
// Agents covers ask/isAllowed, self-inspection, and registration.
Agents *AgentsResource
// Jit covers Just-in-Time permissions.
Jit *JitResource
// Delegation covers RFC 8693 delegation primitives.
Delegation *DelegationResource
// Approvals covers push-approval-for-agent-actions.
Approvals *ApprovalsResource
// Mcp covers token exchange for secured MCP servers.
Mcp *McpResource
// Permissions covers RBAC checks for the agent's own principal.
Permissions *PermissionsResource
// contains filtered or unexported fields
}
Agent is the client for an AI agent acting under its own identity.
It owns an OAuth 2.0 client-credentials token and refreshes it transparently, so no call has to be preceded by an explicit login:
agent, err := lumoauth.NewAgent(lumoauth.AgentConfig{}) // reads env vars
if err != nil {
return err
}
allowed, err := agent.IsAllowed(ctx, "document.read", map[string]any{"id": "doc_99"})
if err != nil {
return err
}
approval, err := agent.Approvals.Require(ctx, lumoauth.ApprovalParams{
TaskID: "wire-001", Reason: "Wire $4,500 to INV-7741",
Impact: lumoauth.ImpactHigh, OnBehalfOf: "ada@acme.com",
}, nil)
For the AAuth protocol — cryptographic agent identity and RFC 9421 message signing — use AAuthClient instead.
An Agent is safe for concurrent use; concurrent callers share one in-flight token request.
func NewAgent ¶
func NewAgent(cfg AgentConfig) (*Agent, error)
NewAgent builds an Agent from config and environment. It returns a *ConfigError when the client credentials cannot be resolved; no network call is made until the first request.
Example ¶
An agent checks whether it may act before acting.
package main
import (
"context"
"log"
lumoauth "github.com/lumoauth/lumo-auth-go"
)
func main() {
agent, err := lumoauth.NewAgent(lumoauth.AgentConfig{})
if err != nil {
log.Fatal(err)
}
ctx := context.Background()
allowed, err := agent.IsAllowed(ctx, "document.read", map[string]any{"id": "doc_99"})
if err != nil {
log.Fatal(err)
}
if !allowed {
return
}
// ... read the document
}
Output:
func (*Agent) AccessToken ¶
AccessToken returns a valid access token, authenticating or refreshing when the cached one is missing or within a minute of expiry. It doubles as the TokenProvider for the underlying client.
Concurrent callers collapse onto a single token request: the first one through refreshes while the rest wait, then all read the fresh token.
func (*Agent) Ask ¶
func (a *Agent) Ask(ctx context.Context, action string, actionContext map[string]any) (*AgentAskResult, error)
Ask asks whether the agent may perform an action — the preflight check before an LLM tool call.
func (*Agent) Authenticate ¶
Authenticate performs the client-credentials grant and caches the token.
Every API call does this on demand, so call it directly only to fail fast at startup or to request non-default scopes.
func (*Agent) Budget ¶
func (a *Agent) Budget(ctx context.Context) (*AgentBudget, error)
Budget returns the agent's budget policy. It is never nil.
func (*Agent) Capabilities ¶
Capabilities returns the agent's capability slugs.
func (*Agent) CheckBudget ¶
CheckBudget returns an error matching ErrBudgetExceeded when the agent's daily token budget is spent, and nil otherwise. Budget state is cached with the rest of the agent info — call Info(ctx, true) first for a live reading.
func (*Agent) Client ¶
Client returns the underlying general-purpose client, for the namespaces the agent does not surface directly (Zanzibar, ABAC, Auth) and the Do escape hatch.
func (*Agent) ClientSecret ¶
ClientSecret returns the agent's OAuth client secret. Needed by DelegationChain for the confidential-client consent exchange.
func (*Agent) Do ¶
Do sends an authenticated request to any endpoint and decodes the JSON response into out (nil to discard). See Client.Do.
func (*Agent) DoRaw ¶
DoRaw is Do without response handling: the caller owns the *http.Response and must close its body.
func (*Agent) HasCapability ¶
HasCapability reports whether the agent holds a capability.
func (*Agent) Identity ¶
Identity returns the agent's own identity, capabilities, and workspace, caching the result. Pass refresh to force a fetch.
func (*Agent) Info ¶
Info returns the agent's UserInfo claims (capabilities, budget policy), caching the result. Pass refresh to force a fetch.
func (*Agent) IsAllowed ¶
func (a *Agent) IsAllowed(ctx context.Context, action string, actionContext map[string]any) (bool, error)
IsAllowed is Ask reduced to a boolean.
func (*Agent) MCPToken ¶
MCPToken exchanges the agent's token for one bound to a secured MCP server. serverID is the server's https URL, e.g. "https://mcp.example.com/mcp"; see McpResource.Token.
func (*Agent) RedirectURI ¶
RedirectURI returns the configured OAuth callback URL.
func (*Agent) Register ¶
func (a *Agent) Register(ctx context.Context, params RegisterParams) (*AgentRegistration, error)
Register creates or updates this agent's record in the organization directory, using its own client ID.
func (*Agent) RequireCapability ¶
RequireCapability is the guard for a capability-gated method: it returns nil when the agent holds the capability, and an error matching ErrPermissionDenied when it does not.
func (s *Service) SearchWeb(ctx context.Context, query string) error {
if err := s.agent.RequireCapability(ctx, "tool:search_web"); err != nil {
return err
}
…
}
Example ¶
Capability gating at the top of a tool implementation.
package main
import (
"context"
"errors"
"fmt"
"log"
lumoauth "github.com/lumoauth/lumo-auth-go"
)
func main() {
agent, err := lumoauth.NewAgent(lumoauth.AgentConfig{})
if err != nil {
log.Fatal(err)
}
if err := agent.RequireCapability(context.Background(), "tool:search_web"); err != nil {
if errors.Is(err, lumoauth.ErrPermissionDenied) {
fmt.Println("this agent is not registered for web search")
return
}
log.Fatal(err)
}
// ... run the search
}
Output:
func (*Agent) TokenScopes ¶
TokenScopes returns the scopes granted by the last authentication.
type AgentAskResult ¶
type AgentAskResult struct {
Allowed bool `json:"allowed"`
Action string `json:"action,omitempty"`
Reason string `json:"reason,omitempty"`
AuditID string `json:"audit_id,omitempty"`
Context map[string]any `json:"context,omitempty"`
// Raw is the complete decoded decision.
Raw map[string]any `json:"-"`
}
AgentAskResult is the decision returned by the Ask API.
func (*AgentAskResult) UnmarshalJSON ¶
func (r *AgentAskResult) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes the typed fields and retains the whole object.
type AgentBudget ¶
type AgentBudget struct {
MaxTokensPerDay int `json:"max_tokens_per_day,omitempty"`
TokensUsedToday int `json:"tokens_used_today,omitempty"`
// Raw is the complete decoded policy.
Raw map[string]any `json:"-"`
}
AgentBudget is the budget policy attached to an agent.
func (*AgentBudget) Exhausted ¶
func (b *AgentBudget) Exhausted() bool
Exhausted reports whether the daily token budget has been reached. A policy without a daily cap is never exhausted.
func (*AgentBudget) UnmarshalJSON ¶
func (b *AgentBudget) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes the typed fields and retains the whole object.
type AgentConfig ¶
type AgentConfig struct {
// BaseURL is the LumoAuth instance. Defaults to $LUMOAUTH_URL, then
// DefaultBaseURL.
BaseURL string
// OrgID is the organization slug. Defaults to $LUMOAUTH_ORG_ID.
OrgID string
// ClientID is the agent's OAuth client. Defaults to $AGENT_CLIENT_ID.
ClientID string
// ClientSecret is the agent's OAuth secret. Defaults to
// $AGENT_CLIENT_SECRET.
ClientSecret string
// Scopes are requested at authentication. Leave empty to receive the
// agent's registered defaults.
Scopes []string
// RedirectURI is the OAuth callback for the delegation consent flow.
RedirectURI string
// Timeout is the per-request timeout. Default: 30s.
Timeout time.Duration
// HTTPClient overrides the *http.Client used for every request.
HTTPClient *http.Client
// SkipCertValidation disables TLS verification. Local development only.
SkipCertValidation bool
}
AgentConfig configures an Agent. Every field falls back to an environment variable when left empty.
type AgentIdentity ¶
type AgentIdentity struct {
Identity map[string]any `json:"identity,omitempty"`
Capabilities []string `json:"capabilities,omitempty"`
Workspace map[string]any `json:"workspace,omitempty"`
// Raw is the complete decoded response.
Raw map[string]any `json:"-"`
}
AgentIdentity is the agent's own identity, capabilities, and workspace.
func (*AgentIdentity) ID ¶
func (i *AgentIdentity) ID() string
ID returns the agent's identity ID, or "" when the server did not send one.
func (*AgentIdentity) UnmarshalJSON ¶
func (i *AgentIdentity) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes the typed fields and retains the whole object.
type AgentRegistration ¶
type AgentRegistration struct {
AgentID string `json:"agent_id,omitempty"`
ClientID string `json:"client_id,omitempty"`
Name string `json:"name,omitempty"`
Status string `json:"status,omitempty"`
// Raw is the complete decoded response.
Raw map[string]any `json:"-"`
}
AgentRegistration is the response to registering an agent.
func (*AgentRegistration) UnmarshalJSON ¶
func (r *AgentRegistration) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes the typed fields and retains the whole object.
type AgentsResource ¶
type AgentsResource struct {
// contains filtered or unexported fields
}
AgentsResource covers agent identity: the Ask API for preflight authorization, self-inspection, and registration.
func (*AgentsResource) Ask ¶
func (r *AgentsResource) Ask(ctx context.Context, action string, actionContext map[string]any) (*AgentAskResult, error)
Ask asks whether the agent may perform an action. It is the preflight check to run before an LLM tool call, and it writes an audit record whichever way the decision goes.
The keys ip, userAgent, requestMethod and requestPath in actionContext always describe the request LumoAuth received. A value you pass under one of those names is kept under pep instead, as in ABAC.
decision, err := client.Agents.Ask(ctx, "document.read", map[string]any{"id": "doc_99"})
if err != nil {
return err
}
if !decision.Allowed {
return fmt.Errorf("refused: %s", decision.Reason)
}
func (*AgentsResource) Budget ¶
func (r *AgentsResource) Budget(ctx context.Context) (*AgentBudget, error)
Budget returns the agent's budget policy. The result is never nil: an agent with no policy gets an empty one, which reports Exhausted() false.
func (*AgentsResource) Capabilities ¶
func (r *AgentsResource) Capabilities(ctx context.Context) ([]string, error)
Capabilities returns the capability slugs granted to the agent.
func (*AgentsResource) Info ¶
func (r *AgentsResource) Info(ctx context.Context) (*UserInfo, error)
Info returns the agent's claims from the UserInfo endpoint, which carries capabilities and the budget policy for agent principals.
func (*AgentsResource) IsAllowed ¶
func (r *AgentsResource) IsAllowed(ctx context.Context, action string, actionContext map[string]any) (bool, error)
IsAllowed is Ask reduced to a boolean.
func (*AgentsResource) Me ¶
func (r *AgentsResource) Me(ctx context.Context) (*AgentIdentity, error)
Me returns the calling agent's own identity, capabilities, and workspace.
For an agent credential, Capabilities lists the agent's capability roles. A user access token without the authz:read scope gets an empty list.
func (*AgentsResource) Register ¶
func (r *AgentsResource) Register(ctx context.Context, params RegisterParams) (*AgentRegistration, error)
Register creates or updates the agent's record in the organization directory.
type ApprovalError ¶
type ApprovalError struct {
*BaseError
// Approval is the last observed approval payload, for audit. It is nil
// when the request was not delivered.
Approval *ApprovalResult
// Reason is set when Code is CodeApprovalNotDelivered:
// ApprovalReasonEmailFallbackSent or ApprovalReasonNoEnrolledDevice.
Reason string
// TaskID is the task the request named, when the server echoed it.
TaskID string
}
ApprovalError is returned when a push approval was denied by a human (ErrApprovalDenied), expired before anyone responded (ErrApprovalTimeout), or never reached a push device (ErrApprovalNotDelivered). Code tells the three apart: CodeApprovalDenied, CodeApprovalTimeout or CodeApprovalNotDelivered.
type ApprovalImpact ¶
type ApprovalImpact string
ApprovalImpact is the severity tier of an approval request; it drives the visual treatment on the approver's phone.
const ( ImpactLow ApprovalImpact = "low" ImpactMedium ApprovalImpact = "medium" ImpactHigh ApprovalImpact = "high" ImpactCritical ApprovalImpact = "critical" )
Approval impact tiers.
func (ApprovalImpact) Valid ¶
func (i ApprovalImpact) Valid() bool
Valid reports whether the impact is one the server accepts.
type ApprovalParams ¶
type ApprovalParams struct {
// TaskID identifies the task the agent is operating against. Required.
TaskID string
// Reason is the description shown on the approver's phone. Required.
Reason string
// OnBehalfOf is the user the agent is acting for — email or user ID.
// Required.
OnBehalfOf string
// Impact is the severity tier. Defaults to ImpactMedium.
Impact ApprovalImpact
// Meta carries structured fields (vendor, amount, …) shown to the user.
Meta map[string]any
}
ApprovalParams describes an approval request.
type ApprovalResult ¶
type ApprovalResult struct {
// Status is "pending", "approved", "denied", or "expired". Create can
// also return ApprovalEmailFallbackSent, with an empty Token.
Status string `json:"status"`
// Message is the server's explanation, when it sends one.
Message string `json:"message,omitempty"`
// Token is the approval token; present it as the credential for the
// side-effecting call the approval authorises.
Token string `json:"approval_token,omitempty"`
TaskID string `json:"task_id,omitempty"`
Impact ApprovalImpact `json:"impact,omitempty"`
Reason string `json:"reason,omitempty"`
ExpiresAt string `json:"expires_at,omitempty"`
RespondedAt string `json:"responded_at,omitempty"`
ApprovedBy *Approver `json:"approved_by,omitempty"`
}
ApprovalResult is the state of a push-approval request.
func (*ApprovalResult) Approved ¶
func (r *ApprovalResult) Approved() bool
Approved reports whether a human approved the action.
type ApprovalsResource ¶
type ApprovalsResource struct {
// contains filtered or unexported fields
}
ApprovalsResource covers push-approval-for-agent-actions.
The headline call is Require: when an agent is about to do something irreversible — wire money, delete data, email customers — it asks first, a push lands on the user's phone with the context, and the call returns once a human decides.
func (*ApprovalsResource) Create ¶
func (r *ApprovalsResource) Create(ctx context.Context, params ApprovalParams) (*ApprovalResult, error)
Create opens an approval request and returns immediately with the pending approval, whose Token identifies it.
When the user has no enrolled push device, the server emails a plain notice with no approval link and answers 202. Create then returns a result with Status ApprovalEmailFallbackSent and an empty Token. Nothing can be polled, and the action is not approved. Tell the user to check their email or enrol a device. The server gives the same answer for an unknown user, so the endpoint does not reveal who has an account.
When the user has no device and the email could not be sent either, the server answers 428. Create returns an *ApprovalError with Code CodeApprovalNotDelivered and Reason ApprovalReasonNoEnrolledDevice.
A portal test token is refused with 403 test_token_not_accepted.
func (*ApprovalsResource) Require ¶
func (r *ApprovalsResource) Require(ctx context.Context, params ApprovalParams, opts *WaitOptions) (*ApprovalResult, error)
Require opens an approval request and blocks until a human decides.
It returns an error for anything other than approval, so the happy path reads as a guard:
approval, err := client.Approvals.Require(ctx, lumoauth.ApprovalParams{
TaskID: "wire-2026-05-07-001",
Reason: "Wire $4,500 to vendor INV-7741",
Impact: lumoauth.ImpactHigh,
OnBehalfOf: "ada@acme.com",
}, nil)
if err != nil {
return err // denied, expired, timed out, or not delivered
}
// approval.Token authorises the side-effecting call.
Use errors.Is with ErrApprovalDenied, ErrApprovalTimeout or ErrApprovalNotDelivered to tell the outcomes apart; the *ApprovalError carries the final payload for audit. When no push device received the request, the error has Code CodeApprovalNotDelivered and a Reason of ApprovalReasonEmailFallbackSent or ApprovalReasonNoEnrolledDevice. Require does not poll in that case, and it never treats it as approval. To handle a denial without an error, call Create and Wait yourself.
Example ¶
Human approval before an irreversible action. Require returns an error for anything except approval, so the happy path reads as a guard.
package main
import (
"context"
"errors"
"fmt"
"log"
lumoauth "github.com/lumoauth/lumo-auth-go"
)
func main() {
agent, err := lumoauth.NewAgent(lumoauth.AgentConfig{})
if err != nil {
log.Fatal(err)
}
approval, err := agent.Approvals.Require(context.Background(), lumoauth.ApprovalParams{
TaskID: "wire-2026-05-07-001",
Reason: "Wire $4,500 to vendor INV-7741",
Impact: lumoauth.ImpactHigh,
OnBehalfOf: "ada@acme.com",
Meta: map[string]any{"amount": 4500, "vendor": "INV-7741"},
}, nil)
switch {
case errors.Is(err, lumoauth.ErrApprovalDenied):
fmt.Println("a human declined the transfer")
return
case errors.Is(err, lumoauth.ErrApprovalTimeout):
fmt.Println("nobody responded in time")
return
case errors.Is(err, lumoauth.ErrApprovalNotDelivered):
// No push device received the request. Reason is
// ApprovalReasonEmailFallbackSent or ApprovalReasonNoEnrolledDevice.
fmt.Println("ask the user to check their email or enrol a device")
return
case err != nil:
log.Fatal(err)
}
// approval.Token authorises the side-effecting call.
fmt.Println("approved by user", approval.ApprovedBy.UserID)
}
Output:
func (*ApprovalsResource) Status ¶
func (r *ApprovalsResource) Status(ctx context.Context, approvalToken string) (*ApprovalResult, error)
Status fetches the current state of an approval request. It only reads state, so it is safe to expose to a polling frontend.
func (*ApprovalsResource) Wait ¶
func (r *ApprovalsResource) Wait(ctx context.Context, approvalToken string, opts *WaitOptions) (*ApprovalResult, error)
Wait polls an approval until it leaves pending, the deadline passes, or the context is cancelled. It returns the last observed state — a still-pending result means the wait timed out, not that the request was denied.
type Approver ¶
type Approver struct {
UserID ID `json:"user_id,omitempty"`
// Email is set only if the server includes it; the current server
// sends user_id alone.
Email string `json:"email,omitempty"`
}
Approver identifies the human who responded to an approval request. The server sends it as {"user_id": …} on an approved request and null otherwise.
type AuthResource ¶
type AuthResource struct {
// contains filtered or unexported fields
}
AuthResource covers the org-scoped OAuth 2.1 endpoints: authorize, token, userinfo, and revoke.
func (*AuthResource) AuthorizationURL ¶
func (r *AuthResource) AuthorizationURL(params AuthorizationURLParams) (string, error)
AuthorizationURL builds the URL to redirect a user to in order to start the authorization-code flow.
func (*AuthResource) ClientCredentials ¶
func (r *AuthResource) ClientCredentials(ctx context.Context, clientID, clientSecret string, scopes ...string) (*TokenResponse, error)
ClientCredentials performs the machine-to-machine client-credentials grant. Passing no scopes lets the server grant the client's defaults.
func (*AuthResource) ExchangeCode ¶
func (r *AuthResource) ExchangeCode(ctx context.Context, params ExchangeCodeParams) (*TokenResponse, error)
ExchangeCode trades an authorization code for tokens.
func (*AuthResource) RefreshToken ¶
func (r *AuthResource) RefreshToken(ctx context.Context, params RefreshTokenParams) (*TokenResponse, error)
RefreshToken exchanges a refresh token for a new access token.
func (*AuthResource) Revoke ¶
func (r *AuthResource) Revoke(ctx context.Context, params RevokeParams) error
Revoke invalidates an access or refresh token. Revoking a refresh token also invalidates the tokens derived from it.
func (*AuthResource) TokenExchange ¶
func (r *AuthResource) TokenExchange(ctx context.Context, params TokenExchangeParams) (*TokenResponse, error)
TokenExchange performs an RFC 8693 exchange — the primitive behind delegation and MCP audience scoping.
type AuthTokenParams ¶
type AuthTokenParams struct {
// ResourceToken is the `resource+jwt` obtained from the target
// resource. Required.
ResourceToken string
// Scope is space-separated and informational; scopes bind through the
// resource token.
Scope string
// AgentToken is the `agent+jwt` presented in Agent-Auth. Required —
// the endpoint authenticates the agent through that header, not the
// request body.
AgentToken string
// RedirectURI is where consent should return the user, for flows that
// need it. Must be registered for the agent.
RedirectURI string
}
AuthTokenParams describes a direct authorization request (request_type=auth).
type AuthorizationURLParams ¶
type AuthorizationURLParams struct {
// ClientID is the OAuth client initiating the flow. Required.
ClientID string
// RedirectURI must match one registered on the client. Required.
RedirectURI string
// Scope defaults to "openid profile email".
Scope string
// State is the CSRF token echoed back to the redirect URI.
State string
// ResponseType defaults to "code".
ResponseType string
// CodeChallenge enables PKCE. When set and CodeChallengeMethod is
// empty, "S256" is used.
CodeChallenge string
CodeChallengeMethod string
// Prompt is the OIDC prompt parameter ("consent", "login", "none").
Prompt string
// AccessType set to "offline" requests a refresh token.
AccessType string
// Extra adds arbitrary query parameters.
Extra map[string]string
}
AuthorizationURLParams describes an authorization-code redirect.
type BaseError ¶
type BaseError struct {
// Code is the stable machine-readable code shared with the JS and
// Python SDKs (see the Code* constants).
Code string
// Message is the human-readable description.
Message string
// contains filtered or unexported fields
}
BaseError carries the fields every LumoAuth error has. The concrete error types embed it, so errors.Is(err, ErrLumoAuth) holds for all of them.
func (*BaseError) ErrCode ¶
ErrCode returns the error's LumoAuth code. It backs the package-level ErrorCode helper across all error types.
type BudgetError ¶
type BudgetError struct {
*BaseError
// Budget is the policy that blocked the action.
Budget *AgentBudget
}
BudgetError is returned when an agent's budget policy blocks an action.
type CheckOptions ¶
type CheckOptions struct {
// Context supplies attributes for ABAC evaluation alongside the RBAC
// decision.
Context map[string]any
// UserID asks about another user instead of the caller. It must be the
// user's LumoAuth ID (a UUID) in the caller's organization. The SDK sends
// it as the request's subject, {"type": "user", "id": UserID}.
//
// Asking about someone other than yourself needs the authz:check scope
// (on the API key or the access token) or the authz.check permission.
// Without it the server answers 403 INSUFFICIENT_PERMISSIONS; an unknown
// ID gets 404 SUBJECT_NOT_FOUND. Leave it empty to check the caller.
UserID string
// AgentID asks about an agent (its agt_… ID) instead of the caller, with
// the same authz:check rule as UserID. Set at most one of the two.
AgentID string
}
CheckOptions carries the optional arguments shared by every check.
type Client ¶
type Client struct {
// Auth covers the OAuth 2.1 flows: authorization URLs, code exchange,
// refresh, client credentials, token exchange, revocation, UserInfo.
Auth *AuthResource
// Permissions covers RBAC checks for the authenticated principal.
Permissions *PermissionsResource
// Zanzibar covers relationship-based (ReBAC) checks.
Zanzibar *ZanzibarResource
// Abac covers attribute-based policy evaluation and attribute management.
Abac *AbacResource
// Agents covers agent identity: ask, self-inspection, registration.
Agents *AgentsResource
// Delegation covers RFC 8693 token exchange (Chain of Agency).
Delegation *DelegationResource
// Jit covers Just-in-Time permissions: ephemeral tasks and scoped tokens.
Jit *JitResource
// Approvals covers push-approval-for-agent-actions.
Approvals *ApprovalsResource
// Mcp covers audience-scoped tokens for secured MCP servers.
Mcp *McpResource
// contains filtered or unexported fields
}
Client is the general-purpose LumoAuth API client.
Curated resource namespaces cover the common surface — the ones an application actually reaches for. Everything else (admin CRUD, SCIM, audit logs) is available through the Do escape hatch or the generated OpenAPI client, which APIConfig configures for you.
client, err := lumoauth.New(
lumoauth.WithAPIKey(os.Getenv("LUMOAUTH_API_KEY")),
lumoauth.WithOrgID("acme-corp"),
)
if err != nil {
return err
}
ok, err := client.Permissions.Check(ctx, "document.edit", nil)
An API key reaches only the admin API, client registration and the permission checks. ABAC, agent and JIT calls need a user access token (WithAccessToken or WithTokenProvider) or an agent credential; ABAC needs the abac:read scope.
A Client is safe for concurrent use.
func New ¶
New builds a Client. It returns a *ConfigError when no credential is configured — either an API key or a token provider is required.
Example ¶
The general-purpose client: check a permission for the authenticated principal.
package main
import (
"context"
"fmt"
"log"
"os"
lumoauth "github.com/lumoauth/lumo-auth-go"
)
func main() {
client, err := lumoauth.New(
lumoauth.WithAPIKey(os.Getenv("LUMOAUTH_API_KEY")),
lumoauth.WithOrgID("acme-corp"),
)
if err != nil {
log.Fatal(err)
}
allowed, err := client.Permissions.Check(context.Background(), "document.edit", nil)
if err != nil {
log.Fatal(err)
}
fmt.Println(allowed)
}
Output:
func (*Client) APIConfig ¶
APIConfig returns the settings for the generated OpenAPI client, which covers the full REST surface (admin endpoints, SCIM, audit logs).
Unlike the JS and Python SDKs, Go cannot import the generated client lazily — a hard dependency would force it on every consumer — so this SDK hands you the configuration instead of the client:
import lumoauthclient "github.com/lumoauth/api-clients/go"
apiCfg, err := client.APIConfig(ctx)
if err != nil {
return err
}
cfg := lumoauthclient.NewConfiguration()
cfg.Servers = lumoauthclient.ServerConfigurations{{URL: apiCfg.BaseURL}}
cfg.DefaultHeader = apiCfg.DefaultHeader
cfg.HTTPClient = apiCfg.HTTPClient
api := lumoauthclient.NewAPIClient(cfg)
The context resolves the current bearer token, so call this once per token lifetime (or per request when using short-lived agent tokens).
func (*Client) BaseURL ¶
BaseURL returns the configured LumoAuth instance URL, without a trailing slash.
func (*Client) Do ¶
Do sends an authenticated request to any LumoAuth endpoint and decodes the JSON response into out (pass nil to discard it). The path is joined to the client's base URL; an absolute URL is used as-is. Non-2xx responses become the typed errors in errors.go.
Reach for this when an endpoint has no curated namespace yet:
var page struct {
Data []map[string]any `json:"data"`
}
err := client.Do(ctx, "GET", "/orgs/acme-corp/api/v1/admin/users", nil, &page)
Example ¶
Reaching past the curated namespaces to the rest of the REST API.
package main
import (
"context"
"fmt"
"log"
"net/http"
"os"
lumoauth "github.com/lumoauth/lumo-auth-go"
)
func main() {
client, err := lumoauth.New(
lumoauth.WithAPIKey(os.Getenv("LUMOAUTH_API_KEY")),
lumoauth.WithOrgID("acme-corp"),
)
if err != nil {
log.Fatal(err)
}
path, err := client.OrgPath("/admin/users")
if err != nil {
log.Fatal(err)
}
var page struct {
Data []map[string]any `json:"data"`
}
if err := client.Do(context.Background(), http.MethodGet, path, nil, &page); err != nil {
log.Fatal(err)
}
fmt.Println(len(page.Data), "users")
}
Output:
func (*Client) DoRaw ¶
DoRaw is Do without response handling: the caller owns the *http.Response and must close its body. Transport failures are still wrapped as *NetworkError, but HTTP statuses are left untouched.
type ConfidentialClient ¶
type ConfidentialClient interface {
TokenSource
ClientID() string
ClientSecret() string
}
ConfidentialClient is what DelegationChain needs from an agent: a token source plus the OAuth client credentials the consent-code exchange and revocation require. *Agent satisfies it.
type ConfigError ¶
type ConfigError struct {
*BaseError
}
ConfigError is returned when a required option is missing or invalid.
func NewConfigError ¶
func NewConfigError(message string) *ConfigError
NewConfigError builds a ConfigError.
type ConsentURLParams ¶
type ConsentURLParams struct {
// ClientID is the agent's OAuth client. Required.
ClientID string
// RedirectURI is where consent returns the user. Required.
RedirectURI string
// Scopes are the permissions being requested. Defaults to
// ["read:documents"].
Scopes []string
// State is the CSRF token echoed back to the redirect URI.
State string
}
ConsentURLParams describes the consent redirect a user follows to let an agent act on their behalf.
type CreateTaskParams ¶
type CreateTaskParams struct {
// Name is a human-readable label ("Analyse Q4 report").
Name string
// Type categorises the task ("research", "analysis").
Type string
// OnBehalfOf is the user's email when the agent acts for someone.
OnBehalfOf string
}
CreateTaskParams describes an ephemeral task.
type DelegationChain ¶
type DelegationChain struct {
// contains filtered or unexported fields
}
DelegationChain manages RFC 8693 token exchange for agents acting on behalf of users — the Chain of Agency.
It tracks one delegation per session ID through the full lifecycle:
User consent — build an authorization URL, then exchange the callback code for the user's tokens.
Token exchange — combine the user's token (subject) with the agent's (actor) into a delegated token carrying an `act` claim.
Delegated requests — call APIs as "agent acting for user", so every action is attributable to both.
Nested delegation — pass authority to a sub-agent, adding a link to the chain (up to MaxDelegationDepth).
Revocation — invalidate a session's tokens.
chain := lumoauth.NewDelegationChain(agent, "https://agent.example.com/callback")
url, err := chain.ConsentURL("session-1", []string{"read:documents"}, "") // … user completes consent, your callback receives `code` … if err := chain.HandleConsentCallback(ctx, "session-1", code); err != nil { return err } resp, err := chain.Do(ctx, "session-1", "GET", "/orgs/acme/api/v1/documents", nil)
A DelegationChain is safe for concurrent use.
func NewDelegationChain ¶
func NewDelegationChain(agent ConfidentialClient, redirectURI string) *DelegationChain
NewDelegationChain builds a chain over an authenticated agent. redirectURI is the OAuth callback the consent flow returns to; it may be empty when tokens are registered directly with SetUserToken.
Example ¶
Acting on behalf of a user, with the chain recorded in the token.
package main
import (
"context"
"fmt"
"log"
"net/http"
lumoauth "github.com/lumoauth/lumo-auth-go"
)
func main() {
agent, err := lumoauth.NewAgent(lumoauth.AgentConfig{})
if err != nil {
log.Fatal(err)
}
chain := lumoauth.NewDelegationChain(agent, "https://agent.example.com/callback")
ctx := context.Background()
// 1. Send the user here to grant consent.
consentURL, err := chain.ConsentURL("session-1", []string{"read:documents"}, "")
if err != nil {
log.Fatal(err)
}
fmt.Println("visit:", consentURL)
// 2. Your callback receives ?code=…
if err := chain.HandleConsentCallback(ctx, "session-1", "code-from-callback"); err != nil {
log.Fatal(err)
}
// 3. Call as "agent acting for user". The exchange happens on demand.
var documents struct {
Data []map[string]any `json:"data"`
}
if err := chain.Do(ctx, "session-1", http.MethodGet,
"/orgs/acme-corp/api/v1/documents", nil, &documents); err != nil {
log.Fatal(err)
}
}
Output:
func (*DelegationChain) ActiveSessions ¶
func (c *DelegationChain) ActiveSessions() []string
ActiveSessions returns the session IDs holding user tokens.
func (*DelegationChain) ActorChain ¶
func (c *DelegationChain) ActorChain(token string) ([]string, error)
ActorChain returns the actors recorded in a delegated JWT, outermost first. Decoded without signature verification — display and audit only.
func (*DelegationChain) ConsentURL ¶
func (c *DelegationChain) ConsentURL(sessionID string, scopes []string, state string) (string, error)
ConsentURL builds the URL where the user grants the agent permission to act on their behalf. Redirect the user there; consent returns them to the chain's redirect URI with an authorization code.
sessionID correlates the consent with the later exchange. state defaults to "session:<sessionID>".
func (*DelegationChain) DelegateToSubAgent ¶
func (c *DelegationChain) DelegateToSubAgent(ctx context.Context, sessionID, subAgentToken string, scopes ...string) (string, error)
DelegateToSubAgent mints a token for the chain user → this agent → sub-agent. Each hop may only narrow scopes, and LumoAuth caps the chain at MaxDelegationDepth.
subAgentToken is the sub-agent's own client-credentials token.
func (*DelegationChain) DelegateToSubAgentForResource ¶ added in v1.1.0
func (c *DelegationChain) DelegateToSubAgentForResource(ctx context.Context, sessionID, subAgentToken, resource string, scopes ...string) (string, error)
DelegateToSubAgentForResource is DelegateToSubAgent with an RFC 8707 resource indicator for the sub-agent's token (its `aud`).
func (*DelegationChain) DelegatedToken ¶
DelegatedToken returns the cached delegated token for a session, performing the exchange if there isn't one yet.
func (*DelegationChain) Do ¶
func (c *DelegationChain) Do(ctx context.Context, sessionID, method, path string, body, out any) error
Do makes a request with a session's delegated token, exchanging for one first if needed, and decodes the JSON response into out (nil to discard).
func (*DelegationChain) DoRaw ¶
func (c *DelegationChain) DoRaw(ctx context.Context, sessionID, method, path string, body any) (*http.Response, error)
DoRaw is Do without response handling: the caller owns the *http.Response and must close its body.
func (*DelegationChain) Exchange ¶
func (c *DelegationChain) Exchange(ctx context.Context, sessionID string, scopes ...string) (string, error)
Exchange produces a delegated token for a session, combining the user's token (subject) with the agent's (actor). The result is cached; scopes may only narrow what the user consented to. The token is bound to this agent; use ExchangeForResource to bind it to the API it will be sent to.
func (*DelegationChain) ExchangeForResource ¶ added in v1.1.0
func (c *DelegationChain) ExchangeForResource(ctx context.Context, sessionID, resource string, scopes ...string) (string, error)
ExchangeForResource is Exchange with an RFC 8707 resource indicator: the https URL in resource becomes the delegated token's `aud`. The result replaces the session's cached delegated token.
func (*DelegationChain) HandleConsentCallback ¶
func (c *DelegationChain) HandleConsentCallback(ctx context.Context, sessionID, authorizationCode string) error
HandleConsentCallback exchanges the authorization code from the consent callback for the user's tokens and stores them under sessionID.
func (*DelegationChain) HasDelegation ¶
func (c *DelegationChain) HasDelegation(sessionID string) bool
HasDelegation reports whether a delegated token is cached for a session.
func (*DelegationChain) Revoke ¶
func (c *DelegationChain) Revoke(ctx context.Context, sessionID string) error
Revoke ends a delegation: it revokes the user's refresh token at the server, which invalidates every derived token, and drops the local state. Local state is cleared even if the server call fails, so a revoked session never keeps serving requests from cache.
func (*DelegationChain) RevokeAll ¶
func (c *DelegationChain) RevokeAll(ctx context.Context) error
RevokeAll revokes every active session, returning the first error while still attempting the rest.
func (*DelegationChain) SetUserToken ¶
func (c *DelegationChain) SetUserToken(sessionID, accessToken string) error
SetUserToken registers a user access token you already hold, skipping the consent redirect. Without a refresh token the SDK cannot renew it, so the delegation lasts only as long as the token does.
type DelegationResource ¶
type DelegationResource struct {
// contains filtered or unexported fields
}
DelegationResource covers the RFC 8693 delegation primitives — the raw operations behind the Chain of Agency.
For session-tracked delegation with consent handling and refresh, use DelegationChain, which wraps this resource.
func (*DelegationResource) ConsentURL ¶
func (r *DelegationResource) ConsentURL(params ConsentURLParams) (string, error)
ConsentURL builds the URL where a user grants an agent delegated access. It requests offline access so the agent receives a refresh token.
func (*DelegationResource) Exchange ¶
func (r *DelegationResource) Exchange(ctx context.Context, subjectToken, actorToken string, scopes ...string) (*TokenResponse, error)
Exchange combines a subject token (the user) with an actor token (the agent) into a delegated token. The resulting JWT carries an `act` claim recording the chain, so every downstream action is attributable to both. The token is bound to the acting agent; use ExchangeForResource to bind it to the API it will be sent to.
func (*DelegationResource) ExchangeCode ¶
func (r *DelegationResource) ExchangeCode(ctx context.Context, params ExchangeCodeParams) (*TokenResponse, error)
ExchangeCode trades a consent callback code for the user's tokens.
func (*DelegationResource) ExchangeForResource ¶ added in v1.1.0
func (r *DelegationResource) ExchangeForResource(ctx context.Context, subjectToken, actorToken, resource string, scopes ...string) (*TokenResponse, error)
ExchangeForResource is Exchange with an RFC 8707 resource indicator: the https URL in resource becomes the delegated token's `aud`.
func (*DelegationResource) ParseActorChain ¶
func (r *DelegationResource) ParseActorChain(token string) ([]string, error)
ParseActorChain is the method form of the package-level function, for callers who already hold the namespace.
func (*DelegationResource) RefreshUserToken ¶
func (r *DelegationResource) RefreshUserToken(ctx context.Context, params RefreshTokenParams) (*TokenResponse, error)
RefreshUserToken refreshes a user's delegated access token.
func (*DelegationResource) Revoke ¶
func (r *DelegationResource) Revoke(ctx context.Context, params RevokeParams) error
Revoke invalidates a delegation's refresh token, which also invalidates every token derived from it.
type EvaluateTaskParams ¶
type EvaluateTaskParams struct {
// Result is TaskResultCompleted, TaskResultFailed, or
// TaskResultCancelled. Defaults to completed.
Result string
// Notes are attached to the audit record.
Notes string
}
EvaluateTaskParams describes how a task ended.
type ExchangeCodeParams ¶
type ExchangeCodeParams struct {
// Code is the authorization code from the callback. Required.
Code string
// RedirectURI must match the one used to obtain the code. Required.
RedirectURI string
// ClientID is the OAuth client. Required.
ClientID string
// ClientSecret is required for confidential clients.
ClientSecret string
// CodeVerifier is the PKCE verifier matching the challenge sent to
// the authorization endpoint.
CodeVerifier string
}
ExchangeCodeParams describes an authorization-code exchange.
type ID ¶
type ID string
ID is an identifier the API may send as either a JSON string or a JSON number (user IDs in particular). It decodes both into a string.
func (ID) MarshalJSON ¶
MarshalJSON emits the ID as a JSON string, or as a number when it is one.
func (*ID) UnmarshalJSON ¶
UnmarshalJSON accepts a string, a number, or null.
type JITContext ¶
type JITContext struct {
// contains filtered or unexported fields
}
JITContext manages one ephemeral task and the scoped permissions requested under it.
The lifecycle is: create a task, request permissions against it, exchange approved requests for short-lived tokens, then complete the task — which revokes every token issued under it. Close makes that cleanup a defer:
jit, err := lumoauth.NewJITContext(agent)
if err != nil {
return err
}
defer jit.Close(ctx)
if _, err := jit.CreateTask(ctx, lumoauth.CreateTaskParams{Name: "Analyse Q4 report"}); err != nil {
return err
}
result, err := jit.RequestPermission(ctx, map[string]any{
"type": "file_access", "actions": []string{"read"}, "identifier": "report_q4.pdf",
}, nil)
if err != nil {
return err
}
if result.Approved() {
token, err := jit.Token(ctx, result.RequestID)
…
}
func NewJITContext ¶
func NewJITContext(source TokenSource, opts ...JITContextOption) (*JITContext, error)
NewJITContext builds a JIT context over any authenticated token source.
Example ¶
A JIT task scopes permissions to one unit of work, and revokes every token it issued when the task closes.
package main
import (
"context"
"fmt"
"log"
lumoauth "github.com/lumoauth/lumo-auth-go"
)
func main() {
agent, err := lumoauth.NewAgent(lumoauth.AgentConfig{})
if err != nil {
log.Fatal(err)
}
jit, err := lumoauth.NewJITContext(agent)
if err != nil {
log.Fatal(err)
}
ctx := context.Background()
defer jit.Close(ctx) // completes the task and revokes its tokens
if _, err := jit.CreateTask(ctx, lumoauth.CreateTaskParams{
Name: "Analyse Q4 report",
Type: "analysis",
}); err != nil {
log.Fatal(err)
}
result, err := jit.RequestPermission(ctx, map[string]any{
"type": "file_access",
"actions": []string{"read"},
"identifier": "report_q4.pdf",
}, &lumoauth.RequestPermissionOptions{
Justification: "The user asked for a Q4 summary",
})
if err != nil {
log.Fatal(err)
}
if !result.Approved() {
fmt.Println("not approved:", result.Status)
return
}
token, err := jit.Token(ctx, result.RequestID)
if err != nil {
log.Fatal(err)
}
_ = token // present it to the resource
}
Output:
func (*JITContext) CaepSessionID ¶
func (j *JITContext) CaepSessionID() string
CaepSessionID returns the CAEP session ID for the current task, when the server issued one.
func (*JITContext) Call ¶
func (j *JITContext) Call(ctx context.Context, jitToken, method, url string, body any) (*http.Response, error)
Call makes a request to any URL using a JIT token. The caller owns the returned response and must close its body.
func (*JITContext) CallWithEscalation ¶
func (j *JITContext) CallWithEscalation(ctx context.Context, method, url string, body any, opts *RequestPermissionOptions) (*http.Response, error)
CallWithEscalation makes a request and, if the server answers 403 with an Insufficient-Authorization-Details header, requests exactly the permission that header names, obtains a JIT token, and retries once.
This is the auto-escalation path: the resource server states what it needs, and the agent asks for that and nothing more. When the escalation is not approved, the original 403 is returned unchanged.
The caller owns the returned response and must close its body.
func (*JITContext) Close ¶
func (j *JITContext) Close(ctx context.Context) error
Close is CompleteTask under the name defer expects.
func (*JITContext) CompleteTask ¶
func (j *JITContext) CompleteTask(ctx context.Context) error
CompleteTask closes the current task and revokes its JIT tokens. It is a no-op when no task is open, and clears the task either way — a failed cleanup should not strand the context on a dead task.
func (*JITContext) CreateTask ¶
func (j *JITContext) CreateTask(ctx context.Context, params CreateTaskParams) (*JitTask, error)
CreateTask opens an ephemeral task and makes it the context's current task.
func (*JITContext) DelegateOnBehalfOf ¶
func (j *JITContext) DelegateOnBehalfOf(ctx context.Context, userToken string) error
DelegateOnBehalfOf exchanges the agent's token and a user's token for a delegated one (RFC 8693), and uses it for subsequent JIT calls. The delegated token carries an `act` claim, so the audit trail names both the user and the agent.
func (*JITContext) EvaluateTask ¶
func (j *JITContext) EvaluateTask(ctx context.Context, taskID string, params EvaluateTaskParams) (map[string]any, error)
EvaluateTask closes a task with an outcome and audit notes. It defaults to the current task.
func (*JITContext) PendingRequests ¶
func (j *JITContext) PendingRequests(ctx context.Context) ([]JitRequest, error)
PendingRequests lists the requests awaiting human approval.
func (*JITContext) RequestPermission ¶
func (j *JITContext) RequestPermission(ctx context.Context, authorizationDetails map[string]any, opts *RequestPermissionOptions) (*JitRequest, error)
RequestPermission asks for a Just-in-Time permission against the current task.
Low-risk requests come back approved. Higher-risk ones enter human-in-the-loop review; by default this polls until the request resolves or the deadline passes, and returns the last state seen — a still-pending result means the wait timed out, not a denial. Set NoWait to poll yourself with Status.
func (*JITContext) Status ¶
func (j *JITContext) Status(ctx context.Context, requestID string) (*JitRequest, error)
Status fetches the current state of a permission request.
func (*JITContext) TaskID ¶
func (j *JITContext) TaskID() string
TaskID returns the current task's ID, or "" when no task is open.
type JITContextOption ¶
type JITContextOption func(*JITContext)
JITContextOption configures a JITContext.
func WithDelegatedToken ¶
func WithDelegatedToken(token string) JITContextOption
WithDelegatedToken makes JIT calls under an on-behalf-of token (from DelegateOnBehalfOf or a DelegationChain) instead of the agent's own.
type JWK ¶
type JWK struct {
Kty string `json:"kty"`
Crv string `json:"crv,omitempty"`
X string `json:"x,omitempty"`
Y string `json:"y,omitempty"`
N string `json:"n,omitempty"`
E string `json:"e,omitempty"`
Use string `json:"use,omitempty"`
Kid string `json:"kid,omitempty"`
Alg string `json:"alg,omitempty"`
}
JWK is a JSON Web Key. Only the members AAuth uses are modelled; Extra preserves anything else the issuer published.
type JWKS ¶
type JWKS struct {
Keys []JWK `json:"keys"`
}
JWKS is a JSON Web Key Set, as published at a jwks_uri.
func FetchIssuerJWKS ¶
FetchIssuerJWKS retrieves an AAuth issuer's signing keys from {issuer}/aauth/jwks.json.
type JWKSCache ¶
type JWKSCache struct {
// contains filtered or unexported fields
}
JWKSCache caches an issuer's JWKS for a TTL, so a busy resource server verifies tokens without fetching keys on every request. The zero value is not usable — build one with NewJWKSCache.
func NewJWKSCache ¶
NewJWKSCache builds a cache for one issuer. A ttl of 0 means one hour.
func (*JWKSCache) Invalidate ¶
func (c *JWKSCache) Invalidate()
Invalidate drops the cached keys, forcing the next Get to refetch. Call it when verification fails on an unknown kid — the issuer may have rotated keys mid-TTL.
type JitRequest ¶
type JitRequest struct {
RequestID string `json:"request_id"`
// Status is "approved", "pending", "denied", or a newer server value.
Status string `json:"status"`
RiskLevel string `json:"risk_level,omitempty"`
TokenURL string `json:"token_url,omitempty"`
StatusURL string `json:"status_url,omitempty"`
ExpiresAt string `json:"expires_at,omitempty"`
// AuthorizationDetails is the RFC 9396 object the request covers.
AuthorizationDetails map[string]any `json:"authorization_details,omitempty"`
// Raw is the complete decoded response.
Raw map[string]any `json:"-"`
}
JitRequest is the state of a Just-in-Time permission request.
func (*JitRequest) Approved ¶
func (r *JitRequest) Approved() bool
Approved reports whether the request has been granted.
func (*JitRequest) Pending ¶
func (r *JitRequest) Pending() bool
Pending reports whether the request is still awaiting a decision.
func (*JitRequest) UnmarshalJSON ¶
func (r *JitRequest) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes the typed fields and retains the whole object.
type JitResource ¶
type JitResource struct {
// contains filtered or unexported fields
}
JitResource covers the Just-in-Time permission endpoints: ephemeral tasks, RFC 9396 permission requests, and short-lived scoped tokens.
For the full lifecycle with automatic cleanup, use JITContext, which wraps this resource.
func (*JitResource) CompleteTask ¶
func (r *JitResource) CompleteTask(ctx context.Context, taskID string) error
CompleteTask closes a task and revokes every JIT token issued under it.
func (*JitResource) CreateTask ¶
func (r *JitResource) CreateTask(ctx context.Context, params CreateTaskParams) (*JitTask, error)
CreateTask opens an ephemeral task — an isolated sub-identity that JIT permissions attach to, and whose tokens are revoked together when the task completes.
func (*JitResource) EvaluateTask ¶
func (r *JitResource) EvaluateTask(ctx context.Context, taskID string, params EvaluateTaskParams) (map[string]any, error)
EvaluateTask closes a task with an outcome and audit notes — the record a supervisor or orchestrator leaves behind.
func (*JitResource) Pending ¶
func (r *JitResource) Pending(ctx context.Context) ([]JitRequest, error)
Pending lists the permission requests awaiting human approval. It is a reviewer call: it needs a browser session or a user access token with the jit:approve scope.
func (*JitResource) Request ¶
func (r *JitResource) Request(ctx context.Context, params RequestPermissionParams) (*JitRequest, error)
Request asks for a Just-in-Time permission. Low-risk requests come back approved; higher-risk ones enter human-in-the-loop review as pending — see JITContext.RequestPermission to wait for the decision.
func (*JitResource) Status ¶
func (r *JitResource) Status(ctx context.Context, requestID string) (*JitRequest, error)
Status fetches the current state of a permission request.
func (*JitResource) Token ¶
func (r *JitResource) Token(ctx context.Context, requestID string) (*TokenResponse, error)
Token exchanges an approved request for a short-lived, narrowly scoped JIT access token.
type JitTask ¶
type JitTask struct {
TaskID string `json:"task_id"`
CaepSessionID string `json:"caep_session_id,omitempty"`
ExpiresAt string `json:"expires_at,omitempty"`
// Raw is the complete decoded response.
Raw map[string]any `json:"-"`
}
JitTask is an ephemeral task (an isolated agent sub-identity).
func (*JitTask) UnmarshalJSON ¶
UnmarshalJSON decodes the typed fields and retains the whole object.
type Keypair ¶
type Keypair struct {
// PrivateKeyPEM is the PKCS#8 private key. Store it in a secret manager.
PrivateKeyPEM string
// PublicKeyPEM is the SPKI public key.
PublicKeyPEM string
// JWK is the public key with use "sig" and the requested kid.
JWK JWK
// JWKS is a key set ready to publish at /.well-known/jwks.json.
JWKS JWKS
}
Keypair is a freshly generated AAuth signing key.
func GenerateKeypair ¶
GenerateKeypair creates an Ed25519 key pair for AAuth. Pass an empty kid to use DefaultKid.
keypair, err := lumoauth.GenerateKeypair("")
// Register keypair.JWKS with LumoAuth, keep keypair.PrivateKeyPEM secret.
Example ¶
Publish a JWKS so LumoAuth can verify the agent's signatures.
package main
import (
"fmt"
"log"
lumoauth "github.com/lumoauth/lumo-auth-go"
)
func main() {
keypair, err := lumoauth.GenerateKeypair("")
if err != nil {
log.Fatal(err)
}
// Store this in a secret manager.
_ = keypair.PrivateKeyPEM
// Register this with LumoAuth, or serve it at /.well-known/jwks.json.
_ = keypair.JWKS
fmt.Println(keypair.JWK.Kty, keypair.JWK.Crv, keypair.JWK.Kid)
}
Output: OKP Ed25519 key-1
type McpResource ¶
type McpResource struct {
// contains filtered or unexported fields
}
McpResource exchanges the caller's token for one bound to a secured MCP server (RFC 8693 token exchange). The server's URL goes in the RFC 8707 `resource` parameter, which sets the issued token's `aud`.
func (*McpResource) Token ¶
Token returns an access token bound to one MCP server.
token, err := client.Mcp.Token(ctx, "https://mcp.example.com/mcp", "")
serverID is the MCP server's https URL, which is its RFC 8707 resource identifier. LumoAuth sets the token's `aud` from it. A plain-http URL is accepted only for localhost and private hosts. Pass an empty subjectToken to exchange the client's own bearer token.
func (*McpResource) TokenDetailed ¶
func (r *McpResource) TokenDetailed(ctx context.Context, serverID, subjectToken string) (*McpToken, error)
TokenDetailed is Token with the full token response — lifetime, type, and granted scope.
type McpToken ¶
type McpToken struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type,omitempty"`
ExpiresIn int `json:"expires_in,omitempty"`
Scope string `json:"scope,omitempty"`
}
McpToken is an audience-scoped token for a secured MCP server.
type NetworkError ¶
type NetworkError struct {
*BaseError
}
NetworkError is returned when a request fails before an HTTP response was received (DNS, connection, TLS, timeout, or a cancelled context).
type Option ¶
type Option func(*clientConfig)
Option configures a Client. Options are applied in order.
func WithAPIKey ¶
WithAPIKey authenticates with a tenant API key, sent as X-API-Key. Defaults to $LUMOAUTH_API_KEY.
func WithAccessToken ¶
WithAccessToken authenticates with a fixed bearer token. For tokens that expire, prefer WithTokenProvider so the SDK can pick up refreshes.
func WithBaseURL ¶
WithBaseURL sets the LumoAuth instance URL. Defaults to $LUMOAUTH_URL, then DefaultBaseURL.
func WithHTTPClient ¶
WithHTTPClient supplies the *http.Client used for every request — the hook for custom transports, proxies, and instrumentation.
func WithHeader ¶
WithHeader adds a header to every request.
func WithOrgID ¶
WithOrgID sets the organization slug. Required for org-scoped endpoints (ABAC, agents, JIT, approvals, OAuth). Defaults to $LUMOAUTH_ORG_ID.
func WithSkipCertValidation ¶
func WithSkipCertValidation() Option
WithSkipCertValidation disables TLS certificate verification. Local development against a self-signed instance only.
func WithTimeout ¶
WithTimeout sets the per-request timeout. Default: 30s.
func WithTokenProvider ¶
func WithTokenProvider(provider TokenProvider) Option
WithTokenProvider authenticates with a bearer token resolved per request, which lets the caller refresh transparently. A provider that returns a token takes precedence over an API key.
func WithUserAgent ¶
WithUserAgent overrides the User-Agent sent with every request.
type Permission ¶
type Permission struct {
Slug string `json:"slug"`
Description string `json:"description,omitempty"`
Source string `json:"source,omitempty"`
}
Permission is one permission granted to a principal.
type PermissionBulkCheck ¶
type PermissionBulkCheck struct {
Results map[string]bool `json:"results"`
UserID ID `json:"user_id,omitempty"`
Context map[string]any `json:"context,omitempty"`
}
PermissionBulkCheck is the result of a bulk permission check: Results maps each requested slug to its decision.
type PermissionCheck ¶
type PermissionCheck struct {
Allowed bool `json:"allowed"`
Permission string `json:"permission,omitempty"`
UserID ID `json:"user_id,omitempty"`
Context map[string]any `json:"context,omitempty"`
}
PermissionCheck is the result of a single permission check.
type PermissionList ¶
type PermissionList struct {
UserID ID `json:"user_id,omitempty"`
Permissions []Permission `json:"permissions"`
Count int `json:"count,omitempty"`
}
PermissionList is the full set of permissions granted to a principal.
type PermissionMultiCheck ¶
type PermissionMultiCheck struct {
Allowed bool `json:"allowed"`
Permissions []string `json:"permissions,omitempty"`
UserID ID `json:"user_id,omitempty"`
Context map[string]any `json:"context,omitempty"`
}
PermissionMultiCheck is the result of a check-any / check-all call.
type PermissionsResource ¶
type PermissionsResource struct {
// contains filtered or unexported fields
}
PermissionsResource covers RBAC permission checks for the authenticated principal: single checks, bulk checks, logical combinations, and listing.
The endpoints infer the organization from the credential, so this namespace works without an org ID.
func (*PermissionsResource) Check ¶
func (r *PermissionsResource) Check(ctx context.Context, permission string, opts *CheckOptions) (bool, error)
Check reports whether the principal holds a permission.
ok, err := client.Permissions.Check(ctx, "document.edit", nil)
func (*PermissionsResource) CheckAll ¶
func (r *PermissionsResource) CheckAll(ctx context.Context, permissions []string, opts *CheckOptions) (bool, error)
CheckAll reports whether the principal holds every one of the permissions (logical AND).
func (*PermissionsResource) CheckAllDetailed ¶
func (r *PermissionsResource) CheckAllDetailed(ctx context.Context, permissions []string, opts *CheckOptions) (*PermissionMultiCheck, error)
CheckAllDetailed is CheckAll with the full response.
func (*PermissionsResource) CheckAny ¶
func (r *PermissionsResource) CheckAny(ctx context.Context, permissions []string, opts *CheckOptions) (bool, error)
CheckAny reports whether the principal holds at least one of the permissions (logical OR).
func (*PermissionsResource) CheckAnyDetailed ¶
func (r *PermissionsResource) CheckAnyDetailed(ctx context.Context, permissions []string, opts *CheckOptions) (*PermissionMultiCheck, error)
CheckAnyDetailed is CheckAny with the full response.
func (*PermissionsResource) CheckBulk ¶
func (r *PermissionsResource) CheckBulk(ctx context.Context, permissions []string, opts *CheckOptions) (*PermissionBulkCheck, error)
CheckBulk evaluates many permissions in one round trip; the Results map holds one decision per requested slug.
func (*PermissionsResource) CheckDetailed ¶
func (r *PermissionsResource) CheckDetailed(ctx context.Context, permission string, opts *CheckOptions) (*PermissionCheck, error)
CheckDetailed is Check with the full response — the permission slug, the principal it was evaluated for, and the context echoed back.
func (*PermissionsResource) List ¶
func (r *PermissionsResource) List(ctx context.Context) (*PermissionList, error)
List returns every permission granted to the authenticated principal.
A user access token needs the authz:read scope (or the blanket admin scope). Organization API keys cannot hold that scope, so with an API key List fails with an *APIError whose RequiredScopes is ["authz:read"].
type RefreshParams ¶
type RefreshParams struct {
// RefreshToken is the token from a prior response. Required.
RefreshToken string
// ResourceToken must be a FRESH resource token for the target
// resource — the server requires one on every refresh. Required.
ResourceToken string
// Scope optionally narrows the refreshed token; it must be a subset
// of the original grant.
Scope string
// AgentToken is the `agent+jwt` presented in Agent-Auth. Required.
AgentToken string
}
RefreshParams describes an auth-token refresh.
type RefreshTokenParams ¶
type RefreshTokenParams struct {
// RefreshToken is the token to redeem. Required.
RefreshToken string
// ClientID is the OAuth client. Required.
ClientID string
// ClientSecret is required for confidential clients.
ClientSecret string
// Scopes optionally narrows the refreshed token; must be a subset of
// the original grant.
Scopes []string
}
RefreshTokenParams describes a refresh-token grant.
type RegisterParams ¶
type RegisterParams struct {
// Name is the human-readable agent name ("Document Analyser"). Required.
Name string
// ClientID is the OAuth client identifying the agent. Required.
ClientID string
// Description explains what the agent is for.
Description string
// Capabilities are the slugs the agent declares
// (e.g. "read:documents", "tool:search_web").
Capabilities []string
// JWKSURI points at the agent's public JWKS. Required for AAuth and
// other proof-of-possession flows.
JWKSURI string
}
RegisterParams describes an agent registration.
type RequestPermissionOptions ¶
type RequestPermissionOptions struct {
// Justification is the human-readable reason shown to an approver.
Justification string
// TTL is the requested token lifetime in seconds, capped at JitMaxTTL.
TTL int
// NoWait returns a pending request immediately instead of polling for
// the human decision.
NoWait bool
// PollInterval is the delay between status polls.
// Defaults to DefaultJitPollInterval.
PollInterval time.Duration
// PollTimeout bounds the wait for approval.
// Defaults to DefaultJitPollTimeout.
PollTimeout time.Duration
// TaskID overrides the context's current task.
TaskID string
}
RequestPermissionOptions tunes a JIT permission request.
type RequestPermissionParams ¶
type RequestPermissionParams struct {
// TaskID is the task the permission attaches to. Required.
TaskID string
// AuthorizationDetails is the RFC 9396 structured object, e.g.
// {"type": "file_access", "actions": ["read"], "identifier": "report.pdf"}
// Required.
AuthorizationDetails map[string]any
// Justification is the human-readable reason shown to an approver.
Justification string
// TTL is the requested token lifetime in seconds; capped at JitMaxTTL.
// Defaults to JitDefaultTTL.
TTL int
}
RequestPermissionParams describes an RFC 9396 permission request.
type RevokeParams ¶
type RevokeParams struct {
// Token is the access or refresh token to revoke. Required.
Token string
// TokenTypeHint is "access_token" or "refresh_token".
TokenTypeHint string
// ClientID and ClientSecret authenticate the revocation.
ClientID string
ClientSecret string
}
RevokeParams describes a token revocation.
type SessionTokens ¶
type SessionTokens struct {
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token,omitempty"`
IDToken string `json:"id_token,omitempty"`
TokenType string `json:"token_type,omitempty"`
ExpiresAt time.Time `json:"expires_at,omitempty"`
Scope string `json:"scope,omitempty"`
}
SessionTokens are the OAuth tokens held for a signed-in user.
func TokensFromContext ¶
func TokensFromContext(ctx context.Context) *SessionTokens
TokensFromContext returns the signed-in user's OAuth tokens, or nil.
func (*SessionTokens) Expired ¶
func (t *SessionTokens) Expired() bool
Expired reports whether the access token has passed its expiry. Tokens with no known expiry never report expired.
type SignOptions ¶
type SignOptions struct {
// Body is the exact request body being signed. Empty means no body.
Body []byte
// ContentType is the media type of the body.
// Defaults to "application/json".
ContentType string
// AgentToken is the `agent+jwt` presented in the Agent-Auth header. It
// travels outside the signature.
AgentToken string
// Authorization is the value of a covered Authorization header, when
// the request carries one (proof-of-possession requests do).
Authorization string
// SignatureKey is the value of a covered Signature-Key header.
SignatureKey string
// Created overrides the signature timestamp. Testing only — the server
// rejects timestamps more than 60s from its own clock.
Created int64
// Nonce overrides the generated nonce. Testing only — the server
// treats nonces as single-use.
Nonce string
}
SignOptions configures SignRequest.
type TokenExchangeParams ¶
type TokenExchangeParams struct {
// SubjectToken is the token representing the principal being acted
// for. Required. The subject must still be active: a deactivated or
// blocked user, or a suspended agent, gets invalid_grant. A JIT task
// token is never accepted as the subject.
SubjectToken string
// ActorToken is the token of the party doing the acting (the agent);
// set it to build a delegation chain with an `act` claim.
ActorToken string
// Audience is sent as the RFC 8693 `audience` parameter. LumoAuth binds
// the issued token's `aud` from Resource, not from Audience.
Audience string
// Resource is the RFC 8707 resource indicator — the absolute https URL
// of the API the issued token is for. It becomes its `aud`; without it
// an agent on-behalf-of token is bound to the acting agent's id.
Resource string
// Scopes optionally narrows the issued token.
Scopes []string
// SubjectTokenType declares what SubjectToken is (TokenTypeAccessToken,
// TokenTypeJWT, TokenTypeIDToken or TokenTypeRefreshToken). Empty means
// TokenTypeAccessToken. The server refuses a token that does not match
// its declared type (sdk-contract/token-types.json).
SubjectTokenType string
// ActorTokenType declares what ActorToken is; empty means
// TokenTypeAccessToken.
ActorTokenType string
}
TokenExchangeParams describes an RFC 8693 token exchange.
type TokenProvider ¶
TokenProvider returns the bearer token to authenticate a request with. It is called once per request, so implementations can refresh transparently.
type TokenResponse ¶
type TokenResponse struct {
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token,omitempty"`
IDToken string `json:"id_token,omitempty"`
TokenType string `json:"token_type,omitempty"`
ExpiresIn int `json:"expires_in,omitempty"`
Scope string `json:"scope,omitempty"`
IssuedTokenType string `json:"issued_token_type,omitempty"`
}
TokenResponse is an OAuth 2.1 token endpoint response.
func (*TokenResponse) Scopes ¶
func (t *TokenResponse) Scopes() []string
Scopes splits the space-separated Scope field.
type TokenSource ¶
type TokenSource interface {
BaseURL() string
OrgID() string
AccessToken(ctx context.Context) (string, error)
}
TokenSource is the minimal contract JITContext needs: where the instance lives, which org it belongs to, and a bearer token that stays fresh. *Agent satisfies it.
type User ¶
type User struct {
Sub string `json:"sub"`
Email string `json:"email,omitempty"`
EmailVerified bool `json:"email_verified,omitempty"`
Name string `json:"name,omitempty"`
GivenName string `json:"given_name,omitempty"`
FamilyName string `json:"family_name,omitempty"`
Picture string `json:"picture,omitempty"`
}
User is the signed-in principal, as returned by the UserInfo endpoint.
func UserFromContext ¶
UserFromContext returns the signed-in user for a request, or nil when the request is unauthenticated.
type UserInfo ¶
type UserInfo struct {
Sub string `json:"sub"`
Email string `json:"email,omitempty"`
EmailVerified bool `json:"email_verified,omitempty"`
Name string `json:"name,omitempty"`
GivenName string `json:"given_name,omitempty"`
FamilyName string `json:"family_name,omitempty"`
Picture string `json:"picture,omitempty"`
AgentID string `json:"agent_id,omitempty"`
Capabilities []string `json:"capabilities,omitempty"`
// BudgetPolicy is the agent's budget, when one is set.
BudgetPolicy *AgentBudget `json:"budget_policy,omitempty"`
// Raw is the complete decoded response, including any claims not
// modelled above.
Raw map[string]any `json:"-"`
}
UserInfo is an OIDC UserInfo response. Agent principals additionally carry Capabilities and BudgetPolicy.
func (*UserInfo) UnmarshalJSON ¶
UnmarshalJSON decodes the typed claims and retains the whole object.
type ValidationError ¶
type ValidationError struct {
*BaseError
// Issues holds per-field detail when the server supplied it.
Issues []any
}
ValidationError is returned when client-side validation fails: bad arguments, or a response whose shape the SDK cannot use.
func NewValidationError ¶
func NewValidationError(message string, issues ...any) *ValidationError
NewValidationError builds a ValidationError. Exported so callers writing their own resources on top of Client can produce consistent errors.
type VerifyOptions ¶
type VerifyOptions struct {
// Issuer is the trusted issuer URL, e.g.
// "https://app.lumoauth.dev/orgs/acme-corp/api/v1". Required.
Issuer string
// Resource is your resource identifier; it must equal the token's
// audience. Required.
Resource string
// JWKS supplies the issuer's keys directly, skipping the fetch. Use
// it with a cache in front of a hot path.
JWKS *JWKS
// HTTPClient fetches the JWKS. Defaults to a 30s-timeout client.
HTTPClient *http.Client
// ClockSkew tolerated on the expiry check. Default: 0, like the server.
ClockSkew time.Duration
}
VerifyOptions configures VerifyAuthToken.
type WaitOptions ¶
type WaitOptions struct {
// PollInterval is the delay between status polls.
// Defaults to DefaultApprovalPollInterval.
PollInterval time.Duration
// Timeout bounds the wait. Defaults to DefaultApprovalTimeout.
Timeout time.Duration
}
WaitOptions tunes approval polling.
type WebAuth ¶
type WebAuth struct {
// contains filtered or unexported fields
}
WebAuth drives the browser sign-in flow.
func NewWebAuth ¶
NewWebAuth validates configuration and returns a usable WebAuth.
Example ¶
Browser sign-in over the Authorization Code + PKCE flow.
package main
import (
"fmt"
"log"
"net/http"
"os"
lumoauth "github.com/lumoauth/lumo-auth-go"
)
func main() {
auth, err := lumoauth.NewWebAuth(lumoauth.WebConfig{
Organization: os.Getenv("LUMO_ORG_ID"),
ClientID: os.Getenv("LUMO_CLIENT_ID"),
ClientSecret: os.Getenv("LUMO_CLIENT_SECRET"),
SessionSecret: os.Getenv("SESSION_SECRET"),
})
if err != nil {
log.Fatal(err)
}
dashboard := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user := lumoauth.UserFromContext(r.Context())
fmt.Fprintf(w, "Hi %s", user.Email)
})
mux := http.NewServeMux()
mux.Handle("/auth/", auth.Router())
mux.Handle("/", auth.Middleware(auth.RequireAuth(dashboard)))
log.Fatal(http.ListenAndServe(":8080", mux))
}
Output:
func (*WebAuth) CallbackHandler ¶
func (w *WebAuth) CallbackHandler() http.HandlerFunc
CallbackHandler completes the sign-in flow.
func (*WebAuth) Client ¶
Client returns a LumoAuth client bound to this deployment and org, for calls made outside the sign-in flow. It carries no user credentials — use ClientForRequest for those.
func (*WebAuth) ClientForRequest ¶
ClientForRequest returns a client authenticated as the signed-in user of this request, so authorization checks run under their identity:
client, err := auth.ClientForRequest(req)
if err != nil {
return err
}
ok, err := client.Permissions.Check(req.Context(), "document.edit", nil)
func (*WebAuth) LoginHandler ¶
func (w *WebAuth) LoginHandler() http.HandlerFunc
LoginHandler starts the sign-in flow. Mount it directly when you would rather wire routes yourself than mount Router.
func (*WebAuth) LogoutHandler ¶
func (w *WebAuth) LogoutHandler() http.HandlerFunc
LogoutHandler clears the session.
func (*WebAuth) Middleware ¶
Middleware reads the signed-in user from the session and attaches the user and their tokens to the request context. It does NOT enforce authentication — compose it with RequireAuth to gate a route.
func (*WebAuth) RefreshSession ¶
RefreshSession renews an expired access token using the stored refresh token and writes the result back to the session. It reports whether a refresh actually happened.
func (*WebAuth) RequireAuth ¶
RequireAuth gates a handler on a signed-in user, answering 401 when there is none. It must run inside Middleware, which is what puts the user on the context.
func (*WebAuth) RequireAuthRedirect ¶
RequireAuthRedirect gates a handler on a signed-in user, sending anyone else to loginPath with a return_to pointing back here — the right behaviour for HTML pages, where RequireAuth's bare 401 is not.
func (*WebAuth) Router ¶
Router serves the sign-in endpoints: login, callback, and logout.
The paths come from CallbackPath, so the default "/auth/callback" gives /auth/login, /auth/callback, and /auth/logout. Mount it at that prefix:
mux := http.NewServeMux()
mux.Handle("/auth/", auth.Router())
It returns a plain http.Handler, so it mounts into chi, gorilla/mux, or net/http alike. The bare /login, /callback, and /logout paths are also registered, so mounting behind http.StripPrefix works too.
type WebConfig ¶
type WebConfig struct {
// BaseURL is the LumoAuth deployment, e.g. "https://app.lumoauth.dev".
// Defaults to $LUMOAUTH_URL, then DefaultBaseURL.
BaseURL string
// Organization is the tenant slug that owns the OAuth client.
// Defaults to $LUMOAUTH_ORG_ID.
Organization string
// ClientID is the OAuth client registered for this app. Required.
ClientID string
// ClientSecret is required for confidential clients; omit for public
// ones, which rely on PKCE alone.
ClientSecret string
// SessionSecret keys the cookie store. Use at least 32 random bytes,
// and keep it stable across restarts or every session is invalidated.
// Required.
SessionSecret string
// CallbackPath is the absolute path LumoAuth redirects back to. It
// must match a redirect URI registered on the OAuth client.
// Defaults to "/auth/callback".
CallbackPath string
// Scope is the space-separated scope list.
// Defaults to "openid profile email".
Scope string
// PostLoginRedirect is where users land after signing in.
// Defaults to "/".
PostLoginRedirect string
// PostLogoutRedirect is where users land after signing out.
// Defaults to "/".
PostLogoutRedirect string
// HTTPClient overrides the client used for token exchange and
// UserInfo. Defaults to a 10s-timeout client.
HTTPClient *http.Client
// CookieName is the session cookie's name. Defaults to "lumo_session".
CookieName string
// CookieSecure controls the Secure flag. Nil means true — the cookie
// is only sent over HTTPS. Set Bool(false) for local development over
// plain HTTP, and leave it alone in production.
CookieSecure *bool
// SessionMaxAge bounds the session cookie's lifetime.
// Defaults to 30 days.
SessionMaxAge time.Duration
// SkipCertValidation disables TLS verification. Local development only.
SkipCertValidation bool
}
WebConfig configures NewWebAuth.
type ZanzibarCheck ¶
type ZanzibarCheck struct {
Allowed bool `json:"allowed"`
Object string `json:"object,omitempty"`
Relation string `json:"relation,omitempty"`
Subject string `json:"subject,omitempty"`
User string `json:"user,omitempty"`
}
ZanzibarCheck is the result of a relationship check.
type ZanzibarResource ¶
type ZanzibarResource struct {
// contains filtered or unexported fields
}
ZanzibarResource covers Google-Zanzibar-style relationship-based access control: does a subject have a relation to an object?
Objects and subjects are "namespace:id" tuples — "document:readme", "user:alice" — and subjects may name a relation ("group:eng#member").
func (*ZanzibarResource) Check ¶
func (r *ZanzibarResource) Check(ctx context.Context, object, relation, subject string) (bool, error)
Check reports whether the relationship holds, directly or by inheritance.
ok, err := client.Zanzibar.Check(ctx, "document:readme", "viewer", "user:bob")
Example ¶
Relationship-based checks read as questions about a tuple.
package main
import (
"context"
"fmt"
"log"
"os"
lumoauth "github.com/lumoauth/lumo-auth-go"
)
func main() {
client, _ := lumoauth.New(
lumoauth.WithAPIKey(os.Getenv("LUMOAUTH_API_KEY")),
lumoauth.WithOrgID("acme-corp"),
)
allowed, err := client.Zanzibar.Check(context.Background(),
"document:readme", lumoauth.RelationViewer, "user:bob")
if err != nil {
log.Fatal(err)
}
fmt.Println(allowed)
}
Output:
func (*ZanzibarResource) CheckDetailed ¶
func (r *ZanzibarResource) CheckDetailed(ctx context.Context, object, relation, subject string) (*ZanzibarCheck, error)
CheckDetailed is Check with the full response.
func (*ZanzibarResource) Expand ¶
func (r *ZanzibarResource) Expand(ctx context.Context, object, relation string) (*ZanzibarUsersetNode, error)
Expand returns the full userset tree for object#relation — every subject that satisfies the relation, including those reached through namespace rewrites.
It is the inverse of Check: Check answers "does this subject have the relation", Expand answers "who has it at all".
Expansion always reveals other subjects, so the server requires the oracle privilege (the authz.check permission or the authz:check scope). There is no self-service variant — a token that can only check itself gets a 403.
tree, err := client.Zanzibar.Expand(ctx, "document:readme", "viewer")
type ZanzibarUsersetNode ¶
type ZanzibarUsersetNode struct {
Type string `json:"type"` // "union", "intersection" or "leaf"
Object string `json:"object,omitempty"`
Relation string `json:"relation,omitempty"`
Children []ZanzibarUsersetNode `json:"children,omitempty"`
Subjects []string `json:"subjects,omitempty"`
}
ZanzibarUsersetNode is a node in an expansion tree. Leaves carry Subjects; union/intersection nodes carry Children of the same shape.
Source Files
¶
- aauth.go
- aauth_keys.go
- aauth_signing.go
- aauth_verify.go
- agent.go
- client.go
- delegation_chain.go
- doc.go
- errors.go
- http.go
- jit_context.go
- resource_abac.go
- resource_agents.go
- resource_approvals.go
- resource_auth.go
- resource_delegation.go
- resource_jit.go
- resource_mcp.go
- resource_permissions.go
- resource_zanzibar.go
- routes.go
- types.go
- util.go
- web_auth.go