lumoauth

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Oct 7, 2026 License: MIT Imports: 32 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

lumo-auth-go

Go SDK for LumoAuth — authorization (RBAC / Zanzibar / ABAC), agent authentication and capability management, AAuth cryptographic identity, Just-in-Time (JIT) permissions, and browser sign-in.

Feature parity with the JS and Python SDKs: the same namespaces, the same error taxonomy, and byte-compatible RFC 9421 request signing.

Installation

go get github.com/lumoauth/lumo-auth-go
import lumoauth "github.com/lumoauth/lumo-auth-go"

Requires Go 1.22+. The only dependency is gorilla/sessions, used by the web sign-in flow; everything else is standard library.

Environment variables

Variable Description Default
LUMOAUTH_URL LumoAuth instance URL https://app.lumoauth.dev
LUMOAUTH_ORG_ID Organization slug (required for org-scoped calls)
LUMOAUTH_API_KEY API key for Client (sent as X-API-Key) —
AGENT_CLIENT_ID Agent OAuth client ID (required for agents)
AGENT_CLIENT_SECRET Agent OAuth client secret (required for agents)

Every one can also be passed directly to New, NewAgent, NewAAuthClient, or NewWebAuth.

Which entry point?

You are… Use
A backend service checking permissions lumoauth.New → Client
An AI agent acting under its own identity lumoauth.NewAgent → Agent
An agent with a signing key (AAuth) lumoauth.NewAAuthClient → AAuthClient
A resource server verifying AAuth tokens lumoauth.VerifyAuthToken
A web app signing users in lumoauth.NewWebAuth → WebAuth

Quick start — Client

The general-purpose client. Curated namespaces cover the common surface; everything else is reachable through Do or the generated OpenAPI client.

client, err := lumoauth.New(
    lumoauth.WithAPIKey(os.Getenv("LUMOAUTH_API_KEY")),
    lumoauth.WithOrgID("acme-corp"),
)
if err != nil {
    return err
}

// RBAC
allowed, err := client.Permissions.Check(ctx, "document.edit", nil)

// ReBAC (Zanzibar)
allowed, err = client.Zanzibar.IsViewer(ctx, "document:readme", "user:bob")

// ABAC
decision, err := client.Abac.Check(ctx, lumoauth.AbacCheckParams{
    ResourceType: "document",
    Action:       "read",
    ResourceID:   "doc-123",
})
Options
lumoauth.WithBaseURL(url)            // instance URL
lumoauth.WithOrgID(slug)             // organization
lumoauth.WithAPIKey(key)             // X-API-Key credential
lumoauth.WithAccessToken(token)      // fixed bearer token
lumoauth.WithTokenProvider(fn)       // bearer token resolved per request
lumoauth.WithTimeout(30*time.Second) // per-request timeout
lumoauth.WithHTTPClient(httpClient)  // custom transport / instrumentation
lumoauth.WithHeader(name, value)     // extra header on every request
lumoauth.WithUserAgent(ua)
lumoauth.WithSkipCertValidation()    // local development only

An API key and a bearer token are never sent together — the server rejects ambiguous credentials, so a token provider that returns a token wins.

Namespaces
Namespace Covers
client.Auth OAuth 2.1: authorization URLs, code exchange, refresh, client credentials, token exchange, revocation, UserInfo
client.Permissions RBAC: Check, CheckBulk, CheckAny, CheckAll, List
client.Zanzibar ReBAC: Check, plus IsViewer / IsEditor / IsOwner / IsMember / IsAdmin
client.Abac Policy evaluation, bulk checks, user and resource attributes
client.Agents Ask, Me, Register, Capabilities, Budget
client.Delegation RFC 8693 primitives (see also DelegationChain)
client.Jit Ephemeral tasks and scoped tokens (see also JITContext)
client.Approvals Push approvals: Create, Status, Wait, Require
client.Mcp Audience-scoped tokens for secured MCP servers

Quick start — Agent

An agent owns an OAuth client-credentials token and refreshes it transparently, so no call needs an explicit login first.

agent, err := lumoauth.NewAgent(lumoauth.AgentConfig{}) // reads env vars
if err != nil {
    return err
}

// Preflight check before an LLM tool call.
allowed, err := agent.IsAllowed(ctx, "document.read", map[string]any{"id": "doc_99"})

// Capability gate at the top of a tool.
if err := agent.RequireCapability(ctx, "tool:search_web"); err != nil {
    return err // matches lumoauth.ErrPermissionDenied
}

// Budget.
if err := agent.CheckBudget(ctx); err != nil {
    return err // matches lumoauth.ErrBudgetExceeded
}

Agent exposes Agents, Jit, Delegation, Approvals, Mcp, and Permissions directly; agent.Client() reaches the rest.

Concurrent callers share one in-flight token request, and the token is renewed 60s before it expires.

Human approval
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",
    Meta:       map[string]any{"amount": 4500, "vendor": "INV-7741"},
}, nil)

switch {
case errors.Is(err, lumoauth.ErrApprovalDenied):
    return fmt.Errorf("a human declined the transfer")
case errors.Is(err, lumoauth.ErrApprovalTimeout):
    return fmt.Errorf("nobody responded in time")
case err != nil:
    return err
}
// approval.Token authorises the side-effecting call.

Require returns an error for anything except approval. To handle a denial without an error, call Create and Wait yourself.

JIT permissions

A task scopes permissions to one unit of work; closing it revokes every token issued under it.

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",
}, &lumoauth.RequestPermissionOptions{Justification: "The user asked for a Q4 summary"})
if err != nil {
    return err
}
if result.Approved() {
    token, err := jit.Token(ctx, result.RequestID)
    // ... present the token to the resource
}

Low-risk requests come back approved. Higher-risk ones enter human-in-the-loop review, and RequestPermission polls until they resolve (set NoWait to poll yourself). A still-pending result means the wait timed out, not a denial.

CallWithEscalation closes the loop automatically: when a resource answers 403 with an Insufficient-Authorization-Details header, it requests exactly the permission that header names, gets a JIT token, and retries once.

resp, err := jit.CallWithEscalation(ctx, http.MethodGet, "https://api.example.com/reports/q4", nil, nil)
Delegation (Chain of Agency)
chain := lumoauth.NewDelegationChain(agent, "https://agent.example.com/callback")

// 1. Send the user to consent.
url, err := chain.ConsentURL("session-1", []string{"read:documents"}, "")

// 2. Your callback receives ?code=…
err = chain.HandleConsentCallback(ctx, "session-1", code)

// 3. Call as "agent acting for user" — the exchange happens on demand.
err = chain.Do(ctx, "session-1", http.MethodGet, "/orgs/acme-corp/api/v1/documents", nil, &out)

// Sub-agents extend the chain (max depth 3).
subToken, err := chain.DelegateToSubAgent(ctx, "session-1", subAgentToken, "read:documents")

// Revoking invalidates the refresh token and every token derived from it.
err = chain.Revoke(ctx, "session-1")

Delegated tokens carry an act claim recording the chain. lumoauth.ParseActorChain(token) reads it back for audit (without verifying the signature — never use it for an authorization decision).

MCP servers
token, err := agent.MCPToken(ctx, "urn:mcp:financial-data")

Quick start — web sign-in

The OAuth 2.1 Authorization Code + PKCE flow, with sessions in a signed cookie.

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"), // 32+ random bytes
})
if err != nil {
    return err
}

mux := http.NewServeMux()
mux.Handle("/auth/", auth.Router())               // /auth/login, /auth/callback, /auth/logout
mux.Handle("/", auth.Middleware(auth.RequireAuth(dashboard)))

// In a handler:
user := lumoauth.UserFromContext(req.Context())
fmt.Fprintf(w, "Hi %s", user.Email)

Router() returns a plain http.Handler, so it mounts into chi, gorilla/mux, or net/http alike.

  • Middleware attaches the user and their tokens to the request context; it does not enforce anything on its own.
  • RequireAuth answers 401 for anonymous requests.
  • RequireAuthRedirect("/auth/login") sends them to sign in instead, preserving where they were going.
  • ClientForRequest(req) returns a Client authenticated as the signed-in user, so authorization checks run under their identity.
  • RefreshSession(w, req) renews an expired access token from the stored refresh token.

Session cookies are HttpOnly, SameSite=Lax, and Secure by default. For local development over plain HTTP, set CookieSecure: lumoauth.Bool(false).

return_to is restricted to same-origin paths, so it cannot be used as an open redirect.


AAuth — cryptographic agent identity

AAuth extends OAuth 2.1 with agent-held keys, proof-of-possession tokens, and RFC 9421 HTTP message signing.

// One-time: generate a key and register the JWKS with LumoAuth.
keypair, err := lumoauth.GenerateKeypair("")
// keypair.PrivateKeyPEM → your secret manager
// keypair.JWKS          → register, or serve at /.well-known/jwks.json

client, err := lumoauth.NewAAuthClient(lumoauth.AAuthConfig{
    AgentIdentifier: "https://my-agent.example.com",
    PrivateKeyPEM:   os.Getenv("AGENT_PRIVATE_KEY"),
    OrgID:           "acme-corp",
})

result, err := client.RequestAuthToken(ctx, lumoauth.AuthTokenParams{
    ResourceToken: resourceToken,
    Scope:         "read write",
    AgentToken:    agentToken,
})
if result.AuthorizationRequired {
    // Redirect the user to result.AuthorizationURI, then:
    // client.ExchangeCode(ctx, code, redirectURI, agentToken)
}

resp, err := client.SignedRequest(ctx, http.MethodGet,
    "https://api.example.com/v1/data", result.AuthToken, nil)

Also available: ExchangeToken (multi-hop with an act chain), Refresh, Revoke, and discovery (DiscoverIssuer, DiscoverAgents, DiscoverResource, JWKS).

Signing output is byte-compatible with the Python and JS SDKs — a shared conformance vector is asserted in aauth_test.go.

Verifying tokens (resource-server side)
claims, err := lumoauth.VerifyAuthToken(ctx, bearerToken, lumoauth.VerifyOptions{
    Issuer:   "https://app.lumoauth.dev/orgs/acme-corp/api/v1",
    Resource: "https://api.example.com",
})
if err != nil {
    return err
}

// AAuth tokens are proof-of-possession: verifying the JWT alone would let
// a stolen token through.
if err := claims.VerifyProofOfPossession(req, body); err != nil {
    return err
}

if !claims.HasScope("read") {
    return errors.New("insufficient scope")
}

VerifyAuthToken checks typ, iss, the JWS signature against the issuer's JWKS, exp, aud, and the presence of cnf.jwk. HMAC and none algorithms are always rejected, and the algorithm must match the published key type. For a busy resource server, pass a cached key set:

cache := lumoauth.NewJWKSCache(issuer, time.Hour, nil)
keys, err := cache.Get(ctx)
claims, err := lumoauth.VerifyAuthToken(ctx, token, lumoauth.VerifyOptions{
    Issuer: issuer, Resource: resource, JWKS: keys,
})

Revocation is not covered — use the server's introspection endpoint when you need revocation-aware checks.


Errors

One taxonomy, shared with the JS and Python SDKs. Match errors 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)
}
Sentinel Meaning Code
ErrLumoAuth Any error from this SDK —
ErrAPI Any non-2xx response API_ERROR
ErrAuthentication 401 AUTHENTICATION_ERROR
ErrPermissionDenied 403 PERMISSION_DENIED
ErrNotFound 404 NOT_FOUND
ErrRateLimited 429 (see APIError.RetryAfter) RATE_LIMITED
ErrValidation Bad input or unusable response VALIDATION_ERROR
ErrConfig Missing or invalid configuration CONFIG_ERROR
ErrNetwork Transport failure, no HTTP response NETWORK_ERROR
ErrApprovalDenied A human declined APPROVAL_DENIED
ErrApprovalTimeout An approval expired APPROVAL_TIMEOUT
ErrBudgetExceeded The agent's budget is spent BUDGET_EXCEEDED

Helpers: AsAPIError(err), StatusCode(err), ErrorCode(err).

Errors wrap their causes, so errors.Is(err, context.DeadlineExceeded) works through a NetworkError.


Escape hatch — the full REST API

The curated namespaces cover what applications reach for. For the rest (admin endpoints, SCIM, audit logs), either call it directly:

path, err := client.OrgPath("/admin/users")

var page struct {
    Data []map[string]any `json:"data"`
}
err = client.Do(ctx, http.MethodGet, path, nil, &page)

…or hand the configuration to the generated OpenAPI client. Go cannot import a package lazily, so this SDK does not depend on the generated client — it configures one for you:

import lumoauthclient "github.com/lumoauth/api-clients/go"

apiCfg, err := client.APIConfig(ctx)

cfg := lumoauthclient.NewConfiguration()
cfg.Servers = lumoauthclient.ServerConfigurations{{URL: apiCfg.BaseURL}}
cfg.DefaultHeader = apiCfg.DefaultHeader
cfg.HTTPClient = apiCfg.HTTPClient

api := lumoauthclient.NewAPIClient(cfg)

APIConfig sets exactly one credential header, matching the credential the client was built with.


Route registry

Every endpoint this SDK calls lives in routes.go — never as an inline string in a resource. A drift test loads server/openapi.json and asserts that each (method, path) still exists, so a route renamed server-side fails the build instead of 404ing in production. Endpoints the spec does not document are listed in knownDrift with a reason.

The same check runs in the JS and Python SDKs against the same spec, and TestRouteRegistryMatchesOtherSDKs flags any endpoint the JS SDK calls that this one is missing.

Development

go test ./...          # unit tests + drift checks
go test -race ./...    # the concurrency paths (token refresh, delegation)
go vet ./...
gofmt -l .

License

MIT — see LICENSE.

Documentation

Overview

Package lumoauth is the official Go SDK for LumoAuth — authentication and authorization for applications and AI agents.

