lumoauth

package module
v1.5.0 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2026 License: MIT Imports: 35 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

The Go SDK for LumoAuth. Use it to check what a user or an AI agent is allowed to do, to sign users in to a net/http app, and to give AI agents their own identity. It covers the following:

  • Authorization checks: roles and permissions (RBAC), relationships (Zanzibar) and attribute policies (ABAC).
  • Sign-in for web apps with OAuth 2.1 and PKCE.
  • AI agents: agent credentials, human approvals, Just-in-Time (JIT) permissions, delegation and MCP tokens.
  • AAuth, the protocol for cryptographic agent identity, with RFC 9421 request signing.
  • Verification of AAuth tokens on your own resource server.

The SDK has the same namespaces and the same error codes as the JS and Python SDKs. Its RFC 9421 signatures match theirs byte for byte.

Contents

Requirements

  • Go 1.22 or later.
  • One dependency: github.com/gorilla/sessions, for the cookie session of the web sign-in helper. Everything else uses the standard library.
  • A LumoAuth organization. The hosted instances are https://app.lumoauth.dev (US) and https://eu.app.lumoauth.dev (EU).

Install

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

Quick start

Check a permission from a backend service
package main

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

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

func main() {
    ctx := context.Background()

    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(ctx, "document.edit", nil)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println("may edit documents:", allowed)
}

With an organization API key, the check runs for the user who created the key. To check a different user, see Check permissions.

Run an AI agent
agent, err := lumoauth.NewAgent(lumoauth.AgentConfig{}) // reads the environment variables
if err != nil {
    log.Fatal(err)
}

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

NewAgent reads LUMOAUTH_URL, LUMOAUTH_ORG_ID, AGENT_CLIENT_ID and AGENT_CLIENT_SECRET. The agent gets its token on the first call and renews it before it expires.

Core concepts

Organization and base URL

Every LumoAuth customer has an organization. Its slug (for example acme-corp) appears in most API paths as /orgs/{orgId}/api/v1/.... Set it with WithOrgID or LUMOAUTH_ORG_ID. Calls that need an organization return a ConfigError when it is missing.

The base URL is the LumoAuth instance. It defaults to https://app.lumoauth.dev. Set https://eu.app.lumoauth.dev when your organization is in the EU region.

Credentials

The SDK sends exactly one credential with each request. Which calls work depends on the kind of credential that you use.

Credential How you set it Sent as What it may call
Organization API key (lmk_…) WithAPIKey or LUMOAUTH_API_KEY X-API-Key header The admin API, client registration, and the permission checks (Permissions.Check*, Zanzibar.Check and Expand). Nothing else.
User access token WithAccessToken, WithTokenProvider, or WebAuth.ClientForRequest Authorization: Bearer Calls about the signed-in user. Some calls need a scope; see Scopes.
Agent credential NewAgent (client credentials), or an agk_… key passed as a bearer token Authorization: Bearer The agent, approval, JIT and MCP calls, and the permission checks. The agent's capabilities determine what it may do.

When both a token and an API key are configured, the token wins and the API key is not sent. The server rejects requests that carry both.

Scopes

A user access token carries scopes. These are the permissions that the user granted to your app when they signed in. Most calls need no special scope. A few need one:

Call Scope that a user access token needs
Permissions.List, Permissions.ListSlugs authz:read
ABAC checks and attribute reads (Abac.Check, CheckBulk, IsAllowed, MyAttributes, ResourceAttributes, AttributeDefinitions) abac:read
ABAC attribute writes (Abac.SetUserAttribute, SetResourceAttribute) abac:write
Jit.Pending (the list for human review) jit:approve
Agents.Register admin:agents:write. Organization API keys cannot register agents.
Permission checks, Zanzibar.Check, Agents.Ask, Agents.Me, Auth.UserInfo none

The admin scope satisfies every row. A check about another user or agent (CheckOptions.UserID or AgentID, or a Zanzibar subject other than yourself) needs authz:check, and so does Zanzibar.Expand. Agent credentials do not use these scopes. The agent's capabilities apply instead.

Request a scope when the user signs in, for example by adding it to WebConfig.Scope. When the token lacks a scope, the server answers 403. The error lists the missing scopes in APIError.RequiredScopes; see Errors.

Configuration

lumoauth.New options
Option What it sets Default
WithBaseURL(url) The LumoAuth instance $LUMOAUTH_URL, then https://app.lumoauth.dev
WithOrgID(slug) The organization slug $LUMOAUTH_ORG_ID
WithAPIKey(key) An organization API key, sent as X-API-Key $LUMOAUTH_API_KEY
WithAccessToken(token) A fixed bearer token none
WithTokenProvider(fn) A function that returns a bearer token for each request; use it for tokens that you refresh none
WithTimeout(d) The timeout of each request 30 seconds
WithHTTPClient(c) Your own *http.Client, for proxies or instrumentation a new client
WithHeader(name, value) An extra header on every request none
WithUserAgent(ua) The User-Agent header lumoauth-go/<version>
WithSkipCertValidation() Turns off TLS verification. Use it for local development only. off
WithDPoP(signer) Binds every token the client obtains to a DPoP key, and presents bound tokens with the DPoP scheme. See DPoP. off

New returns a ConfigError when no credential is configured. It needs an API key, an access token or a token provider.

Environment variables
Variable Read by Meaning
LUMOAUTH_URL every constructor The LumoAuth instance
LUMOAUTH_ORG_ID every constructor The organization slug
LUMOAUTH_API_KEY New The organization API key
AGENT_CLIENT_ID NewAgent The agent's OAuth client ID
AGENT_CLIENT_SECRET NewAgent The agent's OAuth client secret

A value that you pass in code always wins over the environment variable.

AgentConfig
Field Meaning Default
BaseURL, OrgID As above the environment variables
ClientID, ClientSecret The agent's OAuth client $AGENT_CLIENT_ID, $AGENT_CLIENT_SECRET
PrivateKey A *ClientAssertionSigner for a Private key JWT agent: it signs a client assertion instead of sending a secret the PEM key in $AGENT_PRIVATE_KEY, kid from $AGENT_KEY_ID
Issuer The organization's issuer identifier, the assertion's aud IssuerFor(BaseURL, OrgID)
Scopes Scopes to request when the agent authenticates the defaults that are registered for the agent
RedirectURI The callback URL of the consent flow for delegation none
Timeout, HTTPClient, SkipCertValidation As for New 30 seconds, a new client, off
DPoP A *DPoPSigner; the agent's tokens are then bound to its key none

WebConfig and AAuthConfig are described in Sign users in and AAuth.

Guides

In all of the examples, ctx is a context.Context and client is a *lumoauth.Client from lumoauth.New.

Check permissions

A permission is a slug such as document.edit. The user gets it through a role.

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

// The full answer, including the user ID that the server checked.
result, err := client.Permissions.CheckDetailed(ctx, "document.edit", nil)

// Several permissions in one request. The result maps each slug to true or false.
bulk, err := client.Permissions.CheckBulk(ctx, []string{"document.read", "document.edit"}, nil)
fmt.Println(bulk.Results["document.edit"])

// True when the user has at least one of the permissions, or all of them.
anyOf, err := client.Permissions.CheckAny(ctx, []string{"billing.view", "billing.manage"}, nil)
allOf, err := client.Permissions.CheckAll(ctx, []string{"report.read", "report.export"}, nil)

CheckOptions adds optional values to any check:

  • Context passes attributes to ABAC policies that apply to the same decision.
  • UserID asks about another user instead of the caller. It must be the user's LumoAuth ID, which is a UUID. AgentID does the same for an agent (its agt_… ID). Set at most one of them.
allowed, err := client.Permissions.Check(ctx, "document.edit", &lumoauth.CheckOptions{
    UserID: "01a176cb-4095-7bb1-b3fe-7a9b8943e0cf",
})

The SDK sends the ID as the request's subject. Asking about someone other than yourself needs the authz:check scope or the authz.check permission. An organization API key can hold the authz:check scope. Without that right, the server answers 403 with the code INSUFFICIENT_PERMISSIONS. An ID that is not in your organization gets 404 SUBJECT_NOT_FOUND.

To list all of the permissions that the caller has, use List or ListSlugs. These calls need a user access token with the authz:read scope. An organization API key cannot hold that scope, so the server rejects the call with 403.

slugs, err := client.Permissions.ListSlugs(ctx) // []string{"document.read", ...}
Check relationships (Zanzibar)

Zanzibar checks answer questions such as "is Bob a viewer of this document?". Objects are written type:id and subjects are written user:id.

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

// Helpers for the common relations.
ok, err = client.Zanzibar.IsViewer(ctx, "document:readme", "user:bob")
ok, err = client.Zanzibar.IsEditor(ctx, "document:readme", "user:bob")
ok, err = client.Zanzibar.IsOwner(ctx, "document:readme", "user:bob")
ok, err = client.Zanzibar.IsMember(ctx, "team:design", "user:bob")
ok, err = client.Zanzibar.IsAdmin(ctx, "workspace:acme", "user:bob")

// Expand returns the tree of everyone who holds a relation.
tree, err := client.Zanzibar.Expand(ctx, "document:readme", "viewer")

Expand returns a ZanzibarUsersetNode. Each node has a Type (union, intersection or leaf), its Children, and for leaves the Subjects. Expanding needs the right to ask about other subjects: the authz.check permission or the authz:check scope.

Check attribute policies (ABAC)

ABAC policies grant or deny access based on attributes of the user, the resource and the request. ABAC calls are made per organization, so the client needs an org ID. They need a user access token with abac:read (checks and reads) or abac:write (writes). Organization API keys are not accepted on these routes.

client, err := lumoauth.New(
    lumoauth.WithAccessToken(userAccessToken), // a user token with abac:read
    lumoauth.WithOrgID("acme-corp"),
)
if err != nil {
    return err
}

decision, err := client.Abac.Check(ctx, lumoauth.AbacCheckParams{
    ResourceType: "document",
    Action:       "read",
    ResourceID:   "doc-123",
    Context: map[string]any{
        "pep": map[string]any{"ip": endUserIP}, // a value that your gateway forwards
    },
})
if err != nil {
    return err
}
fmt.Println(decision.Allowed, decision.Reason, decision.MatchedPolicies)

The SDK sends Context as the request's environment object, which the policy engine reads. LumoAuth sets the keys ip, userAgent, requestMethod and requestPath from the request that it received. If you send values under those names, the server moves them under pep. To use an end user's IP address in a policy, send it as pep.ip and write the policy against pep.ip.

Other ABAC calls:

// Up to 100 checks in one request (AbacMaxBulkRequests). Results come back in request order.
// The server applies one environment to every check, so give every entry the same Context (or none).
env := map[string]any{"pep": map[string]any{"ip": endUserIP}}
results, err := client.Abac.CheckBulk(ctx, []lumoauth.AbacCheckParams{
    {ResourceType: "document", Action: "read", ResourceID: "doc-1", Context: env},
    {ResourceType: "document", Action: "delete", ResourceID: "doc-2", Context: env},
})
// Each result has Index, ResourceType, Action, ResourceID, Allowed and Reason.
// Error is set when the server could not evaluate that entry.

// A plain yes or no.
ok, err := client.Abac.IsAllowed(ctx, lumoauth.AbacCheckParams{ResourceType: "document", Action: "read"})

// Read attributes.
mine, err := client.Abac.MyAttributes(ctx)
attrs, err := client.Abac.ResourceAttributes(ctx, "document", "doc-123")
defs, err := client.Abac.AttributeDefinitions(ctx, lumoauth.AttributeTypeUser) // or "" for all types

// Write attributes (needs abac:write and the abac.manage permission).
err = client.Abac.SetUserAttribute(ctx, "user_42", "department", "finance")
err = client.Abac.SetResourceAttribute(ctx, "document", "doc-123", "classification", "internal")
Sign users in

WebAuth runs the OAuth 2.1 authorization code flow with PKCE. It stores the session in a signed cookie.

auth, err := lumoauth.NewWebAuth(lumoauth.WebConfig{
    Organization:  os.Getenv("LUMOAUTH_ORG_ID"),
    ClientID:      os.Getenv("LUMO_CLIENT_ID"),
    ClientSecret:  os.Getenv("LUMO_CLIENT_SECRET"),
    SessionSecret: os.Getenv("SESSION_SECRET"), // at least 32 random bytes
})
if err != nil {
    log.Fatal(err)
}

mux := http.NewServeMux()
mux.Handle("/auth/", auth.Router()) // /auth/login, /auth/callback, /auth/logout
mux.Handle("/", auth.Middleware(auth.RequireAuth(http.HandlerFunc(dashboard))))
log.Fatal(http.ListenAndServe(":8080", mux))
func dashboard(w http.ResponseWriter, req *http.Request) {
    user := lumoauth.UserFromContext(req.Context())
    fmt.Fprintf(w, "Hi %s", user.Email)
}

Register https://<your app>/auth/callback as a redirect URI on the OAuth client in the LumoAuth portal.

The router handles three paths:

  • /auth/login sends the user to LumoAuth. Add ?return_to=/some/path to come back to a page after sign-in. Only paths on your own site are accepted, so the parameter cannot be used as an open redirect.
  • /auth/callback exchanges the code for tokens and stores the session.
  • /auth/logout revokes the refresh token, clears the session and redirects to PostLogoutRedirect.

Router() returns a plain http.Handler, so you can mount it in chi, gorilla/mux or net/http. To mount the handlers one by one, use LoginHandler, CallbackHandler and LogoutHandler.

WebConfig fields:

