lumoauth

package module
v1.8.0 Latest Latest
Warning

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

Go to latest
Published: Nov 29, 2026 License: MIT Imports: 40 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.
  • Verification of requests that personal agents send to your API (Personal Agent Protocol).

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, LUMOAUTH_CUSTOM_DOMAIN, 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.

An organization that serves LumoAuth on its own domain needs neither of the two. See Use a custom domain.

Use a custom domain

An organization can serve LumoAuth on its own domain, for example https://auth.acme.com. Pass that domain with WithCustomDomain, or set LUMOAUTH_CUSTOM_DOMAIN. This program is complete:

package main

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

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

func main() {
    client, err := lumoauth.New(
        lumoauth.WithCustomDomain("auth.acme.com"), // or "https://auth.acme.com"
        lumoauth.WithAccessToken(os.Getenv("USER_ACCESS_TOKEN")),
    )
    if err != nil {
        log.Fatal(err) // a ConfigError when the value is not a valid domain
    }

    // POST https://auth.acme.com/api/v1/abac/check
    decision, err := client.Abac.Check(context.Background(), lumoauth.AbacCheckParams{
        ResourceType: "document",
        Action:       "read",
        ResourceID:   "doc-123",
    })
    if err != nil {
        log.Fatal(err)
    }

    issuer, _ := client.Issuer() // https://auth.acme.com
    fmt.Println(decision.Allowed, issuer)
}

With a custom domain, three things differ from the platform host:

  • Paths have no /orgs/... segment. The SDK sends every request to the domain. A route without that segment, such as /api/v1/authz/check, keeps its path.
  • The organization ID is not needed. When you set it too, the SDK never puts it in a path.
  • The issuer is the bare domain. It is the iss of the organization's OAuth and OpenID Connect tokens, and the audience of a client assertion. client.Issuer() returns it. AAuth is the one exception; see AAuth on a custom domain.
Address Platform host Custom domain
Token endpoint https://app.lumoauth.dev/orgs/acme-corp/api/v1/oauth/token https://auth.acme.com/api/v1/oauth/token
Permission check https://app.lumoauth.dev/api/v1/authz/check https://auth.acme.com/api/v1/authz/check
Issuer https://app.lumoauth.dev/orgs/acme-corp/api/v1 https://auth.acme.com

A custom domain wins over the base URL: WithBaseURL and LUMOAUTH_URL are then not used for any request.

The value is a host name or an https:// origin. The SDK turns it into https://<host>[:port] with a lower-case host. http:// is accepted only for localhost, 127.0.0.1 and [::1]. A value with a path, a query, a fragment or credentials is a ConfigError, which the constructor returns. An empty value means "not set".

Every constructor and helper that addresses LumoAuth takes the option:

Where How you set it
lumoauth.New WithCustomDomain(domain), or LUMOAUTH_CUSTOM_DOMAIN
NewAgent, NewWebAuth, NewAAuthClient The CustomDomain field of the config struct, or LUMOAUTH_CUSTOM_DOMAIN
NewJITContext, NewDelegationChainForApplication, NewDelegationChain Nothing: they follow the agent that you pass
VerifyAccessToken, RequireAccessToken AccessTokenVerifyOptions.CustomDomain, in place of Issuer
VerifyAuthToken VerifyOptions.CustomDomain
Key caches NewAccessTokenKeyCacheForCustomDomain, NewJWKSCacheForCustomDomain

The two token verifiers do not read the environment variable. With CustomDomain, VerifyAccessToken accepts exactly one issuer, the bare domain. An access token that names the platform issuer is refused.

Three details matter when you build requests yourself:

  • client.OrgPath("/admin/users") returns /api/v1/admin/users on a custom domain. Give Do and DoRaw paths in that form. A path that starts with the /orgs/... segment of your own organization also works when the client has the organization ID: the SDK removes the segment. It never changes a path of another organization.
  • The generated OpenAPI client puts /orgs/{orgId} in every path. On a custom domain, set WithOrgID as well and pass the same ID to the generated client's calls. The HTTP client from APIConfig then removes the segment. Without the organization ID, the generated client cannot reach a custom domain.
  • A TokenSource of your own that uses a custom domain must have the method CustomDomain() string, as *Agent has. NewJITContext and the delegation chain constructors read it.
AAuth on a custom domain

AAuth does not follow the issuer rule. LumoAuth names the AAuth issuer with the platform address on every host, for example https://app.lumoauth.dev/orgs/acme-corp/api/v1. AAuth tokens carry that value as iss, and an agent addresses it as the audience. The SDK therefore never derives the AAuth issuer from the custom domain:

  • AAuthClient sends its requests to the custom domain, without the /orgs/... segment, like every other client.
  • aauth.ResolveIssuer(ctx) returns the AAuth issuer. With a custom domain it reads the issuer member of the issuer metadata document at https://auth.acme.com/api/v1/.well-known/aauth-issuer, once. aauth.Issuer() makes no request, so it returns an empty string until ResolveIssuer has run.
  • VerifyAuthToken with VerifyOptions.CustomDomain reads the trusted issuer from the same document and keeps it for one hour. It reads the keys from https://auth.acme.com/api/v1/aauth/jwks.json. A token that names the bare domain is refused.
  • Set AAuthConfig.Issuer or VerifyOptions.Issuer to name the AAuth issuer yourself. The SDK then uses that value and does not read the document.
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.
Client credentials of a confidential application WithClientCredentials Authorization: Basic, on the client.Poppy calls only The three client.Poppy calls. The application's allowed scopes must include poppy:verify. See Verify requests from personal agents.

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. The client.Poppy calls send the client credentials and nothing else. No other call sends the client credentials.

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. Not needed with a custom domain. $LUMOAUTH_ORG_ID
WithCustomDomain(domain) The organization's own domain, for example auth.acme.com. It wins over the base URL. See Use a custom domain. $LUMOAUTH_CUSTOM_DOMAIN
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
WithClientCredentials(id, secret) The client ID and client secret of a confidential application, for client.Poppy 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/ followed by the SDK's 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
WithoutCredential() Lets New build a client without a credential, for addresses and the calls that authenticate themselves off

New returns a ConfigError when no credential is configured. It needs an API key, an access token, a token provider or client credentials, unless you pass WithoutCredential(). A client that has only client credentials can call client.Poppy and nothing else.

A client built with WithoutCredential() builds addresses (Auth.AuthorizationURL, Auth.EndSessionURL, Issuer, OrgPath) and makes the calls that carry their own authentication: the token endpoint calls of client.Auth (code exchange, refresh, client credentials with a secret or a client assertion, token exchange with client authentication), Auth.Revoke, Auth.UserInfo with a token, and Agents.Attest. A call that needs a credential is sent without one, and the server's 401 matches ErrAuthentication. An API key from LUMOAUTH_API_KEY is still used when it is set.

// A sign-in that only needs addresses and the token endpoint.
client, err := lumoauth.New(lumoauth.WithOrgID("acme-corp"), lumoauth.WithoutCredential())
authorizeURL, err := client.Auth.AuthorizationURL(lumoauth.AuthorizationURLParams{
    ClientID: clientID, RedirectURI: "https://app.example.com/callback", State: state,
    CodeChallenge: challenge,
})
Environment variables
Variable Read by Meaning
LUMOAUTH_URL every constructor The LumoAuth instance
LUMOAUTH_ORG_ID every constructor The organization slug
LUMOAUTH_CUSTOM_DOMAIN every constructor The organization's own domain. It wins over LUMOAUTH_URL.
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, CustomDomain 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 the custom domain when CustomDomain is set, IssuerFor(BaseURL, OrgID) otherwise
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)

Each entry of MatchedPolicies has the policy's ID as text (the server sends a number, so policy 81 gives "81") and its Name. A caller with the policies.view permission also gets Effect and Priority; the full policy is in decision.Raw.

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 an encrypted cookie (see The session 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 ends the LumoAuth session too: it sends the browser to the organization's end-session endpoint with the session's ID token (id_token_hint), and LumoAuth sends it on to PostLogoutRedirect. Register the absolute address of PostLogoutRedirect (for example https://app.example.com/) on the OAuth client as a post-logout redirect URI; a path is made absolute with the request's origin. Without that registration, the user lands on LumoAuth's own sign-out page. Set LocalLogout: true to end only your app's session.

Another site must not be able to sign the user out (logout CSRF), so /auth/logout checks where a request comes from:

  • A GET signs out at once when the browser says that it did not come from another site: Sec-Fetch-Site is same-origin (a link or button of your app) or none (a typed address, a bookmark). Otherwise, also without that header, it answers with a small page that asks "Do you want to sign out?" and changes nothing. Its button POSTs to the same route.
  • A POST signs out when its Origin is your app's own origin, or, without an Origin (or with Origin: null), when Sec-Fetch-Site is same-origin. Anything else gets 403.
  • Other methods get 405.

A sign-out link in your app keeps working unchanged. To let pages of another origin that you trust POST a sign-out, list it in LogoutAllowedOrigins. LumoAuth's own end-session endpoint is not affected.

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. Required unless CustomDomain is set. $LUMOAUTH_ORG_ID
CustomDomain The organization's own domain. The sign-in, token and UserInfo addresses are then on that domain. $LUMOAUTH_CUSTOM_DOMAIN
ClientID The OAuth client of your app (required) none
ClientSecret Required for confidential clients. Public clients use PKCE alone. none
SessionSecret The secret from which the session cookie's encryption and signing keys are derived. Required unless Store is set. 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. Register the absolute address of PostLogoutRedirect as a post-logout redirect URI. /
LocalLogout /auth/logout ends only your app's session and leaves the user signed in at LumoAuth off
LogoutAllowedOrigins Other origins (for example https://portal.example.com) whose POST to /auth/logout signs the user out. A GET from another site still gets the confirmation page. your app's origin only
AuthorizationDetails Fine-grained permissions to ask for at each sign-in (RFC 9396): a list of objects, each with a type. What LumoAuth granted is in SessionTokens.AuthorizationDetails. none
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
Store Another sessions.Store (gorilla/sessions), for example a server-side store. With a Store, SessionSecret, CookieSecure and SessionMaxAge are not used. the encrypted cookie
ClientAuth Authenticates the app with a key instead of ClientSecret: AssertionSigner (private_key_jwt, a new assertion for each request) or Attestation. The pushed request, the code exchange, the refresh and the revocation at logout use it. Leave ClientSecret empty. none
RequestObjectSigner Signs each sign-in request as a request object (JAR). With UsePAR it is pushed; otherwise it goes in the redirect. It may be the key of ClientAuth.AssertionSigner. none
DPoP Binds the user's tokens to this key: the pushed request, the code exchange and the refresh carry a proof, and UserInfo and ClientForRequest present the tokens with the DPoP scheme. Every instance of the app must load the same key (LoadDPoPSigner). none
UsePAR Pushes each sign-in request to LumoAuth first (RFC 9126). The browser then gets only client_id and request_uri. Turn it on for applications with Require PAR. off
ResponseMode "jwt" or "query.jwt": LumoAuth signs its answer (JARM), and the callback verifies it and refuses an unsigned one. form_post.jwt and fragment.jwt are refused: the cookie does not come with a cross-site POST, and a fragment never reaches the server. the plain answer

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

The session holds the user's profile, the access token, the refresh token and the ID token. /auth/logout needs the ID token to end the LumoAuth session. The cookie is encrypted with AES-256 and signed with HMAC-SHA256 (gorilla/securecookie). Both keys are derived from SessionSecret, so a person who holds the cookie cannot read the tokens or change them.

A browser keeps at most 4,096 bytes per cookie. With the default scopes the session is about 4,300 bytes, so the SDK splits it: the first part goes in lumo_session, the next parts in lumo_session.1, lumo_session.2, and so on. Every save expires the parts that the session no longer needs. A session that needs more than eight parts is refused with a ConfigError; use a server-side store for it.

To keep the session on the server and only its ID in the cookie, pass a store:

store := sessions.NewFilesystemStore("/var/lib/myapp/sessions",
    []byte(os.Getenv("SESSION_AUTH_KEY")),       // 32 or 64 random bytes
    []byte(os.Getenv("SESSION_ENCRYPTION_KEY"))) // 32 random bytes
store.Options = &sessions.Options{Path: "/", HttpOnly: true, Secure: true,
    SameSite: http.SameSiteLaxMode, MaxAge: 30 * 24 * 3600}
store.MaxLength(0) // the store keeps the data in a file, not in the cookie

auth, err := lumoauth.NewWebAuth(lumoauth.WebConfig{
    ClientID: os.Getenv("LUMO_CLIENT_ID"), ClientSecret: os.Getenv("LUMO_CLIENT_SECRET"),
    Store:    store, // a Redis or database store works the same way
})

Sessions written by v1.7.0 and earlier (a signed cookie without encryption) are still read with the same SessionSecret, so an upgrade signs nobody out. The next save writes the encrypted form.

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

// 4. Sign out of LumoAuth too: clear your session, then send the browser here.
logout, err := client.Auth.EndSessionURL(lumoauth.EndSessionURLParams{
    IDTokenHint:           tokens.IDToken,
    PostLogoutRedirectURI: "https://app.example.com/", // registered on the client
})

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

// Exchange a user's token for one that your API accepts (RFC 8693). A confidential
// application authenticates: with its secret (Basic by default, or
// ClientAuthMethod: lumoauth.ClientSecretPost) or with ClientAssertion (private_key_jwt).
// Token exchange must be switched on for the application.
apiToken, err := client.Auth.TokenExchange(ctx, lumoauth.TokenExchangeParams{
    SubjectToken: tokens.AccessToken,
    Resource:     "https://api.example.com/orders",
    ClientID:     clientID,
    ClientSecret: clientSecret,
})

// The same grant for one API: the token's aud is the resource, not the client ID.
forAPI, err := client.Auth.ClientCredentialsWithParams(ctx, lumoauth.ClientCredentialsParams{
    ClientID: clientID, ClientSecret: clientSecret,
    Scopes:   []string{"reports:read"},
    Resource: "https://api.example.com/",
})

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

Ask for fine-grained permissions (authorization_details)

A rich authorization request (RFC 9396) asks for exactly what the person approves, for example one payment:

details := []map[string]any{{
    "type":             "payment_initiation",
    "actions":          []string{"initiate"},
    "instructedAmount": map[string]any{"currency": "EUR", "amount": "123.50"},
}}
url, err := client.Auth.AuthorizationURL(lumoauth.AuthorizationURLParams{
    ClientID: clientID, RedirectURI: redirectURI, State: state, CodeChallenge: challenge,
    AuthorizationDetails: details,
})
// tokens.AuthorizationDetails holds what LumoAuth granted.

// Later, a token for a part of the grant only:
fresh, err := client.Auth.RefreshToken(ctx, lumoauth.RefreshTokenParams{
    RefreshToken: tokens.RefreshToken, ClientID: clientID,
    AuthorizationDetails: []map[string]any{{"type": "payment_initiation", "actions": []string{"status"}}},
})

In RefreshTokenParams and ExchangeCodeParams, AuthorizationDetails asks for a part of the grant: nil sends nothing (the token gets the whole grant), an empty list sends [] (none), and a wider request is an *APIError with the code invalid_authorization_details, as is a refused request at PAR or the device authorization endpoint. At the authorization endpoint the refusal comes back in the callback (WebAuth answers it with a 400 page).

AuthorizationDetails works the same in PushAuthorizationRequest, CreateRequestObject (as a JSON array claim), DeviceAuthorizationParams and WebConfig. The SDK sends it as a JSON string and checks only that each entry is an object with a non-empty type; LumoAuth checks the types and their members. TokenResponse, SessionTokens, TokenIntrospection and the AccessTokenClaims of VerifyAccessToken have an AuthorizationDetails field, with members that the SDK does not model kept as they are.

How your application authenticates

The calls below take a lumoauth.ClientAuth: the client ID and at most one credential.

Field Method
ClientID alone A public client, which sends only client_id
ClientSecret The secret in form fields, or with ClientAuthMethod: lumoauth.ClientSecretBasic in an HTTP Basic header
AssertionSigner private_key_jwt: the SDK signs a new client assertion for each request
ClientAssertion An assertion that you signed. It works once, so the polling calls refuse it
Attestation Attestation-based client authentication; see Authenticate an app instance with an attestation

ExchangeCodeParams and RefreshTokenParams take a ClientAuth too, for applications that authenticate with a key. A refused client authentication is an *APIError with the code invalid_client that matches ErrAuthentication, at 401 and at 400 alike.

Sign in on a device without a browser

The device authorization grant (RFC 8628) signs a person in on a device that cannot show a sign-in page: a CLI, a TV app, an agent on a server. The device shows a code, and the person enters it on their phone or laptop. The application needs the device code grant.

auth := lumoauth.ClientAuth{ClientID: os.Getenv("LUMO_CLIENT_ID")} // a public client
start, err := client.Auth.DeviceAuthorization(ctx, lumoauth.DeviceAuthorizationParams{
    ClientAuth: auth,
    Scopes:     []string{"openid", "profile", "offline_access"},
})
if err != nil {
    return err
}
fmt.Printf("Open %s and enter %s\n", start.VerificationURI, start.UserCode)

tokens, err := client.Auth.PollDeviceToken(ctx, start.DeviceCode, start.PollOptions(auth))
switch {
case errors.Is(err, lumoauth.ErrApprovalDenied):
    // The person denied the request.
case errors.Is(err, lumoauth.ErrApprovalTimeout):
    // The code expired before the person answered.
case err != nil:
    return err
}

PollDeviceToken waits Interval before each poll (5 seconds by default) and keeps polling on authorization_pending. On slow_down it waits 5 seconds longer from then on. It stops at ExpiresIn, or when the context ends. VerificationURIComplete holds the code already, for a QR code. A confidential client authenticates with its credential instead of ClientID alone.

Push the authorization request first (PAR)

With pushed authorization requests (RFC 9126), your server sends the parameters of a sign-in to LumoAuth first. The browser then gets only client_id and a request_uri, so it never sees or changes the parameters. Applications with Require PAR or a FAPI profile must sign in this way.

auth := lumoauth.ClientAuth{ClientID: clientID, ClientSecret: clientSecret}
pushed, err := client.Auth.PushAuthorizationRequest(ctx, lumoauth.AuthorizationURLParams{
    RedirectURI:   "https://app.example.com/callback",
    Scope:         "openid profile",
    State:         state,
    CodeChallenge: challenge,
}, auth)
if err != nil {
    return err
}
redirect, err := client.Auth.AuthorizationURL(lumoauth.AuthorizationURLParams{
    ClientID: clientID, RequestURI: pushed.RequestURI,
})

The callback and the code exchange stay the same. WebAuth does this for you with UsePAR: true. With a DPoP signer on the client (WithDPoP), the pushed request carries a proof, which binds the authorization code to the key.

Sign the request and the answer (JAR, JARM, FAPI 2)

For a web app, WebAuth does all of it. An application with the FAPI 2.0 profile "Advanced" signs in like this:

key, err := lumoauth.LoadClientAssertionSigner(os.Getenv("APP_PRIVATE_KEY"),
    lumoauth.ClientAssertionOptions{KeyID: "app-key-1", Algorithm: "PS256"})
dpop, err := lumoauth.LoadDPoPSigner(os.Getenv("APP_DPOP_KEY")) // the same key on every instance
auth, err := lumoauth.NewWebAuth(lumoauth.WebConfig{
    Organization:        "acme-corp",
    ClientID:            os.Getenv("LUMO_CLIENT_ID"),
    ClientAuth:          &lumoauth.ClientAuth{AssertionSigner: key}, // private_key_jwt, no secret
    RequestObjectSigner: key,                                        // JAR
    UsePAR:              true,                                       // PAR
    ResponseMode:        lumoauth.ResponseModeJWT,                   // JARM
    DPoP:                dpop,                                       // DPoP-bound tokens
    SessionSecret:       os.Getenv("SESSION_SECRET"),
})

The same steps without the web helper:

A signed request object (JAR, RFC 9101) proves that the parameters come from your application. A signed answer (JARM) proves that the code comes from LumoAuth and is for your application. The FAPI 2.0 profile "Advanced" needs both, plus PAR, DPoP and a key instead of a secret.

signer, err := lumoauth.LoadClientAssertionSigner(os.Getenv("APP_PRIVATE_KEY"),
    lumoauth.ClientAssertionOptions{KeyID: "app-key-1", Algorithm: "PS256"})
// Register signer.JWKS() (the public key) on the application.
dpop, _ := lumoauth.NewDPoPSigner()
client, _ := lumoauth.New(lumoauth.WithoutCredential(), lumoauth.WithDPoP(dpop))
auth := lumoauth.ClientAuth{ClientID: clientID, AssertionSigner: signer}

object, err := client.Auth.CreateRequestObject(lumoauth.AuthorizationURLParams{
    ClientID:      clientID,
    RedirectURI:   "https://app.example.com/callback",
    Scope:         "openid profile",
    State:         state,
    CodeChallenge: challenge,
    ResponseMode:  lumoauth.ResponseModeJWT, // ask for a signed answer
}, lumoauth.RequestObjectOptions{Signer: signer})
pushed, err := client.Auth.PushAuthorizationRequest(ctx,
    lumoauth.AuthorizationURLParams{ClientID: clientID, Request: object}, auth)
// … redirect with pushed.RequestURI as above. In the callback:
answer, err := client.Auth.VerifyAuthorizationResponse(ctx, r.URL.Query().Get("response"),
    lumoauth.AuthorizationResponseOptions{ClientID: clientID, ExpectedState: state})
if err != nil {
    return err // not signed by the organization, not for this client, expired, another state
}
if answer.Error != "" {
    return fmt.Errorf("sign-in failed: %s", answer.Error)
}
tokens, err := client.Auth.ExchangeCode(ctx, lumoauth.ExchangeCodeParams{
    Code: answer.Code, RedirectURI: "https://app.example.com/callback",
    CodeVerifier: verifier, ClientAuth: &auth,
})

The request object has the header typ: oauth-authz-req+jwt and the claims of the request plus iss (the client ID), aud (the organization's issuer), iat, nbf, exp (5 minutes by default, at most 10) and a random jti. LumoAuth accepts RS256–RS512, PS256–PS512 and ES256–ES512 for it. VerifyAuthorizationResponse checks the signature against the organization's keys, iss, aud and exp, and refuses alg: none and HMAC. A verified error answer comes back with Error set and a nil error. WebAuth verifies the answer itself with ResponseMode: "jwt".

Ask a person to approve a sign-in on their phone (CIBA)

With OpenID CIBA, your application asks LumoAuth to sign a person in on their own device, by push or by an e-mail that links to their sign-in requests. Call centres and back offices use it: the person approves on their phone, and your server gets their tokens. The application must be confidential and have CIBA switched on.

auth := lumoauth.ClientAuth{ClientID: clientID, ClientSecret: clientSecret}
start, err := client.Auth.BackchannelAuthorize(ctx, lumoauth.BackchannelAuthorizeParams{
    ClientAuth:     auth,
    LoginHint:      "ada@acme.com",
    Scopes:         []string{"openid", "profile"},
    BindingMessage: "Call 4412", // shown to the person on both devices
})
if err != nil {
    return err
}
tokens, err := client.Auth.PollBackchannelToken(ctx, start.AuthReqID, start.PollOptions(auth))

PollBackchannelToken follows the same rules and errors as PollDeviceToken. LumoAuth gives the same answer for a person that it does not know, so the start never confirms the hint. Set one of LoginHint, IDTokenHint and LoginHintToken.

Check a token at LumoAuth (introspection)

A resource server that receives opaque tokens, or that must know whether a token was revoked, asks LumoAuth (RFC 7662):

info, err := client.Auth.Introspect(ctx, token, lumoauth.IntrospectOptions{
    ClientAuth: lumoauth.ClientAuth{ClientID: apiClientID, ClientSecret: apiClientSecret},
})
if err != nil {
    return err
}
if !info.Active {
    // expired, revoked, unknown, or not for this client
}

An inactive token is a result, never an error. LumoAuth answers only about tokens that were issued to the calling client, or whose aud names it. Public clients cannot introspect. An agent introspects with its own client ID and secret.

Register clients (dynamic client registration)

MCP clients and agents can register themselves (RFC 7591):

registered, err := client.Auth.RegisterClient(ctx, lumoauth.ClientMetadata{
    ClientName:              "Acme field app",
    RedirectURIs:            []string{"http://localhost:4400/callback"},
    ApplicationType:         "native", // a loopback redirect
    TokenEndpointAuthMethod: "client_secret_basic",
}, lumoauth.RegisterClientOptions{InitialAccessToken: os.Getenv("LUMO_INITIAL_ACCESS_TOKEN")})
if err != nil {
    return err
}
// Store registered.ClientSecret and registered.RegistrationAccessToken now.
config, err := client.Auth.GetClientConfiguration(ctx, registered.ClientID, registered.RegistrationAccessToken)

The initial access token is sent as the only credential. Without one, the client's API key is sent when it has one (it needs the scope admin:clients:register), and nothing otherwise, for an organization that allows open registration. A bearer token of the client is never sent: LumoAuth reads a bearer token here as an initial access token. RegisteredClient does not print its secret or its registration access token. Refused metadata is an *APIError with the code invalid_client_metadata or invalid_redirect_uri.

Authenticate an app instance with an attestation

With attestation-based client authentication (attest_jwt_client_auth), each installed copy of an app has its own key. Your attester backend vouches for that key in a JWT. The app then sends the attester's JWT and a new proof of possession with each request, instead of a secret.

instanceKey, _ := lumoauth.GenerateClientAssertionSigner("ES256", "")
// Send instanceKey.PublicJWK() to your attester, and receive its JWT for this instance.
auth := lumoauth.ClientAuth{
    ClientID:    clientID,
    Attestation: &lumoauth.ClientAttestation{Attestation: attesterJWT, InstanceKey: instanceKey},
}
tokens, err := client.Auth.PollBackchannelToken(ctx, authReqID, lumoauth.PollOptions{ClientAuth: auth})
// or: client.Auth.Introspect, PushAuthorizationRequest, ExchangeCode with ClientAuth: &auth

The SDK sends the OAuth-Client-Attestation header (the attester's JWT as it is) and the OAuth-Client-Attestation-PoP header, plus client_id in the body. The proof has the header typ: oauth-client-attestation-pop+jwt and the claims iss (the client ID), aud (the organization's issuer), iat, exp (60 seconds), a random jti and challenge when you set one. The instance key must be an RSA or EC key: LumoAuth does not accept EdDSA here. client.Auth.ClientAttestationHeaders builds the two headers for a request of your own.

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, DecidedBy, AuditID and the Context that the server evaluated. DecidedBy names the check that produced the answer: lumoauth.DecidedByCapability (the agent's capabilities), DecidedByPDP (your policies and relationships) or DecidedByDenyOverride (an attribute policy denied what a capability allowed). As with ABAC, the server sets ip, userAgent, requestMethod and requestPath itself and moves your values under pep.

To put the decision's audit entries into your trace, send the W3C traceparent of the current span. LumoAuth stores its trace ID with the entries:

result, err := agent.AskWithOptions(ctx, "tickets:read", nil, lumoauth.AskOptions{
    Traceparent: "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01",
})

IsAllowedWithOptions is the same call reduced to a boolean. A value that is not in the traceparent format is a ValidationError, and nothing is sent.

Check capabilities and the budget:

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

// Returns an error that matches ErrBudgetExceeded when any limit of the budget is reached.
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)          // limits, usage and the server's verdict, see below
me, err := agent.Identity(ctx, false)     // identity, capabilities, workspace (cached)

AgentBudget types every key of the budget_policy that UserInfo and ReportUsage return. A limit that is not set is 0:

Limits Usage in the current UTC window
MaxAPICallsPerHour, MaxAPICallsPerDay APICallsThisHour, APICallsToday
MaxTokensPerHour, MaxTokensPerDay TokensUsedThisHour, TokensUsedToday
MaxCostPerDayUSD, HardLimitUSD (both daily) CostTodayUSD
MaxCostPerMonthUSD CostThisMonthUSD

ReportedExhausted is the server's verdict, and budget.Exhausted() uses it. MaxSteps and TimeoutSeconds are settings that LumoAuth stores but does not enforce: your agent applies them. budget.Raw holds the whole object.

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). An agent never starts a sign-in: the person signs in to an application of your organization, the application redeems the code, and the agent exchanges the person's access token. DelegationChain manages the whole flow for one session ID per user.

chain, err := lumoauth.NewDelegationChainForApplication(agent, lumoauth.DelegationApplication{
    ClientID:      os.Getenv("APP_CLIENT_ID"),     // the application, never the agent's agt_… ID
    ClientSecret:  os.Getenv("APP_CLIENT_SECRET"), // empty for a public application
    RedirectURI:   "https://app.example.com/agent/callback", // registered on the application
    OfflineAccess: true, // a refresh token: to renew the person's token and to revoke
})

// 1. Send the person to sign in to the application. The URL asks for openid, the scopes and
//    offline_access, with a PKCE S256 challenge that the chain keeps.
consentURL, err := chain.ConsentURL("session-1", []string{"documents:read"}, "")

// 2. Your callback receives ?code=…&state=…. Compare the state with chain.ConsentState, then
//    let the application redeem the code (its client ID, its secret and the PKCE verifier).
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 holds at most 5 actors (MaxDelegationDepth).
subToken, err := chain.DelegateToSubAgent(ctx, "session-1", subAgentToken, "documents:read")

// End the delegation: the application revokes the person's refresh token, which ends every
// delegated token of that grant.
err = chain.Revoke(ctx, "session-1")

The scopes must be allowed for the application and held by the agent as capabilities: the delegated token gets what the agent asks for, the agent's capabilities and the person's token have in common. The agent also needs May act on behalf of users.

If your application signs the person in itself, register its tokens with chain.SetUserTokens(sessionID, tokenResponse) and skip the consent step. With the refresh token, the chain renews the person's token as the application and Revoke ends the grant. chain.SetUserToken(sessionID, accessToken) takes an access token alone: the delegation then lasts as long as that token, and Revoke can only forget the session. Revoke then returns an error that matches lumoauth.ErrDelegationNotRevoked, because the grant at LumoAuth still stands; revoke the person's refresh token where it is held, with client.Auth.Revoke and the application's credentials. chain.Forget(sessionID) drops a session without any request.

NewDelegationChain(agent, redirectURI) is deprecated: its consent flow used the agent's client ID, which LumoAuth refuses ("Unknown Application"). With an agent's agt_… ID its ConsentURL and HandleConsentCallback return a ConfigError. Its exchange and SetUserToken keep working. For your own flow, client.Delegation.ApplicationConsentURL builds the same URL as ConsentURL from explicit parameters.

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", "documents:read")

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{"documents:read"},
})

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.

Use tokens of other services (token vault)

The token vault keeps tokens of other services (GitHub, Google, Slack, …) for your organization and for the people who linked their accounts. An agent asks for a live token of a connection that allows it:

connections, err := agent.ListConnections(ctx)
// Each AgentConnection has ConnectionID, Name, Provider, UserDelegated, MachineGrantStatus, …

token, err := agent.GetConnectionToken(ctx, "conn_1f3a9c2b7d8e4a5f6b0c1d2e",
    lumoauth.ConnectionTokenParams{UserID: "ada@acme.com"}) // for a user-delegated connection
if apiErr, ok := lumoauth.AsAPIError(err); ok && apiErr.Code == lumoauth.VaultGrantNotFound {
    // The person has not linked the account yet.
}
req.Header.Set("Authorization", token.Header())

LumoAuth renews the token when needed; the refresh token never leaves LumoAuth. For a person's connection, the agent must be allowed to act on behalf of users, and the person must have allowed this agent on their grant. Refusals keep the server's code: VaultGrantNotFound (matches ErrNotFound), VaultAgentNotAllowed and VaultDelegationNotAllowed (match ErrPermissionDenied), grant_revoked, grant_expired and refresh_failed (409), and budget_exceeded. Printing a ConnectionToken with fmt or log/slog never shows the token, so do not log AccessToken yourself. Set Traceparent in ConnectionTokenParams to put the audit entry into your trace.

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

Connect to an MCP server with the official MCP Go SDK

lumoauth.NewMCPTransport is an http.RoundTripper for the official MCP Go SDK (github.com/modelcontextprotocol/go-sdk). It adds the agent's MCP token to each request; it is not a second MCP client:

transport, err := lumoauth.NewMCPTransport(agent, lumoauth.MCPTransportOptions{
    Resource: "https://mcp.example.com/mcp", // the registered Resource URI; "" = read it from the server
})
if err != nil {
    return err
}
client := mcp.NewClient(&mcp.Implementation{Name: "invoice-agent", Version: "1.0.0"}, nil)
session, err := client.Connect(ctx, &mcp.StreamableClientTransport{
    Endpoint:   "https://mcp.example.com/mcp",
    HTTPClient: transport.Client(),
}, nil)

The transport:

  • gets the token with agent.Mcp (a token exchange for the resource), keeps it and renews it 60 seconds before it expires;
  • adds the token only to requests for the resource's origin and path, never to another server;
  • sends a DPoP-bound token (AgentConfig.DPoP) with the DPoP scheme and a new proof for each request, and sends the request again once when the server asks for a DPoP nonce;
  • reads the protected resource metadata (RFC 9728) once when the server answers 401 with a resource_metadata address. Without Resource, it learns the resource from there. It sends no token when the metadata names a resource on another origin, or does not list the agent's organization as an authorization server. A configured Resource that differs from the server's is a ConfigError;
  • sends a request again once with a new token after a 401, and returns the second 401 as it is.

A 403 (insufficient_scope) comes back unchanged: the agent's token already holds every scope that its capabilities cover. The transport adds no dependency to this module.

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. An application that holds only its private key builds that client with WithoutCredential():

client, err := lumoauth.New(lumoauth.WithOrgID("acme-corp"), lumoauth.WithoutCredential())
issuer, err := client.Issuer() // the assertion's aud
assertion, err := signer.Assertion(clientID, issuer)
token, err := client.Auth.ClientCredentialsWithAssertion(ctx, clientID, assertion)
Sign in with the workload's identity: attestation

An agent that runs on a platform which issues OIDC tokens (GitHub Actions, Kubernetes, AWS, Google Cloud, Azure, SPIFFE) needs no secret at all. Register the agent with the Workload identity type and its binding, then trade the platform's token for an agent access token:

token, err := os.ReadFile("/var/run/secrets/tokens/lumoauth") // the platform's OIDC token
result, err := lumoauth.AttestWorkload(ctx, lumoauth.AttestWorkloadOptions{
    AgentID:          "agt_7f3c2a19b84e5d60",
    AttestationToken: strings.TrimSpace(string(token)),
    Scopes:           []string{"reports:read"}, // optional: some of the agent's capabilities
})
if err != nil {
    return err // a rejected token matches ErrAuthentication (401 attestation_rejected)
}
client, err := lumoauth.New(lumoauth.WithAccessToken(result.AccessToken))

AttestWorkload needs no LumoAuth credential: it reads the address from its options or from LUMOAUTH_URL, LUMOAUTH_ORG_ID and LUMOAUTH_CUSTOM_DOMAIN, and it never sends an API key. client.Agents.Attest(ctx, params) does the same with an existing client. The token lives 15 minutes (result.ExpiresIn); attest again for a new one. result.Identity holds the provider, subject and issuer that LumoAuth verified. Set DPoP (or WithDPoP on the client) to bind the token to a key: the request then carries a proof and result.TokenType is DPoP.

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.

A server that issues DPoP nonces (RFC 9449 §9) sets the nonce it expects. With RequireAccessToken, DPoPNonce returns it for each request; a proof without it gets 401 with error="use_dpop_nonce" and the nonce in a DPoP-Nonce header, so the client can sign a new proof. With VerifyAccessToken, set DPoPRequest.Nonce; the rejection reason is then TokenRejectedDPoPNonce.

protect := lumoauth.RequireAccessToken(lumoauth.AccessTokenVerifyOptions{
    Issuer:    issuer,
    Resource:  resource,
    DPoPNonce: func(*http.Request) string { return nonces.Current() }, // your own rotation
})

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.

For an organization on a custom domain, set CustomDomain in place of Issuer. The trusted issuer is then the bare domain, and the SDK reads the keys through https://auth.acme.com/api/v1/.well-known/openid-configuration:

protect := lumoauth.RequireAccessToken(lumoauth.AccessTokenVerifyOptions{
    CustomDomain: "auth.acme.com",
    Resource:     "https://mcp.example.com/mcp",
})

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

Verify a JIT approval in your MCP server

When a person approves an agent's JIT request, LumoAuth issues a JIT token for the approval. A client sends it next to its MCP access token, in the X-LumoAuth-Jit-Token header. Verify it with the caller's verified access token:

claims, _ := lumoauth.AccessTokenFromContext(r.Context())
approval, err := lumoauth.VerifyJitToken(r.Context(), r.Header.Get("X-LumoAuth-Jit-Token"), lumoauth.JitTokenVerifyOptions{
    Issuer: "https://app.lumoauth.dev/orgs/acme-corp/api/v1",
    Caller: claims,
    RequiredDetails: []map[string]any{
        {"type": "payment_initiation", "actions": []string{"refund"}, "identifier": "INV-1001"},
    },
})
if err != nil {
    // lumoauth.RejectionReason(err): jit_token_not_for_caller, insufficient_authorization_details, …
}

A JIT token is not an access token: its typ is JWT, its aud is the organization ID, and the approval is in permissions.authorization_details. VerifyJitToken checks the signature against the organization's keys, iss, aud, jit: true, exp, nbf and iat. It also checks that the approval belongs to the caller: the same person, and the same agent (the access token's act.sub for a delegated call, else its sub). Without a Caller, set ExpectedSubject and ExpectedAgent. approval.Covers(details...) tests further entries. The SDK does not check revocation before exp; introspect the token for an action with consequences. These are the rules of every LumoAuth SDK and MCP package.