It exposes four entry points, one per kind of caller:

  • Client — the general-purpose API client. Permission checks (RBAC, ReBAC, ABAC), agent identity, delegation, JIT permissions, approvals, and MCP tokens, credentialed with an API key or a bearer token.

  • Agent — for AI agents acting under their own identity. Wraps Client with an OAuth 2.0 client-credentials token it refreshes transparently, plus preflight authorization (Ask), capabilities, and budgets.

  • AAuthClient — for the AAuth protocol: cryptographic agent identity, proof-of-possession tokens, and RFC 9421 HTTP message signing. VerifyAuthToken is the resource-server side of the same protocol.

  • WebAuth — browser sign-in. Wires the OAuth 2.1 Authorization Code + PKCE flow into any net/http-compatible router, with sessions in a signed cookie.

Client

client, err := lumoauth.New(
    lumoauth.WithAPIKey(os.Getenv("LUMOAUTH_API_KEY")),
    lumoauth.WithOrgID("acme-corp"),
)
if err != nil {
    return err
}

ok, err := client.Permissions.Check(ctx, "document.edit", nil)
ok, err = client.Zanzibar.IsViewer(ctx, "document:readme", "user:bob")
decision, err := client.Abac.Check(ctx, lumoauth.AbacCheckParams{
    ResourceType: "document",
    Action:       "read",
    ResourceID:   "doc-123",
})

Resource namespaces cover the surface an application reaches for. For the rest of the REST API — admin endpoints, SCIM, audit logs — use Client.Do, or hand Client.APIConfig to the generated OpenAPI client.

Agent

agent, err := lumoauth.NewAgent(lumoauth.AgentConfig{}) // reads env vars
if err != nil {
    return err
}

if err := agent.RequireCapability(ctx, "tool:search_web"); err != nil {
    return err
}
allowed, err := agent.IsAllowed(ctx, "document.read", map[string]any{"id": "doc_99"})

Before an irreversible action, ask a human:

approval, err := agent.Approvals.Require(ctx, lumoauth.ApprovalParams{
    TaskID:     "wire-2026-05-07-001",
    Reason:     "Wire $4,500 to vendor INV-7741",
    Impact:     lumoauth.ImpactHigh,
    OnBehalfOf: "ada@acme.com",
}, nil)
if err != nil {
    return err // denied, expired, or the wait timed out
}

For narrowly scoped, short-lived permissions, open a JITContext; for acting on behalf of a user, use a DelegationChain.

Web sign-in

auth, err := lumoauth.NewWebAuth(lumoauth.WebConfig{
    Organization:  os.Getenv("LUMO_ORG_ID"),
    ClientID:      os.Getenv("LUMO_CLIENT_ID"),
    ClientSecret:  os.Getenv("LUMO_CLIENT_SECRET"),
    SessionSecret: os.Getenv("SESSION_SECRET"),
})
if err != nil {
    return err
}

mux := http.NewServeMux()
mux.Handle("/auth/", auth.Router())
mux.Handle("/", auth.Middleware(auth.RequireAuth(dashboard)))

// In a handler:
user := lumoauth.UserFromContext(req.Context())

Errors

Every error this package returns is matched with the standard library rather than by type switch:

if errors.Is(err, lumoauth.ErrPermissionDenied) {
    // 403
}

var apiErr *lumoauth.APIError
if errors.As(err, &apiErr) {
    log.Printf("HTTP %d: %v", apiErr.StatusCode, apiErr.Body)
}

The sentinels are ErrAuthentication, ErrPermissionDenied, ErrNotFound, ErrRateLimited, ErrValidation, ErrConfig, ErrNetwork, ErrApprovalDenied, ErrApprovalTimeout, and ErrBudgetExceeded; ErrAPI matches any non-2xx response and ErrLumoAuth matches all of them. The names and codes are shared with the JS and Python SDKs.

Configuration

Options fall back to the environment:

LUMOAUTH_URL           instance URL      (default https://app.lumoauth.dev)
LUMOAUTH_ORG_ID        organization slug
LUMOAUTH_API_KEY       tenant API key    (sent as X-API-Key)
AGENT_CLIENT_ID        agent OAuth client       (Agent only)
AGENT_CLIENT_SECRET    agent OAuth secret       (Agent only)

Every endpoint this SDK calls is registered in Routes; a drift test checks the registry against the server's OpenAPI spec, so a renamed route fails the build rather than 404ing in production.

Example (ErrorHandling)

Errors are matched with the standard library.

package main

import (
	"context"
	"errors"
	"fmt"
	"log"
	"os"

	lumoauth "github.com/lumoauth/lumo-auth-go"
)

func main() {
	client, err := lumoauth.New(
		lumoauth.WithAPIKey(os.Getenv("LUMOAUTH_API_KEY")),
		lumoauth.WithOrgID("acme-corp"),
	)
	if err != nil {
		log.Fatal(err)
	}

	_, err = client.Permissions.Check(context.Background(), "document.edit", nil)
	switch {
	case err == nil:
		// allowed or denied — check the returned bool

	case errors.Is(err, lumoauth.ErrAuthentication):
		fmt.Println("the credential is invalid or expired")

	case errors.Is(err, lumoauth.ErrRateLimited):
		var apiErr *lumoauth.APIError
		errors.As(err, &apiErr)
		fmt.Println("retry after", apiErr.RetryAfter)

	case errors.Is(err, lumoauth.ErrNetwork):
		fmt.Println("could not reach LumoAuth:", err)

	default:
		fmt.Println("unexpected:", err)
	}
}

Index

Examples

Constants

View Source
const (
	AAuthTokenTypeAuth    = "auth_token"
	AAuthTokenTypeRefresh = "refresh_token"
)

Token types accepted by Revoke.

View Source
const (
	EnvAgentClientID     = "AGENT_CLIENT_ID"
	EnvAgentClientSecret = "AGENT_CLIENT_SECRET"
)

Environment variables read by NewAgent when the corresponding field is left empty.

View Source
const (
	EnvBaseURL = "LUMOAUTH_URL"
	EnvOrgID   = "LUMOAUTH_ORG_ID"
	EnvAPIKey  = "LUMOAUTH_API_KEY"
)

Environment variables read when the corresponding option is not passed.

View Source
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"
	CodeBudgetExceeded   = "BUDGET_EXCEEDED"
)

Error codes, identical to the JS and Python SDKs.

View Source
const (
	DefaultJitPollInterval = 5 * time.Second
	DefaultJitPollTimeout  = 5 * time.Minute
)

Defaults for human-in-the-loop approval polling on JIT requests.

View Source
const (
	AttributeTypeUser        = "user"
	AttributeTypeResource    = "resource"
	AttributeTypeEnvironment = "environment"
)

Attribute definition types accepted by AttributeDefinitions.

View Source
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.

View Source
const (
	GrantTypeTokenExchange = "urn:ietf:params:oauth:grant-type:token-exchange"
	TokenTypeAccessToken   = "urn:ietf:params:oauth:token-type:access_token"
)

RFC 8693 token-exchange constants.

View Source
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.

View Source
const (
	// ── Permissions (RBAC) — bearer-scoped, unprefixed ────────────────
	RoutePermissionsCheck     = "permissions.check"
	RoutePermissionsCheckBulk = "permissions.checkBulk"
	RoutePermissionsCheckAny  = "permissions.checkAny"
	RoutePermissionsCheckAll  = "permissions.checkAll"
	RoutePermissionsList      = "permissions.list"

	// ── Zanzibar (ReBAC) ──────────────────────────────────────────────
	RouteZanzibarCheck  = "zanzibar.check"
	RouteZanzibarExpand = "zanzibar.expand"

	// ── ABAC — org-scoped ─────────────────────────────────────────────
	RouteAbacCheck                = "abac.check"
	RouteAbacCheckBulk            = "abac.checkBulk"
	RouteAbacMyAttributes         = "abac.myAttributes"
	RouteAbacSetUserAttribute     = "abac.setUserAttribute"
	RouteAbacResourceAttributes   = "abac.resourceAttributes"
	RouteAbacSetResourceAttribute = "abac.setResourceAttribute"
	RouteAbacAttributeDefinitions = "abac.attributeDefinitions"

	// ── OAuth 2.1 / OIDC ──────────────────────────────────────────────
	RouteOAuthAuthorize = "oauth.authorize"
	RouteOAuthToken     = "oauth.token"
	RouteOAuthRevoke    = "oauth.revoke"
	RouteOAuthUserInfo  = "oauth.userinfo"
	RouteOAuthLogout    = "oauth.logout"
	RouteOAuthLoginJSON = "oauth.loginJson"

	// ── Web (HTML) routes used by identifier-first sign-in ────────────
	RouteWebCheckEmail = "web.checkEmail"
	RouteWebMagicLink  = "web.magicLink"

	// ── Agents (identity) ─────────────────────────────────────────────
	RouteAgentsAsk      = "agents.ask"
	RouteAgentsMe       = "agents.me"
	RouteAgentsRegister = "agents.register"

	// ── Approvals (push-approval-for-actions) ─────────────────────────
	RouteApprovalsCreate = "approvals.create"
	RouteApprovalsStatus = "approvals.status"

	// ── JIT (just-in-time permissions) ────────────────────────────────
	RouteJitCreateTask    = "jit.createTask"
	RouteJitCompleteTask  = "jit.completeTask"
	RouteJitEvaluateTask  = "jit.evaluateTask"
	RouteJitRequest       = "jit.request"
	RouteJitRequestStatus = "jit.requestStatus"
	RouteJitToken         = "jit.token"
	RouteJitPending       = "jit.pending"

	// ── AAuth (agent auth protocol) ───────────────────────────────────
	RouteAAuthAgentToken     = "aauth.agentToken"
	RouteAAuthAgentAuth      = "aauth.agentAuth"
	RouteAAuthTokenRevoke    = "aauth.tokenRevoke"
	RouteAAuthJWKS           = "aauth.jwks"
	RouteAAuthIssuerMetadata = "aauth.issuerMetadata"
	RouteAAuthAgentMetadata  = "aauth.agentMetadata"

	// ── Root discovery ────────────────────────────────────────────────
	RouteWellKnownAAuthIssuer = "wellknown.aauthIssuer"
)

Route names. Using constants rather than bare strings means a typo is a compile error, and every call site is greppable.

View Source
const (
	JitStatusApproved = "approved"
	JitStatusPending  = "pending"
	JitStatusDenied   = "denied"
)

JIT request statuses.

View Source
const (
	TaskResultCompleted = "completed"
	TaskResultFailed    = "failed"
	TaskResultCancelled = "cancelled"
)

Task outcomes accepted by JitResource.EvaluateTask.

View Source
const (
	ApprovalPending  = "pending"
	ApprovalApproved = "approved"
	ApprovalDenied   = "denied"
	ApprovalExpired  = "expired"
)

Approval statuses.

View Source
const AbacMaxBulkRequests = 100

AbacMaxBulkRequests is the server's cap on one bulk check.

View Source
const DefaultBaseURL = "https://app.lumoauth.dev"

DefaultBaseURL is the LumoAuth cloud instance, used when neither WithBaseURL nor LUMOAUTH_URL supplies one.

View Source
const DefaultKid = "key-1"

DefaultKid is the key ID used when none is given, matching the JS and Python SDKs.

View Source
const JitDefaultTTL = 300 // seconds

JitDefaultTTL is the requested lifetime when a call does not specify one.

View Source
const JitMaxTTL = 900 // seconds (15 min)

JitMaxTTL is the longest lifetime the server will grant a JIT token.

View Source
const MaxDelegationDepth = 3

MaxDelegationDepth is the deepest delegation chain LumoAuth will issue tokens for (user → agent → sub-agent).

View Source
const Version = "1.0.0"

Version is the SDK version reported in the User-Agent header.

Variables