Field Meaning Default
BaseURL The LumoAuth instance $LUMOAUTH_URL, then https://app.lumoauth.dev
Organization The organization slug that owns the OAuth client $LUMOAUTH_ORG_ID
ClientID The OAuth client of your app (required) none
ClientSecret Required for confidential clients. Public clients use PKCE alone. none
SessionSecret The key of the cookie store (required). Keep it the same across restarts, or every session ends. none
CallbackPath The callback path. It must match a registered redirect URI. /auth/callback
Scope The scopes to request, separated by spaces openid profile email
PostLoginRedirect, PostLogoutRedirect The pages that users go to after sign-in and sign-out /
CookieName The name of the session cookie lumo_session
CookieSecure The Secure flag of the cookie. nil means true. true
SessionMaxAge The longest lifetime of the session cookie 30 days
HTTPClient The client for the token and UserInfo calls a client with a 10-second timeout
SkipCertValidation Turns off TLS verification. Use it for local development only. off

Add scopes to Scope for the calls that your app makes as the user. Add authz:read when the app lists the user's permissions or reads roles from Agents.Me. Add abac:read when it runs ABAC checks as the user. For example: Scope: "openid profile email authz:read".

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

Protect net/http routes

WebAuth gives you middleware and helpers for handlers:

Helper What it does
auth.Middleware(next) Reads the session and puts the user and tokens on the request context. It does not block anyone.
auth.RequireAuth(next) Answers 401 when nobody is signed in. Wrap it inside Middleware.
auth.RequireAuthRedirect("/auth/login") Sends anonymous users to sign in and brings them back afterwards.
lumoauth.UserFromContext(ctx) Returns the signed-in *User, or nil. Use it inside Middleware.
lumoauth.TokensFromContext(ctx) Returns the session's *SessionTokens, or nil.
auth.User(req), auth.Tokens(req) Read the session directly, without Middleware.
auth.RefreshSession(w, req) Renews an expired access token with the stored refresh token. It reports whether a refresh happened.
auth.ClientForRequest(req) Returns a *Client that is authenticated as the signed-in user.

To check a permission for the signed-in user, run the check with their own token:

func editDocument(w http.ResponseWriter, req *http.Request) {
    client, err := auth.ClientForRequest(req)
    if err != nil {
        http.Error(w, "sign in first", http.StatusUnauthorized)
        return
    }
    ok, err := client.Permissions.Check(req.Context(), "document.edit", nil)
    if err != nil || !ok {
        http.Error(w, "forbidden", http.StatusForbidden)
        return
    }
    // ...
}
OAuth flows without the web helper

client.Auth exposes the OAuth endpoints directly. Use it when you manage sessions yourself. Calls to the token and revocation endpoints authenticate with the client ID and secret in the form body. They never send the client's API key or bearer token.

// 1. Send the user to LumoAuth.
url, err := client.Auth.AuthorizationURL(lumoauth.AuthorizationURLParams{
    ClientID:      clientID,
    RedirectURI:   "https://app.example.com/callback",
    State:         state,
    CodeChallenge: challenge, // PKCE; S256 is used by default
})

// 2. Exchange the code from the callback.
tokens, err := client.Auth.ExchangeCode(ctx, lumoauth.ExchangeCodeParams{
    Code: code, RedirectURI: "https://app.example.com/callback",
    ClientID: clientID, ClientSecret: clientSecret, CodeVerifier: verifier,
})

// 3. Refresh, read the profile, revoke.
fresh, err := client.Auth.RefreshToken(ctx, lumoauth.RefreshTokenParams{
    RefreshToken: tokens.RefreshToken, ClientID: clientID, ClientSecret: clientSecret,
})
profile, err := client.Auth.UserInfo(ctx, fresh.AccessToken)
err = client.Auth.Revoke(ctx, lumoauth.RevokeParams{
    Token: fresh.RefreshToken, TokenTypeHint: "refresh_token",
    ClientID: clientID, ClientSecret: clientSecret,
})

// Machine-to-machine: the client credentials grant.
m2m, err := client.Auth.ClientCredentials(ctx, clientID, clientSecret, "read:reports")

Set AccessType: "offline" on AuthorizationURLParams to ask for a refresh token.

Run an AI agent

An Agent authenticates with the OAuth client credentials grant. It caches the token, renews it 60 seconds before it expires, and shares one token request between concurrent callers.

agent, err := lumoauth.NewAgent(lumoauth.AgentConfig{
    OrgID:        "acme-corp",
    ClientID:     os.Getenv("AGENT_CLIENT_ID"),
    ClientSecret: os.Getenv("AGENT_CLIENT_SECRET"),
})
if err != nil {
    log.Fatal(err)
}

// Optional: authenticate now, so that a bad secret fails at startup.
if _, err := agent.Authenticate(ctx); err != nil {
    log.Fatal(err)
}

Ask before an action. Use this before an LLM calls a tool:

result, err := agent.Ask(ctx, "tickets.read", map[string]any{"ticket": "T-1042"})
if err != nil {
    return err
}
if !result.Allowed {
    return fmt.Errorf("not allowed: %s", result.Reason)
}

AgentAskResult holds Allowed, Reason, AuditID and the Context that the server evaluated. As with ABAC, the server sets ip, userAgent, requestMethod and requestPath itself and moves your values under pep.

Check capabilities and the budget:

// Returns an error that matches ErrPermissionDenied when the capability is missing.
// Names match as on the server: "tool:search_web" matches the stored
// "tool.search_web", and a held "tool.*" covers it.
if err := agent.RequireCapability(ctx, "tool:search_web"); err != nil {
    return err
}

// Returns an error that matches ErrBudgetExceeded when the daily token budget is used up.
if err := agent.CheckBudget(ctx); err != nil {
    return err
}

// LumoAuth does not see your model calls: report their tokens and cost so that
// token and cost limits apply. The result's Budget also refreshes CheckBudget.
_, err = agent.ReportUsage(ctx, resp.Usage.TotalTokens, 0.0042)

caps, err := agent.Capabilities(ctx)      // []string
budget, err := agent.Budget(ctx)          // MaxTokensPerDay, TokensUsedToday, ReportedExhausted
me, err := agent.Identity(ctx, false)     // identity, capabilities, workspace (cached)

The Agent has the namespaces Agents, Jit, Delegation, Approvals, Mcp and Permissions. agent.Client() returns the underlying *Client for the rest. agent.Register(ctx, params) creates or updates the agent's record in the organization's directory. When you call client.Agents.Register with a user access token, the token needs admin:agents:write or admin. Organization API keys cannot register agents.

Agents.Me returns the agent's capability roles when an agent calls it. A user access token without authz:read gets an empty Capabilities list.

Ask a human to approve an action

Before an action that cannot be undone, ask a person. LumoAuth sends a push notification to the user's phone. Require blocks until the user answers.

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("the user declined the transfer")
case errors.Is(err, lumoauth.ErrApprovalTimeout):
    return fmt.Errorf("nobody answered in time")
case errors.Is(err, lumoauth.ErrApprovalNotDelivered):
    return fmt.Errorf("no phone got the request; ask the user to check their email")
case err != nil:
    return err
}
// approval.Token is the credential for the action that the user approved.

The impact levels are ImpactLow, ImpactMedium (the default), ImpactHigh and ImpactCritical. Require polls every 1.5 seconds for up to 90 seconds. Change this with &lumoauth.WaitOptions{PollInterval: ..., Timeout: ...}.

Require returns an error for any answer other than approval. To handle a denial without an error, call Create, then Wait or Status:

pending, err := agent.Approvals.Create(ctx, params)
// ... later, or from another process:
result, err := agent.Approvals.Wait(ctx, pending.Token, nil)
if result.Approved() { /* ... */ }

Some requests never reach a phone. The SDK reports them as follows:

  • If the user has no enrolled push device, the server sends them an email notice. The email has no approval link, so nobody can approve the action in this call. Create returns a result with the status lumoauth.ApprovalEmailFallbackSent and an empty Token. There is nothing to poll. Require does not poll either. It returns an *ApprovalError with the code APPROVAL_NOT_DELIVERED and the reason email_fallback_sent. The server gives the same answer for an unknown user, so the endpoint does not reveal who has an account.
  • If the user has no device and the email could not be sent, the server answers 428. Create and Require both return an *ApprovalError with the code APPROVAL_NOT_DELIVERED and the reason no_enrolled_device.

Neither case counts as approval. Tell the user to check their email or to enrol a device:

var approvalErr *lumoauth.ApprovalError
if errors.As(err, &approvalErr) && approvalErr.Code == lumoauth.CodeApprovalNotDelivered {
    switch approvalErr.Reason {
    case lumoauth.ApprovalReasonEmailFallbackSent:
        // An email notice went out. Ask the user to enrol a device, then try again.
    case lumoauth.ApprovalReasonNoEnrolledDevice:
        // Nothing reached the user. Ask them to enrol a device.
    }
}

A portal test token cannot create approvals. The server answers 403 test_token_not_accepted.

Just-in-Time permissions

JIT permissions give an agent narrow, short-lived access for one task. Closing the task revokes every token that was issued for it.

jit, err := lumoauth.NewJITContext(agent)
if err != nil {
    return err
}
defer jit.Close(ctx) // completes the task and revokes its tokens

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)
    if err != nil {
        return err
    }
    resp, err := jit.Call(ctx, token, http.MethodGet, "https://files.example.com/report_q4.pdf", nil)
    // ... use resp, then close resp.Body
}

How a request is decided:

  • LumoAuth approves low-risk requests at once.
  • A higher-risk request stays pending until a person reviews it. RequestPermission polls every 5 seconds for up to 5 minutes. Set NoWait: true to return at once and poll with Status.
  • If the result is still pending after the wait, the wait timed out. It is not a denial.
  • A JIT token lasts 300 seconds by default (JitDefaultTTL). Set TTL to ask for up to 900 seconds (JitMaxTTL).

CallWithEscalation handles the request for you. When a resource answers 403 with an Insufficient-Authorization-Details header, it requests exactly the permission that the header names, gets a JIT token and retries once.

resp, err := jit.CallWithEscalation(ctx, http.MethodGet, "https://api.example.com/reports/q4", nil, nil)

To act for a user, call jit.DelegateOnBehalfOf(ctx, userToken) before you create the task. The JIT tokens then name both the user and the agent.

People who review JIT requests use client.Jit.Pending(ctx). This needs a user access token with the jit:approve scope. An agent's own token cannot call it.

Act on behalf of a user (delegation)

With delegation, an agent can call APIs as "agent X acting for user Y". It uses OAuth token exchange (RFC 8693). DelegationChain manages the whole flow for one session ID per user.

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

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

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

// 3. Call an API as the agent acting for the user. The exchange happens when needed.
var out map[string]any
err = chain.Do(ctx, "session-1", http.MethodGet, "/orgs/acme-corp/api/v1/documents", nil, &out)

// Hand the delegation to a sub-agent. A chain is at most 3 agents deep.
subToken, err := chain.DelegateToSubAgent(ctx, "session-1", subAgentToken, "read:documents")

// End the delegation. This revokes the refresh token and every token made from it.
err = chain.Revoke(ctx, "session-1")

If you already hold the user's access token, call chain.SetUserToken(sessionID, token) and skip the consent step. Without a refresh token, the delegation lasts only as long as that token does.

Bind the token to an API. Pass the URL of the API that will receive the token as an RFC 8707 resource indicator. It becomes the token's aud claim. Without it, the delegated token is bound to the acting agent's own ID.

token, err := chain.ExchangeForResource(ctx, "session-1", "https://api.example.com", "read:documents")

LumoAuth does not set aud from the audience parameter. Send one resource URL per exchange.

Low-level token exchange. client.Auth.TokenExchange sends the request directly:

resp, err := client.Auth.TokenExchange(ctx, lumoauth.TokenExchangeParams{
    SubjectToken:     userIDToken,
    SubjectTokenType: lumoauth.TokenTypeIDToken,
    ActorToken:       agentToken,
    Resource:         "https://api.example.com",
    Scopes:           []string{"read:documents"},
})

Declare what kind of token you send. The server rejects a token that does not match its declared type.

Constant Use it for
TokenTypeAccessToken (default) An access token issued by LumoAuth
TokenTypeJWT An at+jwt access token, or a JWT for a workload identity from outside LumoAuth
TokenTypeIDToken An OpenID Connect ID token
TokenTypeRefreshToken A refresh token. It is not accepted as the subject when an agent acts for a user.

The subject of an exchange must still be active. A deactivated or blocked user, or a suspended agent, gets invalid_grant. A JIT task token is never accepted as the subject.

Delegated tokens carry an act claim that records the chain. lumoauth.ParseActorChain(token) reads it for logs and audit. It does not verify the signature, so never use it to decide access.

Get a token for an MCP server

An MCP server that is secured by LumoAuth accepts only tokens issued for it. Exchange the agent's token for one:

token, err := agent.MCPToken(ctx, "https://mcp.example.com/mcp")

Pass the Resource URI that the MCP server is registered with. It is the server's https URL. The SDK sends it as the RFC 8707 resource parameter, and LumoAuth sets the token's aud to it. A plain http URL works only for localhost and private hosts. An ID such as urn:mcp:financial-data cannot be bound to a server, so the SDK returns a ValidationError before it sends the request.

The token names exactly one MCP server, and it works only at that server. LumoAuth's own API refuses it. An MCP server that is registered with "Require DPoP" accepts only tokens that are bound to a key. Give the agent a DPoP signer and the same call returns one; see Bind tokens to a key with DPoP.

With a plain Client, call client.Mcp.Token(ctx, serverID, subjectToken). Pass an empty subjectToken to exchange the client's own bearer token. TokenDetailed returns the full response, including TokenType (Bearer or DPoP).