This SDK has no verifier for transaction tokens: LumoAuth documents no procedure to verify them.

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.

Verify requests from personal agents

A personal agent acts for one person and calls your API with a Poppy-Session header (Personal Agent Protocol). client.Poppy asks LumoAuth to verify that header. The answer names the personal agent, its user and the Session, and it says whose account the access token of the request is for.

Set up the application. Your API authenticates as one of your organization's confidential applications. In LumoAuth, open Applications and add the poppy:verify scope to the allowed scopes of that application. Without the scope, every call fails with ErrPermissionDenied. Pass the application's client ID and client secret to the client:

client, err := lumoauth.New(
    lumoauth.WithOrgID("acme-corp"),
    lumoauth.WithClientCredentials(os.Getenv("SHOP_API_CLIENT_ID"), os.Getenv("SHOP_API_CLIENT_SECRET")),
)

The client.Poppy calls send these credentials with HTTP Basic. They never send the client's API key or bearer token. An app that signs users in with NewWebAuth and a confidential application can use auth.Client().Poppy, which sends the credentials of WebConfig.

Protect routes with the middleware. client.Poppy.Middleware verifies each request before your handler runs. This program is complete:

package main

import (
    "encoding/json"
    "log"
    "net/http"
    "os"

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

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

    // verified returns the middleware for routes that need the given scopes.
    verified := func(scopes ...string) func(http.Handler) http.Handler {
        middleware, err := client.Poppy.Middleware(lumoauth.PoppyMiddlewareOptions{
            PublicOrigin:  os.Getenv("PUBLIC_ORIGIN"), // for example https://shop.example.com
            RequiredScope: scopes,
            OnError: func(w http.ResponseWriter, r *http.Request, err error) {
                log.Printf("Session verification failed: %v", err)
                http.Error(w, "not available now", http.StatusServiceUnavailable)
            },
        })
        if err != nil {
            log.Fatal(err) // PublicOrigin or the client credentials are missing
        }
        return middleware
    }

    mux := http.NewServeMux()
    mux.Handle("GET /api/catalog", verified()(http.HandlerFunc(catalog)))
    mux.Handle("GET /api/orders", verified("orders:read")(http.HandlerFunc(orders)))
    log.Fatal(http.ListenAndServe(":8787", mux))
}

// catalog works signed out. Keep signed-out state, such as a cart, under Session.ID.
func catalog(w http.ResponseWriter, r *http.Request) {
    who, _ := lumoauth.PoppyFromContext(r.Context())
    log.Printf("catalog for %s, Session %d", who.ClientID, who.Session.ID)
    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(map[string]any{"items": []string{"trail-socks-3"}})
}

// orders needs a scope, so LumoAuth has checked the access token and Account is set.
func orders(w http.ResponseWriter, r *http.Request) {
    who, _ := lumoauth.PoppyFromContext(r.Context())
    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(map[string]any{"account": who.Account.Subject, "orders": []string{}})
}

For each request, the middleware does one of three things:

  • Verified. It stores the *PoppyVerification in the request context and calls the handler. Read it with lumoauth.PoppyFromContext(r.Context()).
  • Refused. It sends LumoAuth's response to the personal agent unchanged: the status, every header and the body. It does not call the handler.
  • The call failed. The SDK could not reach LumoAuth, or LumoAuth rejected your application (401, 403, 404 or 429). The middleware does not call the handler and relays nothing. It calls OnError. Without OnError it answers 503 with the fixed body {"error":"temporarily_unavailable","error_description":"Requests from personal agents cannot be verified right now."}. The error text never reaches the personal agent. While the organization has the protocol switched off, LumoAuth answers your call with 404 not_found, so the error matches ErrNotFound.

The SDK does not log. Set OnError to record the error, as the example does. Never write the error to the response: it is about your service, not about the personal agent.

Field of PoppyMiddlewareOptions Meaning
PublicOrigin The address that personal agents call, for example https://shop.example.com. Required.
RequiredScope The scopes that the routes need. Leave it empty for routes that work signed out.
Resource The resource identifier of your service, when it takes only access tokens that were issued for it.
AllowReplay Accepts a Session JWT that was verified before. The default is false.
OnError Called when the verification call fails. It must answer the request.

Take the public origin from configuration. The Session JWT names the URL that the personal agent called, so LumoAuth must get that same URL. The middleware builds it from PublicOrigin and the path of the request line (r.RequestURI). It drops the query. It never reads the Host or X-Forwarded-* headers, because a caller controls them. PublicOrigin may carry a base path, such as https://example.com/shop, when a proxy removes that prefix before the request reaches your server. http.StripPrefix or a router prefix in front of the middleware does not shorten the URL, so the order of the two does not matter. Middleware returns a ConfigError when PublicOrigin is missing or is not a valid address.

A Session JWT is good for one verification. Put the middleware on a route once, and pass the result inward. Set AllowReplay only when one request is verified in several places.

Each request waits for the verification call. The call uses the client's timeout, which is 30 seconds by default. Set a shorter one with WithTimeout.

Verify a request without the middleware. Call VerifyHTTPRequest in a handler, and relay a refusal with WritePoppyRefusal:

func returnOrder(w http.ResponseWriter, r *http.Request) {
    verification, err := client.Poppy.VerifyHTTPRequest(r.Context(), publicOrigin, r,
        &lumoauth.PoppyVerifyOptions{RequiredScope: []string{"orders:write"}})
    if err != nil {
        log.Printf("Session verification failed: %v", err)
        http.Error(w, "not available now", http.StatusServiceUnavailable)
        return
    }
    if !verification.Active {
        lumoauth.WritePoppyRefusal(w, verification) // LumoAuth's response, unchanged
        return
    }
    // verification.ClientID, verification.Session.ID, verification.Account.Subject
}

With another router or server, pass the parts of the request to VerifyRequest. You can pass all the headers of the request. The SDK sends only five of them: Poppy-Session, Poppy-Version, Poppy-Extensions, Authorization and DPoP. A cookie or an API key therefore never reaches LumoAuth.

verification, err := client.Poppy.VerifyRequest(ctx, lumoauth.PoppyRequest{
    Method:  method,
    URL:     publicOrigin + path, // the path as the client sent it
    Headers: headers,
}, nil)

A refusal is not an error: Active is false, Error holds the protocol's error code and Response holds the status, headers and body to send. lumoauth.BuildPoppyVerifyBody builds the request body without a call, for your own transport or tests.

A verified result has these fields:

Field Meaning
ClientID, ClientName The personal agent. LumoAuth checked ClientID. The name is the agent's own claim.
UserID The agent's name for its user at your organization. It is not an account.
AgentID Set when the personal agent runs several agents for one user.
Session.ID, Session.SID, Session.IsNew, Session.StartedAt The Session. IsNew is true when this request started it.
SignedIn, Account Whether the request carried a valid access token. Account is nil for a signed-out request.
Account.Subject, Account.Scopes(), Account.HasScope, Account.Audience, Account.Expires, Account.TokenType The user in your organization and the access token. Find account data by Account.Subject, never by UserID.
Version, Extensions The Poppy-Version of the request and the extensions that it declares.
Raw The complete decoded answer.

Look up a Session and end one. A website that joined a browser to a Session asks LumoAuth about the Session on each page request:

status, err := client.Poppy.GetSessionStatus(ctx, personalAgent, sid) // ClientID and Session.SID
if err != nil {
    return err
}
if !status.Active() {
    // The Session ended or is unknown: drop the cookie.
}
if !status.SignedIn || status.Account != joinedAccount {
    // Keep the Session, and treat the browser as signed out.
}

End a Session when your own rules call for it, for example after a fraud signal. The user stays signed in, and the personal agent starts a new Session with its next request:

ended, err := client.Poppy.EndSession(ctx, personalAgent, sid)

ended is false when the Session had ended before. An unknown Session gives ErrNotFound from EndSession, and the status unknown from GetSessionStatus.

The three calls return these errors. None of them is about the personal agent, so never relay one:

Error Cause
ErrConfig The client has no client credentials, or PublicOrigin is missing. On the platform host, a client without an organization ID gets it too. No request is sent.
ErrValidation An argument is empty, or LumoAuth's answer is neither a verified result nor a well-formed refusal. The SDK never returns such an answer as verified.
ErrAPI with status 400 LumoAuth did not accept the forwarded request. One cause is a PublicOrigin that is not https://: plain http:// is accepted only for localhost, 127.0.0.1 and [::1].
ErrAuthentication 401: the client ID or secret is wrong, or the application is not a confidential application of this organization.
ErrPermissionDenied 403: the application's allowed scopes lack poppy:verify.
ErrNotFound 404: unknown organization, the protocol is switched off, or EndSession named an unknown Session.
ErrRateLimited 429: your application sent too many calls. APIError.RetryAfter says when to retry.
ErrNetwork The SDK could not reach LumoAuth.

See Session verification for the endpoints, the checks that LumoAuth runs and the protocol's error codes.

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, CustomDomain As for New the environment variables
Issuer The AAuth issuer. Set it only to override the default. {BaseURL}/orgs/{OrgID}/api/v1; with CustomDomain, the value in the issuer metadata document. See AAuth on a custom domain.
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. The scope of the auth token comes from the resource token: LumoAuth ignores AuthTokenParams.Scope. Set RedirectURI when a person may have to consent.

result, err := aauth.RequestAuthToken(ctx, lumoauth.AuthTokenParams{
    ResourceToken: resourceToken,
    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 and a resource token from the same resource. Scope only narrows: a scope outside the grant is refused with invalid_scope
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
Issuer(), ResolveIssuer(ctx) The AAuth issuer. ResolveIssuer reads it from the metadata document on a custom domain.
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,
})

For an organization on a custom domain, set VerifyOptions.CustomDomain and leave Issuer empty. The keys then come from https://auth.acme.com/api/v1/aauth/jwks.json, and NewJWKSCacheForCustomDomain("auth.acme.com", time.Hour, nil) caches them. The trusted issuer is not the bare domain: AAuth tokens name the platform form of the issuer on every host. The SDK reads it from the domain's issuer metadata document. See AAuth on a custom domain.

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.

On a custom domain, OrgPath returns the path without the /orgs/... segment, so this example works unchanged.

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. On a custom domain the generated client also needs WithOrgID; see Use a custom domain.

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.ErrBudgetExceeded):
    // The agent's budget is spent. It is a rate limit too, so check it first.
    var budgetErr *lumoauth.BudgetError
    if errors.As(err, &budgetErr) {
        log.Printf("budget spent, the window starts again in %s", budgetErr.RetryAfter)
    }
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; also invalid_client at any status AUTHENTICATION_ERROR, or the code in the body
ErrPermissionDenied 403: the caller may not do this; also unauthorized_client and access_denied at any status 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 budget is spent: a 429 with the body code budget_exceeded, or CheckBudget budget_exceeded from the server, BUDGET_EXCEEDED from CheckBudget

*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.

When the server refuses a call because the agent's budget is spent, it answers 429 with the body code budget_exceeded. The error is an *APIError that matches both ErrRateLimited and ErrBudgetExceeded, and errors.As finds a *BudgetError in it, with the same RetryAfter. Code that handles the rate limit keeps working. Agent.CheckBudget returns a *BudgetError too, without a request; its Budget field holds the budget that it checked.