View Source
var (
	// ErrLumoAuth matches every error produced by this SDK.
	ErrLumoAuth = errors.New("lumoauth error")
	// ErrAPI matches any non-2xx HTTP response, including the four below.
	ErrAPI = errors.New("lumoauth: API error")
	// ErrAuthentication matches HTTP 401 responses.
	ErrAuthentication = errors.New("lumoauth: authentication failed")
	// ErrPermissionDenied matches HTTP 403 responses.
	ErrPermissionDenied = errors.New("lumoauth: permission denied")
	// ErrNotFound matches HTTP 404 responses.
	ErrNotFound = errors.New("lumoauth: not found")
	// ErrRateLimited matches HTTP 429 responses.
	ErrRateLimited = errors.New("lumoauth: rate limited")
	// ErrValidation matches client-side validation failures.
	ErrValidation = errors.New("lumoauth: validation failed")
	// ErrConfig matches missing or invalid configuration.
	ErrConfig = errors.New("lumoauth: configuration error")
	// ErrNetwork matches transport failures (no HTTP response was received).
	ErrNetwork = errors.New("lumoauth: network error")
	// ErrApprovalDenied matches an approval a human explicitly denied.
	ErrApprovalDenied = errors.New("lumoauth: approval denied")
	// ErrApprovalTimeout matches an approval that expired before a response.
	ErrApprovalTimeout = errors.New("lumoauth: approval timed out")
	// 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.

View Source
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.

View Source
var Routes = map[string]Route{

	RoutePermissionsCheck:     {"POST", "/api/v1/authz/check"},
	RoutePermissionsCheckBulk: {"POST", "/api/v1/authz/check-bulk"},
	RoutePermissionsCheckAny:  {"POST", "/api/v1/authz/check-any"},
	RoutePermissionsCheckAll:  {"POST", "/api/v1/authz/check-all"},
	RoutePermissionsList:      {"GET", "/api/v1/authz/permissions"},

	RouteZanzibarCheck:  {"POST", "/api/v1/authz/zanzibar/check"},
	RouteZanzibarExpand: {"POST", "/api/v1/authz/zanzibar/expand"},

	RouteAbacCheck:              {"POST", orgBase + "/abac/check"},
	RouteAbacCheckBulk:          {"POST", orgBase + "/abac/check-bulk"},
	RouteAbacMyAttributes:       {"GET", orgBase + "/abac/my-attributes"},
	RouteAbacSetUserAttribute:   {"PUT", orgBase + "/abac/users/{userId}/attributes/{attributeSlug}"},
	RouteAbacResourceAttributes: {"GET", orgBase + "/abac/resources/{resourceType}/{resourceId}/attributes"},
	RouteAbacSetResourceAttribute: {"PUT",
		orgBase + "/abac/resources/{resourceType}/{resourceId}/attributes/{attributeSlug}"},
	RouteAbacAttributeDefinitions: {"GET", orgBase + "/abac/attribute-definitions"},

	RouteOAuthAuthorize: {"GET", orgBase + "/oauth/authorize"},
	RouteOAuthToken:     {"POST", orgBase + "/oauth/token"},
	RouteOAuthRevoke:    {"POST", orgBase + "/oauth/revoke"},
	RouteOAuthUserInfo:  {"GET", orgBase + "/oauth/userinfo"},
	RouteOAuthLogout:    {"GET", orgBase + "/oauth/logout"},

	RouteOAuthLoginJSON: {"POST", orgBase + "/oauth/login/json"},

	RouteWebCheckEmail: {"POST", "/orgs/{orgId}/check-email"},
	RouteWebMagicLink:  {"POST", "/orgs/{orgId}/magic-link"},

	RouteAgentsAsk:      {"POST", orgBase + "/agents/ask"},
	RouteAgentsMe:       {"GET", orgBase + "/agents/me"},
	RouteAgentsRegister: {"POST", orgBase + "/agents/register"},

	RouteApprovalsCreate: {"POST", orgBase + "/agents/me/approvals"},
	RouteApprovalsStatus: {"GET", orgBase + "/agents/me/approvals/{token}/status"},

	RouteJitCreateTask:    {"POST", orgBase + "/jit/task"},
	RouteJitCompleteTask:  {"POST", orgBase + "/jit/task/{taskId}/complete"},
	RouteJitEvaluateTask:  {"POST", orgBase + "/jit/task/{taskId}/evaluate"},
	RouteJitRequest:       {"POST", orgBase + "/jit/request"},
	RouteJitRequestStatus: {"GET", orgBase + "/jit/request/{requestId}/status"},
	RouteJitToken:         {"POST", orgBase + "/jit/request/{requestId}/token"},
	RouteJitPending:       {"GET", orgBase + "/jit/pending"},

	RouteAAuthAgentToken:     {"POST", orgBase + "/aauth/agent/token"},
	RouteAAuthAgentAuth:      {"GET", orgBase + "/aauth/agent/auth"},
	RouteAAuthTokenRevoke:    {"POST", orgBase + "/aauth/token/revoke"},
	RouteAAuthJWKS:           {"GET", orgBase + "/aauth/jwks.json"},
	RouteAAuthIssuerMetadata: {"GET", orgBase + "/.well-known/aauth-issuer"},
	RouteAAuthAgentMetadata:  {"GET", orgBase + "/.well-known/aauth-agent"},

	RouteWellKnownAAuthIssuer: {"GET", "/.well-known/aauth-issuer"},
}

Routes maps every route name to its method and path template.

Functions

func Bool

func Bool(b bool) *bool

Bool returns a pointer to b — for optional *bool fields such as WebConfig.CookieSecure.

func BuildPath

func BuildPath(template string, params map[string]string) (string, error)

BuildPath fills `{param}` placeholders in a path template. Values are URL-escaped.

BuildPath("/orgs/{orgId}/api/v1/abac/check", map[string]string{"orgId": "acme-corp"})
// → "/orgs/acme-corp/api/v1/abac/check"

A missing or empty placeholder value is a ConfigError rather than a server-side 404: an absent org ID should fail loudly at the call site.

func BuildSignatureBase

func BuildSignatureBase(components []string, values map[string]string, created int64, nonce string) string

BuildSignatureBase assembles the RFC 9421 signature base: one `"<component>": <value>` line per covered component in order, then the "@signature-params" line carrying created and nonce.

func ContentDigestSHA256

func ContentDigestSHA256(body []byte) string

ContentDigestSHA256 computes an RFC 9530 Content-Digest header value over exact body bytes, using standard base64 (the server base64-decodes it).

func ErrorCode

func ErrorCode(err error) string

ErrorCode returns the LumoAuth error code carried by err (one of the Code* constants, or a server-supplied code), or "" for errors from elsewhere.

func GenerateNonce

func GenerateNonce() (string, error)

GenerateNonce returns a fresh signature nonce: base64url of 16 random bytes (128 bits), comfortably above the 12-byte floor the profile sets.

func LoadPrivateKey

func LoadPrivateKey(pemData string) (crypto.Signer, error)

LoadPrivateKey parses a PEM private key for AAuth signing. Ed25519 and RSA keys are supported, matching the algorithms the server accepts.

func ParseActorChain

func ParseActorChain(token string) ([]string, error)

ParseActorChain returns the `sub` of each nested `act` claim in a delegated JWT, outermost first — the direct actor, then progressively deeper sub-agents.

The token is decoded WITHOUT signature verification: this is for display and audit, never for an authorization decision.

func RouteNames

func RouteNames() []string

RouteNames returns every registered route name, sorted. Useful for diagnostics and for the drift test.

func RoutePath

func RoutePath(name string, params map[string]string) (string, error)

RoutePath looks up a route and builds its concrete path in one call.

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

func SignSignatureBase(signatureBase string, key crypto.Signer) (string, error)

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

func SignatureParams(components []string, created int64, nonce string) string

SignatureParams renders the `(…);created=…;nonce="…"` string shared by the signature base and the Signature-Input header.

func StatusCode

func StatusCode(err error) int

StatusCode returns the HTTP status carried by err, or 0 if the error did not come from an HTTP response.

func TokenSubject

func TokenSubject(token string) (string, error)

TokenSubject returns a JWT's `sub` (principal) claim.

The token is decoded WITHOUT signature verification — display and audit only.

func VerifySignatureBase

func VerifySignatureBase(signatureBase, signatureB64URL string, key crypto.PublicKey) bool

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.

Types

type AAuthAgentMetadata

type AAuthAgentMetadata struct {
	Agent        string   `json:"agent"`
	JWKSURI      string   `json:"jwks_uri,omitempty"`
	RedirectURIs []string `json:"redirect_uris,omitempty"`
	Name         string   `json:"name,omitempty"`
}

AAuthAgentMetadata describes a registered agent.

type AAuthClaims

type AAuthClaims struct {
	Issuer   string `json:"iss"`
	Audience string `json:"aud"`
	Expires  int64  `json:"exp"`
	IssuedAt int64  `json:"iat"`
	JTI      string `json:"jti"`
	Subject  string `json:"sub,omitempty"`
	// Agent identifies the agent the token was issued to.
	Agent string `json:"agent,omitempty"`
	// AgentDelegate is set when the agent acts for another agent.
	AgentDelegate string `json:"agent_delegate,omitempty"`
	Scope         string `json:"scope,omitempty"`
	// Confirmation binds the token to the holder's key (RFC 7800).
	Confirmation struct {
		JWK JWK `json:"jwk"`
	} `json:"cnf"`
	// Act records the delegation chain, when there is one.
	Act map[string]any `json:"act,omitempty"`

	// Raw is every claim in the token, including ones not modelled above.
	Raw map[string]any `json:"-"`
}

AAuthClaims are the claims carried by an `auth+jwt`.

func VerifyAuthToken

func VerifyAuthToken(ctx context.Context, token string, opts VerifyOptions) (*AAuthClaims, error)

VerifyAuthToken verifies an AAuth auth token against the issuing organization's JWKS and returns its claims.

claims, err := lumoauth.VerifyAuthToken(ctx, bearer, lumoauth.VerifyOptions{
    Issuer:   "https://app.lumoauth.dev/orgs/acme-corp/api/v1",
    Resource: "https://api.example.com",
})
if err != nil {
    return err
}
// Then enforce proof-of-possession over the incoming request:
if err := claims.VerifyProofOfPossession(r, body); err != nil {
    return err
}

HMAC and "none" algorithms are always rejected, and the algorithm must match the key type published in the JWKS.

Example

The resource-server side: verify the token, then prove the caller holds the key it is bound to.

package main

import (
	"fmt"
	"net/http"

	lumoauth "github.com/lumoauth/lumo-auth-go"
)

func main() {
	handler := func(w http.ResponseWriter, r *http.Request, body []byte) {
		token := r.Header.Get("Authorization")[len("Bearer "):]

		claims, err := lumoauth.VerifyAuthToken(r.Context(), token, lumoauth.VerifyOptions{
			Issuer:   "https://app.lumoauth.dev/orgs/acme-corp/api/v1",
			Resource: "https://api.example.com",
		})
		if err != nil {
			http.Error(w, "invalid token", http.StatusUnauthorized)
			return
		}

		// AAuth tokens are proof-of-possession: verifying the JWT alone
		// would let a stolen token through.
		if err := claims.VerifyProofOfPossession(r, body); err != nil {
			http.Error(w, "invalid signature", http.StatusUnauthorized)
			return
		}

		if !claims.HasScope("read") {
			http.Error(w, "insufficient scope", http.StatusForbidden)
			return
		}
		fmt.Fprintf(w, "hello %s", claims.Agent)
	}
	_ = handler
}

func (*AAuthClaims) HasScope

func (c *AAuthClaims) HasScope(scope string) bool

HasScope reports whether the token carries a scope.

func (*AAuthClaims) Scopes

func (c *AAuthClaims) Scopes() []string

Scopes splits the space-separated scope claim.

func (*AAuthClaims) VerifyProofOfPossession

func (c *AAuthClaims) VerifyProofOfPossession(r *http.Request, body []byte) error

VerifyProofOfPossession checks that an incoming request was signed by the key the token is bound to (cnf.jwk) — the second half of AAuth verification, without which a stolen token would be replayable.

body must be the exact bytes the request carried, since Content-Digest is computed over them.

type AAuthClient

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

AAuthClient speaks the AAuth (Agent Auth) protocol, which extends OAuth 2.1 with cryptographic agent identity, proof-of-possession tokens, and RFC 9421 HTTP message signing.

client, err := lumoauth.NewAAuthClient(lumoauth.AAuthConfig{
    AgentIdentifier: "https://my-agent.example.com",
    PrivateKeyPEM:   os.Getenv("AGENT_PRIVATE_KEY"),
    OrgID:           "acme-corp",
})
if err != nil {
    return err
}

result, err := client.RequestAuthToken(ctx, lumoauth.AuthTokenParams{
    ResourceToken: resourceToken,
    Scope:         "read write",
    AgentToken:    agentToken,
})
if err != nil {
    return err
}
if result.AuthorizationRequired {
    // Redirect the user to result.AuthorizationURI, then ExchangeCode.
}

For OAuth client-credentials agents (no signing key) use Agent instead.

func NewAAuthClient

func NewAAuthClient(cfg AAuthConfig) (*AAuthClient, error)

NewAAuthClient builds an AAuth client and parses the agent's private key.

Example

An AAuth agent signs its requests with its own key.

package main

import (
	"context"
	"fmt"
	"log"
	"net/http"
	"os"

	lumoauth "github.com/lumoauth/lumo-auth-go"
)

func main() {
	client, err := lumoauth.NewAAuthClient(lumoauth.AAuthConfig{
		AgentIdentifier: "https://my-agent.example.com",
		PrivateKeyPEM:   os.Getenv("AGENT_PRIVATE_KEY"),
		OrgID:           "acme-corp",
	})
	if err != nil {
		log.Fatal(err)
	}

	result, err := client.RequestAuthToken(context.Background(), lumoauth.AuthTokenParams{
		ResourceToken: os.Getenv("RESOURCE_TOKEN"),
		Scope:         "read write",
		AgentToken:    os.Getenv("AGENT_TOKEN"),
	})
	if err != nil {
		log.Fatal(err)
	}

	if result.AuthorizationRequired {
		fmt.Println("send the user to:", result.AuthorizationURI)
		return
	}

	response, err := client.SignedRequest(context.Background(),
		http.MethodGet, "https://api.example.com/v1/data", result.AuthToken, nil)
	if err != nil {
		log.Fatal(err)
	}
	defer response.Body.Close()
}

func (*AAuthClient) AgentIdentifier

func (c *AAuthClient) AgentIdentifier() string

AgentIdentifier returns the agent's identity URL.

func (*AAuthClient) BaseURL

func (c *AAuthClient) BaseURL() string

BaseURL returns the LumoAuth instance URL.

func (*AAuthClient) ConsentURL

func (c *AAuthClient) ConsentURL(requestToken string) (string, error)

ConsentURL builds the user-consent URL for a pending request token. Prefer the AuthorizationURI returned by RequestAuthToken when present.

func (*AAuthClient) DiscoverAgents

func (c *AAuthClient) DiscoverAgents(ctx context.Context) ([]AAuthAgentMetadata, error)

DiscoverAgents fetches metadata for the organization's active agents.

func (*AAuthClient) DiscoverIssuer

func (c *AAuthClient) DiscoverIssuer(ctx context.Context) (*AAuthIssuerMetadata, error)

DiscoverIssuer fetches the organization's AAuth issuer metadata.

func (*AAuthClient) DiscoverResource

func (c *AAuthClient) DiscoverResource(ctx context.Context, resourceURL string) ([]AAuthResourceMetadata, error)

DiscoverResource fetches a resource server's AAuth metadata from {resourceURL}/.well-known/aauth-resource.

func (*AAuthClient) ExchangeCode

func (c *AAuthClient) ExchangeCode(ctx context.Context, code, redirectURI, agentToken string) (*AAuthTokenResponse, error)

ExchangeCode trades an authorization code for tokens after user consent (request_type=code).

redirectURI must be the exact URI the code was delivered to; the server redeems codes atomically and rejects a mismatch.

func (*AAuthClient) ExchangeToken

func (c *AAuthClient) ExchangeToken(ctx context.Context, authToken, resourceToken, agentToken string) (*AAuthTokenResponse, error)

ExchangeToken performs a multi-hop exchange (request_type=exchange): trade an upstream auth token plus a downstream resource token for a new auth token carrying an `act` actor chain. The agent must be permitted to exchange tokens.

func (*AAuthClient) Issuer

func (c *AAuthClient) Issuer() string

Issuer returns the organization's AAuth issuer URL — {baseURL}/orgs/{orgID}/api/v1 — which is the `iss` value in issued tokens and the base for JWKS discovery.

func (*AAuthClient) JWKS

func (c *AAuthClient) JWKS(ctx context.Context) (*JWKS, error)

JWKS fetches the organization's AAuth signing keys — the keys that verify issued auth tokens.

func (*AAuthClient) OrgID

func (c *AAuthClient) OrgID() string

OrgID returns the organization slug.

func (*AAuthClient) PublicJWK

func (c *AAuthClient) PublicJWK() (JWK, error)

PublicJWK returns the agent's public key as a JWK, tagged with its kid.

func (*AAuthClient) PublicJWKThumbprint

func (c *AAuthClient) PublicJWKThumbprint() (string, error)

PublicJWKThumbprint returns the RFC 7638 thumbprint of the agent's public key — the `jkt` value that binds tokens to this key.

func (*AAuthClient) Refresh

func (c *AAuthClient) Refresh(ctx context.Context, params RefreshParams) (*AAuthTokenResponse, error)

Refresh renews an auth token (request_type=refresh). Refresh tokens are not rotated, so the same one stays valid for the grant's lifetime.

func (*AAuthClient) RequestAuthToken

func (c *AAuthClient) RequestAuthToken(ctx context.Context, params AuthTokenParams) (*AAuthTokenResponse, error)

RequestAuthToken asks for an auth token (AAuth Flow 2, direct authorization).

When the server requires user consent it returns a response with AuthorizationRequired set: redirect the user to AuthorizationURI, then call ExchangeCode with the code delivered to your redirect URI.

func (*AAuthClient) Revoke

func (c *AAuthClient) Revoke(ctx context.Context, token, tokenType, agentToken string) error

Revoke invalidates an auth token (by its `jti`) or a refresh token (by value). It succeeds whether or not the token existed — the server does not reveal that.

func (*AAuthClient) SignRequest

func (c *AAuthClient) SignRequest(method, targetURL string, opts SignOptions) (map[string]string, error)

SignRequest builds RFC 9421 signature headers with this agent's key.

func (*AAuthClient) SignedRequest

func (c *AAuthClient) SignedRequest(ctx context.Context, method, targetURL, authToken string, body any) (*http.Response, error)

SignedRequest makes a signed, authenticated request to a protected resource.

The request carries the auth token as a Bearer credential AND an RFC 9421 signature proving possession of the key bound in the token's cnf.jwk. The signature covers the authorization component, so the resource server verifies both together.

The caller owns the returned response and must close its body.

type AAuthConfig

type AAuthConfig struct {
	// AgentIdentifier is the HTTPS URL uniquely identifying the agent,
	// e.g. "https://my-agent.example.com". Required.
	AgentIdentifier string
	// PrivateKeyPEM is the agent's Ed25519 (PKCS#8) or RSA private key.
	// Required.
	PrivateKeyPEM string
	// BaseURL is the LumoAuth instance. Defaults to $LUMOAUTH_URL, then
	// DefaultBaseURL.
	BaseURL string
	// OrgID is the organization slug. Defaults to $LUMOAUTH_ORG_ID.
	OrgID string
	// Kid identifies the key in the JWKS registered with LumoAuth.
	// Defaults to DefaultKid.
	Kid string
	// Timeout is the per-request timeout. Default: 30s.
	Timeout time.Duration
	// HTTPClient overrides the *http.Client used for every request.
	HTTPClient *http.Client
	// SkipCertValidation disables TLS verification. Local development only.
	SkipCertValidation bool
}

AAuthConfig configures an AAuthClient.

type AAuthIssuerMetadata

type AAuthIssuerMetadata struct {
	Issuer                    string   `json:"issuer"`
	AAuthVersion              string   `json:"aauth_version,omitempty"`
	JWKSURI                   string   `json:"jwks_uri,omitempty"`
	AgentTokenEndpoint        string   `json:"agent_token_endpoint,omitempty"`
	AgentAuthEndpoint         string   `json:"agent_auth_endpoint,omitempty"`
	AgentSigningAlgsSupported []string `json:"agent_signing_algs_supported,omitempty"`
	TokenSigningAlgsSupported []string `json:"token_signing_algs_supported,omitempty"`
	RequestTypesSupported     []string `json:"request_types_supported,omitempty"`
	ScopesSupported           []string `json:"scopes_supported,omitempty"`
}

AAuthIssuerMetadata describes an AAuth authorization server.

type AAuthResourceMetadata

type AAuthResourceMetadata struct {
	Resource              string   `json:"resource"`
	JWKSURI               string   `json:"jwks_uri,omitempty"`
	ResourceTokenEndpoint string   `json:"resource_token_endpoint,omitempty"`
	SupportedScopes       []string `json:"supported_scopes,omitempty"`
}

AAuthResourceMetadata describes a protected resource server.

type AAuthTokenResponse

type AAuthTokenResponse struct {
	// RequestType echoes the flow: auth, code, exchange, or refresh.
	RequestType string
	// AuthToken is the `auth+jwt` to present to the resource.
	AuthToken string
	// ExpiresIn is the token's lifetime in seconds.
	ExpiresIn int
	// TokenType is normally "auth+jwt".
	TokenType string
	// RefreshToken is present when the grant includes one.
	RefreshToken string

	// AuthorizationRequired reports that a human must consent first.
	AuthorizationRequired bool
	// RequestToken identifies the pending request (600s TTL).
	RequestToken string
	// AuthorizationURI is the consent page to redirect the user to.
	AuthorizationURI string
}

AAuthTokenResponse is a successful response from the agent token endpoint. When the server requires user consent instead, AuthorizationRequired is set and the token fields are empty.

type APIConfig

type APIConfig struct {
	// BaseURL is the server URL, without a trailing slash.
	BaseURL string
	// DefaultHeader holds exactly one credential header — X-API-Key or
	// Authorization — never both.
	DefaultHeader map[string]string
	// HTTPClient is this client's underlying *http.Client.
	HTTPClient *http.Client
}

APIConfig carries everything needed to point the generated OpenAPI client (github.com/lumoauth/api-clients/go) at this instance.

type APIError

type APIError struct {
	*BaseError
	// StatusCode is the HTTP status of the response.
	StatusCode int
	// Body is the decoded response body: map[string]any for JSON objects,
	// a string for anything else, nil for an empty body.
	Body any
	// RetryAfter carries the Retry-After hint on 429 responses (0 if absent).
	RetryAfter time.Duration
}

APIError is returned when the server responds with a non-2xx status.

func AsAPIError

func AsAPIError(err error) (*APIError, bool)

AsAPIError extracts the *APIError from an error chain, reporting whether one was present. Shorthand for errors.As.

func (*APIError) Is

func (e *APIError) Is(target error) bool

Is additionally matches ErrAPI for every status, so callers can catch all server-side failures with a single check.

type AbacAttributeDefinition

type AbacAttributeDefinition struct {
	ID              string         `json:"id"`
	Name            string         `json:"name"`
	Slug            string         `json:"slug"`
	Description     string         `json:"description,omitempty"`
	AttributeType   string         `json:"attributeType,omitempty"` // user | resource | environment
	DataType        string         `json:"dataType,omitempty"`      // string | number | boolean | array | date
	ValidationRules map[string]any `json:"validationRules,omitempty"`
	IsActive        bool           `json:"isActive,omitempty"`
}

AbacAttributeDefinition describes an attribute the org has defined.

type AbacBulkDecision

type AbacBulkDecision struct {
	Results []AbacDecision `json:"results"`
}

AbacBulkDecision is the result of a bulk ABAC check, in request order.

type AbacCheckParams

type AbacCheckParams struct {
	// ResourceType is the kind of thing being accessed ("document"). Required.
	ResourceType string
	// Action is the operation ("read", "delete"). Required.
	Action string
	// ResourceID identifies the specific instance, when there is one.
	ResourceID string
	// Context supplies resource and environment attributes for the
	// evaluation, e.g. {"environment": {"ip": "10.0.0.1"}}.
	Context map[string]any
}

AbacCheckParams describes one ABAC evaluation.

type AbacDecision

type AbacDecision struct {
	Allowed         bool                `json:"allowed"`
	Reason          string              `json:"reason,omitempty"`
	MatchedPolicies []AbacMatchedPolicy `json:"matchedPolicies,omitempty"`

	// Raw is the complete decoded decision, including the evaluation
	// context the server echoed back.
	Raw map[string]any `json:"-"`
}

AbacDecision is the outcome of evaluating ABAC policies for one resource/action pair.

func (*AbacDecision) UnmarshalJSON

func (d *AbacDecision) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes the typed fields and retains the whole object.

type AbacMatchedPolicy

type AbacMatchedPolicy struct {
	ID       string `json:"id"`
	Name     string `json:"name"`
	Effect   string `json:"effect"` // "allow" or "deny"
	Priority int    `json:"priority"`
}

AbacMatchedPolicy is a policy that contributed to an ABAC decision.

type AbacResource

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

AbacResource covers attribute-based access control: policy evaluation from user, resource, and environment attributes, plus attribute management.

ABAC is org-scoped, so the client needs an org ID.

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.

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"),
	)

	decision, err := client.Abac.Check(context.Background(), lumoauth.AbacCheckParams{
		ResourceType: "document",
		Action:       "read",
		ResourceID:   "doc-123",
		Context: map[string]any{
			"environment": map[string]any{"ip": "10.0.0.1"},
		},
	})
	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)
	}
}

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.

