axa

package module
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Nov 17, 2026 License: Apache-2.0 Imports: 4 Imported by: 1 module, 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

AxA

Agent x Anything Authentication: one Go library that signs in people, agents and outsiders, and decides what each may touch.

The caller on the other end of a request is no longer always a person. AxA authenticates all of them in one chain and authorizes them in one place:

  • People sign in through the IdP they already use. An embedded Dex brokers upstream OIDC, SAML and LDAP, with TOTP and WebAuthn as a second factor.
  • Agents carry credentials the service issues itself: agent tokens, personal access tokens and the OAuth client_credentials grant.
  • Outsiders, such as a vendor filling in one questionnaire, get a single-use magic link scoped to one object, never an account.
  • Every one of them ends up as the same Claims, and one OpenFGA relationship check decides access.

It is what Armornet runs, as a library: issue identity, relate principals to resources, enforce access. Module github.com/ArmornetIO/axa. Your application imports it; it never imports yours. Persistence, delivery and domain decisions are interfaces you implement.

Status

Alpha, versioned 0.0.x: no compatibility promise between releases, so pin an exact version. What holds regardless is what the tests enforce: authn and authz import nothing else from this module (TestLayering), a recognised but invalid credential never falls through to a weaker one, and stored client secrets are argon2id hashes.

The embedded Dex is a fork of Dex v2.45.1 in internal/dex: it adds token revocation, RP-initiated and back-channel logout, the client_credentials grant, hashed client secrets and sealed claims at rest. Each change is marked ARMORNET FORK.

Quick start

examples/gin-basic is a Gin API behind AxA's browser sign-in, in one process with one Postgres. Dex's mock connector stands in for a real IdP:

cd examples/gin-basic
docker compose up -d          # Postgres on :5433
go run .                      # http://localhost:8081

main.go is the whole wiring. "Behind our auth" is one middleware:

api := r.Group("/api", requireSession(auth))
api.GET("/hello", func(c *gin.Context) {
	sess := c.MustGet("session").(authn.SessionRecord)
	c.JSON(http.StatusOK, gin.H{"hello": sess.Subject, "org_id": sess.OrgID})
})

examples/custom-login puts a designed login page over the same flow with the browser client in ts/.

Design rule

The module defines seams; the host implements them. Persistence, delivery, and domain decisions are reached only through the interfaces defined in each package (e.g. PATLookup, MagicLinkStore, Notifier, Resolver). Domain logic that names a host's own concepts stays in the host.

Layout