OAuth endpoints answer some errors with a status that depends on the request: invalid_client with 401 (400 on earlier servers), unauthorized_client and access_denied with 400 (403 on earlier servers). The class follows the code, not the status: invalid_client matches ErrAuthentication, and the other two match ErrPermissionDenied. StatusCode(err) and ErrorCode(err) still give what the server sent. In PollDeviceToken and PollBackchannelToken, access_denied is a person's denial instead: an *ApprovalError that matches ErrApprovalDenied.

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
ClientCredentialsWithParams(ctx, params) The same grant with a secret or an assertion, and a Resource (RFC 8707) for the token's audience
TokenExchange(ctx, params) RFC 8693 token exchange
Revoke(ctx, params) Revokes an access or refresh token
EndSessionURL(params) Builds the end-session (RP-initiated logout) URL
UserInfo(ctx, accessToken) The OpenID Connect UserInfo claims
DeviceAuthorization(ctx, params), PollDeviceToken(ctx, deviceCode, opts) The device authorization grant (RFC 8628)
PushAuthorizationRequest(ctx, params, auth) Pushed authorization request (RFC 9126); AuthorizationURL with RequestURI builds the redirect
BackchannelAuthorize(ctx, params), PollBackchannelToken(ctx, authReqID, opts) OpenID CIBA for an application (poll mode)
Introspect(ctx, token, opts) Token introspection (RFC 7662)
RegisterClient(ctx, metadata, opts), GetClientConfiguration(ctx, clientID, registrationAccessToken) Dynamic client registration (RFC 7591) and its read (RFC 7592)
CreateRequestObject(params, opts) A signed request object (JAR, RFC 9101)
VerifyAuthorizationResponse(ctx, response, opts) Verifies a JARM answer
ClientAttestationHeaders(attestation) The headers of attestation-based client authentication
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
Attest(ctx, params), lumoauth.AttestWorkload(ctx, opts) Trades a workload's OIDC token for an agent access token none: the workload's token is the credential
AskWithOptions, IsAllowedWithOptions Ask with a traceparent agent credential
ListConnections(ctx), GetConnectionToken(ctx, connectionID, params) The token vault: connections and a live token of one agent credential (not a token narrowed to some scopes)
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
Delegation.ApplicationConsentURL(params) The sign-in URL of your application for a delegation (PKCE, optional offline_access)
DelegationChain.ConsentURL, HandleConsentCallback, ConsentState The person signs in to your application; the application redeems the code
DelegationChain.SetUserTokens, SetUserToken Register tokens that you already hold
DelegationChain.Exchange, ExchangeForResource, DelegatedToken, Do, DoRaw Use the delegation
DelegationChain.DelegateToSubAgent, DelegateToSubAgentForResource Extend the chain to a sub-agent
DelegationChain.Revoke, RevokeAll, Forget End delegations: the application revokes the refresh token (ErrDelegationNotRevoked when only local state could be dropped)
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
client.Poppy
Method What it does
VerifyRequest(ctx, PoppyRequest, opts) Asks LumoAuth who a request from a personal agent is from; a refusal returns Active false with the response to relay
VerifyHTTPRequest(ctx, publicOrigin, r, opts) The same for a *http.Request
Middleware(PoppyMiddlewareOptions) net/http middleware that verifies each request and relays a refusal
GetSessionStatus(ctx, personalAgent, sid) Whether a Session is active, ended or unknown, and whether its account is still signed in
EndSession(ctx, personalAgent, sid) Ends a Session; false when it had ended before

All of them need WithClientCredentials with a confidential application whose allowed scopes include poppy:verify. They send HTTP Basic and no other credential.

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
NewDelegationChainForApplication(agent, app) A delegation manager whose consent goes through your application
NewDelegationChain(agent, redirectURI) Deprecated: its consent flow cannot work with an agent's ID
VerifyAuthToken, NewJWKSCache, NewJWKSCacheForCustomDomain, FetchIssuerJWKS Verify AAuth tokens
VerifyAccessToken, RequireAccessToken, AccessTokenFromContext, DPoPRequestFromHTTP, NewAccessTokenKeyCache, NewAccessTokenKeyCacheForCustomDomain, FetchAccessTokenJWKS, NewMemoryReplayCache, RejectionReason Verify LumoAuth access tokens in an MCP server
VerifyJitToken, OrgIDFromIssuer Verify a JIT approval in an MCP server
NewMCPTransport(agent, opts) An http.RoundTripper that adds the agent's MCP token, for the official MCP Go SDK
IsJARMResponseMode(mode) Whether a response mode returns a signed answer
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
PoppyFromContext, ContextWithPoppy, WritePoppyRefusal, BuildPoppyVerifyBody Personal Agent Protocol: read the verified result in a handler, relay a refusal, build the request body
AsAPIError, StatusCode, ErrorCode Error helpers
RoutePath, RouteNames, BuildPath The route registry. Its paths are in the platform form, with /orgs/{orgId}.
IssuerFor(baseURL, orgID) The issuer of an organization on the platform host. client.Issuer() also covers a custom domain.

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
ErrConfig from a client.Poppy call that mentions poppy:verify The client has no client credentials Pass WithClientCredentials with the client ID and secret of a confidential application
403 insufficient_scope from a client.Poppy call The application's allowed scopes lack poppy:verify Add the scope to the application under Applications
Every request of a personal agent is refused with invalid_session and a description that names the URL (htu) The URL that your API sent differs from the URL that the personal agent called Set PublicOrigin to the public address, with the base path that a proxy removes
A personal agent gets 503 with {"error":"temporarily_unavailable",…} The verification call failed, and the middleware has no OnError. ErrNotFound: the protocol is switched off for the organization Set OnError to log the error, then fix the cause that it names
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. With a custom domain, set WithCustomDomain and no org ID is needed.
404 from every call to an organization's own domain The domain is set as the base URL, so the paths carry /orgs/... Pass the domain with WithCustomDomain or LUMOAUTH_CUSTOM_DOMAIN, not with WithBaseURL
ErrConfig about an invalid custom domain The value has a path, a query or credentials, or it uses http:// on a public host Pass the host name alone, for example auth.acme.com
An access token is rejected with wrong_issuer after a move to a custom domain Access tokens that are issued through the custom domain name the bare domain as issuer Set CustomDomain in AccessTokenVerifyOptions in place of Issuer
VerifyAuthToken answers untrusted issuer for an AAuth token on a custom domain VerifyOptions.Issuer is set to the custom domain, but AAuth tokens name the platform form Leave Issuer empty and set CustomDomain
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

go get github.com/lumoauth/lumo-auth-go installs the latest version. The release notes list every version and what changed in it. The SDK sends its own version in the User-Agent header, as lumoauth-go/ followed by the value of lumoauth.Version. 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 these entry points, one per kind of caller:

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

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

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

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

  • MCPTransport — an http.RoundTripper for the official MCP Go SDK that adds an agent's MCP token to each request.

  • WebAuth — browser sign-in. Wires the OAuth 2.1 Authorization Code + PKCE flow into any net/http-compatible router, with sessions in an encrypted cookie or in a session store of your choice (WebConfig.Store), optionally with pushed and signed requests (WebConfig.UsePAR, WebConfig.ResponseMode).

  • AuthResource (client.Auth) — the OAuth endpoints for your own flows: device authorization, PAR, CIBA, introspection, dynamic client registration, signed request objects (JAR) and answers (JARM).

  • PoppyResource (client.Poppy) — for an API that personal agents call (Personal Agent Protocol). It asks LumoAuth to verify the Poppy-Session header of a request, and PoppyResource.Middleware does that for a net/http route.

Client

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

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

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

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

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

Agent

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

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

Before an irreversible action, ask a human:

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

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

Web sign-in

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

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

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

Personal agents

An API that personal agents call verifies each request with LumoAuth. The client authenticates as a confidential application whose allowed scopes include poppy:verify:

client, err := lumoauth.New(
    lumoauth.WithOrgID("acme-corp"),
    lumoauth.WithClientCredentials(clientID, clientSecret),
)
if err != nil {
    return err
}

verified, err := client.Poppy.Middleware(lumoauth.PoppyMiddlewareOptions{
    PublicOrigin:  "https://shop.example.com", // from your configuration
    RequiredScope: []string{"orders:read"},
})
if err != nil {
    return err
}
mux.Handle("GET /api/orders", verified(ordersHandler))

// In a handler:
who, _ := lumoauth.PoppyFromContext(req.Context())

A refused request gets LumoAuth's response, unchanged. A failed verification call is never sent to the personal agent. PoppyResource.VerifyRequest and WritePoppyRefusal are the same steps without the middleware, and PoppyResource.GetSessionStatus and PoppyResource.EndSession look up and end a Session.

Errors

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

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

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

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

Custom domains

An organization can serve LumoAuth on its own domain. Pass the domain with WithCustomDomain, or with the CustomDomain field of AgentConfig, WebConfig and AAuthConfig:

client, err := lumoauth.New(
    lumoauth.WithCustomDomain("auth.acme.com"),
    lumoauth.WithAPIKey(os.Getenv("LUMOAUTH_API_KEY")),
)

The client then sends every request to that domain, and no path carries the /orgs/{orgId} segment. The organization ID is not needed. The issuer is the bare domain, https://auth.acme.com, and Client.Issuer returns it. To verify access tokens of such an organization, set CustomDomain in AccessTokenVerifyOptions in place of Issuer.

AAuth is the one exception. LumoAuth names the AAuth issuer with the platform address on every host, so the SDK never derives it from the domain. AAuthClient.ResolveIssuer and VerifyAuthToken with VerifyOptions.CustomDomain read it from the issuer metadata document of the custom domain.

Configuration

Options fall back to the environment:

LUMOAUTH_URL           instance URL      (default https://app.lumoauth.dev)
LUMOAUTH_ORG_ID        organization slug
LUMOAUTH_CUSTOM_DOMAIN the organization's own domain (wins over LUMOAUTH_URL)
LUMOAUTH_API_KEY       organization API key (sent as X-API-Key)
AGENT_CLIENT_ID        agent OAuth client       (Agent only)
AGENT_CLIENT_SECRET    agent OAuth secret       (Agent only)

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

Example (ErrorHandling)

Errors are matched with the standard library.

package main

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

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

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

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

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

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

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

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

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"
	// TokenRejectedDPoPNonce: the proof lacks the nonce that the resource
	// server expects (DPoPRequest.Nonce), or carries another one. Answer it
	// with use_dpop_nonce and the expected value in DPoP-Nonce (RFC 9449
	// §9); RequireAccessToken does this.
	TokenRejectedDPoPNonce = "dpop_nonce"
	// TokenRejectedState: a verified authorization response whose state is
	// not the one that the sign-in sent (VerifyAuthorizationResponse).
	TokenRejectedState = "state_mismatch"
	// TokenRejectedNotJIT: a verified token that is not a LumoAuth JIT
	// approval (jit is not true, or it names no agent or no approved
	// authorization details).
	TokenRejectedNotJIT = "not_jit"
	// TokenRejectedJITNotForCaller: a JIT token issued to another caller
	// (another person, or another agent).
	TokenRejectedJITNotForCaller = "jit_token_not_for_caller"
	// TokenRejectedJITInsufficient: a valid JIT token that does not approve
	// what the call needs (JitTokenVerifyOptions.RequiredDetails).
	TokenRejectedJITInsufficient = "insufficient_authorization_details"
)

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

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 (
	// VaultGrantNotFound (404): the person has not linked the connection,
	// or no machine grant exists. LumoAuth gives the same answer for an
	// unknown person.
	VaultGrantNotFound = "grant_not_found"
	// VaultAgentNotAllowed (403): the connection's allowed agents leave
	// this agent out.
	VaultAgentNotAllowed = "agent_not_allowed"
	// VaultDelegationNotAllowed (403): the person has not allowed this
	// agent on their grant.
	VaultDelegationNotAllowed = "delegation_not_allowed"
	// VaultDelegationNotPermitted (403): the agent may not act on behalf of
	// users at all.
	VaultDelegationNotPermitted = "delegation_not_permitted"
	// VaultConnectionNotFound (404): no connection has this ID.
	VaultConnectionNotFound = "connection_not_found"
)

Codes of the vault's refusals (APIError.Code).

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 (
	ResponseModeJWT         = "jwt"
	ResponseModeQueryJWT    = "query.jwt"
	ResponseModeFragmentJWT = "fragment.jwt"
	ResponseModeFormPostJWT = "form_post.jwt"
)

JARM response modes (the answer comes back as a signed `response` JWT).

View Source
const (
	ClientAttestationHeader    = "OAuth-Client-Attestation"
	ClientAttestationPoPHeader = "OAuth-Client-Attestation-PoP"
	// ClientAttestationTyp is the typ header of the attester's JWT.
	ClientAttestationTyp = "oauth-client-attestation+jwt"
	// ClientAttestationPoPTyp is the typ header of the proof of possession.
	ClientAttestationPoPTyp = "oauth-client-attestation-pop+jwt"
)

Header names of attestation-based client authentication (attest_jwt_client_auth).

View Source
const (
	GrantTypeDeviceCode = "urn:ietf:params:oauth:grant-type:device_code"
	GrantTypeCIBA       = "urn:openid:params:grant-type:ciba"
)

Grant types of the two polling flows.

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 (
	// ClientSecretBasic sends the client ID and secret in an HTTP Basic
	// Authorization header.
	ClientSecretBasic = "client_secret_basic"
	// ClientSecretPost sends them as the client_id and client_secret form
	// fields.
	ClientSecretPost = "client_secret_post"
)

Methods of sending a client secret to the token endpoint (RFC 6749 §2.3.1). A client assertion (private_key_jwt) is chosen by setting ClientAssertion instead.

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"
	// Device authorization grant (RFC 8628).
	RouteOAuthDeviceAuthorization = "oauth.deviceAuthorization"
	// Pushed authorization requests (RFC 9126).
	RouteOAuthPAR = "oauth.par"
	// OpenID CIBA, backchannel authentication request.
	RouteOAuthBackchannelAuthorize = "oauth.backchannelAuthorize"
	// Token introspection (RFC 7662).
	RouteOAuthIntrospect = "oauth.introspect"
	// Dynamic client registration (RFC 7591) and its read (RFC 7592).
	RouteOAuthRegisterClient         = "oauth.registerClient"
	RouteOAuthGetClientConfiguration = "oauth.getClientConfiguration"

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

	// ── Agents (identity) ─────────────────────────────────────────────
	RouteAgentsAsk              = "agents.ask"
	RouteAgentsAttest           = "agents.attest"
	RouteAgentsAuthorizeMcpTool = "agents.authorizeMcpTool"
	RouteAgentsMe               = "agents.me"
	RouteAgentsRegister         = "agents.register"
	RouteAgentsReportUsage      = "agents.reportUsage"
	// Token vault: the agent's outbound connections and their tokens.
	RouteAgentsListConnections    = "agents.listConnections"
	RouteAgentsGetConnectionToken = "agents.getConnectionToken"

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

	// ── Personal Agent Protocol (Session verification for your own API) ─
	RoutePoppyVerifyRequest    = "poppy.verifyRequest"
	RoutePoppyGetSessionStatus = "poppy.getSessionStatus"
	RoutePoppyEndSession       = "poppy.endSession"

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

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

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

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

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

View Source
const (
	// DecidedByCapability: the agent's capabilities decided (no policy or
	// relationship data applied).
	DecidedByCapability = "capability"
	// DecidedByPDP: the organization's policies and relationships decided.
	DecidedByPDP = "pdp"
	// DecidedByDenyOverride: an explicit ABAC deny overrode a capability that
	// would have allowed the action.
	DecidedByDenyOverride = "deny_override"
)

Values of AgentAskResult.DecidedBy.

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 (
	PoppyStatusActive = "active"
	PoppyStatusEnded  = "ended"
	// PoppyStatusUnknown means that no Session has the sid: it never
	// started, or nothing used it for the idle period.
	PoppyStatusUnknown = "unknown"
)

Session states that PoppySessionStatus.Status reports.

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 (
	// DefaultPollInterval is the wait between two polls when the server
	// names none (RFC 8628 §3.2).
	DefaultPollInterval = 5 * time.Second
)
View Source
const EnvCustomDomain = "LUMOAUTH_CUSTOM_DOMAIN"

EnvCustomDomain is read when the custom domain option is not passed, by every constructor that reads EnvBaseURL.

View Source
const JITTokenTyp = "JWT"

JITTokenTyp is the typ header of a LumoAuth JIT token.

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 = 5

MaxDelegationDepth is the number of actors that a delegation chain may hold: the depth of the nested `act` claims of a token (user → agent → sub-agent → … , the user not counted). LumoAuth refuses the exchange that would add a sixth actor with 400 invalid_request ("Delegation chain too deep: …"); DelegationChain reports it as a ValidationError.

View Source
const RequestObjectTyp = "oauth-authz-req+jwt"

RequestObjectTyp is the typ header of a request object (RFC 9101 §10.8).

View Source
const Version = "1.8.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, and an OAuth endpoint's
	// invalid_client answer at any status.
	ErrAuthentication = errors.New("lumoauth: authentication failed")
	// ErrPermissionDenied matches HTTP 403 responses, and an OAuth
	// endpoint's unauthorized_client or access_denied answer at any status.
	ErrPermissionDenied = errors.New("lumoauth: permission denied")
	// ErrNotFound matches HTTP 404 responses.
	ErrNotFound = errors.New("lumoauth: not found")
	// ErrRateLimited matches HTTP 429 responses.
	ErrRateLimited = errors.New("lumoauth: rate limited")
	// ErrValidation matches client-side validation failures.
	ErrValidation = errors.New("lumoauth: validation failed")
	// ErrConfig matches missing or invalid configuration.
	ErrConfig = errors.New("lumoauth: configuration error")
	// ErrNetwork matches transport failures (no HTTP response was received).
	ErrNetwork = errors.New("lumoauth: network error")
	// ErrApprovalDenied matches an approval a human explicitly denied.
	ErrApprovalDenied = errors.New("lumoauth: approval denied")
	// ErrApprovalTimeout matches an approval that expired before a response.
	ErrApprovalTimeout = errors.New("lumoauth: approval timed out")
	// ErrApprovalNotDelivered matches an approval request that no push
	// device received, so nobody can approve it in this call.
	ErrApprovalNotDelivered = errors.New("lumoauth: approval not delivered")
	// ErrBudgetExceeded matches an exhausted agent budget.
	ErrBudgetExceeded = errors.New("lumoauth: budget exceeded")
)

Sentinel errors for errors.Is. Every error returned by this SDK matches ErrLumoAuth; each also matches exactly one of the specific sentinels, except the server's budget refusal, which matches ErrRateLimited and ErrBudgetExceeded (see above).

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 ErrDelegationNotRevoked = errors.New("lumoauth: the delegation was forgotten locally, not revoked at LumoAuth")

ErrDelegationNotRevoked matches the error of DelegationChain.Revoke when it could only forget the session's local state: the chain holds no refresh token for the session, or no application credentials to revoke it with. The person's grant at LumoAuth then still stands. The error also matches ErrConfig.

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

	RouteOAuthDeviceAuthorization:  {"POST", orgBase + "/oauth/device_authorization"},
	RouteOAuthPAR:                  {"POST", orgBase + "/oauth/par"},
	RouteOAuthBackchannelAuthorize: {"POST", orgBase + "/oauth/bc-authorize"},
	RouteOAuthIntrospect:           {"POST", orgBase + "/oauth/introspect"},

	RouteOAuthRegisterClient:         {"POST", orgBase + "/connect/register"},
	RouteOAuthGetClientConfiguration: {"GET", orgBase + "/connect/register/{clientId}"},

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

	RouteAgentsAsk: {"POST", orgBase + "/agents/ask"},

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

	RouteAgentsListConnections:    {"GET", orgBase + "/agents/me/connections"},
	RouteAgentsGetConnectionToken: {"POST", orgBase + "/agents/me/connections/{connectionId}/token"},

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

	RoutePoppyVerifyRequest:    {"POST", orgBase + "/poppy/sessions/verify"},
	RoutePoppyGetSessionStatus: {"POST", orgBase + "/poppy/sessions/status"},
	RoutePoppyEndSession:       {"POST", orgBase + "/poppy/sessions/end"},

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

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

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

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

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

Functions

func AnyCapabilityCovers added in v1.4.0

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. The registry's templates are in the platform form, with the /orgs/{orgId} segment; a client with a custom domain removes that segment before it builds the path.

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

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

func BuildPoppyVerifyBody added in v1.7.0

func BuildPoppyVerifyBody(publicOrigin, method, target string, headers http.Header, opts *PoppyVerifyOptions) (map[string]any, error)

BuildPoppyVerifyBody builds the JSON body of a verification call for an incoming request. It is a pure function: it makes no call and reads no configuration.

  • method is sent in upper case.
  • url is publicOrigin without trailing slashes, followed by the path of target as the client sent it. The query and the fragment are dropped, and an empty path is "/". publicOrigin may carry a base path. The URL is never built from the Host header.
  • headers holds only Poppy-Session, Poppy-Version, Poppy-Extensions, Authorization and DPoP, matched without regard to case, under their lower-case names. A repeated header is joined with ", ". A missing or empty header is left out.
  • required_scope, resource and allow_replay are sent only when opts sets them.

target is the request target of the request line, for example "/api/orders?page=2". On a net/http server that is r.RequestURI.

It returns a *ConfigError for a missing or invalid publicOrigin and a *ValidationError for a missing method or a target that is not a path. opts may be nil.

func BuildSignatureBase

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

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

func CapabilityCovers added in v1.4.0

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") and CapabilityCovers("invoices:read", "invoices-read") are 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 ContextWithPoppy added in v1.7.0

func ContextWithPoppy(ctx context.Context, verification *PoppyVerification) context.Context

ContextWithPoppy stores a verified result in a context, for handlers that call VerifyRequest themselves but share downstream code with Middleware.

func DPoPAccessTokenHash added in v1.2.0

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 IsJARMResponseMode added in v1.8.0

func IsJARMResponseMode(mode string) bool

IsJARMResponseMode reports whether a response mode returns the answer as a signed JWT in a single `response` parameter.

func IssuerFor added in v1.3.0

func IssuerFor(baseURL, orgID string) string

IssuerFor is the issuer identifier of an organization on the platform host baseURL: the issuer of /orgs/{orgID}/api/v1/.well-known/openid-configuration, and the aud a client assertion must carry. On a custom domain the issuer is the bare domain, for example "https://auth.acme.com"; Client.Issuer returns the right form for a client.

func LoadPrivateKey

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

LoadPrivateKey parses a PEM private key for AAuth signing. Ed25519 and RSA keys are supported. The server also accepts EC P-256 keys, which this SDK does not sign with.

func NormalizeCapability added in v1.4.0

func NormalizeCapability(capability string) string

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

func OrgIDFromIssuer added in v1.8.0

func OrgIDFromIssuer(issuer string) string

OrgIDFromIssuer returns the organization ID of a platform issuer of the form …/orgs/{slug}/api/v1, or "".

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": …}. With opts.DPoPNonce, a proof without the expected nonce gets error="use_dpop_nonce" and the nonce in a DPoP-Nonce header instead (RFC 9449 §9). When opts.JWKS is nil the middleware keeps one key cache for the issuer.

func RouteNames

func RouteNames() []string

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

func RoutePath

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

RoutePath looks up a route and builds its concrete path in one call. The path is in the platform form. A client with a custom domain does not use this function: it resolves routes without the /orgs/{orgId} segment.

func SignRequest

func SignRequest(privateKeyPEM, method, targetURL string, opts SignOptions) (map[string]string, error)

SignRequest builds the RFC 9421 signature headers for a request under the AAuth profile: Content-Digest, Content-Type, Signature-Input, Signature, and — when an agent token is supplied — Agent-Auth.

headers, err := lumoauth.SignRequest(privateKeyPEM, "POST", url, lumoauth.SignOptions{
    Body:       body,
    AgentToken: agentToken,
})

func SignSignatureBase

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. It handles Ed25519 and RSA keys only: a signature made with an EC P-256 key, which the server also accepts from agents, does not verify here.

func WritePoppyRefusal added in v1.7.0

func WritePoppyRefusal(w http.ResponseWriter, verification *PoppyVerification) error

WritePoppyRefusal sends a refusal to the personal agent as LumoAuth worded it: the status, every header and the body of verification.Response. A body is sent as JSON with Content-Type application/json. A response without a body gets no body and no Content-Type. Nothing else is added.

if !verification.Active {
    lumoauth.WritePoppyRefusal(w, verification)
    return
}

It returns a *ValidationError, and writes nothing, when verification is not a refusal. Otherwise it returns the error of the write, if any.

Types

type AAuthAgentMetadata

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

AAuthAgentMetadata describes a registered agent.

type AAuthClaims

