The in-process go-authbyte auth client library for eIDAS signing services. Compiled into
every backend service — and into the auth authority itself, to guard its own
endpoints.
Module: github.com/gmb-lib/go-authbyte. Companion to the
authbyte-core authority.
It does three jobs. The first two are on the hot path with no per-request call home (JWKS and service tokens are cached); the third runs only at login:
- Inbound — Azugo middleware that validates the access/service token
(signature via cached JWKS,
iss,aud,exp/nbf), verifies the DPoP proof (signature,cnf.jktmatch,htm/htu,ath, jti replay, server nonce), and populatesctx.User(). - Outbound — acquires this service's own DPoP-bound service token via
client-credentials (cached per audience, early-refreshed) and attaches it
plus a fresh DPoP proof to service-to-service calls, handling the
DPoP-Noncechallenge transparently. It can also act on behalf of the logged-in user: it exchanges that user's token for a delegated one (RFC 8693 token exchange) so the callee owner-filters on the user subject exactly as it would for a direct user call. Delegated tokens are cached per(audience, scope, subject token)— keyed on a SHA-256 fingerprint of the user's token, so a new token (another organisation, a stronger sign-in) is always a new exchange — are never reused past that token's own expiry, and are bound to this service's own key. - Confidential browser login (
asclient) — for a back-end that logs a user in and holds their tokens: the authorization-code flow with PKCE, over a key generated per user session, so the browser never holds a token or a secret.
It also carries one piece of shared vocabulary: identitycode, the single
place a signatory's identity code is turned into the form it is stored, compared
and shown in. Every service that holds such a code has to agree on that form
exactly, or the same person arriving two ways becomes two people. It calls
nothing and needs no configuration.
go get github.com/gmb-lib/go-authbyteSee CHANGELOG.md for what each release changed, and what it means for code that
already uses this library, before you bump.
ac, err := authclient.New(cfg) // cfg bound from the service's Azugo Configuration
// ...
g := app.Group("/documents")
g.Use(ac.Authenticate()) // requires a valid DPoP-bound token
// or ac.TryAuthenticate() to allow anonymous through
func (r *router) get(ctx *azugo.Context) {
if !ctx.User().HasScopeLevel("documents", "read") {
ctx.Error(corehttp.ForbiddenError{}); return
}
// ctx.User().ID(), .ClaimValue("login_method"), ...
}When the gate refuses, the caller gets an undifferentiated 401 — it is never told which check
failed, because that would let it walk a bad token toward acceptance one guess at a time. The service
itself is told: each refusal logs refused a request at the auth gate at warn with a reason and
the underlying error, so an expired service token, a wrong audience and a replayed proof are
distinguishable in your own logs. A missing or stale DPoP nonce is not a refusal — it is answered
401 with a fresh DPoP-Nonce, which the outbound client below retries transparently.
Who brought the request. On a token minted on behalf of a person, the subject is the person and the
act claim names the service acting for them, nesting any service before it. The inbound gate copies that
chain into the user's claims (act, the service presenting the token first), and claims.ActingClient
names the client that presented it: the acting service on a delegated token, the service itself on its own
token, nobody on a person's own. A route that only certain clients may reach, whoever they act for, checks it:
if !slices.Contains(allowed, claims.ActingClient(ctx.User())) {
ctx.Error(corehttp.ForbiddenError{}); return
}// Acquire + attach automatically, with transparent nonce retry:
var doc DocumentDTO
err := ac.GetJSON(ctx, "svc:document", "documents:read",
"http://document:8080/documents/"+id, &doc)When a service composes a downstream call for the logged-in user (e.g. fetching that user's document), pass the user's subject and inbound token; the client mints a delegated token via token exchange and the callee sees the user as the subject:
// inboundToken is the user's raw access token (the request's Authorization
// bearer); ctx.User().ID() is its subject.
var doc DocumentDTO
err := ac.GetJSONOnBehalf(ctx, "svc:document", "documents:read",
ctx.User().ID(), inboundToken,
"http://document:8080/documents/"+id, &doc)PostJSONOnBehalf (request context) and DoServiceOnBehalf (background, no
request context) are the on-behalf-of counterparts of PostJSON and
DoService. The delegated token carries an act claim recording the
delegation chain; claims.Claims.Delegated() reports whether a received token
was minted on behalf of its subject.
These lanes keep a delegated token for its lifetime and hand it out again.
ExchangeDelegatedToken asks the authority every time and keeps nothing: for
a subject token the authority may stop exchanging while it is still within its
lifetime (an AI app's, once its connection is signed out), where a kept answer
would outlive that decision.
A token the caller minted itself — an authorization server asking a
service about the person it is signing in, with a token it signed for that one
call — goes through DoWithToken, with no token fetched. The token must be
bound to this client's key: stamp Thumbprint() into its cnf.jkt. The proof,
the nonce retry and the correlation id are the same as for every other call,
and the answer comes back as it was given, a refusal included.
tok := mintFor(person, "svc:rolebyte", "membership:resolve", ac.Thumbprint())
res, err := ac.DoWithToken(ctx, "svc:rolebyte", tok, http.MethodPost,
"http://rolebyte:8081/api/v1/sign-in/memberships", nil, nil)Outbound calls run under a 15s overall timeout by default. For operations that
legitimately outlast it — e.g. a long-term-archival document validation, where
the upstream work alone can take tens of seconds — use the per-call variants
DoServiceWithTimeout / DoServiceOnBehalfWithTimeout: the token acquisition
still runs under the default (it must be fast), and only the resource call runs
under the caller's ceiling.
When the auth service refuses, the answer is readable rather than only loggable. A refusal and an unreachable service are different events — one is a decision about your request, the other a failure to make it — and a caller that cannot tell them apart has to report the worse of the two:
_, err := ac.AcquireDelegatedToken(ctx, audience, scope, subject, subjectToken)
var refused *authclient.Error
if errors.As(err, &refused) && refused.Status < 500 {
// Answered and declined: refused.Body carries the sender's own words.
return relay(refused.Status, refused.Body)
}
// Anything else is a failure to reach the service at all.Error.Hop says which call answered: HopToken the ask to the token endpoint,
HopResource the call that carries the token on to the target service. One
helper call makes both, so the call site alone cannot tell them apart. The error
satisfies error, so existing handling is unaffected and reading the answer is
opt-in; its message states the status only, and the body stays in its field
because it is another service's wording and may describe the person the call was
made for.
The third job, for a back-end that logs a browser user in and holds the tokens
on their behalf (a BFF): it drives the authorization-code flow with PKCE, and every
server-side hop proves possession of a key that belongs to that one session, with
the DPoP-Nonce challenge retried transparently. The browser never receives a
token, a key or a secret — it holds only the calling service's own session cookie.
Its calls are traced out of the box (client spans + trace context propagation), so
a login reads as one trace across the caller and the authority. WithHTTPClient
overrides the client when a caller needs its own timeout or transport — and then
owns instrumenting it.
A back-end the authority registers as a confidential client passes its secret
with WithClientSecret: the client then proves itself at every call it makes as
itself — by HTTP Basic on the code exchange, a refresh and a revocation.
Without it the client is public and sends no secret, as before.
A sign-in that asks for an ID token proves itself to the back-end too. The
back-end names the authority's issuer with WithIssuer, exactly as its discovery
document states it, and keeps a nonce with each sign-in. On the browser's return it
checks the iss parameter before using anything in it (CheckIssuer), then redeems
the code with ExchangeSignIn, which refuses, and returns no tokens, unless the
answer's ID token comes from that issuer, names this client as its only audience,
names a subject and its issue time, is unexpired, is signed with ES256 by a key the
authority publishes, carries the nonce, was met by one of the methods named, and,
when an age was asked, names an authentication no older than it. A refused ID token
also ends the session the exchange opened. For a fresh sign-in pass MaxAge of
zero to both calls: Prompt: "login" alone is a request, which only the checked
authentication time proves.
as := asclient.New(publicURL, internalURL, clientID, redirectURI,
asclient.WithClientSecret(clientSecret), // a confidential client; omit for a public one
asclient.WithIssuer(issuerURL)) // the issuer a sign-in's answers must name
// 1. Start: one key + one PKCE pair + one nonce per sign-in, kept with it,
// then send the browser off.
key, _ := asclient.GenerateKey()
verifier, challenge, _ := asclient.PKCE()
state, _ := asclient.RandomToken(32)
nonce, _ := asclient.RandomToken(32)
redirect := as.AuthorizationURL(asclient.AuthorizationRequest{
CodeChallenge: challenge, State: state, Nonce: nonce,
ACRValues: "", // the authority's method names, to name the way in
MaxAge: nil, // a pointer to zero for a fresh sign-in, passed to the check too
})
// 2. Callback: check who answered, then redeem the code, proving possession of
// that session's key, and check the ID token.
if err := as.CheckIssuer(iss); err != nil { /* refuse; redeem nothing */ }
tokens, id, err := as.ExchangeSignIn(ctx, key, code, verifier,
asclient.IDTokenCheck{Nonce: nonce, ACRValues: "", MaxAge: nil, Started: startedAt})
// 3. Later: refresh, read the identity, or elevate the session.
tokens, err = as.Refresh(ctx, key, tokens.RefreshToken)
id, err := as.Identity(ctx, key, tokens.AccessToken)
// 4. Sign-out: end the session at the authority, server to server, then send
// the browser through its logout leg, which names no session.
_ = as.Revoke(ctx, key, refreshToken)
redirect = as.BrowserLogoutURL(postLogoutURL, loginMethod)AuthorizeURL and ExchangeCode remain for a sign-in that asks for no ID token.
AuthorizeURL asks for no fresh sign-in: the authority refuses a sign-in completed
with a method the request did not name, so the named method still wins.
An ID-card sign-in is a redirect sign-in like any other: the authority reads the card
on its own sign-in page. A session's method is fixed by its sign-in; a back-end that
needs another proof starts a fresh sign-in naming the way it wants. The refresh
token is answered to the back-end only and is bound there to this client and the
session key; it never belongs in a browser address, which is why the sign-out runs
Revoke before the browser leaves.
ParseUnverified reads a token this service was just issued into the shared claim
model — for labelling the session it already holds, never for authorizing anything.
SerialFromToken answers its identity code in the spelling codes are compared in
(identitycode.Key), ready to match against a record somebody else wrote.
The AI apps connected as a person's assistants are read and signed out with the person's own token and the session's key, at the authority's identity door:
own, err := as.OwnConnections(ctx, key, accessToken) // the person's own assistants, each with its apps
err = as.SignOutOwnConnection(ctx, key, accessToken, own[0].Connections[0].ID)
// An administrator of the workspace the token names, for any one assistant:
apps, err := as.AssistantConnections(ctx, key, accessToken, assistantKey)
err = as.SignOutAssistantConnection(ctx, key, accessToken, assistantKey, apps[0].ID)
err = as.EndAssistantConnections(ctx, key, accessToken, assistantKey) // every app, as its removal asksA connection is named by its public name, never a session's key or a token. A
refusal is an *asclient.Error carrying the authority's own body, to relay as it
came; a name or key that is empty, or that a path would read as more than one
segment, is refused before anything is sent.
A code exchange also hands back Tokens.Capabilities when the login captured a
signing-capability set: the signing identity, its certificate, the paired
authentication certificate and the organisation seals the person may sign with.
It is nil when the authority sent none, which means "unknown", never "none"; a
refresh never carries it, so keep it with the session. The certificates carry
personal data and are never logged.
A person who is in several organisations can name the one to act under. Set
AuthorizationRequest.Tenant (or call AuthorizeURLForTenant for a sign-in that asks
for no ID token); it is sent as one tenant parameter, however odd its value, and an
empty one changes nothing. The authority checks it when it issues the token and
refuses an organisation the person is not in with a 403; NotMember tells that
refusal from any other. A code exchange and a refresh answer Tokens.Memberships, every
organisation the person may act under at that moment (id and name, in the order sent),
only for a person in more than one; a token for one organisation still lists the others.
redirect := as.AuthorizationURL(asclient.AuthorizationRequest{
CodeChallenge: challenge, State: state, Nonce: nonce,
Tenant: chosenTenant, // empty: the authority's own choice
})
tokens, id, err := as.ExchangeSignIn(ctx, key, code, verifier, check)
if asclient.NotMember(err) { /* sign the person in again naming none, once; never loop */ }
for _, m := range tokens.Memberships { /* m.Tenant, m.Name (may be "") */ }The authority answers the same refusal to a person with no membership at all and to a refresh whose organisation is gone, so it does not show that another organisation exists: a back-end may sign the person in again naming none, once, and must not loop.
A back-end that keeps one session per browser acts in the session's organisation. A page
says which organisation it was opened for in the asclient.WorkspaceHeader request
header (Workspace-Id); CheckWorkspace(asked, held) serves a request that names none or
the session's own, and otherwise answers a 409 problem with the code
asclient.OtherWorkspaceCode that names neither organisation, as a
*asclient.WorkspaceRefusal (status, code and detail, for the back-end to answer in its own problem document). The back-end acts in the
session's organisation whatever the header says; the check only notices a stale page.
A page built before the header existed sends none, so its writes would be served in
whatever organisation the session is in now. For a request for which
asclient.Changes(method) is true (every method except GET, HEAD and OPTIONS), call
asclient.CheckWorkspaceWrite(asked, held, companies) instead, where companies is the
number of organisations the person is in: a write that names none is refused, as above,
when companies is more than one. A person in one organisation is never refused for a
missing header. A named organisation is checked exactly as CheckWorkspace checks it.
if err := asclient.CheckWorkspace(r.Header.Get(asclient.WorkspaceHeader), session.Tenant); err != nil {
var refusal *asclient.WorkspaceRefusal
if errors.As(err, &refusal) { /* answer refusal.StatusCode() with refusal.Code and refusal.Detail: the page must reload */ }
}Never read the header to choose, widen or narrow what is served.
A signatory's identity code arrives written several ways — with the identity type
and country a certificate or an identity provider puts on it, with the separator
dropped, as a person writes their national code, or in the LV/LV/… shape a
cross-border login carries. Canonicalise before storing and before comparing, and
all of them are one person:
stored, err := identitycode.Canonical(rawFromCertificate, "") // "PNOLV-XXXXXXXXXXX"
stored, err = identitycode.Canonical(typedCode, chosenCountry) // the same value
shown := identitycode.Display(stored) // "XXXXXX-XXXXX"Display is the spelling to put in front of a person: their own national code,
written the way their country writes it where that spelling is known, and
otherwise the whole stored code, prefix and all. It never drops the country or
the identity type — the same digits in two countries belong to two people, and an
organisation's register number is not a person's — so nothing it returns can
stand for more than one principal. What it returns can also be typed back in and
resolves to the same person.
The country argument is a hint, consulted only when the code names no country of its own: the country chosen on the screen the code was typed into, the country in the signing certificate, the country recorded for the system that sent it. A country in the value always wins, and one that contradicts the hint is ignored rather than being an error — a caller's software may or may not put the country on the wire, and both have to work.
The country is never guessed. A bare code with no country available is refused
(ErrCountryRequired), because the same digits belong to different people in
different countries. The refusals are sentinel errors, comparable with
errors.Is, and none of them carries the offending code — an identity code is
personal data, and these errors reach service logs. Validation is shape only: a
typed code is a reference to a person, and what settles who signed is the
certificate they sign with, so a checksum rule written for one country's format
could only add ways to refuse a real foreign signatory.
Key is for comparing a value of unknown provenance without storing it; storing
always goes through Canonical.
A code also says whether it belongs to a person or to an organisation. The
identity types come in two lists, and a certificate carries them in two different
places — a natural person's code in the subject's serialNumber, a legal person's
in its organizationIdentifier:
c, err := identitycode.Parse(stored)
if err == nil && !c.IsNaturalPerson() {
// a trade-register number: a valid identity, and one no login answers to
}Ask it wherever a code has to name somebody who will later authenticate — a party
expected to act, a slot waiting to be claimed. Nobody authenticates as an
organisation: its electronic seal is a signing method its people reach for after
identifying themselves, so a code naming an organisation is an identity no login
will ever answer to. IsNaturalPerson is false for anything the standard does not
place with a natural person, an unrecognised type included, because the question is
asked in order to refuse. The list is the standard's, not this package's, so it
already covers identity types this package does not yet recognise.
A permission is one act on one feature of a service, such as removing a file
somebody else attached to a task. It travels on a token as a scope,
<service>/<feature path>:<act>, and a route checks it as an exact match, so
holding one act implies no other and nesting a feature under another grants
nothing. The service writes its permissions once; the same list is what the
membership register learns and what every route checks:
var Permissions = permissions.MustNew("projects", "Project and workflow engine", []permissions.Permission{
{Feature: "project", Act: "create", Description: "Register a project",
Class: permissions.Ordinary, Plane: permissions.Tenant,
Labels: map[string]string{"lv": "Reģistrēt projektu"}},
{Feature: "task/comment", Act: "add", Description: "Comment on a task",
Class: permissions.Ordinary, Plane: permissions.Object},
{Feature: "setup", Act: "import", Description: "Apply a configuration file",
Class: permissions.TenantConfiguration, Plane: permissions.Tenant},
})
var permCommentAdd = Permissions.Declared("task/comment", "add") // stops the service if undeclared
gate := Permissions.Gate(func(ctx *azugo.Context, required string) { /* record the refusal */ })
v1.Post("/tasks/{id}/comments", gate.OneOf(permissions.Levels("projects", "log", "write"), r.commentAdd, permCommentAdd))
v1.Get("/config", gate.Member(permissions.Levels("projects", "read"), r.configGet))Declaredanswers the permission a route checks and panics when the list does not declare it, so a check nobody can be given stops the service at load.- The route gate passes a caller holding one of the permissions (
OneOf) or all of them (AllOf), beside an optional coarser level — a rung of the service's own role ladder, or any check the service writes as aLevel; passpermissions.Level{}for none.Memberpasses the level or any permission the service declares. A refusal is403, after the callback has been told what would have been enough. A handler that tells an act on the caller's own work from an act on anybody's readsperm.HeldBy(ctx.User()). - The register document:
Section()renders the list as the membership register's configuration section, andCommand()is apermissionscommand that prints it, for a deployment to apply; neither makes a call. A service that declares itself when it starts usesdeclare(below). - Levels:
Set.AddLevels(permissions.Rung{Group: "projects", Level: "read"}, …)attaches the rungs of the service's own role ladder (a scope group and a level name, one lower-case word each, an optional one-sentence description). A level named twice is an error. A Set with levels renders them asrolesin its section; a Set with none renders exactly what it always did. - One document for several Sets:
permissions.Declaration(a, b)renders one service entry per Set, in the order given, the same bytes every time, and refuses two Sets under one key;permissions.ServiceKeys(a, b)answers the keys. - Each permission says its
Class(whether it changes what others may do, or is a family of rights, one per field), itsPlane(granted to the wholeTenant, on oneObjectthe service owns, or to a position in the tenant'sChartof authority), its label per language (Label(lang)falls back to the description) and whether it isRetired— kept for the roles that already hold it, never handed out again. A permission is never removed from a list. - Seeds: an ordinary permission on the object plane may name the roles the
register creates with every new tenant that hold it (
Seeds: []string{"worker", "manager"}), so a tenant starts with working roles; the tenant changes or deletes them like any other. - A family of rights, one per field (
Class: permissions.PerField): a service whose tenants add their own fields, and restrict who sees a field's values, declares one family per kind of field (task:viewField) on the object plane. A field's right is the family,@, the field's key and a generation the field counts up each time it is restricted —projects/task:viewField@rate.2— held only as a tick on a role placed on the service's objects, so it arrives in a placement's keys and never on a token. The bare family is the administrators', on their token, and means every field of the kind. The service checks it on each value it answers, so the test kit asks no route to accept it. - A library contributes its own permissions:
MustNew(key, name, own, library.Permissions)puts them under the service's key, and the library's routes check them through the same Set, so the same start check covers them.
The test kit holds the routes against the list, both ways:
func TestPermissions(t *testing.T) {
r := register(testApp(t)) // the service's routes, through its Gate
permissionstest.Check(t, Permissions, r.gate)
}It fails when a declared permission is checked by no route (a retired one or a
per-field family aside),
when a route checks one the list lacks, when a check naming an undeclared act does
not stop the service, when an act on your own work (editOwn) has no act on
anybody's (edit) beside it, and when the register document carries a property the
register would refuse.
A task a service adds at start that sends its Sets to the membership register as
the service itself, so nobody has to apply the permissions output by hand:
task, err := declare.New(authClient, "http://membership:8080", "membership", declare.Config{},
Permissions, AuthorityPermissions) // each a *permissions.Set, under its own key
app.AddTask(task)-
The request is
POST <address>/api/v1/declarationswithContent-Type: application/jsonand the bodypermissions.Declarationrenders. The token is asked for the register's audience with the scopedeclare:<key>for each key in the document, anddeclare-group:<group>for each level group that is not named like the service key it is declared under (each once, all sorted together and space-separated), and nothing else, so the register can hold the service to the keys and groups its deployment granted it. A level whose group equals its key adds no scope; a document with no levels asks only fordeclare:scopes. The deployment's client registry must grant the service's client everydeclare-group:scope it asks for, or the token is refused and nothing is declared until the grant is there. -
Startreturns at once and never fails because the register is away; the loop runs in the background. A call that cannot be made, a token that is not given, a5xxor a429is tried again afterFirstPause, doubling up toLongestPause. A200is reported (OnDeclared) and the document is sent again afterRepeat. Any other answer is a refusal: it is reported as an*declare.Errorcarrying the status, the problemcodeanddetail, and tried again only afterLongestPause, because a change of the deployment or of the document cures it, not a second's wait. -
Defaults for a zero
Config:DefaultFirstPause1 s,DefaultLongestPause1 min,DefaultRepeat1 h.OnErrorhears every failed attempt. -
Stopends the loop and waits for it; no request is made after it returns. -
Products and the caller's own account can ride in the same document. Give
ConfigProducts(a key, a display name, the services it gives, each with an optional feature, and the products it needs) andAccounts(the product the account is in, a display name and the levels it holds). An account never names a client: it is always the caller's. A program that only attaches its account passes no set at all:task, err := declare.New(authClient, "http://membership:8080", "membership", declare.Config{ Products: []declare.Product{{ Key: "suite", DisplayName: "Suite", Gives: []declare.Give{{Service: "alpha", Feature: "tasks"}, {Service: "beta"}}, Needs: []string{"base"}, }}, Accounts: []declare.Account{{ Product: "suite", DisplayName: "Suite account", Roles: []declare.Level{{Service: "alpha", Group: "tasks", Level: "read"}}, }}, }, AlphaPermissions) // the set of service alpha; beta is declared elsewhere
A word (a key, a service, a group, a level) is one lower-case word of letters, digits and
-, at most 64 characters, starting with a letter.Newrefuses what the register would refuse: more than 20 products or 20 accounts; a product with no gives, more than 50 gives or more than 20 needs, that needs itself, repeats a key or repeats a (service, feature) pair; an account with more than 50 levels or a level twice; a product with two accounts; a display name that is empty, over 200 characters or holds a control character. With no products and no accounts the document and the scopes are exactly what they were. -
Three more scopes are asked, sorted with the rest:
declare-product:<key>for every product,declare-give:<service>for every service a product gives that is not a service of the same document (a service the document declares is covered by itsdeclare:scope), anddeclare-account:<product>for every account. The deployment's client registry must grant the service's client each of them, or the token is refused. In the example the token carriesdeclare-account:suite declare-give:beta declare-product:suite declare:alpha. The register must be a version that knows products and accounts before a service sends them. -
An entry can wait. A
200answer lists each product and account with a status:added,unchanged,changedorwaiting.waitingmeans the entry refers to something the register does not hold yet (aproduct, aserviceor alevel); nothing is wrong. The task sends the document again afterLongestPause, notRepeat, for as long as any entry waits.OnDeclaredis still told, andOnWaitingreceives the waiting entries (kind, key, reason). An answer that cannot be read, or is longer thanMaxAnswerBytes(256 KB), counts as accepted with nothing waiting.
A service that owns objects — a project, a register — can let a tenant put a person on one of them with one of the tenant's roles. What the person may do there is what the role carries in that service, and a check on every request should not ask the membership register every time. So the service keeps a copy of the roles beside its placements, and this package keeps the copy current and honest:
reg, _ := placement.NewRegister(authClient, "http://membership:8080", "membership", "projects")
keeper, _ := placement.New(reg, myStore, placement.Config{}) // 10 s poll, 15 min trust window
go keeper.Run(ctx)
// On a request from a tenant this service has never read the roles of:
keeper.Wake(tenant)
// Wherever a placement is checked, a copy confirmed before this grants nothing:
since := keeper.TrustedSince()
// On the readiness check:
if err := keeper.Ready(); err != nil { /* degraded: placed keys grant nothing */ }- The poll sends the version the service holds; while nothing changed the
register answers
304with no body, so asking every few seconds costs almost nothing. A changed answer goes to the service'sStore.Replace, which replaces the copy and the keys beside every placement of a changed role in one transaction. - The trust window is how long a confirmed copy counts. A role taken back in
the register stops working here within the window even when the register cannot
be reached;
Readynames the tenants whose copy is past it. - The count: after a cycle in which they changed, the service's placements per role go to the register, which then refuses to delete a role somebody is still placed in. An id it no longer knows comes back as an error for that tenant.
- Only the service's own groups are copied:
NewRegister(…, "projects")keepsprojects/…permissions and drops the rest.Keys.Holds(perm)checks a placement's keys with the same exact match the route gate uses. - A role's names:
Role.Nameis the name as the tenant entered it, andRole.Labelsits name in other languages ({"en": "Worker"}), so the service can name a role to each reader in the reader's language and fall back toName.Labelsis empty, never nil, when the role has no other names or the register answers none; an answer whose names are not a language-to-name object is refused like any answer that cannot be read, and the copy stays as it was. - The copy lives with the service's data, behind the
Storeinterface — five methods: the tenants it holds, a copy's version, replace, confirm, and counts. The register is reached as the service itself, a member of each tenant, holdingmembership:definitionsandmembership:placements.
A tenant may draw its own tree of positions and put its people in them, and a service may let a person see what the people below them see — the projects of everyone who reports to them — without joining any of them. The service reads that from a copy of the tree, kept the way the roles' copy is kept:
reg, _ := chart.NewRegister(authClient, "http://membership:8080", "membership")
keeper, _ := chart.New(reg, myStore, chart.Config{}) // 10 s poll, 15 min trust window
go keeper.Run(ctx)
keeper.Wake(tenant) // a tenant this service has never read the chart of
since := keeper.TrustedSince() // a copy confirmed before this lifts nothing
if err := keeper.Ready(); err != nil { /* degraded: the chart lifts nothing */ }- The copy is a list: for each person, everyone below them, all the way down,
as subject keys (
Chart.Below). Nobody is below themselves, and a person with nobody below has no entry. - Same discipline as the roles' copy: the poll sends the version held and a
304costs nothing, a changed answer replaces the copy in oneStore.Replace, and a copy is trusted for one window after it was last confirmed. A person moved out of a position stops seeing through it within one interval, and when the register cannot be reached, within the window. - The store has four methods: the tenants it holds, a copy's version, replace,
confirm. The register is reached as the service itself, holding
membership:chart; a tenant without a chart is answered as an empty one. - The permissions that read the copy are declared on the third plane,
permissions.Chart: held by a position, relative to the tree, ordinary in class, never ticked on a role or a user type and never seeded. The test kit's declared is checked rule skips them, since they are read from the viewer's reach rather than checked on a route.
A service that hands a program its own key — an integration, an assistant — makes the key here, stores only its hash, and checks a presented key with the same work whether it is wrong, unknown or malformed:
scheme, _ := apikeys.NewScheme(apikeys.Config{Scheme: "ak"}) // argon2id at 19 MiB, t=2, p=1
k, _ := scheme.Mint()
store(k.Lookup, k.Hash) // keep these two; nothing else about the key is kept
show(k.Key.Reveal()) // once, to its holder; k.Key prints and marshals as [redacted]
v, _ := scheme.NewVerifier(lookupStored, apikeys.VerifierConfig{}) // limit and cap on by default
res, err := v.Verify(ctx, connectionAddress, presented)
if err != nil {
status := apikeys.HTTPStatus(err) // 401, 429, 503 or 500
if after, ok := apikeys.RetryAfter(err); ok { /* Retry-After */ }
}
if res.Rehash != "" { storeIfStill(res.Lookup, res.Replaces, res.Rehash) } // below the current parameters- A key reads
<scheme>_<lookup>_<secret>: the lookup part (8 characters of Crockford's Base32, 40 random bits) is stored in clear to find the key by, and the store holds it unique (mint again on a clash); the secret (32 characters of base64url, 192 random bits) is never stored. Only an argon2id hash of the secret is, as a PHC string, never weaker than 19 MiB and two passes. - A check, in order: the caller's rate limit (60 attempts a minute by default, successes included, which suits keys exchanged now and then; a service checking a key on every request gives a higher one); the key's shape, its length first; the lookup; a derive slot (4 at once by default, a check past it is refused at once); one derive; a constant-time comparison. A wrong secret, an unknown or revoked key and a malformed one each pay exactly one derive, and an unknown key can never pass.
- The caller is what the limit is kept by, so it is something a client cannot
choose: the connection's address (an IPv6 client by its /64), never a forwarded-for
header the service does not set itself. An empty one is refused. Once the limiter's
table is full, callers never seen before share one allowance: its memory and the
derives it lets through stay bounded under a flood, and new callers wait while it
lasts. Lookups run outside the derive cap; the store's pool and the deadline of the
ctxgiven toVerifybound them. - A stored string is read strictly: one spelling, argon2id version 19, a salt of
16 to 64 bytes, a 32-byte tag, and parameters between the scheme's floor and its
ceiling. A corrupt or tampered one is
ErrStoredHash— neither a panic nor a cheap check — and the key is not accepted; it answers 500 and is the service's alarm. - Revocation counts at once: the lookup runs on every check, and a revoked or
replaced key is simply not found. A service that checks a key on every request
may turn on a success cache (
CacheTTL); an entry is bound to the stored string it passed against and holds a digest of the secret, never the secret. - Raising the parameters: set the new ones as
Params; the floor stays at the defaults, so each key stored below the new ones still verifies and hands backResult.Rehash, every field raised to the new value and none lowered. Store it only where the store still holdsResult.Replaces, so a key changed in between is never overwritten. While old stored strings remain, an unknown key's check costs what a key at the new parameters costs, not what an old one does.
A service that receives a key but does not check it — a door that hands it on to the authority, which keeps the stored hashes — reads its shape and exchanges it for a token toward the service it calls:
key, err := scheme.Presented(header) // shape only: nothing derived, nothing looked up
if err != nil { /* 401: it can never be a key of this family */ }
tok, ttl, err := ac.ExchangeKey(ctx, "svc:api", "projects/task:view", key)
var refused *authclient.Error
if errors.As(err, &refused) && refused.RetryAfter != "" { /* the authority's limit: pass Retry-After on */ }
res, err := ac.DoWithToken(ctx, "svc:api", tok, http.MethodGet, url, nil, nil)- The exchange is RFC 8693's, with the key as the subject token and
apikeys.TokenType(urn:gmb:params:oauth:token-type:api-key) as its type; the authority checks the key as above. The token is bound to the client's own DPoP key, soDoWithTokenpresents it. - Nothing is cached by
ExchangeKey: how long a token made from a key is reused is the calling service's decision, since the key can be taken away at any moment.
apikeys/ API keys for programs: mint, store only an argon2id hash, check behind a limit and a cap
asclient/ Confidential authorization-code browser login (PKCE + per-session proof)
authclient/ Configuration, Client, Azugo middleware, outbound calls
chart/ A service's copy of who is below whom in a tenant's chart of authority
claims/ Shared JWT claim model (user + service + delegated tokens; `act`)
declare/ A task that declares a service's permissions and levels to the membership register at start
dpop/ RFC 9449 proof generation & verification, JWK thumbprint
identitycode/ One spelling of an identity code — store, compare, show
jwks/ Caching JWKS client (TTL + unknown-kid refresh)
nonce/ Stateless HMAC server nonce (DPoP-Nonce)
permissions/ One list of the acts a service enforces: declare, check on routes, register, test
placement/ A service's copy of a tenant's roles, for roles placed on its own objects
replay/ jti replay cache — memory (default) or redis
Bound as a sub-configuration of each consuming service. Typically only the issuer URL, this service's audience, and its client id/secret are set per service; everything else defaults safely.
| Env | Default | Purpose |
|---|---|---|
AUTH_ISSUER_URL |
— | Trust anchor; JWKS/discovery source; expected iss. |
AUTH_JWKS_URL |
derived | Override JWKS location. |
AUTH_JWKS_CACHE_TTL |
10m |
Public-key cache lifetime. A token whose kid is not cached triggers one out-of-band fetch regardless of this TTL, so a rotated signing key is picked up without restarting the service; repeat unknown kids are rate-limited (30s) so they cannot be used to generate traffic at the issuer. |
SERVICE_AUDIENCE |
— | This service's own aud. |
SERVICE_CLIENT_ID / SERVICE_CLIENT_SECRET (_FILE) |
— | Outbound client-credentials. |
SERVICE_TOKEN_EARLY_REFRESH |
30s |
Refresh own token before exp. |
DPOP_PROOF_MAX_AGE |
60s |
Inbound proof age window. |
TOKEN_CLOCK_SKEW_LEEWAY |
30s |
Leeway on exp/iat/proof age. |
DPOP_REPLAY_BACKEND |
memory |
memory (per-pod) or redis. |
REDIS_URL |
— | Required when backend is redis. |
DPOP_NONCE_ENABLED |
true |
Require + issue DPoP-Nonce. |
DPOP_NONCE_TTL |
5m |
Issued nonce lifetime. |
REQUIRE_DPOP |
true |
Enforce DPoP on inbound. |
A service that answers for more than one audience — an authority serving several
products' sign-in clients, say — sets AlsoAcceptedAudiences in code: an inbound
token may then name any one of those audiences instead of ServiceAudience.
TLS is selected by the URL scheme. rediss://… connects over TLS; redis://… does not. skip_verify=true only relaxes certificate verification on a rediss:// URL — on a redis:// URL the client rejects it outright (redis: unexpected option: skip_verify) rather than silently upgrading the connection. Earlier Azugo versions did treat skip_verify=true as an implicit request for TLS; that side-effect is fixed from Azugo v0.37 onwards, so a TLS endpoint must always be addressed as rediss://.
go test ./...DPoP proof round-trip and tamper/expiry/ath/nonce rejection
(dpop), the stateless nonce
(nonce) and every spelling of an identity code — for
every identity type this library recognises, crossed with the separator, no
separator and lower case (identitycode,
with a fuzz target over the round trip a person makes when they retype what they
were shown) are covered. The end-to-end token+JWKS path is
exercised from the authbyte-core issuer tests.
Bug reports and pull requests are welcome. CONTRIBUTING.md names the gate a change has to pass, what a change to this library needs, and the sign-off every commit carries.
Suspected vulnerabilities go through the private route in SECURITY.md — never a public issue.
MIT — see LICENSE.