Path What it owns
broker.go, clients.go, connectors.go Root contracts: Broker, ClientStore, ConnectorStore/Connector (upstream IdP CRUD, backend-agnostic).
authn/ Request authentication: Claims, Authenticator, and Service, the ordered chain (below). Credentials the host itself issues & verifies — not federated OIDC: AgentTokenProvider, PATProvider, MagicLinkProvider. token.go (GenerateToken, prefixes), scopes.go.
authz/ Authorization: Service (the access decision pipeline assembled from host ports), Grapher (Checker → graph axis), Checker, Tuple, mapper, FGAClientIface. Tenant-agnostic (tenancy is a host boundary).
access/ Composes authn and authz into one decision per request, plus short-lived signed assertions for a proxy to check.
dex/ The embedded Dex broker, configured by a Config struct (DB URL, connectors, hasher injected — no env reads except the secrets seam).
fga/ OpenFGA server/client wiring.
ginauthz/ Gin middleware adapter for the checker.
authn/secrethash/ argon2id token hashing (HashToken/VerifyToken) + params.
pgstore/ Postgres implementations of AxA-owned persistence seams (see below). Uses a host-injected *sql.DB; imports no driver.
service/ Assembly/health entry points.
web/ The browser sign-in flow: /api/auth/* (authorize, callback, session, logout, back-channel logout, MFA) over the authn stores. Plain net/http: Handler() for a mux, Routes() for a router that registers per pattern. ts/ is its browser client.
examples/ gin-basic — a Gin API behind this sign-in, runnable against one Postgres. custom-login — a designed login UI over ts/.
internal/dex/ The Dex fork. Upstream code except where marked ARMORNET FORK.

The credential chain (authn/)

Every authenticator implements Authenticator: Authenticate(ctx, r) (Claims, error). You list them, most privileged first, in an authn.Service:

svc := &authn.Service{Authenticators: []authn.Authenticator{
	agentTokens, // anet_agent_…
	pats,        // anet_user_…
	sessions,    // __Host-session cookie
}}
claims, err := svc.Authenticate(ctx, r)

An authenticator returns ErrNoCredential for a request it does not recognise, and the chain tries the next. Once it recognises its credential, any rejection is final: a revoked PAT never falls through to the session cookie riding on the same request. The zero Service authenticates nobody. Persistence is a seam you fill.

PAT — authn/pat.go

Personal access tokens (anet_user_ / anet_agent_ prefixes), argon2id-hashed, prefix-narrowed lookup via the host's PATLookup.

Short-lived, single-use, scoped access links for a third party (e.g. a vendor filling out an assessment) who can't do federated login. Not a general passwordless fallback — it grants scoped access to one object, enforced by FGA.

  • MagicLinkProvider — Request(ctx, email) (resolve → mint token → persist hash → deliver; enumeration-safe: unknown emails send nothing) and Redeem(ctx, token) (verify → atomic single-use consume → return Grant). Token prefix anet_magic_; default TTL 15m.
  • Grant{Subject, OrgID, ObjectType, ObjectID, Relation} — opaque to the module. The host interprets it: write an FGA tuple Relation on ObjectType:ObjectID for Subject, then mint a scoped session. Subject is a host-minted principal id, never an email.
  • Seams the host implements:
    • Notifier — delivery. The module builds the token + link; the host chooses the channel.
    • Resolver — domain. Given an email, does it map to a scoped Grant? The module has no concept of assessments or assignees — the host answers.
    • MagicLinkStore — persistence (Create / ByPrefix / atomic Consume).
  • pgstore.MagicLinkStore — the Postgres implementation of MagicLinkStore over the AxA-owned magic_link table (host injects *sql.DB).

Schema: AxA owns the code, you own the tables

pgstore takes an opened *sql.DB and runs queries. It never migrates, and there is no migrator in this module. Creating and versioning the tables below is the host's job.

That split is deliberate rather than unfinished. A library that reshapes a database it was handed fights whatever the host already uses to manage schema — which is why the embedded Dex and OpenFGA run with their own migrators disabled, and a host applies their tables through its own migrations instead. AxA follows the same rule for its own tables.

Table Used by
users pgstore.UserStore → authn.UserStore
organizations pgstore.OrgStore → authn.OrgStore
organization_users pgstore.UserStore → authn.UserStore
sessions pgstore.SessionStore → authn.SessionStore
magic_link pgstore.MagicLinkStore → authn.MagicLinkStore
personal_access_tokens pgstore.PATStore → authn.PATStore (and authn.PATLookup)
preauth_sessions pgstore.PreAuthStore → authn.PreAuthStore
mfa_challenges pgstore.MFAChallengeStore → authn.MFAChallengeStore
user_totp_credentials pgstore.TOTPStore → authn.TOTPStore
webauthn_credentials pgstore.WebAuthnCredentialStore → authn.WebAuthnCredentialStore
webauthn_sessions pgstore.WebAuthnSessionStore → authn.WebAuthnSessionStore
invite_kinds, org_invites, org_invite_parties pgstore.InviteStore → authn.InviteStore
org_domain_allowlist pgstore.DomainAllowlistStore → authn.DomainAllowlistStore
legal_document_kinds, legal_documents, legal_document_versions, legal_acceptance pgstore.LegalStore → authn.LegalStore

A host's own tables may carry foreign keys into users and organizations. That is expected: AxA owns the definition, the host applies it into the host's database, and the tables sit alongside each other. What AxA must not acquire is the reverse — a reference from these tables out into anything a host defines.

pgstore.Schema() returns the reference DDL (pgstore/schema.sql) so a host can execute it, diff against it, or fold it into its own migrations. dex.Schema() and fga.Schema() do the same for the embedded Dex and OpenFGA tables, whose own migrators are disabled — without them a fresh database has nowhere for either engine to write. Every statement is IF NOT EXISTS, so running it is safe — but it will not upgrade a table that already exists in an older shape.

Two things a host should know before wiring these up:

  • org_id is opaque here. AxA treats it as a scoping string and nothing more. A host may point a foreign key at its own tenant table. Nothing in this module requires that, and sessions.org_id is nullable because a session can legitimately exist before its owner belongs to anything.
  • Encryption is yours. The upstream tokens on a session are bytea and are sealed by an authn.Encrypter the host supplies, because the key is the host's. Supply none and they are stored as-is.

Develop

authn, authz and ginauthz are modules of their own, so ./... from the root does not reach them:

for m in . authn authz ginauthz; do (cd $m && go vet ./... && go test ./...); done

The LDAP connector's tests need an LDAP server and skip without one.

Security

Report a vulnerability privately: see SECURITY.md.

The GIFs in this README are scenes from Showcase, filmed frame by frame by its npm run record:scenes.

License

Apache-2.0

Documentation

Overview

Package identity is the broker contract the REST and OIDC layers program against; backends (dex/) implement it and callers never import one directly.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrClientNotFound = errors.New("identity: client not found")
	ErrClientExists   = errors.New("identity: client already exists")
)
View Source
var (
	ErrConnectorNotFound = errors.New("identity: connector not found")
	ErrConnectorExists   = errors.New("identity: connector already exists")
)

Functions

func ConnectorType

func ConnectorType(c ConnectorConfig) string

ConnectorType is the kind label for logs and validation; type-switch for the value.

Types

type Broker

type Broker interface {
	// Handler serves discovery, /auth, /token, /keys and /callback; it must not
	// rewrite the prefix it is mounted under.
	Handler() http.Handler
	Connectors() ConnectorStore
	Clients() ClientStore
}

Broker issues OIDC tokens, federates upstream IdPs and serves connector and client CRUD. Safe for concurrent use.

type Client

type Client struct {
	ID   string
	Name string
	// RedirectURIs is an allowlist: any other redirect_uri is rejected.
	RedirectURIs []string
	// TrustedPeers are client IDs whose ID tokens this client accepts.
	TrustedPeers []string
	// Public clients (native apps, SPAs) use PKCE and have no secret.
	Public  bool
	LogoURL string
}

type ClientStore

type ClientStore interface {
	// Create returns the generated secret once and never again (Dex stores it
	// hashed). A Public client gets "": PKCE needs no secret to leak.
	Create(ctx context.Context, c Client) (secret string, err error)
	// List and Get always leave Secret empty.
	List(ctx context.Context) ([]Client, error)
	Get(ctx context.Context, id string) (Client, error)
	// Update replaces Name, RedirectURIs, TrustedPeers and LogoURL, never the secret.
	Update(ctx context.Context, c Client) error
	Delete(ctx context.Context, id string) error
	// RotateSecret returns the new secret once. The old one dies immediately, with
	// no overlap, so rotate a live client only if you can deliver the new one.
	RotateSecret(ctx context.Context, id string) (secret string, err error)
}

ClientStore is CRUD for the broker's OAuth2 clients. Unknown IDs return ErrClientNotFound; a duplicate Create returns ErrClientExists.

type ConfigSealer

type ConfigSealer interface {
	// Seal's output carries whatever nonce and version framing Open needs.
	Seal(plaintext []byte) ([]byte, error)
	// Open passes through rows written before sealing was on, until re-sealed.
	Open(sealed []byte) ([]byte, error)
}

ConfigSealer encrypts state that must be recoverable at rest (connector credentials replayed on every login, decisions, device codes). The host supplies the cipher so this module holds no key; nil means cleartext.

type Connector

type Connector struct {
	// ID is the seeding idempotency key and the login URL segment.
	ID   string
	Name string
	// Config's concrete type is the connector kind.
	Config ConnectorConfig
}

type ConnectorConfig

type ConnectorConfig interface {
	// contains filtered or unexported methods
}

ConnectorConfig is sealed: the unexported method keeps the set of kinds here.

type ConnectorStore

type ConnectorStore interface {
	Create(ctx context.Context, c Connector) error
	List(ctx context.Context) ([]Connector, error)
	Get(ctx context.Context, id string) (Connector, error)
	Update(ctx context.Context, c Connector) error
	Delete(ctx context.Context, id string) error
}

ConnectorStore is CRUD for upstream IdP connectors. Unknown IDs return ErrConnectorNotFound; a duplicate Create returns ErrConnectorExists.

type GitHubConnectorConfig

type GitHubConnectorConfig struct {
	ClientID     string
	ClientSecret SecretRef
	// RedirectURI must be issuerURL + "/callback".
	RedirectURI string
	// Orgs, when set, restricts login to their members.
	Orgs []GitHubOrg
	// HostName points the connector at a GitHub Enterprise host instead of
	// github.com; Dex always dials it over https.
	HostName string
	// RootCA is a PEM, or a path to one, trusted for HostName only.
	RootCA string
}

type GitHubOrg

type GitHubOrg struct {
	Name  string
	Teams []string
}

GitHubOrg optionally narrows the org to Teams.

type GoogleConnectorConfig

type GoogleConnectorConfig struct {
	ClientID     string
	ClientSecret SecretRef
	// RedirectURI is issuerURL + "/callback", registered in the Google OAuth client.
	RedirectURI string
	// HostedDomains, when set, restricts login to those Workspace domains.
	HostedDomains []string
}

type LDAPConnectorConfig

type LDAPConnectorConfig struct {
	// Host is "host:port".
	Host       string
	BindDN     string
	BindSecret SecretRef
	// StartTLS is ignored on 636 (LDAPS).
	StartTLS bool
	// InsecureSkipVerify: never in production.
	InsecureSkipVerify bool
	UserSearch         LDAPUserSearch
	GroupSearch        LDAPGroupSearch
}

LDAPConnectorConfig is LDAP or Active Directory.

type LDAPGroupSearch

type LDAPGroupSearch struct {
	BaseDN       string
	Filter       string
	UserMatchers []LDAPUserMatcher
	NameAttr     string
}

type LDAPUserMatcher

type LDAPUserMatcher struct {
	UserAttr  string
	GroupAttr string
}

LDAPUserMatcher joins a group entry attribute to a user entry attribute.

type LDAPUserSearch

type LDAPUserSearch struct {
	BaseDN string
	Filter string
	// Username is the attribute the login name matches (e.g. "uid").
	Username string
	// IDAttr, EmailAttr and NameAttr map LDAP attributes to token claims.
	IDAttr    string
	EmailAttr string
	NameAttr  string
}

type MicrosoftConnectorConfig

type MicrosoftConnectorConfig struct {
	ClientID     string
	ClientSecret SecretRef
	// Tenant is required and must be single-tenant; "common", "organizations"
	// and "consumers" are refused (see axa/dex marshalMicrosoft).
	Tenant string
	// OnlySecurityGroups keeps tokens small for users in many groups.
	OnlySecurityGroups bool
	// Groups, when set, is an allowlist of group object IDs.
	Groups []string
}

MicrosoftConnectorConfig is Azure AD / Entra.

type OIDCConnectorConfig

type OIDCConnectorConfig struct {
	// IssuerURL keeps its trailing slash ("https://example.us.auth0.com/").
	IssuerURL    string
	ClientID     string
	ClientSecret SecretRef
	// Scopes are requested on top of "openid".
	Scopes []string
	// RedirectURI must be issuerURL + "/callback"; Dex refuses the callback otherwise.
	RedirectURI string
	// InsecureSkipVerify: never in production.
	InsecureSkipVerify bool
}

OIDCConnectorConfig is any upstream OIDC provider (Auth0, Okta, Google…).

type OpaqueConnectorConfig

type OpaqueConnectorConfig struct {
	Type      string
	RawConfig json.RawMessage
}

OpaqueConnectorConfig is what Get and List return: the kind and the stored config. Credentials appear only as Secret refs; they are never round-tripped.

type SAMLConnectorConfig

type SAMLConnectorConfig struct {
	SSOURL string
	// CARef holds the PEM cert(s) the IdP signs responses with.
	CARef SecretRef
	// EntityIssuer is the SP entity ID sent in AuthnRequests.
	EntityIssuer string
	// SSOIssuer, when set, must equal every response's Issuer.
	SSOIssuer string
	// Dex will not open the connector without UsernameAttr and EmailAttr.
	UsernameAttr string
	EmailAttr    string
	GroupsAttr   string
	// GroupsDelim splits a single-valued groups attribute.
	GroupsDelim string
	// NameIDPolicyFormat becomes the Dex subject; defaults to persistent.
	NameIDPolicyFormat string
	// RedirectURI is the ACS URL: issuerURL + "/callback".
	RedirectURI string
}

SAMLConnectorConfig makes Armornet the SP. Dex never signs AuthnRequests, so there is no SP key.

type SecretRef

type SecretRef struct {
	Namespace string
	Name      string
	Key       string
}

SecretRef names a key in a Kubernetes Secret. Configs take no raw credentials, so none reach Dex storage or an API response.

type SeedFunc

type SeedFunc func(ctx context.Context, b Broker) error

SeedFunc runs once storage is healthy. Idempotent: never overwrites a record.

type StartupSeeder

type StartupSeeder interface {
	Name() string
	Seed(ctx context.Context, b Broker) error
}

StartupSeeder is a SeedFunc with a name for the startup logs.

func Named

func Named(name string, fn SeedFunc) StartupSeeder

Directories

Path Synopsis
Package access decides who reaches a destination and signs a short-lived assertion it verifies; the only package composing authn and authz.
Package access decides who reaches a destination and signs a short-lived assertion it verifies; the only package composing authn and authz.
authn module
authz module
Package dex is axa.Broker on an embedded Dex (the fork in pkg/dex).
Package dex is axa.Broker on an embedded Dex (the fork in pkg/dex).
Package fga embeds OpenFGA in process; Client() calls it with no network hop.
Package fga embeds OpenFGA in process; Client() calls it with no network hop.
ginauthz module
internal
dex/connector
Package connector defines interfaces for federated identity strategies.
Package connector defines interfaces for federated identity strategies.
dex/connector/atlassiancrowd
Package atlassiancrowd provides authentication strategies using Atlassian Crowd.
Package atlassiancrowd provides authentication strategies using Atlassian Crowd.
dex/connector/authproxy
Package authproxy implements a connector which relies on external authentication (e.g.
Package authproxy implements a connector which relies on external authentication (e.g.
dex/connector/bitbucketcloud
Package bitbucketcloud provides authentication strategies using Bitbucket Cloud.
Package bitbucketcloud provides authentication strategies using Bitbucket Cloud.
dex/connector/gitea
Package gitea provides authentication strategies using Gitea.
Package gitea provides authentication strategies using Gitea.
dex/connector/github
Package github provides authentication strategies using GitHub.
Package github provides authentication strategies using GitHub.
dex/connector/gitlab
Package gitlab provides authentication strategies using GitLab.
Package gitlab provides authentication strategies using GitLab.
dex/connector/google
Package google implements logging in through Google's OpenID Connect provider.
Package google implements logging in through Google's OpenID Connect provider.
dex/connector/keystone
Package keystone provides authentication strategy using Keystone.
Package keystone provides authentication strategy using Keystone.
dex/connector/ldap
Package ldap implements strategies for authenticating using the LDAP protocol.
Package ldap implements strategies for authenticating using the LDAP protocol.
dex/connector/linkedin
Package linkedin provides authentication strategies using LinkedIn
Package linkedin provides authentication strategies using LinkedIn
dex/connector/microsoft
Package microsoft provides authentication strategies using Microsoft.
Package microsoft provides authentication strategies using Microsoft.
dex/connector/mock
Package mock implements connectors which help test various server components.
Package mock implements connectors which help test various server components.
dex/connector/oidc
Package oidc implements logging in through OpenID Connect providers.
Package oidc implements logging in through OpenID Connect providers.
dex/connector/saml
Package saml contains login methods for SAML.
Package saml contains login methods for SAML.
dex/pkg/groups
Package groups contains helper functions related to groups
Package groups contains helper functions related to groups
dex/server
Package server implements an OpenID Connect server with federated logins.
Package server implements an OpenID Connect server with federated logins.
dex/storage
Package storage defines the storage interface and types used by the server.
Package storage defines the storage interface and types used by the server.
dex/storage/memory
Package memory provides an in memory implementation of the storage interface.
Package memory provides an in memory implementation of the storage interface.
Package pgstore is Postgres for the tables identity owns: the host injects a *sql.DB (and the driver), identity owns the SQL, authn stays database-free.
Package pgstore is Postgres for the tables identity owns: the host injects a *sql.DB (and the driver), identity owns the SQL, authn stays database-free.
Package service is Dex + OpenFGA + health as one Start/Stop Server, so a host (own pod, goroutine, or inside armornet) wires one object instead of four.
Package service is Dex + OpenFGA + health as one Start/Stop Server, so a host (own pod, goroutine, or inside armornet) wires one object instead of four.
Package web is browser sign-in on net/http: /api/auth/* from issuer bounce to session cookie, plus MFA.
Package web is browser sign-in on net/http: /api/auth/* from issuer bounce to session cookie, plus MFA.

Jump to

Keyboard shortcuts

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