type AAuthClaims struct {
	Issuer   string `json:"iss"`
	Audience string `json:"aud"`
	Expires  int64  `json:"exp"`
	IssuedAt int64  `json:"iat"`
	JTI      string `json:"jti"`
	// Subject is the user. It is a pseudonym for this resource, not the
	// user ID, when the resource's default auth level is `pseudonymous`, or
	// `authorized` without a consent record.
	Subject string `json:"sub,omitempty"`
	// Agent identifies the agent the token was issued to. The claim is
	// present only when the audience differs from the agent identifier.
	Agent string `json:"agent,omitempty"`
	// AgentDelegate is the delegate (the `sub` of the agent token) that
	// made the request for the agent, if any.
	AgentDelegate string `json:"agent_delegate,omitempty"`
	// Scope lists resource scopes only: openid, profile, email, phone and
	// address are never listed.
	Scope string `json:"scope,omitempty"`
	// Confirmation binds the token to the holder's key (RFC 7800). Auth
	// tokens carry the agent's full public JWK and no cnf.jkt.
	Confirmation struct {
		JWK JWK `json:"jwk"`
	} `json:"cnf"`
	// Act is the actor chain of an exchanged token: {agent,
	// agent_delegate?, sub?, act?}. act.agent names the upstream agent and
	// act.sub the upstream user; a nested act holds the earlier hops (at
	// most 5).
	Act map[string]any `json:"act,omitempty"`

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

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

func VerifyAuthToken

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

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

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

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

Example

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

package main

import (
	"fmt"
	"net/http"

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

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

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

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

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

func (*AAuthClaims) HasScope

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

HasScope reports whether the token carries a scope.

func (*AAuthClaims) Scopes

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

Scopes splits the space-separated scope claim.

func (*AAuthClaims) VerifyProofOfPossession

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

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

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

The check is narrower than the one LumoAuth applies to its own endpoints. It does not require a recent `created`, a new nonce, a Content-Digest header or any particular covered component, and it reads only the `created` and `nonce` parameters. LumoAuth requires @method, @authority, @path and signature-key to be covered, `created` within 60 seconds and a single-use nonce. Apply those checks yourself to stop a captured request from being replayed.

type AAuthClient

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

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

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

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

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

func NewAAuthClient

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

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

Example

An AAuth agent signs its requests with its own key.

package main

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

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

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

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

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

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

func (*AAuthClient) AgentIdentifier

func (c *AAuthClient) AgentIdentifier() string

AgentIdentifier returns the agent's identity URL.

func (*AAuthClient) BaseURL

func (c *AAuthClient) BaseURL() string

BaseURL returns the address that the client sends its requests to: the custom domain when one is set, the LumoAuth instance URL otherwise.

func (*AAuthClient) ConsentURL

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

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

func (*AAuthClient) CustomDomain added in v1.7.0

func (c *AAuthClient) CustomDomain() string

CustomDomain returns the organization's custom domain as an origin, or "" when none is set.

func (*AAuthClient) DiscoverAgents

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

DiscoverAgents fetches metadata for the organization's active agents.

func (*AAuthClient) DiscoverIssuer

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

DiscoverIssuer fetches the organization's AAuth issuer metadata.

func (*AAuthClient) DiscoverResource

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

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

func (*AAuthClient) ExchangeCode

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

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

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

func (*AAuthClient) ExchangeToken

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

ExchangeToken performs a multi-hop exchange (request_type=exchange): trade an upstream auth token plus a downstream resource token for a new auth token carrying an `act` actor chain (act.agent names the upstream agent, act.sub the upstream user; at most 5 hops). The agent must be permitted to exchange tokens.

func (*AAuthClient) Issuer

func (c *AAuthClient) Issuer() string

Issuer returns the organization's AAuth issuer URL, which is the `iss` value in issued tokens and the audience that the agent addresses.

It returns AAuthConfig.Issuer when that is set. On the platform host it is otherwise {baseURL}/orgs/{orgID}/api/v1, the base for JWKS discovery.

On a custom domain the issuer keeps the platform form, and this method never derives it from the domain. It makes no request, so there it returns the value that ResolveIssuer has read, or "" before the first call of ResolveIssuer. Prefer ResolveIssuer with a custom domain.

func (*AAuthClient) JWKS

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

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

func (*AAuthClient) OrgID

func (c *AAuthClient) OrgID() string

OrgID returns the organization slug.

func (*AAuthClient) PublicJWK

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

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

func (*AAuthClient) PublicJWKThumbprint

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

PublicJWKThumbprint returns the RFC 7638 thumbprint of the agent's public key. A resource names this value as `agent_jkt` when it asks for a resource token for the agent.

func (*AAuthClient) Refresh

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

Refresh renews an auth token (request_type=refresh). Refresh tokens are not rotated, so the same one stays valid for the grant's lifetime and the response carries no new one. A refresh never widens the scope.

func (*AAuthClient) RequestAuthToken

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

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

When the server requires user consent it answers 200 with a request_token and an authorization_uri, returned here as a response with AuthorizationRequired set: redirect the user to AuthorizationURI, then call ExchangeCode with the code delivered to your redirect URI.

func (*AAuthClient) ResolveIssuer added in v1.7.0

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

ResolveIssuer returns the organization's AAuth issuer, like Issuer, and reads it from LumoAuth when the client cannot know it.

With a custom domain and no AAuthConfig.Issuer, it fetches the issuer metadata document from the custom domain once and returns its `issuer` member, which is the platform form. Later calls return the same value without a request. On the platform host it makes no request, and it returns a *ConfigError when the client has no organization ID.

func (*AAuthClient) Revoke

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

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

func (*AAuthClient) SignRequest

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

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

func (*AAuthClient) SignedRequest

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

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

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

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

type AAuthConfig

type AAuthConfig struct {
	// AgentIdentifier is the HTTPS URL uniquely identifying the agent,
	// e.g. "https://my-agent.example.com". Required.
	AgentIdentifier string
	// PrivateKeyPEM is the agent's Ed25519 (PKCS#8) or RSA private key.
	// Required.
	PrivateKeyPEM string
	// BaseURL is the LumoAuth instance. Defaults to $LUMOAUTH_URL, then
	// DefaultBaseURL.
	BaseURL string
	// OrgID is the organization slug. Defaults to $LUMOAUTH_ORG_ID. Not
	// needed with CustomDomain.
	OrgID string
	// CustomDomain addresses the organization on its own domain, for
	// example "auth.acme.com". Defaults to $LUMOAUTH_CUSTOM_DOMAIN. It wins
	// over BaseURL: the token endpoint, the key set, the issuer metadata
	// and the URLs that the agent signs are then on that domain, without
	// the /orgs/{orgId} segment. See WithCustomDomain.
	//
	// The AAuth issuer does not follow the domain: see Issuer.
	CustomDomain string
	// Issuer is the organization's AAuth issuer: the `iss` of its AAuth
	// tokens and the audience that the agent addresses. Leave it empty on
	// the platform host, where it is {BaseURL}/orgs/{OrgID}/api/v1.
	//
	// LumoAuth names the AAuth issuer with the platform address on every
	// host, so with CustomDomain it is NOT the bare domain. When Issuer is
	// empty there, ResolveIssuer reads it from the issuer metadata
	// document of the custom domain.
	Issuer string
	// Kid identifies the key in the JWKS registered with LumoAuth.
	// Defaults to DefaultKid.
	Kid string
	// Timeout is the per-request timeout. Default: 30s.
	Timeout time.Duration
	// HTTPClient overrides the *http.Client used for every request.
	HTTPClient *http.Client
	// SkipCertValidation disables TLS verification. Local development only.
	SkipCertValidation bool
}

AAuthConfig configures an AAuthClient.

type AAuthIssuerMetadata

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

AAuthIssuerMetadata describes an AAuth authorization server.

type AAuthResourceMetadata

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

AAuthResourceMetadata describes a protected resource server.

type AAuthTokenResponse

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

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

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

type APIConfig

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

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

type APIError

type APIError struct {
	*BaseError
	// StatusCode is the HTTP status of the response.
	StatusCode int
	// Body is the decoded response body: map[string]any for JSON objects,
	// a string for anything else, nil for an empty body.
	Body any
	// RetryAfter carries the Retry-After hint on 429 responses (0 if absent).
	RetryAfter time.Duration
	// RequiredScopes lists the scopes a 403 scope refusal names in
	// details.required_scopes; nil when the body has none. The server sends
	//
	//	{"error":"forbidden","message":"Insufficient scope: …","status":403,
	//	 "details":{"required_scopes":["authz:read"],"granted_scopes":[…]}}
	//
	// when the credential lacks a user-delegated scope the route needs.
	RequiredScopes []string
}

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

func AsAPIError

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 is the definition's ID as text. The server sends a number; a
	// string is accepted too.
	ID              string         `json:"id"`
	Name            string         `json:"name"`
	Slug            string         `json:"slug"`
	Description     string         `json:"description,omitempty"`
	AttributeType   string         `json:"attributeType,omitempty"` // user | resource | environment
	DataType        string         `json:"dataType,omitempty"`      // string | number | boolean | array | date
	ValidationRules map[string]any `json:"validationRules,omitempty"`
	// DefaultValue is the value an entity has when none is set; nil when the
	// definition has none.
	DefaultValue any `json:"defaultValue,omitempty"`
	// IsRequired reports whether every entity must have a value.
	IsRequired bool `json:"isRequired,omitempty"`
	// IsSystem marks a definition that LumoAuth manages.
	IsSystem bool `json:"isSystem,omitempty"`
	// BuiltIn marks a definition that LumoAuth provides to every
	// organization: readable, never writable by one.
	BuiltIn bool `json:"builtIn,omitempty"`
	// CreatedAt and UpdatedAt are RFC 3339 times; UpdatedAt is "" for a
	// definition that was never changed.
	CreatedAt string `json:"createdAt,omitempty"`
	UpdatedAt string `json:"updatedAt,omitempty"`
	// IsActive is not sent by the server and is always false.
	//
	// Deprecated: the server has no such flag; every listed definition
	// applies.
	IsActive bool `json:"isActive,omitempty"`
}

AbacAttributeDefinition describes an attribute the org has defined.

func (*AbacAttributeDefinition) UnmarshalJSON added in v1.8.0

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

UnmarshalJSON decodes the definition and accepts its ID as a number or a string.

type AbacBulkDecision

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

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

type AbacCheckParams

type AbacCheckParams struct {
	// ResourceType is the kind of thing being accessed ("document"). Required.
	ResourceType string
	// Action is the operation ("read", "delete"). Required.
	Action string
	// ResourceID identifies the specific instance, when there is one.
	ResourceID string
	// Context supplies environment attributes for the evaluation. The SDK
	// sends it as the request's "environment" object, which the policy
	// engine reads. The keys ip, userAgent, requestMethod and requestPath
	// always describe the request that LumoAuth received; values that you
	// pass under those names are kept under "pep" instead, so forward the
	// end user's IP as {"pep": {"ip": "10.0.0.1"}}.
	//
	// In CheckBulk the server applies one environment to every check, so
	// every entry must carry the same Context (or none).
	Context map[string]any
}

AbacCheckParams describes one ABAC evaluation.

type AbacDecision

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

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

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

func (*AbacDecision) UnmarshalJSON

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

UnmarshalJSON decodes the typed fields and retains the whole object.

type AbacMatchedPolicy

type AbacMatchedPolicy struct {
	// ID is the policy's ID as text. The server sends a number ({"id": 81}
	// gives "81"); a string is accepted too, and null gives "".
	ID       string `json:"id"`
	Name     string `json:"name"`
	Effect   string `json:"effect"` // "allow" or "deny"
	Priority int    `json:"priority"`
}

AbacMatchedPolicy is a policy that contributed to an ABAC decision.

func (*AbacMatchedPolicy) UnmarshalJSON added in v1.8.0

func (p *AbacMatchedPolicy) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes the policy and accepts its ID as a number or a string.

type AbacResource

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

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

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

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

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

func (*AbacResource) AttributeDefinitions

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

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

func (*AbacResource) Check

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

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

Example

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

package main

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

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

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

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

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

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"`
	// AuthorizationDetails are the token's fine-grained permissions
	// (RFC 9396 authorization_details), when it has some. Members that the
	// SDK does not model are kept.
	AuthorizationDetails []map[string]any `json:"authorization_details,omitempty"`

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

AccessTokenClaims are the claims of a verified LumoAuth access token.

func AccessTokenFromContext added in v1.2.0

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

AccessTokenFromContext returns the claims RequireAccessToken stored for the request.

func VerifyAccessToken added in v1.2.0

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

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

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

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

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

func (*AccessTokenClaims) ActorChain added in v1.2.0

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

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

func (*AccessTokenClaims) HasCapability added in v1.2.0

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

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

func (*AccessTokenClaims) HasScope added in v1.2.0

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

HasScope reports whether the token carries a scope.

func (*AccessTokenClaims) IsDPoPBound added in v1.2.0

func (c *AccessTokenClaims) IsDPoPBound() bool

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

func (*AccessTokenClaims) Scopes added in v1.2.0

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

Scopes splits the space-separated scope claim.

type AccessTokenKeyCache added in v1.2.0

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

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

func NewAccessTokenKeyCache added in v1.2.0

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

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

func NewAccessTokenKeyCacheForCustomDomain added in v1.7.0

func NewAccessTokenKeyCacheForCustomDomain(customDomain string, ttl time.Duration, httpClient *http.Client) (*AccessTokenKeyCache, error)

NewAccessTokenKeyCacheForCustomDomain builds a cache for an organization on its custom domain, for example "auth.acme.com". The issuer is the bare domain. It returns a *ConfigError for a value that is empty or not valid (see WithCustomDomain). A ttl of 0 means one hour.

func (*AccessTokenKeyCache) Get added in v1.2.0

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

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

func (*AccessTokenKeyCache) Invalidate added in v1.2.0

func (c *AccessTokenKeyCache) Invalidate()

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

type AccessTokenVerifyOptions added in v1.2.0

type AccessTokenVerifyOptions struct {
	// Issuer is the organization's issuer URL, e.g.
	// "https://app.lumoauth.dev/orgs/acme-corp/api/v1". Required unless
	// CustomDomain is set.
	Issuer string
	// CustomDomain is the organization's custom domain, for example
	// "auth.acme.com". When it is set, the trusted issuer is the bare
	// domain ("https://auth.acme.com") and Issuer is not used: a token
	// that names the platform issuer is refused. The keys are read from
	// the domain's discovery document. The value follows the rules of
	// WithCustomDomain; an invalid one is a *ConfigError from
	// VerifyAccessToken. The environment is not read.
	CustomDomain string
	// Resource is this server's resource URI — the value the MCP server is
	// registered with and the token's `aud` must name. Required.
	Resource string
	// JWKS supplies the issuer's keys directly. When nil, the keys are
	// fetched through the issuer's discovery document and cached (KeyCache,
	// or a process-wide cache per issuer), with one refetch on an unknown
	// kid.
	JWKS *JWKS
	// KeyCache is the cache to fetch keys through when JWKS is nil.
	KeyCache *AccessTokenKeyCache
	// HTTPClient fetches discovery and keys. Defaults to a 30s-timeout
	// client.
	HTTPClient *http.Client
	// ClockSkew tolerated on exp, nbf and the proof's iat. The default (0)
	// means 60 seconds; a negative value means no tolerance.
	ClockSkew time.Duration
	// RequireDPoP rejects tokens that are not sender-constrained. Set it
	// when the MCP server is registered with "Require DPoP".
	RequireDPoP bool
	// DPoP describes the request the token arrived with. Required for a
	// DPoP-bound token; RequireAccessToken fills it from the request.
	DPoP *DPoPRequest
	// ReplayCache stores proof identifiers. Defaults to a process-wide
	// in-memory cache.
	ReplayCache ReplayCache
	// DPoPNonce gives RequireAccessToken the nonce that this resource
	// server expects in the DPoP proof of a request (DPoPRequest.Nonce), for
	// a server that issues nonces. A proof without it gets 401 with
	// error="use_dpop_nonce" and the value in a DPoP-Nonce header, so the
	// client can retry. Nil (or "") means no nonce check. VerifyAccessToken
	// does not call it: set DPoP.Nonce there.
	DPoPNonce func(r *http.Request) string
}

AccessTokenVerifyOptions configures VerifyAccessToken.

type ActorClaim added in v1.2.0

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

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

type Agent

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

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

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

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

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

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

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

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

func NewAgent

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

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

Example

An agent checks whether it may act before acting.

package main

import (
	"context"
	"log"

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

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

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

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) AskWithOptions added in v1.8.0

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

AskWithOptions asks whether the agent may perform an action, with per-call options such as the traceparent; see AgentsResource.AskWithOptions.

func (*Agent) Authenticate

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 address that the agent sends its requests to: the custom domain when one is set, the LumoAuth instance URL otherwise.

func (*Agent) Budget

func (a *Agent) Budget(ctx context.Context) (*AgentBudget, error)

Budget returns the agent's budget policy. It is never nil.

func (*Agent) Capabilities

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 budget is spent (any limit, see AgentBudget.Exhausted), and nil otherwise. Budget state is cached with the rest of the agent info — call Info(ctx, true) first for a live reading.

func (*Agent) Client

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, else to the custom domain, else to 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) CustomDomain added in v1.7.0

func (a *Agent) CustomDomain() string

CustomDomain returns the organization's custom domain as an origin, or "" when none is set. NewJITContext and NewDelegationChain read it, so their requests follow the agent's own addressing.

func (*Agent) DPoP added in v1.2.0

func (a *Agent) DPoP() *DPoPSigner

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

func (*Agent) Do

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) GetConnectionToken added in v1.8.0

func (a *Agent) GetConnectionToken(ctx context.Context, connectionID string, params ConnectionTokenParams) (*ConnectionToken, error)

GetConnectionToken returns a live token of an outbound connection; see AgentsResource.GetConnectionToken.

func (*Agent) HasCapability

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: "Web:Search" matches the held "web:search", and a held "web:*" covers it (see CapabilityCovers). It checks only the agent's registered capabilities; the Ask API (Agent.Ask) also applies your policies and the token's scope.

func (*Agent) Identity

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) IsAllowedWithOptions added in v1.8.0

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

IsAllowedWithOptions is AskWithOptions reduced to a boolean.

func (*Agent) ListConnections added in v1.8.0

func (a *Agent) ListConnections(ctx context.Context) ([]AgentConnection, error)

ListConnections lists the outbound connections that this agent may use.

func (*Agent) MCPToken

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, "web:search"); err != nil {
        return err
    }
    …
}
Example

Capability gating at the top of a tool implementation.

package main

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

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

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

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

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"`
	// DecidedBy names the check that produced the answer: DecidedByCapability,
	// DecidedByPDP or DecidedByDenyOverride. "" when the server did not say.
	DecidedBy string         `json:"decided_by,omitempty"`
	AuditID   string         `json:"audit_id,omitempty"`
	Context   map[string]any `json:"context,omitempty"`

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

AgentAskResult is the decision returned by the Ask API.

func (*AgentAskResult) UnmarshalJSON

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

UnmarshalJSON decodes the typed fields and retains the whole object.

type AgentBudget