func (*AbacResource) IsAllowed

func (r *AbacResource) IsAllowed(ctx context.Context, params AbacCheckParams) (bool, error)

IsAllowed is Check reduced to a boolean.

func (*AbacResource) MyAttributes

func (r *AbacResource) MyAttributes(ctx context.Context) (map[string]any, error)

MyAttributes returns every ABAC attribute for the authenticated user, built-in and custom.

func (*AbacResource) ResourceAttributes

func (r *AbacResource) ResourceAttributes(ctx context.Context, resourceType, resourceID string) (map[string]any, error)

ResourceAttributes returns the ABAC attributes attached to one resource.

func (*AbacResource) SetResourceAttribute

func (r *AbacResource) SetResourceAttribute(ctx context.Context, resourceType, resourceID, attributeSlug string, value any) error

SetResourceAttribute sets one attribute value on a resource.

func (*AbacResource) SetUserAttribute

func (r *AbacResource) SetUserAttribute(ctx context.Context, userID, attributeSlug string, value any) error

SetUserAttribute sets one attribute value on a user.

type Agent

type Agent struct {
	// Agents covers ask/isAllowed, self-inspection, and registration.
	Agents *AgentsResource
	// Jit covers Just-in-Time permissions.
	Jit *JitResource
	// Delegation covers RFC 8693 delegation primitives.
	Delegation *DelegationResource
	// Approvals covers push-approval-for-agent-actions.
	Approvals *ApprovalsResource
	// Mcp covers token exchange for secured MCP servers.
	Mcp *McpResource
	// Permissions covers RBAC checks for the agent's own principal.
	Permissions *PermissionsResource
	// contains filtered or unexported fields
}

Agent is the client for an AI agent acting under its own identity.

It owns an OAuth 2.0 client-credentials token and refreshes it transparently, so no call has to be preceded by an explicit login:

agent, err := lumoauth.NewAgent(lumoauth.AgentConfig{}) // reads env vars
if err != nil {
    return err
}

allowed, err := agent.IsAllowed(ctx, "document.read", map[string]any{"id": "doc_99"})
if err != nil {
    return err
}

approval, err := agent.Approvals.Require(ctx, lumoauth.ApprovalParams{
    TaskID: "wire-001", Reason: "Wire $4,500 to INV-7741",
    Impact: lumoauth.ImpactHigh, OnBehalfOf: "ada@acme.com",
}, nil)

For the AAuth protocol — cryptographic agent identity and RFC 9421 message signing — use AAuthClient instead.

An Agent is safe for concurrent use; concurrent callers share one in-flight token request.

func NewAgent

func NewAgent(cfg AgentConfig) (*Agent, error)

NewAgent builds an Agent from config and environment. It returns a *ConfigError when the client credentials cannot be resolved; no network call is made until the first request.

Example

An agent checks whether it may act before acting.

package main

import (
	"context"
	"log"

	lumoauth "github.com/lumoauth/lumo-auth-go"
)

func main() {
	agent, err := lumoauth.NewAgent(lumoauth.AgentConfig{})
	if err != nil {
		log.Fatal(err)
	}

	ctx := context.Background()
	allowed, err := agent.IsAllowed(ctx, "document.read", map[string]any{"id": "doc_99"})
	if err != nil {
		log.Fatal(err)
	}
	if !allowed {
		return
	}
	// ... read the document
}

func (*Agent) AccessToken

func (a *Agent) AccessToken(ctx context.Context) (string, error)

AccessToken returns a valid access token, authenticating or refreshing when the cached one is missing or within a minute of expiry. It doubles as the TokenProvider for the underlying client.

Concurrent callers collapse onto a single token request: the first one through refreshes while the rest wait, then all read the fresh token.

func (*Agent) Ask

func (a *Agent) Ask(ctx context.Context, action string, actionContext map[string]any) (*AgentAskResult, error)

Ask asks whether the agent may perform an action — the preflight check before an LLM tool call.

func (*Agent) Authenticate

func (a *Agent) Authenticate(ctx context.Context, scopes ...string) (string, error)

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) BaseURL

