Let UI OIDC clients learn redirect URIs on first sign-in

New per-client option learn_redirects (admin API and client dialog).
An unknown redirect_uri is accepted for such a client, and stored
after the user signed in and passed the group policy. Only confidential
UI clients can use it: the client secret is still needed to redeem a
code. Kubernetes and CLIENTS_FILE clients are refused, since their sync
would overwrite the list. Each learned URI is recorded as a
redirect_learned event. Migration 202611071700_learn_redirects.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
This commit is contained in:
Jonas Leder 2026-11-08 15:42:48 +01:00
commit b44e3700f5
14 changed files with 193 additions and 30 deletions

View file

@ -13,6 +13,7 @@ A small OIDC provider with Traefik forward auth and a user account UI. Go backen
|---|---|
| OIDC code flow with PKCE, token, userinfo, discovery, JWKS | done |
| OIDC RP-initiated logout at `/oauth2/logout` (`id_token_hint` may be expired, `post_logout_redirect_uri` must be a registered redirect URI, `state`), advertised as `end_session_endpoint` | done, unit tested, not tried with a real relying party |
| Optional per UI client: add an unknown redirect URI on first sign-in (confidential clients only; not for Kubernetes or `CLIENTS_FILE` clients; stored after the sign-in and group check, audited as `redirect_learned`) | done, unit tested, not checked in a browser |
| OIDC redirect URIs: http(s) or a custom app scheme such as `app.immich:///oauth-callback`; script and data schemes refused; authorization still needs an exact match with a registered URI | done, unit tested |
| SAML identity provider (metadata, SSO with Redirect and POST binding, signed assertions, groups) | done |
| Traefik ForwardAuth (`/auth/forward`, optional `?policy=`) | done |

View file

@ -2060,6 +2060,9 @@ const docTemplate = `{
"id": {
"type": "integer"
},
"learn_redirects": {
"type": "boolean"
},
"name": {
"type": "string"
},
@ -2095,6 +2098,10 @@ const docTemplate = `{
"type": "string",
"maxLength": 190
},
"learn_redirects": {
"description": "LearnRedirects adds an unknown redirect URI on the first sign-in. Only for confidential clients made in the UI.",
"type": "boolean"
},
"name": {
"type": "string",
"maxLength": 190

View file

@ -2053,6 +2053,9 @@
"id": {
"type": "integer"
},
"learn_redirects": {
"type": "boolean"
},
"name": {
"type": "string"
},
@ -2088,6 +2091,10 @@
"type": "string",
"maxLength": 190
},
"learn_redirects": {
"description": "LearnRedirects adds an unknown redirect URI on the first sign-in. Only for confidential clients made in the UI.",
"type": "boolean"
},
"name": {
"type": "string",
"maxLength": 190

View file

@ -44,6 +44,8 @@ definitions:
type: string
id:
type: integer
learn_redirects:
type: boolean
name:
type: string
public:
@ -65,6 +67,10 @@ definitions:
description: empty = generated
maxLength: 190
type: string
learn_redirects:
description: LearnRedirects adds an unknown redirect URI on the first sign-in.
Only for confidential clients made in the UI.
type: boolean
name:
maxLength: 190
type: string

View file

@ -46,6 +46,7 @@ func migrations() []*gormigrate.Migration {
migrationUserGroups(),
migrationUserNames(),
migrationCrdGroups(),
migrationLearnRedirects(),
}
}

View file