type AgentBudget struct {
	// Limits on API calls and model tokens.
	MaxAPICallsPerHour int `json:"max_api_calls_per_hour,omitempty"`
	MaxAPICallsPerDay  int `json:"max_api_calls_per_day,omitempty"`
	MaxTokensPerHour   int `json:"max_tokens_per_hour,omitempty"`
	MaxTokensPerDay    int `json:"max_tokens_per_day,omitempty"`
	// Limits on cost, in USD. HardLimitUSD (`hard_limit`) and
	// MaxCostPerDayUSD are both daily limits; the lower one applies.
	MaxCostPerDayUSD   float64 `json:"max_cost_per_day_usd,omitempty"`
	MaxCostPerMonthUSD float64 `json:"max_cost_per_month_usd,omitempty"`
	HardLimitUSD       float64 `json:"hard_limit,omitempty"`

	// Usage in the current UTC hour, day and month. Tokens and cost count
	// only reported usage (Agent.ReportUsage).
	APICallsThisHour   int     `json:"api_calls_this_hour,omitempty"`
	APICallsToday      int     `json:"api_calls_today,omitempty"`
	TokensUsedThisHour int     `json:"tokens_used_this_hour,omitempty"`
	TokensUsedToday    int     `json:"tokens_used_today,omitempty"`
	CostTodayUSD       float64 `json:"cost_today_usd,omitempty"`
	CostThisMonthUSD   float64 `json:"cost_this_month_usd,omitempty"`

	// MaxSteps and TimeoutSeconds are settings that LumoAuth stores and
	// returns but does not enforce: your agent applies them. They are 0
	// when unset or when the stored value is not a number.
	MaxSteps       int `json:"-"`
	TimeoutSeconds int `json:"-"`

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

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

AgentBudget is the budget of an agent as UserInfo (budget_policy) and the usage report return it: the limits that are set, the usage in the current UTC windows, and the server's verdict. A limit that is not set is 0.

func (*AgentBudget) Exhausted

func (b *AgentBudget) Exhausted() bool

Exhausted reports whether the agent's budget is spent, so the next metered call would get 429. It uses the server's verdict when reported (any limit, any window); otherwise it compares every limit that is set with the usage of its window, and a policy without limits is never exhausted.

func (*AgentBudget) UnmarshalJSON

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

UnmarshalJSON decodes the typed fields and retains the whole object.

type AgentConfig

type AgentConfig struct {
	// BaseURL is the LumoAuth instance. Defaults to $LUMOAUTH_URL, then
	// DefaultBaseURL.
	BaseURL string
	// OrgID is the organization slug. Defaults to $LUMOAUTH_ORG_ID. Not
	// needed with CustomDomain.
	OrgID string
	// CustomDomain addresses the organization on its own domain, for
	// example "auth.acme.com". Defaults to $LUMOAUTH_CUSTOM_DOMAIN. It wins
	// over BaseURL, no path then carries the /orgs/{orgId} segment, and the
	// issuer is the bare domain. See WithCustomDomain.
	CustomDomain string
	// ClientID is the agent's OAuth client. Defaults to $AGENT_CLIENT_ID.
	ClientID string
	// ClientSecret is the agent's OAuth secret. Defaults to
	// $AGENT_CLIENT_SECRET.
	ClientSecret string
	// Scopes are requested at authentication. Leave empty to receive the
	// agent's registered defaults.
	Scopes []string
	// RedirectURI is the OAuth callback for the delegation consent flow.
	RedirectURI string
	// Timeout is the per-request timeout. Default: 30s.
	Timeout time.Duration
	// HTTPClient overrides the *http.Client used for every request.
	HTTPClient *http.Client
	// SkipCertValidation disables TLS verification. Local development only.
	SkipCertValidation bool
	// PrivateKey is for an agent registered with the "Private key JWT"
	// identity type: the agent then signs a client assertion (RFC 7523) for
	// every token request and needs no ClientSecret. Defaults to the PEM key
	// in $AGENT_PRIVATE_KEY, with its kid from $AGENT_KEY_ID.
	PrivateKey *ClientAssertionSigner
	// Issuer is the organization's issuer identifier, the assertion's aud.
	// Defaults to the custom domain when CustomDomain is set, and to
	// IssuerFor(BaseURL, OrgID) otherwise.
	Issuer string
	// DPoP binds the agent's tokens to a key (RFC 9449). The client
	// credentials grant, MCP token exchanges and delegation exchanges then
	// send a DPoP proof, the tokens come back with token_type "DPoP", and
	// the agent presents them with the DPoP scheme. Needed for MCP servers
	// registered with "Require DPoP". See NewDPoPSigner.
	DPoP *DPoPSigner
}

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

type AgentConnection added in v1.8.0

type AgentConnection struct {
	ConnectionID string `json:"connection_id"`
	Name         string `json:"name"`
	// Provider is the provider key ("github", "google", …); ProviderLabel
	// its name for people.
	Provider      string   `json:"provider"`
	ProviderLabel string   `json:"provider_label"`
	GrantMode     string   `json:"grant_mode"`
	Scopes        []string `json:"scopes"`
	// UserDelegated is true when each person links their own account;
	// GetConnectionToken then needs ConnectionTokenParams.UserID.
	UserDelegated bool `json:"user_delegated"`
	// MachineGrantStatus is the state of the machine grant
	// ("not_established" when there is none); "" for a user-delegated
	// connection.
	MachineGrantStatus string `json:"machine_grant_status,omitempty"`
	// LinkedUsers is the number of people with an active grant; nil for a
	// machine connection.
	LinkedUsers *int `json:"linked_users,omitempty"`
}

AgentConnection is one outbound connection that the agent may use. It holds no secret.

type AgentIdentity

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

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

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

func (*AgentIdentity) ID

func (i *AgentIdentity) ID() string

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

func (*AgentIdentity) UnmarshalJSON

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

UnmarshalJSON decodes the typed fields and retains the whole object.

type AgentMcpToolDecision added in v1.2.0

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

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

type AgentRegistration

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

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

AgentRegistration is the response to registering an agent.

func (*AgentRegistration) UnmarshalJSON

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

UnmarshalJSON decodes the typed fields and retains the whole object.

type AgentsResource

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

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

func (*AgentsResource) Ask

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

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

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

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

To send the traceparent of your trace, use AskWithOptions.

func (*AgentsResource) AskWithOptions added in v1.8.0

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

AskWithOptions is Ask with per-call options, such as the traceparent of your trace:

decision, err := agent.AskWithOptions(ctx, "invoices:refund", nil,
    lumoauth.AskOptions{Traceparent: span.Traceparent()})

func (*AgentsResource) Attest added in v1.8.0

func (r *AgentsResource) Attest(ctx context.Context, params AttestParams) (*AttestResult, error)

Attest exchanges a workload's OIDC token for an access token of the agent (workload attestation). The endpoint is public: the attestation token is the credential, so no API key or bearer token of the client is sent. With WithDPoP the request carries a proof, the token comes back bound to the key (TokenType "DPoP"), and a use_dpop_nonce answer is retried once with the server's nonce.

A rejected attestation (unknown agent, inactive agent, a token that failed verification) is a 401 attestation_rejected that matches ErrAuthentication. A spent budget matches ErrBudgetExceeded.

result, err := client.Agents.Attest(ctx, lumoauth.AttestParams{
    AgentID:          "agt_7f3c2a19b84e5d60",
    AttestationToken: workloadToken,
})

A runtime without any LumoAuth credential uses AttestWorkload, or a client built with WithoutCredential.

func (*AgentsResource) AuthorizeMcpTool added in v1.2.0

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

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

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

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

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

func (*AgentsResource) Budget

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

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

func (*AgentsResource) Capabilities

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

Capabilities returns the capability slugs granted to the agent.

func (*AgentsResource) GetConnectionToken added in v1.8.0

func (r *AgentsResource) GetConnectionToken(ctx context.Context, connectionID string, params ConnectionTokenParams) (*ConnectionToken, error)

GetConnectionToken returns a live token of an outbound connection, refreshed by LumoAuth when needed. Agent credentials only; a token that was narrowed to some scopes is refused (403 insufficient_scope).

token, err := agent.GetConnectionToken(ctx, "conn_1f3a9c2b7d8e4a5f6b0c1d2e",
    lumoauth.ConnectionTokenParams{UserID: "ada@acme.com"})
if apiErr, ok := lumoauth.AsAPIError(err); ok && apiErr.Code == lumoauth.VaultGrantNotFound {
    // ask the person to link the account
}
req.Header.Set("Authorization", token.Header())

Refusals keep the server's code: VaultGrantNotFound (matches ErrNotFound), VaultAgentNotAllowed and VaultDelegationNotAllowed (match ErrPermissionDenied), grant_revoked / grant_expired / refresh_failed (409), budget_exceeded (matches ErrBudgetExceeded).

func (*AgentsResource) Info

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

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

func (*AgentsResource) IsAllowed

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

IsAllowed is Ask reduced to a boolean.

func (*AgentsResource) IsAllowedWithOptions added in v1.8.0

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

IsAllowedWithOptions is AskWithOptions reduced to a boolean.

func (*AgentsResource) ListConnections added in v1.8.0

func (r *AgentsResource) ListConnections(ctx context.Context) ([]AgentConnection, error)

ListConnections lists the outbound connections that the calling agent may use, with the state of their grants. Agent credentials only.

func (*AgentsResource) Me

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

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

func (*AgentsResource) Register

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

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

func (*AgentsResource) ReportUsage added in v1.4.0

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

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

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

type ApplicationConsentParams added in v1.8.0

type ApplicationConsentParams struct {
	// ClientID is the application's client ID, never the agent's agt_… ID.
	// Required.
	ClientID string
	// RedirectURI is one of the application's registered redirect URIs.
	// Required.
	RedirectURI string
	// Scopes are what the agent may do for the person: scopes that the
	// application is allowed and that the agent holds as capabilities.
	// "openid" is added. Required.
	Scopes []string
	// State is the CSRF value echoed back to the redirect URI. Required.
	State string
	// CodeChallenge is the PKCE S256 challenge of a verifier that you keep
	// for the code redemption. Required.
	CodeChallenge string
	// OfflineAccess asks for a refresh token (scope offline_access): the
	// application needs it to renew the person's token and to revoke the
	// grant.
	OfflineAccess bool
}

ApplicationConsentParams describes the sign-in through which a person lets an agent act for them. An agent never starts a sign-in: the person signs in to an APPLICATION of your organization, the application redeems the code, and the agent exchanges the person's access token (Exchange).

type ApprovalError

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

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

type ApprovalImpact

type ApprovalImpact string

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

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

Approval impact tiers.

func (ApprovalImpact) Valid

func (i ApprovalImpact) Valid() bool

Valid reports whether the impact is one the server accepts.

type ApprovalParams

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

ApprovalParams describes an approval request.

type ApprovalResult

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

ApprovalResult is the state of a push-approval request.

func (*ApprovalResult) Approved

func (r *ApprovalResult) Approved() bool

Approved reports whether a human approved the action.

type ApprovalsResource

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

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

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

func (*ApprovalsResource) Create

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 AskOptions added in v1.8.0

type AskOptions struct {
	// Traceparent is a W3C trace context header value
	// ("00-<32 hex>-<16 hex>-<2 hex>"), sent as the traceparent header, so
	// that the audit entries of the decision carry your trace ID.
	Traceparent string
}

AskOptions are per-call options of AskWithOptions.

type AttestParams added in v1.8.0

type AttestParams struct {
	// AgentID is the agent's ID, for example "agt_7f3c2a19b84e5d60". Required.
	AgentID string
	// AttestationToken is the workload's OIDC token (a JWT). Required.
	AttestationToken string
	// Scopes optionally narrows the token to some of the agent's
	// capabilities. Empty means every capability. A scope outside the
	// capabilities is refused with invalid_scope.
	Scopes []string
}

AttestParams describes a workload attestation.

type AttestResult added in v1.8.0

type AttestResult struct {
	// AccessToken is the agent's access token; it lives 15 minutes.
	AccessToken string `json:"access_token"`
	// TokenType is "DPoP" when the token is bound to the client's DPoP key
	// (WithDPoP), "Bearer" otherwise.
	TokenType string `json:"token_type"`
	// ExpiresIn is the token's lifetime in seconds.
	ExpiresIn int `json:"expires_in"`
	// Scope holds the issued scope values, separated by spaces; "" when
	// none was issued.
	Scope string `json:"scope,omitempty"`
	// Identity is the workload identity that LumoAuth verified.
	Identity WorkloadIdentity `json:"identity"`

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

AttestResult is the answer to an accepted attestation.

func AttestWorkload added in v1.8.0

func AttestWorkload(ctx context.Context, opts AttestWorkloadOptions) (*AttestResult, error)

AttestWorkload performs a workload attestation without a LumoAuth client: the workload has no credential of its own, only its platform's OIDC token. It reads the address from the options, then from $LUMOAUTH_URL, $LUMOAUTH_ORG_ID and $LUMOAUTH_CUSTOM_DOMAIN, and never sends an API key.

token, _ := os.ReadFile("/var/run/secrets/tokens/lumoauth")
result, err := lumoauth.AttestWorkload(ctx, lumoauth.AttestWorkloadOptions{
    AgentID:          os.Getenv("LUMOAUTH_AGENT_ID"),
    AttestationToken: strings.TrimSpace(string(token)),
})

func (*AttestResult) Scopes added in v1.8.0

func (r *AttestResult) Scopes() []string

Scopes splits the space-separated Scope field.

func (*AttestResult) UnmarshalJSON added in v1.8.0

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

UnmarshalJSON decodes the typed fields and retains the whole object.

type AttestWorkloadOptions added in v1.8.0

type AttestWorkloadOptions struct {
	// BaseURL is the LumoAuth instance. Defaults to $LUMOAUTH_URL, then
	// DefaultBaseURL.
	BaseURL string
	// OrgID is the organization slug. Defaults to $LUMOAUTH_ORG_ID. Not
	// needed with CustomDomain.
	OrgID string
	// CustomDomain is the organization's own domain. Defaults to
	// $LUMOAUTH_CUSTOM_DOMAIN. It wins over BaseURL.
	CustomDomain string
	// AgentID, AttestationToken and Scopes are those of AttestParams.
	AgentID          string
	AttestationToken string
	Scopes           []string
	// DPoP binds the issued token to this signer's key.
	DPoP *DPoPSigner
	// HTTPClient overrides the client used for the request.
	HTTPClient *http.Client
	// Timeout is the request timeout. Default: 30s.
	Timeout time.Duration
	// SkipCertValidation disables TLS verification. Local development only.
	SkipCertValidation bool
}

AttestWorkloadOptions configures AttestWorkload.

type AudienceClaim added in v1.2.0

type AudienceClaim []string

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

func (AudienceClaim) Contains added in v1.2.0

func (a AudienceClaim) Contains(value string) bool

Contains reports whether the audience names value.

func (*AudienceClaim) UnmarshalJSON added in v1.2.0

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

UnmarshalJSON accepts a single string or an array of strings.

type AuthResource

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

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

func (*AuthResource) AuthorizationURL

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

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

After a pushed authorization request, pass only ClientID and its RequestURI: the URL then carries client_id and request_uri alone.

func (*AuthResource) BackchannelAuthorize added in v1.8.0

BackchannelAuthorize starts an OpenID CIBA request for the application (poll mode):

auth := lumoauth.ClientAuth{ClientID: clientID, ClientSecret: clientSecret}
start, err := client.Auth.BackchannelAuthorize(ctx, lumoauth.BackchannelAuthorizeParams{
    ClientAuth:     auth,
    LoginHint:      "ada@acme.com",
    Scopes:         []string{"openid", "profile"},
    BindingMessage: "Order 4412",
})
if err != nil {
    return err
}
tokens, err := client.Auth.PollBackchannelToken(ctx, start.AuthReqID, start.PollOptions(auth))

func (*AuthResource) ClientAttestationHeaders added in v1.8.0

func (r *AuthResource) ClientAttestationHeaders(attestation ClientAttestation) (map[string]string, error)

ClientAttestationHeaders builds the two request headers of attestation-based client authentication (attest_jwt_client_auth): OAuth-Client-Attestation, the attestation as given, and OAuth-Client-Attestation-PoP, a new proof of possession signed with the instance key. The proof's claims are iss (the client ID: the attestation's sub), aud (the organization's issuer identifier), iat, exp (the lifetime of InstanceKey, 60 s by default), a random jti and, when given, challenge. Each proof works once.

The token, PAR, CIBA and introspection calls of this SDK send the headers themselves when ClientAuth.Attestation is set. Send client_id in the request body too: the headers do not replace it.

func (*AuthResource) ClientCredentials

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

ClientCredentials performs the machine-to-machine client-credentials grant. Passing no scopes lets the server grant the client's defaults. To send a resource indicator, use ClientCredentialsWithParams.

func (*AuthResource) ClientCredentialsWithAssertion added in v1.3.0

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

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

func (*AuthResource) ClientCredentialsWithParams added in v1.8.0

func (r *AuthResource) ClientCredentialsWithParams(ctx context.Context, params ClientCredentialsParams) (*TokenResponse, error)

ClientCredentialsWithParams performs the client-credentials grant with a secret or an assertion, and optionally a resource indicator:

token, err := client.Auth.ClientCredentialsWithParams(ctx, lumoauth.ClientCredentialsParams{
    ClientID:     clientID,
    ClientSecret: clientSecret,
    Scopes:       []string{"reports:read"},
    Resource:     "https://api.example.com/",
})

func (*AuthResource) CreateRequestObject added in v1.8.0

func (r *AuthResource) CreateRequestObject(params AuthorizationURLParams, opts RequestObjectOptions) (string, error)

CreateRequestObject signs the parameters of an authorization request as a request object (JAR, RFC 9101): a JWT with the header typ oauth-authz-req+jwt, alg and kid, and the claims = the authorization parameters plus iss (the client ID), aud (the organization's issuer identifier), iat, nbf, exp and a random jti.

object, err := client.Auth.CreateRequestObject(lumoauth.AuthorizationURLParams{
    ClientID:      clientID,
    RedirectURI:   "https://app.example.com/callback",
    Scope:         "openid profile",
    State:         state,
    CodeChallenge: challenge,
    ResponseMode:  lumoauth.ResponseModeJWT,
}, lumoauth.RequestObjectOptions{Signer: signer})
// Push it (FAPI 2), or send it by value:
pushed, err := client.Auth.PushAuthorizationRequest(ctx,
    lumoauth.AuthorizationURLParams{ClientID: clientID, Request: object}, auth)

func (*AuthResource) DeviceAuthorization added in v1.8.0

DeviceAuthorization starts the device authorization grant (RFC 8628):

start, err := client.Auth.DeviceAuthorization(ctx, lumoauth.DeviceAuthorizationParams{
    ClientAuth: lumoauth.ClientAuth{ClientID: "lumo_cli_client"},
    Scopes:     []string{"openid", "profile", "offline_access"},
})
if err != nil {
    return err
}
fmt.Printf("Open %s and enter %s\n", start.VerificationURI, start.UserCode)
tokens, err := client.Auth.PollDeviceToken(ctx, start.DeviceCode, start.PollOptions(auth))

func (*AuthResource) EndSessionURL added in v1.8.0

func (r *AuthResource) EndSessionURL(params EndSessionURLParams) (string, error)

EndSessionURL builds the address to send a browser to so that it signs out of LumoAuth as well (the discovery document's end_session_endpoint). Clear your own session first. WebAuth's logout route does this for you.

logout, err := client.Auth.EndSessionURL(lumoauth.EndSessionURLParams{
    IDTokenHint:           tokens.IDToken,
    PostLogoutRedirectURI: "https://app.example.com/",
})
if err != nil {
    return err
}
http.Redirect(w, req, logout, http.StatusFound)

func (*AuthResource) ExchangeCode

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

ExchangeCode trades an authorization code for tokens.

func (*AuthResource) GetClientConfiguration added in v1.8.0

func (r *AuthResource) GetClientConfiguration(ctx context.Context, clientID, registrationAccessToken string) (*RegisteredClient, error)

GetClientConfiguration reads the stored metadata of a registered client (RFC 7592 §2.1) with its registration access token, which is the only credential sent. The answer never holds the client secret or the token.

func (*AuthResource) Introspect added in v1.8.0

func (r *AuthResource) Introspect(ctx context.Context, token string, opts IntrospectOptions) (*TokenIntrospection, error)

Introspect asks LumoAuth whether a token is active and what it carries (RFC 7662):

info, err := client.Auth.Introspect(ctx, token, lumoauth.IntrospectOptions{
    ClientAuth: lumoauth.ClientAuth{ClientID: apiClientID, ClientSecret: apiClientSecret},
})
if err != nil {
    return err
}
if !info.Active {
    // refuse the request
}

LumoAuth answers only about tokens that were issued to the calling client or whose aud names it; any other token is inactive. An inactive token is a result, never an error. A refused client authentication is an error that matches ErrAuthentication.

func (*AuthResource) PollBackchannelToken added in v1.8.0

func (r *AuthResource) PollBackchannelToken(ctx context.Context, authReqID string, opts PollOptions) (*TokenResponse, error)

PollBackchannelToken polls the token endpoint with the CIBA grant (urn:openid:params:grant-type:ciba) until the person approved, denied or the request expired. The polling rules and errors are those of PollDeviceToken. The client must authenticate (opts.ClientAuth with a credential).

func (*AuthResource) PollDeviceToken added in v1.8.0

func (r *AuthResource) PollDeviceToken(ctx context.Context, deviceCode string, opts PollOptions) (*TokenResponse, error)

PollDeviceToken polls the token endpoint with a device code until the person approved (tokens), denied (an *ApprovalError that matches ErrApprovalDenied) or the code expired (an *ApprovalError that matches ErrApprovalTimeout: the server's expired_token, or opts.ExpiresIn passed). It waits opts.Interval before each poll, keeps polling on authorization_pending and waits 5 seconds longer after each slow_down. Other answers are returned as usual API errors; a cancelled ctx ends it with a *NetworkError.

func (*AuthResource) PushAuthorizationRequest added in v1.8.0

func (r *AuthResource) PushAuthorizationRequest(ctx context.Context, params AuthorizationURLParams, auth ClientAuth) (*PushedAuthorizationResponse, error)

PushAuthorizationRequest sends the parameters of an authorization request to LumoAuth first (RFC 9126), so that they never pass through the browser, and returns the request_uri to redirect with. Applications with "Require PAR" or a FAPI profile must start every sign-in this way.

auth := lumoauth.ClientAuth{ClientID: clientID, ClientSecret: clientSecret}
pushed, err := client.Auth.PushAuthorizationRequest(ctx, lumoauth.AuthorizationURLParams{
    RedirectURI:   "https://app.example.com/callback",
    Scope:         "openid profile",
    State:         state,
    CodeChallenge: challenge,
}, auth)
if err != nil {
    return err
}
redirect, err := client.Auth.AuthorizationURL(lumoauth.AuthorizationURLParams{
    ClientID: clientID, RequestURI: pushed.RequestURI,
})

params.ClientID defaults to auth.ClientID. Set params.Request (with ClientID only) to push a signed request object instead of the plain parameters. A confidential client authenticates with auth; a public client sends its client_id. With WithDPoP, the request carries a DPoP proof, which binds the authorization code to the key.

func (*AuthResource) RefreshToken

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

RefreshToken exchanges a refresh token for a new access token.

func (*AuthResource) RegisterClient added in v1.8.0

func (r *AuthResource) RegisterClient(ctx context.Context, metadata ClientMetadata, opts RegisterClientOptions) (*RegisteredClient, error)

RegisterClient registers a client (RFC 7591), for example an MCP client or an agent that registers itself:

registered, err := client.Auth.RegisterClient(ctx, lumoauth.ClientMetadata{
    ClientName:              "Acme field app",
    RedirectURIs:            []string{"https://field.acme.com/callback"},
    TokenEndpointAuthMethod: "none",
}, lumoauth.RegisterClientOptions{InitialAccessToken: iat})

Keep RegistrationAccessToken (and ClientSecret, for a confidential client) secret; neither is shown again. Refused metadata is an *APIError with Code invalid_client_metadata or invalid_redirect_uri.

func (*AuthResource) Revoke

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

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

func (*AuthResource) TokenExchange

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

TokenExchange performs an RFC 8693 exchange — the primitive behind delegation and MCP audience scoping. A confidential application authenticates with ClientID and ClientSecret (Basic by default) or ClientAssertion; an agent's on-behalf-of exchange needs none.

func (*AuthResource) UserInfo

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.

func (*AuthResource) VerifyAuthorizationResponse added in v1.8.0

func (r *AuthResource) VerifyAuthorizationResponse(ctx context.Context, responseJWT string, opts AuthorizationResponseOptions) (*AuthorizationResponse, error)

VerifyAuthorizationResponse verifies the `response` parameter of a callback that a JARM response mode (jwt, query.jwt, form_post.jwt, fragment.jwt) produced, and returns its parameters. It checks, in order: the compact JWS form; alg (RSA or EC families, never none or HMAC) and kid; iss = the organization's issuer identifier; the signature against the issuer's keys (from the discovery document); aud = opts.ClientID; exp; and state when opts.ExpectedState is set. Use the code only after this.

Failures are a *ValidationError whose Reason is a TokenRejected* constant (TokenRejectedState for a state that is not the expected one). A verified response that carries an error (the person denied, say) is returned with Error set and a nil error: check Error before you read Code.

type AuthTokenParams

type AuthTokenParams struct {
	// ResourceToken is the `resource+jwt` obtained from the target
	// resource. Required.
	ResourceToken string
	// Scope is space-separated. It is sent as the body field `scope`, which
	// the server ignores for request_type=auth: the scope of the auth token
	// comes from the resource token's `scope` claim.
	Scope string
	// AgentToken is the `agent+jwt` presented in Agent-Auth. Required —
	// the endpoint authenticates the agent through that header, not the
	// request body. The request must be signed with the key in the agent
	// token's cnf claim.
	AgentToken string
	// RedirectURI is where consent should return the user. Required when
	// the user has to consent (the server answers 400 invalid_request
	// without it). Must be registered for the agent.
	RedirectURI string
}

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

type AuthorizationResponse added in v1.8.0

type AuthorizationResponse struct {
	Code  string
	State string
	// Issuer is the response's iss: the organization's issuer identifier.
	Issuer           string
	Error            string
	ErrorDescription string
	ErrorURI         string
	// Claims are every claim of the response JWT.
	Claims map[string]any
}

AuthorizationResponse holds the parameters of a verified authorization response. Either Code (and State) or Error is set.

type AuthorizationResponseOptions added in v1.8.0

type AuthorizationResponseOptions struct {
	// ClientID is your application's client ID: the response's aud.
	// Required.
	ClientID string
	// ExpectedState, when set, must equal the response's state (the value
	// that you sent and kept for this sign-in).
	ExpectedState string
	// JWKS supplies the organization's keys directly. When nil, the keys
	// are read through the issuer's discovery document and cached on this
	// client, with one refetch for an unknown kid.
	JWKS *JWKS
	// ClockSkew tolerated on exp. The default (0) means 60 seconds; a
	// negative value means none.
	ClockSkew time.Duration
}

AuthorizationResponseOptions configures VerifyAuthorizationResponse.

type AuthorizationURLParams

type AuthorizationURLParams struct {
	// ClientID is the OAuth client initiating the flow. Required.
	ClientID string
	// RedirectURI must match one registered on the client. Required, except
	// with RequestURI or Request.
	RedirectURI string
	// Scope defaults to "openid profile email".
	Scope string
	// State is the CSRF token echoed back to the redirect URI.
	State string
	// Nonce is the OpenID Connect nonce that the ID token carries back.
	Nonce string
	// ResponseType defaults to "code".
	ResponseType string
	// ResponseMode is how the answer comes back: "query" (the default for
	// code), or a JARM mode ("jwt", "query.jwt", "form_post.jwt",
	// "fragment.jwt") that signs it. Verify a JARM answer with
	// VerifyAuthorizationResponse.
	ResponseMode string
	// CodeChallenge enables PKCE. When set and CodeChallengeMethod is
	// empty, "S256" is used.
	CodeChallenge       string
	CodeChallengeMethod string
	// Prompt is the OIDC prompt parameter ("consent", "login", "none").
	Prompt string
	// AccessType set to "offline" requests a refresh token.
	AccessType string
	// Resource is the RFC 8707 resource indicator: the absolute URL of the
	// API that the token is for.
	Resource string
	// Extra adds arbitrary query parameters.
	Extra map[string]string
	// AuthorizationDetails asks for fine-grained permissions (RFC 9396):
	// a list of objects, each with a non-empty "type", for example
	// {"type": "payment_initiation", "actions": ["initiate"], "instructedAmount": …}.
	// It is sent as a JSON string, and as a JSON array claim in a request
	// object. LumoAuth checks the types; the SDK checks only the shape.
	AuthorizationDetails []map[string]any

	// RequestURI is the request_uri of a pushed authorization request
	// (PushAuthorizationRequest). The URL then carries only client_id and
	// request_uri, and every other field must be empty.
	RequestURI string
	// Request is a signed request object (CreateRequestObject), sent by
	// value. The URL then carries only client_id and request, and every
	// other field must be empty: the parameters are in the object.
	Request string
}

AuthorizationURLParams describes an authorization-code redirect. The same parameters make a pushed authorization request (PushAuthorizationRequest) and a signed request object (CreateRequestObject).

type BackchannelAuthorizeParams added in v1.8.0

type BackchannelAuthorizeParams struct {
	// ClientAuth authenticates the application, which must be confidential
	// and have CIBA switched on. Required.
	ClientAuth ClientAuth
	// LoginHint names the person: an e-mail address or a user ID. Set it,
	// IDTokenHint or LoginHintToken (exactly one).
	LoginHint string
	// IDTokenHint is an ID token that LumoAuth issued to the application for
	// the person.
	IDTokenHint string
	// LoginHintToken is a token that names the person.
	LoginHintToken string
	// Scopes are the scopes asked for. Required; include openid.
	Scopes []string
	// BindingMessage is shown to the person on both devices, so that they
	// can tell that the request is the one they started (at most 255
	// characters).
	BindingMessage string
	// RequestedExpiry asks for a lifetime of the request (whole seconds).
	RequestedExpiry time.Duration
	// ACRValues are the requested authentication context classes.
	ACRValues []string
}

BackchannelAuthorizeParams starts an OpenID CIBA request: LumoAuth asks the person on their own device (push or e-mail) to approve the sign-in.

type BackchannelAuthorizeResponse added in v1.8.0

type BackchannelAuthorizeResponse struct {
	AuthReqID string `json:"auth_req_id"`
	// ExpiresIn is the lifetime of the request in seconds.
	ExpiresIn int `json:"expires_in"`
	// Interval is the minimum wait between polls in seconds.
	Interval int `json:"interval,omitempty"`
}

BackchannelAuthorizeResponse is the answer of the backchannel authentication endpoint (CIBA Core §7.3). LumoAuth gives the same answer for a person it does not know, so the answer never confirms the hint.

func (*BackchannelAuthorizeResponse) PollOptions added in v1.8.0

PollOptions returns the options for PollBackchannelToken from this answer: its interval and lifetime, with the given client authentication.

type BaseError

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

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

func (*BaseError) ErrCode

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. It is set by
	// CheckBudget; a server refusal carries no policy, so it is nil there.
	Budget *AgentBudget
	// RetryAfter is the server's Retry-After hint: the time until the spent
	// window starts again. 0 for CheckBudget.
	RetryAfter time.Duration
}

BudgetError is returned when an agent's budget policy blocks an action: by Agent.CheckBudget, which checks locally and makes no request, and for a server answer with the body code budget_exceeded (429).

type CheckOptions

type CheckOptions struct {
	// Context supplies attributes for ABAC evaluation alongside the RBAC
	// decision.
	Context map[string]any
	// UserID asks about another user instead of the caller. It must be the
	// user's LumoAuth ID (a UUID) in the caller's organization. The SDK sends
	// it as the request's subject, {"type": "user", "id": UserID}.
	//
	// Asking about someone other than yourself needs the authz:check scope
	// (on the API key or the access token) or the authz.check permission.
	// Without it the server answers 403 INSUFFICIENT_PERMISSIONS; an unknown
	// ID gets 404 SUBJECT_NOT_FOUND. Leave it empty to check the caller.
	UserID string
	// AgentID asks about an agent (its agt_… ID) instead of the caller, with
	// the same authz:check rule as UserID. Set at most one of the two.
	AgentID string
}

CheckOptions carries the optional arguments shared by every check.

type Client

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

Client is the general-purpose LumoAuth API client.

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

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

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

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

A Client is safe for concurrent use.

func New

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

New builds a Client. It returns a *ConfigError when no credential is configured (an API key, a token provider, or the client credentials of WithClientCredentials), unless WithoutCredential is given.

Example

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

package main

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

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

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

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

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

On a custom domain BaseURL is the domain. The generated client puts /orgs/{orgId} in every path, and a custom domain answers 404 for those. When the client has an organization ID (WithOrgID), HTTPClient is a copy whose transport removes the segment of that organization from requests to the custom domain, so pass the same ID to the generated client's calls. Without an organization ID the generated client cannot reach a custom domain.

func (*Client) BaseURL

func (c *Client) BaseURL() string

BaseURL returns the address that the client sends its requests to, without a trailing slash: the custom domain when one is set, the LumoAuth instance URL otherwise.

func (*Client) CustomDomain added in v1.7.0

func (c *Client) CustomDomain() string

CustomDomain returns the organization's custom domain as an origin, for example "https://auth.acme.com", or "" when none is set.

func (*Client) DPoP added in v1.2.0

func (c *Client) DPoP() *DPoPSigner

DPoP returns the signer passed with WithDPoP, or nil.

func (*Client) Do

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.

On a custom domain, give the path without the /orgs/{orgId} segment, or build it with OrgPath. A path that starts with the segment of the client's own organization still works when the client has that organization ID: the segment is removed. A path of another organization is sent as it is.

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

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

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

package main

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

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

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

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

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

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) Issuer added in v1.7.0

func (c *Client) Issuer() (string, error)

Issuer returns the issuer identifier of the organization: the `iss` of its tokens and the audience of a client assertion. On a custom domain it is the bare domain. On the platform host it is {baseURL}/orgs/{orgID}/api/v1, and a client without an organization ID gets a *ConfigError.

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

On a custom domain the result is /api/v1/admin/users, and no organization ID is needed.

type ClientAssertionOptions added in v1.3.0

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

ClientAssertionOptions configures a ClientAssertionSigner.

type ClientAssertionSigner added in v1.3.0

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

ClientAssertionSigner signs private_key_jwt client assertions with one key.

func GenerateClientAssertionSigner added in v1.3.0

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

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

func LoadClientAssertionSigner added in v1.3.0

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

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

func NewClientAssertionSigner added in v1.3.0

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

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

func (*ClientAssertionSigner) Algorithm added in v1.3.0

func (s *ClientAssertionSigner) Algorithm() string

Algorithm is the JWS alg of the assertions.

func (*ClientAssertionSigner) Assertion added in v1.3.0

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

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

func (*ClientAssertionSigner) JWKS added in v1.3.0

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

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

func (*ClientAssertionSigner) KeyID added in v1.3.0

func (s *ClientAssertionSigner) KeyID() string

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

func (*ClientAssertionSigner) PrivateKeyPEM added in v1.3.0

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

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

func (*ClientAssertionSigner) PublicJWK added in v1.3.0

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

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

type ClientAttestation added in v1.8.0

type ClientAttestation struct {
	// Attestation is the attester's JWT (typ oauth-client-attestation+jwt),
	// sent as it is. Its sub is the client ID and its cnf.jwk the public key
	// of InstanceKey. Required.
	Attestation string
	// InstanceKey is the instance's private key. It signs the proof of
	// possession; its algorithm must be one of RS256–RS512, PS256–PS512 or
	// ES256–ES512. Required.
	InstanceKey *ClientAssertionSigner
	// Challenge is a challenge that the server handed out, when it uses
	// them. It becomes the proof's challenge claim.
	Challenge string
}

ClientAttestation is what an instance of your application presents for attestation-based client authentication: the JWT that your attester issued for the instance and the instance's own key.

type ClientAuth added in v1.8.0

type ClientAuth struct {
	// ClientID is the application's client ID. Required.
	ClientID string
	// ClientSecret is the secret of a confidential application.
	ClientSecret string
	// ClientAuthMethod is how ClientSecret is sent: ClientSecretPost (the
	// default) or ClientSecretBasic.
	ClientAuthMethod string
	// AssertionSigner signs a private_key_jwt client assertion (RFC 7523)
	// for each request, addressed to the organization's issuer.
	AssertionSigner *ClientAssertionSigner
	// ClientAssertion is a client assertion that you signed. Single-use.
	ClientAssertion string
	// Attestation authenticates an instance of the application with an
	// attestation and a proof of possession of its key.
	Attestation *ClientAttestation
}

ClientAuth is how your application authenticates at LumoAuth's OAuth endpoints. Set ClientID and at most one credential:

  • nothing else: a public client, which sends only client_id;
  • ClientSecret, sent as form fields (ClientSecretPost, the default) or in an HTTP Basic header (ClientAuthMethod: ClientSecretBasic);
  • AssertionSigner (private_key_jwt): a new client assertion is signed for each request, so it also works for the polling calls;
  • ClientAssertion: one assertion that you signed yourself. It works once, so do not use it for polling;
  • Attestation (attest_jwt_client_auth): the attester's JWT and a new proof of possession for each request.

type ClientCredentialsParams added in v1.8.0

type ClientCredentialsParams struct {
	// ClientID is the OAuth client or the agent. Required.
	ClientID string
	// ClientSecret authenticates a client with a secret. Set it or
	// ClientAssertion, not both.
	ClientSecret string
	// ClientAuthMethod is how ClientSecret is sent: ClientSecretPost (the
	// default, as ClientCredentials does) or ClientSecretBasic.
	ClientAuthMethod string
	// ClientAssertion is a private_key_jwt client assertion (RFC 7523),
	// built with ClientAssertionSigner.Assertion; it is single-use.
	ClientAssertion string
	// Scopes optionally narrows the token; empty means the client's
	// defaults.
	Scopes []string
	// Resource is the RFC 8707 resource indicator: the absolute URL of the
	// API that the token is for. It becomes the token's aud; without it,
	// aud is the client ID. The client's allowed audiences, when set, must
	// cover it, and a registered MCP server applies its own policy.
	Resource string
}

ClientCredentialsParams describes a client-credentials grant.

type ClientMetadata added in v1.8.0

type ClientMetadata struct {
	RedirectURIs            []string `json:"redirect_uris,omitempty"`
	ClientName              string   `json:"client_name,omitempty"`
	TokenEndpointAuthMethod string   `json:"token_endpoint_auth_method,omitempty"`
	GrantTypes              []string `json:"grant_types,omitempty"`
	ResponseTypes           []string `json:"response_types,omitempty"`
	// Scope is the space-separated list of scopes the client may ask for.
	Scope                  string   `json:"scope,omitempty"`
	ApplicationType        string   `json:"application_type,omitempty"`
	ClientURI              string   `json:"client_uri,omitempty"`
	LogoURI                string   `json:"logo_uri,omitempty"`
	PolicyURI              string   `json:"policy_uri,omitempty"`
	TOSURI                 string   `json:"tos_uri,omitempty"`
	Contacts               []string `json:"contacts,omitempty"`
	JWKSURI                string   `json:"jwks_uri,omitempty"`
	JWKS                   *JWKS    `json:"jwks,omitempty"`
	PostLogoutRedirectURIs []string `json:"post_logout_redirect_uris,omitempty"`
	// Extra holds other members; a name that a field above also sets is
	// refused.
	Extra map[string]any `json:"-"`
}

ClientMetadata is the metadata of a client to register (RFC 7591 §2, OpenID Connect Dynamic Client Registration). Fields left empty are not sent; Extra adds any other member.

type ConfidentialClient

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

ConfidentialClient is what the deprecated NewDelegationChain needs from an agent: a token source plus OAuth client credentials. *Agent satisfies it.

As for a TokenSource, an implementation that addresses its organization on a custom domain also has the method CustomDomain() string.

type ConfigError

type ConfigError struct {
	*BaseError
}

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

func NewConfigError

func NewConfigError(message string) *ConfigError

NewConfigError builds a ConfigError.

type ConnectionToken added in v1.8.0

type ConnectionToken struct {
	// AccessToken is the provider's token. Send it to the provider only.
	AccessToken string
	// TokenType is "Bearer".
	TokenType string
	// ExpiresAt is when the token expires; zero when the provider's token
	// does not expire.
	ExpiresAt time.Time
	Scopes    []string
}

ConnectionToken is a live access token for an outbound connection. Printing it (fmt, log/slog) shows no token; read AccessToken to use it, and never log it.

func (ConnectionToken) GoString added in v1.8.0

func (t ConnectionToken) GoString() string

GoString keeps the token out of %#v.

func (ConnectionToken) Header added in v1.8.0

func (t ConnectionToken) Header() string

Header is the Authorization header value for the provider.

func (ConnectionToken) LogValue added in v1.8.0

func (t ConnectionToken) LogValue() slog.Value

LogValue keeps the token out of log/slog output.

func (ConnectionToken) String added in v1.8.0

func (t ConnectionToken) String() string

String shows the token's type, expiry and scopes, never the token.

type ConnectionTokenParams added in v1.8.0

type ConnectionTokenParams struct {
	// UserID names the person (user ID or e-mail address) of a
	// user-delegated connection. The agent must be allowed to act on behalf
	// of users, and the person must have allowed this agent on their grant.
	// Leave it empty for a machine connection.
	UserID string
	// Traceparent is a W3C trace context header value, sent as the
	// traceparent header, so that the audit entry carries your trace ID.
	Traceparent string
}

ConnectionTokenParams configures GetConnectionToken.

type ConsentURLParams deprecated

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

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

Deprecated: use ApplicationConsentParams. LumoAuth starts a sign-in only for an application, never for an agent's ID, and the agent's credentials cannot redeem the code.

type CreateTaskParams

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

CreateTaskParams describes an ephemeral task.

type DPoPProofOption added in v1.2.0

type DPoPProofOption func(*dpopProofConfig)

DPoPProofOption customises one proof.

func WithProofAccessToken added in v1.2.0

func WithProofAccessToken(accessToken string) DPoPProofOption

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

func WithProofNonce added in v1.2.0

func WithProofNonce(nonce string) DPoPProofOption

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

type DPoPRequest added in v1.2.0

type DPoPRequest struct {
	// Method is the HTTP method of the request.
	Method string
	// URL is the absolute request URL. Query and fragment are ignored.
	URL string
	// Proof is the value of the DPoP header ("" when absent).
	Proof string
	// Scheme is the Authorization scheme the token came with: "DPoP" or
	// "Bearer".
	Scheme string
	// Nonce is the nonce that this resource server expects in the proof
	// (RFC 9449 §9), when it issues nonces. "" means no nonce check. A
	// proof without it, or with another value, is refused with
	// TokenRejectedDPoPNonce.
	Nonce string
}

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

func DPoPRequestFromHTTP added in v1.2.0

func DPoPRequestFromHTTP(r *http.Request) *DPoPRequest

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

type DPoPSigner added in v1.2.0

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

DPoPSigner signs RFC 9449 proofs with one private key.

func LoadDPoPSigner added in v1.2.0

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

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

func NewDPoPSigner added in v1.2.0

func NewDPoPSigner() (*DPoPSigner, error)

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

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

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

func NewDPoPSignerEd25519 added in v1.2.0

func NewDPoPSignerEd25519() (*DPoPSigner, error)

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

func NewDPoPSignerFromKey added in v1.2.0

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

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

func (*DPoPSigner) Algorithm added in v1.2.0

func (s *DPoPSigner) Algorithm() string

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

func (*DPoPSigner) AuthorizeRequest added in v1.2.0

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

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

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

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

func (*DPoPSigner) Nonce added in v1.2.0

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

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

func (*DPoPSigner) Proof added in v1.2.0

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

Proof signs a DPoP proof for one HTTP request.

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

func (*DPoPSigner) PublicJWK added in v1.2.0

func (s *DPoPSigner) PublicJWK() JWK

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

func (*DPoPSigner) RememberNonce added in v1.2.0

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

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

func (*DPoPSigner) SetNonce added in v1.2.0

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

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

func (*DPoPSigner) Thumbprint added in v1.2.0

func (s *DPoPSigner) Thumbprint() string

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

type DelegationApplication added in v1.8.0

type DelegationApplication struct {
	// ClientID is the application's client ID, never the agent's agt_… ID.
	// Required.
	ClientID string
	// ClientSecret is the application's secret; leave it empty for a public
	// application (PKCE alone).
	ClientSecret string
	// RedirectURI is one of the application's registered redirect URIs,
	// where your callback receives the code. Required.
	RedirectURI string
	// OfflineAccess asks for a refresh token (scope offline_access). The
	// chain needs it to renew the person's token and to revoke the grant.
	OfflineAccess bool
}

DelegationApplication is the application of your organization through which a person lets an agent act for them. An agent never starts a sign-in: the person signs in to this application, the application redeems the code, and the agent exchanges the person's access token.

type DelegationChain

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

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

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

  1. Consent — the person signs in to your application (ConsentURL), and the application redeems the code (HandleConsentCallback). Or register tokens that you already hold (SetUserTokens, SetUserToken).

  2. Token exchange — combine the person'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 — the application revokes the person's refresh token, which ends every delegated token of that grant.

For example:

chain, err := lumoauth.NewDelegationChainForApplication(agent, lumoauth.DelegationApplication{
    ClientID:      os.Getenv("APP_CLIENT_ID"),
    ClientSecret:  os.Getenv("APP_CLIENT_SECRET"),
    RedirectURI:   "https://app.example.com/agent/callback",
    OfflineAccess: true,
})
url, err := chain.ConsentURL("session-1", []string{"documents:read"}, "")
// … the person signs in, your callback receives `code` …
err = chain.HandleConsentCallback(ctx, "session-1", code)
resp, err := chain.DoRaw(ctx, "session-1", "GET", "https://api.example.com/documents", nil)

A DelegationChain is safe for concurrent use.

func NewDelegationChain deprecated

func NewDelegationChain(agent ConfidentialClient, redirectURI string) *DelegationChain

NewDelegationChain builds a chain over an authenticated agent, with the agent's own client ID for the consent flow.

Deprecated: LumoAuth starts a sign-in only for an application, so the consent flow of this chain cannot work for an agent's agt_… ID: ConsentURL and HandleConsentCallback then return a *ConfigError. Use NewDelegationChainForApplication. The exchange, delegated requests and SetUserToken keep working.

func NewDelegationChainForApplication added in v1.8.0

func NewDelegationChainForApplication(agent TokenSource, app DelegationApplication) (*DelegationChain, error)

NewDelegationChainForApplication builds a chain whose consent flow goes through one of your organization's applications. agent supplies the actor token of every exchange (an *Agent does); the application's credentials redeem the code, refresh the person's token and revoke it. It returns a *ConfigError for an application without a client ID, with an agent's ID, or without an absolute redirect URI.

Example

Acting on behalf of a user, with the chain recorded in the token. The person signs in to an application of the organization; the agent then exchanges the person's token.

package main

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

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

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

	chain, err := lumoauth.NewDelegationChainForApplication(agent, lumoauth.DelegationApplication{
		ClientID:      os.Getenv("APP_CLIENT_ID"),
		ClientSecret:  os.Getenv("APP_CLIENT_SECRET"), // empty for a public application
		RedirectURI:   "https://app.example.com/agent/callback",
		OfflineAccess: true, // a refresh token, to renew the person's token and to revoke
	})
	if err != nil {
		log.Fatal(err)
	}
	ctx := context.Background()

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

	// 2. Your callback receives ?code=…&state=… (compare the state with
	// chain.ConsentState). The application redeems the code.
	if err := chain.HandleConsentCallback(ctx, "session-1", "code-from-callback"); err != nil {
		log.Fatal(err)
	}

	// 3. Call as "agent acting for user". The exchange happens on demand.
	resp, err := chain.DoRaw(ctx, "session-1", http.MethodGet, "https://api.example.com/documents", nil)
	if err != nil {
		log.Fatal(err)
	}
	_ = resp.Body.Close()

	// 4. End the delegation: the application revokes the person's refresh token.
	if err := chain.Revoke(ctx, "session-1"); err != nil {
		log.Print(err)
	}
}

func (*DelegationChain) ActiveSessions

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

ActiveSessions returns the session IDs holding user tokens.

func (*DelegationChain) ActorChain

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

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

func (*DelegationChain) ConsentState added in v1.8.0

func (c *DelegationChain) ConsentState(sessionID string) string

ConsentState returns the state of the session's consent URL that has not been redeemed yet, or "".

func (*DelegationChain) ConsentURL

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

ConsentURL builds the URL where the person signs in to your application to let the agent act for them. Redirect the person there; the sign-in returns them to the application's redirect URI with a code.

The URL names the application, asks for "openid", the scopes and, with DelegationApplication.OfflineAccess, offline_access, and carries a PKCE S256 challenge whose verifier the chain keeps for HandleConsentCallback. Scopes are required: the exchange grants the agent only scopes that the person consented to. state defaults to a random value; ConsentState returns it, so your callback can compare it with the one it receives.

On a chain from the deprecated NewDelegationChain, this builds the old URL with the agent's client ID, and returns a *ConfigError for an agent's agt_… ID, which LumoAuth answers with "Unknown Application".

func (*DelegationChain) DelegateToSubAgent

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

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

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

func (*DelegationChain) DelegateToSubAgentForResource added in v1.1.0

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

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

func (*DelegationChain) DelegatedToken

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) Forget added in v1.8.0

func (c *DelegationChain) Forget(sessionID string)

Forget drops a session's local state (tokens and pending consent) without any request. The person's grant at LumoAuth is not touched.

func (*DelegationChain) HandleConsentCallback

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

HandleConsentCallback redeems the code of the consent callback as the application (its client ID, its secret when it is confidential, and the PKCE verifier of this session's ConsentURL) and stores the person's tokens under sessionID. The agent's credentials play no part. The session's consent is used up whether or not the redemption succeeds: a code is single-use, so a failure needs a new ConsentURL.

It returns a *ConfigError when this chain handed out no consent URL for the session, and, on a chain from the deprecated NewDelegationChain, for an agent's agt_… ID.

func (*DelegationChain) HasDelegation

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

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

func (*DelegationChain) Revoke

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

Revoke ends a delegation: the application revokes the person's refresh token at LumoAuth (POST /oauth/revoke with the application's client ID, and its secret when it is confidential), which ends every delegated token of that grant, and the chain drops the session's local state. Local state is cleared even if the server call fails, so a revoked session never keeps serving requests from cache.

When the chain cannot end the grant at LumoAuth, it only forgets the local state and says so: the error matches ErrDelegationNotRevoked (and ErrConfig). That is the case for a session without a refresh token (for example one registered with SetUserToken), and on a chain without the application's credentials (the deprecated NewDelegationChain with an agent: LumoAuth refuses a revocation by another client than the one the token was issued to). Revoke the person's refresh token where it is held, with Auth.Revoke and the application's credentials, or call Forget when forgetting is all you want. An unknown session returns nil.

func (*DelegationChain) RevokeAll

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

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

func (*DelegationChain) SetUserToken

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

SetUserToken registers a user access token you already hold, skipping the consent redirect. Without a refresh token the SDK cannot renew it, so the delegation lasts only as long as the token does, and Revoke can only forget it (ErrDelegationNotRevoked). SetUserTokens also takes the refresh token.

func (*DelegationChain) SetUserTokens added in v1.8.0

func (c *DelegationChain) SetUserTokens(sessionID string, tokens *TokenResponse) error

SetUserTokens registers the person's tokens that your application got itself, for example from its own sign-in: the access token, and the refresh token when there is one. With the refresh token, and the application's credentials (NewDelegationChainForApplication), the chain renews the person's token and Revoke ends the grant.

type DelegationResource

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

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

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

func (*DelegationResource) ApplicationConsentURL added in v1.8.0

func (r *DelegationResource) ApplicationConsentURL(params ApplicationConsentParams) (string, error)

ApplicationConsentURL builds the authorization URL where a person signs in to your application to let an agent act for them. The application then redeems the code with ExchangeCode (its client ID, its secret when it is confidential, and the PKCE verifier), and the agent calls Exchange with the person's access token. Revoke the person's refresh token as the application to end the delegation.

func (*DelegationResource) ConsentURL deprecated

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

ConsentURL builds an authorization URL that requests offline access.

Deprecated: use ApplicationConsentURL, which names an application, uses PKCE and asks for offline_access. With an agent's ID this returns a ValidationError: LumoAuth answers "Unknown Application" for it.

func (*DelegationResource) Exchange

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

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

func (*DelegationResource) ExchangeCode

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

ExchangeCode trades a consent callback code for the person's tokens. Pass the APPLICATION's client ID (and its secret when it is confidential) and the PKCE verifier; the agent's credentials are refused for the code.

func (*DelegationResource) ExchangeForResource added in v1.1.0

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

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

func (*DelegationResource) ParseActorChain

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

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

func (*DelegationResource) RefreshUserToken

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

RefreshUserToken refreshes the person's access token, as the application that holds the refresh token (its client ID, and its secret when it is confidential).

func (*DelegationResource) Revoke

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

Revoke invalidates the person's refresh token, which also ends every token derived from it, the agent's delegated tokens included. Pass the client ID (and secret) of the APPLICATION that the token was issued to: LumoAuth refuses a revocation by another client, such as the agent (RFC 7009 §2.1).

func (*DelegationResource) Subject

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

Subject is the method form of TokenSubject.

type DeviceAuthorizationParams added in v1.8.0

type DeviceAuthorizationParams struct {
	// ClientAuth names the application. A public client (a CLI, a TV app)
	// sets ClientID alone; a confidential client authenticates as at the
	// token endpoint. The application must allow the device code grant.
	ClientAuth ClientAuth
	// Scopes are the scopes asked for. Empty means openid, profile and email,
	// as far as the application allows them.
	Scopes []string
	// Resource is the RFC 8707 resource indicator: the absolute URL of the
	// API that the token is for.
	Resource string
	// AuthorizationDetails asks for fine-grained permissions (RFC 9396);
	// see AuthorizationURLParams.AuthorizationDetails.
	AuthorizationDetails []map[string]any
}

DeviceAuthorizationParams starts a device authorization grant.

type DeviceAuthorizationResponse added in v1.8.0

type DeviceAuthorizationResponse struct {
	DeviceCode              string `json:"device_code"`
	UserCode                string `json:"user_code"`
	VerificationURI         string `json:"verification_uri"`
	VerificationURIComplete string `json:"verification_uri_complete,omitempty"`
	// ExpiresIn is the lifetime of the codes in seconds.
	ExpiresIn int `json:"expires_in"`
	// Interval is the minimum wait between polls in seconds.
	Interval int `json:"interval,omitempty"`
}

DeviceAuthorizationResponse is the answer of the device authorization endpoint (RFC 8628 §3.2). Show UserCode and VerificationURI (or VerificationURIComplete, for example as a QR code) to the person, then call PollDeviceToken with DeviceCode.

func (*DeviceAuthorizationResponse) PollOptions added in v1.8.0

func (d *DeviceAuthorizationResponse) PollOptions(auth ClientAuth) PollOptions

PollOptions returns the options for PollDeviceToken from this answer: its interval and lifetime, with the given client authentication.

type EndSessionURLParams added in v1.8.0

type EndSessionURLParams struct {
	// IDTokenHint is the last ID token that LumoAuth issued to your client
	// for this user; an expired one is accepted. With it, LumoAuth ends the
	// session at once and honours PostLogoutRedirectURI. Without it, the
	// user confirms the sign-out on a LumoAuth page and stays there.
	IDTokenHint string
	// PostLogoutRedirectURI is where LumoAuth sends the browser afterwards.
	// It must be an absolute URL registered on the client as a post-logout
	// redirect URI.
	PostLogoutRedirectURI string
	// State is passed back to PostLogoutRedirectURI unchanged.
	State string
}

EndSessionURLParams describes an RP-initiated logout (OpenID Connect RP-Initiated Logout 1.0) at the organization's end-session endpoint.

type EvaluateTaskParams

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

EvaluateTaskParams describes how a task ended.

type ExchangeCodeParams

type ExchangeCodeParams struct {
	// Code is the authorization code from the callback. Required.
	Code string
	// RedirectURI must match the one used to obtain the code. Required.
	RedirectURI string
	// ClientID is the OAuth client. Required.
	ClientID string
	// ClientSecret is required for confidential clients.
	ClientSecret string
	// CodeVerifier is the PKCE verifier matching the challenge sent to
	// the authorization endpoint.
	CodeVerifier string
	// ClientAuth, when set, authenticates the client instead of ClientID and
	// ClientSecret (leave those empty): private_key_jwt with an
	// AssertionSigner, attestation, HTTP Basic. FAPI applications need it.
	ClientAuth *ClientAuth
	// AuthorizationDetails asks for a part of the granted fine-grained
	// permissions (RFC 9396). nil sends nothing: the token gets the whole
	// grant. An empty, non-nil list sends [] (none). A wider request is
	// refused with invalid_authorization_details.
	AuthorizationDetails []map[string]any
}

ExchangeCodeParams describes an authorization-code exchange.

type ID

type ID string

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

func (ID) MarshalJSON

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 IntrospectOptions added in v1.8.0

type IntrospectOptions struct {
	// TokenTypeHint is "access_token" or "refresh_token": where LumoAuth
	// looks first.
	TokenTypeHint string
	// ClientAuth authenticates your application (or agent), which must hold
	// a credential: public clients cannot introspect. Required.
	ClientAuth ClientAuth
}

IntrospectOptions configures Introspect.

type JITContext

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

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

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

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

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

func NewJITContext

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

NewJITContext builds a JIT context over any authenticated token source.

Example

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

package main

import (
	"context"
	"fmt"
	"log"

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

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

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

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

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

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

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

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. LumoAuth uses it as `agent_jkt` in resource tokens and as `cnf_jkt` in the answer of the token verify endpoint. Auth tokens carry the full key in cnf.jwk, not the thumbprint.

type JWKS

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

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

func FetchAccessTokenJWKS added in v1.2.0

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

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

For an organization on a custom domain, the issuer is the bare domain. NewAccessTokenKeyCacheForCustomDomain and AccessTokenVerifyOptions.CustomDomain read the domain's discovery document at /api/v1/.well-known/openid-configuration.

func FetchIssuerJWKS

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. The AAuth issuer has the platform form on every host, so this address is on the platform host. To read the keys from an organization's custom domain, use NewJWKSCacheForCustomDomain or VerifyOptions.CustomDomain.

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 NewJWKSCacheForCustomDomain added in v1.7.0

func NewJWKSCacheForCustomDomain(customDomain string, ttl time.Duration, httpClient *http.Client) (*JWKSCache, error)

NewJWKSCacheForCustomDomain builds a cache that reads the AAuth key set from an organization's custom domain, for example "auth.acme.com", at /api/v1/aauth/jwks.json. It returns a *ConfigError for a value that is empty or not valid (see WithCustomDomain). A ttl of 0 means one hour.

func (*JWKSCache) 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 JitTokenClaims added in v1.8.0

type JitTokenClaims struct {
	// AuthorizationDetails are the approved RFC 9396 entries
	// (permissions.authorization_details).
	AuthorizationDetails []map[string]any
	// Subject is the token's sub: the user, or "agent_agt_…" for an agent
	// that acts on its own.
	Subject string
	// AgentID is the agent that the approval was issued to ("agt_…").
	AgentID string
	// TaskID is the task of the approval ("task_…"), when there is one.
	TaskID string
	// RequestID is the approved request ("jit_…"), when the token names it.
	RequestID string
	JTI       string
	Expires   int64
	// Raw is every claim of the token.
	Raw map[string]any
}

JitTokenClaims is a verified JIT token: the approval of one JIT request.

func VerifyJitToken added in v1.8.0

func VerifyJitToken(ctx context.Context, token string, opts JitTokenVerifyOptions) (*JitTokenClaims, error)

VerifyJitToken verifies a LumoAuth JIT token and returns the approval:

approval, err := lumoauth.VerifyJitToken(ctx, r.Header.Get("X-LumoAuth-Jit-Token"), lumoauth.JitTokenVerifyOptions{
    Issuer: "https://app.lumoauth.dev/orgs/acme-corp/api/v1",
    Caller: claims, // the verified access token of this request
    RequiredDetails: []map[string]any{{"type": "invoice", "actions": []string{"refund"}, "identifier": "INV-1001"}},
})

Failures are a *ValidationError whose Reason is a TokenRejected* constant: TokenRejectedJITNotForCaller for an approval of another person or agent, TokenRejectedJITInsufficient when RequiredDetails are not covered, TokenRejectedNotJIT for a token that is no approval. Fetch failures are *NetworkError or *APIError.

func (*JitTokenClaims) Covers added in v1.8.0

func (c *JitTokenClaims) Covers(required ...map[string]any) bool

Covers reports whether the approval allows every required entry (rule 11).

type JitTokenVerifyOptions added in v1.8.0

type JitTokenVerifyOptions struct {
	// Issuer is the organization's issuer, e.g.
	// "https://app.lumoauth.dev/orgs/acme-corp/api/v1". Required unless
	// CustomDomain is set.
	Issuer string
	// OrgID is the organization ID (slug): the aud of its JIT tokens. When
	// empty it is read from an Issuer of the form …/orgs/{slug}/api/v1.
	// Required with CustomDomain.
	OrgID string
	// CustomDomain is the organization's custom domain ("auth.acme.com"):
	// the issuer is then the bare domain, and Issuer is not used.
	CustomDomain string

	// Caller is the verified access token of the request (for example from
	// VerifyAccessToken or AccessTokenFromContext). The JIT token must
	// belong to it (rule 10). Set Caller, or ExpectedSubject and
	// ExpectedAgent; with neither, the binding is not checked.
	Caller *AccessTokenClaims
	// ExpectedSubject is the sub that the JIT token must carry: the user, or
	// "agent_agt_…" for an agent that acts on its own.
	ExpectedSubject string
	// ExpectedAgent is the agent that must hold the approval: "agt_…" or
	// "agent_agt_…".
	ExpectedAgent string
	// RequiredDetails are the RFC 9396 entries that the call needs; each
	// must be covered by the approval (rule 11). Empty means no check.
	RequiredDetails []map[string]any

	// JWKS supplies the organization's keys directly. When nil, they are
	// fetched through the discovery document and cached (KeyCache, or a
	// process-wide cache per issuer).
	JWKS *JWKS
	// KeyCache is the cache to fetch keys through when JWKS is nil.
	KeyCache *AccessTokenKeyCache
	// HTTPClient fetches discovery and keys. Defaults to a 30s-timeout
	// client.
	HTTPClient *http.Client
	// ClockSkew tolerated on exp, nbf and iat. The default (0) means 60
	// seconds; a negative value means none.
	ClockSkew time.Duration
}

JitTokenVerifyOptions configures VerifyJitToken.

type Keypair

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

Keypair is a freshly generated AAuth signing key.

func GenerateKeypair

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 MCPTransport added in v1.8.0

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

MCPTransport is an http.RoundTripper that adds the agent's MCP token to each request for one MCP server:

  • the token comes from Agent.Mcp (a token exchange for the resource, RFC 8707), is kept, and is renewed before it expires;
  • a DPoP-bound token (AgentConfig.DPoP) goes with the DPoP scheme and a new proof for each request, and a 401 use_dpop_nonce answer is sent again once with the server's nonce;
  • a 401 whose WWW-Authenticate names resource_metadata makes the transport read that document once: it learns the resource (when Resource is empty), checks that the resource is on the server's own origin and that the server trusts the agent's organization, and sends the request again once with a new token.

A request whose body cannot be read again (no GetBody) is not sent again; its 401 is returned. The transport never logs a token. It is safe for concurrent use.

func NewMCPTransport added in v1.8.0

func NewMCPTransport(agent *Agent, opts MCPTransportOptions) (*MCPTransport, error)

NewMCPTransport builds the transport for one MCP server. The agent's credentials authenticate the token requests; the agent's DPoP signer (AgentConfig.DPoP), when set, binds the MCP tokens.

func (*MCPTransport) Client added in v1.8.0

func (t *MCPTransport) Client() *http.Client

Client returns an *http.Client that sends through this transport, for StreamableClientTransport.HTTPClient.

func (*MCPTransport) Resource added in v1.8.0

func (t *MCPTransport) Resource() string

Resource returns the resource URI that the transport gets tokens for: the configured one, the one learned from the server, or "".

func (*MCPTransport) RoundTrip added in v1.8.0

func (t *MCPTransport) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip implements http.RoundTripper.

type MCPTransportOptions added in v1.8.0

type MCPTransportOptions struct {
	// Resource is the resource URI that the MCP server is registered with in
	// LumoAuth, e.g. "https://mcp.example.com/mcp". The agent gets tokens for
	// it, and the transport adds them only to requests for that origin and
	// path (or a path below it). Empty means: learn it from the server's
	// first 401 answer, through the protected resource metadata that its
	// WWW-Authenticate header names (RFC 9728).
	Resource string
	// Base sends the requests. Defaults to http.DefaultTransport.
	Base http.RoundTripper
	// RenewBefore renews a token this long before it expires. Default 60s.
	RenewBefore time.Duration
}

MCPTransportOptions configures NewMCPTransport.

type McpResource

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

McpResource covers secured MCP servers. Token exchanges the caller's token for one bound to a single MCP server (RFC 8693 token exchange). AuthorizeTool lets an MCP server ask whether a caller may run one tool.

func (*McpResource) AuthorizeTool added in v1.2.0

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

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

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

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

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

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

func (*McpResource) Token

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 WithClientCredentials added in v1.7.0

func WithClientCredentials(clientID, clientSecret string) Option

WithClientCredentials sets the client ID and the client secret of a confidential application of the organization. Only client.Poppy uses them: its calls authenticate with HTTP Basic, and they never send the client's bearer token or API key. The application's allowed scopes must include poppy:verify.

A client with these credentials and no other credential can call client.Poppy only.

func WithCustomDomain added in v1.7.0

func WithCustomDomain(domain string) Option

WithCustomDomain addresses the organization on its own domain, for example "auth.acme.com" or "https://auth.acme.com". Defaults to $LUMOAUTH_CUSTOM_DOMAIN.

With a custom domain the client sends every request to that domain, and no path carries the /orgs/{orgId} segment. The organization ID is not needed, and the issuer is the bare domain. A custom domain wins over WithBaseURL and $LUMOAUTH_URL: the base URL is then not used at all.

The value is a host name or an https:// origin. http:// is accepted only for localhost, 127.0.0.1 and [::1]. New returns a *ConfigError for a value with a path, a query, a fragment or credentials. An empty value means "not set".

Example

An organization on its own domain: no organization ID, and no path with an /orgs/ segment.

package main

import (
	"fmt"
	"log"

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

func main() {
	client, err := lumoauth.New(
		lumoauth.WithCustomDomain("auth.acme.com"),
		lumoauth.WithAPIKey("lmk_example"),
	)
	if err != nil {
		log.Fatal(err)
	}

	issuer, _ := client.Issuer()
	adminUsers, _ := client.OrgPath("/admin/users")
	fmt.Println(issuer)
	fmt.Println(client.BaseURL() + adminUsers)
}
Output:
https://auth.acme.com
https://auth.acme.com/api/v1/admin/users

func WithDPoP added in v1.2.0

func WithDPoP(signer *DPoPSigner) Option

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

func WithHTTPClient

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) on the platform host. Defaults to $LUMOAUTH_ORG_ID. A client with a custom domain does not need it.

func WithSkipCertValidation

func WithSkipCertValidation() Option

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

func WithTimeout

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.

func WithoutCredential added in v1.8.0

func WithoutCredential() Option

WithoutCredential lets New build a client that holds no credential. Such a client builds addresses (Auth.AuthorizationURL, Auth.EndSessionURL, Issuer, OrgPath) and makes the calls that authenticate themselves: the token endpoint calls of client.Auth (code exchange, refresh, client credentials with a secret or an assertion, token exchange with client authentication), Auth.Revoke, Auth.UserInfo with a token, and Agents.Attest. A call that needs a credential is sent without one, and the server's 401 is an error that matches ErrAuthentication.

A credential given with another option or LUMOAUTH_API_KEY is still used. Without this option, New refuses to build a client with no credential, so that a missing API key is found at start-up.

type Permission

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

Permission is one permission granted to a principal.

type PermissionBulkCheck

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

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

type PermissionCheck

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

PermissionCheck is the result of a single permission check.

type PermissionList

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

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

type PermissionMultiCheck

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

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

type PermissionsResource

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

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

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

func (*PermissionsResource) Check

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

Check reports whether the principal holds a permission.

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

func (*PermissionsResource) CheckAll

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

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

func (*PermissionsResource) CheckAllDetailed

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

CheckAllDetailed is CheckAll with the full response.

func (*PermissionsResource) CheckAny

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

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

func (*PermissionsResource) CheckAnyDetailed

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

CheckAnyDetailed is CheckAny with the full response.

func (*PermissionsResource) CheckBulk

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

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

func (*PermissionsResource) CheckDetailed

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

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

func (*PermissionsResource) List

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 PollOptions added in v1.8.0

type PollOptions struct {
	// ClientAuth authenticates the application at the token endpoint, as
	// when it started the request. A public client (device flow only) sets
	// ClientID alone. Use AssertionSigner rather than ClientAssertion: each
	// poll needs a new assertion.
	ClientAuth ClientAuth
	// Interval is the wait before each poll. Defaults to
	// DefaultPollInterval. Each slow_down answer adds 5 seconds.
	Interval time.Duration
	// ExpiresIn bounds the polling: after it, the poll ends with an error
	// that matches ErrApprovalTimeout. Use the expires_in of the start
	// answer. 0 means until the server answers expired_token or ctx ends.
	ExpiresIn time.Duration
}

PollOptions configures PollDeviceToken and PollBackchannelToken.

type PoppyAccount added in v1.7.0

type PoppyAccount struct {
	// Subject is the id of the user in your LumoAuth organization. Use it
	// to find the account's data.
	Subject string `json:"sub"`
	// Scope is the space-separated scope string of the access token; see
	// Scopes and HasScope.
	Scope string `json:"scope"`
	// Audience lists the services that the access token is for.
	Audience []string `json:"aud"`
	// Expires is the expiry of the access token in Unix seconds, or 0 when
	// LumoAuth sent none.
	Expires int64 `json:"exp"`
	// TokenType is "DPoP" for a token bound to a DPoP key, "Bearer"
	// otherwise.
	TokenType string `json:"token_type,omitempty"`
}

PoppyAccount describes the access token of a signed-in request.

func (*PoppyAccount) HasScope added in v1.7.0

func (a *PoppyAccount) HasScope(scope string) bool

HasScope reports whether the access token carries the scope.

func (*PoppyAccount) Scopes added in v1.7.0

func (a *PoppyAccount) Scopes() []string

Scopes returns the access token's scopes as a slice.

type PoppyMiddlewareOptions added in v1.7.0

type PoppyMiddlewareOptions struct {
	// PublicOrigin is the address that personal agents call, for example
	// "https://shop.example.com". It may carry a base path. Take it from
	// your configuration. Required.
	PublicOrigin string
	// RequiredScope lists the scopes that the routes behind this
	// middleware need. Leave it empty for routes that work signed out.
	RequiredScope []string
	// Resource is the resource identifier of your service, when it takes
	// only access tokens that were issued for it.
	Resource string
	// AllowReplay accepts a Session JWT that was verified before.
	AllowReplay bool
	// OnError is called when the verification call itself fails: the SDK
	// could not reach LumoAuth, or LumoAuth refused your application's call
	// (for example 404 not_found while the organization has the protocol
	// switched off: errors.Is(err, ErrNotFound)). It must answer the
	// request. Never write err to the response: it is about your service,
	// not about the personal agent. When OnError is nil, the middleware
	// answers 503 with the fixed body {"error":"temporarily_unavailable",…}.
	// The SDK does not log, so set OnError to record the error.
	OnError func(w http.ResponseWriter, r *http.Request, err error)
}

PoppyMiddlewareOptions configures PoppyResource.Middleware.

type PoppyRelayResponse added in v1.7.0

type PoppyRelayResponse struct {
	Status  int               `json:"status"`
	Headers map[string]string `json:"headers"`
	// Body is the JSON object to send, or nil when the response has no
	// body. Access token errors travel in WWW-Authenticate and have none.
	Body map[string]any `json:"body"`
}

PoppyRelayResponse is the HTTP response that a refused personal agent must get: the status, the headers and the body, exactly as LumoAuth worded them.

type PoppyRequest added in v1.7.0

type PoppyRequest struct {
	// Method is the method of the request. Required.
	Method string
	// URL is the public address that the personal agent called, for example
	// "https://shop.example.com/api/orders". Build it from your configured
	// public origin and the request path, never from the Host header. The
	// query and the fragment are dropped. Required.
	URL string
	// Headers are the headers of the request. You can pass all of them:
	// only Poppy-Session, Poppy-Version, Poppy-Extensions, Authorization
	// and DPoP are sent.
	Headers http.Header
}

PoppyRequest is a request that a personal agent sent to your API.

type PoppyResource added in v1.7.0

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

PoppyResource verifies requests from personal agents, and looks up and ends their Sessions.

Its three calls authenticate as one of your organization's confidential applications, with HTTP Basic: the client ID and the client secret of WithClientCredentials. The application's allowed scopes must include poppy:verify. The calls never send the client's bearer token or API key.

client, err := lumoauth.New(
    lumoauth.WithOrgID("acme-corp"),
    lumoauth.WithClientCredentials(clientID, clientSecret),
)

On a net/http server, Middleware does the whole job for a route.

func (*PoppyResource) EndSession added in v1.7.0

func (r *PoppyResource) EndSession(ctx context.Context, personalAgent, sid string) (bool, error)

EndSession ends a Session. Later requests with its sid are refused with session_ended, and the personal agent starts a new Session. The user stays signed in.

It returns false when the Session had ended before. An unknown Session is an error that matches ErrNotFound.

func (*PoppyResource) GetSessionStatus added in v1.7.0

func (r *PoppyResource) GetSessionStatus(ctx context.Context, personalAgent, sid string) (*PoppySessionStatus, error)

GetSessionStatus says whether a Session still stands and whether its account is still signed in to the personal agent. It needs no request from the personal agent. personalAgent is the ClientID of a verified result, and sid is its Session.SID.

An unknown Session is not an error: Status is PoppyStatusUnknown.

func (*PoppyResource) Middleware added in v1.7.0

func (r *PoppyResource) Middleware(opts PoppyMiddlewareOptions) (func(http.Handler) http.Handler, error)

Middleware returns net/http middleware that verifies each request with LumoAuth before the handler runs.

verified, err := client.Poppy.Middleware(lumoauth.PoppyMiddlewareOptions{
    PublicOrigin:  "https://shop.example.com",
    RequiredScope: []string{"orders:read"},
})
if err != nil {
    log.Fatal(err)
}
mux.Handle("GET /api/orders", verified(ordersHandler))

// in ordersHandler:
who, _ := lumoauth.PoppyFromContext(r.Context())

For each request the middleware does one of three things:

  • Verified: it stores the *PoppyVerification in the request context and calls the handler.
  • Refused: it answers with LumoAuth's response, unchanged, and does not call the handler.
  • The call failed: it does not call the handler and relays nothing. It calls OnError, or answers 503 Service Unavailable with a fixed body. The error text never reaches the personal agent.

The URL that LumoAuth checks is PublicOrigin followed by the path of r.RequestURI. The Host and X-Forwarded-* headers are never used. Because r.RequestURI is the request line as the client sent it, a router prefix or http.StripPrefix in front of the middleware does not shorten the path. The middleware does not read the request body.

A Session JWT is good for one verification, so put the middleware on a route once.

Middleware returns a *ConfigError when PublicOrigin is missing or is not a valid address, when the client has no client credentials (WithClientCredentials) or when it has neither an organization ID nor a custom domain.

Example

An API that personal agents call: the middleware asks LumoAuth to verify each request before the handler runs.

package main

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

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

func main() {
	client, err := lumoauth.New(
		lumoauth.WithOrgID("acme-corp"),
		// A confidential application whose allowed scopes include poppy:verify.
		lumoauth.WithClientCredentials(os.Getenv("SHOP_API_CLIENT_ID"), os.Getenv("SHOP_API_CLIENT_SECRET")),
	)
	if err != nil {
		log.Fatal(err)
	}

	verified, err := client.Poppy.Middleware(lumoauth.PoppyMiddlewareOptions{
		PublicOrigin:  os.Getenv("PUBLIC_ORIGIN"), // for example https://shop.example.com
		RequiredScope: []string{"orders:read"},
		OnError: func(w http.ResponseWriter, r *http.Request, err error) {
			// The error is about this service. Log it, and never send it.
			log.Printf("Session verification failed: %v", err)
			http.Error(w, "not available now", http.StatusServiceUnavailable)
		},
	})
	if err != nil {
		log.Fatal(err)
	}

	orders := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		who, _ := lumoauth.PoppyFromContext(r.Context())
		fmt.Fprintf(w, "orders of account %s, asked by %s", who.Account.Subject, who.ClientID)
	})

	mux := http.NewServeMux()
	mux.Handle("GET /api/orders", verified(orders))

	log.Fatal(http.ListenAndServe(":8787", mux))
}

