Add OIDC login via Authentik: PKCE, JIT provisioning, email linking (#5)
OIDC is pansy's primary login path (Authentik the target IdP); local auth (#4) remains the fallback and both issue the same session cookie. - deps: github.com/coreos/go-oidc/v3 + golang.org/x/oauth2 (both pure Go; CGO stays off). - api/oidc.go: lazy issuer discovery (retried per-request, never crashes a server that also serves local auth), GET /auth/oidc/login builds an authorization-code URL with PKCE S256 + random state + nonce stashed in a short-lived HttpOnly cookie, GET /auth/oidc/callback verifies state (constant-time), exchanges the code with the PKCE verifier, verifies the ID token + nonce, and starts a pansy session. Failures redirect to /login?error=... ; success to /gardens. - service.LoginOIDC: (issuer,subject) match -> login; else *verified* email match -> link onto the existing account; else JIT-create (the IdP gates access, so PANSY_REGISTRATION doesn't apply). Unverified email colliding with an existing account is refused (takeover guard); no email is refused (email is the account key). Reuses the atomic CreateUser. - store: GetUserByOIDC + LinkOIDC (unique-pair backstop). - config: OIDCReady() (needs issuer+client+BaseURL for the redirect URI); /auth/providers now reports oidc from it and defaults the button label to "Sign in with Authentik". OIDC routes are only registered when ready, so an unconfigured instance 404s them. - PANSY_LOCAL_AUTH=false rejects/hides local auth but not OIDC. Tests: service provisioning (JIT, repeat login, link, unverified-collision refusal, no-email, name fallback, works with local auth off); api (routes-absent-when-unconfigured, providers reporting, login redirect with PKCE params + tx cookie via a fake discovery server, callback state/error paths). Smoke-tested: unreachable issuer degrades to error=oidc_unavailable with the server still up and local auth working. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01JdQpdYYsTgtkJBxbcpAszi
This commit is contained in:
@@ -30,17 +30,84 @@ type Providers struct {
|
||||
OIDCLabel string `json:"oidcLabel"`
|
||||
}
|
||||
|
||||
// Providers returns the enabled auth methods. OIDC is always false until #5
|
||||
// wires the endpoints; advertising it before then would point the UI at routes
|
||||
// that don't exist.
|
||||
// OIDCIdentity is the set of claims the API layer extracts from a verified ID
|
||||
// token and hands to LoginOIDC for provisioning. Issuer and Subject come from
|
||||
// the verified token (not raw claims); Email/Name come from claims.
|
||||
type OIDCIdentity struct {
|
||||
Issuer string
|
||||
Subject string
|
||||
Email string
|
||||
EmailVerified bool
|
||||
Name string
|
||||
}
|
||||
|
||||
// Providers returns the enabled auth methods, so the login page renders the
|
||||
// right controls. OIDC is reported only when it can actually be offered (issuer,
|
||||
// client ID, and a BaseURL for the redirect URI), matching the routes that
|
||||
// api.New registers.
|
||||
func (s *Service) Providers() Providers {
|
||||
return Providers{
|
||||
Local: s.cfg.LocalAuth,
|
||||
OIDC: false,
|
||||
OIDC: s.cfg.OIDCReady(),
|
||||
OIDCLabel: s.cfg.OIDC.ButtonLabel,
|
||||
}
|
||||
}
|
||||
|
||||
// LoginOIDC provisions and returns the pansy user for a verified OIDC identity,
|
||||
// issuing no session itself (the caller does). The IdP has already gated access,
|
||||
// so PANSY_REGISTRATION does not apply. Resolution order:
|
||||
// 1. an existing user with the same (issuer, subject) — a returning OIDC user;
|
||||
// 2. else an existing user with the same *verified* email — linked to this
|
||||
// identity (so one person isn't split across a local and an OIDC account);
|
||||
// 3. else a new just-in-time account stamped with the identity.
|
||||
//
|
||||
// An unverified email that collides with an existing account is refused (it
|
||||
// would let anyone who can assert that email at the IdP take over the account).
|
||||
// An identity with no email can't be provisioned (email is the account key).
|
||||
func (s *Service) LoginOIDC(ctx context.Context, id OIDCIdentity) (*domain.User, error) {
|
||||
if id.Issuer == "" || id.Subject == "" {
|
||||
return nil, domain.ErrInvalidInput
|
||||
}
|
||||
|
||||
// 1. Returning OIDC user.
|
||||
u, err := s.store.GetUserByOIDC(ctx, id.Issuer, id.Subject)
|
||||
if err == nil {
|
||||
return u, nil
|
||||
}
|
||||
if !errors.Is(err, domain.ErrNotFound) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
email := normalizeEmail(id.Email)
|
||||
if email == "" {
|
||||
return nil, domain.ErrOIDCNoEmail
|
||||
}
|
||||
|
||||
// 2. Link to an existing account by email — but only a verified one.
|
||||
existing, err := s.store.GetUserByEmail(ctx, email)
|
||||
switch {
|
||||
case err == nil:
|
||||
if !id.EmailVerified {
|
||||
return nil, domain.ErrOIDCEmailUnverified
|
||||
}
|
||||
return s.store.LinkOIDC(ctx, existing.ID, id.Issuer, id.Subject)
|
||||
case !errors.Is(err, domain.ErrNotFound):
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 3. Just-in-time provisioning.
|
||||
name := strings.TrimSpace(id.Name)
|
||||
if name == "" {
|
||||
name = emailLocalPart(email)
|
||||
}
|
||||
return s.store.CreateUser(ctx, &domain.User{
|
||||
Email: email,
|
||||
DisplayName: name,
|
||||
OIDCIssuer: &id.Issuer,
|
||||
OIDCSubject: &id.Subject,
|
||||
}, true) // allowSignup: the IdP gates access, so registration policy is bypassed.
|
||||
}
|
||||
|
||||
// Register creates a local (password) account and returns it. The first user on
|
||||
// a fresh instance becomes admin and may always register (bootstrap), even when
|
||||
// PANSY_REGISTRATION=closed; afterward, closed registration is enforced.
|
||||
@@ -208,3 +275,12 @@ func (s *Service) CleanupExpiredSessions(ctx context.Context) (int64, error) {
|
||||
func normalizeEmail(email string) string {
|
||||
return strings.ToLower(strings.TrimSpace(email))
|
||||
}
|
||||
|
||||
// emailLocalPart returns the portion of an email before '@', used as a fallback
|
||||
// display name for JIT-provisioned OIDC users whose token carried no name.
|
||||
func emailLocalPart(email string) string {
|
||||
if i := strings.IndexByte(email, '@'); i > 0 {
|
||||
return email[:i]
|
||||
}
|
||||
return email
|
||||
}
|
||||
|
||||
@@ -280,15 +280,112 @@ func TestCleanupExpiredSessions(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestProvidersReflectsConfig(t *testing.T) {
|
||||
cfg := openConfig()
|
||||
cfg.OIDC.ButtonLabel = "Sign in with Authentik"
|
||||
s := newTestService(t, cfg)
|
||||
|
||||
// No OIDC configured → local only.
|
||||
s := newTestService(t, openConfig())
|
||||
p := s.Providers()
|
||||
if !p.Local {
|
||||
t.Error("expected local=true")
|
||||
if !p.Local || p.OIDC {
|
||||
t.Errorf("providers = %+v, want local=true oidc=false", p)
|
||||
}
|
||||
if p.OIDC {
|
||||
t.Error("OIDC must be false until #5 wires it")
|
||||
|
||||
// OIDC configured with a base URL → reported ready.
|
||||
ready := openConfig()
|
||||
ready.BaseURL = "https://pansy.example.com"
|
||||
ready.OIDC = config.OIDCConfig{Issuer: "https://idp.example", ClientID: "cid", ButtonLabel: "Sign in with Authentik"}
|
||||
if got := newTestService(t, ready).Providers(); !got.OIDC || got.OIDCLabel != "Sign in with Authentik" {
|
||||
t.Errorf("providers = %+v, want oidc=true with Authentik label", got)
|
||||
}
|
||||
|
||||
// OIDC configured but no base URL → not ready (can't build a redirect URI).
|
||||
noBase := openConfig()
|
||||
noBase.OIDC = config.OIDCConfig{Issuer: "https://idp.example", ClientID: "cid"}
|
||||
if got := newTestService(t, noBase).Providers(); got.OIDC {
|
||||
t.Error("OIDC should be false without a base URL")
|
||||
}
|
||||
}
|
||||
|
||||
func oidcIdentity(sub, email, name string, verified bool) OIDCIdentity {
|
||||
return OIDCIdentity{Issuer: "https://idp.example", Subject: sub, Email: email, EmailVerified: verified, Name: name}
|
||||
}
|
||||
|
||||
func TestLoginOIDCJITProvisionsThenReturnsSameUser(t *testing.T) {
|
||||
s := newTestService(t, openConfig())
|
||||
|
||||
u, err := s.LoginOIDC(context.Background(), oidcIdentity("sub-1", "[email protected]", "Alice", true))
|
||||
if err != nil {
|
||||
t.Fatalf("LoginOIDC create: %v", err)
|
||||
}
|
||||
if !u.IsAdmin {
|
||||
t.Error("first provisioned OIDC user should be admin")
|
||||
}
|
||||
if u.OIDCSubject == nil || *u.OIDCSubject != "sub-1" {
|
||||
t.Errorf("oidc subject not stamped: %+v", u.OIDCSubject)
|
||||
}
|
||||
|
||||
// A second login with the same identity returns the same user (no duplicate).
|
||||
again, err := s.LoginOIDC(context.Background(), oidcIdentity("sub-1", "[email protected]", "Alice", true))
|
||||
if err != nil {
|
||||
t.Fatalf("LoginOIDC repeat: %v", err)
|
||||
}
|
||||
if again.ID != u.ID {
|
||||
t.Errorf("repeat login made a new user: %d vs %d", again.ID, u.ID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoginOIDCLinksExistingLocalAccount(t *testing.T) {
|
||||
s := newTestService(t, openConfig())
|
||||
local := mustRegister(t, s, "[email protected]", "Bob", "password123")
|
||||
|
||||
linked, err := s.LoginOIDC(context.Background(), oidcIdentity("sub-2", "[email protected]", "Bob", true))
|
||||
if err != nil {
|
||||
t.Fatalf("LoginOIDC link: %v", err)
|
||||
}
|
||||
if linked.ID != local.ID {
|
||||
t.Errorf("linked to a new user %d, want existing %d", linked.ID, local.ID)
|
||||
}
|
||||
if linked.OIDCSubject == nil || *linked.OIDCSubject != "sub-2" {
|
||||
t.Error("existing account was not stamped with the oidc identity")
|
||||
}
|
||||
// Local password still works after linking (one account, two methods).
|
||||
if _, err := s.Login(context.Background(), "[email protected]", "password123"); err != nil {
|
||||
t.Errorf("local login after linking failed: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoginOIDCRefusesUnverifiedEmailCollision(t *testing.T) {
|
||||
s := newTestService(t, openConfig())
|
||||
mustRegister(t, s, "[email protected]", "Carol", "password123")
|
||||
|
||||
_, err := s.LoginOIDC(context.Background(), oidcIdentity("sub-3", "[email protected]", "Carol", false))
|
||||
if !errors.Is(err, domain.ErrOIDCEmailUnverified) {
|
||||
t.Errorf("unverified collision err = %v, want ErrOIDCEmailUnverified", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoginOIDCRequiresEmail(t *testing.T) {
|
||||
s := newTestService(t, openConfig())
|
||||
_, err := s.LoginOIDC(context.Background(), oidcIdentity("sub-4", "", "No Email", true))
|
||||
if !errors.Is(err, domain.ErrOIDCNoEmail) {
|
||||
t.Errorf("no-email err = %v, want ErrOIDCNoEmail", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoginOIDCFallsBackToEmailLocalPartForName(t *testing.T) {
|
||||
s := newTestService(t, openConfig())
|
||||
u, err := s.LoginOIDC(context.Background(), oidcIdentity("sub-5", "[email protected]", "", true))
|
||||
if err != nil {
|
||||
t.Fatalf("LoginOIDC: %v", err)
|
||||
}
|
||||
if u.DisplayName != "dave" {
|
||||
t.Errorf("display name = %q, want %q", u.DisplayName, "dave")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLocalAuthDisabledDoesNotBlockOIDC(t *testing.T) {
|
||||
cfg := openConfig()
|
||||
cfg.LocalAuth = false
|
||||
s := newTestService(t, cfg)
|
||||
// OIDC provisioning must work even when local auth is off (pure-Authentik).
|
||||
if _, err := s.LoginOIDC(context.Background(), oidcIdentity("sub-6", "[email protected]", "Erin", true)); err != nil {
|
||||
t.Errorf("LoginOIDC with local auth disabled: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user