Sign in without a secret: private key JWT

An agent registered with the Private key JWT identity type has no client secret. Whenever it needs a token, it signs a short-lived JWT (a client assertion, RFC 7523) with its private key. Only the public key is registered:

signer, err := lumoauth.GenerateClientAssertionSigner("ES256", "agent-2026-11")
pemData, err := signer.PrivateKeyPEM() // keep it in your secret store
jwks, err := signer.JWKS()             // register this on the agent

signer, err = lumoauth.LoadClientAssertionSigner(os.Getenv("AGENT_PRIVATE_KEY"),
	lumoauth.ClientAssertionOptions{KeyID: "agent-2026-11"})
agent, err := lumoauth.NewAgent(lumoauth.AgentConfig{ClientID: "agt_0123456789abcdef", PrivateKey: signer})
token, err := agent.Authenticate(ctx)

Every token request carries a new assertion: iss and sub are the agent ID, aud is the organization's issuer identifier, exp is 60 seconds ahead and jti is random. The signer works with ECDSA (P-256, P-384, P-521), Ed25519 and RSA keys, and RSA keys can use PS256 to PS512 through ClientAssertionOptions.Algorithm. Auth.ClientCredentialsWithAssertion sends an assertion on a plain client.

Bind tokens to a key with DPoP

DPoP (RFC 9449) binds a token to a private key that only the agent holds. A stolen token is then useless without the key. Generate a signer and pass it to the agent:

signer, err := lumoauth.NewDPoPSigner() // a fresh P-256 key, ES256 proofs
agent, err := lumoauth.NewAgent(lumoauth.AgentConfig{DPoP: signer})

mcpToken, err := agent.MCPToken(ctx, "https://mcp.example.com/mcp") // bound to the key

req, _ := http.NewRequestWithContext(ctx, "POST", "https://mcp.example.com/mcp", body)
if err := signer.AuthorizeRequest(req, mcpToken); err != nil {
    return err
}
// Authorization: DPoP <token>  and  DPoP: <proof with ath>

With a signer in place, the SDK:

  • sends a DPoP proof with every token request: the client-credentials grant, the MCP and delegation exchanges. The tokens come back with token_type: "DPoP"; agent.TokenType() reports it.
  • retries a token request once when the server answers use_dpop_nonce, and remembers the latest DPoP-Nonce of each origin for the following proofs.
  • presents a bound token with the DPoP authorization scheme and a proof that carries ath, on LumoAuth's own API as well as through AuthorizeRequest. An unbound token keeps the Bearer scheme.

NewDPoPSignerEd25519 signs EdDSA proofs instead. GenerateDPoPKeyPEM and LoadDPoPSigner keep one key across restarts; NewDPoPSignerFromKey wraps an existing *ecdsa.PrivateKey (P-256) or ed25519.PrivateKey. signer.Proof(method, url, opts...) signs a proof by hand, and signer.Thumbprint() is the value that appears in a bound token's cnf.jkt. If a resource server answers 401 with a DPoP-Nonce header, call signer.RememberNonce(resp) and send the request again. WithDPoP(signer) does the same for a plain Client. APIConfig refuses a bound token: the generated client cannot sign proofs.

Verify LumoAuth tokens in your MCP server

An MCP server, or any API, that receives LumoAuth access tokens verifies them locally. Three lines protect a net/http handler:

protect := lumoauth.RequireAccessToken(lumoauth.AccessTokenVerifyOptions{
    Issuer:   "https://app.lumoauth.dev/orgs/acme-corp/api/v1",
    Resource: "https://mcp.example.com/mcp", // the Resource URI the server is registered with
})
mux.Handle("/mcp", protect(mcpHandler))

Inside the handler, claims, _ := lumoauth.AccessTokenFromContext(r.Context()) gives the verified claims: Subject (agent_agt_… for an agent, a user id otherwise), IsAgent, Scopes() and HasScope, Capabilities, the delegation chain in Act (ActorChain() lists it), and Confirmation.JKT for a bound token. A missing or invalid token gets a 401 with a WWW-Authenticate challenge and a JSON body.

To verify a token yourself, call VerifyAccessToken:

claims, err := lumoauth.VerifyAccessToken(ctx, token, lumoauth.AccessTokenVerifyOptions{
    Issuer:   issuer,
    Resource: resource,
    DPoP:     lumoauth.DPoPRequestFromHTTP(r), // needed for DPoP-bound tokens
})

It checks the at+jwt type, the algorithm (RSA and EC only; none and HMAC are refused), the issuer, the signature against the organization's keys, exp and nbf with 60 seconds of tolerance (ClockSkew; a negative value means none), that aud contains Resource, and that the token is not a test token (token_use: "test"). For a token with cnf.jkt it also checks the DPoP proof: the DPoP scheme, the proof signature, htm and htu, the iat window, ath, the key thumbprint, and that the proof's jti was not seen before. RequireDPoP: true refuses tokens that are not bound. A rejection is a ValidationError whose Reason is one of the TokenRejected* constants; RejectionReason(err) reads it.

The keys come from {issuer}/.well-known/openid-configuration and are cached per issuer, with one refetch when a token names an unknown kid. Pass JWKS to supply them yourself, or KeyCache (NewAccessTokenKeyCache) to control the cache. Replayed proofs are caught by an in-memory ReplayCache; a server with several replicas should pass a shared implementation. Local verification does not check revocation.

VerifyAuthToken is the separate verifier for AAuth auth+jwt tokens.

Check access to an MCP tool

LumoAuth can decide whether a caller may run one tool on a registered MCP server. Two methods ask this question. Both take the registered server ID, such as mcp_0123456789abcdef01234567. Do not pass the Resource URI here.

From the MCP server. The MCP server first verifies the caller's token. Then it asks LumoAuth about that caller with its own token. It must never forward the caller's token, because the MCP specification forbids token passthrough. The server's OAuth client needs the mcp:authorize scope, and it must be one of the server's tool authorizers.

NewAgent runs the client credentials grant and refreshes the token, so the MCP server can use it for its own client:

mcpAuth, err := lumoauth.NewAgent(lumoauth.AgentConfig{
    OrgID:        "acme-corp",
    ClientID:     os.Getenv("MCP_CLIENT_ID"),
    ClientSecret: os.Getenv("MCP_CLIENT_SECRET"),
    Scopes:       []string{"mcp:authorize"},
})
if err != nil {
    log.Fatal(err)
}

// claims holds the verified MCP token of the caller.
decision, err := mcpAuth.Mcp.AuthorizeTool(ctx, lumoauth.McpToolAuthorizeParams{
    ServerID:    "mcp_0123456789abcdef01234567",
    SubjectType: "user", // "agent" when the caller is an agent
    SubjectID:   claims.Subject,
    Tool:        "send_invoice",
})
if err != nil {
    return err
}
if !decision.Allowed {
    return errors.New("tool not allowed")
}

Pass the sub claim of the verified token as SubjectID. For an agent, you can pass the claim as it is (agent_agt_…) or the bare agent ID (agt_…).

From the agent. An agent can ask about itself before it calls a tool. The request uses the agent's own credential:

decision, err := agent.AuthorizeMcpTool(ctx, "mcp_0123456789abcdef01234567", "send_invoice")

With a plain Client, call client.Agents.AuthorizeMcpTool(ctx, serverID, tool).

A deny is not an error. Both methods return a decision with Allowed set to false and a nil error. Other failures are errors as usual. A missing scope, or a client that is not a tool authorizer, gives ErrPermissionDenied. An unknown server gives ErrNotFound. The SDK checks the arguments before it sends the request. A tool name or server ID must not contain /, :, # or *, and a tool name has at most 80 characters.

AAuth: cryptographic agent identity

AAuth extends OAuth 2.1 for agents that hold their own signing key. Tokens are bound to the key (proof of possession), and every request is signed with RFC 9421 HTTP message signatures. Use AAuth instead of Agent when the agent must prove its identity with a key.

1. Create a key once. Store the private key in a secret manager. Register the JWKS with LumoAuth, or serve it at /.well-known/jwks.json.

keypair, err := lumoauth.GenerateKeypair("") // Ed25519; the kid defaults to "key-1"
// keypair.PrivateKeyPEM: keep it secret
// keypair.JWKS:          register it, or publish it

2. Build the client.

aauth, err := lumoauth.NewAAuthClient(lumoauth.AAuthConfig{
    AgentIdentifier: "https://my-agent.example.com",
    PrivateKeyPEM:   os.Getenv("AGENT_PRIVATE_KEY"),
    OrgID:           "acme-corp",
})
AAuthConfig field Meaning Default
AgentIdentifier The HTTPS URL that identifies the agent (required) none
PrivateKeyPEM An Ed25519 (PKCS#8) or RSA private key (required) none
BaseURL, OrgID As for New the environment variables
Kid The key ID in the registered JWKS key-1
Timeout, HTTPClient, SkipCertValidation As for New 30 seconds, a new client, off

3. Get an auth token for a resource. The resource gives the agent a resource token. The agent trades it for an auth token.

result, err := aauth.RequestAuthToken(ctx, lumoauth.AuthTokenParams{
    ResourceToken: resourceToken,
    Scope:         "read write",
    AgentToken:    agentToken,
})
if err != nil {
    return err
}
if result.AuthorizationRequired {
    // A person must consent first. Redirect them to result.AuthorizationURI,
    // then exchange the code that comes back:
    // result, err = aauth.ExchangeCode(ctx, code, redirectURI, agentToken)
}

4. Call the resource with a signed request.

resp, err := aauth.SignedRequest(ctx, http.MethodGet,
    "https://api.example.com/v1/data", result.AuthToken, nil)
if err != nil {
    return err
}
defer resp.Body.Close()

The request carries the auth token as a bearer token and an RFC 9421 signature that covers it. A stolen token is useless without the private key.

Other AAuthClient methods:

Method What it does
ExchangeToken(ctx, authToken, resourceToken, agentToken) Gets a token for a further hop. The new token records the chain in act.
Refresh(ctx, params) Renews an auth token with a refresh token
Revoke(ctx, token, tokenType, agentToken) Revokes an auth token (by its jti, with AAuthTokenTypeAuth) or a refresh token (with AAuthTokenTypeRefresh)
DiscoverIssuer, DiscoverAgents, DiscoverResource, JWKS Read the metadata documents
SignRequest(method, url, opts) Builds the signature headers without sending the request
PublicJWK, PublicJWKThumbprint Return the agent's public key and its RFC 7638 thumbprint

If you sign your own agent tokens (agent+jwt) on your agent's server, LumoAuth checks them strictly. It rejects a token that lacks iat or jti, or that is valid for more than 24 hours. The agent's JWKS document must be served as JSON and must not be larger than 256 KB.

Verify AAuth tokens on a resource server

When your API receives AAuth tokens, verify each token and its proof of possession:

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
}

// The token is bound to the agent's key. Check that the request was signed with that key,
// or a stolen token would pass.
if err := claims.VerifyProofOfPossession(req, body); err != nil {
    return err
}

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

VerifyAuthToken checks the following:

  • the typ header and the iss claim;
  • the JWS signature, against the issuer's JWKS;
  • the exp and aud claims;
  • the presence of cnf.jwk.

It always rejects HMAC and none algorithms. The algorithm must also match the type of the published key.

For a busy server, cache the issuer's keys:

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

VerifyOptions.ClockSkew adds tolerance to the expiry check. It defaults to zero, like the server. Local verification does not check revocation. For checks that must detect revoked tokens, use the server's introspection endpoint.

Call any other endpoint

The namespaces cover what most applications need. For other endpoints, such as the admin API, SCIM or audit logs, use Do:

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

DoRaw returns the *http.Response instead. You must close its body.

You can also use the generated OpenAPI client, which covers the full REST API. This SDK does not depend on it, so that your build stays small. APIConfig gives you its settings:

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, the one that matches the client's credential. It reads the current bearer token, so call it again after the token changes.

Errors

Every error from this SDK matches lumoauth.ErrLumoAuth. Use errors.Is with the sentinel errors, and errors.As to read the details:

_, err := client.Permissions.List(ctx)

switch {
case errors.Is(err, lumoauth.ErrPermissionDenied):
    var apiErr *lumoauth.APIError
    if errors.As(err, &apiErr) && len(apiErr.RequiredScopes) > 0 {
        // The token lacks a scope. Ask the user to sign in again with these scopes.
        log.Printf("missing scopes: %v", apiErr.RequiredScopes)
    }
case errors.Is(err, lumoauth.ErrRateLimited):
    var apiErr *lumoauth.APIError
    if errors.As(err, &apiErr) {
        time.Sleep(apiErr.RetryAfter)
    }
case errors.Is(err, lumoauth.ErrNetwork):
    // No HTTP response: DNS, connection, TLS or timeout.
case err != nil:
    return err
}
Sentinel Meaning ErrorCode(err)
ErrLumoAuth Any error from this SDK the code below
ErrAPI Any response with a status that is not 2xx API_ERROR
ErrAuthentication 401: the credential is missing, invalid or expired AUTHENTICATION_ERROR
ErrPermissionDenied 403: the caller may not do this PERMISSION_DENIED, or the code in the body
ErrNotFound 404 NOT_FOUND
ErrRateLimited 429: too many requests RATE_LIMITED
ErrValidation Bad input, or a response that the SDK cannot use VALIDATION_ERROR
ErrConfig A required option is missing or invalid CONFIG_ERROR
ErrNetwork The request failed before a response arrived NETWORK_ERROR
ErrApprovalDenied A person declined an approval APPROVAL_DENIED
ErrApprovalTimeout An approval expired before anyone answered APPROVAL_TIMEOUT
ErrApprovalNotDelivered No push device got the approval request; see ApprovalError.Reason APPROVAL_NOT_DELIVERED
ErrBudgetExceeded The agent's daily budget is used up BUDGET_EXCEEDED