func (a *Agent) BaseURL() string

BaseURL returns the LumoAuth instance URL.

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

func (a *Agent) Capabilities(ctx context.Context) ([]string, error)

Capabilities returns the agent's capability slugs.

func (*Agent) CheckBudget

func (a *Agent) CheckBudget(ctx context.Context) error

CheckBudget returns an error matching ErrBudgetExceeded when the agent's daily token budget is spent, and nil otherwise. Budget state is cached with the rest of the agent info — call Info(ctx, true) first for a live reading.

func (*Agent) Client

func (a *Agent) Client() *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) ClientID

func (a *Agent) ClientID() string

ClientID returns the agent's OAuth client ID.

func (*Agent) ClientSecret

func (a *Agent) ClientSecret() string

ClientSecret returns the agent's OAuth client secret. Needed by DelegationChain for the confidential-client consent exchange.

func (*Agent) Do

func (a *Agent) Do(ctx context.Context, method, path string, body, out any) error

Do sends an authenticated request to any endpoint and decodes the JSON response into out (nil to discard). See Client.Do.

func (*Agent) DoRaw

func (a *Agent) DoRaw(ctx context.Context, 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 (*Agent) HasCapability

func (a *Agent) HasCapability(ctx context.Context, capability string) (bool, error)

HasCapability reports whether the agent holds a capability.

func (*Agent) Identity

func (a *Agent) Identity(ctx context.Context, refresh bool) (*AgentIdentity, error)

Identity returns the agent's own identity, capabilities, and workspace, caching the result. Pass refresh to force a fetch.

func (*Agent) Info

func (a *Agent) Info(ctx context.Context, refresh bool) (*UserInfo, error)

Info returns the agent's UserInfo claims (capabilities, budget policy), caching the result. Pass refresh to force a fetch.

func (*Agent) IsAllowed

func (a *Agent) IsAllowed(ctx context.Context, action string, actionContext map[string]any) (bool, error)

IsAllowed is Ask reduced to a boolean.

func (*Agent) MCPToken

func (a *Agent) MCPToken(ctx context.Context, serverID string) (string, error)

MCPToken exchanges the agent's token for one scoped to a secured MCP server.

func (*Agent) OrgID

func (a *Agent) OrgID() string

OrgID returns the organization slug.

func (*Agent) RedirectURI

func (a *Agent) RedirectURI() string

RedirectURI returns the configured OAuth callback URL.

func (*Agent) Register

func (a *Agent) Register(ctx context.Context, params RegisterParams) (*AgentRegistration, error)

Register creates or updates this agent's record in the organization directory, using its own client ID.

func (*Agent) RequireCapability

func (a *Agent) RequireCapability(ctx context.Context, capability string) error

RequireCapability is the guard for a capability-gated method: it returns nil when the agent holds the capability, and an error matching ErrPermissionDenied when it does not.

func (s *Service) SearchWeb(ctx context.Context, query string) error {
    if err := s.agent.RequireCapability(ctx, "tool:search_web"); err != nil {
        return err
    }
    …
}
Example

Capability gating at the top of a tool implementation.

package main

import (
	"context"
	"errors"
	"fmt"
	"log"

	lumoauth "github.com/lumoauth/lumo-auth-go"
)

func main() {
	agent, err := lumoauth.NewAgent(lumoauth.AgentConfig{})
	if err != nil {
		log.Fatal(err)
	}

	if err := agent.RequireCapability(context.Background(), "tool:search_web"); err != nil {
		if errors.Is(err, lumoauth.ErrPermissionDenied) {
			fmt.Println("this agent is not registered for web search")
			return
		}
		log.Fatal(err)
	}
	// ... run the search
}

func (*Agent) TokenScopes

func (a *Agent) TokenScopes() []string

TokenScopes returns the scopes granted by the last authentication.

type AgentAskResult

type AgentAskResult struct {
	Allowed bool           `json:"allowed"`
	Action  string         `json:"action,omitempty"`
	Reason  string         `json:"reason,omitempty"`
	AuditID string         `json:"audit_id,omitempty"`
	Context map[string]any `json:"context,omitempty"`

	// Raw is the complete decoded decision.
	Raw map[string]any `json:"-"`
}

AgentAskResult is the decision returned by the Ask API.

func (*AgentAskResult) UnmarshalJSON

func (r *AgentAskResult) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes the typed fields and retains the whole object.

type AgentBudget

type AgentBudget struct {
	MaxTokensPerDay int `json:"max_tokens_per_day,omitempty"`
	TokensUsedToday int `json:"tokens_used_today,omitempty"`

	// Raw is the complete decoded policy.
	Raw map[string]any `json:"-"`
}

AgentBudget is the budget policy attached to an agent.

func (*AgentBudget) Exhausted

func (b *AgentBudget) Exhausted() bool

Exhausted reports whether the daily token budget has been reached. A policy without a daily cap is never exhausted.

func (*AgentBudget) UnmarshalJSON

func (b *AgentBudget) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes the typed fields and retains the whole object.

type AgentConfig

type AgentConfig struct {
	// BaseURL is the LumoAuth instance. Defaults to $LUMOAUTH_URL, then
	// DefaultBaseURL.
	BaseURL string
	// OrgID is the organization slug. Defaults to $LUMOAUTH_ORG_ID.
	OrgID string
	// ClientID is the agent's OAuth client. Defaults to $AGENT_CLIENT_ID.
	ClientID string
	// ClientSecret is the agent's OAuth secret. Defaults to
	// $AGENT_CLIENT_SECRET.
	ClientSecret string
	// Scopes are requested at authentication. Leave empty to receive the
	// agent's registered defaults.
	Scopes []string
	// RedirectURI is the OAuth callback for the delegation consent flow.
	RedirectURI string
	// Timeout is the per-request timeout. Default: 30s.
	Timeout time.Duration
	// HTTPClient overrides the *http.Client used for every request.
	HTTPClient *http.Client
	// SkipCertValidation disables TLS verification. Local development only.
	SkipCertValidation bool
}

AgentConfig configures an Agent. Every field falls back to an environment variable when left empty.

type AgentIdentity

type AgentIdentity struct {
	Identity     map[string]any `json:"identity,omitempty"`
	Capabilities []string       `json:"capabilities,omitempty"`
	Workspace    map[string]any `json:"workspace,omitempty"`

	// Raw is the complete decoded response.
	Raw map[string]any `json:"-"`
}

AgentIdentity is the agent's own identity, capabilities, and workspace.

func (*AgentIdentity) ID

func (i *AgentIdentity) ID() string

ID returns the agent's identity ID, or "" when the server did not send one.

func (*AgentIdentity) UnmarshalJSON

func (i *AgentIdentity) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes the typed fields and retains the whole object.

type AgentRegistration

type AgentRegistration struct {
	AgentID  string `json:"agent_id,omitempty"`
	ClientID string `json:"client_id,omitempty"`
	Name     string `json:"name,omitempty"`
	Status   string `json:"status,omitempty"`

	// Raw is the complete decoded response.
	Raw map[string]any `json:"-"`
}

AgentRegistration is the response to registering an agent.

func (*AgentRegistration) UnmarshalJSON

func (r *AgentRegistration) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes the typed fields and retains the whole object.

type AgentsResource

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

AgentsResource covers agent identity: the Ask API for preflight authorization, self-inspection, and registration.

func (*AgentsResource) Ask

func (r *AgentsResource) Ask(ctx context.Context, action string, actionContext map[string]any) (*AgentAskResult, error)

Ask asks whether the agent may perform an action. It is the preflight check to run before an LLM tool call, and it writes an audit record whichever way the decision goes.

decision, err := client.Agents.Ask(ctx, "document.read", map[string]any{"id": "doc_99"})
if err != nil {
    return err
}
if !decision.Allowed {
    return fmt.Errorf("refused: %s", decision.Reason)
}

func (*AgentsResource) Budget

func (r *AgentsResource) Budget(ctx context.Context) (*AgentBudget, error)

Budget returns the agent's budget policy. The result is never nil: an agent with no policy gets an empty one, which reports Exhausted() false.

func (*AgentsResource) Capabilities

func (r *AgentsResource) Capabilities(ctx context.Context) ([]string, error)

Capabilities returns the capability slugs granted to the agent.

func (*AgentsResource) Info

func (r *AgentsResource) Info(ctx context.Context) (*UserInfo, error)

Info returns the agent's claims from the UserInfo endpoint, which carries capabilities and the budget policy for agent principals.

func (*AgentsResource) IsAllowed

func (r *AgentsResource) IsAllowed(ctx context.Context, action string, actionContext map[string]any) (bool, error)

IsAllowed is Ask reduced to a boolean.

func (*AgentsResource) Me

Me returns the calling agent's own identity, capabilities, and workspace.

func (*AgentsResource) Register

func (r *AgentsResource) Register(ctx context.Context, params RegisterParams) (*AgentRegistration, error)

Register creates or updates the agent's record in the organization directory.

type ApprovalError

type ApprovalError struct {
	*BaseError
	// Approval is the last observed approval payload, for audit.
	Approval *ApprovalResult
}

ApprovalError is returned when a push approval was denied by a human (ErrApprovalDenied) or expired before anyone responded (ErrApprovalTimeout).

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".
	Status string `json:"status"`
	// 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

Create opens an approval request and returns immediately with the pending approval, whose Token identifies it.

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, or the wait timed out
}
// approval.Token authorises the side-effecting call.

Use errors.Is with ErrApprovalDenied or ErrApprovalTimeout to tell the outcomes apart; the *ApprovalError carries the final payload for audit. 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 err != nil:
		log.Fatal(err)
	}

	// approval.Token authorises the side-effecting call.
	fmt.Println("approved by", approval.ApprovedBy.Email)
}

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  string `json:"email,omitempty"`
}

Approver identifies the human who responded to an approval request.

type AuthResource

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

AuthResource covers the org-scoped OAuth 2.1 endpoints: authorize, token, userinfo, and revoke.

func (*AuthResource) AuthorizationURL

func (r *AuthResource) AuthorizationURL(params AuthorizationURLParams) (string, error)

AuthorizationURL builds the URL to redirect a user to in order to start the authorization-code flow.

func (*AuthResource) ClientCredentials

func (r *AuthResource) ClientCredentials(ctx context.Context, clientID, clientSecret string, scopes ...string) (*TokenResponse, error)

ClientCredentials performs the machine-to-machine client-credentials grant. Passing no scopes lets the server grant the client's defaults.

func (*AuthResource) ExchangeCode

func (r *AuthResource) ExchangeCode(ctx context.Context, params ExchangeCodeParams) (*TokenResponse, error)

ExchangeCode trades an authorization code for tokens.

func (*AuthResource) RefreshToken

func (r *AuthResource) RefreshToken(ctx context.Context, params RefreshTokenParams) (*TokenResponse, error)

RefreshToken exchanges a refresh token for a new access token.

func (*AuthResource) Revoke

func (r *AuthResource) Revoke(ctx context.Context, params RevokeParams) error

Revoke invalidates an access or refresh token. Revoking a refresh token also invalidates the tokens derived from it.

func (*AuthResource) TokenExchange

func (r *AuthResource) TokenExchange(ctx context.Context, params TokenExchangeParams) (*TokenResponse, error)

TokenExchange performs an RFC 8693 exchange — the primitive behind delegation and MCP audience scoping.

func (*AuthResource) UserInfo

func (r *AuthResource) UserInfo(ctx context.Context, accessToken string) (*UserInfo, error)

UserInfo fetches the OIDC UserInfo claims. Pass an empty accessToken to use the client's own credentials.

type AuthTokenParams

type AuthTokenParams struct {
	// ResourceToken is the `resource+jwt` obtained from the target
	// resource. Required.
	ResourceToken string
	// Scope is space-separated and informational; scopes bind through the
	// resource token.
	Scope string
	// AgentToken is the `agent+jwt` presented in Agent-Auth. Required —
	// the endpoint authenticates the agent through that header, not the
	// request body.
	AgentToken string
	// RedirectURI is where consent should return the user, for flows that
	// need it. Must be registered for the agent.
	RedirectURI string
}

AuthTokenParams describes a direct authorization request (request_type=auth).

type AuthorizationURLParams

type AuthorizationURLParams struct {
	// ClientID is the OAuth client initiating the flow. Required.
	ClientID string
	// RedirectURI must match one registered on the client. Required.
	RedirectURI string
	// Scope defaults to "openid profile email".
	Scope string
	// State is the CSRF token echoed back to the redirect URI.
	State string
	// ResponseType defaults to "code".
	ResponseType string
	// CodeChallenge enables PKCE. When set and CodeChallengeMethod is
	// empty, "S256" is used.
	CodeChallenge       string
	CodeChallengeMethod string
	// Prompt is the OIDC prompt parameter ("consent", "login", "none").
	Prompt string
	// AccessType set to "offline" requests a refresh token.
	AccessType string
	// Extra adds arbitrary query parameters.
	Extra map[string]string
}

AuthorizationURLParams describes an authorization-code redirect.

type BaseError

type BaseError struct {
	// Code is the stable machine-readable code shared with the JS and
	// Python SDKs (see the Code* constants).
	Code string
	// Message is the human-readable description.
	Message string
	// contains filtered or unexported fields
}

BaseError carries the fields every LumoAuth error has. The concrete error types embed it, so errors.Is(err, ErrLumoAuth) holds for all of them.

func (*BaseError) ErrCode

func (e *BaseError) ErrCode() string

ErrCode returns the error's LumoAuth code. It backs the package-level ErrorCode helper across all error types.

func (*BaseError) Error

func (e *BaseError) Error() string

func (*BaseError) Is

func (e *BaseError) Is(target error) bool

Is reports whether the error matches ErrLumoAuth or its own sentinel.

func (*BaseError) Unwrap

func (e *BaseError) Unwrap() error

Unwrap returns the underlying cause, if the error wraps one.

