Skip to content

Polaris for Go

Authentication and authorization for Go services, for users and for AI agents. Everything an auth system needs, self-hosted in your database, on net/http, with one import.

  • Complete. Accounts, MFA, sessions, organizations and roles, passwordless, passkeys, social sign-in, API keys, an OAuth 2.1 / OpenID Connect provider, SSO, SCIM, audit and risk scoring: the whole auth system, not a toolkit to assemble one.
  • Yours. Users live in your PostgreSQL, MySQL or SQLite database, next to your own tables. No hosted service, no per-user pricing, no data leaving your infrastructure.
  • Agents are first-class principals. An AI agent signs in with its own key, asks for grants a person approves, spends a budget, and leaves a signed, hash-chained receipt for every action. MCP servers take Polaris tokens.
  • Plain Go. An http.Handler for the auth routes, middleware for yours, context.Context everywhere, errors you match with errors.Is. polaristest gives your tests a server in one line.
  • Built to be integrated by coding agents. llms.txt is the whole integration on one page; every snippet in it is compiled by the test suite. Startup errors say how to fix them.
  • Careful where it matters. Argon2id, constant-time comparisons, rotating refresh tokens with reuse detection, fuzzed parsers, contract tests replaying every route, and a stable API checked on every pull request.
Terminal window
go get github.com/univeros/polaris.go
go install github.com/univeros/polaris.go/cmd/polaris@latest
polaris init # writes .env: APP_KEY, an RS256 key pair, AUTH_ISSUER
set -a && . ./.env && set +a # FromEnv reads the process environment
db, err := sqlstore.Open(ctx, store.Postgres, os.Getenv("DATABASE_URL"))
cfg, err := polaris.FromEnv(db) // APP_KEY, AUTH_JWT_*, AUTH_ISSUER; plugins go here too
p, err := polaris.New(cfg) // validates everything; every error says how to fix it
_, err = p.Migrate(ctx) // creates the missing tables; safe to run on every start
mux := http.NewServeMux()
mux.Handle("/", p.Handler()) // /auth/register, /auth/login, /auth/token/refresh, /orgs, …
mux.Handle("GET /api/invoices", p.Protect(invoicesHandler, "org.read"))

Inside your handler, the caller is one call away:

func invoices(w http.ResponseWriter, r *http.Request) {
who, _ := polaris.PrincipalFrom(r.Context())
fmt.Fprintf(w, "user %s in organization %s (%s)\n", who.UserID, who.OrganizationID, who.Kind)
}

p.Protect answers 401 without a principal and 403 without the permission. The principal can be a user, an API key, an OAuth client or an agent; the same check covers all of them. A complete program is in examples/minimal.

Databases: PostgreSQL 17, MySQL 8.4 (CI runs every suite on both) and SQLite (the bundled pure-Go driver, SQLite 3.54, no cgo). Other versions are untested. Migrate keeps the schema current across releases: it creates missing tables and adds missing columns and indexes, and never drops data.

More complete programs, each one POLARIS_DEV=1 go run away (throwaway keys, generated by polaris.DevEnv) with a curl walkthrough: agents (an AI agent end to end), mcp (your MCP server behind Polaris tokens), b2b (organizations, roles, invitations, API keys, SSO, SCIM), signin-methods (passwordless, passkeys, social, guests, MFA), hooks (your own tables, claims and transactions); and api-keys, which reads the environment as the quickstart does.

AreaIncluded
AccountsRegistration, email verification, password sign-in and reset (Argon2id, breached-password check), account disable, erase
MFATOTP, SMS and email codes, recovery codes, step-up for sensitive routes
SessionsShort-lived JWTs (RS256 or EdDSA, JWKS published), rotating refresh tokens with reuse detection, cookie or body delivery, sign out everywhere
OrganizationsMulti-tenant organizations, members, invitations, roles and permissions resolved per request, your own permissions in the catalog
Your dataHooks in the account’s transaction, your own JWT claims, a Go API (p.Users(), p.Orgs(), p.Sessions(), p.Can()) with the same rules as the routes
Migrationp.Users().Import brings existing accounts with their password hashes (bcrypt, PBKDF2, scrypt; from your own table, Auth0, Firebase, Django, Devise, Laravel): no forced reset, upgraded to Argon2id on first sign-in (Migrating your users)
OperationsOpenTelemetry traces and metrics, a CLI (init, migrate, doctor, schema:*, keys:generate), PostgreSQL, MySQL, SQLite

Add what your service needs; each plugin brings its own tables, routes, permissions and events.