func (*PoppyResource) VerifyHTTPRequest added in v1.7.0

func (r *PoppyResource) VerifyHTTPRequest(ctx context.Context, publicOrigin string, req *http.Request, opts *PoppyVerifyOptions) (*PoppyVerification, error)

VerifyHTTPRequest is VerifyRequest for a *http.Request. It builds the URL from publicOrigin and the request target as the client sent it (see BuildPoppyVerifyBody), and it does not read the request body.

verification, err := client.Poppy.VerifyHTTPRequest(ctx, "https://shop.example.com", r, nil)

Take publicOrigin from your configuration.

Example

Without the middleware: verify a request in a handler and relay a refusal.

package main

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

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

func main() {
	client, err := lumoauth.New(
		lumoauth.WithOrgID("acme-corp"),
		lumoauth.WithClientCredentials(os.Getenv("SHOP_API_CLIENT_ID"), os.Getenv("SHOP_API_CLIENT_SECRET")),
	)
	if err != nil {
		log.Fatal(err)
	}
	publicOrigin := os.Getenv("PUBLIC_ORIGIN")

	http.HandleFunc("POST /api/orders/{id}/return", func(w http.ResponseWriter, r *http.Request) {
		verification, err := client.Poppy.VerifyHTTPRequest(r.Context(), publicOrigin, r,
			&lumoauth.PoppyVerifyOptions{RequiredScope: []string{"orders:write"}})
		if err != nil {
			log.Printf("Session verification failed: %v", err)
			http.Error(w, "not available now", http.StatusServiceUnavailable)
			return
		}
		if !verification.Active {
			_ = lumoauth.WritePoppyRefusal(w, verification)
			return
		}
		fmt.Fprintf(w, "order %s returned for account %s", r.PathValue("id"), verification.Account.Subject)
	})
}