type BudgetError

type BudgetError struct {
	*BaseError
	// Budget is the policy that blocked the action.
	Budget *AgentBudget
}

BudgetError is returned when an agent's budget policy blocks an action.

type CheckOptions

type CheckOptions struct {
	// Context supplies attributes for ABAC evaluation alongside the RBAC
	// decision.
	Context map[string]any
	// UserID checks on behalf of another user. Backend credentials only —
	// the endpoint otherwise defaults to the authenticated principal.
	UserID string
}

CheckOptions carries the optional arguments shared by every check.

type Client

type Client struct {
	// Auth covers the OAuth 2.1 flows: authorization URLs, code exchange,
	// refresh, client credentials, token exchange, revocation, UserInfo.
	Auth *AuthResource
	// Permissions covers RBAC checks for the authenticated principal.
	Permissions *PermissionsResource
	// Zanzibar covers relationship-based (ReBAC) checks.
	Zanzibar *ZanzibarResource
	// Abac covers attribute-based policy evaluation and attribute management.
	Abac *AbacResource
	// Agents covers agent identity: ask, self-inspection, registration.
	Agents *AgentsResource
	// Delegation covers RFC 8693 token exchange (Chain of Agency).
	Delegation *DelegationResource
	// Jit covers Just-in-Time permissions: ephemeral tasks and scoped tokens.
	Jit *JitResource
	// Approvals covers push-approval-for-agent-actions.
	Approvals *ApprovalsResource
	// Mcp covers audience-scoped tokens for secured MCP servers.
	Mcp *McpResource
	// contains filtered or unexported fields
}

Client is the general-purpose LumoAuth API client.

Curated resource namespaces cover the common surface — the ones an application actually reaches for. Everything else (admin CRUD, SCIM, audit logs) is available through the Do escape hatch or the generated OpenAPI client, which APIConfig configures for you.

client, err := lumoauth.New(
    lumoauth.WithAPIKey(os.Getenv("LUMOAUTH_API_KEY")),
    lumoauth.WithOrgID("acme-corp"),
)
if err != nil {
    return err
}

ok, err := client.Permissions.Check(ctx, "document.edit", nil)
decision, err := client.Abac.Check(ctx, lumoauth.AbacCheckParams{
    ResourceType: "document", Action: "read", ResourceID: "doc-123",
})

A Client is safe for concurrent use.

func New

func New(opts ...Option) (*Client, error)

New builds a Client. It returns a *ConfigError when no credential is configured — either an API key or a token provider is required.

Example

The general-purpose client: check a permission for the authenticated principal.

package main

import (
	"context"
	"fmt"
	"log"
	"os"

	lumoauth "github.com/lumoauth/lumo-auth-go"
)

func main() {
	client, err := lumoauth.New(
		lumoauth.WithAPIKey(os.Getenv("LUMOAUTH_API_KEY")),
		lumoauth.WithOrgID("acme-corp"),
	)
	if err != nil {
		log.Fatal(err)
	}

	allowed, err := client.Permissions.Check(context.Background(), "document.edit", nil)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(allowed)
}

func (*Client) APIConfig

func (c *Client) APIConfig(ctx context.Context) (*APIConfig, error)

APIConfig returns the settings for the generated OpenAPI client, which covers the full REST surface (admin endpoints, SCIM, audit logs).

Unlike the JS and Python SDKs, Go cannot import the generated client lazily — a hard dependency would force it on every consumer — so this SDK hands you the configuration instead of the client:

import lumoauthclient "github.com/lumoauth/api-clients/go"

apiCfg, err := client.APIConfig(ctx)
if err != nil {
    return err
}
cfg := lumoauthclient.NewConfiguration()
cfg.Servers = lumoauthclient.ServerConfigurations{{URL: apiCfg.BaseURL}}
cfg.DefaultHeader = apiCfg.DefaultHeader
cfg.HTTPClient = apiCfg.HTTPClient
api := lumoauthclient.NewAPIClient(cfg)

The context resolves the current bearer token, so call this once per token lifetime (or per request when using short-lived agent tokens).

func (*Client) BaseURL

func (c *Client) BaseURL() string

BaseURL returns the configured LumoAuth instance URL, without a trailing slash.

func (*Client) Do

func (c *Client) Do(ctx context.Context, method, path string, body, out any) error

Do sends an authenticated request to any LumoAuth endpoint and decodes the JSON response into out (pass nil to discard it). The path is joined to the client's base URL; an absolute URL is used as-is. Non-2xx responses become the typed errors in errors.go.

Reach for this when an endpoint has no curated namespace yet:

var page struct {
    Data []map[string]any `json:"data"`
}
err := client.Do(ctx, "GET", "/orgs/acme-corp/api/v1/admin/users", nil, &page)
Example

Reaching past the curated namespaces to the rest of the REST API.

package main

import (
	"context"
	"fmt"
	"log"
	"net/http"
	"os"

	lumoauth "github.com/lumoauth/lumo-auth-go"
)

func main() {
	client, err := lumoauth.New(
		lumoauth.WithAPIKey(os.Getenv("LUMOAUTH_API_KEY")),
		lumoauth.WithOrgID("acme-corp"),
	)
	if err != nil {
		log.Fatal(err)
	}

	path, err := client.OrgPath("/admin/users")
	if err != nil {
		log.Fatal(err)
	}

	var page struct {
		Data []map[string]any `json:"data"`
	}
	if err := client.Do(context.Background(), http.MethodGet, path, nil, &page); err != nil {
		log.Fatal(err)
	}
	fmt.Println(len(page.Data), "users")
}

func (*Client) DoRaw