*APIError has these fields:

  • StatusCode: the HTTP status.
  • Code and Message: taken from the response body when it has them.
  • Body: the decoded body (map[string]any for JSON).
  • RetryAfter: the Retry-After hint on a 429 response.
  • RequiredScopes: the scopes that the server named when a token lacked one. It is empty for other errors.

When a token lacks a scope, the server's error code is forbidden, so ErrorCode(err) returns forbidden. errors.Is(err, lumoauth.ErrPermissionDenied) still matches.

The helpers AsAPIError(err), StatusCode(err) and ErrorCode(err) read these values without errors.As. Errors wrap their causes, so errors.Is(err, context.DeadlineExceeded) works through a NetworkError.

API reference

The tables list the scope that a user access token needs. Agent credentials use the agent's capabilities instead. An organization API key works only where the table says so.

client.Permissions
Method What it does Needs
Check(ctx, permission, opts) One permission, as a bool any credential
CheckDetailed The same, with the full response any credential
CheckBulk(ctx, permissions, opts) Several permissions; a map of results any credential
CheckAny, CheckAnyDetailed True when at least one is granted any credential
CheckAll, CheckAllDetailed True when all of them are granted any credential
List(ctx), ListSlugs(ctx) Every permission of the caller user token with authz:read

Checking another user or agent (CheckOptions.UserID or AgentID) needs the authz:check scope or the authz.check permission.

client.Zanzibar
Method What it does Needs
Check(ctx, object, relation, subject) Does the subject hold the relation? any credential
CheckDetailed The same, with the full response any credential
IsViewer, IsEditor, IsOwner, IsMember, IsAdmin Check with a fixed relation any credential
Expand(ctx, object, relation) The tree of everyone who holds the relation authz.check permission or authz:check
client.Abac
Method What it does Needs
Check(ctx, params) Evaluate the policies for one resource and action abac:read
CheckBulk(ctx, checks) Up to 100 checks in one request, with one shared environment abac:read
IsAllowed(ctx, params) Check as a bool abac:read
MyAttributes(ctx) The caller's attributes abac:read
ResourceAttributes(ctx, type, id) The attributes of one resource abac:read
AttributeDefinitions(ctx, attributeType) The organization's attribute definitions abac:read
SetUserAttribute(ctx, userID, slug, value) Set a user's attribute abac:write and abac.manage
SetResourceAttribute(ctx, type, id, slug, value) Set a resource's attribute abac:write and abac.manage

API keys are not accepted on ABAC routes.

client.Auth
Method What it does
AuthorizationURL(params) Builds the URL that starts sign-in
ExchangeCode(ctx, params) Trades an authorization code for tokens
RefreshToken(ctx, params) Gets a new access token with a refresh token
ClientCredentials(ctx, id, secret, scopes...) The machine-to-machine grant
TokenExchange(ctx, params) RFC 8693 token exchange
Revoke(ctx, params) Revokes an access or refresh token
UserInfo(ctx, accessToken) The OpenID Connect UserInfo claims
client.Agents and Agent
Method What it does Needs
Ask(ctx, action, context), IsAllowed May the agent do this action? agent credential
Me(ctx) Identity, capabilities and workspace any bearer credential; a user token without authz:read gets no capabilities
Capabilities(ctx), Budget(ctx), Info(ctx) Capability slugs, budget policy, UserInfo claims agent credential
Register(ctx, params) Create or update an agent record admin:agents:write on a user token; not an API key
Agent.RequireCapability, HasCapability, CheckBudget Guards that return errors agent credential
Agent.MCPToken(ctx, serverID) A token for an MCP server agent credential
AuthorizeMcpTool(ctx, serverID, tool), Agent.AuthorizeMcpTool May the agent run this MCP tool? A deny returns Allowed false agent credential
client.Approvals
Method What it does
Require(ctx, params, opts) Create an approval and wait for the answer; any answer other than approval is an error
Create(ctx, params) Create an approval and return at once; the status is email_fallback_sent with no token when no device got it
Status(ctx, token) Read the current state
Wait(ctx, token, opts) Poll until the approval is answered or expires

All of them need an agent credential. Portal test tokens are refused.

client.Jit and JITContext
Method What it does Needs
CreateTask, CompleteTask, EvaluateTask Manage a task agent credential
Request(ctx, params), Status, Token Request a permission, read it, get its token agent credential
Pending(ctx) Requests that are pending review by a person user token with jit:approve
JITContext.RequestPermission, Token, Call, CallWithEscalation, Close The managed task lifecycle agent credential
client.Delegation and DelegationChain
Method What it does
Delegation.Exchange(ctx, subject, actor, scopes...) One RFC 8693 exchange
Delegation.ExchangeForResource(...) The same, bound to one resource URL
DelegationChain.ConsentURL, HandleConsentCallback, SetUserToken Get the user's token
DelegationChain.Exchange, ExchangeForResource, DelegatedToken, Do, DoRaw Use the delegation
DelegationChain.DelegateToSubAgent, DelegateToSubAgentForResource Extend the chain to a sub-agent
DelegationChain.Revoke, RevokeAll End delegations
ParseActorChain(token), TokenSubject(token) Read claims for audit, without verification
client.Mcp
Method What it does
Token(ctx, serverID, subjectToken) A token for one MCP server; serverID is the server's registered Resource URI
TokenDetailed(...) The same, with the full response
AuthorizeTool(ctx, McpToolAuthorizeParams) May a user or agent run this tool? Called by the MCP server with its own token (mcp:authorize); a deny returns Allowed false
DPoPSigner
Method What it does
Proof(method, url, opts...) Signs a DPoP proof; WithProofAccessToken adds ath, WithProofNonce overrides the nonce
AuthorizeRequest(req, token) Sets Authorization (DPoP scheme for a bound token, Bearer otherwise) and the DPoP header
PublicJWK(), Thumbprint(), Algorithm() The public key, its RFC 7638 thumbprint, ES256 or EdDSA
SetNonce(url, nonce), Nonce(url), RememberNonce(resp) Nonce memory per origin
Package functions
Function What it does
New, NewAgent, NewWebAuth, NewAAuthClient Constructors
NewJITContext(source, opts...) A JIT context over an Agent or any TokenSource
NewDelegationChain(agent, redirectURI) A delegation manager
VerifyAuthToken, NewJWKSCache, FetchIssuerJWKS Verify AAuth tokens
VerifyAccessToken, RequireAccessToken, AccessTokenFromContext, DPoPRequestFromHTTP, NewAccessTokenKeyCache, FetchAccessTokenJWKS, NewMemoryReplayCache, RejectionReason Verify LumoAuth access tokens in an MCP server
NewDPoPSigner, NewDPoPSignerEd25519, NewDPoPSignerFromKey, LoadDPoPSigner, GenerateDPoPKeyPEM, DPoPBound, DPoPAccessTokenHash DPoP keys and helpers
GenerateKeypair, LoadPrivateKey, PublicJWK, SignRequest AAuth key and signing helpers
UserFromContext, TokensFromContext Read the session in a handler
AsAPIError, StatusCode, ErrorCode Error helpers
RoutePath, RouteNames, BuildPath The route registry

Troubleshooting

Symptom Cause Fix
401 from an ABAC, agent or JIT call that uses an organization API key API keys work only on the admin API, client registration and the permission checks Call these routes with a user access token or an agent credential
403 from Permissions.List with RequiredScopes ["authz:read"] The token lacks authz:read, or the call uses an API key, which cannot hold it Add authz:read to the scopes that the app requests, and sign the user in again
403 INSUFFICIENT_PERMISSIONS from a check with CheckOptions.UserID The caller may only ask about itself Give the API key the authz:check scope, or grant the caller the authz.check permission
404 SUBJECT_NOT_FOUND from a check with CheckOptions.UserID The ID is not a LumoAuth user ID in your organization Pass the user's LumoAuth ID (the sub claim), not an email or a local ID
ValidationError from Abac.CheckBulk about one environment The entries carry different Context values Split the call, or give every entry the same Context
403 from an ABAC call with RequiredScopes ["abac:read"] The user token lacks the ABAC scope Request abac:read, or abac:write for writes
Agents.Me returns an empty Capabilities list A user token without authz:read called it Request authz:read, or call it with the agent's credential
invalid_grant from a token exchange The declared token type does not match the token, the subject is no longer active, or the subject is a JIT token Set SubjectTokenType correctly (for example TokenTypeIDToken for an ID token), and exchange an active user's token
400 invalid_request when an agent exchanges a refresh token for a user A refresh token cannot be the subject of an on-behalf-of exchange Exchange the user's access token or ID token
403 test_token_not_accepted from Approvals.Create The agent uses a test token from the portal Use the agent's real credential
ErrApprovalNotDelivered from Approvals.Require The user has no enrolled push device Ask the user to enrol a device in the LumoAuth app, then try again
ValidationError from Mcp.Token about the server ID The ID is not an http(s) URL, for example urn:mcp:… Pass the MCP server's https URL, for example https://mcp.example.com/mcp
ValidationError from AuthorizeTool or AuthorizeMcpTool about the server ID The ID is a URL Pass the registered server ID, for example mcp_0123456789abcdef01234567
403 insufficient_scope or forbidden from Mcp.AuthorizeTool The token lacks mcp:authorize, or its client is not a tool authorizer of the server Request mcp:authorize with the MCP server's own client, and list that client as a tool authorizer
400 invalid_target from Mcp.Token The server URL uses plain http on a public host, or has a fragment Use an https URL with no # part
ErrRateLimited Too many requests Wait for APIError.RetryAfter, then retry
ErrConfig mentioning the organization The call needs an org ID Set WithOrgID or LUMOAUTH_ORG_ID
The session is lost after every restart SessionSecret changes at each start Load a fixed secret from your configuration
The session cookie is not set during local development The cookie is Secure and the app uses plain HTTP Set CookieSecure: lumoauth.Bool(false) in development only

Versioning and compatibility

The SDK reports itself as lumoauth-go/1.0.0 in the User-Agent header (lumoauth.Version). The module has no release tag yet. It needs a LumoAuth server whose API is version 1.0.0 or later.

Every endpoint that this SDK calls is listed in routes.go. A test compares that list with the server's OpenAPI spec and with the shared SDK contract (../sdk-contract). A route that is renamed on the server therefore fails the build instead of returning 404 in production.

Development

go test ./...          # unit tests, contract tests and route checks
go test -race ./...    # the concurrent paths (token refresh, delegation)
go vet ./...
gofmt -l .

The contract tests read ../sdk-contract, or the directory in LUMO_SDK_CONTRACT. They are skipped when neither exists.

Licence

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.

  • VerifyAccessToken and RequireAccessToken — for an MCP server or API that receives LumoAuth access tokens: local verification against the organization's keys, including DPoP sender-constraint checks. DPoPSigner is the client side of DPoP (RFC 9449).

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

Client

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

ok, err := client.Permissions.Check(ctx, "document.edit", nil)
ok, err = client.Zanzibar.IsViewer(ctx, "document:readme", "user:bob")

An organization API key works only on the admin API, client registration and the permission checks. ABAC, agent and JIT routes refuse it. Call ABAC with a user access token that has the abac:read scope (abac:write for writes):

userClient, err := lumoauth.New(
    lumoauth.WithAccessToken(userAccessToken), // has abac:read
    lumoauth.WithOrgID("acme-corp"),
)
decision, err := userClient.Abac.Check(ctx, lumoauth.AbacCheckParams{
    ResourceType: "document",
    Action:       "read",
    ResourceID:   "doc-123",
})

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

Agent

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

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

Before an irreversible action, ask a human:

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

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

Web sign-in

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

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

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

Errors

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

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

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

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

Configuration

Options fall back to the environment:

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

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

Example (ErrorHandling)

Errors are matched with the standard library.

package main

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

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

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

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

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

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

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

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

Index

Examples

Constants

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

Token types accepted by Revoke.

View Source
const (
	TokenRejectedMalformed    = "malformed"
	TokenRejectedType         = "wrong_type"
	TokenRejectedAlgorithm    = "bad_algorithm"
	TokenRejectedIssuer       = "wrong_issuer"
	TokenRejectedUnknownKey   = "unknown_key"
	TokenRejectedSignature    = "bad_signature"
	TokenRejectedExpired      = "expired"
	TokenRejectedNotYetValid  = "not_yet_valid"
	TokenRejectedAudience     = "wrong_audience"
	TokenRejectedTestToken    = "test_token"
	TokenRejectedDPoPRequired = "dpop_required"
	TokenRejectedDPoPScheme   = "dpop_scheme"
	TokenRejectedDPoPProof    = "dpop_proof"
	TokenRejectedDPoPBinding  = "dpop_binding"
	TokenRejectedDPoPReplay   = "dpop_replay"
)

Rejection reasons carried by the *ValidationError that VerifyAccessToken returns, in ValidationError.Reason. They are stable; match on them rather than on the message.

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 (
	// ClientAssertionType is the client_assertion_type of a JWT client assertion.
	ClientAssertionType = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"
	// ClientAssertionTyp is the typ header of a client-authentication JWT.
	ClientAssertionTyp = "client-authentication+jwt"
	// MaxClientAssertionLifetime is the longest validity LumoAuth accepts.
	MaxClientAssertionLifetime = 10 * time.Minute

	// EnvAgentPrivateKey holds the PEM private key of a private key JWT agent.
	EnvAgentPrivateKey = "AGENT_PRIVATE_KEY"
	// EnvAgentKeyID holds the kid of the registered public key.
	EnvAgentKeyID = "AGENT_KEY_ID"
)
View Source
const (
	DPoPAlgES256 = "ES256"
	DPoPAlgEdDSA = "EdDSA"
)