func (*PoppyResource) VerifyRequest added in v1.7.0

func (r *PoppyResource) VerifyRequest(ctx context.Context, request PoppyRequest, opts *PoppyVerifyOptions) (*PoppyVerification, error)

VerifyRequest asks LumoAuth who a request from a personal agent is from.

verification, err := client.Poppy.VerifyRequest(ctx, lumoauth.PoppyRequest{
    Method:  r.Method,
    URL:     "https://shop.example.com" + r.URL.EscapedPath(),
    Headers: r.Header,
}, &lumoauth.PoppyVerifyOptions{RequiredScope: []string{"orders:read"}})
if err != nil {
    http.Error(w, "internal error", http.StatusInternalServerError)
    return
}
if !verification.Active {
    lumoauth.WritePoppyRefusal(w, verification)
    return
}

A refusal is not an error. It comes back with Active set to false and the response to send in Response. An error means that the call itself failed: the SDK could not reach LumoAuth, or LumoAuth rejected your application (401, 403, 404 or 429). Never send such an error to the personal agent. An answer that is neither a verified result nor a well-formed refusal is an error too.

opts may be nil.

type PoppySession added in v1.7.0

type PoppySession struct {
	// ID is LumoAuth's id of the Session. Store your own Session state
	// under it, such as a cart.
	ID int64 `json:"id"`
	// SID is the Session ID that the personal agent chose. GetSessionStatus
	// and EndSession take it.
	SID string `json:"sid"`
	// IsNew is true when this request started the Session.
	IsNew bool `json:"new"`
	// StartedAt is the start of the Session, as an RFC 3339 time.
	StartedAt string `json:"started_at,omitempty"`
}