func (c *Client) DoRaw(ctx context.Context, 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. Transport failures are still wrapped as *NetworkError, but HTTP statuses are left untouched.

func (*Client) OrgID

func (c *Client) OrgID() string

OrgID returns the configured organization slug ("" when unset).

func (*Client) OrgPath

func (c *Client) OrgPath(path string) (string, error)

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

type ConfidentialClient

type ConfidentialClient interface {
	TokenSource
	ClientID() string
	ClientSecret() string
}

ConfidentialClient is what DelegationChain needs from an agent: a token source plus the OAuth client credentials the consent-code exchange and revocation require. *Agent satisfies it.

type ConfigError

type ConfigError struct {
	*BaseError
}

ConfigError is returned when a required option is missing or invalid.

func NewConfigError

func NewConfigError(message string) *ConfigError

NewConfigError builds a ConfigError.

type ConsentURLParams

type ConsentURLParams struct {
	// ClientID is the agent's OAuth client. Required.
	ClientID string
	// RedirectURI is where consent returns the user. Required.
	RedirectURI string
	// Scopes are the permissions being requested. Defaults to
	// ["read:documents"].
	Scopes []string
	// State is the CSRF token echoed back to the redirect URI.
	State string
}

ConsentURLParams describes the consent redirect a user follows to let an agent act on their behalf.

type CreateTaskParams

type CreateTaskParams struct {
	// Name is a human-readable label ("Analyse Q4 report").
	Name string
	// Type categorises the task ("research", "analysis").
	Type string
	// OnBehalfOf is the user's email when the agent acts for someone.
	OnBehalfOf string
}

CreateTaskParams describes an ephemeral task.

type DelegationChain

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

DelegationChain manages RFC 8693 token exchange for agents acting on behalf of users — the Chain of Agency.

It tracks one delegation per session ID through the full lifecycle:

  1. User consent — build an authorization URL, then exchange the callback code for the user's tokens.

  2. Token exchange — combine the user's token (subject) with the agent's (actor) into a delegated token carrying an `act` claim.

  3. Delegated requests — call APIs as "agent acting for user", so every action is attributable to both.

  4. Nested delegation — pass authority to a sub-agent, adding a link to the chain (up to MaxDelegationDepth).

  5. Revocation — invalidate a session's tokens.

    chain := lumoauth.NewDelegationChain(agent, "https://agent.example.com/callback")

    url, err := chain.ConsentURL("session-1", []string{"read:documents"}, "") // … user completes consent, your callback receives `code` … if err := chain.HandleConsentCallback(ctx, "session-1", code); err != nil { return err } resp, err := chain.Do(ctx, "session-1", "GET", "/orgs/acme/api/v1/documents", nil)

A DelegationChain is safe for concurrent use.

func NewDelegationChain

func NewDelegationChain(agent ConfidentialClient, redirectURI string) *DelegationChain

NewDelegationChain builds a chain over an authenticated agent. redirectURI is the OAuth callback the consent flow returns to; it may be empty when tokens are registered directly with SetUserToken.

Example

Acting on behalf of a user, with the chain recorded in the token.

package main

import (
	"context"
	"fmt"
	"log"
	"net/http"

	lumoauth "github.com/lumoauth/lumo-auth-go"
)

func main() {
	agent, err := lumoauth.NewAgent(lumoauth.AgentConfig{})
	if err != nil {
		log.Fatal(err)
	}

	chain := lumoauth.NewDelegationChain(agent, "https://agent.example.com/callback")
	ctx := context.Background()

	// 1. Send the user here to grant consent.
	consentURL, err := chain.ConsentURL("session-1", []string{"read:documents"}, "")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("visit:", consentURL)

	// 2. Your callback receives ?code=…
	if err := chain.HandleConsentCallback(ctx, "session-1", "code-from-callback"); err != nil {
		log.Fatal(err)
	}

	// 3. Call as "agent acting for user". The exchange happens on demand.
	var documents struct {
		Data []map[string]any `json:"data"`
	}
	if err := chain.Do(ctx, "session-1", http.MethodGet,
		"/orgs/acme-corp/api/v1/documents", nil, &documents); err != nil {
		log.Fatal(err)
	}
}

func (*DelegationChain) ActiveSessions

func (c *DelegationChain) ActiveSessions() []string

ActiveSessions returns the session IDs holding user tokens.

func (*DelegationChain) ActorChain

func (c *DelegationChain) ActorChain(token string) ([]string, error)

ActorChain returns the actors recorded in a delegated JWT, outermost first. Decoded without signature verification — display and audit only.

func (*DelegationChain) ConsentURL

func (c *DelegationChain) ConsentURL(sessionID string, scopes []string, state string) (string, error)

ConsentURL builds the URL where the user grants the agent permission to act on their behalf. Redirect the user there; consent returns them to the chain's redirect URI with an authorization code.

sessionID correlates the consent with the later exchange. state defaults to "session:<sessionID>".

func (*DelegationChain) DelegateToSubAgent

func (c *DelegationChain) DelegateToSubAgent(ctx context.Context, sessionID, subAgentToken string, scopes ...string) (string, error)

DelegateToSubAgent mints a token for the chain user → this agent → sub-agent. Each hop may only narrow scopes, and LumoAuth caps the chain at MaxDelegationDepth.

subAgentToken is the sub-agent's own client-credentials token.

func (*DelegationChain) DelegatedToken

func (c *DelegationChain) DelegatedToken(ctx context.Context, sessionID string) (string, error)

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.

func (*DelegationChain) HandleConsentCallback

func (c *DelegationChain) HandleConsentCallback(ctx context.Context, sessionID, authorizationCode string) error

HandleConsentCallback exchanges the authorization code from the consent callback for the user's tokens and stores them under sessionID.

func (*DelegationChain) HasDelegation

func (c *DelegationChain) HasDelegation(sessionID string) bool

HasDelegation reports whether a delegated token is cached for a session.

func (*DelegationChain) Revoke

func (c *DelegationChain) Revoke(ctx context.Context, sessionID string) error

Revoke ends a delegation: it revokes the user's refresh token at the server, which invalidates every derived token, and drops the local state. Local state is cleared even if the server call fails, so a revoked session never keeps serving requests from cache.

func (*DelegationChain) RevokeAll

func (c *DelegationChain) RevokeAll(ctx context.Context) error

RevokeAll revokes every active session, returning the first error while still attempting the rest.

func (*DelegationChain) SetUserToken

func (c *DelegationChain) SetUserToken(sessionID, accessToken string) error

SetUserToken registers a user access token you already hold, skipping the consent redirect. Without a refresh token the SDK cannot renew it, so the delegation lasts only as long as the token does.

type DelegationResource

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

DelegationResource covers the RFC 8693 delegation primitives — the raw operations behind the Chain of Agency.

For session-tracked delegation with consent handling and refresh, use DelegationChain, which wraps this resource.

func (*DelegationResource) ConsentURL

func (r *DelegationResource) ConsentURL(params ConsentURLParams) (string, error)

ConsentURL builds the URL where a user grants an agent delegated access. It requests offline access so the agent receives a refresh token.

func (*DelegationResource) Exchange

func (r *DelegationResource) Exchange(ctx context.Context, subjectToken, actorToken string, scopes ...string) (*TokenResponse, error)

Exchange combines a subject token (the user) with an actor token (the agent) into a delegated token. The resulting JWT carries an `act` claim recording the chain, so every downstream action is attributable to both.

func (*DelegationResource) ExchangeCode

func (r *DelegationResource) ExchangeCode(ctx context.Context, params ExchangeCodeParams) (*TokenResponse, error)

ExchangeCode trades a consent callback code for the user's tokens.

func (*DelegationResource) ParseActorChain

func (r *DelegationResource) ParseActorChain(token string) ([]string, error)

ParseActorChain is the method form of the package-level function, for callers who already hold the namespace.

func (*DelegationResource) RefreshUserToken

func (r *DelegationResource) RefreshUserToken(ctx context.Context, params RefreshTokenParams) (*TokenResponse, error)

RefreshUserToken refreshes a user's delegated access token.

func (*DelegationResource) Revoke

func (r *DelegationResource) Revoke(ctx context.Context, params RevokeParams) error

Revoke invalidates a delegation's refresh token, which also invalidates every token derived from it.

func (*DelegationResource) Subject

func (r *DelegationResource) Subject(token string) (string, error)

Subject is the method form of TokenSubject.

type EvaluateTaskParams

type EvaluateTaskParams struct {
	// Result is TaskResultCompleted, TaskResultFailed, or
	// TaskResultCancelled. Defaults to completed.
	Result string
	// Notes are attached to the audit record.
	Notes string
}

EvaluateTaskParams describes how a task ended.

type ExchangeCodeParams

type ExchangeCodeParams struct {
	// Code is the authorization code from the callback. Required.
	Code string
	// RedirectURI must match the one used to obtain the code. Required.
	RedirectURI string
	// ClientID is the OAuth client. Required.
	ClientID string
	// ClientSecret is required for confidential clients.
	ClientSecret string
	// CodeVerifier is the PKCE verifier matching the challenge sent to
	// the authorization endpoint.
	CodeVerifier string
}

ExchangeCodeParams describes an authorization-code exchange.

type ID

type ID string

ID is an identifier the API may send as either a JSON string or a JSON number (user IDs in particular). It decodes both into a string.

func (ID) MarshalJSON

func (id ID) MarshalJSON() ([]byte, error)

MarshalJSON emits the ID as a JSON string, or as a number when it is one.

func (ID) String

func (id ID) String() string

String returns the identifier as text.

func (*ID) UnmarshalJSON

func (id *ID) UnmarshalJSON(data []byte) error

UnmarshalJSON accepts a string, a number, or null.

type JITContext

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

JITContext manages one ephemeral task and the scoped permissions requested under it.

The lifecycle is: create a task, request permissions against it, exchange approved requests for short-lived tokens, then complete the task — which revokes every token issued under it. Close makes that cleanup a defer:

jit, err := lumoauth.NewJITContext(agent)
if err != nil {
    return err
}
defer jit.Close(ctx)

if _, err := jit.CreateTask(ctx, lumoauth.CreateTaskParams{Name: "Analyse Q4 report"}); err != nil {
    return err
}
result, err := jit.RequestPermission(ctx, map[string]any{
    "type": "file_access", "actions": []string{"read"}, "identifier": "report_q4.pdf",
}, nil)
if err != nil {
    return err
}
if result.Approved() {
    token, err := jit.Token(ctx, result.RequestID)
    …
}

func NewJITContext

func NewJITContext(source TokenSource, opts ...JITContextOption) (*JITContext, error)

NewJITContext builds a JIT context over any authenticated token source.

Example

A JIT task scopes permissions to one unit of work, and revokes every token it issued when the task closes.

package main

import (
	"context"
	"fmt"
	"log"

	lumoauth "github.com/lumoauth/lumo-auth-go"
)

func main() {
	agent, err := lumoauth.NewAgent(lumoauth.AgentConfig{})
	if err != nil {
		log.Fatal(err)
	}

	jit, err := lumoauth.NewJITContext(agent)
	if err != nil {
		log.Fatal(err)
	}

	ctx := context.Background()
	defer jit.Close(ctx) // completes the task and revokes its tokens

	if _, err := jit.CreateTask(ctx, lumoauth.CreateTaskParams{
		Name: "Analyse Q4 report",
		Type: "analysis",
	}); err != nil {
		log.Fatal(err)
	}

	result, err := jit.RequestPermission(ctx, map[string]any{
		"type":       "file_access",
		"actions":    []string{"read"},
		"identifier": "report_q4.pdf",
	}, &lumoauth.RequestPermissionOptions{
		Justification: "The user asked for a Q4 summary",
	})
	if err != nil {
		log.Fatal(err)
	}
	if !result.Approved() {
		fmt.Println("not approved:", result.Status)
		return
	}

	token, err := jit.Token(ctx, result.RequestID)
	if err != nil {
		log.Fatal(err)
	}
	_ = token // present it to the resource
}

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.

func (*JITContext) Token

func (j *JITContext) Token(ctx context.Context, requestID string) (string, error)

Token exchanges an approved request for a short-lived JIT access token.

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 PublicJWK

func PublicJWK(privateKeyPEM, kid string) (JWK, error)

PublicJWK derives the public JWK for a PEM private key.

func (*JWK) PublicKey

func (j *JWK) PublicKey() (crypto.PublicKey, error)

PublicKey converts a JWK into a Go public key for signature verification.

func (*JWK) Thumbprint

func (j *JWK) Thumbprint() (string, error)

Thumbprint computes the RFC 7638 JWK thumbprint — the base64url SHA-256 of the key's canonical form. AAuth uses it as the `jkt` value binding a token to a key.

type JWKS

type JWKS struct {
	Keys []JWK `json:"keys"`
}

JWKS is a JSON Web Key Set, as published at a jwks_uri.

func FetchIssuerJWKS

func FetchIssuerJWKS(ctx context.Context, issuer string, httpClient *http.Client) (*JWKS, error)

FetchIssuerJWKS retrieves an AAuth issuer's signing keys from {issuer}/aauth/jwks.json.

func (*JWKS) Find

func (s *JWKS) Find(kid string) (*JWK, bool)

Find returns the key with the given kid.

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

func NewJWKSCache(issuer string, ttl time.Duration, httpClient *http.Client) *JWKSCache

NewJWKSCache builds a cache for one issuer. A ttl of 0 means one hour.

func (*JWKSCache) Get

func (c *JWKSCache) Get(ctx context.Context) (*JWKS, error)

Get returns the cached key set, fetching it when absent or stale.

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.

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

func (t *JitTask) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes the typed fields and retains the whole object.

type Keypair

type Keypair struct {
	// PrivateKeyPEM is the PKCS#8 private key. Store it in a secret manager.
	PrivateKeyPEM string
	// PublicKeyPEM is the SPKI public key.
	PublicKeyPEM string
	// JWK is the public key with use "sig" and the requested kid.
	JWK JWK
	// JWKS is a key set ready to publish at /.well-known/jwks.json.
	JWKS JWKS
}

Keypair is a freshly generated AAuth signing key.

func GenerateKeypair

func GenerateKeypair(kid string) (*Keypair, error)

GenerateKeypair creates an Ed25519 key pair for AAuth. Pass an empty kid to use DefaultKid.

keypair, err := lumoauth.GenerateKeypair("")
// Register keypair.JWKS with LumoAuth, keep keypair.PrivateKeyPEM secret.
Example

Publish a JWKS so LumoAuth can verify the agent's signatures.

package main

import (
	"fmt"
	"log"

	lumoauth "github.com/lumoauth/lumo-auth-go"
)

func main() {
	keypair, err := lumoauth.GenerateKeypair("")
	if err != nil {
		log.Fatal(err)
	}

	// Store this in a secret manager.
	_ = keypair.PrivateKeyPEM
	// Register this with LumoAuth, or serve it at /.well-known/jwks.json.
	_ = keypair.JWKS

	fmt.Println(keypair.JWK.Kty, keypair.JWK.Crv, keypair.JWK.Kid)
}
Output:
OKP Ed25519 key-1

type McpResource

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

McpResource exchanges the caller's token for one scoped to a secured MCP server (RFC 8693, with the server id as the audience).

func (*McpResource) Token

func (r *McpResource) Token(ctx context.Context, serverID, subjectToken string) (string, error)

Token returns an access token scoped to one MCP server.

token, err := client.Mcp.Token(ctx, "urn:mcp:financial-data", "")

serverID is the audience identifier of the target server. Pass an empty subjectToken to exchange the client's own bearer token.

func (*McpResource) TokenDetailed

func (r *McpResource) TokenDetailed(ctx context.Context, serverID, subjectToken string) (*McpToken, error)

TokenDetailed is Token with the full token response — lifetime, type, and granted scope.

type McpToken

type McpToken struct {
	AccessToken string `json:"access_token"`
	TokenType   string `json:"token_type,omitempty"`
	ExpiresIn   int    `json:"expires_in,omitempty"`
	Scope       string `json:"scope,omitempty"`
}

McpToken is an audience-scoped token for a secured MCP server.

type NetworkError

type NetworkError struct {
	*BaseError
}

NetworkError is returned when a request fails before an HTTP response was received (DNS, connection, TLS, timeout, or a cancelled context).

type Option

type Option func(*clientConfig)

Option configures a Client. Options are applied in order.

func WithAPIKey

func WithAPIKey(apiKey string) Option

WithAPIKey authenticates with a tenant API key, sent as X-API-Key. Defaults to $LUMOAUTH_API_KEY.

func WithAccessToken

func WithAccessToken(token string) Option

WithAccessToken authenticates with a fixed bearer token. For tokens that expire, prefer WithTokenProvider so the SDK can pick up refreshes.

func WithBaseURL

func WithBaseURL(baseURL string) Option

WithBaseURL sets the LumoAuth instance URL. Defaults to $LUMOAUTH_URL, then DefaultBaseURL.

func WithHTTPClient

func WithHTTPClient(httpClient *http.Client) Option

WithHTTPClient supplies the *http.Client used for every request — the hook for custom transports, proxies, and instrumentation.

func WithHeader

func WithHeader(name, value string) Option

WithHeader adds a header to every request.

func WithOrgID

func WithOrgID(orgID string) Option

WithOrgID sets the organization slug. Required for org-scoped endpoints (ABAC, agents, JIT, approvals, OAuth). Defaults to $LUMOAUTH_ORG_ID.

func WithSkipCertValidation

func WithSkipCertValidation() Option

WithSkipCertValidation disables TLS certificate verification. Local development against a self-signed instance only.

func WithTimeout

func WithTimeout(timeout time.Duration) Option

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

func WithUserAgent(userAgent string) Option

WithUserAgent overrides the User-Agent sent with every request.

type Permission

type Permission struct {
	Slug        string `json:"slug"`
	Description string `json:"description,omitempty"`
	Source      string `json:"source,omitempty"`
}

Permission is one permission granted to a principal.

type PermissionBulkCheck

type PermissionBulkCheck struct {
	Results map[string]bool `json:"results"`
	UserID  ID              `json:"user_id,omitempty"`
	Context map[string]any  `json:"context,omitempty"`
}

PermissionBulkCheck is the result of a bulk permission check: Results maps each requested slug to its decision.

type PermissionCheck

type PermissionCheck struct {
	Allowed    bool           `json:"allowed"`
	Permission string         `json:"permission,omitempty"`
	UserID     ID             `json:"user_id,omitempty"`
	Context    map[string]any `json:"context,omitempty"`
}

PermissionCheck is the result of a single permission check.

type PermissionList

type PermissionList struct {
	UserID      ID           `json:"user_id,omitempty"`
	Permissions []Permission `json:"permissions"`
	Count       int          `json:"count,omitempty"`
}

PermissionList is the full set of permissions granted to a principal.

type PermissionMultiCheck

type PermissionMultiCheck struct {
	Allowed     bool           `json:"allowed"`
	Permissions []string       `json:"permissions,omitempty"`
	UserID      ID             `json:"user_id,omitempty"`
	Context     map[string]any `json:"context,omitempty"`
}

PermissionMultiCheck is the result of a check-any / check-all call.

type PermissionsResource

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

PermissionsResource covers RBAC permission checks for the authenticated principal: single checks, bulk checks, logical combinations, and listing.

The endpoints infer the organization from the credential, so this namespace works without an org ID.

func (*PermissionsResource) Check

func (r *PermissionsResource) Check(ctx context.Context, permission string, opts *CheckOptions) (bool, error)

Check reports whether the principal holds a permission.

ok, err := client.Permissions.Check(ctx, "document.edit", nil)

func (*PermissionsResource) CheckAll

func (r *PermissionsResource) CheckAll(ctx context.Context, permissions []string, opts *CheckOptions) (bool, error)

CheckAll reports whether the principal holds every one of the permissions (logical AND).

func (*PermissionsResource) CheckAllDetailed

func (r *PermissionsResource) CheckAllDetailed(ctx context.Context, permissions []string, opts *CheckOptions) (*PermissionMultiCheck, error)

CheckAllDetailed is CheckAll with the full response.

func (*PermissionsResource) CheckAny

func (r *PermissionsResource) CheckAny(ctx context.Context, permissions []string, opts *CheckOptions) (bool, error)

CheckAny reports whether the principal holds at least one of the permissions (logical OR).

func (*PermissionsResource) CheckAnyDetailed

func (r *PermissionsResource) CheckAnyDetailed(ctx context.Context, permissions []string, opts *CheckOptions) (*PermissionMultiCheck, error)

CheckAnyDetailed is CheckAny with the full response.

func (*PermissionsResource) CheckBulk

func (r *PermissionsResource) CheckBulk(ctx context.Context, permissions []string, opts *CheckOptions) (*PermissionBulkCheck, error)

CheckBulk evaluates many permissions in one round trip; the Results map holds one decision per requested slug.

func (*PermissionsResource) CheckDetailed

func (r *PermissionsResource) CheckDetailed(ctx context.Context, permission string, opts *CheckOptions) (*PermissionCheck, error)

CheckDetailed is Check with the full response — the permission slug, the principal it was evaluated for, and the context echoed back.

func (*PermissionsResource) List

List returns every permission granted to the authenticated principal.

func (*PermissionsResource) ListSlugs

func (r *PermissionsResource) ListSlugs(ctx context.Context) ([]string, error)

ListSlugs returns just the permission slugs granted to the principal.

type RefreshParams

type RefreshParams struct {
	// RefreshToken is the token from a prior response. Required.
	RefreshToken string
	// ResourceToken must be a FRESH resource token for the target
	// resource — the server requires one on every refresh. Required.
	ResourceToken string
	// Scope optionally narrows the refreshed token; it must be a subset
	// of the original grant.
	Scope string
	// AgentToken is the `agent+jwt` presented in Agent-Auth. Required.
	AgentToken string
}

RefreshParams describes an auth-token refresh.

type RefreshTokenParams

type RefreshTokenParams struct {
	// RefreshToken is the token to redeem. Required.
	RefreshToken string
	// ClientID is the OAuth client. Required.
	ClientID string
	// ClientSecret is required for confidential clients.
	ClientSecret string
	// Scopes optionally narrows the refreshed token; must be a subset of
	// the original grant.
	Scopes []string
}

RefreshTokenParams describes a refresh-token grant.

type RegisterParams

type RegisterParams struct {
	// Name is the human-readable agent name ("Document Analyser"). Required.
	Name string
	// ClientID is the OAuth client identifying the agent. Required.
	ClientID string
	// Description explains what the agent is for.
	Description string
	// Capabilities are the slugs the agent declares
	// (e.g. "read:documents", "tool:search_web").
	Capabilities []string
	// JWKSURI points at the agent's public JWKS. Required for AAuth and
	// other proof-of-possession flows.
	JWKSURI string
}

RegisterParams describes an agent registration.

type RequestPermissionOptions

type RequestPermissionOptions struct {
	// Justification is the human-readable reason shown to an approver.
	Justification string
	// TTL is the requested token lifetime in seconds, capped at JitMaxTTL.
	TTL int
	// NoWait returns a pending request immediately instead of polling for
	// the human decision.
	NoWait bool
	// PollInterval is the delay between status polls.
	// Defaults to DefaultJitPollInterval.
	PollInterval time.Duration
	// PollTimeout bounds the wait for approval.
	// Defaults to DefaultJitPollTimeout.
	PollTimeout time.Duration
	// TaskID overrides the context's current task.
	TaskID string
}

RequestPermissionOptions tunes a JIT permission request.

type RequestPermissionParams

type RequestPermissionParams struct {
	// TaskID is the task the permission attaches to. Required.
	TaskID string
	// AuthorizationDetails is the RFC 9396 structured object, e.g.
	//   {"type": "file_access", "actions": ["read"], "identifier": "report.pdf"}
	// Required.
	AuthorizationDetails map[string]any
	// Justification is the human-readable reason shown to an approver.
	Justification string
	// TTL is the requested token lifetime in seconds; capped at JitMaxTTL.
	// Defaults to JitDefaultTTL.
	TTL int
}

RequestPermissionParams describes an RFC 9396 permission request.

type RevokeParams

type RevokeParams struct {
	// Token is the access or refresh token to revoke. Required.
	Token string
	// TokenTypeHint is "access_token" or "refresh_token".
	TokenTypeHint string
	// ClientID and ClientSecret authenticate the revocation.
	ClientID     string
	ClientSecret string
}

RevokeParams describes a token revocation.

type Route

type Route struct {
	Method string
	Path   string
}

Route is a single endpoint: an HTTP method and a path template.

type SessionTokens

type SessionTokens struct {
	AccessToken  string    `json:"access_token"`
	RefreshToken string    `json:"refresh_token,omitempty"`
	IDToken      string    `json:"id_token,omitempty"`
	TokenType    string    `json:"token_type,omitempty"`
	ExpiresAt    time.Time `json:"expires_at,omitempty"`
	Scope        string    `json:"scope,omitempty"`
}

SessionTokens are the OAuth tokens held for a signed-in user.

func TokensFromContext

func TokensFromContext(ctx context.Context) *SessionTokens

TokensFromContext returns the signed-in user's OAuth tokens, or nil.

func (*SessionTokens) Expired

func (t *SessionTokens) Expired() bool

Expired reports whether the access token has passed its expiry. Tokens with no known expiry never report expired.

type SignOptions

type SignOptions struct {
	// Body is the exact request body being signed. Empty means no body.
	Body []byte
	// ContentType is the media type of the body.
	// Defaults to "application/json".
	ContentType string
	// AgentToken is the `agent+jwt` presented in the Agent-Auth header. It
	// travels outside the signature.
	AgentToken string
	// Authorization is the value of a covered Authorization header, when
	// the request carries one (proof-of-possession requests do).
	Authorization string
	// SignatureKey is the value of a covered Signature-Key header.
	SignatureKey string
	// Created overrides the signature timestamp. Testing only — the server
	// rejects timestamps more than 60s from its own clock.
	Created int64
	// Nonce overrides the generated nonce. Testing only — the server
	// treats nonces as single-use.
	Nonce string
}

SignOptions configures SignRequest.

type TokenExchangeParams

type TokenExchangeParams struct {
	// SubjectToken is the token representing the principal being acted
	// for. Required.
	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 scopes the issued token to one resource (an MCP server id,
	// for instance).
	Audience string
	// Scopes optionally narrows the issued token.
	Scopes []string
}

TokenExchangeParams describes an RFC 8693 token exchange.

type TokenProvider

type TokenProvider func(ctx context.Context) (string, error)

TokenProvider returns the bearer token to authenticate a request with. It is called once per request, so implementations can refresh transparently.

type TokenResponse

type TokenResponse struct {
	AccessToken     string `json:"access_token"`
	RefreshToken    string `json:"refresh_token,omitempty"`
	IDToken         string `json:"id_token,omitempty"`
	TokenType       string `json:"token_type,omitempty"`
	ExpiresIn       int    `json:"expires_in,omitempty"`
	Scope           string `json:"scope,omitempty"`
	IssuedTokenType string `json:"issued_token_type,omitempty"`
}

TokenResponse is an OAuth 2.1 token endpoint response.

func (*TokenResponse) Scopes

func (t *TokenResponse) Scopes() []string

Scopes splits the space-separated Scope field.

type TokenSource

type TokenSource interface {
	BaseURL() string
	OrgID() string
	AccessToken(ctx context.Context) (string, error)
}

TokenSource is the minimal contract JITContext needs: where the instance lives, which org it belongs to, and a bearer token that stays fresh. *Agent satisfies it.

type User

type User struct {
	Sub           string `json:"sub"`
	Email         string `json:"email,omitempty"`
	EmailVerified bool   `json:"email_verified,omitempty"`
	Name          string `json:"name,omitempty"`
	GivenName     string `json:"given_name,omitempty"`
	FamilyName    string `json:"family_name,omitempty"`
	Picture       string `json:"picture,omitempty"`
}

User is the signed-in principal, as returned by the UserInfo endpoint.

func UserFromContext

func UserFromContext(ctx context.Context) *User

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

func (u *UserInfo) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes the typed claims and retains the whole object.

type ValidationError

type ValidationError struct {
	*BaseError
	// Issues holds per-field detail when the server supplied it.
	Issues []any
}

ValidationError is returned when client-side validation fails: bad arguments, or a response whose shape the SDK cannot use.

func NewValidationError

func NewValidationError(message string, issues ...any) *ValidationError

NewValidationError builds a ValidationError. Exported so callers writing their own resources on top of Client can produce consistent errors.

type VerifyOptions

type VerifyOptions struct {
	// Issuer is the trusted issuer URL, e.g.
	// "https://app.lumoauth.dev/orgs/acme-corp/api/v1". Required.
	Issuer string
	// Resource is your resource identifier; it must equal the token's
	// audience. Required.
	Resource string
	// JWKS supplies the issuer's keys directly, skipping the fetch. Use
	// it with a cache in front of a hot path.
	JWKS *JWKS
	// HTTPClient fetches the JWKS. Defaults to a 30s-timeout client.
	HTTPClient *http.Client
	// ClockSkew tolerated on the expiry check. Default: 0, like the server.
	ClockSkew time.Duration
}

VerifyOptions configures VerifyAuthToken.

type WaitOptions

type WaitOptions struct {
	// PollInterval is the delay between status polls.
	// Defaults to DefaultApprovalPollInterval.
	PollInterval time.Duration
	// Timeout bounds the wait. Defaults to DefaultApprovalTimeout.
	Timeout time.Duration
}

WaitOptions tunes approval polling.

type WebAuth

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

WebAuth drives the browser sign-in flow.

func NewWebAuth

func NewWebAuth(cfg WebConfig) (*WebAuth, error)

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))
}