DPoP proof algorithms this SDK signs with. The server also accepts the RSA and larger EC families; ES256 is the RFC 9449 default.

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"
	// CodeApprovalNotDelivered marks an ApprovalError for a request that
	// never reached a push device; see ApprovalError.Reason.
	CodeApprovalNotDelivered = "APPROVAL_NOT_DELIVERED"
	CodeBudgetExceeded       = "BUDGET_EXCEEDED"
)

Error codes, identical to the JS and Python SDKs.

View Source
const (
	// ApprovalReasonEmailFallbackSent means the user has no enrolled push
	// device, so the server sent an email notice instead. The email holds no
	// approval link. The server gives the same answer for an unknown user.
	ApprovalReasonEmailFallbackSent = "email_fallback_sent"
	// ApprovalReasonNoEnrolledDevice means the user has no enrolled push
	// device and the server could not send the email notice either.
	ApprovalReasonNoEnrolledDevice = "no_enrolled_device"
)

Reasons carried by an ApprovalError with Code CodeApprovalNotDelivered.

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 is an opaque or at+jwt access token issued by the
	// organization — the default subject/actor type.
	TokenTypeAccessToken = "urn:ietf:params:oauth:token-type:access_token"
	// TokenTypeJWT is an at+jwt access token, or an external workload identity
	// token (Kubernetes, AWS, GCP, Azure, GitHub, SPIFFE) presented by a
	// registered agent.
	TokenTypeJWT = "urn:ietf:params:oauth:token-type:jwt"
	// TokenTypeIDToken is an OpenID Connect ID token issued by the organization
	// to the exchanging client.
	TokenTypeIDToken = "urn:ietf:params:oauth:token-type:id_token"
	// TokenTypeRefreshToken is a refresh token issued to the exchanging client.
	// It is refused as the subject when an agent acts on a user's behalf
	// (ActorToken is an agent access token): 400 invalid_request.
	TokenTypeRefreshToken = "urn:ietf:params:oauth:token-type:refresh_token"
)

RFC 8693 token-exchange constants.

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"
	RouteAgentsAuthorizeMcpTool = "agents.authorizeMcpTool"
	RouteAgentsMe               = "agents.me"
	RouteAgentsRegister         = "agents.register"
	RouteAgentsReportUsage      = "agents.reportUsage"

	// ── MCP (per-tool checks asked by an MCP server) ──────────────────
	RouteMcpAuthorizeTool = "mcp.authorizeTool"

	// ── 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"
	// ApprovalEmailFallbackSent is the status Create returns when the user
	// has no enrolled push device. The server sent an email notice with no
	// approval link instead. The result has no Token and nothing to poll.
	ApprovalEmailFallbackSent = "email_fallback_sent"
)

Approval statuses.

View Source
const AbacMaxBulkRequests = 100

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

View Source
const DPoPHeader = "DPoP"

DPoPHeader is the request header that carries a DPoP proof.

View Source
const DPoPNonceHeader = "DPoP-Nonce"

DPoPNonceHeader is the response header a server uses to hand out a nonce.

View Source
const DPoPTokenType = "DPoP"

DPoPTokenType is the token_type of a DPoP-bound token.

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.5.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")
	// ErrApprovalNotDelivered matches an approval request that no push
	// device received, so nobody can approve it in this call.
	ErrApprovalNotDelivered = errors.New("lumoauth: approval not delivered")
	// ErrBudgetExceeded matches an exhausted agent budget.
	ErrBudgetExceeded = errors.New("lumoauth: budget exceeded")
)

Sentinel errors for errors.Is. Every error returned by this SDK matches ErrLumoAuth; each also matches exactly one of the specific sentinels.

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}/api/v1/oauth/magic-link"},

	RouteAgentsAsk:              {"POST", orgBase + "/agents/ask"},
	RouteAgentsAuthorizeMcpTool: {"POST", orgBase + "/agents/me/mcp/authorize"},
	RouteAgentsMe:               {"GET", orgBase + "/agents/me"},
	RouteAgentsRegister:         {"POST", orgBase + "/agents/register"},
	RouteAgentsReportUsage:      {"POST", orgBase + "/agents/me/usage"},

	RouteMcpAuthorizeTool: {"POST", orgBase + "/mcp/servers/{serverId}/tools/authorize"},

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

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

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

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

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

Functions

func AnyCapabilityCovers added in v1.4.0

func AnyCapabilityCovers(capabilities []string, action string) bool

AnyCapabilityCovers reports whether any capability in the list covers the action.

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 CapabilityCovers added in v1.4.0

func CapabilityCovers(capability, action string) bool

CapabilityCovers reports whether one capability covers an action, in any spelling of either. CapabilityCovers("users:*", "USERS-DELETE") is true; CapabilityCovers("invoices.*", "invoices") is false.

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 ContextWithAccessToken added in v1.2.0

func ContextWithAccessToken(ctx context.Context, claims *AccessTokenClaims) context.Context

ContextWithAccessToken stores verified claims in a context, for handlers that verify tokens themselves but share downstream code with RequireAccessToken.

func DPoPAccessTokenHash added in v1.2.0

func DPoPAccessTokenHash(accessToken string) string

DPoPAccessTokenHash computes the `ath` claim: base64url(SHA-256(token)).

func DPoPBound added in v1.2.0

func DPoPBound(token string) bool

DPoPBound reports whether a JWT access token is sender-constrained — it carries a cnf.jkt claim — and so must be presented with the DPoP scheme and a proof. Opaque or malformed tokens are reported as unbound.

The claims are read WITHOUT signature verification: this only picks the authorization scheme, it never grants anything.

func ErrorCode

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 GenerateDPoPKeyPEM added in v1.2.0

func GenerateDPoPKeyPEM() (string, error)

GenerateDPoPKeyPEM generates a P-256 key and returns it as a PKCS#8 PEM block, for storing in a secret manager and loading with LoadDPoPSigner.

func GenerateNonce

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 IssuerFor added in v1.3.0

func IssuerFor(baseURL, orgID string) string

IssuerFor is the issuer identifier of an organization on baseURL: the issuer of /orgs/{orgID}/api/v1/.well-known/openid-configuration, and the aud a client assertion must carry. On a custom domain the issuer differs; set it explicitly there.

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 NormalizeCapability added in v1.4.0

func NormalizeCapability(capability string) string

NormalizeCapability returns a capability in the form that the server stores it: "Invoices:Read" and "invoices-read" both become "invoices.read". Only ASCII letters are lower-cased, as on the server.

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 RejectionReason added in v1.2.0

func RejectionReason(err error) string

RejectionReason returns the TokenRejected* reason carried by err, or "" when err is not a token rejection.

func RequireAccessToken added in v1.2.0

func RequireAccessToken(opts AccessTokenVerifyOptions) func(http.Handler) http.Handler

RequireAccessToken is net/http middleware that verifies the LumoAuth access token on every request and stores its claims in the context — the guard for an MCP server built on net/http:

protect := lumoauth.RequireAccessToken(lumoauth.AccessTokenVerifyOptions{
    Issuer:   "https://app.lumoauth.dev/orgs/acme-corp/api/v1",
    Resource: "https://mcp.example.com/mcp",
})
mux.Handle("/mcp", protect(mcpHandler))

// in mcpHandler:
claims, _ := lumoauth.AccessTokenFromContext(r.Context())

The token is read from the Authorization header (Bearer or DPoP scheme) and, for a bound token, the DPoP header is checked against the request (opts.DPoP is filled from each request; DPoPRequestFromHTTP documents how the URL is derived). A missing or invalid token gets 401 with a WWW-Authenticate challenge (RFC 6750 and RFC 9449 §7.1) and a JSON body {"error": "invalid_token", "error_description": …}. When opts.JWKS is nil the middleware keeps one key cache for the issuer.

func RouteNames

func RouteNames() []string

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

func RoutePath

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
	// RequiredScopes lists the scopes a 403 scope refusal names in
	// details.required_scopes; nil when the body has none. The server sends
	//
	//	{"error":"forbidden","message":"Insufficient scope: …","status":403,
	//	 "details":{"required_scopes":["authz:read"],"granted_scopes":[…]}}
	//
	// when the credential lacks a user-delegated scope the route needs.
	RequiredScopes []string
}

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

func AsAPIError

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 environment attributes for the evaluation. The SDK
	// sends it as the request's "environment" object, which the policy
	// engine reads. The keys ip, userAgent, requestMethod and requestPath
	// always describe the request that LumoAuth received; values that you
	// pass under those names are kept under "pep" instead, so forward the
	// end user's IP as {"pep": {"ip": "10.0.0.1"}}.
	//
	// In CheckBulk the server applies one environment to every check, so
	// every entry must carry the same Context (or none).
	Context map[string]any
}

AbacCheckParams describes one ABAC evaluation.

type AbacDecision