cfg, err := polaris.FromEnv(db,
audit.New(audit.Config{}),
admin.New(admin.Config{}),
apikeys.New(apikeys.Config{}),
passkey.New(passkey.Config{RPID: "example.com", Origins: []string{"https://example.com"}}),
)
Sign-inWhat it does
passwordlessMagic links, email and phone codes, one-time hand-off tokens
passkeyWebAuthn sign-in; a passkey is also an MFA factor
social19 OAuth / OIDC providers and a generic one, account linking, Google One Tap
usernameCase-insensitive usernames; sign in with username or email
anonymousGuest sessions converted on sign-up
multisessionSeveral accounts per device, switch without signing in again
uiServer-rendered sign-in, sign-up, MFA, verification, reset and OAuth consent pages; no JavaScript
Machines and agentsWhat it does
apikeysUser and organization API keys, scoped to a subset of permissions, rate-limited, rotatable
oauthOAuth 2.1 / OIDC provider: PKCE, client credentials, device, CIBA, token exchange, DPoP, dynamic registration
agentsAgents as principals: grants, constraints, budgets, approvals, signed receipts, kill switch
mcpPolaris as an MCP server, and mcp.Protect for your own MCP servers
Enterprise and operationsWhat it does
ssoSAML 2.0 and OIDC per organization, verified domains, single logout
scimSCIM 2.0 provisioning per organization
adminOperator API for users, sessions, MFA, organizations and audit
auditAppend-only audit log, sinks and drains, optional hash chain
sentinelRisk engine: captcha, breached passwords, disposable domains, velocity, geo
messagingEmail and SMS delivery with templates, translations and send caps

Declare what agents may do in your service; Polaris checks the grant, its constraints and budget before your handler runs, and signs a receipt after.

ag := agents.New(agents.Config{Capabilities: []agents.Capability{{
Name: "invoices.list",
Description: "List invoices",
Permission: "org.read",
Risk: agents.RiskLow, // auto-approved, with a budget
Handler: func(ctx context.Context, call agents.Call) (any, error) {
return listInvoices(ctx, call.Agent)
},
}, {
Name: "refund",
Description: "Refund an invoice",
Permission: "billing.refund",
Risk: agents.RiskHigh, // a person approves, with step-up
Location: "https://app.example.com/api/refunds",
}}})
mux.Handle("POST /api/refunds", ag.Protect("refund", refundHandler))

The agent side is a Go SDK too:

key, _ := agent.GenerateKey(agent.EdDSA) // persist key.Export()
a, _ := agent.New(ctx, "https://app.example.com", agent.WithKey(key))
bot, _, err := a.Enroll(ctx, enrollmentToken, agent.Registration{Name: "Worker", Mode: agent.Delegated})
asked, _ := bot.RequestGrants(ctx, agent.GrantRequest{
Capabilities: []agent.CapabilityRequest{{Name: "refund"}},
})
if asked.Approval != nil {
_, err = bot.WaitForApproval(ctx, *asked.Approval) // a person approves
}
res, err := bot.Execute(ctx, "invoices.list", nil) // res.Receipt is the signed receipt
func TestSignUp(t *testing.T) {
srv := polaristest.New(t) // SQLite in a temp dir, test keys, recorded mail and SMS
req := httptest.NewRequest("POST", "/auth/register",
strings.NewReader(`{"email": "ada@example.com", "password": "correct horse battery staple"}`))
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
srv.Handler().ServeHTTP(rec, req)
if rec.Code != http.StatusAccepted || len(srv.Mailer.Sent()) != 1 {
t.Fatalf("register: %d, %d mails", rec.Code, len(srv.Mailer.Sent()))
}
}

srv.Handler() serves every route; srv.Mailer.Sent() holds the verification and reset emails; srv.Users() and srv.Sessions() set up state without HTTP; polaristest.WithPlugins(…) adds plugins.

ReadFor
llms.txtThe whole integration on one page: configuration, hooks, plugins, agents, MCP, testing, CLI, errors
Website docsThe same guides, rendered
plugins/<id>/README.mdPer plugin: configuration, routes, events, permissions, problems
pkg.go.devEvery exported identifier, with runnable examples
API.mdThe Go API promise: the host surface, the plugin SDK, the deprecation policy
docs/decisions.mdEvery design decision, with the reason

Polaris is 1.0. The Go API (API.md: every exported name outside internal/) does not break within v1, nor do the routes, and CI checks every pull request for it. Stored data (password hashes, encrypted secrets, issued tokens, the schema) stays readable across releases. It needs Go 1.26 or newer. CHANGELOG.md says what changes in each release, SECURITY.md which versions get fixes, and docs/v1.md what 1.0 had to meet.

Contributions go through pull requests with CI green; CONTRIBUTING.md has the workflow and AGENT.md the rules (tests first, make qa). Report a vulnerability privately through GitHub security advisories, not in an issue; SECURITY.md says what to include and what happens next.

MIT © 2026 2am.tech


Built and maintained by 2am.tech