func (*WebAuth) CallbackHandler

func (w *WebAuth) CallbackHandler() http.HandlerFunc

CallbackHandler completes the sign-in flow.

func (*WebAuth) Client

func (w *WebAuth) Client() *Client

Client returns a LumoAuth client bound to this deployment and org, for calls made outside the sign-in flow. It carries no user credentials — use ClientForRequest for those.

func (*WebAuth) ClientForRequest

func (w *WebAuth) ClientForRequest(req *http.Request) (*Client, error)

ClientForRequest returns a client authenticated as the signed-in user of this request, so authorization checks run under their identity:

client, err := auth.ClientForRequest(req)
if err != nil {
    return err
}
ok, err := client.Permissions.Check(req.Context(), "document.edit", nil)

func (*WebAuth) LoginHandler

func (w *WebAuth) LoginHandler() http.HandlerFunc

LoginHandler starts the sign-in flow. Mount it directly when you would rather wire routes yourself than mount Router.

func (*WebAuth) LogoutHandler

func (w *WebAuth) LogoutHandler() http.HandlerFunc

LogoutHandler clears the session.

func (*WebAuth) Middleware

func (w *WebAuth) Middleware(next http.Handler) http.Handler

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

func (w *WebAuth) RefreshSession(rw http.ResponseWriter, req *http.Request) (bool, error)

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

func (w *WebAuth) RequireAuth(next http.Handler) http.Handler

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

func (w *WebAuth) RequireAuthRedirect(loginPath string) func(http.Handler) http.Handler

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

func (w *WebAuth) Router() http.Handler

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.

func (*WebAuth) Tokens

func (w *WebAuth) Tokens(req *http.Request) (*SessionTokens, error)

Tokens reads the signed-in user's OAuth tokens from the session.

func (*WebAuth) User

func (w *WebAuth) User(req *http.Request) (*User, error)

User reads the signed-in user straight from the request's session, without requiring Middleware. It returns nil when nobody is signed in.

type WebConfig

type WebConfig struct {
	// BaseURL is the LumoAuth deployment, e.g. "https://app.lumoauth.dev".
	// Defaults to $LUMOAUTH_URL, then DefaultBaseURL.
	BaseURL string
	// Organization is the tenant slug that owns the OAuth client.
	// Defaults to $LUMOAUTH_ORG_ID.
	Organization string
	// ClientID is the OAuth client registered for this app. Required.
	ClientID string
	// ClientSecret is required for confidential clients; omit for public
	// ones, which rely on PKCE alone.
	ClientSecret string
	// SessionSecret keys the cookie store. Use at least 32 random bytes,
	// and keep it stable across restarts or every session is invalidated.
	// Required.
	SessionSecret string
	// CallbackPath is the absolute path LumoAuth redirects back to. It
	// must match a redirect URI registered on the OAuth client.
	// Defaults to "/auth/callback".
	CallbackPath string
	// Scope is the space-separated scope list.
	// Defaults to "openid profile email".
	Scope string
	// PostLoginRedirect is where users land after signing in.
	// Defaults to "/".
	PostLoginRedirect string
	// PostLogoutRedirect is where users land after signing out.
	// Defaults to "/".
	PostLogoutRedirect string
	// HTTPClient overrides the client used for token exchange and
	// UserInfo. Defaults to a 10s-timeout client.
	HTTPClient *http.Client
	// CookieName is the session cookie's name. Defaults to "lumo_session".
	CookieName string
	// CookieSecure controls the Secure flag. Nil means true — the cookie
	// is only sent over HTTPS. Set Bool(false) for local development over
	// plain HTTP, and leave it alone in production.
	CookieSecure *bool
	// SessionMaxAge bounds the session cookie's lifetime.
	// Defaults to 30 days.
	SessionMaxAge time.Duration
	// SkipCertValidation disables TLS verification. Local development only.
	SkipCertValidation bool
}

WebConfig configures NewWebAuth.

type ZanzibarCheck

type ZanzibarCheck struct {
	Allowed  bool   `json:"allowed"`
	Object   string `json:"object,omitempty"`
	Relation string `json:"relation,omitempty"`
	Subject  string `json:"subject,omitempty"`
	User     string `json:"user,omitempty"`
}

ZanzibarCheck is the result of a relationship check.

type ZanzibarResource

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

ZanzibarResource covers Google-Zanzibar-style relationship-based access control: does a subject have a relation to an object?

Objects and subjects are "namespace:id" tuples — "document:readme", "user:alice" — and subjects may name a relation ("group:eng#member").

func (*ZanzibarResource) Check

func (r *ZanzibarResource) Check(ctx context.Context, object, relation, subject string) (bool, error)

Check reports whether the relationship holds, directly or by inheritance.

ok, err := client.Zanzibar.Check(ctx, "document:readme", "viewer", "user:bob")
Example

Relationship-based checks read as questions about a tuple.

package main

import (
	"context"
	"fmt"
	"log"
	"os"

	lumoauth "github.com/lumoauth/lumo-auth-go"
)

func main() {
	client, _ := lumoauth.New(
		lumoauth.WithAPIKey(os.Getenv("LUMOAUTH_API_KEY")),
		lumoauth.WithOrgID("acme-corp"),
	)

	allowed, err := client.Zanzibar.Check(context.Background(),
		"document:readme", lumoauth.RelationViewer, "user:bob")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(allowed)
}

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")

func (*ZanzibarResource) IsAdmin

func (r *ZanzibarResource) IsAdmin(ctx context.Context, object, subject string) (bool, error)

IsAdmin reports whether the subject administers the object.

func (*ZanzibarResource) IsEditor

func (r *ZanzibarResource) IsEditor(ctx context.Context, object, subject string) (bool, error)

IsEditor reports whether the subject can edit the object.

func (*ZanzibarResource) IsMember

func (r *ZanzibarResource) IsMember(ctx context.Context, object, subject string) (bool, error)

IsMember reports whether the subject is a member of the object.

func (*ZanzibarResource) IsOwner

func (r *ZanzibarResource) IsOwner(ctx context.Context, object, subject string) (bool, error)

IsOwner reports whether the subject owns the object.

func (*ZanzibarResource) IsViewer

func (r *ZanzibarResource) IsViewer(ctx context.Context, object, subject string) (bool, error)

IsViewer reports whether the subject can view the object.

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.

Jump to

Keyboard shortcuts

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