type AbacDecision struct {
	Allowed bool   `json:"allowed"`
	Reason  string `json:"reason,omitempty"`
	// MatchedPolicies lists the policies that applied. A caller without the
	// policies.view permission receives only each policy's ID and Name.
	MatchedPolicies []AbacMatchedPolicy `json:"matchedPolicies,omitempty"`
	// ResourceType, Action and ResourceID echo the evaluated target.
	ResourceType string `json:"resourceType,omitempty"`
	Action       string `json:"action,omitempty"`
	ResourceID   string `json:"resourceId,omitempty"`
	// Index is the position of this result in a bulk request (0 for a
	// single check).
	Index int `json:"index,omitempty"`
	// Error is set on a bulk result whose entry the server could not
	// evaluate; Allowed is then false.
	Error string `json:"error,omitempty"`

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

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

func (*AbacDecision) UnmarshalJSON

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

UnmarshalJSON decodes the typed fields and retains the whole object.

type AbacMatchedPolicy

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

AbacMatchedPolicy is a policy that contributed to an ABAC decision.

type AbacResource

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

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

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

A user access token needs the abac:read scope for checks and attribute reads, and abac:write to set attributes. Organization API keys are not accepted on the ABAC routes.

Note the wire format uses camelCase keys (resourceType, resourceId); this resource takes Go-shaped params and translates.

func (*AbacResource) AttributeDefinitions

func (r *AbacResource) AttributeDefinitions(ctx context.Context, attributeType string) ([]AbacAttributeDefinition, error)

AttributeDefinitions lists the org's attribute definitions. Pass an empty attributeType for all of them.

func (*AbacResource) Check

func (r *AbacResource) Check(ctx context.Context, params AbacCheckParams) (*AbacDecision, error)

Check evaluates the policies for one resource/action pair and returns the full decision, including the policies that matched.

Example

ABAC decisions carry the policies that produced them. ABAC routes refuse an organization API key: they need a user access token with the abac:read scope (abac:write for writes).

package main

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

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

func main() {
	client, _ := lumoauth.New(
		lumoauth.WithAccessToken(os.Getenv("LUMOAUTH_ACCESS_TOKEN")), // a user token with abac:read
		lumoauth.WithOrgID("acme-corp"),
	)

	decision, err := client.Abac.Check(context.Background(), lumoauth.AbacCheckParams{
		ResourceType: "document",
		Action:       "read",
		ResourceID:   "doc-123",
		Context: map[string]any{
			"pep": map[string]any{"ip": "10.0.0.1"}, // sent as the request's environment
		},
	})
	if err != nil {
		log.Fatal(err)
	}

	if !decision.Allowed {
		fmt.Println("denied:", decision.Reason)
		return
	}
	for _, policy := range decision.MatchedPolicies {
		fmt.Printf("matched %s (%s)\n", policy.Name, policy.Effect)
	}
}

func (*AbacResource) CheckBulk

func (r *AbacResource) CheckBulk(ctx context.Context, checks []AbacCheckParams) ([]AbacDecision, error)

CheckBulk evaluates up to AbacMaxBulkRequests pairs in one round trip. Results come back in request order.

The server applies one environment to every check in a bulk call. Give every entry the same Context, or none; entries with different Context values return a ValidationError before any request is sent.

func (*AbacResource) IsAllowed

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

IsAllowed is Check reduced to a boolean.

func (*AbacResource) MyAttributes

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 AccessTokenClaims added in v1.2.0

type AccessTokenClaims struct {
	Issuer string `json:"iss"`
	// Subject is "agent_agt_…" for an agent, a user id for a user token or a
	// delegated token.
	Subject   string        `json:"sub"`
	Audience  AudienceClaim `json:"aud"`
	Expires   int64         `json:"exp"`
	NotBefore int64         `json:"nbf,omitempty"`
	IssuedAt  int64         `json:"iat,omitempty"`
	JTI       string        `json:"jti"`
	// ClientID is the OAuth client that obtained the token.
	ClientID string `json:"client_id,omitempty"`
	// Scope is the space-separated scope string; see Scopes and HasScope.
	Scope string `json:"scope,omitempty"`
	// IsAgent is true for tokens issued to an agent identity.
	IsAgent bool `json:"is_agent,omitempty"`
	// Capabilities are the agent's capability slugs, when IsAgent.
	Capabilities []string `json:"capabilities,omitempty"`
	// Act is the RFC 8693 actor claim of a delegated token: the agent acting
	// for Subject, with any deeper sub-agents nested in Act.Act.
	Act *ActorClaim `json:"act,omitempty"`
	// Confirmation is the RFC 7800 key binding; JKT is set for a DPoP-bound
	// token.
	Confirmation *TokenConfirmation `json:"cnf,omitempty"`
	// TokenUse marks special-purpose tokens. "test" tokens are refused.
	TokenUse string `json:"token_use,omitempty"`

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

AccessTokenClaims are the claims of a verified LumoAuth access token.

func AccessTokenFromContext added in v1.2.0

func AccessTokenFromContext(ctx context.Context) (*AccessTokenClaims, bool)

AccessTokenFromContext returns the claims RequireAccessToken stored for the request.

func VerifyAccessToken added in v1.2.0

func VerifyAccessToken(ctx context.Context, token string, opts AccessTokenVerifyOptions) (*AccessTokenClaims, error)

VerifyAccessToken verifies a LumoAuth access token for this resource and returns its claims.

claims, err := lumoauth.VerifyAccessToken(ctx, token, lumoauth.AccessTokenVerifyOptions{
    Issuer:   "https://app.lumoauth.dev/orgs/acme-corp/api/v1",
    Resource: "https://mcp.example.com/mcp",
    DPoP:     lumoauth.DPoPRequestFromHTTP(r),
})

It checks, in order: the compact JWS shape; the `typ` header (at+jwt); the algorithm (RSA and EC families only — HMAC and none are refused, and the algorithm must match the published key); `iss`; the signature; `exp` and `nbf`; `aud` contains Resource; `token_use` is not "test"; and, for a token with cnf.jkt, the DPoP proof: scheme, signature, htm/htu, iat window, ath, key thumbprint and jti replay.

Failures are a *ValidationError whose Reason is a TokenRejected* constant. Fetch failures are *NetworkError or *APIError.

func (*AccessTokenClaims) ActorChain added in v1.2.0

func (c *AccessTokenClaims) ActorChain() []string

ActorChain returns the `sub` of each actor in the delegation chain, outermost first: the agent acting for Subject, then its sub-agents. It is empty for a token with no `act` claim.

func (*AccessTokenClaims) HasCapability added in v1.2.0

func (c *AccessTokenClaims) HasCapability(capability string) bool

HasCapability reports whether the agent's capabilities claim covers a capability. Names match as on the server ("tool:search_web" matches "tool.search_web"; "invoices.*" covers "invoices.read"). Scopes are different: HasScope compares them exactly.

func (*AccessTokenClaims) HasScope added in v1.2.0

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

HasScope reports whether the token carries a scope.

func (*AccessTokenClaims) IsDPoPBound added in v1.2.0

func (c *AccessTokenClaims) IsDPoPBound() bool

IsDPoPBound reports whether the token is sender-constrained (cnf.jkt).

func (*AccessTokenClaims) Scopes added in v1.2.0

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

Scopes splits the space-separated scope claim.

type AccessTokenKeyCache added in v1.2.0

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

AccessTokenKeyCache caches an organization's token-signing keys for a TTL. Build one with NewAccessTokenKeyCache and pass it as AccessTokenVerifyOptions.KeyCache, or let VerifyAccessToken use its process-wide cache.

func NewAccessTokenKeyCache added in v1.2.0

func NewAccessTokenKeyCache(issuer string, ttl time.Duration, httpClient *http.Client) *AccessTokenKeyCache

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

func (*AccessTokenKeyCache) Get added in v1.2.0

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

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

func (*AccessTokenKeyCache) Invalidate added in v1.2.0

func (c *AccessTokenKeyCache) Invalidate()

Invalidate drops the cached keys, forcing the next Get to refetch.

type AccessTokenVerifyOptions added in v1.2.0

type AccessTokenVerifyOptions struct {
	// Issuer is the organization's issuer URL, e.g.
	// "https://app.lumoauth.dev/orgs/acme-corp/api/v1". Required.
	Issuer string
	// Resource is this server's resource URI — the value the MCP server is
	// registered with and the token's `aud` must name. Required.
	Resource string
	// JWKS supplies the issuer's keys directly. When nil, the keys are
	// fetched through the issuer's discovery document and cached (KeyCache,
	// or a process-wide cache per issuer), with one refetch on an unknown
	// kid.
	JWKS *JWKS
	// KeyCache is the cache to fetch keys through when JWKS is nil.
	KeyCache *AccessTokenKeyCache
	// HTTPClient fetches discovery and keys. Defaults to a 30s-timeout
	// client.
	HTTPClient *http.Client
	// ClockSkew tolerated on exp, nbf and the proof's iat. The default (0)
	// means 60 seconds; a negative value means no tolerance.
	ClockSkew time.Duration
	// RequireDPoP rejects tokens that are not sender-constrained. Set it
	// when the MCP server is registered with "Require DPoP".
	RequireDPoP bool
	// DPoP describes the request the token arrived with. Required for a
	// DPoP-bound token; RequireAccessToken fills it from the request.
	DPoP *DPoPRequest
	// ReplayCache stores proof identifiers. Defaults to a process-wide
	// in-memory cache.
	ReplayCache ReplayCache
}

AccessTokenVerifyOptions configures VerifyAccessToken.

type ActorClaim added in v1.2.0

type ActorClaim struct {
	Subject        string `json:"sub"`
	Issuer         string `json:"iss,omitempty"`
	SubjectProfile string `json:"sub_profile,omitempty"`
	Name           string `json:"name,omitempty"`
	// Act is the next actor down the chain, when there is one.
	Act *ActorClaim `json:"act,omitempty"`
}

ActorClaim is one link of a delegation chain (`act`).

type Agent

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

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

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

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

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

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

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

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

func NewAgent

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

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

Example

An agent checks whether it may act before acting.

package main

import (
	"context"
	"log"

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

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

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

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) AuthorizeMcpTool added in v1.2.0

func (a *Agent) AuthorizeMcpTool(ctx context.Context, serverID, tool string) (*AgentMcpToolDecision, error)

AuthorizeMcpTool asks whether this agent may run one tool on an MCP server. serverID is the registered MCP server ID, not its URL. A deny returns Allowed false and a nil error; see AgentsResource.AuthorizeMcpTool.

func (*Agent) BaseURL

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) ClientAssertion added in v1.3.0

func (a *Agent) ClientAssertion() (string, error)

ClientAssertion signs a new private_key_jwt client assertion for this agent (single-use), addressed to AgentConfig.Issuer or IssuerFor(BaseURL, OrgID). It is a *ConfigError when the agent has no PrivateKey.

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) DPoP added in v1.2.0

func (a *Agent) DPoP() *DPoPSigner

DPoP returns the signer from AgentConfig.DPoP, or nil when the agent's tokens are plain bearer tokens.

func (*Agent) Do

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. Names match as on the server: "tool:search_web" matches the stored "tool.search_web", and a held "tool.*" covers it (see CapabilityCovers). It checks only the agent's registered capabilities; the Ask API (Agent.Ask) also applies your policies and the token's scope.

func (*Agent) Identity

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 bound to a secured MCP server. serverID is the Resource URI that the server is registered with, e.g. "https://mcp.example.com/mcp". The token works only at that server; see McpResource.Token.

func (*Agent) 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) ReportUsage added in v1.4.0

func (a *Agent) ReportUsage(ctx context.Context, tokens int, costUSD float64) (*UsageReportResult, error)

ReportUsage reports the model tokens and cost that the agent just used, for example the usage that the model provider returned. LumoAuth does not see model calls, so token and cost limits count only reported usage. The budget in the result also replaces the cached one, so CheckBudget reflects the report without another request.

resp, _ := llm.Chat(ctx, req)
if _, err := agent.ReportUsage(ctx, resp.Usage.TotalTokens, 0.0042); err != nil {
    return err
}
if err := agent.CheckBudget(ctx); err != nil {
    return err // ErrBudgetExceeded
}

func (*Agent) RequireCapability

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.

func (*Agent) TokenType added in v1.2.0

func (a *Agent) TokenType() string