PoppySession is the Session of a verified request.

type PoppySessionStatus added in v1.7.0

type PoppySessionStatus struct {
	// Status is PoppyStatusActive, PoppyStatusEnded or PoppyStatusUnknown.
	Status string `json:"status"`
	// UserID is the personal agent's name for its user. Empty for an
	// unknown Session.
	UserID string `json:"user_id,omitempty"`
	// AgentID is set when the personal agent named one of several agents.
	AgentID string `json:"agent_id,omitempty"`
	// Account is the id of the account that the Session used, or "".
	Account string `json:"account,omitempty"`
	// SignedIn is true while the Session is active, it used an account,
	// and the personal agent still holds a valid refresh token for it.
	SignedIn bool `json:"signed_in"`
	// LastSeenAt is the time of the Session's last request, as an RFC 3339
	// time. Empty for an unknown Session.
	LastSeenAt string `json:"last_seen_at,omitempty"`

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

PoppySessionStatus is the answer to PoppyResource.GetSessionStatus.

func (*PoppySessionStatus) Active added in v1.7.0

func (s *PoppySessionStatus) Active() bool

Active reports whether the Session still stands.

func (*PoppySessionStatus) UnmarshalJSON added in v1.7.0

func (s *PoppySessionStatus) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes a Session status and refuses an answer without a status or with a member of the wrong type.

type PoppyVerification added in v1.7.0

type PoppyVerification struct {
	// Active is true when LumoAuth verified the request.
	Active bool `json:"active"`

	// ClientID is the personal agent: the URL of its metadata document.
	// LumoAuth checked this value.
	ClientID string `json:"client_id,omitempty"`
	// ClientName is the name that the personal agent gives itself.
	ClientName string `json:"client_name,omitempty"`
	// UserID is the personal agent's stable name for its user at your
	// organization. It is not an account: never look an account up by it.
	UserID string `json:"user_id,omitempty"`
	// AgentID is set when the personal agent runs several agents for one
	// user and says which one this is. Empty otherwise.
	AgentID string `json:"agent_id,omitempty"`
	// Session is the Session of the request. Nil in a refusal.
	Session *PoppySession `json:"session,omitempty"`
	// SignedIn is true when the request carried a valid access token.
	SignedIn bool `json:"signed_in"`
	// Account says whose access token the request carried. Nil when the
	// request is signed out.
	Account *PoppyAccount `json:"account,omitempty"`
	// Version is the Poppy-Version of the request.
	Version string `json:"version,omitempty"`
	// Extensions are the extensions that the request declares, as name and
	// version.
	Extensions map[string]string `json:"extensions,omitempty"`

	// Error is the protocol's error code of a refusal, such as
	// "invalid_session" or "insufficient_scope".
	Error string `json:"error,omitempty"`
	// ErrorDescription explains a refusal.
	ErrorDescription string `json:"error_description,omitempty"`
	// Scope holds the scopes that a refusal asks for, space-separated.
	// Empty when the refusal names none.
	Scope string `json:"scope,omitempty"`
	// Response is the HTTP response that the personal agent must get. Nil
	// in a verified result.
	Response *PoppyRelayResponse `json:"response,omitempty"`

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

PoppyVerification is the answer to PoppyResource.VerifyRequest: who a request from a personal agent is from, or the refusal to send back.

Active tells the two apart. A verified result (Active true) carries ClientID, UserID, Session and, for a signed-in request, Account. A refusal (Active false) carries Error and Response; send Response to the personal agent unchanged with WritePoppyRefusal.

func PoppyFromContext added in v1.7.0

func PoppyFromContext(ctx context.Context) (*PoppyVerification, bool)

PoppyFromContext returns the verified result that PoppyResource.Middleware stored for the request.

func (*PoppyVerification) UnmarshalJSON added in v1.7.0

func (v *PoppyVerification) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes a verification answer and fails closed: an answer that is neither a complete verified result nor a well-formed refusal is an error, and is never decoded as verified.

type PoppyVerifyOptions added in v1.7.0

type PoppyVerifyOptions struct {
	// RequiredScope lists the scopes that the operation needs. An entry may
	// also hold several scopes separated by spaces. Leave it empty for an
	// operation that works signed out.
	RequiredScope []string
	// Resource is the resource identifier of your service. Set it when the
	// service takes only access tokens that were issued for it, as an MCP
	// server does.
	Resource string
	// AllowReplay accepts a Session JWT that was verified before. Use it
	// only when one request is verified in several places.
	AllowReplay bool
}

PoppyVerifyOptions are the checks that one operation asks for.

type PushedAuthorizationResponse added in v1.8.0

type PushedAuthorizationResponse struct {
	// RequestURI goes into the authorization URL (AuthorizationURL with
	// ClientID and RequestURI). It works once.
	RequestURI string `json:"request_uri"`
	// ExpiresIn is its lifetime in seconds.
	ExpiresIn int `json:"expires_in"`
}

PushedAuthorizationResponse is the answer of the PAR endpoint.

type RecordedUsage added in v1.4.0

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

RecordedUsage is the usage that LumoAuth added to the agent's budget windows.

type RefreshParams

type RefreshParams struct {
	// RefreshToken is the token from a prior response. Required.
	RefreshToken string
	// ResourceToken must be a resource token from the resource that the
	// refresh token was granted for — the server requires one on every
	// refresh. Its `scope` claim may narrow the granted scopes. Required.
	ResourceToken string
	// Scope is an optional space-delimited scope. It narrows only: every
	// scope must be in the original grant (and in the resource token's
	// scope, when it has one). A scope outside the grant is refused with
	// 400 invalid_scope.
	Scope string
	// AgentToken is the `agent+jwt` presented in Agent-Auth. Required.
	AgentToken string
}

RefreshParams describes an auth-token refresh.

type RefreshTokenParams

type RefreshTokenParams struct {
	// RefreshToken is the token to redeem. Required.
	RefreshToken string
	// ClientID is the OAuth client. Required.
	ClientID string
	// ClientSecret is required for confidential clients.
	ClientSecret string
	// Scopes optionally narrows the refreshed token; must be a subset of
	// the original grant.
	Scopes []string
	// ClientAuth, when set, authenticates the client instead of ClientID and
	// ClientSecret (leave those empty); see ExchangeCodeParams.ClientAuth.
	ClientAuth *ClientAuth
	// AuthorizationDetails asks for a part of the granted fine-grained
	// permissions; see ExchangeCodeParams.AuthorizationDetails.
	AuthorizationDetails []map[string]any
}

RefreshTokenParams describes a refresh-token grant.

type RegisterClientOptions added in v1.8.0

type RegisterClientOptions struct {
	// InitialAccessToken is the token that your organization issued for
	// registrations. It is sent as the only credential. Without it, the
	// client's API key is sent when it has one (the key needs the scope
	// admin:clients:register), and nothing otherwise, for an organization
	// that allows open registration.
	InitialAccessToken string
}

RegisterClientOptions configures RegisterClient.

type RegisterParams

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

RegisterParams describes an agent registration.

type RegisteredClient added in v1.8.0

type RegisteredClient struct {
	ClientMetadata
	ClientID string `json:"client_id"`
	// ClientSecret is set for a confidential client at registration only.
	// Store it at once: it is not shown again.
	ClientSecret          string `json:"client_secret,omitempty"`
	ClientSecretExpiresAt int64  `json:"client_secret_expires_at,omitempty"`
	ClientIDIssuedAt      int64  `json:"client_id_issued_at,omitempty"`
	// RegistrationAccessToken reads the configuration later
	// (GetClientConfiguration). Set at registration only; keep it secret.
	RegistrationAccessToken string `json:"registration_access_token,omitempty"`
	RegistrationClientURI   string `json:"registration_client_uri,omitempty"`

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

RegisteredClient is the answer of a registration or of a read of the client configuration.

func (*RegisteredClient) String added in v1.8.0

func (c *RegisteredClient) String() string

String never shows the client secret or the registration access token.

func (*RegisteredClient) UnmarshalJSON added in v1.8.0

func (c *RegisteredClient) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes the typed members and keeps every member in Raw.

type ReplayCache added in v1.2.0

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 RequestObjectOptions added in v1.8.0

type RequestObjectOptions struct {
	// Signer holds the application's private key; its algorithm (RS256–RS512,
	// PS256–PS512 or ES256–ES512) and key ID become the object's alg and
	// kid. Register the public key (Signer.JWKS) on the application.
	// Required.
	Signer *ClientAssertionSigner
	// Lifetime is the time until exp: 1 second to 10 minutes. Default 5
	// minutes.
	Lifetime time.Duration
}

RequestObjectOptions configures CreateRequestObject.

type RequestPermissionOptions

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

RequestPermissionOptions tunes a JIT permission request.

type RequestPermissionParams

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

RequestPermissionParams describes an RFC 9396 permission request.

type RevokeParams

type RevokeParams struct {
	// Token is the access or refresh token to revoke. Required.
	Token string
	// TokenTypeHint is "access_token" or "refresh_token".
	TokenTypeHint string
	// ClientID and ClientSecret authenticate the revocation.
	ClientID     string
	ClientSecret string
	// ClientAuth, when set, authenticates the client instead of ClientID and
	// ClientSecret (leave those empty); see ExchangeCodeParams.ClientAuth.
	ClientAuth *ClientAuth
}

RevokeParams describes a token revocation.

type 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"`
	// AuthorizationDetails are the fine-grained permissions (RFC 9396) that
	// LumoAuth granted at sign-in (WebConfig.AuthorizationDetails).
	AuthorizationDetails []map[string]any `json:"authorization_details,omitempty"`
}

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

func TokensFromContext

func TokensFromContext(ctx context.Context) *SessionTokens

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

func (*SessionTokens) Expired

func (t *SessionTokens) Expired() bool

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

type SignOptions

type SignOptions struct {
	// Body is the exact request body being signed. Empty means no body.
	Body []byte
	// ContentType is the media type of the body.
	// Defaults to "application/json".
	ContentType string
	// AgentToken is the `agent+jwt` presented in the Agent-Auth header. It
	// travels outside the signature.
	AgentToken string
	// Authorization is the value of a covered Authorization header, when
	// the request carries one (proof-of-possession requests do).
	Authorization string
	// SignatureKey is the value of a covered Signature-Key header. It is
	// also sent as that header. Its label must be "sig1", the label of
	// Signature-Input and Signature. POST /aauth/agent/issue requires
	// `sig1=jwks_uri;id="<agent identifier>";kid="<kid>"`; the agent token
	// endpoint and /aauth/token/revoke need no Signature-Key.
	SignatureKey string
	// Created overrides the signature timestamp. Testing only — the server
	// rejects timestamps more than 60s from its own clock.
	Created int64
	// Nonce overrides the generated nonce. Testing only — the server
	// treats nonces as single-use.
	Nonce string
}

SignOptions configures SignRequest.

type TokenConfirmation added in v1.2.0

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

TokenConfirmation is the `cnf` claim.

type TokenExchangeParams

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

	// ClientID, with ClientSecret or ClientAssertion, authenticates your
	// application at the token endpoint: the exchange of a confidential
	// application (token exchange switched on for it). Leave all three empty
	// for the agent on-behalf-of exchange, where the actor token
	// authenticates the agent.
	ClientID string
	// ClientSecret is the application's secret.
	ClientSecret string
	// ClientAuthMethod is how ClientSecret is sent: ClientSecretBasic (the
	// default, an Authorization header) or ClientSecretPost (form fields).
	ClientAuthMethod string
	// ClientAssertion is a private_key_jwt client assertion (RFC 7523),
	// built with ClientAssertionSigner.Assertion, instead of a secret.
	ClientAssertion string
}

TokenExchangeParams describes an RFC 8693 token exchange.

type TokenIntrospection added in v1.8.0

type TokenIntrospection struct {
	Active bool `json:"active"`
	// TokenType is "Bearer" (or "DPoP") for access tokens, "refresh_token"
	// for refresh tokens.
	TokenType string `json:"token_type,omitempty"`
	// Scope is the space-separated scope string; see Scopes.
	Scope    string `json:"scope,omitempty"`
	ClientID string `json:"client_id,omitempty"`
	// Subject is the user ID, or client_… / agent_… for other subjects.
	Subject string `json:"sub,omitempty"`
	// Username is the user's e-mail address (tokens of a user only).
	Username  string        `json:"username,omitempty"`
	Expires   int64         `json:"exp,omitempty"`
	IssuedAt  int64         `json:"iat,omitempty"`
	NotBefore int64         `json:"nbf,omitempty"`
	Issuer    string        `json:"iss,omitempty"`
	Audience  AudienceClaim `json:"aud,omitempty"`
	JTI       string        `json:"jti,omitempty"`
	// Act is the actor of a delegated token, earlier actors nested in it.
	Act *ActorClaim `json:"act,omitempty"`
	// Confirmation is the key binding of a DPoP-bound token (cnf.jkt).
	Confirmation *TokenConfirmation `json:"cnf,omitempty"`
	// AuthorizationDetails are the token's fine-grained permissions
	// (RFC 9396), when it has some.
	AuthorizationDetails []map[string]any `json:"authorization_details,omitempty"`

	// Raw is the complete answer, including members not modelled above.
	Raw map[string]any `json:"-"`
}

TokenIntrospection is the introspection answer (RFC 7662 §2.2). An inactive, expired, revoked or unknown token is only Active false. For an active token the other members are set when LumoAuth knows them.

func (*TokenIntrospection) Scopes added in v1.8.0

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

Scopes splits the scope string.

func (*TokenIntrospection) UnmarshalJSON added in v1.8.0

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

UnmarshalJSON decodes the typed members and keeps every member in Raw.

type TokenProvider

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"`
	// AuthorizationDetails are the fine-grained permissions (RFC 9396) that
	// LumoAuth granted, when the request asked for some. Members that the
	// SDK does not model are kept.
	AuthorizationDetails []map[string]any `json:"authorization_details,omitempty"`
}

TokenResponse is an OAuth 2.1 token endpoint response.

func (*TokenResponse) Scopes

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

Scopes splits the space-separated Scope field.

type TokenSource

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

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

A source that addresses its organization on a custom domain also has the method CustomDomain() string, as *Agent does. JITContext then sends its requests to that domain without the /orgs/{orgId} segment. Without that method the paths are in the platform form, which a custom domain answers with 404.

type UsageReportResult added in v1.4.0

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

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

type User

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

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

func UserFromContext

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 unless
	// CustomDomain is set.
	Issuer string
	// CustomDomain is the organization's custom domain, for example
	// "auth.acme.com". When it is set, the key set is fetched from
	// {domain}/api/v1/aauth/jwks.json. The value follows the rules of
	// WithCustomDomain. The environment is not read.
	//
	// The trusted issuer is NOT the bare domain: LumoAuth names the AAuth
	// issuer with the platform address on every host. With CustomDomain
	// and an empty Issuer, VerifyAuthToken reads the issuer from the
	// issuer metadata document of the custom domain
	// ({domain}/api/v1/.well-known/aauth-issuer) and keeps it for an hour.
	// A non-empty Issuer is used as it is, and no document is read.
	CustomDomain string
	// Resource is your resource identifier; it must equal the token's
	// audience. Required.
	Resource string
	// JWKS supplies the issuer's keys directly, skipping the fetch. Use
	// it with a cache in front of a hot path.
	JWKS *JWKS
	// HTTPClient fetches the JWKS. Defaults to a 30s-timeout client.
	HTTPClient *http.Client
	// ClockSkew tolerated on the expiry check. Default: 0, like the server.
	ClockSkew time.Duration
}

VerifyOptions configures VerifyAuthToken.

type WaitOptions

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

WaitOptions tunes approval polling.

type WebAuth

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

WebAuth drives the browser sign-in flow.

func NewWebAuth

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. Its Poppy namespace authenticates with the ClientID and ClientSecret of this WebConfig.

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 ends the session: it revokes the refresh token, clears the local session and, unless LocalLogout is set, sends the browser to LumoAuth's end-session endpoint, which returns it to PostLogoutRedirect.

Another site cannot sign the user out: a GET signs out at once only when the browser's Sec-Fetch-Site is same-origin or none (a link of this app, a typed address); otherwise it answers with a page that asks first and posts to the same route. A POST signs out when its Origin is this app's origin (or one of LogoutAllowedOrigins), or, without an Origin, when Sec-Fetch-Site is same-origin; anything else gets 403.

func (*WebAuth) Middleware

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 slug of the organization that owns the OAuth
	// client. Defaults to $LUMOAUTH_ORG_ID. Required unless CustomDomain is
	// set.
	Organization string
	// CustomDomain addresses the organization on its own domain, for
	// example "auth.acme.com". Defaults to $LUMOAUTH_CUSTOM_DOMAIN. It wins
	// over BaseURL: the sign-in, token and UserInfo addresses are then on
	// that domain, without the /orgs/{orgId} segment. See WithCustomDomain.
	CustomDomain string
	// ClientID is the OAuth client registered for this app. Required.
	ClientID string
	// ClientSecret is required for confidential clients; omit for public
	// ones, which rely on PKCE alone.
	ClientSecret string
	// SessionSecret is the secret from which the default store derives the
	// keys that encrypt and sign the session cookie. Use at least 32 random
	// bytes, and keep it stable across restarts or every session is
	// invalidated. Required unless Store is set.
	SessionSecret string
	// CallbackPath is the absolute path LumoAuth redirects back to. It
	// must match a redirect URI registered on the OAuth client.
	// Defaults to "/auth/callback".
	CallbackPath string
	// Scope is the space-separated scope list.
	// Defaults to "openid profile email".
	Scope string
	// AuthorizationDetails asks for fine-grained permissions (RFC 9396) at
	// each sign-in; see AuthorizationURLParams.AuthorizationDetails. What
	// LumoAuth granted is in SessionTokens.AuthorizationDetails.
	AuthorizationDetails []map[string]any
	// PostLoginRedirect is where users land after signing in.
	// Defaults to "/".
	PostLoginRedirect string
	// PostLogoutRedirect is where users land after signing out. Defaults to
	// "/". The logout route also ends the LumoAuth session, so LumoAuth
	// sends the browser here: a path is made absolute with the request's
	// origin, and the absolute address must be registered on the client as
	// a post-logout redirect URI.
	PostLogoutRedirect string
	// LogoutAllowedOrigins lists other origins (for example
	// "https://portal.example.com") whose POST to the logout route signs the
	// user out too. Empty (the default) means this app's own origin only. A
	// GET from another site always gets the confirmation page first.
	LogoutAllowedOrigins []string
	// LocalLogout makes the logout route end only this app's session: the
	// user stays signed in at LumoAuth, and the next sign-in needs no
	// password. False (the default) also ends the LumoAuth session through
	// the end-session endpoint (RP-initiated logout).
	LocalLogout bool
	// HTTPClient overrides the client used for token exchange and
	// UserInfo. Defaults to a 10s-timeout client.
	HTTPClient *http.Client
	// CookieName is the session cookie's name. Defaults to "lumo_session".
	CookieName string
	// CookieSecure controls the Secure flag. Nil means true — the cookie
	// is only sent over HTTPS. Set Bool(false) for local development over
	// plain HTTP, and leave it alone in production.
	CookieSecure *bool
	// SessionMaxAge bounds the session cookie's lifetime.
	// Defaults to 30 days.
	SessionMaxAge time.Duration
	// SkipCertValidation disables TLS verification. Local development only.
	SkipCertValidation bool
	// ClientAuth authenticates the app with a key instead of ClientSecret
	// (leave ClientSecret empty): AssertionSigner for private_key_jwt, which
	// signs a new client assertion for each request, or Attestation. The
	// pushed request, the code exchange, the refresh and the revocation at
	// logout use it. ClientAuth.ClientID may stay empty (it is ClientID).
	// ClientAssertion is refused: one assertion works once.
	ClientAuth *ClientAuth
	// RequestObjectSigner signs each sign-in request as a request object
	// (JAR, RFC 9101): with UsePAR it is pushed, otherwise it goes in the
	// redirect as the request parameter. Register its public key on the
	// application; it may be the key of ClientAuth.AssertionSigner. FAPI 2
	// Message Signing needs it.
	RequestObjectSigner *ClientAssertionSigner
	// DPoP binds the user's tokens to this key (RFC 9449): the pushed
	// request, the code exchange and the refresh carry a proof, and the
	// tokens are presented with the DPoP scheme (UserInfo, ClientForRequest).
	// Every instance of the app must load the same key (LoadDPoPSigner), or
	// a session's tokens stop working after a restart.
	DPoP *DPoPSigner
	// UsePAR pushes each sign-in request to LumoAuth first (pushed
	// authorization requests, RFC 9126) and sends the browser to LumoAuth
	// with only client_id and request_uri. The parameters then never pass
	// through the browser. Applications with "Require PAR" or a FAPI
	// profile need it. False (the default) puts the parameters in the
	// redirect.
	UsePAR bool
	// ResponseMode asks LumoAuth to sign its answer (JARM): "jwt" or
	// "query.jwt". The callback then reads the `response` parameter,
	// verifies its signature, issuer, audience and expiry, and refuses an
	// unsigned answer. "" (the default) is the plain query answer.
	// form_post.jwt and fragment.jwt are refused: the session cookie
	// (SameSite=Lax) does not come with a cross-site POST, and a fragment
	// never reaches the server.
	ResponseMode string
	// Store replaces the session store, for example with a server-side
	// store (gorilla's FilesystemStore, a Redis store) that keeps only an
	// ID in the cookie. The session is named CookieName. With a Store,
	// SessionSecret, CookieSecure and SessionMaxAge are not used: the store
	// has its own keys and cookie options. Nil means the default store: an
	// encrypted, signed cookie that is split over several cookies when the
	// session does not fit in one.
	Store sessions.Store
}

WebConfig configures NewWebAuth.

type WorkloadIdentity added in v1.8.0

type WorkloadIdentity struct {
	// Provider names the platform, for example "github" or "k8s".
	Provider string `json:"provider"`
	// Subject is the token's subject, for example
	// "repo:acme/app:ref:refs/heads/main".
	Subject string `json:"subject"`
	// Issuer is the token's issuer.
	Issuer string `json:"issuer"`
	// AudienceGeneric is true when the agent's registered audience is not
	// specific to LumoAuth (for example sts.amazonaws.com), so any token
	// that the provider mints for it satisfies the agent. Move the binding
	// to the agent-specific audience that the portal shows.
	AudienceGeneric bool `json:"audience_generic"`
}

WorkloadIdentity is the verified identity of an attested workload.

type ZanzibarCheck

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

ZanzibarCheck is the result of a relationship check.

type ZanzibarResource

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

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

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

func (*ZanzibarResource) Check

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

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

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

Relationship-based checks read as questions about a tuple.

package main

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

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

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

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

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