diff --git a/ext/security/oidc.mq.md b/ext/security/oidc.mq.md index 3b037e9..095ef0b 100644 --- a/ext/security/oidc.mq.md +++ b/ext/security/oidc.mq.md @@ -21,11 +21,21 @@ import sys:lib/sys.mq.md + `client_id` + `client_secret` + `redirect_uri` + + `redirect_origins`=None + `scopes`="openid profile email" + `callback_path`=None + `authorize_url`=None + `token_url`=None + `userinfo_url`=None +`redirect_uri` may be an absolute URL (`https://qdqc.com/oidc/callback`) or a path +(`/oidc/callback`). Path mode resolves the absolute callback from the login request +Host (`X-Forwarded-Proto` / `X-Forwarded-Host` when behind a reverse proxy) and stores +it in the session so token exchange uses the same string. + +Optional `redirect_origins` is a comma-separated allowlist +(`https://qdqc.com,https://www.qdqc.com`). When set, path-mode origins must match. +The IdP must still register every absolute callback URL that will be used. + > _load -*> web_app_oidc app=`app` issuer=`issuer` client_id=`client_id` client_secret=`client_secret` redirect_uri=`redirect_uri` scopes=`scopes` callback_path=`callback_path` authorize_url=`authorize_url` token_url=`token_url` userinfo_url=`userinfo_url`* +*> web_app_oidc app=`app` issuer=`issuer` client_id=`client_id` client_secret=`client_secret` redirect_uri=`redirect_uri` redirect_origins=`redirect_origins` scopes=`scopes` callback_path=`callback_path` authorize_url=`authorize_url` token_url=`token_url` userinfo_url=`userinfo_url`* diff --git a/plugins/web/internal/app/app.go b/plugins/web/internal/app/app.go index 84c1c8d..55de1ac 100644 --- a/plugins/web/internal/app/app.go +++ b/plugins/web/internal/app/app.go @@ -256,6 +256,9 @@ func OIDC(appBag map[string]any, opts map[string]any) (map[string]any, error) { "scopes": cfg.ScopesCSV(), "callback_path": cfg.Callback(), } + if cfg.RedirectOrigins != "" { + bag["redirect_origins"] = cfg.RedirectOrigins + } if cfg.AuthorizeURL != "" { bag["authorize_url"] = cfg.AuthorizeURL } diff --git a/plugins/web/internal/httpx/auth_oidc.go b/plugins/web/internal/httpx/auth_oidc.go index fecaada..a9f87c2 100644 --- a/plugins/web/internal/httpx/auth_oidc.go +++ b/plugins/web/internal/httpx/auth_oidc.go @@ -117,11 +117,17 @@ func (st *state) handleOIDCStart(w http.ResponseWriter, r *http.Request) { http.Error(w, err.Error(), http.StatusInternalServerError) return } + redirectURI, err := st.oidc.ResolveRedirectURI(r) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } session.SetValue(sid, "oidc_state", state) session.SetValue(sid, "oidc_verifier", verifier) + session.SetValue(sid, "oidc_redirect_uri", redirectURI) next := loginDest(r, st.oidcFallbackNext(r)) session.SetValue(sid, "oidc_next", next) - loc, err := st.oidc.AuthorizeRedirect(state, oidc.PKCEChallengeS256(verifier)) + loc, err := st.oidc.AuthorizeRedirect(state, oidc.PKCEChallengeS256(verifier), redirectURI) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return @@ -164,6 +170,15 @@ func (st *state) handleOIDCCallback(w http.ResponseWriter, r *http.Request) { } verifier, _ := session.GetValue(sid, "oidc_verifier") verifierS, _ := verifier.(string) + redirVal, _ := session.GetValue(sid, "oidc_redirect_uri") + redirectURI, _ := redirVal.(string) + if redirectURI == "" && !st.oidc.IsPathRedirect() { + redirectURI = strings.TrimSpace(st.oidc.RedirectURI) + } + if redirectURI == "" { + http.Error(w, "oidc: missing redirect_uri in session", http.StatusBadRequest) + return + } nextVal, _ := session.GetValue(sid, "oidc_next") next, _ := nextVal.(string) if next == "" { @@ -171,9 +186,10 @@ func (st *state) handleOIDCCallback(w http.ResponseWriter, r *http.Request) { } session.DelKey(sid, "oidc_state") session.DelKey(sid, "oidc_verifier") + session.DelKey(sid, "oidc_redirect_uri") session.DelKey(sid, "oidc_next") - tok, err := st.oidc.ExchangeCode(oidcClient(), code, verifierS) + tok, err := st.oidc.ExchangeCode(oidcClient(), code, verifierS, redirectURI) if err != nil { http.Error(w, "oidc token exchange: "+err.Error(), http.StatusBadGateway) return diff --git a/plugins/web/internal/oidc/oidc.go b/plugins/web/internal/oidc/oidc.go index 695e19b..17fd800 100644 --- a/plugins/web/internal/oidc/oidc.go +++ b/plugins/web/internal/oidc/oidc.go @@ -20,8 +20,11 @@ type Config struct { ClientID string ClientSecret string RedirectURI string - Scopes string - CallbackPath string + // RedirectOrigins is an optional comma-separated allowlist of origins + // (e.g. "https://qdqc.com,https://www.qdqc.com") used when RedirectURI is a path. + RedirectOrigins string + Scopes string + CallbackPath string // AuthorizeURL / TokenURL / UserInfoURL override discovery when set. AuthorizeURL string TokenURL string @@ -36,11 +39,35 @@ func (c Config) Enabled() bool { (strings.TrimSpace(c.Issuer) != "" || strings.TrimSpace(c.AuthorizeURL) != "") } +// IsPathRedirect reports whether RedirectURI is a path (resolved per request Host). +func (c Config) IsPathRedirect() bool { + s := strings.TrimSpace(c.RedirectURI) + if s == "" { + return false + } + if strings.HasPrefix(s, "/") { + return true + } + u, err := url.Parse(s) + if err != nil { + return false + } + // scheme-relative or bare path without host + return u.Scheme == "" && u.Host == "" && u.Path != "" +} + // Callback reports the local path (default /oidc/callback). func (c Config) Callback() string { p := strings.TrimSpace(c.CallbackPath) if p == "" { - if u, err := url.Parse(c.RedirectURI); err == nil && u.Path != "" { + ru := strings.TrimSpace(c.RedirectURI) + if c.IsPathRedirect() { + if !strings.HasPrefix(ru, "/") { + ru = "/" + ru + } + return ru + } + if u, err := url.Parse(ru); err == nil && u.Path != "" { return u.Path } return "/oidc/callback" @@ -51,6 +78,91 @@ func (c Config) Callback() string { return p } +// PublicOrigin derives scheme://host from a login/callback request. +// Prefers X-Forwarded-Proto + X-Forwarded-Host (first value), else Host + TLS. +func PublicOrigin(r *http.Request) (string, error) { + if r == nil { + return "", fmt.Errorf("oidc: nil request") + } + scheme := strings.TrimSpace(r.Header.Get("X-Forwarded-Proto")) + if i := strings.IndexByte(scheme, ','); i >= 0 { + scheme = strings.TrimSpace(scheme[:i]) + } + if scheme == "" { + if r.TLS != nil { + scheme = "https" + } else { + scheme = "http" + } + } + host := strings.TrimSpace(r.Header.Get("X-Forwarded-Host")) + if i := strings.IndexByte(host, ','); i >= 0 { + host = strings.TrimSpace(host[:i]) + } + if host == "" { + host = strings.TrimSpace(r.Host) + } + if host == "" { + return "", fmt.Errorf("oidc: empty Host") + } + return scheme + "://" + host, nil +} + +// ResolveRedirectURI returns the absolute redirect_uri for this request. +// Absolute RedirectURI is returned unchanged; path RedirectURI is joined to the request origin. +func (c Config) ResolveRedirectURI(r *http.Request) (string, error) { + ru := strings.TrimSpace(c.RedirectURI) + if ru == "" { + return "", fmt.Errorf("oidc: empty redirect_uri") + } + if !c.IsPathRedirect() { + return ru, nil + } + origin, err := PublicOrigin(r) + if err != nil { + return "", err + } + path := ru + if !strings.HasPrefix(path, "/") { + path = "/" + path + } + abs := origin + path + if err := c.checkOriginAllowlist(origin); err != nil { + return "", err + } + return abs, nil +} + +// AllowedOrigins returns trimmed non-empty origins from RedirectOrigins. +func (c Config) AllowedOrigins() []string { + raw := strings.TrimSpace(c.RedirectOrigins) + if raw == "" { + return nil + } + var out []string + for _, p := range strings.Split(raw, ",") { + p = strings.TrimRight(strings.TrimSpace(p), "/") + if p != "" { + out = append(out, p) + } + } + return out +} + +func (c Config) checkOriginAllowlist(origin string) error { + allowed := c.AllowedOrigins() + if len(allowed) == 0 { + return nil + } + origin = strings.TrimRight(strings.TrimSpace(origin), "/") + for _, a := range allowed { + if strings.EqualFold(a, origin) { + return nil + } + } + return fmt.Errorf("oidc: origin %q not in redirect_origins", origin) +} + type discoveryDoc struct { AuthorizationEndpoint string `json:"authorization_endpoint"` TokenEndpoint string `json:"token_endpoint"` @@ -126,14 +238,19 @@ func PKCEChallengeS256(verifier string) string { } // AuthorizeRedirect builds the browser redirect to the IdP authorize endpoint. -func (c Config) AuthorizeRedirect(state, codeChallenge string) (string, error) { +// redirectURI must be the absolute URI used for this login (same value later for token exchange). +func (c Config) AuthorizeRedirect(state, codeChallenge, redirectURI string) (string, error) { if c.AuthorizeURL == "" { return "", fmt.Errorf("oidc: authorize URL not resolved") } + redirectURI = strings.TrimSpace(redirectURI) + if redirectURI == "" { + return "", fmt.Errorf("oidc: empty redirect_uri") + } q := url.Values{} q.Set("response_type", "code") q.Set("client_id", c.ClientID) - q.Set("redirect_uri", c.RedirectURI) + q.Set("redirect_uri", redirectURI) q.Set("scope", c.ScopesCSV()) q.Set("state", state) if codeChallenge != "" { @@ -160,17 +277,22 @@ type TokenResponse struct { } // ExchangeCode swaps authorization code for tokens (client_secret_post). -func (c Config) ExchangeCode(client *http.Client, code, codeVerifier string) (*TokenResponse, error) { +// redirectURI must match the absolute URI sent in AuthorizeRedirect. +func (c Config) ExchangeCode(client *http.Client, code, codeVerifier, redirectURI string) (*TokenResponse, error) { if c.TokenURL == "" { return nil, fmt.Errorf("oidc: token URL not resolved") } + redirectURI = strings.TrimSpace(redirectURI) + if redirectURI == "" { + return nil, fmt.Errorf("oidc: empty redirect_uri") + } if client == nil { client = &http.Client{Timeout: 15 * time.Second} } form := url.Values{} form.Set("grant_type", "authorization_code") form.Set("code", code) - form.Set("redirect_uri", c.RedirectURI) + form.Set("redirect_uri", redirectURI) form.Set("client_id", c.ClientID) form.Set("client_secret", c.ClientSecret) if codeVerifier != "" { @@ -313,15 +435,16 @@ func ParseConfig(m map[string]any) Config { m = nested } c := Config{ - Issuer: firstStr(m, "issuer", "发行方", "issuer_url"), - ClientID: firstStr(m, "client_id", "客户端编号", "客户端id", "clientId"), - ClientSecret: firstStr(m, "client_secret", "客户端密钥", "clientSecret"), - RedirectURI: firstStr(m, "redirect_uri", "回调", "回调地址", "redirect"), - Scopes: firstStr(m, "scopes", "范围", "scope"), - CallbackPath: firstStr(m, "callback_path", "回调路径"), - AuthorizeURL: firstStr(m, "authorize_url", "授权地址"), - TokenURL: firstStr(m, "token_url", "令牌地址"), - UserInfoURL: firstStr(m, "userinfo_url", "用户信息地址"), + Issuer: firstStr(m, "issuer", "发行方", "issuer_url"), + ClientID: firstStr(m, "client_id", "客户端编号", "客户端id", "clientId"), + ClientSecret: firstStr(m, "client_secret", "客户端密钥", "clientSecret"), + RedirectURI: firstStr(m, "redirect_uri", "回调", "回调地址", "redirect"), + RedirectOrigins: firstStr(m, "redirect_origins", "回调来源", "redirect_origin"), + Scopes: firstStr(m, "scopes", "范围", "scope"), + CallbackPath: firstStr(m, "callback_path", "回调路径"), + AuthorizeURL: firstStr(m, "authorize_url", "授权地址"), + TokenURL: firstStr(m, "token_url", "令牌地址"), + UserInfoURL: firstStr(m, "userinfo_url", "用户信息地址"), } return c } diff --git a/plugins/web/internal/oidc/oidc_test.go b/plugins/web/internal/oidc/oidc_test.go index df57968..54e889a 100644 --- a/plugins/web/internal/oidc/oidc_test.go +++ b/plugins/web/internal/oidc/oidc_test.go @@ -1,6 +1,10 @@ package oidc_test import ( + "crypto/tls" + "net/http" + "net/url" + "strings" "testing" "github.com/marqdo/marqdo/plugins/web/internal/oidc" @@ -46,4 +50,138 @@ func TestPKCEAndParse(t *testing.T) { if c.Callback() != "/oidc/callback" { t.Fatalf("callback=%s", c.Callback()) } + if c.IsPathRedirect() { + t.Fatal("absolute redirect should not be path mode") + } +} + +func TestPathRedirectParseAndCallback(t *testing.T) { + c := oidc.ParseConfig(map[string]any{ + "issuer": "https://id.example.com", + "client_id": "app_x", + "client_secret": "secret", + "redirect_uri": "/oidc/callback", + "redirect_origins": "https://qdqc.com,https://www.qdqc.com", + }) + if !c.Enabled() { + t.Fatal("expected enabled") + } + if !c.IsPathRedirect() { + t.Fatal("expected path mode") + } + if c.Callback() != "/oidc/callback" { + t.Fatalf("callback=%s", c.Callback()) + } + origins := c.AllowedOrigins() + if len(origins) != 2 || origins[0] != "https://qdqc.com" { + t.Fatalf("origins=%v", origins) + } +} + +func TestResolveRedirectURIAbsolute(t *testing.T) { + c := oidc.Config{RedirectURI: "https://qdqc.com/oidc/callback"} + r, _ := http.NewRequest(http.MethodGet, "http://www.qdqc.com/oidc/login", nil) + r.Host = "www.qdqc.com" + got, err := c.ResolveRedirectURI(r) + if err != nil { + t.Fatal(err) + } + if got != "https://qdqc.com/oidc/callback" { + t.Fatalf("got=%s", got) + } +} + +func TestResolveRedirectURIPathFromHost(t *testing.T) { + c := oidc.Config{RedirectURI: "/oidc/callback"} + r, _ := http.NewRequest(http.MethodGet, "http://qdqc.com/oidc/login", nil) + r.Host = "qdqc.com" + got, err := c.ResolveRedirectURI(r) + if err != nil { + t.Fatal(err) + } + if got != "http://qdqc.com/oidc/callback" { + t.Fatalf("got=%s", got) + } +} + +func TestResolveRedirectURIPathTLS(t *testing.T) { + c := oidc.Config{RedirectURI: "/oidc/callback"} + r, _ := http.NewRequest(http.MethodGet, "https://qdqc.com/oidc/login", nil) + r.Host = "qdqc.com" + r.TLS = &tls.ConnectionState{} + got, err := c.ResolveRedirectURI(r) + if err != nil { + t.Fatal(err) + } + if got != "https://qdqc.com/oidc/callback" { + t.Fatalf("got=%s", got) + } +} + +func TestResolveRedirectURIXForwarded(t *testing.T) { + c := oidc.Config{RedirectURI: "/oidc/callback"} + r, _ := http.NewRequest(http.MethodGet, "http://127.0.0.1:18085/oidc/login", nil) + r.Host = "127.0.0.1:18085" + r.Header.Set("X-Forwarded-Proto", "https") + r.Header.Set("X-Forwarded-Host", "www.qdqc.com, other.example") + got, err := c.ResolveRedirectURI(r) + if err != nil { + t.Fatal(err) + } + if got != "https://www.qdqc.com/oidc/callback" { + t.Fatalf("got=%s", got) + } +} + +func TestResolveRedirectURIAllowlistReject(t *testing.T) { + c := oidc.Config{ + RedirectURI: "/oidc/callback", + RedirectOrigins: "https://qdqc.com,https://www.qdqc.com", + } + r, _ := http.NewRequest(http.MethodGet, "https://evil.example/oidc/login", nil) + r.Host = "evil.example" + r.Header.Set("X-Forwarded-Proto", "https") + _, err := c.ResolveRedirectURI(r) + if err == nil || !strings.Contains(err.Error(), "redirect_origins") { + t.Fatalf("expected allowlist error, got %v", err) + } +} + +func TestResolveRedirectURIAllowlistOK(t *testing.T) { + c := oidc.Config{ + RedirectURI: "/oidc/callback", + RedirectOrigins: "https://qdqc.com,https://www.qdqc.com", + } + r, _ := http.NewRequest(http.MethodGet, "https://www.qdqc.com/oidc/login", nil) + r.Host = "www.qdqc.com" + r.Header.Set("X-Forwarded-Proto", "https") + got, err := c.ResolveRedirectURI(r) + if err != nil { + t.Fatal(err) + } + if got != "https://www.qdqc.com/oidc/callback" { + t.Fatalf("got=%s", got) + } +} + +func TestAuthorizeRedirectUsesExplicitURI(t *testing.T) { + c := oidc.Config{ + ClientID: "app_x", + AuthorizeURL: "https://id.example.com/oauth2/authorize", + RedirectURI: "/oidc/callback", + } + loc, err := c.AuthorizeRedirect("st", "ch", "https://www.qdqc.com/oidc/callback") + if err != nil { + t.Fatal(err) + } + u, err := url.Parse(loc) + if err != nil { + t.Fatal(err) + } + if got := u.Query().Get("redirect_uri"); got != "https://www.qdqc.com/oidc/callback" { + t.Fatalf("redirect_uri=%s", got) + } + if u.Query().Get("state") != "st" { + t.Fatal("state") + } } diff --git a/plugins/web/plugin.go b/plugins/web/plugin.go index b79cfc4..7c50f71 100644 --- a/plugins/web/plugin.go +++ b/plugins/web/plugin.go @@ -219,7 +219,7 @@ static int register_core(void) { if (host_register((char *)"web_auth_logout", (char *)"session_id", web_auth_logout) != 0) return 1; if (host_register((char *)"web_auth_new", (char *)"users,session_ttl", web_auth_new) != 0) return 1; if (host_register((char *)"web_app_auth", (char *)"app,users,session_ttl,admin_prefix,login_redirect,logout_redirect,login_path,register,register_path,default_role,session_url", web_app_auth) != 0) return 1; - if (host_register((char *)"web_app_oidc", (char *)"app,issuer,client_id,client_secret,redirect_uri,scopes,callback_path,authorize_url,token_url,userinfo_url", web_app_oidc) != 0) return 1; + if (host_register((char *)"web_app_oidc", (char *)"app,issuer,client_id,client_secret,redirect_uri,redirect_origins,scopes,callback_path,authorize_url,token_url,userinfo_url", web_app_oidc) != 0) return 1; if (host_register((char *)"web_app_gate", (char *)"app,path,roles,permissions,match,on_deny,exclude", web_app_gate) != 0) return 1; if (host_register((char *)"web_app_rbac", (char *)"app,catalog,desk", web_app_rbac) != 0) return 1; if (host_register((char *)"web_app_tenant", (char *)"app,mode,param,column,default_scope", web_app_tenant) != 0) return 1;