TokenType returns the token_type of the cached token: "Bearer", or "DPoP" when AgentConfig.DPoP bound it to a key. It is "" before the first 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:"-"`
}

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

	// ReportedExhausted is the server's own verdict (`exhausted`): true when
	// any limit (calls, tokens or cost, per hour, day or month) is reached.
	// Nil when the server did not report it.
	ReportedExhausted *bool `json:"exhausted,omitempty"`

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

AgentBudget is the budget policy attached to an agent.

func (*AgentBudget) Exhausted

func (b *AgentBudget) Exhausted() bool

Exhausted reports whether the agent's budget is spent, so the next metered call would get 429. It uses the server's verdict when reported (any limit, any window); otherwise it compares the daily token cap with today's usage, and 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
	// PrivateKey is for an agent registered with the "Private key JWT"
	// identity type: the agent then signs a client assertion (RFC 7523) for
	// every token request and needs no ClientSecret. Defaults to the PEM key
	// in $AGENT_PRIVATE_KEY, with its kid from $AGENT_KEY_ID.
	PrivateKey *ClientAssertionSigner
	// Issuer is the organization's issuer identifier, the assertion's aud.
	// Defaults to IssuerFor(BaseURL, OrgID); set it on a custom domain.
	Issuer string
	// DPoP binds the agent's tokens to a key (RFC 9449). The client
	// credentials grant, MCP token exchanges and delegation exchanges then
	// send a DPoP proof, the tokens come back with token_type "DPoP", and
	// the agent presents them with the DPoP scheme. Needed for MCP servers
	// registered with "Require DPoP". See NewDPoPSigner.
	DPoP *DPoPSigner
}

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

type AgentIdentity

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

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

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

func (*AgentIdentity) ID

func (i *AgentIdentity) ID() string

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

func (*AgentIdentity) UnmarshalJSON

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

UnmarshalJSON decodes the typed fields and retains the whole object.

type AgentMcpToolDecision added in v1.2.0

type AgentMcpToolDecision struct {
	Allowed  bool            `json:"allowed"`
	AgentID  string          `json:"agent_id,omitempty"`
	Resource McpToolResource `json:"resource"`
}

AgentMcpToolDecision is the answer to AgentsResource.AuthorizeMcpTool. A deny comes back with Allowed set to false and a nil error.

type AgentRegistration

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

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

AgentRegistration is the response to registering an agent.

func (*AgentRegistration) UnmarshalJSON

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

UnmarshalJSON decodes the typed fields and retains the whole object.

type AgentsResource

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

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

func (*AgentsResource) Ask

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

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

The keys ip, userAgent, requestMethod and requestPath in actionContext always describe the request LumoAuth received. A value you pass under one of those names is kept under pep instead, as in ABAC.

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

func (*AgentsResource) AuthorizeMcpTool added in v1.2.0

func (r *AgentsResource) AuthorizeMcpTool(ctx context.Context, serverID, tool string) (*AgentMcpToolDecision, error)

AuthorizeMcpTool asks whether the calling agent may run one tool on an MCP server. It uses the agent's own credential, so it suits an agent that checks a tool before it calls it. An MCP server must not use it, because it would have to forward the agent's token; the server calls Mcp.AuthorizeTool with its own token instead.

serverID is the registered MCP server ID, for example "mcp_0123456789abcdef01234567". It is not the Resource URI.

decision, err := agent.Agents.AuthorizeMcpTool(ctx, "mcp_0123456789abcdef01234567", "send_invoice")
if err != nil {
    return err
}
if !decision.Allowed {
    return errors.New("tool refused")
}

A deny is not an error. It comes back with Allowed set to false and a nil error. An unknown server is an error that matches ErrNotFound.

func (*AgentsResource) Budget

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

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

func (*AgentsResource) Capabilities

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

Capabilities returns the capability slugs granted to the agent.

func (*AgentsResource) 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.

For an agent credential, Capabilities lists the agent's capability roles. A user access token without the authz:read scope gets an empty list.

func (*AgentsResource) Register

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

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

func (*AgentsResource) ReportUsage added in v1.4.0

func (r *AgentsResource) ReportUsage(ctx context.Context, tokens int, costUSD float64) (*UsageReportResult, error)

ReportUsage reports the model tokens and cost that the agent used.

LumoAuth does not see the agent's model calls, so token and cost limits (max_tokens_per_day, max_cost_per_month_usd, …) count only the usage that is reported here. Report after each model call, or batch a few. The report is not a metered call and is accepted when the budget is spent; the result's Budget says whether it is. Agent credentials only.

type ApprovalError

type ApprovalError struct {
	*BaseError
	// Approval is the last observed approval payload, for audit. It is nil
	// when the request was not delivered.
	Approval *ApprovalResult
	// Reason is set when Code is CodeApprovalNotDelivered:
	// ApprovalReasonEmailFallbackSent or ApprovalReasonNoEnrolledDevice.
	Reason string
	// TaskID is the task the request named, when the server echoed it.
	TaskID string
}

ApprovalError is returned when a push approval was denied by a human (ErrApprovalDenied), expired before anyone responded (ErrApprovalTimeout), or never reached a push device (ErrApprovalNotDelivered). Code tells the three apart: CodeApprovalDenied, CodeApprovalTimeout or CodeApprovalNotDelivered.

type ApprovalImpact

type ApprovalImpact string

ApprovalImpact is the severity tier of an approval request; it drives the visual treatment on the approver's phone.

const (
	ImpactLow      ApprovalImpact = "low"
	ImpactMedium   ApprovalImpact = "medium"
	ImpactHigh     ApprovalImpact = "high"
	ImpactCritical ApprovalImpact = "critical"
)

Approval impact tiers.

func (ApprovalImpact) Valid

func (i ApprovalImpact) Valid() bool

Valid reports whether the impact is one the server accepts.

type ApprovalParams

type ApprovalParams struct {
	// TaskID identifies the task the agent is operating against. Required.
	TaskID string
	// Reason is the description shown on the approver's phone. Required.
	Reason string
	// OnBehalfOf is the user the agent is acting for — email or user ID.
	// Required.
	OnBehalfOf string
	// Impact is the severity tier. Defaults to ImpactMedium.
	Impact ApprovalImpact
	// Meta carries structured fields (vendor, amount, …) shown to the user.
	Meta map[string]any
}

ApprovalParams describes an approval request.

type ApprovalResult

type ApprovalResult struct {
	// Status is "pending", "approved", "denied", or "expired". Create can
	// also return ApprovalEmailFallbackSent, with an empty Token.
	Status string `json:"status"`
	// Message is the server's explanation, when it sends one.
	Message string `json:"message,omitempty"`
	// Token is the approval token; present it as the credential for the
	// side-effecting call the approval authorises.
	Token       string         `json:"approval_token,omitempty"`
	TaskID      string         `json:"task_id,omitempty"`
	Impact      ApprovalImpact `json:"impact,omitempty"`
	Reason      string         `json:"reason,omitempty"`
	ExpiresAt   string         `json:"expires_at,omitempty"`
	RespondedAt string         `json:"responded_at,omitempty"`
	ApprovedBy  *Approver      `json:"approved_by,omitempty"`
}

ApprovalResult is the state of a push-approval request.

func (*ApprovalResult) Approved

func (r *ApprovalResult) Approved() bool

Approved reports whether a human approved the action.

type ApprovalsResource

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

ApprovalsResource covers push-approval-for-agent-actions.

The headline call is Require: when an agent is about to do something irreversible — wire money, delete data, email customers — it asks first, a push lands on the user's phone with the context, and the call returns once a human decides.

func (*ApprovalsResource) Create

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

When the user has no enrolled push device, the server emails a plain notice with no approval link and answers 202. Create then returns a result with Status ApprovalEmailFallbackSent and an empty Token. Nothing can be polled, and the action is not approved. Tell the user to check their email or enrol a device. The server gives the same answer for an unknown user, so the endpoint does not reveal who has an account.

When the user has no device and the email could not be sent either, the server answers 428. Create returns an *ApprovalError with Code CodeApprovalNotDelivered and Reason ApprovalReasonNoEnrolledDevice.

A portal test token is refused with 403 test_token_not_accepted.

func (*ApprovalsResource) Require

func (r *ApprovalsResource) Require(ctx context.Context, params ApprovalParams, opts *WaitOptions) (*ApprovalResult, error)

Require opens an approval request and blocks until a human decides.

It returns an error for anything other than approval, so the happy path reads as a guard:

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

Use errors.Is with ErrApprovalDenied, ErrApprovalTimeout or ErrApprovalNotDelivered to tell the outcomes apart; the *ApprovalError carries the final payload for audit. When no push device received the request, the error has Code CodeApprovalNotDelivered and a Reason of ApprovalReasonEmailFallbackSent or ApprovalReasonNoEnrolledDevice. Require does not poll in that case, and it never treats it as approval. To handle a denial without an error, call Create and Wait yourself.

Example

Human approval before an irreversible action. Require returns an error for anything except approval, so the happy path reads as a guard.

package main

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

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

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

	approval, err := agent.Approvals.Require(context.Background(), lumoauth.ApprovalParams{
		TaskID:     "wire-2026-05-07-001",
		Reason:     "Wire $4,500 to vendor INV-7741",
		Impact:     lumoauth.ImpactHigh,
		OnBehalfOf: "ada@acme.com",
		Meta:       map[string]any{"amount": 4500, "vendor": "INV-7741"},
	}, nil)

	switch {
	case errors.Is(err, lumoauth.ErrApprovalDenied):
		fmt.Println("a human declined the transfer")
		return
	case errors.Is(err, lumoauth.ErrApprovalTimeout):
		fmt.Println("nobody responded in time")
		return
	case errors.Is(err, lumoauth.ErrApprovalNotDelivered):
		// No push device received the request. Reason is
		// ApprovalReasonEmailFallbackSent or ApprovalReasonNoEnrolledDevice.
		fmt.Println("ask the user to check their email or enrol a device")
		return
	case err != nil:
		log.Fatal(err)
	}

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

func (*ApprovalsResource) Status

func (r *ApprovalsResource) Status(ctx context.Context, approvalToken string) (*ApprovalResult, error)

Status fetches the current state of an approval request. It only reads state, so it is safe to expose to a polling frontend.

func (*ApprovalsResource) Wait

func (r *ApprovalsResource) Wait(ctx context.Context, approvalToken string, opts *WaitOptions) (*ApprovalResult, error)

Wait polls an approval until it leaves pending, the deadline passes, or the context is cancelled. It returns the last observed state — a still-pending result means the wait timed out, not that the request was denied.

type Approver

type Approver struct {
	UserID ID `json:"user_id,omitempty"`
	// Email is set only if the server includes it; the current server
	// sends user_id alone.
	Email string `json:"email,omitempty"`
}

Approver identifies the human who responded to an approval request. The server sends it as {"user_id": …} on an approved request and null otherwise.

type AudienceClaim added in v1.2.0

type AudienceClaim []string

AudienceClaim is a JWT `aud` claim, which may be a string or an array.

func (AudienceClaim) Contains added in v1.2.0

func (a AudienceClaim) Contains(value string) bool

Contains reports whether the audience names value.

func (*AudienceClaim) UnmarshalJSON added in v1.2.0

func (a *AudienceClaim) UnmarshalJSON(data []byte) error

UnmarshalJSON accepts a single string or an array of strings.

type AuthResource

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

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

func (*AuthResource) AuthorizationURL

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

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

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) ClientCredentialsWithAssertion added in v1.3.0

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

ClientCredentialsWithAssertion performs the client-credentials grant with a private_key_jwt client assertion (RFC 7523) instead of a secret: the authentication of an agent registered with the "Private key JWT" identity type. Build clientAssertion with ClientAssertionSigner.Assertion; it is single-use.

func (*AuthResource) 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 asks about another user instead of the caller. It must be the
	// user's LumoAuth ID (a UUID) in the caller's organization. The SDK sends
	// it as the request's subject, {"type": "user", "id": UserID}.
	//
	// Asking about someone other than yourself needs the authz:check scope
	// (on the API key or the access token) or the authz.check permission.
	// Without it the server answers 403 INSUFFICIENT_PERMISSIONS; an unknown
	// ID gets 404 SUBJECT_NOT_FOUND. Leave it empty to check the caller.
	UserID string
	// AgentID asks about an agent (its agt_… ID) instead of the caller, with
	// the same authz:check rule as UserID. Set at most one of the two.
	AgentID string
}

CheckOptions carries the optional arguments shared by every check.

type Client

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

Client is the general-purpose LumoAuth API client.

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

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

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

An API key reaches only the admin API, client registration and the permission checks. ABAC, agent and JIT calls need a user access token (WithAccessToken or WithTokenProvider) or an agent credential; ABAC needs the abac:read scope.

A Client is safe for concurrent use.

func New

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) DPoP added in v1.2.0

func (c *Client) DPoP() *DPoPSigner

DPoP returns the signer passed with WithDPoP, or nil.

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 ClientAssertionOptions added in v1.3.0

type ClientAssertionOptions struct {
	// KeyID is the kid of the registered public key. Required by the server
	// when the agent has more than one key.
	KeyID string
	// Algorithm overrides the key's natural algorithm (ES256/ES384/ES512 by
	// curve, EdDSA, RS256). RSA keys may also use RS384, RS512, PS256, PS384
	// or PS512.
	Algorithm string
	// Lifetime is the time until exp: 1s to 10m. Default 60s.
	Lifetime time.Duration
}

ClientAssertionOptions configures a ClientAssertionSigner.

type ClientAssertionSigner added in v1.3.0

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

ClientAssertionSigner signs private_key_jwt client assertions with one key.

func GenerateClientAssertionSigner added in v1.3.0

func GenerateClientAssertionSigner(algorithm, keyID string) (*ClientAssertionSigner, error)

GenerateClientAssertionSigner creates a new key for algorithm: ES256 (default when empty), ES384, ES512, EdDSA, or an RSA algorithm (2048 bits).

func LoadClientAssertionSigner added in v1.3.0

func LoadClientAssertionSigner(pemData string, opts ClientAssertionOptions) (*ClientAssertionSigner, error)

LoadClientAssertionSigner parses a PEM private key (PKCS#8 "PRIVATE KEY", SEC 1 "EC PRIVATE KEY" or PKCS#1 "RSA PRIVATE KEY").

func NewClientAssertionSigner added in v1.3.0

func NewClientAssertionSigner(key crypto.Signer, opts ClientAssertionOptions) (*ClientAssertionSigner, error)

NewClientAssertionSigner wraps a private key: an *ecdsa.PrivateKey on P-256, P-384 or P-521, an ed25519.PrivateKey or an *rsa.PrivateKey of at least 2048 bits.

func (*ClientAssertionSigner) Algorithm added in v1.3.0

func (s *ClientAssertionSigner) Algorithm() string

Algorithm is the JWS alg of the assertions.

func (*ClientAssertionSigner) Assertion added in v1.3.0

func (s *ClientAssertionSigner) Assertion(clientID, audience string) (string, error)

Assertion signs one client assertion for clientID (the agent ID) and audience (the organization's issuer identifier, see IssuerFor).

func (*ClientAssertionSigner) JWKS added in v1.3.0

func (s *ClientAssertionSigner) JWKS() (JWKS, error)

JWKS is {"keys": PublicJWK}: what to register on the agent.

func (*ClientAssertionSigner) KeyID added in v1.3.0

func (s *ClientAssertionSigner) KeyID() string

KeyID is the kid put in every assertion header ("" when unset).

func (*ClientAssertionSigner) PrivateKeyPEM added in v1.3.0

func (s *ClientAssertionSigner) PrivateKeyPEM() (string, error)

PrivateKeyPEM is the private key as PKCS#8 PEM, for your secret store.

func (*ClientAssertionSigner) PublicJWK added in v1.3.0

func (s *ClientAssertionSigner) PublicJWK() (JWK, error)

PublicJWK is the public key with kid (when set), alg and use "sig".

type 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 DPoPProofOption added in v1.2.0

type DPoPProofOption func(*dpopProofConfig)

DPoPProofOption customises one proof.

func WithProofAccessToken added in v1.2.0

func WithProofAccessToken(accessToken string) DPoPProofOption

WithProofAccessToken adds the `ath` claim — the SHA-256 hash of the access token the proof accompanies. Required on every resource request.

func WithProofNonce added in v1.2.0

func WithProofNonce(nonce string) DPoPProofOption

WithProofNonce sets the `nonce` claim explicitly, overriding the nonce the signer remembers for the target's origin. Pass "" to omit the claim.

type DPoPRequest added in v1.2.0

type DPoPRequest struct {
	// Method is the HTTP method of the request.
	Method string
	// URL is the absolute request URL. Query and fragment are ignored.
	URL string
	// Proof is the value of the DPoP header ("" when absent).
	Proof string
	// Scheme is the Authorization scheme the token came with: "DPoP" or
	// "Bearer".
	Scheme string
}

DPoPRequest describes the incoming request a DPoP-bound token arrived with, so the proof can be checked against it. Build one with DPoPRequestFromHTTP.

func DPoPRequestFromHTTP added in v1.2.0

func DPoPRequestFromHTTP(r *http.Request) *DPoPRequest

DPoPRequestFromHTTP reads the DPoP-relevant parts of an incoming request. The scheme of the URL is https when the connection is TLS or an X-Forwarded-Proto header says so, http otherwise; the host is r.Host. Behind a proxy that rewrites the host, set DPoPRequest.URL yourself.

type DPoPSigner added in v1.2.0

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

DPoPSigner signs RFC 9449 proofs with one private key.

func LoadDPoPSigner added in v1.2.0

func LoadDPoPSigner(pemData string) (*DPoPSigner, error)

LoadDPoPSigner parses a PEM private key (PKCS#8 "PRIVATE KEY" or SEC 1 "EC PRIVATE KEY") into a signer. The key must be P-256 or Ed25519.

func NewDPoPSigner added in v1.2.0

func NewDPoPSigner() (*DPoPSigner, error)

NewDPoPSigner generates a fresh P-256 key and returns a signer for ES256 proofs — the recommended default.

signer, err := lumoauth.NewDPoPSigner()
agent, err := lumoauth.NewAgent(lumoauth.AgentConfig{DPoP: signer})

The key lives only in memory; a new process gets a new key, which is fine because the tokens it binds are short-lived. To keep one key across restarts, generate it once (GenerateDPoPKeyPEM) and load it with LoadDPoPSigner.

func NewDPoPSignerEd25519 added in v1.2.0

func NewDPoPSignerEd25519() (*DPoPSigner, error)

NewDPoPSignerEd25519 generates a fresh Ed25519 key and returns a signer for EdDSA proofs.

func NewDPoPSignerFromKey added in v1.2.0

func NewDPoPSignerFromKey(key crypto.Signer) (*DPoPSigner, error)

NewDPoPSignerFromKey wraps an existing private key: an *ecdsa.PrivateKey on P-256 (ES256) or an ed25519.PrivateKey (EdDSA). Other key types are a *ValidationError.

func (*DPoPSigner) Algorithm added in v1.2.0

func (s *DPoPSigner) Algorithm() string

Algorithm returns the JWS algorithm of the proofs: "ES256" or "EdDSA".

func (*DPoPSigner) AuthorizeRequest added in v1.2.0

func (s *DPoPSigner) AuthorizeRequest(req *http.Request, accessToken string) error

AuthorizeRequest sets the Authorization header for a resource call — an MCP server, say — and, when the token is DPoP-bound (carries cnf.jkt), the `DPoP` scheme plus a proof over the request with `ath`:

req, _ := http.NewRequestWithContext(ctx, "POST", "https://mcp.example.com/mcp", body)
if err := signer.AuthorizeRequest(req, mcpToken); err != nil {
    return err
}

An unbound token is sent as `Authorization: Bearer`, without a proof. If the server answers 401 with a DPoP-Nonce header, call RememberNonce on the response and send the request again.

func (*DPoPSigner) Nonce added in v1.2.0

func (s *DPoPSigner) Nonce(rawURL string) string

Nonce returns the nonce the signer remembers for rawURL's origin, or "".

func (*DPoPSigner) Proof added in v1.2.0

func (s *DPoPSigner) Proof(method, rawURL string, opts ...DPoPProofOption) (string, error)

Proof signs a DPoP proof for one HTTP request.

method is the HTTP method; rawURL is the request URL. The proof carries `htm` (the method, upper-case), `htu` (the URL without query or fragment), `iat`, a random `jti`, the `nonce` the signer remembers for that origin unless WithProofNonce overrides it, and `ath` when WithProofAccessToken is given.

func (*DPoPSigner) PublicJWK added in v1.2.0

func (s *DPoPSigner) PublicJWK() JWK

PublicJWK returns the public key as it appears in each proof's header. It never includes private members.

func (*DPoPSigner) RememberNonce added in v1.2.0

func (s *DPoPSigner) RememberNonce(resp *http.Response) bool

RememberNonce reads a DPoP-Nonce header from a response and stores it for the origin of the request that produced it. It reports whether a nonce was present. Call it on every response from a server that uses DPoP nonces; the SDK does so for its own requests.

func (*DPoPSigner) SetNonce added in v1.2.0

func (s *DPoPSigner) SetNonce(rawURL, nonce string)

SetNonce remembers a server-issued nonce for rawURL's origin (scheme://host[:port]). Later proofs for that origin carry it. Pass "" to forget the nonce.

func (*DPoPSigner) Thumbprint added in v1.2.0

func (s *DPoPSigner) Thumbprint() string

Thumbprint returns the RFC 7638 thumbprint of the public key — the value the server writes into a bound token's cnf.jkt.

type 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) DelegateToSubAgentForResource added in v1.1.0

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

DelegateToSubAgentForResource is DelegateToSubAgent with an RFC 8707 resource indicator for the sub-agent's token (its `aud`).

func (*DelegationChain) DelegatedToken

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. The token is bound to this agent; use ExchangeForResource to bind it to the API it will be sent to.

func (*DelegationChain) ExchangeForResource added in v1.1.0

func (c *DelegationChain) ExchangeForResource(ctx context.Context, sessionID, resource string, scopes ...string) (string, error)

ExchangeForResource is Exchange with an RFC 8707 resource indicator: the https URL in resource becomes the delegated token's `aud`. The result replaces the session's cached delegated token.

func (*DelegationChain) HandleConsentCallback

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

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

func (*DelegationChain) HasDelegation

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

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

func (*DelegationChain) Revoke

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

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

func (*DelegationChain) RevokeAll

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

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

func (*DelegationChain) SetUserToken

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

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

type DelegationResource

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

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

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

func (*DelegationResource) ConsentURL

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

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

func (*DelegationResource) Exchange

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

Exchange combines a subject token (the user) with an actor token (the agent) into a delegated token. The resulting JWT carries an `act` claim recording the chain, so every downstream action is attributable to both. The token is bound to the acting agent; use ExchangeForResource to bind it to the API it will be sent to.

func (*DelegationResource) ExchangeCode

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

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

func (*DelegationResource) ExchangeForResource added in v1.1.0

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

ExchangeForResource is Exchange with an RFC 8707 resource indicator: the https URL in resource becomes the delegated token's `aud`.

func (*DelegationResource) ParseActorChain

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

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

func (*DelegationResource) RefreshUserToken

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

RefreshUserToken refreshes a user's delegated access token.

func (*DelegationResource) Revoke

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

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

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 FetchAccessTokenJWKS added in v1.2.0

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

FetchAccessTokenJWKS retrieves an organization's token-signing keys: it reads jwks_uri from {issuer}/.well-known/openid-configuration and fetches that document.

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. It is a reviewer call: it needs a browser session or a user access token with the jit:approve scope.

func (*JitResource) Request

func (r *JitResource) Request(ctx context.Context, params RequestPermissionParams) (*JitRequest, error)

Request asks for a Just-in-Time permission. Low-risk requests come back approved; higher-risk ones enter human-in-the-loop review as pending — see JITContext.RequestPermission to wait for the decision.

func (*JitResource) Status

func (r *JitResource) Status(ctx context.Context, requestID string) (*JitRequest, error)

Status fetches the current state of a permission request.

func (*JitResource) Token

func (r *JitResource) Token(ctx context.Context, requestID string) (*TokenResponse, error)

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

type JitTask

type JitTask struct {
	TaskID        string `json:"task_id"`
	CaepSessionID string `json:"caep_session_id,omitempty"`
	ExpiresAt     string `json:"expires_at,omitempty"`

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

JitTask is an ephemeral task (an isolated agent sub-identity).

func (*JitTask) UnmarshalJSON

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 covers secured MCP servers. Token exchanges the caller's token for one bound to a single MCP server (RFC 8693 token exchange). AuthorizeTool lets an MCP server ask whether a caller may run one tool.

func (*McpResource) AuthorizeTool added in v1.2.0

func (r *McpResource) AuthorizeTool(ctx context.Context, params McpToolAuthorizeParams) (*McpToolDecision, error)

AuthorizeTool asks whether a user or an agent may run one tool on an MCP server. The MCP server calls it after it has verified the caller's token.

The client must authenticate with the MCP server's own client-credentials token, which needs the mcp:authorize scope. The server's OAuth client must also be one of the MCP server's tool authorizers. Never pass the caller's token here: the MCP specification forbids token passthrough.

NewAgent runs the client-credentials grant and keeps the token fresh, so it works for the MCP server's own client too:

mcpAuth, err := lumoauth.NewAgent(lumoauth.AgentConfig{
    OrgID: "acme-corp", ClientID: mcpClientID, ClientSecret: mcpClientSecret,
    Scopes: []string{"mcp:authorize"},
})
// handle err
decision, err := mcpAuth.Mcp.AuthorizeTool(ctx, lumoauth.McpToolAuthorizeParams{
    ServerID:    "mcp_0123456789abcdef01234567",
    SubjectType: "user",
    SubjectID:   verifiedSub, // the `sub` claim of the verified MCP token
    Tool:        "send_invoice",
})

A deny is not an error. It comes back with Allowed set to false and a nil error. A 403 without an `allowed` key, such as insufficient_scope, is an error that matches ErrPermissionDenied.

func (*McpResource) Token

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

Token returns an access token bound to one MCP server.

token, err := client.Mcp.Token(ctx, "https://mcp.example.com/mcp", "")

serverID is the Resource URI that the MCP server is registered with in LumoAuth. It is an https URL, and the SDK sends it as the RFC 8707 `resource` parameter. The token names exactly one MCP server, and LumoAuth sets the token's `aud` from this value. A plain-http URL is accepted only for localhost and private hosts. Pass an empty subjectToken to exchange the client's own bearer token.

The token works only at that MCP server. LumoAuth's own API refuses it. With a DPoP signer configured (WithDPoP, or AgentConfig.DPoP), the exchange carries a DPoP proof and the token comes back bound to the key (token_type "DPoP") — which is what an MCP server registered with "Require DPoP" expects. Present it with DPoPSigner.AuthorizeRequest. Without a signer the exchange sends no proof and the token is a plain bearer token.

func (*McpResource) TokenDetailed

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

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

type McpToken

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

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

type McpToolAuthorizeParams added in v1.2.0

type McpToolAuthorizeParams struct {
	// ServerID is the registered MCP server ID, for example
	// "mcp_0123456789abcdef01234567". It is not the Resource URI. Required.
	ServerID string
	// SubjectType is "user" or "agent". Required.
	SubjectType string
	// SubjectID is the `sub` claim of the verified MCP token. For a user it
	// is the user ID. For an agent it may be the agent ID ("agt_…") or the
	// `sub` claim as is ("agent_agt_…"). Required.
	SubjectID string
	// Tool is the name of the MCP tool. Required.
	Tool string
}

McpToolAuthorizeParams describes one per-tool question that an MCP server asks about a caller it has already verified.

type McpToolDecision added in v1.2.0

type McpToolDecision struct {
	Allowed  bool            `json:"allowed"`
	Subject  McpToolSubject  `json:"subject"`
	Resource McpToolResource `json:"resource"`
}

McpToolDecision is the answer to McpResource.AuthorizeTool. A deny comes back with Allowed set to false and a nil error.

type McpToolResource added in v1.2.0

type McpToolResource struct {
	Type string `json:"type"`
	ID   string `json:"id"`
}

McpToolResource names the tool that a decision covers. Type is "mcp_tool" and ID is "<serverId>/<tool>".

type McpToolSubject added in v1.2.0

type McpToolSubject struct {
	Type string `json:"type"`
	ID   string `json:"id"`
}

McpToolSubject names the caller of an MCP tool: a user or an agent.

type MemoryReplayCache added in v1.2.0

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

MemoryReplayCache is an in-process ReplayCache. The zero value is ready to use.

func NewMemoryReplayCache added in v1.2.0

func NewMemoryReplayCache() *MemoryReplayCache

NewMemoryReplayCache returns an empty in-process replay cache.

func (*MemoryReplayCache) Seen added in v1.2.0

func (c *MemoryReplayCache) Seen(jti string, ttl time.Duration) bool

Seen implements ReplayCache.

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 WithDPoP added in v1.2.0

func WithDPoP(signer *DPoPSigner) Option

WithDPoP binds the client's token requests to a DPoP key (RFC 9449). Every token the client obtains through client.Auth — client credentials, token exchange, MCP tokens — is then sender-constrained (token_type "DPoP"), and the client presents bound tokens with the DPoP scheme and a fresh proof. See DPoPSigner.

func WithHTTPClient

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.

A user access token needs the authz:read scope (or the blanket admin scope). Organization API keys cannot hold that scope, so with an API key List fails with an *APIError whose RequiredScopes is ["authz:read"].

func (*PermissionsResource) ListSlugs

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

ListSlugs returns just the permission slugs granted to the principal.

type RecordedUsage added in v1.4.0

type RecordedUsage struct {
	Tokens  int     `json:"tokens"`
	CostUSD float64 `json:"cost_usd"`
}

AgentAskResult is the decision returned by the Ask API. RecordedUsage is the usage that LumoAuth added to the agent's budget windows.

type RefreshParams

type RefreshParams struct {
	// RefreshToken is the token from a prior response. Required.
	RefreshToken string
	// ResourceToken must be a 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 ReplayCache added in v1.2.0

type ReplayCache interface {
	Seen(jti string, ttl time.Duration) bool
}

ReplayCache remembers DPoP proof identifiers so a captured proof cannot be presented twice. Seen records jti and reports whether it was already present; entries may be forgotten after ttl. Implementations must be safe for concurrent use. A shared store (Redis, say) is the right choice for a resource server with several replicas.

type 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 TokenConfirmation added in v1.2.0

type TokenConfirmation struct {
	// JKT is the RFC 7638 thumbprint of the DPoP key the token is bound to.
	JKT string `json:"jkt,omitempty"`
}

TokenConfirmation is the `cnf` claim.

type TokenExchangeParams

type TokenExchangeParams struct {
	// SubjectToken is the token representing the principal being acted
	// for. Required. The subject must still be active: a deactivated or
	// blocked user, or a suspended agent, gets invalid_grant. A JIT task
	// token is never accepted as the subject.
	SubjectToken string
	// ActorToken is the token of the party doing the acting (the agent);
	// set it to build a delegation chain with an `act` claim.
	ActorToken string
	// Audience is sent as the RFC 8693 `audience` parameter. LumoAuth binds
	// the issued token's `aud` from Resource, not from Audience.
	Audience string
	// Resource is the RFC 8707 resource indicator — the absolute https URL
	// of the API the issued token is for. It becomes its `aud`; without it
	// an agent on-behalf-of token is bound to the acting agent's id.
	Resource string
	// Scopes optionally narrows the issued token.
	Scopes []string
	// SubjectTokenType declares what SubjectToken is (TokenTypeAccessToken,
	// TokenTypeJWT, TokenTypeIDToken or TokenTypeRefreshToken). Empty means
	// TokenTypeAccessToken. The server refuses a token that does not match
	// its declared type (sdk-contract/token-types.json).
	SubjectTokenType string
	// ActorTokenType declares what ActorToken is; empty means
	// TokenTypeAccessToken.
	ActorTokenType string
}

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 UsageReportResult added in v1.4.0

type UsageReportResult struct {
	Recorded RecordedUsage `json:"recorded"`
	Budget   *AgentBudget  `json:"budget,omitempty"`
}

UsageReportResult is the answer to AgentsResource.ReportUsage: what was recorded, and the agent's budget after it (the same shape as BudgetPolicy in UserInfo; Budget.Exhausted() means that the next metered call gets 429).

type User

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

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

func UserFromContext

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
	// Reason is a stable, machine-readable cause set by the token
	// verifiers (one of the TokenRejected* constants); "" elsewhere. Read
	// it with RejectionReason.
	Reason string
}

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

func NewValidationError

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

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

type VerifyOptions

type VerifyOptions struct {
	// Issuer is the trusted issuer URL, e.g.
	// "https://app.lumoauth.dev/orgs/acme-corp/api/v1". Required.
	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