Documentation
¶
Overview ¶
Package lumoauth is the official Go SDK for LumoAuth — authentication and authorization for applications and AI agents.
It exposes these 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.
VerifyAccessToken and RequireAccessToken — for an MCP server or API that receives LumoAuth access tokens: local verification against the organization's keys, including DPoP sender-constraint checks. DPoPSigner is the client side of DPoP (RFC 9449). VerifyJitToken verifies a JIT approval that a client sends with its access token.
MCPTransport — an http.RoundTripper for the official MCP Go SDK that adds an agent's MCP token to each request.
WebAuth — browser sign-in. Wires the OAuth 2.1 Authorization Code + PKCE flow into any net/http-compatible router, with sessions in an encrypted cookie or in a session store of your choice (WebConfig.Store), optionally with pushed and signed requests (WebConfig.UsePAR, WebConfig.ResponseMode).
AuthResource (client.Auth) — the OAuth endpoints for your own flows: device authorization, PAR, CIBA, introspection, dynamic client registration, signed request objects (JAR) and answers (JARM).
PoppyResource (client.Poppy) — for an API that personal agents call (Personal Agent Protocol). It asks LumoAuth to verify the Poppy-Session header of a request, and PoppyResource.Middleware does that for a net/http route.
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, "web:search"); 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())
Personal agents ¶
An API that personal agents call verifies each request with LumoAuth. The client authenticates as a confidential application whose allowed scopes include poppy:verify:
client, err := lumoauth.New(
lumoauth.WithOrgID("acme-corp"),
lumoauth.WithClientCredentials(clientID, clientSecret),
)
if err != nil {
return err
}
verified, err := client.Poppy.Middleware(lumoauth.PoppyMiddlewareOptions{
PublicOrigin: "https://shop.example.com", // from your configuration
RequiredScope: []string{"orders:read"},
})
if err != nil {
return err
}
mux.Handle("GET /api/orders", verified(ordersHandler))
// In a handler:
who, _ := lumoauth.PoppyFromContext(req.Context())
A refused request gets LumoAuth's response, unchanged. A failed verification call is never sent to the personal agent. PoppyResource.VerifyRequest and WritePoppyRefusal are the same steps without the middleware, and PoppyResource.GetSessionStatus and PoppyResource.EndSession look up and end a Session.
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.
Custom domains ¶
An organization can serve LumoAuth on its own domain. Pass the domain with WithCustomDomain, or with the CustomDomain field of AgentConfig, WebConfig and AAuthConfig:
client, err := lumoauth.New(
lumoauth.WithCustomDomain("auth.acme.com"),
lumoauth.WithAPIKey(os.Getenv("LUMOAUTH_API_KEY")),
)
The client then sends every request to that domain, and no path carries the /orgs/{orgId} segment. The organization ID is not needed. The issuer is the bare domain, https://auth.acme.com, and Client.Issuer returns it. To verify access tokens of such an organization, set CustomDomain in AccessTokenVerifyOptions in place of Issuer.
AAuth is the one exception. LumoAuth names the AAuth issuer with the platform address on every host, so the SDK never derives it from the domain. AAuthClient.ResolveIssuer and VerifyAuthToken with VerifyOptions.CustomDomain read it from the issuer metadata document of the custom domain.
Configuration ¶
Options fall back to the environment:
LUMOAUTH_URL instance URL (default https://app.lumoauth.dev) LUMOAUTH_ORG_ID organization slug LUMOAUTH_CUSTOM_DOMAIN the organization's own domain (wins over LUMOAUTH_URL) LUMOAUTH_API_KEY organization 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 AnyCapabilityCovers(capabilities []string, action string) bool
- func Bool(b bool) *bool
- func BuildPath(template string, params map[string]string) (string, error)
- func BuildPoppyVerifyBody(publicOrigin, method, target string, headers http.Header, ...) (map[string]any, error)
- func BuildSignatureBase(components []string, values map[string]string, created int64, nonce string) string
- func CapabilityCovers(capability, action string) bool
- func ContentDigestSHA256(body []byte) string
- func ContextWithAccessToken(ctx context.Context, claims *AccessTokenClaims) context.Context
- func ContextWithPoppy(ctx context.Context, verification *PoppyVerification) context.Context
- func DPoPAccessTokenHash(accessToken string) string
- func DPoPBound(token string) bool
- func ErrorCode(err error) string
- func GenerateDPoPKeyPEM() (string, error)
- func GenerateNonce() (string, error)
- func IsJARMResponseMode(mode string) bool
- func IssuerFor(baseURL, orgID string) string
- func LoadPrivateKey(pemData string) (crypto.Signer, error)
- func NormalizeCapability(capability string) string
- func OrgIDFromIssuer(issuer string) string
- func ParseActorChain(token string) ([]string, error)
- func RejectionReason(err error) string
- func RequireAccessToken(opts AccessTokenVerifyOptions) func(http.Handler) http.Handler
- 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
- func WritePoppyRefusal(w http.ResponseWriter, verification *PoppyVerification) error
- 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) CustomDomain() string
- 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) ResolveIssuer(ctx context.Context) (string, 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 AccessTokenClaims
- type AccessTokenKeyCache
- type AccessTokenVerifyOptions
- type ActorClaim
- 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) AskWithOptions(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) AuthorizeMcpTool(ctx context.Context, serverID, tool string) (*AgentMcpToolDecision, 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) ClientAssertion() (string, error)
- func (a *Agent) ClientID() string
- func (a *Agent) ClientSecret() string
- func (a *Agent) CustomDomain() string
- func (a *Agent) DPoP() *DPoPSigner
- 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) GetConnectionToken(ctx context.Context, connectionID string, params ConnectionTokenParams) (*ConnectionToken, 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) IsAllowedWithOptions(ctx context.Context, action string, actionContext map[string]any, ...) (bool, error)
- func (a *Agent) ListConnections(ctx context.Context) ([]AgentConnection, 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) ReportUsage(ctx context.Context, tokens int, costUSD float64) (*UsageReportResult, error)
- func (a *Agent) RequireCapability(ctx context.Context, capability string) error
- func (a *Agent) TokenScopes() []string
- func (a *Agent) TokenType() string
- type AgentAskResult
- type AgentBudget
- type AgentConfig
- type AgentConnection
- type AgentIdentity
- type AgentMcpToolDecision
- type AgentRegistration
- type AgentsResource
- func (r *AgentsResource) Ask(ctx context.Context, action string, actionContext map[string]any) (*AgentAskResult, error)
- func (r *AgentsResource) AskWithOptions(ctx context.Context, action string, actionContext map[string]any, ...) (*AgentAskResult, error)
- func (r *AgentsResource) Attest(ctx context.Context, params AttestParams) (*AttestResult, error)
- func (r *AgentsResource) AuthorizeMcpTool(ctx context.Context, serverID, tool string) (*AgentMcpToolDecision, error)
- func (r *AgentsResource) Budget(ctx context.Context) (*AgentBudget, error)
- func (r *AgentsResource) Capabilities(ctx context.Context) ([]string, error)
- func (r *AgentsResource) GetConnectionToken(ctx context.Context, connectionID string, params ConnectionTokenParams) (*ConnectionToken, 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) IsAllowedWithOptions(ctx context.Context, action string, actionContext map[string]any, ...) (bool, error)
- func (r *AgentsResource) ListConnections(ctx context.Context) ([]AgentConnection, error)
- func (r *AgentsResource) Me(ctx context.Context) (*AgentIdentity, error)
- func (r *AgentsResource) Register(ctx context.Context, params RegisterParams) (*AgentRegistration, error)
- func (r *AgentsResource) ReportUsage(ctx context.Context, tokens int, costUSD float64) (*UsageReportResult, error)
- type ApplicationConsentParams
- 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 AskOptions
- type AttestParams
- type AttestResult
- type AttestWorkloadOptions
- type AudienceClaim
- type AuthResource
- func (r *AuthResource) AuthorizationURL(params AuthorizationURLParams) (string, error)
- func (r *AuthResource) BackchannelAuthorize(ctx context.Context, params BackchannelAuthorizeParams) (*BackchannelAuthorizeResponse, error)
- func (r *AuthResource) ClientAttestationHeaders(attestation ClientAttestation) (map[string]string, error)
- func (r *AuthResource) ClientCredentials(ctx context.Context, clientID, clientSecret string, scopes ...string) (*TokenResponse, error)
- func (r *AuthResource) ClientCredentialsWithAssertion(ctx context.Context, clientID, clientAssertion string, scopes ...string) (*TokenResponse, error)
- func (r *AuthResource) ClientCredentialsWithParams(ctx context.Context, params ClientCredentialsParams) (*TokenResponse, error)
- func (r *AuthResource) CreateRequestObject(params AuthorizationURLParams, opts RequestObjectOptions) (string, error)
- func (r *AuthResource) DeviceAuthorization(ctx context.Context, params DeviceAuthorizationParams) (*DeviceAuthorizationResponse, error)
- func (r *AuthResource) EndSessionURL(params EndSessionURLParams) (string, error)
- func (r *AuthResource) ExchangeCode(ctx context.Context, params ExchangeCodeParams) (*TokenResponse, error)
- func (r *AuthResource) GetClientConfiguration(ctx context.Context, clientID, registrationAccessToken string) (*RegisteredClient, error)
- func (r *AuthResource) Introspect(ctx context.Context, token string, opts IntrospectOptions) (*TokenIntrospection, error)
- func (r *AuthResource) PollBackchannelToken(ctx context.Context, authReqID string, opts PollOptions) (*TokenResponse, error)
- func (r *AuthResource) PollDeviceToken(ctx context.Context, deviceCode string, opts PollOptions) (*TokenResponse, error)
- func (r *AuthResource) PushAuthorizationRequest(ctx context.Context, params AuthorizationURLParams, auth ClientAuth) (*PushedAuthorizationResponse, error)
- func (r *AuthResource) RefreshToken(ctx context.Context, params RefreshTokenParams) (*TokenResponse, error)
- func (r *AuthResource) RegisterClient(ctx context.Context, metadata ClientMetadata, opts RegisterClientOptions) (*RegisteredClient, 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)
- func (r *AuthResource) VerifyAuthorizationResponse(ctx context.Context, responseJWT string, opts AuthorizationResponseOptions) (*AuthorizationResponse, error)
- type AuthTokenParams
- type AuthorizationResponse
- type AuthorizationResponseOptions
- type AuthorizationURLParams
- type BackchannelAuthorizeParams
- type BackchannelAuthorizeResponse
- 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) CustomDomain() string
- func (c *Client) DPoP() *DPoPSigner
- 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) Issuer() (string, error)
- func (c *Client) OrgID() string
- func (c *Client) OrgPath(path string) (string, error)
- type ClientAssertionOptions
- type ClientAssertionSigner
- func GenerateClientAssertionSigner(algorithm, keyID string) (*ClientAssertionSigner, error)
- func LoadClientAssertionSigner(pemData string, opts ClientAssertionOptions) (*ClientAssertionSigner, error)
- func NewClientAssertionSigner(key crypto.Signer, opts ClientAssertionOptions) (*ClientAssertionSigner, error)
- func (s *ClientAssertionSigner) Algorithm() string
- func (s *ClientAssertionSigner) Assertion(clientID, audience string) (string, error)
- func (s *ClientAssertionSigner) JWKS() (JWKS, error)
- func (s *ClientAssertionSigner) KeyID() string
- func (s *ClientAssertionSigner) PrivateKeyPEM() (string, error)
- func (s *ClientAssertionSigner) PublicJWK() (JWK, error)
- type ClientAttestation
- type ClientAuth
- type ClientCredentialsParams
- type ClientMetadata
- type ConfidentialClient
- type ConfigError
- type ConnectionToken
- type ConnectionTokenParams
- type ConsentURLParamsdeprecated
- type CreateTaskParams
- type DPoPProofOption
- type DPoPRequest
- type DPoPSigner
- func (s *DPoPSigner) Algorithm() string
- func (s *DPoPSigner) AuthorizeRequest(req *http.Request, accessToken string) error
- func (s *DPoPSigner) Nonce(rawURL string) string
- func (s *DPoPSigner) Proof(method, rawURL string, opts ...DPoPProofOption) (string, error)
- func (s *DPoPSigner) PublicJWK() JWK
- func (s *DPoPSigner) RememberNonce(resp *http.Response) bool
- func (s *DPoPSigner) SetNonce(rawURL, nonce string)
- func (s *DPoPSigner) Thumbprint() string
- type DelegationApplication
- type DelegationChain
- func (c *DelegationChain) ActiveSessions() []string
- func (c *DelegationChain) ActorChain(token string) ([]string, error)
- func (c *DelegationChain) ConsentState(sessionID string) string
- 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) Forget(sessionID string)
- 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
- func (c *DelegationChain) SetUserTokens(sessionID string, tokens *TokenResponse) error
- type DelegationResource
- func (r *DelegationResource) ApplicationConsentURL(params ApplicationConsentParams) (string, error)
- func (r *DelegationResource) ConsentURL(params ConsentURLParams) (string, error)deprecated
- 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 DeviceAuthorizationParams
- type DeviceAuthorizationResponse
- type EndSessionURLParams
- type EvaluateTaskParams
- type ExchangeCodeParams
- type ID
- type IntrospectOptions
- 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 JitTokenClaims
- type JitTokenVerifyOptions
- type Keypair
- type MCPTransport
- type MCPTransportOptions
- type McpResource
- func (r *McpResource) AuthorizeTool(ctx context.Context, params McpToolAuthorizeParams) (*McpToolDecision, error)
- func (r *McpResource) Token(ctx context.Context, serverID, subjectToken string) (string, error)
- func (r *McpResource) TokenDetailed(ctx context.Context, serverID, subjectToken string) (*McpToken, error)
- type McpToken
- type McpToolAuthorizeParams
- type McpToolDecision
- type McpToolResource
- type McpToolSubject
- type MemoryReplayCache
- type NetworkError
- type Option
- func WithAPIKey(apiKey string) Option
- func WithAccessToken(token string) Option
- func WithBaseURL(baseURL string) Option
- func WithClientCredentials(clientID, clientSecret string) Option
- func WithCustomDomain(domain string) Option
- func WithDPoP(signer *DPoPSigner) 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
- func WithoutCredential() 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 PollOptions
- type PoppyAccount
- type PoppyMiddlewareOptions
- type PoppyRelayResponse
- type PoppyRequest
- type PoppyResource
- func (r *PoppyResource) EndSession(ctx context.Context, personalAgent, sid string) (bool, error)
- func (r *PoppyResource) GetSessionStatus(ctx context.Context, personalAgent, sid string) (*PoppySessionStatus, error)
- func (r *PoppyResource) Middleware(opts PoppyMiddlewareOptions) (func(http.Handler) http.Handler, error)
- func (r *PoppyResource) VerifyHTTPRequest(ctx context.Context, publicOrigin string, req *http.Request, ...) (*PoppyVerification, error)
- func (r *PoppyResource) VerifyRequest(ctx context.Context, request PoppyRequest, opts *PoppyVerifyOptions) (*PoppyVerification, error)
- type PoppySession
- type PoppySessionStatus
- type PoppyVerification
- type PoppyVerifyOptions
- type PushedAuthorizationResponse
- type RecordedUsage
- type RefreshParams
- type RefreshTokenParams
- type RegisterClientOptions
- type RegisterParams
- type RegisteredClient
- type ReplayCache
- type RequestObjectOptions
- type RequestPermissionOptions
- type RequestPermissionParams
- type RevokeParams
- type Route
- type SessionTokens
- type SignOptions
- type TokenConfirmation
- type TokenExchangeParams
- type TokenIntrospection
- type TokenProvider
- type TokenResponse
- type TokenSource
- type UsageReportResult
- 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 WorkloadIdentity
- 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 ¶
- Package (ErrorHandling)
- AbacResource.Check
- Agent.RequireCapability
- ApprovalsResource.Require
- Client.Do
- GenerateKeypair
- New
- NewAAuthClient
- NewAgent
- NewDelegationChainForApplication
- NewJITContext
- NewWebAuth
- PoppyResource.Middleware
- PoppyResource.VerifyHTTPRequest
- VerifyAuthToken
- WithCustomDomain
- ZanzibarResource.Check
Constants ¶
const ( AAuthTokenTypeAuth = "auth_token" AAuthTokenTypeRefresh = "refresh_token" )
Token types accepted by Revoke.
const ( TokenRejectedMalformed = "malformed" TokenRejectedType = "wrong_type" TokenRejectedAlgorithm = "bad_algorithm" TokenRejectedIssuer = "wrong_issuer" TokenRejectedUnknownKey = "unknown_key" TokenRejectedSignature = "bad_signature" TokenRejectedExpired = "expired" TokenRejectedNotYetValid = "not_yet_valid" TokenRejectedAudience = "wrong_audience" TokenRejectedTestToken = "test_token" TokenRejectedDPoPRequired = "dpop_required" TokenRejectedDPoPScheme = "dpop_scheme" TokenRejectedDPoPProof = "dpop_proof" TokenRejectedDPoPBinding = "dpop_binding" TokenRejectedDPoPReplay = "dpop_replay" // TokenRejectedDPoPNonce: the proof lacks the nonce that the resource // server expects (DPoPRequest.Nonce), or carries another one. Answer it // with use_dpop_nonce and the expected value in DPoP-Nonce (RFC 9449 // §9); RequireAccessToken does this. TokenRejectedDPoPNonce = "dpop_nonce" // TokenRejectedState: a verified authorization response whose state is // not the one that the sign-in sent (VerifyAuthorizationResponse). TokenRejectedState = "state_mismatch" // TokenRejectedNotJIT: a verified token that is not a LumoAuth JIT // approval (jit is not true, or it names no agent or no approved // authorization details). TokenRejectedNotJIT = "not_jit" // TokenRejectedJITNotForCaller: a JIT token issued to another caller // (another person, or another agent). TokenRejectedJITNotForCaller = "jit_token_not_for_caller" // TokenRejectedJITInsufficient: a valid JIT token that does not approve // what the call needs (JitTokenVerifyOptions.RequiredDetails). TokenRejectedJITInsufficient = "insufficient_authorization_details" )
Rejection reasons carried by the *ValidationError that VerifyAccessToken returns, in ValidationError.Reason. They are stable; match on them rather than on the message.
const ( EnvAgentClientID = "AGENT_CLIENT_ID" EnvAgentClientSecret = "AGENT_CLIENT_SECRET" )
Environment variables read by NewAgent when the corresponding field is left empty.
const ( // VaultGrantNotFound (404): the person has not linked the connection, // or no machine grant exists. LumoAuth gives the same answer for an // unknown person. VaultGrantNotFound = "grant_not_found" // VaultAgentNotAllowed (403): the connection's allowed agents leave // this agent out. VaultAgentNotAllowed = "agent_not_allowed" // VaultDelegationNotAllowed (403): the person has not allowed this // agent on their grant. VaultDelegationNotAllowed = "delegation_not_allowed" // VaultDelegationNotPermitted (403): the agent may not act on behalf of // users at all. VaultDelegationNotPermitted = "delegation_not_permitted" // VaultConnectionNotFound (404): no connection has this ID. VaultConnectionNotFound = "connection_not_found" )
Codes of the vault's refusals (APIError.Code).
const ( EnvBaseURL = "LUMOAUTH_URL" EnvOrgID = "LUMOAUTH_ORG_ID" EnvAPIKey = "LUMOAUTH_API_KEY" )
Environment variables read when the corresponding option is not passed.
const ( // ClientAssertionType is the client_assertion_type of a JWT client assertion. ClientAssertionType = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer" // ClientAssertionTyp is the typ header of a client-authentication JWT. ClientAssertionTyp = "client-authentication+jwt" // MaxClientAssertionLifetime is the longest validity LumoAuth accepts. MaxClientAssertionLifetime = 10 * time.Minute // EnvAgentPrivateKey holds the PEM private key of a private key JWT agent. EnvAgentPrivateKey = "AGENT_PRIVATE_KEY" // EnvAgentKeyID holds the kid of the registered public key. EnvAgentKeyID = "AGENT_KEY_ID" )
const ( DPoPAlgES256 = "ES256" DPoPAlgEdDSA = "EdDSA" )
DPoP proof algorithms this SDK signs with. The server also accepts the RSA and larger EC families; ES256 is the RFC 9449 default.
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 ( ResponseModeJWT = "jwt" ResponseModeQueryJWT = "query.jwt" ResponseModeFragmentJWT = "fragment.jwt" ResponseModeFormPostJWT = "form_post.jwt" )
JARM response modes (the answer comes back as a signed `response` JWT).
const ( ClientAttestationHeader = "OAuth-Client-Attestation" ClientAttestationPoPHeader = "OAuth-Client-Attestation-PoP" // ClientAttestationTyp is the typ header of the attester's JWT. ClientAttestationTyp = "oauth-client-attestation+jwt" // ClientAttestationPoPTyp is the typ header of the proof of possession. ClientAttestationPoPTyp = "oauth-client-attestation-pop+jwt" )
Header names of attestation-based client authentication (attest_jwt_client_auth).
const ( GrantTypeDeviceCode = "urn:ietf:params:oauth:grant-type:device_code" GrantTypeCIBA = "urn:openid:params:grant-type:ciba" )
Grant types of the two polling flows.
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 ( // ClientSecretBasic sends the client ID and secret in an HTTP Basic // Authorization header. ClientSecretBasic = "client_secret_basic" // ClientSecretPost sends them as the client_id and client_secret form // fields. ClientSecretPost = "client_secret_post" )
Methods of sending a client secret to the token endpoint (RFC 6749 §2.3.1). A client assertion (private_key_jwt) is chosen by setting ClientAssertion instead.
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" // Device authorization grant (RFC 8628). RouteOAuthDeviceAuthorization = "oauth.deviceAuthorization" // Pushed authorization requests (RFC 9126). RouteOAuthPAR = "oauth.par" // OpenID CIBA, backchannel authentication request. RouteOAuthBackchannelAuthorize = "oauth.backchannelAuthorize" // Token introspection (RFC 7662). RouteOAuthIntrospect = "oauth.introspect" // Dynamic client registration (RFC 7591) and its read (RFC 7592). RouteOAuthRegisterClient = "oauth.registerClient" RouteOAuthGetClientConfiguration = "oauth.getClientConfiguration" // ── Web (HTML) routes used by identifier-first sign-in ──────────── RouteWebCheckEmail = "web.checkEmail" RouteWebMagicLink = "web.magicLink" // ── Agents (identity) ───────────────────────────────────────────── RouteAgentsAsk = "agents.ask" RouteAgentsAttest = "agents.attest" RouteAgentsAuthorizeMcpTool = "agents.authorizeMcpTool" RouteAgentsMe = "agents.me" RouteAgentsRegister = "agents.register" RouteAgentsReportUsage = "agents.reportUsage" // Token vault: the agent's outbound connections and their tokens. RouteAgentsListConnections = "agents.listConnections" RouteAgentsGetConnectionToken = "agents.getConnectionToken" // ── MCP (per-tool checks asked by an MCP server) ────────────────── RouteMcpAuthorizeTool = "mcp.authorizeTool" // ── Personal Agent Protocol (Session verification for your own API) ─ RoutePoppyVerifyRequest = "poppy.verifyRequest" RoutePoppyGetSessionStatus = "poppy.getSessionStatus" RoutePoppyEndSession = "poppy.endSession" // ── 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 ( // DecidedByCapability: the agent's capabilities decided (no policy or // relationship data applied). DecidedByCapability = "capability" // DecidedByPDP: the organization's policies and relationships decided. DecidedByPDP = "pdp" // DecidedByDenyOverride: an explicit ABAC deny overrode a capability that // would have allowed the action. DecidedByDenyOverride = "deny_override" )
Values of AgentAskResult.DecidedBy.
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 ( PoppyStatusActive = "active" PoppyStatusEnded = "ended" // PoppyStatusUnknown means that no Session has the sid: it never // started, or nothing used it for the idle period. PoppyStatusUnknown = "unknown" )
Session states that PoppySessionStatus.Status reports.
const AbacMaxBulkRequests = 100
AbacMaxBulkRequests is the server's cap on one bulk check.
const DPoPHeader = "DPoP"
DPoPHeader is the request header that carries a DPoP proof.
const DPoPNonceHeader = "DPoP-Nonce"
DPoPNonceHeader is the response header a server uses to hand out a nonce.
const DPoPTokenType = "DPoP"
DPoPTokenType is the token_type of a DPoP-bound token.
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 ( // DefaultPollInterval is the wait between two polls when the server // names none (RFC 8628 §3.2). DefaultPollInterval = 5 * time.Second )
const EnvCustomDomain = "LUMOAUTH_CUSTOM_DOMAIN"
EnvCustomDomain is read when the custom domain option is not passed, by every constructor that reads EnvBaseURL.
const JITTokenTyp = "JWT"
JITTokenTyp is the typ header of a LumoAuth JIT token.
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 = 5
MaxDelegationDepth is the number of actors that a delegation chain may hold: the depth of the nested `act` claims of a token (user → agent → sub-agent → … , the user not counted). LumoAuth refuses the exchange that would add a sixth actor with 400 invalid_request ("Delegation chain too deep: …"); DelegationChain reports it as a ValidationError.
const RequestObjectTyp = "oauth-authz-req+jwt"
RequestObjectTyp is the typ header of a request object (RFC 9101 §10.8).
const Version = "1.8.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, and an OAuth endpoint's // invalid_client answer at any status. ErrAuthentication = errors.New("lumoauth: authentication failed") // ErrPermissionDenied matches HTTP 403 responses, and an OAuth // endpoint's unauthorized_client or access_denied answer at any status. 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, except the server's budget refusal, which matches ErrRateLimited and ErrBudgetExceeded (see above).
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 ErrDelegationNotRevoked = errors.New("lumoauth: the delegation was forgotten locally, not revoked at LumoAuth")
ErrDelegationNotRevoked matches the error of DelegationChain.Revoke when it could only forget the session's local state: the chain holds no refresh token for the session, or no application credentials to revoke it with. The person's grant at LumoAuth then still stands. The error also matches ErrConfig.
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"}, RouteOAuthDeviceAuthorization: {"POST", orgBase + "/oauth/device_authorization"}, RouteOAuthPAR: {"POST", orgBase + "/oauth/par"}, RouteOAuthBackchannelAuthorize: {"POST", orgBase + "/oauth/bc-authorize"}, RouteOAuthIntrospect: {"POST", orgBase + "/oauth/introspect"}, RouteOAuthRegisterClient: {"POST", orgBase + "/connect/register"}, RouteOAuthGetClientConfiguration: {"GET", orgBase + "/connect/register/{clientId}"}, RouteWebCheckEmail: {"POST", "/orgs/{orgId}/api/v1/oauth/check-email"}, RouteWebMagicLink: {"POST", "/orgs/{orgId}/api/v1/oauth/magic-link"}, RouteAgentsAsk: {"POST", orgBase + "/agents/ask"}, RouteAgentsAttest: {"POST", orgBase + "/agents/{agentId}/attest"}, RouteAgentsAuthorizeMcpTool: {"POST", orgBase + "/agents/me/mcp/authorize"}, RouteAgentsMe: {"GET", orgBase + "/agents/me"}, RouteAgentsRegister: {"POST", orgBase + "/agents/register"}, RouteAgentsReportUsage: {"POST", orgBase + "/agents/me/usage"}, RouteAgentsListConnections: {"GET", orgBase + "/agents/me/connections"}, RouteAgentsGetConnectionToken: {"POST", orgBase + "/agents/me/connections/{connectionId}/token"}, RouteMcpAuthorizeTool: {"POST", orgBase + "/mcp/servers/{serverId}/tools/authorize"}, RoutePoppyVerifyRequest: {"POST", orgBase + "/poppy/sessions/verify"}, RoutePoppyGetSessionStatus: {"POST", orgBase + "/poppy/sessions/status"}, RoutePoppyEndSession: {"POST", orgBase + "/poppy/sessions/end"}, 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 AnyCapabilityCovers ¶ added in v1.4.0
AnyCapabilityCovers reports whether any capability in the list covers the action.
func BuildPath ¶
BuildPath fills `{param}` placeholders in a path template. Values are URL-escaped. The registry's templates are in the platform form, with the /orgs/{orgId} segment; a client with a custom domain removes that segment before it builds the path.
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 BuildPoppyVerifyBody ¶ added in v1.7.0
func BuildPoppyVerifyBody(publicOrigin, method, target string, headers http.Header, opts *PoppyVerifyOptions) (map[string]any, error)
BuildPoppyVerifyBody builds the JSON body of a verification call for an incoming request. It is a pure function: it makes no call and reads no configuration.
- method is sent in upper case.
- url is publicOrigin without trailing slashes, followed by the path of target as the client sent it. The query and the fragment are dropped, and an empty path is "/". publicOrigin may carry a base path. The URL is never built from the Host header.
- headers holds only Poppy-Session, Poppy-Version, Poppy-Extensions, Authorization and DPoP, matched without regard to case, under their lower-case names. A repeated header is joined with ", ". A missing or empty header is left out.
- required_scope, resource and allow_replay are sent only when opts sets them.
target is the request target of the request line, for example "/api/orders?page=2". On a net/http server that is r.RequestURI.
It returns a *ConfigError for a missing or invalid publicOrigin and a *ValidationError for a missing method or a target that is not a path. opts may be nil.
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 CapabilityCovers ¶ added in v1.4.0
CapabilityCovers reports whether one capability covers an action, in any spelling of either. CapabilityCovers("users:*", "USERS.DELETE") is true; CapabilityCovers("invoices:*", "invoices") and CapabilityCovers("invoices:read", "invoices-read") are false.
func ContentDigestSHA256 ¶
ContentDigestSHA256 computes an RFC 9530 Content-Digest header value over exact body bytes, using standard base64 (the server base64-decodes it).
func ContextWithAccessToken ¶ added in v1.2.0
func ContextWithAccessToken(ctx context.Context, claims *AccessTokenClaims) context.Context
ContextWithAccessToken stores verified claims in a context, for handlers that verify tokens themselves but share downstream code with RequireAccessToken.
func ContextWithPoppy ¶ added in v1.7.0
func ContextWithPoppy(ctx context.Context, verification *PoppyVerification) context.Context
ContextWithPoppy stores a verified result in a context, for handlers that call VerifyRequest themselves but share downstream code with Middleware.
func DPoPAccessTokenHash ¶ added in v1.2.0
DPoPAccessTokenHash computes the `ath` claim: base64url(SHA-256(token)).
func DPoPBound ¶ added in v1.2.0
DPoPBound reports whether a JWT access token is sender-constrained — it carries a cnf.jkt claim — and so must be presented with the DPoP scheme and a proof. Opaque or malformed tokens are reported as unbound.
The claims are read WITHOUT signature verification: this only picks the authorization scheme, it never grants anything.
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 GenerateDPoPKeyPEM ¶ added in v1.2.0
GenerateDPoPKeyPEM generates a P-256 key and returns it as a PKCS#8 PEM block, for storing in a secret manager and loading with LoadDPoPSigner.
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 IsJARMResponseMode ¶ added in v1.8.0
IsJARMResponseMode reports whether a response mode returns the answer as a signed JWT in a single `response` parameter.
func IssuerFor ¶ added in v1.3.0
IssuerFor is the issuer identifier of an organization on the platform host baseURL: the issuer of /orgs/{orgID}/api/v1/.well-known/openid-configuration, and the aud a client assertion must carry. On a custom domain the issuer is the bare domain, for example "https://auth.acme.com"; Client.Issuer returns the right form for a client.
func LoadPrivateKey ¶
LoadPrivateKey parses a PEM private key for AAuth signing. Ed25519 and RSA keys are supported. The server also accepts EC P-256 keys, which this SDK does not sign with.
func NormalizeCapability ¶ added in v1.4.0
NormalizeCapability returns a capability in the canonical form that the server compares: "Invoices.Read" and "invoices::read" both become "invoices:read", while "invoices-read" stays as it is. Only ASCII letters are lower-cased, as on the server.
func OrgIDFromIssuer ¶ added in v1.8.0
OrgIDFromIssuer returns the organization ID of a platform issuer of the form …/orgs/{slug}/api/v1, or "".
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 RejectionReason ¶ added in v1.2.0
RejectionReason returns the TokenRejected* reason carried by err, or "" when err is not a token rejection.
func RequireAccessToken ¶ added in v1.2.0
func RequireAccessToken(opts AccessTokenVerifyOptions) func(http.Handler) http.Handler
RequireAccessToken is net/http middleware that verifies the LumoAuth access token on every request and stores its claims in the context — the guard for an MCP server built on net/http:
protect := lumoauth.RequireAccessToken(lumoauth.AccessTokenVerifyOptions{
Issuer: "https://app.lumoauth.dev/orgs/acme-corp/api/v1",
Resource: "https://mcp.example.com/mcp",
})
mux.Handle("/mcp", protect(mcpHandler))
// in mcpHandler:
claims, _ := lumoauth.AccessTokenFromContext(r.Context())
The token is read from the Authorization header (Bearer or DPoP scheme) and, for a bound token, the DPoP header is checked against the request (opts.DPoP is filled from each request; DPoPRequestFromHTTP documents how the URL is derived). A missing or invalid token gets 401 with a WWW-Authenticate challenge (RFC 6750 and RFC 9449 §7.1) and a JSON body {"error": "invalid_token", "error_description": …}. With opts.DPoPNonce, a proof without the expected nonce gets error="use_dpop_nonce" and the nonce in a DPoP-Nonce header instead (RFC 9449 §9). When opts.JWKS is nil the middleware keeps one key cache for the issuer.
func RouteNames ¶
func RouteNames() []string
RouteNames returns every registered route name, sorted. Useful for diagnostics and for the drift test.
func RoutePath ¶
RoutePath looks up a route and builds its concrete path in one call. The path is in the platform form. A client with a custom domain does not use this function: it resolves routes without the /orgs/{orgId} segment.
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.
func VerifySignatureBase ¶
VerifySignatureBase checks a base64url signature over a signature base. Resource servers use it to verify proof-of-possession against the key in a token's cnf.jwk. It handles Ed25519 and RSA keys only: a signature made with an EC P-256 key, which the server also accepts from agents, does not verify here.
func WritePoppyRefusal ¶ added in v1.7.0
func WritePoppyRefusal(w http.ResponseWriter, verification *PoppyVerification) error
WritePoppyRefusal sends a refusal to the personal agent as LumoAuth worded it: the status, every header and the body of verification.Response. A body is sent as JSON with Content-Type application/json. A response without a body gets no body and no Content-Type. Nothing else is added.
if !verification.Active {
lumoauth.WritePoppyRefusal(w, verification)
return
}
It returns a *ValidationError, and writes nothing, when verification is not a refusal. Otherwise it returns the error of the write, if any.
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 is the user. It is a pseudonym for this resource, not the
// user ID, when the resource's default auth level is `pseudonymous`, or
// `authorized` without a consent record.
Subject string `json:"sub,omitempty"`
// Agent identifies the agent the token was issued to. The claim is
// present only when the audience differs from the agent identifier.
Agent string `json:"agent,omitempty"`
// AgentDelegate is the delegate (the `sub` of the agent token) that
// made the request for the agent, if any.
AgentDelegate string `json:"agent_delegate,omitempty"`
// Scope lists resource scopes only: openid, profile, email, phone and
// address are never listed.
Scope string `json:"scope,omitempty"`
// Confirmation binds the token to the holder's key (RFC 7800). Auth
// tokens carry the agent's full public JWK and no cnf.jkt.
Confirmation struct {
JWK JWK `json:"jwk"`
} `json:"cnf"`
// Act is the actor chain of an exchanged token: {agent,
// agent_delegate?, sub?, act?}. act.agent names the upstream agent and
// act.sub the upstream user; a nested act holds the earlier hops (at
// most 5).
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.
The check is narrower than the one LumoAuth applies to its own endpoints. It does not require a recent `created`, a new nonce, a Content-Digest header or any particular covered component, and it reads only the `created` and `nonce` parameters. LumoAuth requires @method, @authority, @path and signature-key to be covered, `created` within 60 seconds and a single-use nonce. Apply those checks yourself to stop a captured request from being replayed.
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, // its scope claim names the scope
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 address that the client sends its requests to: the custom domain when one is set, the LumoAuth instance URL otherwise.
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) CustomDomain ¶ added in v1.7.0
func (c *AAuthClient) CustomDomain() string
CustomDomain returns the organization's custom domain as an origin, or "" when none is set.
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 (act.agent names the upstream agent, act.sub the upstream user; at most 5 hops). The agent must be permitted to exchange tokens.
func (*AAuthClient) Issuer ¶
func (c *AAuthClient) Issuer() string
Issuer returns the organization's AAuth issuer URL, which is the `iss` value in issued tokens and the audience that the agent addresses.
It returns AAuthConfig.Issuer when that is set. On the platform host it is otherwise {baseURL}/orgs/{orgID}/api/v1, the base for JWKS discovery.
On a custom domain the issuer keeps the platform form, and this method never derives it from the domain. It makes no request, so there it returns the value that ResolveIssuer has read, or "" before the first call of ResolveIssuer. Prefer ResolveIssuer with a custom domain.
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. A resource names this value as `agent_jkt` when it asks for a resource token for the agent.
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 and the response carries no new one. A refresh never widens the scope.
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 answers 200 with a request_token and an authorization_uri, returned here as a response with AuthorizationRequired set: redirect the user to AuthorizationURI, then call ExchangeCode with the code delivered to your redirect URI.
func (*AAuthClient) ResolveIssuer ¶ added in v1.7.0
func (c *AAuthClient) ResolveIssuer(ctx context.Context) (string, error)
ResolveIssuer returns the organization's AAuth issuer, like Issuer, and reads it from LumoAuth when the client cannot know it.
With a custom domain and no AAuthConfig.Issuer, it fetches the issuer metadata document from the custom domain once and returns its `issuer` member, which is the platform form. Later calls return the same value without a request. On the platform host it makes no request, and it returns a *ConfigError when the client has no organization ID.
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. Not
// needed with CustomDomain.
OrgID string
// CustomDomain addresses the organization on its own domain, for
// example "auth.acme.com". Defaults to $LUMOAUTH_CUSTOM_DOMAIN. It wins
// over BaseURL: the token endpoint, the key set, the issuer metadata
// and the URLs that the agent signs are then on that domain, without
// the /orgs/{orgId} segment. See WithCustomDomain.
//
// The AAuth issuer does not follow the domain: see Issuer.
CustomDomain string
// Issuer is the organization's AAuth issuer: the `iss` of its AAuth
// tokens and the audience that the agent addresses. Leave it empty on
// the platform host, where it is {BaseURL}/orgs/{OrgID}/api/v1.
//
// LumoAuth names the AAuth issuer with the platform address on every
// host, so with CustomDomain it is NOT the bare domain. When Issuer is
// empty there, ResolveIssuer reads it from the issuer metadata
// document of the custom domain.
Issuer 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 is the definition's ID as text. The server sends a number; a
// string is accepted too.
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"`
// DefaultValue is the value an entity has when none is set; nil when the
// definition has none.
DefaultValue any `json:"defaultValue,omitempty"`
// IsRequired reports whether every entity must have a value.
IsRequired bool `json:"isRequired,omitempty"`
// IsSystem marks a definition that LumoAuth manages.
IsSystem bool `json:"isSystem,omitempty"`
// BuiltIn marks a definition that LumoAuth provides to every
// organization: readable, never writable by one.
BuiltIn bool `json:"builtIn,omitempty"`
// CreatedAt and UpdatedAt are RFC 3339 times; UpdatedAt is "" for a
// definition that was never changed.
CreatedAt string `json:"createdAt,omitempty"`
UpdatedAt string `json:"updatedAt,omitempty"`
// IsActive is not sent by the server and is always false.
//
// Deprecated: the server has no such flag; every listed definition
// applies.
IsActive bool `json:"isActive,omitempty"`
}
AbacAttributeDefinition describes an attribute the org has defined.
func (*AbacAttributeDefinition) UnmarshalJSON ¶ added in v1.8.0
func (d *AbacAttributeDefinition) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes the definition and accepts its ID as a number or a string.
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 is the policy's ID as text. The server sends a number ({"id": 81}
// gives "81"); a string is accepted too, and null gives "".
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.
func (*AbacMatchedPolicy) UnmarshalJSON ¶ added in v1.8.0
func (p *AbacMatchedPolicy) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes the policy and accepts its ID as a number or a string.
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 AccessTokenClaims ¶ added in v1.2.0
type AccessTokenClaims struct {
Issuer string `json:"iss"`
// Subject is "agent_agt_…" for an agent, a user id for a user token or a
// delegated token.
Subject string `json:"sub"`
Audience AudienceClaim `json:"aud"`
Expires int64 `json:"exp"`
NotBefore int64 `json:"nbf,omitempty"`
IssuedAt int64 `json:"iat,omitempty"`
JTI string `json:"jti"`
// ClientID is the OAuth client that obtained the token.
ClientID string `json:"client_id,omitempty"`
// Scope is the space-separated scope string; see Scopes and HasScope.
Scope string `json:"scope,omitempty"`
// IsAgent is true for tokens issued to an agent identity.
IsAgent bool `json:"is_agent,omitempty"`
// Capabilities are the agent's capability slugs, when IsAgent.
Capabilities []string `json:"capabilities,omitempty"`
// Act is the RFC 8693 actor claim of a delegated token: the agent acting
// for Subject, with any deeper sub-agents nested in Act.Act.
Act *ActorClaim `json:"act,omitempty"`
// Confirmation is the RFC 7800 key binding; JKT is set for a DPoP-bound
// token.
Confirmation *TokenConfirmation `json:"cnf,omitempty"`
// TokenUse marks special-purpose tokens. "test" tokens are refused.
TokenUse string `json:"token_use,omitempty"`
// AuthorizationDetails are the token's fine-grained permissions
// (RFC 9396 authorization_details), when it has some. Members that the
// SDK does not model are kept.
AuthorizationDetails []map[string]any `json:"authorization_details,omitempty"`
// Raw is every claim in the token, including ones not modelled above.
Raw map[string]any `json:"-"`
}
AccessTokenClaims are the claims of a verified LumoAuth access token.
func AccessTokenFromContext ¶ added in v1.2.0
func AccessTokenFromContext(ctx context.Context) (*AccessTokenClaims, bool)
AccessTokenFromContext returns the claims RequireAccessToken stored for the request.
func VerifyAccessToken ¶ added in v1.2.0
func VerifyAccessToken(ctx context.Context, token string, opts AccessTokenVerifyOptions) (*AccessTokenClaims, error)
VerifyAccessToken verifies a LumoAuth access token for this resource and returns its claims.
claims, err := lumoauth.VerifyAccessToken(ctx, token, lumoauth.AccessTokenVerifyOptions{
Issuer: "https://app.lumoauth.dev/orgs/acme-corp/api/v1",
Resource: "https://mcp.example.com/mcp",
DPoP: lumoauth.DPoPRequestFromHTTP(r),
})
It checks, in order: the compact JWS shape; the `typ` header (at+jwt); the algorithm (RSA and EC families only — HMAC and none are refused, and the algorithm must match the published key); `iss`; the signature; `exp` and `nbf`; `aud` contains Resource; `token_use` is not "test"; and, for a token with cnf.jkt, the DPoP proof: scheme, signature, htm/htu, iat window, ath, key thumbprint and jti replay.
Failures are a *ValidationError whose Reason is a TokenRejected* constant. Fetch failures are *NetworkError or *APIError.
func (*AccessTokenClaims) ActorChain ¶ added in v1.2.0
func (c *AccessTokenClaims) ActorChain() []string
ActorChain returns the `sub` of each actor in the delegation chain, outermost first: the agent acting for Subject, then its sub-agents. It is empty for a token with no `act` claim.
func (*AccessTokenClaims) HasCapability ¶ added in v1.2.0
func (c *AccessTokenClaims) HasCapability(capability string) bool
HasCapability reports whether the agent's capabilities claim covers a capability. Names match as on the server ("web.search" matches "web:search"; "invoices:*" covers "invoices:read"). Scopes are different: HasScope compares them exactly.
func (*AccessTokenClaims) HasScope ¶ added in v1.2.0
func (c *AccessTokenClaims) HasScope(scope string) bool
HasScope reports whether the token carries a scope.
func (*AccessTokenClaims) IsDPoPBound ¶ added in v1.2.0
func (c *AccessTokenClaims) IsDPoPBound() bool
IsDPoPBound reports whether the token is sender-constrained (cnf.jkt).
func (*AccessTokenClaims) Scopes ¶ added in v1.2.0
func (c *AccessTokenClaims) Scopes() []string
Scopes splits the space-separated scope claim.
type AccessTokenKeyCache ¶ added in v1.2.0
type AccessTokenKeyCache struct {
// contains filtered or unexported fields
}
AccessTokenKeyCache caches an organization's token-signing keys for a TTL. Build one with NewAccessTokenKeyCache and pass it as AccessTokenVerifyOptions.KeyCache, or let VerifyAccessToken use its process-wide cache.
func NewAccessTokenKeyCache ¶ added in v1.2.0
func NewAccessTokenKeyCache(issuer string, ttl time.Duration, httpClient *http.Client) *AccessTokenKeyCache
NewAccessTokenKeyCache builds a cache for one issuer. A ttl of 0 means one hour.
func NewAccessTokenKeyCacheForCustomDomain ¶ added in v1.7.0
func NewAccessTokenKeyCacheForCustomDomain(customDomain string, ttl time.Duration, httpClient *http.Client) (*AccessTokenKeyCache, error)
NewAccessTokenKeyCacheForCustomDomain builds a cache for an organization on its custom domain, for example "auth.acme.com". The issuer is the bare domain. It returns a *ConfigError for a value that is empty or not valid (see WithCustomDomain). A ttl of 0 means one hour.
func (*AccessTokenKeyCache) Get ¶ added in v1.2.0
func (c *AccessTokenKeyCache) Get(ctx context.Context) (*JWKS, error)
Get returns the cached key set, fetching it when absent or stale.
func (*AccessTokenKeyCache) Invalidate ¶ added in v1.2.0
func (c *AccessTokenKeyCache) Invalidate()
Invalidate drops the cached keys, forcing the next Get to refetch.
type AccessTokenVerifyOptions ¶ added in v1.2.0
type AccessTokenVerifyOptions struct {
// Issuer is the organization's issuer URL, e.g.
// "https://app.lumoauth.dev/orgs/acme-corp/api/v1". Required unless
// CustomDomain is set.
Issuer string
// CustomDomain is the organization's custom domain, for example
// "auth.acme.com". When it is set, the trusted issuer is the bare
// domain ("https://auth.acme.com") and Issuer is not used: a token
// that names the platform issuer is refused. The keys are read from
// the domain's discovery document. The value follows the rules of
// WithCustomDomain; an invalid one is a *ConfigError from
// VerifyAccessToken. The environment is not read.
CustomDomain string
// Resource is this server's resource URI — the value the MCP server is
// registered with and the token's `aud` must name. Required.
Resource string
// JWKS supplies the issuer's keys directly. When nil, the keys are
// fetched through the issuer's discovery document and cached (KeyCache,
// or a process-wide cache per issuer), with one refetch on an unknown
// kid.
JWKS *JWKS
// KeyCache is the cache to fetch keys through when JWKS is nil.
KeyCache *AccessTokenKeyCache
// HTTPClient fetches discovery and keys. Defaults to a 30s-timeout
// client.
HTTPClient *http.Client
// ClockSkew tolerated on exp, nbf and the proof's iat. The default (0)
// means 60 seconds; a negative value means no tolerance.
ClockSkew time.Duration
// RequireDPoP rejects tokens that are not sender-constrained. Set it
// when the MCP server is registered with "Require DPoP".
RequireDPoP bool
// DPoP describes the request the token arrived with. Required for a
// DPoP-bound token; RequireAccessToken fills it from the request.
DPoP *DPoPRequest
// ReplayCache stores proof identifiers. Defaults to a process-wide
// in-memory cache.
ReplayCache ReplayCache
// DPoPNonce gives RequireAccessToken the nonce that this resource
// server expects in the DPoP proof of a request (DPoPRequest.Nonce), for
// a server that issues nonces. A proof without it gets 401 with
// error="use_dpop_nonce" and the value in a DPoP-Nonce header, so the
// client can retry. Nil (or "") means no nonce check. VerifyAccessToken
// does not call it: set DPoP.Nonce there.
DPoPNonce func(r *http.Request) string
}
AccessTokenVerifyOptions configures VerifyAccessToken.
type ActorClaim ¶ added in v1.2.0
type ActorClaim struct {
Subject string `json:"sub"`
Issuer string `json:"iss,omitempty"`
SubjectProfile string `json:"sub_profile,omitempty"`
Name string `json:"name,omitempty"`
// Act is the next actor down the chain, when there is one.
Act *ActorClaim `json:"act,omitempty"`
}
ActorClaim is one link of a delegation chain (`act`).
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) AskWithOptions ¶ added in v1.8.0
func (a *Agent) AskWithOptions(ctx context.Context, action string, actionContext map[string]any, opts AskOptions) (*AgentAskResult, error)
AskWithOptions asks whether the agent may perform an action, with per-call options such as the traceparent; see AgentsResource.AskWithOptions.
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) AuthorizeMcpTool ¶ added in v1.2.0
func (a *Agent) AuthorizeMcpTool(ctx context.Context, serverID, tool string) (*AgentMcpToolDecision, error)
AuthorizeMcpTool asks whether this agent may run one tool on an MCP server. serverID is the registered MCP server ID, not its URL. A deny returns Allowed false and a nil error; see AgentsResource.AuthorizeMcpTool.
func (*Agent) BaseURL ¶
BaseURL returns the address that the agent sends its requests to: the custom domain when one is set, the LumoAuth instance URL otherwise.
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 budget is spent (any limit, see AgentBudget.Exhausted), 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) ClientAssertion ¶ added in v1.3.0
ClientAssertion signs a new private_key_jwt client assertion for this agent (single-use), addressed to AgentConfig.Issuer, else to the custom domain, else to IssuerFor(BaseURL, OrgID). It is a *ConfigError when the agent has no PrivateKey.
func (*Agent) ClientSecret ¶
ClientSecret returns the agent's OAuth client secret. Needed by DelegationChain for the confidential-client consent exchange.
func (*Agent) CustomDomain ¶ added in v1.7.0
CustomDomain returns the organization's custom domain as an origin, or "" when none is set. NewJITContext and NewDelegationChain read it, so their requests follow the agent's own addressing.
func (*Agent) DPoP ¶ added in v1.2.0
func (a *Agent) DPoP() *DPoPSigner
DPoP returns the signer from AgentConfig.DPoP, or nil when the agent's tokens are plain bearer tokens.
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) GetConnectionToken ¶ added in v1.8.0
func (a *Agent) GetConnectionToken(ctx context.Context, connectionID string, params ConnectionTokenParams) (*ConnectionToken, error)
GetConnectionToken returns a live token of an outbound connection; see AgentsResource.GetConnectionToken.
func (*Agent) HasCapability ¶
HasCapability reports whether the agent holds a capability. Names match as on the server: "Web:Search" matches the held "web:search", and a held "web:*" covers it (see CapabilityCovers). It checks only the agent's registered capabilities; the Ask API (Agent.Ask) also applies your policies and the token's scope.
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) IsAllowedWithOptions ¶ added in v1.8.0
func (a *Agent) IsAllowedWithOptions(ctx context.Context, action string, actionContext map[string]any, opts AskOptions) (bool, error)
IsAllowedWithOptions is AskWithOptions reduced to a boolean.
func (*Agent) ListConnections ¶ added in v1.8.0
func (a *Agent) ListConnections(ctx context.Context) ([]AgentConnection, error)
ListConnections lists the outbound connections that this agent may use.
func (*Agent) MCPToken ¶
MCPToken exchanges the agent's token for one bound to a secured MCP server. serverID is the Resource URI that the server is registered with, e.g. "https://mcp.example.com/mcp". The token works only at that server; 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) ReportUsage ¶ added in v1.4.0
func (a *Agent) ReportUsage(ctx context.Context, tokens int, costUSD float64) (*UsageReportResult, error)
ReportUsage reports the model tokens and cost that the agent just used, for example the usage that the model provider returned. LumoAuth does not see model calls, so token and cost limits count only reported usage. The budget in the result also replaces the cached one, so CheckBudget reflects the report without another request.
resp, _ := llm.Chat(ctx, req)
if _, err := agent.ReportUsage(ctx, resp.Usage.TotalTokens, 0.0042); err != nil {
return err
}
if err := agent.CheckBudget(ctx); err != nil {
return err // ErrBudgetExceeded
}
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, "web:search"); 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(), "web:search"); 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"`
// DecidedBy names the check that produced the answer: DecidedByCapability,
// DecidedByPDP or DecidedByDenyOverride. "" when the server did not say.
DecidedBy string `json:"decided_by,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 {
// Limits on API calls and model tokens.
MaxAPICallsPerHour int `json:"max_api_calls_per_hour,omitempty"`
MaxAPICallsPerDay int `json:"max_api_calls_per_day,omitempty"`
MaxTokensPerHour int `json:"max_tokens_per_hour,omitempty"`
MaxTokensPerDay int `json:"max_tokens_per_day,omitempty"`
// Limits on cost, in USD. HardLimitUSD (`hard_limit`) and
// MaxCostPerDayUSD are both daily limits; the lower one applies.
MaxCostPerDayUSD float64 `json:"max_cost_per_day_usd,omitempty"`
MaxCostPerMonthUSD float64 `json:"max_cost_per_month_usd,omitempty"`
HardLimitUSD float64 `json:"hard_limit,omitempty"`
// Usage in the current UTC hour, day and month. Tokens and cost count
// only reported usage (Agent.ReportUsage).
APICallsThisHour int `json:"api_calls_this_hour,omitempty"`
APICallsToday int `json:"api_calls_today,omitempty"`
TokensUsedThisHour int `json:"tokens_used_this_hour,omitempty"`
TokensUsedToday int `json:"tokens_used_today,omitempty"`
CostTodayUSD float64 `json:"cost_today_usd,omitempty"`
CostThisMonthUSD float64 `json:"cost_this_month_usd,omitempty"`
// MaxSteps and TimeoutSeconds are settings that LumoAuth stores and
// returns but does not enforce: your agent applies them. They are 0
// when unset or when the stored value is not a number.
MaxSteps int `json:"-"`
TimeoutSeconds int `json:"-"`
// ReportedExhausted is the server's own verdict (`exhausted`): true when
// any limit (calls, tokens or cost, per hour, day or month) is reached.
// Nil when the server did not report it.
ReportedExhausted *bool `json:"exhausted,omitempty"`
// Raw is the complete decoded policy.
Raw map[string]any `json:"-"`
}
AgentBudget is the budget of an agent as UserInfo (budget_policy) and the usage report return it: the limits that are set, the usage in the current UTC windows, and the server's verdict. A limit that is not set is 0.
func (*AgentBudget) Exhausted ¶
func (b *AgentBudget) Exhausted() bool
Exhausted reports whether the agent's budget is spent, so the next metered call would get 429. It uses the server's verdict when reported (any limit, any window); otherwise it compares every limit that is set with the usage of its window, and a policy without limits 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. Not
// needed with CustomDomain.
OrgID string
// CustomDomain addresses the organization on its own domain, for
// example "auth.acme.com". Defaults to $LUMOAUTH_CUSTOM_DOMAIN. It wins
// over BaseURL, no path then carries the /orgs/{orgId} segment, and the
// issuer is the bare domain. See WithCustomDomain.
CustomDomain 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
// PrivateKey is for an agent registered with the "Private key JWT"
// identity type: the agent then signs a client assertion (RFC 7523) for
// every token request and needs no ClientSecret. Defaults to the PEM key
// in $AGENT_PRIVATE_KEY, with its kid from $AGENT_KEY_ID.
PrivateKey *ClientAssertionSigner
// Issuer is the organization's issuer identifier, the assertion's aud.
// Defaults to the custom domain when CustomDomain is set, and to
// IssuerFor(BaseURL, OrgID) otherwise.
Issuer string
// DPoP binds the agent's tokens to a key (RFC 9449). The client
// credentials grant, MCP token exchanges and delegation exchanges then
// send a DPoP proof, the tokens come back with token_type "DPoP", and
// the agent presents them with the DPoP scheme. Needed for MCP servers
// registered with "Require DPoP". See NewDPoPSigner.
DPoP *DPoPSigner
}
AgentConfig configures an Agent. Every field falls back to an environment variable when left empty.
type AgentConnection ¶ added in v1.8.0
type AgentConnection struct {
ConnectionID string `json:"connection_id"`
Name string `json:"name"`
// Provider is the provider key ("github", "google", …); ProviderLabel
// its name for people.
Provider string `json:"provider"`
ProviderLabel string `json:"provider_label"`
GrantMode string `json:"grant_mode"`
Scopes []string `json:"scopes"`
// UserDelegated is true when each person links their own account;
// GetConnectionToken then needs ConnectionTokenParams.UserID.
UserDelegated bool `json:"user_delegated"`
// MachineGrantStatus is the state of the machine grant
// ("not_established" when there is none); "" for a user-delegated
// connection.
MachineGrantStatus string `json:"machine_grant_status,omitempty"`
// LinkedUsers is the number of people with an active grant; nil for a
// machine connection.
LinkedUsers *int `json:"linked_users,omitempty"`
}
AgentConnection is one outbound connection that the agent may use. It holds no secret.
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 AgentMcpToolDecision ¶ added in v1.2.0
type AgentMcpToolDecision struct {
Allowed bool `json:"allowed"`
AgentID string `json:"agent_id,omitempty"`
Resource McpToolResource `json:"resource"`
}
AgentMcpToolDecision is the answer to AgentsResource.AuthorizeMcpTool. A deny comes back with Allowed set to false and a nil error.
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)
}
To send the traceparent of your trace, use AskWithOptions.
func (*AgentsResource) AskWithOptions ¶ added in v1.8.0
func (r *AgentsResource) AskWithOptions(ctx context.Context, action string, actionContext map[string]any, opts AskOptions) (*AgentAskResult, error)
AskWithOptions is Ask with per-call options, such as the traceparent of your trace:
decision, err := agent.AskWithOptions(ctx, "invoices:refund", nil,
lumoauth.AskOptions{Traceparent: span.Traceparent()})
func (*AgentsResource) Attest ¶ added in v1.8.0
func (r *AgentsResource) Attest(ctx context.Context, params AttestParams) (*AttestResult, error)
Attest exchanges a workload's OIDC token for an access token of the agent (workload attestation). The endpoint is public: the attestation token is the credential, so no API key or bearer token of the client is sent. With WithDPoP the request carries a proof, the token comes back bound to the key (TokenType "DPoP"), and a use_dpop_nonce answer is retried once with the server's nonce.
A rejected attestation (unknown agent, inactive agent, a token that failed verification) is a 401 attestation_rejected that matches ErrAuthentication. A spent budget matches ErrBudgetExceeded.
result, err := client.Agents.Attest(ctx, lumoauth.AttestParams{
AgentID: "agt_7f3c2a19b84e5d60",
AttestationToken: workloadToken,
})
A runtime without any LumoAuth credential uses AttestWorkload, or a client built with WithoutCredential.
func (*AgentsResource) AuthorizeMcpTool ¶ added in v1.2.0
func (r *AgentsResource) AuthorizeMcpTool(ctx context.Context, serverID, tool string) (*AgentMcpToolDecision, error)
AuthorizeMcpTool asks whether the calling agent may run one tool on an MCP server. It uses the agent's own credential, so it suits an agent that checks a tool before it calls it. An MCP server must not use it, because it would have to forward the agent's token; the server calls Mcp.AuthorizeTool with its own token instead.
serverID is the registered MCP server ID, for example "mcp_0123456789abcdef01234567". It is not the Resource URI.
decision, err := agent.Agents.AuthorizeMcpTool(ctx, "mcp_0123456789abcdef01234567", "send_invoice")
if err != nil {
return err
}
if !decision.Allowed {
return errors.New("tool refused")
}
A deny is not an error. It comes back with Allowed set to false and a nil error. An unknown server is an error that matches ErrNotFound.
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) GetConnectionToken ¶ added in v1.8.0
func (r *AgentsResource) GetConnectionToken(ctx context.Context, connectionID string, params ConnectionTokenParams) (*ConnectionToken, error)
GetConnectionToken returns a live token of an outbound connection, refreshed by LumoAuth when needed. Agent credentials only; a token that was narrowed to some scopes is refused (403 insufficient_scope).
token, err := agent.GetConnectionToken(ctx, "conn_1f3a9c2b7d8e4a5f6b0c1d2e",
lumoauth.ConnectionTokenParams{UserID: "ada@acme.com"})
if apiErr, ok := lumoauth.AsAPIError(err); ok && apiErr.Code == lumoauth.VaultGrantNotFound {
// ask the person to link the account
}
req.Header.Set("Authorization", token.Header())
Refusals keep the server's code: VaultGrantNotFound (matches ErrNotFound), VaultAgentNotAllowed and VaultDelegationNotAllowed (match ErrPermissionDenied), grant_revoked / grant_expired / refresh_failed (409), budget_exceeded (matches ErrBudgetExceeded).
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) IsAllowedWithOptions ¶ added in v1.8.0
func (r *AgentsResource) IsAllowedWithOptions(ctx context.Context, action string, actionContext map[string]any, opts AskOptions) (bool, error)
IsAllowedWithOptions is AskWithOptions reduced to a boolean.
func (*AgentsResource) ListConnections ¶ added in v1.8.0
func (r *AgentsResource) ListConnections(ctx context.Context) ([]AgentConnection, error)
ListConnections lists the outbound connections that the calling agent may use, with the state of their grants. Agent credentials only.
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.
func (*AgentsResource) ReportUsage ¶ added in v1.4.0
func (r *AgentsResource) ReportUsage(ctx context.Context, tokens int, costUSD float64) (*UsageReportResult, error)
ReportUsage reports the model tokens and cost that the agent used.
LumoAuth does not see the agent's model calls, so token and cost limits (max_tokens_per_day, max_cost_per_month_usd, …) count only the usage that is reported here. Report after each model call, or batch a few. The report is not a metered call and is accepted when the budget is spent; the result's Budget says whether it is. Agent credentials only.
type ApplicationConsentParams ¶ added in v1.8.0
type ApplicationConsentParams struct {
// ClientID is the application's client ID, never the agent's agt_… ID.
// Required.
ClientID string
// RedirectURI is one of the application's registered redirect URIs.
// Required.
RedirectURI string
// Scopes are what the agent may do for the person: scopes that the
// application is allowed and that the agent holds as capabilities.
// "openid" is added. Required.
Scopes []string
// State is the CSRF value echoed back to the redirect URI. Required.
State string
// CodeChallenge is the PKCE S256 challenge of a verifier that you keep
// for the code redemption. Required.
CodeChallenge string
// OfflineAccess asks for a refresh token (scope offline_access): the
// application needs it to renew the person's token and to revoke the
// grant.
OfflineAccess bool
}
ApplicationConsentParams describes the sign-in through which a person lets an agent act for them. An agent never starts a sign-in: the person signs in to an APPLICATION of your organization, the application redeems the code, and the agent exchanges the person's access token (Exchange).
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 AskOptions ¶ added in v1.8.0
type AskOptions struct {
// Traceparent is a W3C trace context header value
// ("00-<32 hex>-<16 hex>-<2 hex>"), sent as the traceparent header, so
// that the audit entries of the decision carry your trace ID.
Traceparent string
}
AskOptions are per-call options of AskWithOptions.
type AttestParams ¶ added in v1.8.0
type AttestParams struct {
// AgentID is the agent's ID, for example "agt_7f3c2a19b84e5d60". Required.
AgentID string
// AttestationToken is the workload's OIDC token (a JWT). Required.
AttestationToken string
// Scopes optionally narrows the token to some of the agent's
// capabilities. Empty means every capability. A scope outside the
// capabilities is refused with invalid_scope.
Scopes []string
}
AttestParams describes a workload attestation.
type AttestResult ¶ added in v1.8.0
type AttestResult struct {
// AccessToken is the agent's access token; it lives 15 minutes.
AccessToken string `json:"access_token"`
// TokenType is "DPoP" when the token is bound to the client's DPoP key
// (WithDPoP), "Bearer" otherwise.
TokenType string `json:"token_type"`
// ExpiresIn is the token's lifetime in seconds.
ExpiresIn int `json:"expires_in"`
// Scope holds the issued scope values, separated by spaces; "" when
// none was issued.
Scope string `json:"scope,omitempty"`
// Identity is the workload identity that LumoAuth verified.
Identity WorkloadIdentity `json:"identity"`
// Raw is the complete decoded answer.
Raw map[string]any `json:"-"`
}
AttestResult is the answer to an accepted attestation.
func AttestWorkload ¶ added in v1.8.0
func AttestWorkload(ctx context.Context, opts AttestWorkloadOptions) (*AttestResult, error)
AttestWorkload performs a workload attestation without a LumoAuth client: the workload has no credential of its own, only its platform's OIDC token. It reads the address from the options, then from $LUMOAUTH_URL, $LUMOAUTH_ORG_ID and $LUMOAUTH_CUSTOM_DOMAIN, and never sends an API key.
token, _ := os.ReadFile("/var/run/secrets/tokens/lumoauth")
result, err := lumoauth.AttestWorkload(ctx, lumoauth.AttestWorkloadOptions{
AgentID: os.Getenv("LUMOAUTH_AGENT_ID"),
AttestationToken: strings.TrimSpace(string(token)),
})
func (*AttestResult) Scopes ¶ added in v1.8.0
func (r *AttestResult) Scopes() []string
Scopes splits the space-separated Scope field.
func (*AttestResult) UnmarshalJSON ¶ added in v1.8.0
func (r *AttestResult) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes the typed fields and retains the whole object.
type AttestWorkloadOptions ¶ added in v1.8.0
type AttestWorkloadOptions struct {
// BaseURL is the LumoAuth instance. Defaults to $LUMOAUTH_URL, then
// DefaultBaseURL.
BaseURL string
// OrgID is the organization slug. Defaults to $LUMOAUTH_ORG_ID. Not
// needed with CustomDomain.
OrgID string
// CustomDomain is the organization's own domain. Defaults to
// $LUMOAUTH_CUSTOM_DOMAIN. It wins over BaseURL.
CustomDomain string
// AgentID, AttestationToken and Scopes are those of AttestParams.
AgentID string
AttestationToken string
Scopes []string
// DPoP binds the issued token to this signer's key.
DPoP *DPoPSigner
// HTTPClient overrides the client used for the request.
HTTPClient *http.Client
// Timeout is the request timeout. Default: 30s.
Timeout time.Duration
// SkipCertValidation disables TLS verification. Local development only.
SkipCertValidation bool
}
AttestWorkloadOptions configures AttestWorkload.
type AudienceClaim ¶ added in v1.2.0
type AudienceClaim []string
AudienceClaim is a JWT `aud` claim, which may be a string or an array.
func (AudienceClaim) Contains ¶ added in v1.2.0
func (a AudienceClaim) Contains(value string) bool
Contains reports whether the audience names value.
func (*AudienceClaim) UnmarshalJSON ¶ added in v1.2.0
func (a *AudienceClaim) UnmarshalJSON(data []byte) error
UnmarshalJSON accepts a single string or an array of strings.
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.
After a pushed authorization request, pass only ClientID and its RequestURI: the URL then carries client_id and request_uri alone.
func (*AuthResource) BackchannelAuthorize ¶ added in v1.8.0
func (r *AuthResource) BackchannelAuthorize(ctx context.Context, params BackchannelAuthorizeParams) (*BackchannelAuthorizeResponse, error)
BackchannelAuthorize starts an OpenID CIBA request for the application (poll mode):
auth := lumoauth.ClientAuth{ClientID: clientID, ClientSecret: clientSecret}
start, err := client.Auth.BackchannelAuthorize(ctx, lumoauth.BackchannelAuthorizeParams{
ClientAuth: auth,
LoginHint: "ada@acme.com",
Scopes: []string{"openid", "profile"},
BindingMessage: "Order 4412",
})
if err != nil {
return err
}
tokens, err := client.Auth.PollBackchannelToken(ctx, start.AuthReqID, start.PollOptions(auth))
func (*AuthResource) ClientAttestationHeaders ¶ added in v1.8.0
func (r *AuthResource) ClientAttestationHeaders(attestation ClientAttestation) (map[string]string, error)
ClientAttestationHeaders builds the two request headers of attestation-based client authentication (attest_jwt_client_auth): OAuth-Client-Attestation, the attestation as given, and OAuth-Client-Attestation-PoP, a new proof of possession signed with the instance key. The proof's claims are iss (the client ID: the attestation's sub), aud (the organization's issuer identifier), iat, exp (the lifetime of InstanceKey, 60 s by default), a random jti and, when given, challenge. Each proof works once.
The token, PAR, CIBA and introspection calls of this SDK send the headers themselves when ClientAuth.Attestation is set. Send client_id in the request body too: the headers do not replace it.
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. To send a resource indicator, use ClientCredentialsWithParams.
func (*AuthResource) ClientCredentialsWithAssertion ¶ added in v1.3.0
func (r *AuthResource) ClientCredentialsWithAssertion(ctx context.Context, clientID, clientAssertion string, scopes ...string) (*TokenResponse, error)
ClientCredentialsWithAssertion performs the client-credentials grant with a private_key_jwt client assertion (RFC 7523) instead of a secret: the authentication of an agent registered with the "Private key JWT" identity type. Build clientAssertion with ClientAssertionSigner.Assertion; it is single-use.
func (*AuthResource) ClientCredentialsWithParams ¶ added in v1.8.0
func (r *AuthResource) ClientCredentialsWithParams(ctx context.Context, params ClientCredentialsParams) (*TokenResponse, error)
ClientCredentialsWithParams performs the client-credentials grant with a secret or an assertion, and optionally a resource indicator:
token, err := client.Auth.ClientCredentialsWithParams(ctx, lumoauth.ClientCredentialsParams{
ClientID: clientID,
ClientSecret: clientSecret,
Scopes: []string{"reports:read"},
Resource: "https://api.example.com/",
})
func (*AuthResource) CreateRequestObject ¶ added in v1.8.0
func (r *AuthResource) CreateRequestObject(params AuthorizationURLParams, opts RequestObjectOptions) (string, error)
CreateRequestObject signs the parameters of an authorization request as a request object (JAR, RFC 9101): a JWT with the header typ oauth-authz-req+jwt, alg and kid, and the claims = the authorization parameters plus iss (the client ID), aud (the organization's issuer identifier), iat, nbf, exp and a random jti.
object, err := client.Auth.CreateRequestObject(lumoauth.AuthorizationURLParams{
ClientID: clientID,
RedirectURI: "https://app.example.com/callback",
Scope: "openid profile",
State: state,
CodeChallenge: challenge,
ResponseMode: lumoauth.ResponseModeJWT,
}, lumoauth.RequestObjectOptions{Signer: signer})
// Push it (FAPI 2), or send it by value:
pushed, err := client.Auth.PushAuthorizationRequest(ctx,
lumoauth.AuthorizationURLParams{ClientID: clientID, Request: object}, auth)
func (*AuthResource) DeviceAuthorization ¶ added in v1.8.0
func (r *AuthResource) DeviceAuthorization(ctx context.Context, params DeviceAuthorizationParams) (*DeviceAuthorizationResponse, error)
DeviceAuthorization starts the device authorization grant (RFC 8628):
start, err := client.Auth.DeviceAuthorization(ctx, lumoauth.DeviceAuthorizationParams{
ClientAuth: lumoauth.ClientAuth{ClientID: "lumo_cli_client"},
Scopes: []string{"openid", "profile", "offline_access"},
})
if err != nil {
return err
}
fmt.Printf("Open %s and enter %s\n", start.VerificationURI, start.UserCode)
tokens, err := client.Auth.PollDeviceToken(ctx, start.DeviceCode, start.PollOptions(auth))
func (*AuthResource) EndSessionURL ¶ added in v1.8.0
func (r *AuthResource) EndSessionURL(params EndSessionURLParams) (string, error)
EndSessionURL builds the address to send a browser to so that it signs out of LumoAuth as well (the discovery document's end_session_endpoint). Clear your own session first. WebAuth's logout route does this for you.
logout, err := client.Auth.EndSessionURL(lumoauth.EndSessionURLParams{
IDTokenHint: tokens.IDToken,
PostLogoutRedirectURI: "https://app.example.com/",
})
if err != nil {
return err
}
http.Redirect(w, req, logout, http.StatusFound)
func (*AuthResource) ExchangeCode ¶
func (r *AuthResource) ExchangeCode(ctx context.Context, params ExchangeCodeParams) (*TokenResponse, error)
ExchangeCode trades an authorization code for tokens.
func (*AuthResource) GetClientConfiguration ¶ added in v1.8.0
func (r *AuthResource) GetClientConfiguration(ctx context.Context, clientID, registrationAccessToken string) (*RegisteredClient, error)
GetClientConfiguration reads the stored metadata of a registered client (RFC 7592 §2.1) with its registration access token, which is the only credential sent. The answer never holds the client secret or the token.
func (*AuthResource) Introspect ¶ added in v1.8.0
func (r *AuthResource) Introspect(ctx context.Context, token string, opts IntrospectOptions) (*TokenIntrospection, error)
Introspect asks LumoAuth whether a token is active and what it carries (RFC 7662):
info, err := client.Auth.Introspect(ctx, token, lumoauth.IntrospectOptions{
ClientAuth: lumoauth.ClientAuth{ClientID: apiClientID, ClientSecret: apiClientSecret},
})
if err != nil {
return err
}
if !info.Active {
// refuse the request
}
LumoAuth answers only about tokens that were issued to the calling client or whose aud names it; any other token is inactive. An inactive token is a result, never an error. A refused client authentication is an error that matches ErrAuthentication.
func (*AuthResource) PollBackchannelToken ¶ added in v1.8.0
func (r *AuthResource) PollBackchannelToken(ctx context.Context, authReqID string, opts PollOptions) (*TokenResponse, error)
PollBackchannelToken polls the token endpoint with the CIBA grant (urn:openid:params:grant-type:ciba) until the person approved, denied or the request expired. The polling rules and errors are those of PollDeviceToken. The client must authenticate (opts.ClientAuth with a credential).
func (*AuthResource) PollDeviceToken ¶ added in v1.8.0
func (r *AuthResource) PollDeviceToken(ctx context.Context, deviceCode string, opts PollOptions) (*TokenResponse, error)
PollDeviceToken polls the token endpoint with a device code until the person approved (tokens), denied (an *ApprovalError that matches ErrApprovalDenied) or the code expired (an *ApprovalError that matches ErrApprovalTimeout: the server's expired_token, or opts.ExpiresIn passed). It waits opts.Interval before each poll, keeps polling on authorization_pending and waits 5 seconds longer after each slow_down. Other answers are returned as usual API errors; a cancelled ctx ends it with a *NetworkError.
func (*AuthResource) PushAuthorizationRequest ¶ added in v1.8.0
func (r *AuthResource) PushAuthorizationRequest(ctx context.Context, params AuthorizationURLParams, auth ClientAuth) (*PushedAuthorizationResponse, error)
PushAuthorizationRequest sends the parameters of an authorization request to LumoAuth first (RFC 9126), so that they never pass through the browser, and returns the request_uri to redirect with. Applications with "Require PAR" or a FAPI profile must start every sign-in this way.
auth := lumoauth.ClientAuth{ClientID: clientID, ClientSecret: clientSecret}
pushed, err := client.Auth.PushAuthorizationRequest(ctx, lumoauth.AuthorizationURLParams{
RedirectURI: "https://app.example.com/callback",
Scope: "openid profile",
State: state,
CodeChallenge: challenge,
}, auth)
if err != nil {
return err
}
redirect, err := client.Auth.AuthorizationURL(lumoauth.AuthorizationURLParams{
ClientID: clientID, RequestURI: pushed.RequestURI,
})
params.ClientID defaults to auth.ClientID. Set params.Request (with ClientID only) to push a signed request object instead of the plain parameters. A confidential client authenticates with auth; a public client sends its client_id. With WithDPoP, the request carries a DPoP proof, which binds the authorization code to the key.
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) RegisterClient ¶ added in v1.8.0
func (r *AuthResource) RegisterClient(ctx context.Context, metadata ClientMetadata, opts RegisterClientOptions) (*RegisteredClient, error)
RegisterClient registers a client (RFC 7591), for example an MCP client or an agent that registers itself:
registered, err := client.Auth.RegisterClient(ctx, lumoauth.ClientMetadata{
ClientName: "Acme field app",
RedirectURIs: []string{"https://field.acme.com/callback"},
TokenEndpointAuthMethod: "none",
}, lumoauth.RegisterClientOptions{InitialAccessToken: iat})
Keep RegistrationAccessToken (and ClientSecret, for a confidential client) secret; neither is shown again. Refused metadata is an *APIError with Code invalid_client_metadata or invalid_redirect_uri.
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. A confidential application authenticates with ClientID and ClientSecret (Basic by default) or ClientAssertion; an agent's on-behalf-of exchange needs none.
func (*AuthResource) UserInfo ¶
UserInfo fetches the OIDC UserInfo claims. Pass an empty accessToken to use the client's own credentials.
func (*AuthResource) VerifyAuthorizationResponse ¶ added in v1.8.0
func (r *AuthResource) VerifyAuthorizationResponse(ctx context.Context, responseJWT string, opts AuthorizationResponseOptions) (*AuthorizationResponse, error)
VerifyAuthorizationResponse verifies the `response` parameter of a callback that a JARM response mode (jwt, query.jwt, form_post.jwt, fragment.jwt) produced, and returns its parameters. It checks, in order: the compact JWS form; alg (RSA or EC families, never none or HMAC) and kid; iss = the organization's issuer identifier; the signature against the issuer's keys (from the discovery document); aud = opts.ClientID; exp; and state when opts.ExpectedState is set. Use the code only after this.
Failures are a *ValidationError whose Reason is a TokenRejected* constant (TokenRejectedState for a state that is not the expected one). A verified response that carries an error (the person denied, say) is returned with Error set and a nil error: check Error before you read Code.
type AuthTokenParams ¶
type AuthTokenParams struct {
// ResourceToken is the `resource+jwt` obtained from the target
// resource. Required.
ResourceToken string
// Scope is space-separated. It is sent as the body field `scope`, which
// the server ignores for request_type=auth: the scope of the auth token
// comes from the resource token's `scope` claim.
Scope string
// AgentToken is the `agent+jwt` presented in Agent-Auth. Required —
// the endpoint authenticates the agent through that header, not the
// request body. The request must be signed with the key in the agent
// token's cnf claim.
AgentToken string
// RedirectURI is where consent should return the user. Required when
// the user has to consent (the server answers 400 invalid_request
// without it). Must be registered for the agent.
RedirectURI string
}
AuthTokenParams describes a direct authorization request (request_type=auth).
type AuthorizationResponse ¶ added in v1.8.0
type AuthorizationResponse struct {
Code string
State string
// Issuer is the response's iss: the organization's issuer identifier.
Issuer string
Error string
ErrorDescription string
ErrorURI string
// Claims are every claim of the response JWT.
Claims map[string]any
}
AuthorizationResponse holds the parameters of a verified authorization response. Either Code (and State) or Error is set.
type AuthorizationResponseOptions ¶ added in v1.8.0
type AuthorizationResponseOptions struct {
// ClientID is your application's client ID: the response's aud.
// Required.
ClientID string
// ExpectedState, when set, must equal the response's state (the value
// that you sent and kept for this sign-in).
ExpectedState string
// JWKS supplies the organization's keys directly. When nil, the keys
// are read through the issuer's discovery document and cached on this
// client, with one refetch for an unknown kid.
JWKS *JWKS
// ClockSkew tolerated on exp. The default (0) means 60 seconds; a
// negative value means none.
ClockSkew time.Duration
}
AuthorizationResponseOptions configures VerifyAuthorizationResponse.
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, except
// with RequestURI or Request.
RedirectURI string
// Scope defaults to "openid profile email".
Scope string
// State is the CSRF token echoed back to the redirect URI.
State string
// Nonce is the OpenID Connect nonce that the ID token carries back.
Nonce string
// ResponseType defaults to "code".
ResponseType string
// ResponseMode is how the answer comes back: "query" (the default for
// code), or a JARM mode ("jwt", "query.jwt", "form_post.jwt",
// "fragment.jwt") that signs it. Verify a JARM answer with
// VerifyAuthorizationResponse.
ResponseMode 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
// Resource is the RFC 8707 resource indicator: the absolute URL of the
// API that the token is for.
Resource string
// Extra adds arbitrary query parameters.
Extra map[string]string
// AuthorizationDetails asks for fine-grained permissions (RFC 9396):
// a list of objects, each with a non-empty "type", for example
// {"type": "payment_initiation", "actions": ["initiate"], "instructedAmount": …}.
// It is sent as a JSON string, and as a JSON array claim in a request
// object. LumoAuth checks the types; the SDK checks only the shape.
AuthorizationDetails []map[string]any
// RequestURI is the request_uri of a pushed authorization request
// (PushAuthorizationRequest). The URL then carries only client_id and
// request_uri, and every other field must be empty.
RequestURI string
// Request is a signed request object (CreateRequestObject), sent by
// value. The URL then carries only client_id and request, and every
// other field must be empty: the parameters are in the object.
Request string
}
AuthorizationURLParams describes an authorization-code redirect. The same parameters make a pushed authorization request (PushAuthorizationRequest) and a signed request object (CreateRequestObject).
type BackchannelAuthorizeParams ¶ added in v1.8.0
type BackchannelAuthorizeParams struct {
// ClientAuth authenticates the application, which must be confidential
// and have CIBA switched on. Required.
ClientAuth ClientAuth
// LoginHint names the person: an e-mail address or a user ID. Set it,
// IDTokenHint or LoginHintToken (exactly one).
LoginHint string
// IDTokenHint is an ID token that LumoAuth issued to the application for
// the person.
IDTokenHint string
// LoginHintToken is a token that names the person.
LoginHintToken string
// Scopes are the scopes asked for. Required; include openid.
Scopes []string
// BindingMessage is shown to the person on both devices, so that they
// can tell that the request is the one they started (at most 255
// characters).
BindingMessage string
// RequestedExpiry asks for a lifetime of the request (whole seconds).
RequestedExpiry time.Duration
// ACRValues are the requested authentication context classes.
ACRValues []string
}
BackchannelAuthorizeParams starts an OpenID CIBA request: LumoAuth asks the person on their own device (push or e-mail) to approve the sign-in.
type BackchannelAuthorizeResponse ¶ added in v1.8.0
type BackchannelAuthorizeResponse struct {
AuthReqID string `json:"auth_req_id"`
// ExpiresIn is the lifetime of the request in seconds.
ExpiresIn int `json:"expires_in"`
// Interval is the minimum wait between polls in seconds.
Interval int `json:"interval,omitempty"`
}
BackchannelAuthorizeResponse is the answer of the backchannel authentication endpoint (CIBA Core §7.3). LumoAuth gives the same answer for a person it does not know, so the answer never confirms the hint.
func (*BackchannelAuthorizeResponse) PollOptions ¶ added in v1.8.0
func (b *BackchannelAuthorizeResponse) PollOptions(auth ClientAuth) PollOptions
PollOptions returns the options for PollBackchannelToken from this answer: its interval and lifetime, with the given client authentication.
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. It is set by
// CheckBudget; a server refusal carries no policy, so it is nil there.
Budget *AgentBudget
// RetryAfter is the server's Retry-After hint: the time until the spent
// window starts again. 0 for CheckBudget.
RetryAfter time.Duration
}
BudgetError is returned when an agent's budget policy blocks an action: by Agent.CheckBudget, which checks locally and makes no request, and for a server answer with the body code budget_exceeded (429).
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
// Poppy covers the Personal Agent Protocol for your own API: it
// verifies requests from personal agents, and looks up and ends their
// Sessions. It needs WithClientCredentials.
Poppy *PoppyResource
// 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 (an API key, a token provider, or the client credentials of WithClientCredentials), unless WithoutCredential is given.
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).
On a custom domain BaseURL is the domain. The generated client puts /orgs/{orgId} in every path, and a custom domain answers 404 for those. When the client has an organization ID (WithOrgID), HTTPClient is a copy whose transport removes the segment of that organization from requests to the custom domain, so pass the same ID to the generated client's calls. Without an organization ID the generated client cannot reach a custom domain.
func (*Client) BaseURL ¶
BaseURL returns the address that the client sends its requests to, without a trailing slash: the custom domain when one is set, the LumoAuth instance URL otherwise.
func (*Client) CustomDomain ¶ added in v1.7.0
CustomDomain returns the organization's custom domain as an origin, for example "https://auth.acme.com", or "" when none is set.
func (*Client) DPoP ¶ added in v1.2.0
func (c *Client) DPoP() *DPoPSigner
DPoP returns the signer passed with WithDPoP, or nil.
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.
On a custom domain, give the path without the /orgs/{orgId} segment, or build it with OrgPath. A path that starts with the segment of the client's own organization still works when the client has that organization ID: the segment is removed. A path of another organization is sent as it is.
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.
func (*Client) Issuer ¶ added in v1.7.0
Issuer returns the issuer identifier of the organization: the `iss` of its tokens and the audience of a client assertion. On a custom domain it is the bare domain. On the platform host it is {baseURL}/orgs/{orgID}/api/v1, and a client without an organization ID gets a *ConfigError.
func (*Client) OrgPath ¶
OrgPath prefixes a path with this client's org-scoped API base, so callers building requests by hand do not hardcode the layout:
path, err := client.OrgPath("/admin/users") // /orgs/acme-corp/api/v1/admin/users
On a custom domain the result is /api/v1/admin/users, and no organization ID is needed.
type ClientAssertionOptions ¶ added in v1.3.0
type ClientAssertionOptions struct {
// KeyID is the kid of the registered public key. Required by the server
// when the agent has more than one key.
KeyID string
// Algorithm overrides the key's natural algorithm (ES256/ES384/ES512 by
// curve, EdDSA, RS256). RSA keys may also use RS384, RS512, PS256, PS384
// or PS512.
Algorithm string
// Lifetime is the time until exp: 1s to 10m. Default 60s.
Lifetime time.Duration
}
ClientAssertionOptions configures a ClientAssertionSigner.
type ClientAssertionSigner ¶ added in v1.3.0
type ClientAssertionSigner struct {
// contains filtered or unexported fields
}
ClientAssertionSigner signs private_key_jwt client assertions with one key.
func GenerateClientAssertionSigner ¶ added in v1.3.0
func GenerateClientAssertionSigner(algorithm, keyID string) (*ClientAssertionSigner, error)
GenerateClientAssertionSigner creates a new key for algorithm: ES256 (default when empty), ES384, ES512, EdDSA, or an RSA algorithm (2048 bits).
func LoadClientAssertionSigner ¶ added in v1.3.0
func LoadClientAssertionSigner(pemData string, opts ClientAssertionOptions) (*ClientAssertionSigner, error)
LoadClientAssertionSigner parses a PEM private key (PKCS#8 "PRIVATE KEY", SEC 1 "EC PRIVATE KEY" or PKCS#1 "RSA PRIVATE KEY").
func NewClientAssertionSigner ¶ added in v1.3.0
func NewClientAssertionSigner(key crypto.Signer, opts ClientAssertionOptions) (*ClientAssertionSigner, error)
NewClientAssertionSigner wraps a private key: an *ecdsa.PrivateKey on P-256, P-384 or P-521, an ed25519.PrivateKey or an *rsa.PrivateKey of at least 2048 bits.
func (*ClientAssertionSigner) Algorithm ¶ added in v1.3.0
func (s *ClientAssertionSigner) Algorithm() string
Algorithm is the JWS alg of the assertions.
func (*ClientAssertionSigner) Assertion ¶ added in v1.3.0
func (s *ClientAssertionSigner) Assertion(clientID, audience string) (string, error)
Assertion signs one client assertion for clientID (the agent ID) and audience (the organization's issuer identifier, see IssuerFor).
func (*ClientAssertionSigner) JWKS ¶ added in v1.3.0
func (s *ClientAssertionSigner) JWKS() (JWKS, error)
JWKS is {"keys": PublicJWK}: what to register on the agent.
func (*ClientAssertionSigner) KeyID ¶ added in v1.3.0
func (s *ClientAssertionSigner) KeyID() string
KeyID is the kid put in every assertion header ("" when unset).
func (*ClientAssertionSigner) PrivateKeyPEM ¶ added in v1.3.0
func (s *ClientAssertionSigner) PrivateKeyPEM() (string, error)
PrivateKeyPEM is the private key as PKCS#8 PEM, for your secret store.
func (*ClientAssertionSigner) PublicJWK ¶ added in v1.3.0
func (s *ClientAssertionSigner) PublicJWK() (JWK, error)
PublicJWK is the public key with kid (when set), alg and use "sig".
type ClientAttestation ¶ added in v1.8.0
type ClientAttestation struct {
// Attestation is the attester's JWT (typ oauth-client-attestation+jwt),
// sent as it is. Its sub is the client ID and its cnf.jwk the public key
// of InstanceKey. Required.
Attestation string
// InstanceKey is the instance's private key. It signs the proof of
// possession; its algorithm must be one of RS256–RS512, PS256–PS512 or
// ES256–ES512. Required.
InstanceKey *ClientAssertionSigner
// Challenge is a challenge that the server handed out, when it uses
// them. It becomes the proof's challenge claim.
Challenge string
}
ClientAttestation is what an instance of your application presents for attestation-based client authentication: the JWT that your attester issued for the instance and the instance's own key.
type ClientAuth ¶ added in v1.8.0
type ClientAuth struct {
// ClientID is the application's client ID. Required.
ClientID string
// ClientSecret is the secret of a confidential application.
ClientSecret string
// ClientAuthMethod is how ClientSecret is sent: ClientSecretPost (the
// default) or ClientSecretBasic.
ClientAuthMethod string
// AssertionSigner signs a private_key_jwt client assertion (RFC 7523)
// for each request, addressed to the organization's issuer.
AssertionSigner *ClientAssertionSigner
// ClientAssertion is a client assertion that you signed. Single-use.
ClientAssertion string
// Attestation authenticates an instance of the application with an
// attestation and a proof of possession of its key.
Attestation *ClientAttestation
}
ClientAuth is how your application authenticates at LumoAuth's OAuth endpoints. Set ClientID and at most one credential:
- nothing else: a public client, which sends only client_id;
- ClientSecret, sent as form fields (ClientSecretPost, the default) or in an HTTP Basic header (ClientAuthMethod: ClientSecretBasic);
- AssertionSigner (private_key_jwt): a new client assertion is signed for each request, so it also works for the polling calls;
- ClientAssertion: one assertion that you signed yourself. It works once, so do not use it for polling;
- Attestation (attest_jwt_client_auth): the attester's JWT and a new proof of possession for each request.
type ClientCredentialsParams ¶ added in v1.8.0
type ClientCredentialsParams struct {
// ClientID is the OAuth client or the agent. Required.
ClientID string
// ClientSecret authenticates a client with a secret. Set it or
// ClientAssertion, not both.
ClientSecret string
// ClientAuthMethod is how ClientSecret is sent: ClientSecretPost (the
// default, as ClientCredentials does) or ClientSecretBasic.
ClientAuthMethod string
// ClientAssertion is a private_key_jwt client assertion (RFC 7523),
// built with ClientAssertionSigner.Assertion; it is single-use.
ClientAssertion string
// Scopes optionally narrows the token; empty means the client's
// defaults.
Scopes []string
// Resource is the RFC 8707 resource indicator: the absolute URL of the
// API that the token is for. It becomes the token's aud; without it,
// aud is the client ID. The client's allowed audiences, when set, must
// cover it, and a registered MCP server applies its own policy.
Resource string
}
ClientCredentialsParams describes a client-credentials grant.
type ClientMetadata ¶ added in v1.8.0
type ClientMetadata struct {
RedirectURIs []string `json:"redirect_uris,omitempty"`
ClientName string `json:"client_name,omitempty"`
TokenEndpointAuthMethod string `json:"token_endpoint_auth_method,omitempty"`
GrantTypes []string `json:"grant_types,omitempty"`
ResponseTypes []string `json:"response_types,omitempty"`
// Scope is the space-separated list of scopes the client may ask for.
Scope string `json:"scope,omitempty"`
ApplicationType string `json:"application_type,omitempty"`
ClientURI string `json:"client_uri,omitempty"`
LogoURI string `json:"logo_uri,omitempty"`
PolicyURI string `json:"policy_uri,omitempty"`
TOSURI string `json:"tos_uri,omitempty"`
Contacts []string `json:"contacts,omitempty"`
JWKSURI string `json:"jwks_uri,omitempty"`
JWKS *JWKS `json:"jwks,omitempty"`
PostLogoutRedirectURIs []string `json:"post_logout_redirect_uris,omitempty"`
// Extra holds other members; a name that a field above also sets is
// refused.
Extra map[string]any `json:"-"`
}
ClientMetadata is the metadata of a client to register (RFC 7591 §2, OpenID Connect Dynamic Client Registration). Fields left empty are not sent; Extra adds any other member.
type ConfidentialClient ¶
type ConfidentialClient interface {
TokenSource
ClientID() string
ClientSecret() string
}
ConfidentialClient is what the deprecated NewDelegationChain needs from an agent: a token source plus OAuth client credentials. *Agent satisfies it.
As for a TokenSource, an implementation that addresses its organization on a custom domain also has the method CustomDomain() string.
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 ConnectionToken ¶ added in v1.8.0
type ConnectionToken struct {
// AccessToken is the provider's token. Send it to the provider only.
AccessToken string
// TokenType is "Bearer".
TokenType string
// ExpiresAt is when the token expires; zero when the provider's token
// does not expire.
ExpiresAt time.Time
Scopes []string
}
ConnectionToken is a live access token for an outbound connection. Printing it (fmt, log/slog) shows no token; read AccessToken to use it, and never log it.
func (ConnectionToken) GoString ¶ added in v1.8.0
func (t ConnectionToken) GoString() string
GoString keeps the token out of %#v.
func (ConnectionToken) Header ¶ added in v1.8.0
func (t ConnectionToken) Header() string
Header is the Authorization header value for the provider.
func (ConnectionToken) LogValue ¶ added in v1.8.0
func (t ConnectionToken) LogValue() slog.Value
LogValue keeps the token out of log/slog output.
func (ConnectionToken) String ¶ added in v1.8.0
func (t ConnectionToken) String() string
String shows the token's type, expiry and scopes, never the token.
type ConnectionTokenParams ¶ added in v1.8.0
type ConnectionTokenParams struct {
// UserID names the person (user ID or e-mail address) of a
// user-delegated connection. The agent must be allowed to act on behalf
// of users, and the person must have allowed this agent on their grant.
// Leave it empty for a machine connection.
UserID string
// Traceparent is a W3C trace context header value, sent as the
// traceparent header, so that the audit entry carries your trace ID.
Traceparent string
}
ConnectionTokenParams configures GetConnectionToken.
type ConsentURLParams
deprecated
type ConsentURLParams struct {
// ClientID is the OAuth client of the sign-in. Required. An agent's ID
// is refused.
ClientID string
// RedirectURI is where consent returns the user. Required.
RedirectURI string
// Scopes are the scopes being requested. Defaults to
// ["documents:read"].
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.
Deprecated: use ApplicationConsentParams. LumoAuth starts a sign-in only for an application, never for an agent's ID, and the agent's credentials cannot redeem the code.
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 DPoPProofOption ¶ added in v1.2.0
type DPoPProofOption func(*dpopProofConfig)
DPoPProofOption customises one proof.
func WithProofAccessToken ¶ added in v1.2.0
func WithProofAccessToken(accessToken string) DPoPProofOption
WithProofAccessToken adds the `ath` claim — the SHA-256 hash of the access token the proof accompanies. Required on every resource request.
func WithProofNonce ¶ added in v1.2.0
func WithProofNonce(nonce string) DPoPProofOption
WithProofNonce sets the `nonce` claim explicitly, overriding the nonce the signer remembers for the target's origin. Pass "" to omit the claim.
type DPoPRequest ¶ added in v1.2.0
type DPoPRequest struct {
// Method is the HTTP method of the request.
Method string
// URL is the absolute request URL. Query and fragment are ignored.
URL string
// Proof is the value of the DPoP header ("" when absent).
Proof string
// Scheme is the Authorization scheme the token came with: "DPoP" or
// "Bearer".
Scheme string
// Nonce is the nonce that this resource server expects in the proof
// (RFC 9449 §9), when it issues nonces. "" means no nonce check. A
// proof without it, or with another value, is refused with
// TokenRejectedDPoPNonce.
Nonce string
}
DPoPRequest describes the incoming request a DPoP-bound token arrived with, so the proof can be checked against it. Build one with DPoPRequestFromHTTP.
func DPoPRequestFromHTTP ¶ added in v1.2.0
func DPoPRequestFromHTTP(r *http.Request) *DPoPRequest
DPoPRequestFromHTTP reads the DPoP-relevant parts of an incoming request. The scheme of the URL is https when the connection is TLS or an X-Forwarded-Proto header says so, http otherwise; the host is r.Host. Behind a proxy that rewrites the host, set DPoPRequest.URL yourself.
type DPoPSigner ¶ added in v1.2.0
type DPoPSigner struct {
// contains filtered or unexported fields
}
DPoPSigner signs RFC 9449 proofs with one private key.
func LoadDPoPSigner ¶ added in v1.2.0
func LoadDPoPSigner(pemData string) (*DPoPSigner, error)
LoadDPoPSigner parses a PEM private key (PKCS#8 "PRIVATE KEY" or SEC 1 "EC PRIVATE KEY") into a signer. The key must be P-256 or Ed25519.
func NewDPoPSigner ¶ added in v1.2.0
func NewDPoPSigner() (*DPoPSigner, error)
NewDPoPSigner generates a fresh P-256 key and returns a signer for ES256 proofs — the recommended default.
signer, err := lumoauth.NewDPoPSigner()
agent, err := lumoauth.NewAgent(lumoauth.AgentConfig{DPoP: signer})
The key lives only in memory; a new process gets a new key, which is fine because the tokens it binds are short-lived. To keep one key across restarts, generate it once (GenerateDPoPKeyPEM) and load it with LoadDPoPSigner.
func NewDPoPSignerEd25519 ¶ added in v1.2.0
func NewDPoPSignerEd25519() (*DPoPSigner, error)
NewDPoPSignerEd25519 generates a fresh Ed25519 key and returns a signer for EdDSA proofs.
func NewDPoPSignerFromKey ¶ added in v1.2.0
func NewDPoPSignerFromKey(key crypto.Signer) (*DPoPSigner, error)
NewDPoPSignerFromKey wraps an existing private key: an *ecdsa.PrivateKey on P-256 (ES256) or an ed25519.PrivateKey (EdDSA). Other key types are a *ValidationError.
func (*DPoPSigner) Algorithm ¶ added in v1.2.0
func (s *DPoPSigner) Algorithm() string
Algorithm returns the JWS algorithm of the proofs: "ES256" or "EdDSA".
func (*DPoPSigner) AuthorizeRequest ¶ added in v1.2.0
func (s *DPoPSigner) AuthorizeRequest(req *http.Request, accessToken string) error
AuthorizeRequest sets the Authorization header for a resource call — an MCP server, say — and, when the token is DPoP-bound (carries cnf.jkt), the `DPoP` scheme plus a proof over the request with `ath`:
req, _ := http.NewRequestWithContext(ctx, "POST", "https://mcp.example.com/mcp", body)
if err := signer.AuthorizeRequest(req, mcpToken); err != nil {
return err
}
An unbound token is sent as `Authorization: Bearer`, without a proof. If the server answers 401 with a DPoP-Nonce header, call RememberNonce on the response and send the request again.
func (*DPoPSigner) Nonce ¶ added in v1.2.0
func (s *DPoPSigner) Nonce(rawURL string) string
Nonce returns the nonce the signer remembers for rawURL's origin, or "".
func (*DPoPSigner) Proof ¶ added in v1.2.0
func (s *DPoPSigner) Proof(method, rawURL string, opts ...DPoPProofOption) (string, error)
Proof signs a DPoP proof for one HTTP request.
method is the HTTP method; rawURL is the request URL. The proof carries `htm` (the method, upper-case), `htu` (the URL without query or fragment), `iat`, a random `jti`, the `nonce` the signer remembers for that origin unless WithProofNonce overrides it, and `ath` when WithProofAccessToken is given.
func (*DPoPSigner) PublicJWK ¶ added in v1.2.0
func (s *DPoPSigner) PublicJWK() JWK
PublicJWK returns the public key as it appears in each proof's header. It never includes private members.
func (*DPoPSigner) RememberNonce ¶ added in v1.2.0
func (s *DPoPSigner) RememberNonce(resp *http.Response) bool
RememberNonce reads a DPoP-Nonce header from a response and stores it for the origin of the request that produced it. It reports whether a nonce was present. Call it on every response from a server that uses DPoP nonces; the SDK does so for its own requests.
func (*DPoPSigner) SetNonce ¶ added in v1.2.0
func (s *DPoPSigner) SetNonce(rawURL, nonce string)
SetNonce remembers a server-issued nonce for rawURL's origin (scheme://host[:port]). Later proofs for that origin carry it. Pass "" to forget the nonce.
func (*DPoPSigner) Thumbprint ¶ added in v1.2.0
func (s *DPoPSigner) Thumbprint() string
Thumbprint returns the RFC 7638 thumbprint of the public key — the value the server writes into a bound token's cnf.jkt.
type DelegationApplication ¶ added in v1.8.0
type DelegationApplication struct {
// ClientID is the application's client ID, never the agent's agt_… ID.
// Required.
ClientID string
// ClientSecret is the application's secret; leave it empty for a public
// application (PKCE alone).
ClientSecret string
// RedirectURI is one of the application's registered redirect URIs,
// where your callback receives the code. Required.
RedirectURI string
// OfflineAccess asks for a refresh token (scope offline_access). The
// chain needs it to renew the person's token and to revoke the grant.
OfflineAccess bool
}
DelegationApplication is the application of your organization through which a person lets an agent act for them. An agent never starts a sign-in: the person signs in to this application, the application redeems the code, and the agent exchanges the person's access token.
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:
Consent — the person signs in to your application (ConsentURL), and the application redeems the code (HandleConsentCallback). Or register tokens that you already hold (SetUserTokens, SetUserToken).
Token exchange — combine the person'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 — the application revokes the person's refresh token, which ends every delegated token of that grant.
For example:
chain, err := lumoauth.NewDelegationChainForApplication(agent, lumoauth.DelegationApplication{
ClientID: os.Getenv("APP_CLIENT_ID"),
ClientSecret: os.Getenv("APP_CLIENT_SECRET"),
RedirectURI: "https://app.example.com/agent/callback",
OfflineAccess: true,
})
url, err := chain.ConsentURL("session-1", []string{"documents:read"}, "")
// … the person signs in, your callback receives `code` …
err = chain.HandleConsentCallback(ctx, "session-1", code)
resp, err := chain.DoRaw(ctx, "session-1", "GET", "https://api.example.com/documents", nil)
A DelegationChain is safe for concurrent use.
func NewDelegationChain
deprecated
func NewDelegationChain(agent ConfidentialClient, redirectURI string) *DelegationChain
NewDelegationChain builds a chain over an authenticated agent, with the agent's own client ID for the consent flow.
Deprecated: LumoAuth starts a sign-in only for an application, so the consent flow of this chain cannot work for an agent's agt_… ID: ConsentURL and HandleConsentCallback then return a *ConfigError. Use NewDelegationChainForApplication. The exchange, delegated requests and SetUserToken keep working.
func NewDelegationChainForApplication ¶ added in v1.8.0
func NewDelegationChainForApplication(agent TokenSource, app DelegationApplication) (*DelegationChain, error)
NewDelegationChainForApplication builds a chain whose consent flow goes through one of your organization's applications. agent supplies the actor token of every exchange (an *Agent does); the application's credentials redeem the code, refresh the person's token and revoke it. It returns a *ConfigError for an application without a client ID, with an agent's ID, or without an absolute redirect URI.
Example ¶
Acting on behalf of a user, with the chain recorded in the token. The person signs in to an application of the organization; the agent then exchanges the person's token.
package main
import (
"context"
"fmt"
"log"
"net/http"
"os"
lumoauth "github.com/lumoauth/lumo-auth-go"
)
func main() {
agent, err := lumoauth.NewAgent(lumoauth.AgentConfig{})
if err != nil {
log.Fatal(err)
}
chain, err := lumoauth.NewDelegationChainForApplication(agent, lumoauth.DelegationApplication{
ClientID: os.Getenv("APP_CLIENT_ID"),
ClientSecret: os.Getenv("APP_CLIENT_SECRET"), // empty for a public application
RedirectURI: "https://app.example.com/agent/callback",
OfflineAccess: true, // a refresh token, to renew the person's token and to revoke
})
if err != nil {
log.Fatal(err)
}
ctx := context.Background()
// 1. Send the person here to sign in to the application.
consentURL, err := chain.ConsentURL("session-1", []string{"documents:read"}, "")
if err != nil {
log.Fatal(err)
}
fmt.Println("visit:", consentURL)
// 2. Your callback receives ?code=…&state=… (compare the state with
// chain.ConsentState). The application redeems the 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.
resp, err := chain.DoRaw(ctx, "session-1", http.MethodGet, "https://api.example.com/documents", nil)
if err != nil {
log.Fatal(err)
}
_ = resp.Body.Close()
// 4. End the delegation: the application revokes the person's refresh token.
if err := chain.Revoke(ctx, "session-1"); err != nil {
log.Print(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) ConsentState ¶ added in v1.8.0
func (c *DelegationChain) ConsentState(sessionID string) string
ConsentState returns the state of the session's consent URL that has not been redeemed yet, or "".
func (*DelegationChain) ConsentURL ¶
func (c *DelegationChain) ConsentURL(sessionID string, scopes []string, state string) (string, error)
ConsentURL builds the URL where the person signs in to your application to let the agent act for them. Redirect the person there; the sign-in returns them to the application's redirect URI with a code.
The URL names the application, asks for "openid", the scopes and, with DelegationApplication.OfflineAccess, offline_access, and carries a PKCE S256 challenge whose verifier the chain keeps for HandleConsentCallback. Scopes are required: the exchange grants the agent only scopes that the person consented to. state defaults to a random value; ConsentState returns it, so your callback can compare it with the one it receives.
On a chain from the deprecated NewDelegationChain, this builds the old URL with the agent's client ID, and returns a *ConfigError for an agent's agt_… ID, which LumoAuth answers with "Unknown Application".
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) Forget ¶ added in v1.8.0
func (c *DelegationChain) Forget(sessionID string)
Forget drops a session's local state (tokens and pending consent) without any request. The person's grant at LumoAuth is not touched.
func (*DelegationChain) HandleConsentCallback ¶
func (c *DelegationChain) HandleConsentCallback(ctx context.Context, sessionID, authorizationCode string) error
HandleConsentCallback redeems the code of the consent callback as the application (its client ID, its secret when it is confidential, and the PKCE verifier of this session's ConsentURL) and stores the person's tokens under sessionID. The agent's credentials play no part. The session's consent is used up whether or not the redemption succeeds: a code is single-use, so a failure needs a new ConsentURL.
It returns a *ConfigError when this chain handed out no consent URL for the session, and, on a chain from the deprecated NewDelegationChain, for an agent's agt_… ID.
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: the application revokes the person's refresh token at LumoAuth (POST /oauth/revoke with the application's client ID, and its secret when it is confidential), which ends every delegated token of that grant, and the chain drops the session's local state. Local state is cleared even if the server call fails, so a revoked session never keeps serving requests from cache.
When the chain cannot end the grant at LumoAuth, it only forgets the local state and says so: the error matches ErrDelegationNotRevoked (and ErrConfig). That is the case for a session without a refresh token (for example one registered with SetUserToken), and on a chain without the application's credentials (the deprecated NewDelegationChain with an agent: LumoAuth refuses a revocation by another client than the one the token was issued to). Revoke the person's refresh token where it is held, with Auth.Revoke and the application's credentials, or call Forget when forgetting is all you want. An unknown session returns nil.
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, and Revoke can only forget it (ErrDelegationNotRevoked). SetUserTokens also takes the refresh token.
func (*DelegationChain) SetUserTokens ¶ added in v1.8.0
func (c *DelegationChain) SetUserTokens(sessionID string, tokens *TokenResponse) error
SetUserTokens registers the person's tokens that your application got itself, for example from its own sign-in: the access token, and the refresh token when there is one. With the refresh token, and the application's credentials (NewDelegationChainForApplication), the chain renews the person's token and Revoke ends the grant.
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) ApplicationConsentURL ¶ added in v1.8.0
func (r *DelegationResource) ApplicationConsentURL(params ApplicationConsentParams) (string, error)
ApplicationConsentURL builds the authorization URL where a person signs in to your application to let an agent act for them. The application then redeems the code with ExchangeCode (its client ID, its secret when it is confidential, and the PKCE verifier), and the agent calls Exchange with the person's access token. Revoke the person's refresh token as the application to end the delegation.
func (*DelegationResource) ConsentURL
deprecated
func (r *DelegationResource) ConsentURL(params ConsentURLParams) (string, error)
ConsentURL builds an authorization URL that requests offline access.
Deprecated: use ApplicationConsentURL, which names an application, uses PKCE and asks for offline_access. With an agent's ID this returns a ValidationError: LumoAuth answers "Unknown Application" for it.
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 person's tokens. Pass the APPLICATION's client ID (and its secret when it is confidential) and the PKCE verifier; the agent's credentials are refused for the code.
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 the person's access token, as the application that holds the refresh token (its client ID, and its secret when it is confidential).
func (*DelegationResource) Revoke ¶
func (r *DelegationResource) Revoke(ctx context.Context, params RevokeParams) error
Revoke invalidates the person's refresh token, which also ends every token derived from it, the agent's delegated tokens included. Pass the client ID (and secret) of the APPLICATION that the token was issued to: LumoAuth refuses a revocation by another client, such as the agent (RFC 7009 §2.1).
type DeviceAuthorizationParams ¶ added in v1.8.0
type DeviceAuthorizationParams struct {
// ClientAuth names the application. A public client (a CLI, a TV app)
// sets ClientID alone; a confidential client authenticates as at the
// token endpoint. The application must allow the device code grant.
ClientAuth ClientAuth
// Scopes are the scopes asked for. Empty means openid, profile and email,
// as far as the application allows them.
Scopes []string
// Resource is the RFC 8707 resource indicator: the absolute URL of the
// API that the token is for.
Resource string
// AuthorizationDetails asks for fine-grained permissions (RFC 9396);
// see AuthorizationURLParams.AuthorizationDetails.
AuthorizationDetails []map[string]any
}
DeviceAuthorizationParams starts a device authorization grant.
type DeviceAuthorizationResponse ¶ added in v1.8.0
type DeviceAuthorizationResponse struct {
DeviceCode string `json:"device_code"`
UserCode string `json:"user_code"`
VerificationURI string `json:"verification_uri"`
VerificationURIComplete string `json:"verification_uri_complete,omitempty"`
// ExpiresIn is the lifetime of the codes in seconds.
ExpiresIn int `json:"expires_in"`
// Interval is the minimum wait between polls in seconds.
Interval int `json:"interval,omitempty"`
}
DeviceAuthorizationResponse is the answer of the device authorization endpoint (RFC 8628 §3.2). Show UserCode and VerificationURI (or VerificationURIComplete, for example as a QR code) to the person, then call PollDeviceToken with DeviceCode.
func (*DeviceAuthorizationResponse) PollOptions ¶ added in v1.8.0
func (d *DeviceAuthorizationResponse) PollOptions(auth ClientAuth) PollOptions
PollOptions returns the options for PollDeviceToken from this answer: its interval and lifetime, with the given client authentication.
type EndSessionURLParams ¶ added in v1.8.0
type EndSessionURLParams struct {
// IDTokenHint is the last ID token that LumoAuth issued to your client
// for this user; an expired one is accepted. With it, LumoAuth ends the
// session at once and honours PostLogoutRedirectURI. Without it, the
// user confirms the sign-out on a LumoAuth page and stays there.
IDTokenHint string
// PostLogoutRedirectURI is where LumoAuth sends the browser afterwards.
// It must be an absolute URL registered on the client as a post-logout
// redirect URI.
PostLogoutRedirectURI string
// State is passed back to PostLogoutRedirectURI unchanged.
State string
}
EndSessionURLParams describes an RP-initiated logout (OpenID Connect RP-Initiated Logout 1.0) at the organization's end-session endpoint.
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
// ClientAuth, when set, authenticates the client instead of ClientID and
// ClientSecret (leave those empty): private_key_jwt with an
// AssertionSigner, attestation, HTTP Basic. FAPI applications need it.
ClientAuth *ClientAuth
// AuthorizationDetails asks for a part of the granted fine-grained
// permissions (RFC 9396). nil sends nothing: the token gets the whole
// grant. An empty, non-nil list sends [] (none). A wider request is
// refused with invalid_authorization_details.
AuthorizationDetails []map[string]any
}
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 IntrospectOptions ¶ added in v1.8.0
type IntrospectOptions struct {
// TokenTypeHint is "access_token" or "refresh_token": where LumoAuth
// looks first.
TokenTypeHint string
// ClientAuth authenticates your application (or agent), which must hold
// a credential: public clients cannot introspect. Required.
ClientAuth ClientAuth
}
IntrospectOptions configures Introspect.
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.
func (*JWK) Thumbprint ¶
Thumbprint computes the RFC 7638 JWK thumbprint — the base64url SHA-256 of the key's canonical form. LumoAuth uses it as `agent_jkt` in resource tokens and as `cnf_jkt` in the answer of the token verify endpoint. Auth tokens carry the full key in cnf.jwk, not the thumbprint.
type JWKS ¶
type JWKS struct {
Keys []JWK `json:"keys"`
}
JWKS is a JSON Web Key Set, as published at a jwks_uri.
func FetchAccessTokenJWKS ¶ added in v1.2.0
func FetchAccessTokenJWKS(ctx context.Context, issuer string, httpClient *http.Client) (*JWKS, error)
FetchAccessTokenJWKS retrieves an organization's token-signing keys: it reads jwks_uri from {issuer}/.well-known/openid-configuration and fetches that document.
For an organization on a custom domain, the issuer is the bare domain. NewAccessTokenKeyCacheForCustomDomain and AccessTokenVerifyOptions.CustomDomain read the domain's discovery document at /api/v1/.well-known/openid-configuration.
func FetchIssuerJWKS ¶
FetchIssuerJWKS retrieves an AAuth issuer's signing keys from {issuer}/aauth/jwks.json. The AAuth issuer has the platform form on every host, so this address is on the platform host. To read the keys from an organization's custom domain, use NewJWKSCacheForCustomDomain or VerifyOptions.CustomDomain.
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 NewJWKSCacheForCustomDomain ¶ added in v1.7.0
func NewJWKSCacheForCustomDomain(customDomain string, ttl time.Duration, httpClient *http.Client) (*JWKSCache, error)
NewJWKSCacheForCustomDomain builds a cache that reads the AAuth key set from an organization's custom domain, for example "auth.acme.com", at /api/v1/aauth/jwks.json. It returns a *ConfigError for a value that is empty or not valid (see WithCustomDomain). 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 JitTokenClaims ¶ added in v1.8.0
type JitTokenClaims struct {
// AuthorizationDetails are the approved RFC 9396 entries
// (permissions.authorization_details).
AuthorizationDetails []map[string]any
// Subject is the token's sub: the user, or "agent_agt_…" for an agent
// that acts on its own.
Subject string
// AgentID is the agent that the approval was issued to ("agt_…").
AgentID string
// TaskID is the task of the approval ("task_…"), when there is one.
TaskID string
// RequestID is the approved request ("jit_…"), when the token names it.
RequestID string
JTI string
Expires int64
// Raw is every claim of the token.
Raw map[string]any
}
JitTokenClaims is a verified JIT token: the approval of one JIT request.
func VerifyJitToken ¶ added in v1.8.0
func VerifyJitToken(ctx context.Context, token string, opts JitTokenVerifyOptions) (*JitTokenClaims, error)
VerifyJitToken verifies a LumoAuth JIT token and returns the approval:
approval, err := lumoauth.VerifyJitToken(ctx, r.Header.Get("X-LumoAuth-Jit-Token"), lumoauth.JitTokenVerifyOptions{
Issuer: "https://app.lumoauth.dev/orgs/acme-corp/api/v1",
Caller: claims, // the verified access token of this request
RequiredDetails: []map[string]any{{"type": "invoice", "actions": []string{"refund"}, "identifier": "INV-1001"}},
})
Failures are a *ValidationError whose Reason is a TokenRejected* constant: TokenRejectedJITNotForCaller for an approval of another person or agent, TokenRejectedJITInsufficient when RequiredDetails are not covered, TokenRejectedNotJIT for a token that is no approval. Fetch failures are *NetworkError or *APIError.
type JitTokenVerifyOptions ¶ added in v1.8.0
type JitTokenVerifyOptions struct {
// Issuer is the organization's issuer, e.g.
// "https://app.lumoauth.dev/orgs/acme-corp/api/v1". Required unless
// CustomDomain is set.
Issuer string
// OrgID is the organization ID (slug): the aud of its JIT tokens. When
// empty it is read from an Issuer of the form …/orgs/{slug}/api/v1.
// Required with CustomDomain.
OrgID string
// CustomDomain is the organization's custom domain ("auth.acme.com"):
// the issuer is then the bare domain, and Issuer is not used.
CustomDomain string
// Caller is the verified access token of the request (for example from
// VerifyAccessToken or AccessTokenFromContext). The JIT token must
// belong to it (rule 10). Set Caller, or ExpectedSubject and
// ExpectedAgent; with neither, the binding is not checked.
Caller *AccessTokenClaims
// ExpectedSubject is the sub that the JIT token must carry: the user, or
// "agent_agt_…" for an agent that acts on its own.
ExpectedSubject string
// ExpectedAgent is the agent that must hold the approval: "agt_…" or
// "agent_agt_…".
ExpectedAgent string
// RequiredDetails are the RFC 9396 entries that the call needs; each
// must be covered by the approval (rule 11). Empty means no check.
RequiredDetails []map[string]any
// JWKS supplies the organization's keys directly. When nil, they are
// fetched through the discovery document and cached (KeyCache, or a
// process-wide cache per issuer).
JWKS *JWKS
// KeyCache is the cache to fetch keys through when JWKS is nil.
KeyCache *AccessTokenKeyCache
// HTTPClient fetches discovery and keys. Defaults to a 30s-timeout
// client.
HTTPClient *http.Client
// ClockSkew tolerated on exp, nbf and iat. The default (0) means 60
// seconds; a negative value means none.
ClockSkew time.Duration
}
JitTokenVerifyOptions configures VerifyJitToken.
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 MCPTransport ¶ added in v1.8.0
type MCPTransport struct {
// contains filtered or unexported fields
}
MCPTransport is an http.RoundTripper that adds the agent's MCP token to each request for one MCP server:
- the token comes from Agent.Mcp (a token exchange for the resource, RFC 8707), is kept, and is renewed before it expires;
- a DPoP-bound token (AgentConfig.DPoP) goes with the DPoP scheme and a new proof for each request, and a 401 use_dpop_nonce answer is sent again once with the server's nonce;
- a 401 whose WWW-Authenticate names resource_metadata makes the transport read that document once: it learns the resource (when Resource is empty), checks that the resource is on the server's own origin and that the server trusts the agent's organization, and sends the request again once with a new token.
A request whose body cannot be read again (no GetBody) is not sent again; its 401 is returned. The transport never logs a token. It is safe for concurrent use.
func NewMCPTransport ¶ added in v1.8.0
func NewMCPTransport(agent *Agent, opts MCPTransportOptions) (*MCPTransport, error)
NewMCPTransport builds the transport for one MCP server. The agent's credentials authenticate the token requests; the agent's DPoP signer (AgentConfig.DPoP), when set, binds the MCP tokens.
func (*MCPTransport) Client ¶ added in v1.8.0
func (t *MCPTransport) Client() *http.Client
Client returns an *http.Client that sends through this transport, for StreamableClientTransport.HTTPClient.
func (*MCPTransport) Resource ¶ added in v1.8.0
func (t *MCPTransport) Resource() string
Resource returns the resource URI that the transport gets tokens for: the configured one, the one learned from the server, or "".
type MCPTransportOptions ¶ added in v1.8.0
type MCPTransportOptions struct {
// Resource is the resource URI that the MCP server is registered with in
// LumoAuth, e.g. "https://mcp.example.com/mcp". The agent gets tokens for
// it, and the transport adds them only to requests for that origin and
// path (or a path below it). Empty means: learn it from the server's
// first 401 answer, through the protected resource metadata that its
// WWW-Authenticate header names (RFC 9728).
Resource string
// Base sends the requests. Defaults to http.DefaultTransport.
Base http.RoundTripper
// RenewBefore renews a token this long before it expires. Default 60s.
RenewBefore time.Duration
}
MCPTransportOptions configures NewMCPTransport.
type McpResource ¶
type McpResource struct {
// contains filtered or unexported fields
}
McpResource covers secured MCP servers. Token exchanges the caller's token for one bound to a single MCP server (RFC 8693 token exchange). AuthorizeTool lets an MCP server ask whether a caller may run one tool.
func (*McpResource) AuthorizeTool ¶ added in v1.2.0
func (r *McpResource) AuthorizeTool(ctx context.Context, params McpToolAuthorizeParams) (*McpToolDecision, error)
AuthorizeTool asks whether a user or an agent may run one tool on an MCP server. The MCP server calls it after it has verified the caller's token.
The client must authenticate with the MCP server's own client-credentials token, which needs the mcp:authorize scope. The server's OAuth client must also be one of the MCP server's tool authorizers. Never pass the caller's token here: the MCP specification forbids token passthrough.
NewAgent runs the client-credentials grant and keeps the token fresh, so it works for the MCP server's own client too:
mcpAuth, err := lumoauth.NewAgent(lumoauth.AgentConfig{
OrgID: "acme-corp", ClientID: mcpClientID, ClientSecret: mcpClientSecret,
Scopes: []string{"mcp:authorize"},
})
// handle err
decision, err := mcpAuth.Mcp.AuthorizeTool(ctx, lumoauth.McpToolAuthorizeParams{
ServerID: "mcp_0123456789abcdef01234567",
SubjectType: "user",
SubjectID: verifiedSub, // the `sub` claim of the verified MCP token
Tool: "send_invoice",
})
A deny is not an error. It comes back with Allowed set to false and a nil error. A 403 without an `allowed` key, such as insufficient_scope, is an error that matches ErrPermissionDenied.
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 Resource URI that the MCP server is registered with in LumoAuth. It is an https URL, and the SDK sends it as the RFC 8707 `resource` parameter. The token names exactly one MCP server, and LumoAuth sets the token's `aud` from this value. A plain-http URL is accepted only for localhost and private hosts. Pass an empty subjectToken to exchange the client's own bearer token.
The token works only at that MCP server. LumoAuth's own API refuses it. With a DPoP signer configured (WithDPoP, or AgentConfig.DPoP), the exchange carries a DPoP proof and the token comes back bound to the key (token_type "DPoP") — which is what an MCP server registered with "Require DPoP" expects. Present it with DPoPSigner.AuthorizeRequest. Without a signer the exchange sends no proof and the token is a plain 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 McpToolAuthorizeParams ¶ added in v1.2.0
type McpToolAuthorizeParams struct {
// ServerID is the registered MCP server ID, for example
// "mcp_0123456789abcdef01234567". It is not the Resource URI. Required.
ServerID string
// SubjectType is "user" or "agent". Required.
SubjectType string
// SubjectID is the `sub` claim of the verified MCP token. For a user it
// is the user ID. For an agent it may be the agent ID ("agt_…") or the
// `sub` claim as is ("agent_agt_…"). Required.
SubjectID string
// Tool is the name of the MCP tool. Required.
Tool string
}
McpToolAuthorizeParams describes one per-tool question that an MCP server asks about a caller it has already verified.
type McpToolDecision ¶ added in v1.2.0
type McpToolDecision struct {
Allowed bool `json:"allowed"`
Subject McpToolSubject `json:"subject"`
Resource McpToolResource `json:"resource"`
}
McpToolDecision is the answer to McpResource.AuthorizeTool. A deny comes back with Allowed set to false and a nil error.
type McpToolResource ¶ added in v1.2.0
McpToolResource names the tool that a decision covers. Type is "mcp_tool" and ID is "<serverId>/<tool>".
type McpToolSubject ¶ added in v1.2.0
McpToolSubject names the caller of an MCP tool: a user or an agent.
type MemoryReplayCache ¶ added in v1.2.0
type MemoryReplayCache struct {
// contains filtered or unexported fields
}
MemoryReplayCache is an in-process ReplayCache. The zero value is ready to use.
func NewMemoryReplayCache ¶ added in v1.2.0
func NewMemoryReplayCache() *MemoryReplayCache
NewMemoryReplayCache returns an empty in-process replay cache.
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 WithClientCredentials ¶ added in v1.7.0
WithClientCredentials sets the client ID and the client secret of a confidential application of the organization. Only client.Poppy uses them: its calls authenticate with HTTP Basic, and they never send the client's bearer token or API key. The application's allowed scopes must include poppy:verify.
A client with these credentials and no other credential can call client.Poppy only.
func WithCustomDomain ¶ added in v1.7.0
WithCustomDomain addresses the organization on its own domain, for example "auth.acme.com" or "https://auth.acme.com". Defaults to $LUMOAUTH_CUSTOM_DOMAIN.
With a custom domain the client sends every request to that domain, and no path carries the /orgs/{orgId} segment. The organization ID is not needed, and the issuer is the bare domain. A custom domain wins over WithBaseURL and $LUMOAUTH_URL: the base URL is then not used at all.
The value is a host name or an https:// origin. http:// is accepted only for localhost, 127.0.0.1 and [::1]. New returns a *ConfigError for a value with a path, a query, a fragment or credentials. An empty value means "not set".
Example ¶
An organization on its own domain: no organization ID, and no path with an /orgs/ segment.
package main
import (
"fmt"
"log"
lumoauth "github.com/lumoauth/lumo-auth-go"
)
func main() {
client, err := lumoauth.New(
lumoauth.WithCustomDomain("auth.acme.com"),
lumoauth.WithAPIKey("lmk_example"),
)
if err != nil {
log.Fatal(err)
}
issuer, _ := client.Issuer()
adminUsers, _ := client.OrgPath("/admin/users")
fmt.Println(issuer)
fmt.Println(client.BaseURL() + adminUsers)
}
Output: https://auth.acme.com https://auth.acme.com/api/v1/admin/users
func WithDPoP ¶ added in v1.2.0
func WithDPoP(signer *DPoPSigner) Option
WithDPoP binds the client's token requests to a DPoP key (RFC 9449). Every token the client obtains through client.Auth — client credentials, token exchange, MCP tokens — is then sender-constrained (token_type "DPoP"), and the client presents bound tokens with the DPoP scheme and a fresh proof. See DPoPSigner.
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) on the platform host. Defaults to $LUMOAUTH_ORG_ID. A client with a custom domain does not need it.
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.
func WithoutCredential ¶ added in v1.8.0
func WithoutCredential() Option
WithoutCredential lets New build a client that holds no credential. Such a client builds addresses (Auth.AuthorizationURL, Auth.EndSessionURL, Issuer, OrgPath) and makes the calls that authenticate themselves: the token endpoint calls of client.Auth (code exchange, refresh, client credentials with a secret or an assertion, token exchange with client authentication), Auth.Revoke, Auth.UserInfo with a token, and Agents.Attest. A call that needs a credential is sent without one, and the server's 401 is an error that matches ErrAuthentication.
A credential given with another option or LUMOAUTH_API_KEY is still used. Without this option, New refuses to build a client with no credential, so that a missing API key is found at start-up.
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 PollOptions ¶ added in v1.8.0
type PollOptions struct {
// ClientAuth authenticates the application at the token endpoint, as
// when it started the request. A public client (device flow only) sets
// ClientID alone. Use AssertionSigner rather than ClientAssertion: each
// poll needs a new assertion.
ClientAuth ClientAuth
// Interval is the wait before each poll. Defaults to
// DefaultPollInterval. Each slow_down answer adds 5 seconds.
Interval time.Duration
// ExpiresIn bounds the polling: after it, the poll ends with an error
// that matches ErrApprovalTimeout. Use the expires_in of the start
// answer. 0 means until the server answers expired_token or ctx ends.
ExpiresIn time.Duration
}
PollOptions configures PollDeviceToken and PollBackchannelToken.
type PoppyAccount ¶ added in v1.7.0
type PoppyAccount struct {
// Subject is the id of the user in your LumoAuth organization. Use it
// to find the account's data.
Subject string `json:"sub"`
// Scope is the space-separated scope string of the access token; see
// Scopes and HasScope.
Scope string `json:"scope"`
// Audience lists the services that the access token is for.
Audience []string `json:"aud"`
// Expires is the expiry of the access token in Unix seconds, or 0 when
// LumoAuth sent none.
Expires int64 `json:"exp"`
// TokenType is "DPoP" for a token bound to a DPoP key, "Bearer"
// otherwise.
TokenType string `json:"token_type,omitempty"`
}
PoppyAccount describes the access token of a signed-in request.
func (*PoppyAccount) HasScope ¶ added in v1.7.0
func (a *PoppyAccount) HasScope(scope string) bool
HasScope reports whether the access token carries the scope.
func (*PoppyAccount) Scopes ¶ added in v1.7.0
func (a *PoppyAccount) Scopes() []string
Scopes returns the access token's scopes as a slice.
type PoppyMiddlewareOptions ¶ added in v1.7.0
type PoppyMiddlewareOptions struct {
// PublicOrigin is the address that personal agents call, for example
// "https://shop.example.com". It may carry a base path. Take it from
// your configuration. Required.
PublicOrigin string
// RequiredScope lists the scopes that the routes behind this
// middleware need. Leave it empty for routes that work signed out.
RequiredScope []string
// Resource is the resource identifier of your service, when it takes
// only access tokens that were issued for it.
Resource string
// AllowReplay accepts a Session JWT that was verified before.
AllowReplay bool
// OnError is called when the verification call itself fails: the SDK
// could not reach LumoAuth, or LumoAuth refused your application's call
// (for example 404 not_found while the organization has the protocol
// switched off: errors.Is(err, ErrNotFound)). It must answer the
// request. Never write err to the response: it is about your service,
// not about the personal agent. When OnError is nil, the middleware
// answers 503 with the fixed body {"error":"temporarily_unavailable",…}.
// The SDK does not log, so set OnError to record the error.
OnError func(w http.ResponseWriter, r *http.Request, err error)
}
PoppyMiddlewareOptions configures PoppyResource.Middleware.
type PoppyRelayResponse ¶ added in v1.7.0
type PoppyRelayResponse struct {
Status int `json:"status"`
Headers map[string]string `json:"headers"`
// Body is the JSON object to send, or nil when the response has no
// body. Access token errors travel in WWW-Authenticate and have none.
Body map[string]any `json:"body"`
}
PoppyRelayResponse is the HTTP response that a refused personal agent must get: the status, the headers and the body, exactly as LumoAuth worded them.
type PoppyRequest ¶ added in v1.7.0
type PoppyRequest struct {
// Method is the method of the request. Required.
Method string
// URL is the public address that the personal agent called, for example
// "https://shop.example.com/api/orders". Build it from your configured
// public origin and the request path, never from the Host header. The
// query and the fragment are dropped. Required.
URL string
// Headers are the headers of the request. You can pass all of them:
// only Poppy-Session, Poppy-Version, Poppy-Extensions, Authorization
// and DPoP are sent.
Headers http.Header
}
PoppyRequest is a request that a personal agent sent to your API.
type PoppyResource ¶ added in v1.7.0
type PoppyResource struct {
// contains filtered or unexported fields
}
PoppyResource verifies requests from personal agents, and looks up and ends their Sessions.
Its three calls authenticate as one of your organization's confidential applications, with HTTP Basic: the client ID and the client secret of WithClientCredentials. The application's allowed scopes must include poppy:verify. The calls never send the client's bearer token or API key.
client, err := lumoauth.New(
lumoauth.WithOrgID("acme-corp"),
lumoauth.WithClientCredentials(clientID, clientSecret),
)
On a net/http server, Middleware does the whole job for a route.
func (*PoppyResource) EndSession ¶ added in v1.7.0
EndSession ends a Session. Later requests with its sid are refused with session_ended, and the personal agent starts a new Session. The user stays signed in.
It returns false when the Session had ended before. An unknown Session is an error that matches ErrNotFound.
func (*PoppyResource) GetSessionStatus ¶ added in v1.7.0
func (r *PoppyResource) GetSessionStatus(ctx context.Context, personalAgent, sid string) (*PoppySessionStatus, error)
GetSessionStatus says whether a Session still stands and whether its account is still signed in to the personal agent. It needs no request from the personal agent. personalAgent is the ClientID of a verified result, and sid is its Session.SID.
An unknown Session is not an error: Status is PoppyStatusUnknown.
func (*PoppyResource) Middleware ¶ added in v1.7.0
func (r *PoppyResource) Middleware(opts PoppyMiddlewareOptions) (func(http.Handler) http.Handler, error)
Middleware returns net/http middleware that verifies each request with LumoAuth before the handler runs.
verified, err := client.Poppy.Middleware(lumoauth.PoppyMiddlewareOptions{
PublicOrigin: "https://shop.example.com",
RequiredScope: []string{"orders:read"},
})
if err != nil {
log.Fatal(err)
}
mux.Handle("GET /api/orders", verified(ordersHandler))
// in ordersHandler:
who, _ := lumoauth.PoppyFromContext(r.Context())
For each request the middleware does one of three things:
- Verified: it stores the *PoppyVerification in the request context and calls the handler.
- Refused: it answers with LumoAuth's response, unchanged, and does not call the handler.
- The call failed: it does not call the handler and relays nothing. It calls OnError, or answers 503 Service Unavailable with a fixed body. The error text never reaches the personal agent.
The URL that LumoAuth checks is PublicOrigin followed by the path of r.RequestURI. The Host and X-Forwarded-* headers are never used. Because r.RequestURI is the request line as the client sent it, a router prefix or http.StripPrefix in front of the middleware does not shorten the path. The middleware does not read the request body.
A Session JWT is good for one verification, so put the middleware on a route once.
Middleware returns a *ConfigError when PublicOrigin is missing or is not a valid address, when the client has no client credentials (WithClientCredentials) or when it has neither an organization ID nor a custom domain.
Example ¶
An API that personal agents call: the middleware asks LumoAuth to verify each request before the handler runs.
package main
import (
"fmt"
"log"
"net/http"
"os"
lumoauth "github.com/lumoauth/lumo-auth-go"
)
func main() {
client, err := lumoauth.New(
lumoauth.WithOrgID("acme-corp"),
// A confidential application whose allowed scopes include poppy:verify.
lumoauth.WithClientCredentials(os.Getenv("SHOP_API_CLIENT_ID"), os.Getenv("SHOP_API_CLIENT_SECRET")),
)
if err != nil {
log.Fatal(err)
}
verified, err := client.Poppy.Middleware(lumoauth.PoppyMiddlewareOptions{
PublicOrigin: os.Getenv("PUBLIC_ORIGIN"), // for example https://shop.example.com
RequiredScope: []string{"orders:read"},
OnError: func(w http.ResponseWriter, r *http.Request, err error) {
// The error is about this service. Log it, and never send it.
log.Printf("Session verification failed: %v", err)
http.Error(w, "not available now", http.StatusServiceUnavailable)
},
})
if err != nil {
log.Fatal(err)
}
orders := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
who, _ := lumoauth.PoppyFromContext(r.Context())
fmt.Fprintf(w, "orders of account %s, asked by %s", who.Account.Subject, who.ClientID)
})
mux := http.NewServeMux()
mux.Handle("GET /api/orders", verified(orders))
log.Fatal(http.ListenAndServe(":8787", mux))
}
Output:
func (*PoppyResource) VerifyHTTPRequest ¶ added in v1.7.0
func (r *PoppyResource) VerifyHTTPRequest(ctx context.Context, publicOrigin string, req *http.Request, opts *PoppyVerifyOptions) (*PoppyVerification, error)
VerifyHTTPRequest is VerifyRequest for a *http.Request. It builds the URL from publicOrigin and the request target as the client sent it (see BuildPoppyVerifyBody), and it does not read the request body.
verification, err := client.Poppy.VerifyHTTPRequest(ctx, "https://shop.example.com", r, nil)
Take publicOrigin from your configuration.
Example ¶
Without the middleware: verify a request in a handler and relay a refusal.
package main
import (
"fmt"
"log"
"net/http"
"os"
lumoauth "github.com/lumoauth/lumo-auth-go"
)
func main() {
client, err := lumoauth.New(
lumoauth.WithOrgID("acme-corp"),
lumoauth.WithClientCredentials(os.Getenv("SHOP_API_CLIENT_ID"), os.Getenv("SHOP_API_CLIENT_SECRET")),
)
if err != nil {
log.Fatal(err)
}
publicOrigin := os.Getenv("PUBLIC_ORIGIN")
http.HandleFunc("POST /api/orders/{id}/return", func(w http.ResponseWriter, r *http.Request) {
verification, err := client.Poppy.VerifyHTTPRequest(r.Context(), publicOrigin, r,
&lumoauth.PoppyVerifyOptions{RequiredScope: []string{"orders:write"}})
if err != nil {
log.Printf("Session verification failed: %v", err)
http.Error(w, "not available now", http.StatusServiceUnavailable)
return
}
if !verification.Active {
_ = lumoauth.WritePoppyRefusal(w, verification)
return
}
fmt.Fprintf(w, "order %s returned for account %s", r.PathValue("id"), verification.Account.Subject)
})
}
Output:
func (*PoppyResource) VerifyRequest ¶ added in v1.7.0
func (r *PoppyResource) VerifyRequest(ctx context.Context, request PoppyRequest, opts *PoppyVerifyOptions) (*PoppyVerification, error)
VerifyRequest asks LumoAuth who a request from a personal agent is from.
verification, err := client.Poppy.VerifyRequest(ctx, lumoauth.PoppyRequest{
Method: r.Method,
URL: "https://shop.example.com" + r.URL.EscapedPath(),
Headers: r.Header,
}, &lumoauth.PoppyVerifyOptions{RequiredScope: []string{"orders:read"}})
if err != nil {
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
if !verification.Active {
lumoauth.WritePoppyRefusal(w, verification)
return
}
A refusal is not an error. It comes back with Active set to false and the response to send in Response. An error means that the call itself failed: the SDK could not reach LumoAuth, or LumoAuth rejected your application (401, 403, 404 or 429). Never send such an error to the personal agent. An answer that is neither a verified result nor a well-formed refusal is an error too.
opts may be nil.
type PoppySession ¶ added in v1.7.0
type PoppySession struct {
// ID is LumoAuth's id of the Session. Store your own Session state
// under it, such as a cart.
ID int64 `json:"id"`
// SID is the Session ID that the personal agent chose. GetSessionStatus
// and EndSession take it.
SID string `json:"sid"`
// IsNew is true when this request started the Session.
IsNew bool `json:"new"`
// StartedAt is the start of the Session, as an RFC 3339 time.
StartedAt string `json:"started_at,omitempty"`
}
PoppySession is the Session of a verified request.
type PoppySessionStatus ¶ added in v1.7.0
type PoppySessionStatus struct {
// Status is PoppyStatusActive, PoppyStatusEnded or PoppyStatusUnknown.
Status string `json:"status"`
// UserID is the personal agent's name for its user. Empty for an
// unknown Session.
UserID string `json:"user_id,omitempty"`
// AgentID is set when the personal agent named one of several agents.
AgentID string `json:"agent_id,omitempty"`
// Account is the id of the account that the Session used, or "".
Account string `json:"account,omitempty"`
// SignedIn is true while the Session is active, it used an account,
// and the personal agent still holds a valid refresh token for it.
SignedIn bool `json:"signed_in"`
// LastSeenAt is the time of the Session's last request, as an RFC 3339
// time. Empty for an unknown Session.
LastSeenAt string `json:"last_seen_at,omitempty"`
// Raw is the complete decoded answer.
Raw map[string]any `json:"-"`
}
PoppySessionStatus is the answer to PoppyResource.GetSessionStatus.
func (*PoppySessionStatus) Active ¶ added in v1.7.0
func (s *PoppySessionStatus) Active() bool
Active reports whether the Session still stands.
func (*PoppySessionStatus) UnmarshalJSON ¶ added in v1.7.0
func (s *PoppySessionStatus) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes a Session status and refuses an answer without a status or with a member of the wrong type.
type PoppyVerification ¶ added in v1.7.0
type PoppyVerification struct {
// Active is true when LumoAuth verified the request.
Active bool `json:"active"`
// ClientID is the personal agent: the URL of its metadata document.
// LumoAuth checked this value.
ClientID string `json:"client_id,omitempty"`
// ClientName is the name that the personal agent gives itself.
ClientName string `json:"client_name,omitempty"`
// UserID is the personal agent's stable name for its user at your
// organization. It is not an account: never look an account up by it.
UserID string `json:"user_id,omitempty"`
// AgentID is set when the personal agent runs several agents for one
// user and says which one this is. Empty otherwise.
AgentID string `json:"agent_id,omitempty"`
// Session is the Session of the request. Nil in a refusal.
Session *PoppySession `json:"session,omitempty"`
// SignedIn is true when the request carried a valid access token.
SignedIn bool `json:"signed_in"`
// Account says whose access token the request carried. Nil when the
// request is signed out.
Account *PoppyAccount `json:"account,omitempty"`
// Version is the Poppy-Version of the request.
Version string `json:"version,omitempty"`
// Extensions are the extensions that the request declares, as name and
// version.
Extensions map[string]string `json:"extensions,omitempty"`
// Error is the protocol's error code of a refusal, such as
// "invalid_session" or "insufficient_scope".
Error string `json:"error,omitempty"`
// ErrorDescription explains a refusal.
ErrorDescription string `json:"error_description,omitempty"`
// Scope holds the scopes that a refusal asks for, space-separated.
// Empty when the refusal names none.
Scope string `json:"scope,omitempty"`
// Response is the HTTP response that the personal agent must get. Nil
// in a verified result.
Response *PoppyRelayResponse `json:"response,omitempty"`
// Raw is the complete decoded answer.
Raw map[string]any `json:"-"`
}
PoppyVerification is the answer to PoppyResource.VerifyRequest: who a request from a personal agent is from, or the refusal to send back.
Active tells the two apart. A verified result (Active true) carries ClientID, UserID, Session and, for a signed-in request, Account. A refusal (Active false) carries Error and Response; send Response to the personal agent unchanged with WritePoppyRefusal.
func PoppyFromContext ¶ added in v1.7.0
func PoppyFromContext(ctx context.Context) (*PoppyVerification, bool)
PoppyFromContext returns the verified result that PoppyResource.Middleware stored for the request.
func (*PoppyVerification) UnmarshalJSON ¶ added in v1.7.0
func (v *PoppyVerification) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes a verification answer and fails closed: an answer that is neither a complete verified result nor a well-formed refusal is an error, and is never decoded as verified.
type PoppyVerifyOptions ¶ added in v1.7.0
type PoppyVerifyOptions struct {
// RequiredScope lists the scopes that the operation needs. An entry may
// also hold several scopes separated by spaces. Leave it empty for an
// operation that works signed out.
RequiredScope []string
// Resource is the resource identifier of your service. Set it when the
// service takes only access tokens that were issued for it, as an MCP
// server does.
Resource string
// AllowReplay accepts a Session JWT that was verified before. Use it
// only when one request is verified in several places.
AllowReplay bool
}
PoppyVerifyOptions are the checks that one operation asks for.
type PushedAuthorizationResponse ¶ added in v1.8.0
type PushedAuthorizationResponse struct {
// RequestURI goes into the authorization URL (AuthorizationURL with
// ClientID and RequestURI). It works once.
RequestURI string `json:"request_uri"`
// ExpiresIn is its lifetime in seconds.
ExpiresIn int `json:"expires_in"`
}
PushedAuthorizationResponse is the answer of the PAR endpoint.
type RecordedUsage ¶ added in v1.4.0
RecordedUsage is the usage that LumoAuth added to the agent's budget windows.
type RefreshParams ¶
type RefreshParams struct {
// RefreshToken is the token from a prior response. Required.
RefreshToken string
// ResourceToken must be a resource token from the resource that the
// refresh token was granted for — the server requires one on every
// refresh. Its `scope` claim may narrow the granted scopes. Required.
ResourceToken string
// Scope is an optional space-delimited scope. It narrows only: every
// scope must be in the original grant (and in the resource token's
// scope, when it has one). A scope outside the grant is refused with
// 400 invalid_scope.
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
// ClientAuth, when set, authenticates the client instead of ClientID and
// ClientSecret (leave those empty); see ExchangeCodeParams.ClientAuth.
ClientAuth *ClientAuth
// AuthorizationDetails asks for a part of the granted fine-grained
// permissions; see ExchangeCodeParams.AuthorizationDetails.
AuthorizationDetails []map[string]any
}
RefreshTokenParams describes a refresh-token grant.
type RegisterClientOptions ¶ added in v1.8.0
type RegisterClientOptions struct {
// InitialAccessToken is the token that your organization issued for
// registrations. It is sent as the only credential. Without it, the
// client's API key is sent when it has one (the key needs the scope
// admin:clients:register), and nothing otherwise, for an organization
// that allows open registration.
InitialAccessToken string
}
RegisterClientOptions configures RegisterClient.
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, written
// <resource>:<action> (e.g. "documents:read", "web:search").
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 RegisteredClient ¶ added in v1.8.0
type RegisteredClient struct {
ClientMetadata
ClientID string `json:"client_id"`
// ClientSecret is set for a confidential client at registration only.
// Store it at once: it is not shown again.
ClientSecret string `json:"client_secret,omitempty"`
ClientSecretExpiresAt int64 `json:"client_secret_expires_at,omitempty"`
ClientIDIssuedAt int64 `json:"client_id_issued_at,omitempty"`
// RegistrationAccessToken reads the configuration later
// (GetClientConfiguration). Set at registration only; keep it secret.
RegistrationAccessToken string `json:"registration_access_token,omitempty"`
RegistrationClientURI string `json:"registration_client_uri,omitempty"`
// Raw is the complete answer.
Raw map[string]any `json:"-"`
}
RegisteredClient is the answer of a registration or of a read of the client configuration.
func (*RegisteredClient) String ¶ added in v1.8.0
func (c *RegisteredClient) String() string
String never shows the client secret or the registration access token.
func (*RegisteredClient) UnmarshalJSON ¶ added in v1.8.0
func (c *RegisteredClient) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes the typed members and keeps every member in Raw.
type ReplayCache ¶ added in v1.2.0
ReplayCache remembers DPoP proof identifiers so a captured proof cannot be presented twice. Seen records jti and reports whether it was already present; entries may be forgotten after ttl. Implementations must be safe for concurrent use. A shared store (Redis, say) is the right choice for a resource server with several replicas.
type RequestObjectOptions ¶ added in v1.8.0
type RequestObjectOptions struct {
// Signer holds the application's private key; its algorithm (RS256–RS512,
// PS256–PS512 or ES256–ES512) and key ID become the object's alg and
// kid. Register the public key (Signer.JWKS) on the application.
// Required.
Signer *ClientAssertionSigner
// Lifetime is the time until exp: 1 second to 10 minutes. Default 5
// minutes.
Lifetime time.Duration
}
RequestObjectOptions configures CreateRequestObject.
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
// ClientAuth, when set, authenticates the client instead of ClientID and
// ClientSecret (leave those empty); see ExchangeCodeParams.ClientAuth.
ClientAuth *ClientAuth
}
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"`
// AuthorizationDetails are the fine-grained permissions (RFC 9396) that
// LumoAuth granted at sign-in (WebConfig.AuthorizationDetails).
AuthorizationDetails []map[string]any `json:"authorization_details,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. It is
// also sent as that header. Its label must be "sig1", the label of
// Signature-Input and Signature. POST /aauth/agent/issue requires
// `sig1=jwks_uri;id="<agent identifier>";kid="<kid>"`; the agent token
// endpoint and /aauth/token/revoke need no Signature-Key.
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 TokenConfirmation ¶ added in v1.2.0
type TokenConfirmation struct {
// JKT is the RFC 7638 thumbprint of the DPoP key the token is bound to.
JKT string `json:"jkt,omitempty"`
}
TokenConfirmation is the `cnf` claim.
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
// ClientID, with ClientSecret or ClientAssertion, authenticates your
// application at the token endpoint: the exchange of a confidential
// application (token exchange switched on for it). Leave all three empty
// for the agent on-behalf-of exchange, where the actor token
// authenticates the agent.
ClientID string
// ClientSecret is the application's secret.
ClientSecret string
// ClientAuthMethod is how ClientSecret is sent: ClientSecretBasic (the
// default, an Authorization header) or ClientSecretPost (form fields).
ClientAuthMethod string
// ClientAssertion is a private_key_jwt client assertion (RFC 7523),
// built with ClientAssertionSigner.Assertion, instead of a secret.
ClientAssertion string
}
TokenExchangeParams describes an RFC 8693 token exchange.
type TokenIntrospection ¶ added in v1.8.0
type TokenIntrospection struct {
Active bool `json:"active"`
// TokenType is "Bearer" (or "DPoP") for access tokens, "refresh_token"
// for refresh tokens.
TokenType string `json:"token_type,omitempty"`
// Scope is the space-separated scope string; see Scopes.
Scope string `json:"scope,omitempty"`
ClientID string `json:"client_id,omitempty"`
// Subject is the user ID, or client_… / agent_… for other subjects.
Subject string `json:"sub,omitempty"`
// Username is the user's e-mail address (tokens of a user only).
Username string `json:"username,omitempty"`
Expires int64 `json:"exp,omitempty"`
IssuedAt int64 `json:"iat,omitempty"`
NotBefore int64 `json:"nbf,omitempty"`
Issuer string `json:"iss,omitempty"`
Audience AudienceClaim `json:"aud,omitempty"`
JTI string `json:"jti,omitempty"`
// Act is the actor of a delegated token, earlier actors nested in it.
Act *ActorClaim `json:"act,omitempty"`
// Confirmation is the key binding of a DPoP-bound token (cnf.jkt).
Confirmation *TokenConfirmation `json:"cnf,omitempty"`
// AuthorizationDetails are the token's fine-grained permissions
// (RFC 9396), when it has some.
AuthorizationDetails []map[string]any `json:"authorization_details,omitempty"`
// Raw is the complete answer, including members not modelled above.
Raw map[string]any `json:"-"`
}
TokenIntrospection is the introspection answer (RFC 7662 §2.2). An inactive, expired, revoked or unknown token is only Active false. For an active token the other members are set when LumoAuth knows them.
func (*TokenIntrospection) Scopes ¶ added in v1.8.0
func (t *TokenIntrospection) Scopes() []string
Scopes splits the scope string.
func (*TokenIntrospection) UnmarshalJSON ¶ added in v1.8.0
func (t *TokenIntrospection) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes the typed members and keeps every member in Raw.
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"`
// AuthorizationDetails are the fine-grained permissions (RFC 9396) that
// LumoAuth granted, when the request asked for some. Members that the
// SDK does not model are kept.
AuthorizationDetails []map[string]any `json:"authorization_details,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.
A source that addresses its organization on a custom domain also has the method CustomDomain() string, as *Agent does. JITContext then sends its requests to that domain without the /orgs/{orgId} segment. Without that method the paths are in the platform form, which a custom domain answers with 404.
type UsageReportResult ¶ added in v1.4.0
type UsageReportResult struct {
Recorded RecordedUsage `json:"recorded"`
Budget *AgentBudget `json:"budget,omitempty"`
}
UsageReportResult is the answer to AgentsResource.ReportUsage: what was recorded, and the agent's budget after it (the same shape as BudgetPolicy in UserInfo; Budget.Exhausted() means that the next metered call gets 429).
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
// Reason is a stable, machine-readable cause set by the token
// verifiers (one of the TokenRejected* constants); "" elsewhere. Read
// it with RejectionReason.
Reason string
}
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 unless
// CustomDomain is set.
Issuer string
// CustomDomain is the organization's custom domain, for example
// "auth.acme.com". When it is set, the key set is fetched from
// {domain}/api/v1/aauth/jwks.json. The value follows the rules of
// WithCustomDomain. The environment is not read.
//
// The trusted issuer is NOT the bare domain: LumoAuth names the AAuth
// issuer with the platform address on every host. With CustomDomain
// and an empty Issuer, VerifyAuthToken reads the issuer from the
// issuer metadata document of the custom domain
// ({domain}/api/v1/.well-known/aauth-issuer) and keeps it for an hour.
// A non-empty Issuer is used as it is, and no document is read.
CustomDomain 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. Its Poppy namespace authenticates with the ClientID and ClientSecret of this WebConfig.
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 ends the session: it revokes the refresh token, clears the local session and, unless LocalLogout is set, sends the browser to LumoAuth's end-session endpoint, which returns it to PostLogoutRedirect.
Another site cannot sign the user out: a GET signs out at once only when the browser's Sec-Fetch-Site is same-origin or none (a link of this app, a typed address); otherwise it answers with a page that asks first and posts to the same route. A POST signs out when its Origin is this app's origin (or one of LogoutAllowedOrigins), or, without an Origin, when Sec-Fetch-Site is same-origin; anything else gets 403.
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 slug of the organization that owns the OAuth
// client. Defaults to $LUMOAUTH_ORG_ID. Required unless CustomDomain is
// set.
Organization string
// CustomDomain addresses the organization on its own domain, for
// example "auth.acme.com". Defaults to $LUMOAUTH_CUSTOM_DOMAIN. It wins
// over BaseURL: the sign-in, token and UserInfo addresses are then on
// that domain, without the /orgs/{orgId} segment. See WithCustomDomain.
CustomDomain 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 is the secret from which the default store derives the
// keys that encrypt and sign the session cookie. Use at least 32 random
// bytes, and keep it stable across restarts or every session is
// invalidated. Required unless Store is set.
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
// AuthorizationDetails asks for fine-grained permissions (RFC 9396) at
// each sign-in; see AuthorizationURLParams.AuthorizationDetails. What
// LumoAuth granted is in SessionTokens.AuthorizationDetails.
AuthorizationDetails []map[string]any
// PostLoginRedirect is where users land after signing in.
// Defaults to "/".
PostLoginRedirect string
// PostLogoutRedirect is where users land after signing out. Defaults to
// "/". The logout route also ends the LumoAuth session, so LumoAuth
// sends the browser here: a path is made absolute with the request's
// origin, and the absolute address must be registered on the client as
// a post-logout redirect URI.
PostLogoutRedirect string
// LogoutAllowedOrigins lists other origins (for example
// "https://portal.example.com") whose POST to the logout route signs the
// user out too. Empty (the default) means this app's own origin only. A
// GET from another site always gets the confirmation page first.
LogoutAllowedOrigins []string
// LocalLogout makes the logout route end only this app's session: the
// user stays signed in at LumoAuth, and the next sign-in needs no
// password. False (the default) also ends the LumoAuth session through
// the end-session endpoint (RP-initiated logout).
LocalLogout bool
// 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
// ClientAuth authenticates the app with a key instead of ClientSecret
// (leave ClientSecret empty): AssertionSigner for private_key_jwt, which
// signs a new client assertion for each request, or Attestation. The
// pushed request, the code exchange, the refresh and the revocation at
// logout use it. ClientAuth.ClientID may stay empty (it is ClientID).
// ClientAssertion is refused: one assertion works once.
ClientAuth *ClientAuth
// RequestObjectSigner signs each sign-in request as a request object
// (JAR, RFC 9101): with UsePAR it is pushed, otherwise it goes in the
// redirect as the request parameter. Register its public key on the
// application; it may be the key of ClientAuth.AssertionSigner. FAPI 2
// Message Signing needs it.
RequestObjectSigner *ClientAssertionSigner
// DPoP binds the user's tokens to this key (RFC 9449): the pushed
// request, the code exchange and the refresh carry a proof, and the
// tokens are presented with the DPoP scheme (UserInfo, ClientForRequest).
// Every instance of the app must load the same key (LoadDPoPSigner), or
// a session's tokens stop working after a restart.
DPoP *DPoPSigner
// UsePAR pushes each sign-in request to LumoAuth first (pushed
// authorization requests, RFC 9126) and sends the browser to LumoAuth
// with only client_id and request_uri. The parameters then never pass
// through the browser. Applications with "Require PAR" or a FAPI
// profile need it. False (the default) puts the parameters in the
// redirect.
UsePAR bool
// ResponseMode asks LumoAuth to sign its answer (JARM): "jwt" or
// "query.jwt". The callback then reads the `response` parameter,
// verifies its signature, issuer, audience and expiry, and refuses an
// unsigned answer. "" (the default) is the plain query answer.
// form_post.jwt and fragment.jwt are refused: the session cookie
// (SameSite=Lax) does not come with a cross-site POST, and a fragment
// never reaches the server.
ResponseMode string
// Store replaces the session store, for example with a server-side
// store (gorilla's FilesystemStore, a Redis store) that keeps only an
// ID in the cookie. The session is named CookieName. With a Store,
// SessionSecret, CookieSecure and SessionMaxAge are not used: the store
// has its own keys and cookie options. Nil means the default store: an
// encrypted, signed cookie that is split over several cookies when the
// session does not fit in one.
Store sessions.Store
}
WebConfig configures NewWebAuth.
type WorkloadIdentity ¶ added in v1.8.0
type WorkloadIdentity struct {
// Provider names the platform, for example "github" or "k8s".
Provider string `json:"provider"`
// Subject is the token's subject, for example
// "repo:acme/app:ref:refs/heads/main".
Subject string `json:"subject"`
// Issuer is the token's issuer.
Issuer string `json:"issuer"`
// AudienceGeneric is true when the agent's registered audience is not
// specific to LumoAuth (for example sts.amazonaws.com), so any token
// that the provider mints for it satisfies the agent. Move the binding
// to the agent-specific audience that the portal shows.
AudienceGeneric bool `json:"audience_generic"`
}
WorkloadIdentity is the verified identity of an attested workload.
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
- access_token_verify.go
- agent.go
- agent_vault.go
- attest.go
- authorization_details.go
- capability.go
- client.go
- client_assertion.go
- custom_domain.go
- delegation_chain.go
- doc.go
- dpop.go
- errors.go
- http.go
- jit_context.go
- jit_verify.go
- mcp_transport.go
- oauth_authorization.go
- oauth_client_auth.go
- oauth_introspection.go
- oauth_polling.go
- org_jwt.go
- poppy_http.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_poppy.go
- resource_zanzibar.go
- routes.go
- types.go
- util.go
- web_auth.go
- web_session_store.go