Add SSO authorization code flow (Phase 1)

MCIAS now acts as an SSO provider for downstream services. Services
redirect users to /sso/authorize, MCIAS handles login (password, TOTP,
or passkey), then redirects back with an authorization code that the
service exchanges for a JWT via POST /v1/sso/token.

- Add SSO client registry to config (client_id, redirect_uri,
  service_name, tags) with validation
- Add internal/sso package: authorization code and session stores
  using sync.Map with TTL, single-use LoadAndDelete, cleanup goroutines
- Add GET /sso/authorize endpoint (validates client, creates session,
  redirects to /login?sso=<nonce>)
- Add POST /v1/sso/token endpoint (exchanges code for JWT with policy
  evaluation using client's service_name/tags from config)
- Thread SSO nonce through password→TOTP and WebAuthn login flows
- Update login.html, totp_step.html, and webauthn.js for SSO nonce
  passthrough

Security:
- Authorization codes are 256-bit random, single-use, 60-second TTL
- redirect_uri validated as exact match against registered config
- Policy context comes from MCIAS config, not the calling service
- SSO sessions are server-side only; nonce is the sole client-visible value
- WebAuthn SSO returns redirect URL as JSON (not HTTP redirect) for JS compat

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-03-30 15:21:48 -07:00
parent 5b5e1a7ed6
commit e450ade988
15 changed files with 809 additions and 13 deletions

View File

@@ -15,6 +15,7 @@ import (
func (u *UIServer) handleLoginPage(w http.ResponseWriter, r *http.Request) {
u.render(w, "login", LoginData{
WebAuthnEnabled: u.cfg.WebAuthnEnabled(),
SSONonce: r.URL.Query().Get("sso"),
})
}
@@ -97,6 +98,8 @@ func (u *UIServer) handleLoginPost(w http.ResponseWriter, r *http.Request) {
return
}
ssoNonce := r.FormValue("sso_nonce")
// TOTP required: issue a server-side nonce and show the TOTP step form.
// Security: the nonce replaces the password hidden field (F-02). The password
// is not stored anywhere after this point; only the account ID is retained.
@@ -110,11 +113,12 @@ func (u *UIServer) handleLoginPost(w http.ResponseWriter, r *http.Request) {
u.render(w, "totp_step", LoginData{
Username: username,
Nonce: nonce,
SSONonce: ssoNonce,
})
return
}
u.finishLogin(w, r, acct)
u.finishLogin(w, r, acct, ssoNonce)
}
// handleTOTPStep handles the second POST when totp_step=1 is set.
@@ -129,6 +133,7 @@ func (u *UIServer) handleTOTPStep(w http.ResponseWriter, r *http.Request) {
username := r.FormValue("username") //nolint:gosec // body already limited by caller
nonce := r.FormValue("totp_nonce") //nolint:gosec // body already limited by caller
totpCode := r.FormValue("totp_code") //nolint:gosec // body already limited by caller
ssoNonce := r.FormValue("sso_nonce") //nolint:gosec // body already limited by caller
// Security: consume the nonce (single-use); reject if unknown or expired.
accountID, ok := u.consumeTOTPNonce(nonce)
@@ -172,6 +177,7 @@ func (u *UIServer) handleTOTPStep(w http.ResponseWriter, r *http.Request) {
Error: "invalid TOTP code",
Username: username,
Nonce: newNonce,
SSONonce: ssoNonce,
})
return
}
@@ -189,15 +195,28 @@ func (u *UIServer) handleTOTPStep(w http.ResponseWriter, r *http.Request) {
Error: "invalid TOTP code",
Username: username,
Nonce: newNonce,
SSONonce: ssoNonce,
})
return
}
u.finishLogin(w, r, acct)
u.finishLogin(w, r, acct, ssoNonce)
}
// finishLogin issues a JWT, sets the session cookie, and redirects to dashboard.
func (u *UIServer) finishLogin(w http.ResponseWriter, r *http.Request, acct *model.Account) {
// When ssoNonce is non-empty, the login is part of an SSO redirect flow: instead
// of setting a session cookie, an authorization code is issued and the user is
// redirected back to the service's callback URL.
func (u *UIServer) finishLogin(w http.ResponseWriter, r *http.Request, acct *model.Account, ssoNonce string) {
// SSO redirect flow: issue authorization code and redirect to service.
if ssoNonce != "" {
if callbackURL, ok := u.buildSSOCallback(r, ssoNonce, acct.ID); ok {
http.Redirect(w, r, callbackURL, http.StatusFound)
return
}
// SSO session expired/consumed — fall through to normal login.
}
// Determine token expiry based on admin role.
expiry := u.cfg.DefaultExpiry()
roles, err := u.db.GetRoles(acct.ID)

View File

@@ -0,0 +1,84 @@
package ui
import (
"net/http"
"net/url"
"git.wntrmute.dev/mc/mcias/internal/audit"
"git.wntrmute.dev/mc/mcias/internal/model"
"git.wntrmute.dev/mc/mcias/internal/sso"
)
// handleSSOAuthorize validates the SSO request parameters against registered
// clients, creates an SSO session, and redirects to /login with the SSO nonce.
//
// Security: the client_id and redirect_uri are validated against the MCIAS
// config (exact match). The state parameter is opaque and carried through
// unchanged. An SSO session is created server-side so the nonce is the only
// value embedded in the login form.
func (u *UIServer) handleSSOAuthorize(w http.ResponseWriter, r *http.Request) {
clientID := r.URL.Query().Get("client_id")
redirectURI := r.URL.Query().Get("redirect_uri")
state := r.URL.Query().Get("state")
if clientID == "" || redirectURI == "" || state == "" {
http.Error(w, "missing required parameters: client_id, redirect_uri, state", http.StatusBadRequest)
return
}
// Security: validate client_id against registered SSO clients.
client := u.cfg.SSOClient(clientID)
if client == nil {
u.logger.Warn("sso: unknown client_id", "client_id", clientID)
http.Error(w, "unknown client_id", http.StatusBadRequest)
return
}
// Security: redirect_uri must exactly match the registered URI to prevent
// open-redirect attacks.
if redirectURI != client.RedirectURI {
u.logger.Warn("sso: redirect_uri mismatch",
"client_id", clientID,
"expected", client.RedirectURI,
"got", redirectURI)
http.Error(w, "redirect_uri does not match registered URI", http.StatusBadRequest)
return
}
nonce, err := sso.StoreSession(clientID, redirectURI, state)
if err != nil {
u.logger.Error("sso: store session", "error", err)
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
u.writeAudit(r, model.EventSSOAuthorize, nil, nil,
audit.JSON("client_id", clientID))
http.Redirect(w, r, "/login?sso="+url.QueryEscape(nonce), http.StatusFound)
}
// buildSSOCallback consumes the SSO session, generates an authorization code,
// and returns the callback URL with code and state parameters. Returns ("", false)
// if the SSO session is expired or already consumed.
//
// Security: the SSO session is consumed (single-use) and the authorization code
// is stored server-side for exchange via POST /v1/sso/token. The state parameter
// is carried through unchanged for the service to validate.
func (u *UIServer) buildSSOCallback(r *http.Request, ssoNonce string, accountID int64) (string, bool) {
sess, ok := sso.ConsumeSession(ssoNonce)
if !ok {
return "", false
}
code, err := sso.Store(sess.ClientID, sess.RedirectURI, sess.State, accountID)
if err != nil {
u.logger.Error("sso: store auth code", "error", err)
return "", false
}
u.writeAudit(r, model.EventSSOLoginOK, &accountID, nil,
audit.JSON("client_id", sess.ClientID))
return sess.RedirectURI + "?code=" + url.QueryEscape(code) + "&state=" + url.QueryEscape(sess.State), true
}

View File

@@ -27,10 +27,11 @@ const (
)
// webauthnCeremony holds a pending WebAuthn ceremony.
type webauthnCeremony struct {
type webauthnCeremony struct { //nolint:govet // fieldalignment: field order matches logical grouping
expiresAt time.Time
session *libwebauthn.SessionData
accountID int64
ssoNonce string // non-empty when login is part of an SSO redirect flow
}
// pendingWebAuthnCeremonies stores in-flight WebAuthn ceremonies for the UI.
@@ -55,7 +56,7 @@ func cleanupUIWebAuthnCeremonies() {
}
}
func storeUICeremony(session *libwebauthn.SessionData, accountID int64) (string, error) {
func storeUICeremony(session *libwebauthn.SessionData, accountID int64, ssoNonce string) (string, error) {
raw, err := crypto.RandomBytes(webauthnNonceBytes)
if err != nil {
return "", fmt.Errorf("webauthn: generate ceremony nonce: %w", err)
@@ -64,6 +65,7 @@ func storeUICeremony(session *libwebauthn.SessionData, accountID int64) (string,
pendingUIWebAuthnCeremonies.Store(nonce, &webauthnCeremony{
session: session,
accountID: accountID,
ssoNonce: ssoNonce,
expiresAt: time.Now().Add(webauthnCeremonyTTL),
})
return nonce, nil
@@ -170,7 +172,7 @@ func (u *UIServer) handleWebAuthnBegin(w http.ResponseWriter, r *http.Request) {
return
}
nonce, err := storeUICeremony(session, acct.ID)
nonce, err := storeUICeremony(session, acct.ID, "")
if err != nil {
writeJSONError(w, http.StatusInternalServerError, "internal error")
return
@@ -352,6 +354,7 @@ func (u *UIServer) handleWebAuthnLoginBegin(w http.ResponseWriter, r *http.Reque
r.Body = http.MaxBytesReader(w, r.Body, maxFormBytes)
var req struct {
Username string `json:"username"`
SSONonce string `json:"sso_nonce"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeJSONError(w, http.StatusBadRequest, "invalid JSON")
@@ -413,7 +416,7 @@ func (u *UIServer) handleWebAuthnLoginBegin(w http.ResponseWriter, r *http.Reque
return
}
nonce, err := storeUICeremony(session, accountID)
nonce, err := storeUICeremony(session, accountID, req.SSONonce)
if err != nil {
writeJSONError(w, http.StatusInternalServerError, "internal error")
return
@@ -582,6 +585,17 @@ func (u *UIServer) handleWebAuthnLoginFinish(w http.ResponseWriter, r *http.Requ
_ = u.db.ClearLoginFailures(acct.ID)
// SSO redirect flow: issue authorization code and return redirect URL as JSON.
if ceremony.ssoNonce != "" {
if callbackURL, ok := u.buildSSOCallback(r, ceremony.ssoNonce, acct.ID); ok {
u.writeAudit(r, model.EventWebAuthnLoginOK, &acct.ID, nil, "")
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]string{"redirect": callbackURL})
return
}
// SSO session expired — fall through to normal login.
}
// Issue JWT and set session cookie.
expiry := u.cfg.DefaultExpiry()
roles, err := u.db.GetRoles(acct.ID)

View File

@@ -445,6 +445,9 @@ func (u *UIServer) Register(mux *http.ServeMux) {
uiMux.HandleFunc("GET /unseal", u.handleUnsealPage)
uiMux.Handle("POST /unseal", unsealRateLimit(http.HandlerFunc(u.handleUnsealPost)))
// SSO authorize route (no session required, rate-limited).
uiMux.Handle("GET /sso/authorize", loginRateLimit(http.HandlerFunc(u.handleSSOAuthorize)))
// Auth routes (no session required).
uiMux.HandleFunc("GET /login", u.handleLoginPage)
uiMux.Handle("POST /login", loginRateLimit(http.HandlerFunc(u.handleLoginPost)))
@@ -810,6 +813,7 @@ type PageData struct {
type LoginData struct {
Error string
Username string // pre-filled on TOTP step
SSONonce string // SSO session nonce (hidden field for SSO redirect flow)
// Security (F-02): Password is no longer carried in the HTML form. Instead
// a short-lived server-side nonce is issued after successful password
// verification, and only the nonce is embedded in the TOTP step form.