@ -24,7 +24,7 @@ import (
//
// A model change fails TestModelsMatchTheRecordedFingerprint. That is the reminder to add a migration to
// migrations() in migrate.go and then update this value (the failure message prints the new one).
const modelsFingerprint = "0f2cf3357680e2cc6033b80520ebecffd858af5803bd97bf1b9134a4418ee725"
const modelsFingerprint = "f13bbbe295bf389d5e0b31e1d1efb7fbc01186c4b2b523f172cd5aece1b86555"
func fingerprint(t *testing.T, db *gorm.DB) string {
t.Helper()

View file

@ -0,0 +1,20 @@
package database
import (
"github.com/go-gormigrate/gormigrate/v2"
"gorm.io/gorm"
)
// migrationLearnRedirects is migration 202611071700_learn_redirects.
func migrationLearnRedirects() *gormigrate.Migration {
return &gormigrate.Migration{
ID: "202611071700_learn_redirects",
Migrate: func(tx *gorm.DB) error {
type learn struct { // frozen copy of the column added to clients as of this migration
LearnRedirects bool `gorm:"not null;default:false"`
}
// Existing clients keep exact matching.
return tx.Table("clients").Migrator().AddColumn(&learn{}, "LearnRedirects")
},
}
}

View file

@ -68,15 +68,16 @@ func (u User) GroupList() []string {
// Client is an OIDC relying party (an application registered with this server).
type Client struct {
ID uint `gorm:"primaryKey"`
ClientID string `gorm:"uniqueIndex;size:190;not null"`
Name string
SecretHash string // empty for public clients (PKCE only)
RedirectURIs string // comma separated, exact match
AllowedGroups string // comma separated policy. Empty = every enabled user may sign in
Source string `gorm:"size:8;not null;default:ui"`
Ref string `gorm:"size:253"` // namespace/name of the owning custom resource
CreatedAt time.Time
ID uint `gorm:"primaryKey"`
ClientID string `gorm:"uniqueIndex;size:190;not null"`
Name string
SecretHash string // empty for public clients (PKCE only)
RedirectURIs string // comma separated, exact match
LearnRedirects bool `gorm:"not null;default:false"` // UI clients with a secret: a new redirect URI is added on first sign-in
AllowedGroups string // comma separated policy. Empty = every enabled user may sign in
Source string `gorm:"size:8;not null;default:ui"`
Ref string `gorm:"size:253"` // namespace/name of the owning custom resource
CreatedAt time.Time
}
// RedirectURIList returns the registered redirect URIs.
@ -178,6 +179,7 @@ const (
EventTOTPEnabled = "totp_enabled"
EventTOTPDisabled = "totp_disabled"
EventPasskeyAdded = "passkey_added"
EventRedirectLearned = "redirect_learned"
EventPasskeyRemoved = "passkey_removed"
EventReset2FA = "mfa_reset_by_admin"
EventRecoveryUsed = "recovery_code_used"

View file

@ -359,19 +359,20 @@ func (s *Server) reset2FA(c *gin.Context) {
// ClientDTO is an OIDC client. ClientSecret is only set in the response that creates or rotates it.
type ClientDTO struct {
ID uint `json:"id"`
ClientID string `json:"client_id"`
Name string `json:"name"`
Public bool `json:"public"`
RedirectURIs []string `json:"redirect_uris"`
AllowedGroups []string `json:"allowed_groups"`
Source string `json:"source"`
ClientSecret string `json:"client_secret,omitempty"`
ID uint `json:"id"`
ClientID string `json:"client_id"`
Name string `json:"name"`
Public bool `json:"public"`
RedirectURIs []string `json:"redirect_uris"`
AllowedGroups []string `json:"allowed_groups"`
LearnRedirects bool `json:"learn_redirects"`
Source string `json:"source"`
ClientSecret string `json:"client_secret,omitempty"`
}
func clientDTO(c model.Client) ClientDTO {
return ClientDTO{ID: c.ID, ClientID: c.ClientID, Name: c.Name, Public: c.SecretHash == "", RedirectURIs: list(c.RedirectURIList()),
AllowedGroups: list(model.SplitList(c.AllowedGroups)), Source: c.Source}
AllowedGroups: list(model.SplitList(c.AllowedGroups)), LearnRedirects: c.LearnRedirects, Source: c.Source}
}
// listClients godoc
@ -397,8 +398,14 @@ type ClientRequest struct {
Public bool `json:"public"`
RedirectURIs []string `json:"redirect_uris" binding:"required,min=1"`
AllowedGroups []string `json:"allowed_groups"`
// LearnRedirects adds an unknown redirect URI on the first sign-in. Only for confidential clients made in the UI.
LearnRedirects bool `json:"learn_redirects"`
}
// learnAllowed says whether a client may learn redirect URIs: a secret is needed to redeem a code, and
// clients from Kubernetes or CLIENTS_FILE are overwritten at the next sync.
func learnAllowed(source string, public bool) bool { return !public && source == model.SourceUI }
func newSecret() (plain, hash string, err error) {
plain, err = auth.RandomToken()
if err != nil {
@ -437,7 +444,11 @@ func (s *Server) createClient(c *gin.Context) {
}
req.ClientID = "c_" + id[:16]
}
cl := model.Client{ClientID: req.ClientID, Name: req.Name, RedirectURIs: model.JoinList(req.RedirectURIs), AllowedGroups: model.JoinList(req.AllowedGroups), Source: model.SourceUI, CreatedAt: time.Now()}
if req.LearnRedirects && !learnAllowed(model.SourceUI, req.Public) {
errorJSON(c, http.StatusBadRequest, "only confidential clients can learn redirect URIs")
return
}
cl := model.Client{ClientID: req.ClientID, Name: req.Name, RedirectURIs: model.JoinList(req.RedirectURIs), AllowedGroups: model.JoinList(req.AllowedGroups), LearnRedirects: req.LearnRedirects, Source: model.SourceUI, CreatedAt: time.Now()}
secret := ""
if !req.Public {
var err error
@ -488,7 +499,11 @@ func (s *Server) updateClient(c *gin.Context) {
return
}
}
cl.Name, cl.RedirectURIs, cl.AllowedGroups = req.Name, model.JoinList(req.RedirectURIs), model.JoinList(req.AllowedGroups)
if req.LearnRedirects && !learnAllowed(cl.Source, cl.SecretHash == "") {
errorJSON(c, http.StatusBadRequest, "only confidential clients can learn redirect URIs")
return
}
cl.Name, cl.RedirectURIs, cl.AllowedGroups, cl.LearnRedirects = req.Name, model.JoinList(req.RedirectURIs), model.JoinList(req.AllowedGroups), req.LearnRedirects
s.db.Save(&cl)
c.JSON(http.StatusOK, clientDTO(cl))
}

View file

@ -0,0 +1,62 @@
package server
import (
"net/http"
"slices"
"strings"
"testing"
"jonasled.dev/jonasled/auth-server/internal/model"
)
func TestClientLearnsRedirectOnFirstSignIn(t *testing.T) {
f := newFixture(t)
const learned = "https://new.example.test/cb"
rec := f.adminDo(http.MethodPost, "/clients", map[string]any{"name": "Learner", "redirect_uris": []string{redirectApp}, "learn_redirects": true})
if rec.Code != http.StatusCreated {
t.Fatalf("create = %d %s", rec.Code, rec.Body)
}
cl := decode[ClientDTO](t, rec.Body.Bytes())
if !cl.LearnRedirects {
t.Fatal("learn_redirects not returned")
}
if bad := f.adminDo(http.MethodPost, "/clients", map[string]any{"name": "SPA", "public": true, "learn_redirects": true, "redirect_uris": []string{redirectApp}}); bad.Code != http.StatusBadRequest {
t.Fatalf("public client learning = %d, want 400", bad.Code)
}
var stored model.Client
authz := authorizeURL(cl.ClientID, learned, pkceChallenge(verifier))
// Anonymous visitors store nothing: they are sent to sign in first.
if rec := f.do(http.MethodGet, authz, nil, "", nil); !strings.HasPrefix(rec.Header().Get("Location"), issuer+"/login?next=") {
t.Fatalf("anonymous = %d %q", rec.Code, rec.Header().Get("Location"))
}
f.db.First(&stored, cl.ID)
if slices.Contains(stored.RedirectURIList(), learned) {
t.Fatal("URI stored before sign-in")
}
// After sign-in the code goes to the new URI, and the URI is stored once.
s := f.login("alice", password)
rec = f.do(http.MethodGet, authz, nil, s, nil)
if loc := locationOf(t, rec); rec.Code != http.StatusFound || !strings.HasPrefix(loc.String(), learned+"?code=") {
t.Fatalf("signed in = %d %q", rec.Code, rec.Header().Get("Location"))
}
f.do(http.MethodGet, authz, nil, s, nil)
f.db.First(&stored, cl.ID)
if n := len(stored.RedirectURIList()); n != 2 || !slices.Contains(stored.RedirectURIList(), learned) {
t.Fatalf("stored redirects = %v", stored.RedirectURIList())
}
var events int64
f.db.Model(&model.AuthEvent{}).Where("type = ?", model.EventRedirectLearned).Count(&events)
if events != 1 {
t.Fatalf("learned events = %d, want 1", events)
}
// A client without the option still refuses unknown URIs.
info := f.errorPage(t, f.do(http.MethodGet, authorizeURL("app", "https://other.example.test/cb", pkceChallenge(verifier)), nil, s, nil))
if info.Code != ErrInvalidRedirect {
t.Fatalf("exact-match client: %+v", info)
}
}

View file

@ -97,18 +97,28 @@ func (s *Server) authorize(c *gin.Context) {
s.showError(c, errorContext{Code: ErrInvalidClient, Detail: "client_id: " + q.Get("client_id")})
return
}
if !slices.Contains(client.RedirectURIList(), q.Get("redirect_uri")) {
s.showError(c, errorContext{Code: ErrInvalidRedirect, App: client.Name, Detail: "redirect_uri: " + q.Get("redirect_uri")})
redirect := q.Get("redirect_uri")
// An unknown URI is only taken from a client that learns URIs. It is stored after the sign-in and group check.
registered := slices.Contains(client.RedirectURIList(), redirect)
if !registered && !(client.LearnRedirects && learnAllowed(client.Source, client.SecretHash == "") && validRedirectURI(redirect)) {
s.showError(c, errorContext{Code: ErrInvalidRedirect, App: client.Name, Detail: "redirect_uri: " + redirect})
return
}
redirect := q.Get("redirect_uri")
// Errors go to the redirect URI only when it is registered. Before that it is untrusted.
fail := func(code, desc string) {
if registered {
s.redirectError(c, redirect, q.Get("state"), code, desc)
return
}
c.String(http.StatusBadRequest, desc)
}
if q.Get("response_type") != "code" || !slices.Contains(strings.Fields(q.Get("scope")), oidcScope) {
s.redirectError(c, redirect, q.Get("state"), "invalid_request", "response_type must be code and scope must include openid")
fail("invalid_request", "response_type must be code and scope must include openid")
return
}
if ch := q.Get("code_challenge"); ch != "" && q.Get("code_challenge_method") != "S256" {
s.redirectError(c, redirect, q.Get("state"), "invalid_request", "code_challenge_method must be S256")
fail("invalid_request", "code_challenge_method must be S256")
return
}
@ -120,10 +130,20 @@ func (s *Server) authorize(c *gin.Context) {
if !client.Allows(*u) {
s.record(c, u, u.Username, model.EventAccessDenied, client.ClientID)
// The person sitting there gets an explanation; the application gets the standard error through "back".
back, _ := withParams(redirect, url.Values{"error": {"access_denied"}, "state": {q.Get("state")}})
back := ""
if registered {
back, _ = withParams(redirect, url.Values{"error": {"access_denied"}, "state": {q.Get("state")}})
}
s.showError(c, errorContext{Code: ErrAccessDenied, App: client.Name, Return: back})
return
}
if !registered {
if err := s.learnRedirect(c, client, u, redirect); err != nil {
s.log.WithError(err).Error("learn redirect URI")
c.String(http.StatusInternalServerError, "could not store the redirect URI")
return
}
}
code, err := auth.RandomToken()
if err != nil {
@ -326,6 +346,22 @@ func (s *Server) endSession(c *gin.Context) {
s.redirect(c, target, url.Values{"state": {c.Request.FormValue("state")}})
}
// learnRedirect adds a redirect URI to a client that learns them. It re-reads the list, so a parallel sign-in does not drop a URI.
func (s *Server) learnRedirect(c *gin.Context, cl model.Client, u *model.User, uri string) error {
var fresh model.Client
if err := s.db.First(&fresh, cl.ID).Error; err != nil {
return err
}
if slices.Contains(fresh.RedirectURIList(), uri) {
return nil
}
err := s.db.Model(&model.Client{}).Where("id = ?", cl.ID).Update("redirect_uris", model.JoinList(append(fresh.RedirectURIList(), uri))).Error
if err == nil {
s.record(c, u, u.Username, model.EventRedirectLearned, cl.ClientID)
}
return err
}
func (s *Server) findClient(id string) (model.Client, bool) {
var cl model.Client
if id == "" {

View file

@ -93,6 +93,7 @@ export interface Client {
public: boolean;
redirect_uris: string[];
allowed_groups: string[];
learn_redirects: boolean;
source: string;
client_secret?: string;
}
@ -194,8 +195,8 @@ export const api = {
reset2FA: (id: number) => post<void>(`${a}/users/${id}/reset-2fa`),
clients: () => get<Client[]>(`${a}/clients`),
createClient: (c: { name: string; public: boolean; redirect_uris: string[]; allowed_groups: string[] }) => post<Client>(`${a}/clients`, c),
updateClient: (id: number, c: { name: string; redirect_uris: string[]; allowed_groups: string[] }) => request<Client>("PATCH", `${a}/clients/${id}`, c),
createClient: (c: { name: string; public: boolean; redirect_uris: string[]; allowed_groups: string[]; learn_redirects: boolean }) => post<Client>(`${a}/clients`, c),
updateClient: (id: number, c: { name: string; redirect_uris: string[]; allowed_groups: string[]; learn_redirects: boolean }) => request<Client>("PATCH", `${a}/clients/${id}`, c),
deleteClient: (id: number) => request<void>("DELETE", `${a}/clients/${id}`),
rotateSecret: (id: number) => post<Client>(`${a}/clients/${id}/rotate-secret`),

View file

@ -66,6 +66,7 @@ const labels: Record<string, string> = {
totp_enabled: "Authenticator app added",
totp_disabled: "Authenticator app removed",
passkey_added: "Passkey added",
redirect_learned: "Redirect URI added to an app",
passkey_removed: "Passkey removed",
mfa_reset_by_admin: "Second factors reset by an admin",
recovery_code_used: "Recovery code used",

View file

@ -65,12 +65,13 @@ function ClientDialog({ client, onClose, onSaved }: { client: Client | null; onC
const [isPublic, setPublic] = useState(client?.public ?? false);
const [uris, setUris] = useState(client?.redirect_uris.join("\n") ?? "");
const [groups, setGroups] = useState(client?.allowed_groups.join(", ") ?? "");
const [learn, setLearn] = useState(client?.learn_redirects ?? false);
const [err, setErr] = useState("");
async function submit(e: FormEvent) {
e.preventDefault();
try {
const body = { name, redirect_uris: lines(uris), allowed_groups: csv(groups) };
const body = { name, redirect_uris: lines(uris), allowed_groups: csv(groups), learn_redirects: learn && !isPublic };
onSaved(client ? await api.admin.updateClient(client.id, body) : await api.admin.createClient({ ...body, public: isPublic }));
} catch (e2) { setErr(errorText(e2)); }
}
@ -82,6 +83,9 @@ function ClientDialog({ client, onClose, onSaved }: { client: Client | null; onC
<label>Redirect URIs (one per line)<textarea required rows={3} value={uris} onChange={(e) => setUris(e.target.value)} /></label>
<label>Allowed groups (comma separated, empty = every user)<input value={groups} onChange={(e) => setGroups(e.target.value)} /></label>
{!client && <label className="check"><input type="checkbox" checked={isPublic} onChange={(e) => setPublic(e.target.checked)} />Public client without secret (single page or native app, uses PKCE)</label>}
{!isPublic && (
<label className="check"><input type="checkbox" checked={learn} onChange={(e) => setLearn(e.target.checked)} />Add unknown redirect URIs on first sign-in (confidential client only; the URI is shown in the list afterwards)</label>
)}
<Err text={err} />
<div className="row-gap"><button type="submit">Save</button><button type="button" className="secondary" onClick={onClose}>Cancel</button></div>
</form>