diff --git a/ext/web/web.mq.md b/ext/web/web.mq.md index 7640b64..38bd699 100644 --- a/ext/web/web.mq.md +++ b/ext/web/web.mq.md @@ -821,6 +821,21 @@ Keep the app's `admin=True`, and gate `{admin_prefix}` (segment-boundary prefix) *> web_app_auth app=`self` users=`users` session_ttl=`session_ttl` admin_prefix=`admin_prefix` login_redirect=`login_redirect` logout_redirect=`logout_redirect` login_path=`login_path` register=`register` register_path=`register_path` default_role=`default_role` session_url=`session_url`* +## oidc + + `issuer`=None + + `client_id` + + `client_secret` + + `redirect_uri` + + `scopes`="openid profile email" + + `callback_path`=None + + `authorize_url`=None + + `token_url`=None + + `userinfo_url`=None + +Enable OAuth 2.0 authorization-code / OIDC login (e.g. CFLMY IdP). When set, `login_path` / `register_path` / desk login redirect to the IdP; the `redirect_uri` callback exchanges the code and opens a local session. userinfo `is_admin` / `admin_role` map to local role `admin`; otherwise `default_role`. Secrets stay server-side; PKCE S256 is always sent. + +*> web_app_oidc app=`self` 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`* + ## gate + `path` + `roles`=admin diff --git a/ext/web/网页.mq.md b/ext/web/网页.mq.md index 106ce79..a541a48 100644 --- a/ext/web/网页.mq.md +++ b/ext/web/网页.mq.md @@ -623,7 +623,7 @@ SSR 顶栏刊名 Logo、主题切换钮与目录抽屉钮。交互写在 `client + `动作`=插入 + `id`=None -字段表 + 校验表;提交经 `# 数据库` 写入。 +字段表 + 校验表;提交经 `# 数据库` 写入。`动作` 为 `插入` / `更新` / `删除`(英:`insert` / `update` / `delete`)。删除按 `id` 删行,字段表可只读展示上下文。站点后台用「列表 + 表单页」声明即可,不必改插件。 > 确保插件 *> web_form_new table=`表` action=`动作` id=`id`* @@ -789,6 +789,21 @@ SSR 顶栏刊名 Logo、主题切换钮与目录抽屉钮。交互写在 `client *> web_app_auth app=`self` users=`用户表` session_ttl=`会话时长` admin_prefix=`后台前缀` login_redirect=`登录回跳` logout_redirect=`登出回跳` login_path=`登录路径` register=`注册` register_path=`注册路径` default_role=`默认角色` session_url=`会话地址`* +## 统一身份 + + `发行方`=None + + `客户端编号` + + `客户端密钥` + + `回调` + + `范围`="openid profile email" + + `回调路径`=None + + `授权地址`=None + + `令牌地址`=None + + `用户信息地址`=None + +接入 OIDC / OAuth 2.0 授权码(如 [CFLMY 统一身份](https://id.cflmy.cn/api-docs))。listen 后:`登录路径` / `注册路径` / 后台登录页 302 到 IdP;回调 `回调`(默认 `/oidc/callback`)换票并建本地会话。userinfo 的 `is_admin` / `admin_role` 映射为本地角色 `admin`(写作台权限),否则为 `默认角色`。`client_secret` 仅服务端;推荐配 PKCE(框架已启用 S256)。 + +*> web_app_oidc app=`self` issuer=`发行方` client_id=`客户端编号` client_secret=`客户端密钥` redirect_uri=`回调` scopes=`范围` callback_path=`回调路径` authorize_url=`授权地址` token_url=`令牌地址` userinfo_url=`用户信息地址`* + ## 门禁 + `路径` + `角色`=admin diff --git a/plugins/web/abi_extra.go b/plugins/web/abi_extra.go index 6be094c..85c191d 100644 --- a/plugins/web/abi_extra.go +++ b/plugins/web/abi_extra.go @@ -502,6 +502,16 @@ func web_app_auth(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { return replyJSON(outJSON, errMsg, out, err) } +//export web_app_oidc +func web_app_oidc(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { + args, err := parseArgs(argsJSON) + if err != nil { + return replyJSON(outJSON, errMsg, nil, err) + } + out, err := app.OIDC(asPageMap(args["app"]), args) + return replyJSON(outJSON, errMsg, out, err) +} + //export web_app_gate func web_app_gate(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { args, err := parseArgs(argsJSON) diff --git a/plugins/web/internal/app/app.go b/plugins/web/internal/app/app.go index 0ee0b8e..7fcffb7 100644 --- a/plugins/web/internal/app/app.go +++ b/plugins/web/internal/app/app.go @@ -6,6 +6,7 @@ import ( "strings" "github.com/marqdo/marqdo/plugins/web/internal/assets" + "github.com/marqdo/marqdo/plugins/web/internal/oidc" "github.com/marqdo/marqdo/plugins/web/internal/session" "github.com/marqdo/marqdo/plugins/web/internal/tenant" ) @@ -234,6 +235,48 @@ func Auth(appBag map[string]any, users any, opts map[string]any) (map[string]any return out, nil } +// OIDC configures OAuth2/OIDC authorization-code login (CFLMY IdP or compatible). +// When enabled, GET/POST on login_path and register_path redirect to the IdP; +// callback at redirect_uri path establishes the local session. IdP is_admin / +// admin_role map to local role "admin". +func OIDC(appBag map[string]any, opts map[string]any) (map[string]any, error) { + if opts == nil { + opts = map[string]any{} + } + cfg := oidc.ParseConfig(opts) + if !cfg.Enabled() { + return nil, fmt.Errorf("oidc: need client_id, client_secret, redirect_uri, and issuer (or authorize_url)") + } + out := clone(appBag) + bag := map[string]any{ + "issuer": cfg.Issuer, + "client_id": cfg.ClientID, + "client_secret": cfg.ClientSecret, + "redirect_uri": cfg.RedirectURI, + "scopes": cfg.ScopesCSV(), + "callback_path": cfg.Callback(), + } + if cfg.AuthorizeURL != "" { + bag["authorize_url"] = cfg.AuthorizeURL + } + if cfg.TokenURL != "" { + bag["token_url"] = cfg.TokenURL + } + if cfg.UserInfoURL != "" { + bag["userinfo_url"] = cfg.UserInfoURL + } + out["oidc"] = bag + authBag, _ := out["auth"].(map[string]any) + if authBag == nil { + authBag = map[string]any{} + } else { + authBag = clone(authBag) + } + authBag["oidc"] = true + out["auth"] = authBag + return out, nil +} + // Tenant configures multi-tenant resolution on the app bag (path|subdomain|header). func Tenant(appBag map[string]any, opts map[string]any) (map[string]any, error) { return tenant.Configure(appBag, opts) diff --git a/plugins/web/internal/form/form.go b/plugins/web/internal/form/form.go index 182cd93..fe1cdf1 100644 --- a/plugins/web/internal/form/form.go +++ b/plugins/web/internal/form/form.go @@ -47,6 +47,8 @@ func normalizeAction(action string) string { switch action { case "update", "更新": return "update" + case "delete", "删除": + return "delete" case "": return "insert" default: @@ -737,7 +739,7 @@ func RenderBodyCtx(formBag map[string]any, formID string, data, errors any, csrf } } } - if action == "update" && rowID != "" && !hasIDField { + if (action == "update" || action == "delete") && rowID != "" && !hasIDField { fmt.Fprintf(&body, ``, esc(rowID)) } if ctx != nil { @@ -896,7 +898,7 @@ body{font-family:"IBM Plex Sans","Noto Sans SC",sans-serif;margin:1.5rem;backgro func Submit(formBag map[string]any, data any, dbURL string) (map[string]any, error) { action := strOf(formBag, "action", "insert") rowMap := dataMap(data) - if action == "update" { + if action == "update" || action == "delete" { if formBag != nil { if fid := cellStr(formBag["id"]); fid != "" { if _, ok := rowMap["id"]; !ok { @@ -905,14 +907,16 @@ func Submit(formBag map[string]any, data any, dbURL string) (map[string]any, err } } } - v := Validate(formBag, nil, rowMap) - ok, _ := v["ok"].(bool) - if !ok { - errs := v["errors"] - if errs == nil { - errs = []any{} + if action != "delete" { + v := Validate(formBag, nil, rowMap) + ok, _ := v["ok"].(bool) + if !ok { + errs := v["errors"] + if errs == nil { + errs = []any{} + } + return map[string]any{"ok": false, "errors": errs}, nil } - return map[string]any{"ok": false, "errors": errs}, nil } tableName := "" if formBag != nil { @@ -923,7 +927,20 @@ func Submit(formBag map[string]any, data any, dbURL string) (map[string]any, err } var result map[string]any var err error - if action == "update" { + switch action { + case "delete": + id := "" + if formBag != nil { + id = cellStr(formBag["id"]) + } + if id == "" { + id = cellStr(rowMap["id"]) + } + if id == "" { + return nil, fmt.Errorf("delete requires `id`") + } + result, err = db.Delete(dbURL, tableName, id) + case "update": id := "" if formBag != nil { id = cellStr(formBag["id"]) @@ -935,7 +952,7 @@ func Submit(formBag map[string]any, data any, dbURL string) (map[string]any, err return nil, fmt.Errorf("update requires `id`") } result, err = db.Update(dbURL, tableName, id, rowMap) - } else { + default: result, err = db.Insert(dbURL, tableName, []any{rowMap}) } if err != nil { diff --git a/plugins/web/internal/httpx/auth.go b/plugins/web/internal/httpx/auth.go index f2600af..07ea8a8 100644 --- a/plugins/web/internal/httpx/auth.go +++ b/plugins/web/internal/httpx/auth.go @@ -245,6 +245,9 @@ func pathExcluded(path string, exclude []string, loginPath string) bool { if path == loginPath || strings.HasPrefix(path, loginPath+"?") { return true } + if strings.HasPrefix(path, "/oidc/") { + return true + } for _, ex := range exclude { ex = strings.TrimRight(strings.TrimSuffix(ex, "*"), "/") if ex == "" { @@ -364,10 +367,11 @@ func (st *state) hasPageRoute(path string) bool { } func (st *state) mountAuthRoutes(mux *http.ServeMux) { - if st.auth.users == nil && !(st.auth.rbac && st.auth.register) { + st.mountOIDCRoutes(mux) + if st.auth.users == nil && !(st.auth.rbac && st.auth.register) && !st.oidcEnabled() { return } - if st.auth.users != nil || st.auth.rbac { + if st.auth.users != nil || st.auth.rbac || st.oidcEnabled() { lp := st.auth.loginPath // Site pages may own GET /login (or /desk/login); always keep POST for auth. if !st.hasPageRoute(lp) { @@ -385,7 +389,7 @@ func (st *state) mountAuthRoutes(mux *http.ServeMux) { logoutPath := strings.TrimRight(st.auth.adminPrefix, "/") + "/logout" mux.HandleFunc("GET "+logoutPath, st.handleLogout) } - if st.auth.register && st.auth.rbac { + if st.auth.register && st.auth.rbac && !st.oidcEnabled() { rp := st.auth.registerPath if !st.hasPageRoute(rp) { mux.HandleFunc("GET "+rp, st.handleRegisterGet) @@ -410,6 +414,10 @@ func (st *state) mountAuthRoutes(mux *http.ServeMux) { } func (st *state) handleLoginGet(w http.ResponseWriter, r *http.Request) { + if st.oidcEnabled() { + st.handleOIDCStart(w, r) + return + } if st.auth.users == nil && !st.auth.rbac { http.Redirect(w, r, st.auth.loginRedirect, http.StatusSeeOther) return @@ -427,6 +435,10 @@ func (st *state) handleLoginGet(w http.ResponseWriter, r *http.Request) { } func (st *state) handleLoginPost(w http.ResponseWriter, r *http.Request) { + if st.oidcEnabled() { + st.handleOIDCStart(w, r) + return + } if st.auth.users == nil && !st.auth.rbac { http.Redirect(w, r, st.auth.loginRedirect, http.StatusSeeOther) return @@ -474,7 +486,8 @@ func (st *state) handleLoginPost(w http.ResponseWriter, r *http.Request) { } dest := loginDest(r, fallback) held := session.PermissionsFromSession(sessID) - if strings.HasPrefix(dest, "/desk") && !session.PermissionAllowed(held, []string{"desk:access"}) { + if (strings.HasPrefix(dest, "/desk") || strings.HasPrefix(dest, "/admin")) && + !session.PermissionAllowed(held, []string{"desk:access"}) { dest = "/" } w.Header().Add("Set-Cookie", session.IssueCookie(sessID)) diff --git a/plugins/web/internal/httpx/auth_oidc.go b/plugins/web/internal/httpx/auth_oidc.go new file mode 100644 index 0000000..fecaada --- /dev/null +++ b/plugins/web/internal/httpx/auth_oidc.go @@ -0,0 +1,245 @@ +package httpx + +import ( + "fmt" + "net/http" + "strings" + "sync" + "time" + + "github.com/marqdo/marqdo/plugins/web/internal/auth" + "github.com/marqdo/marqdo/plugins/web/internal/oidc" + "github.com/marqdo/marqdo/plugins/web/internal/rbac" + "github.com/marqdo/marqdo/plugins/web/internal/session" +) + +const oidcPasswordSentinel = "!oidc!" + +var ( + oidcHTTPOnce sync.Once + oidcHTTP *http.Client +) + +func oidcClient() *http.Client { + oidcHTTPOnce.Do(func() { + oidcHTTP = &http.Client{Timeout: 20 * time.Second} + }) + return oidcHTTP +} + +func (st *state) oidcEnabled() bool { + return st.oidc.Enabled() +} + +func (st *state) ensureOIDCEndpoints() error { + if !st.oidc.Enabled() { + return fmt.Errorf("oidc not configured") + } + return st.oidc.ResolveEndpoints(oidcClient()) +} + +func (st *state) isOIDCEntryPath(path string) bool { + if !st.oidcEnabled() || path == "" { + return false + } + if path == st.auth.loginPath || path == st.auth.registerPath { + return true + } + alt := strings.TrimRight(st.auth.adminPrefix, "/") + "/login" + if path == alt || path == "/desk/login" || path == "/admin/login" { + return true + } + return false +} + +// oidcFallbackNext picks where to land after IdP login when ?next= is absent. +// Admin entry pages must not fall back to the public homepage. +func (st *state) oidcFallbackNext(r *http.Request) string { + path := "" + if r != nil { + path = r.URL.Path + } + switch path { + case "/desk/login", "/admin/login", "/oidc/login": + return "/admin" + case "/desk", "/admin": + return "/admin" + } + if strings.HasPrefix(path, "/desk/") || strings.HasPrefix(path, "/admin/") { + return "/admin" + } + if st.auth.loginRedirect != "" { + return st.auth.loginRedirect + } + return "/" +} + +func (st *state) mountOIDCRoutes(mux *http.ServeMux) { + if !st.oidcEnabled() { + return + } + cb := st.oidc.Callback() + mux.HandleFunc("GET "+cb, st.handleOIDCCallback) + mux.HandleFunc("GET /oidc/login", st.handleOIDCStart) + mux.HandleFunc("GET /oidc/register", st.handleOIDCStart) +} + +func (st *state) handleOIDCStart(w http.ResponseWriter, r *http.Request) { + if !st.oidcEnabled() { + http.NotFound(w, r) + return + } + // Already signed in → skip IdP round-trip when destination is allowed. + cookie := r.Header.Get("Cookie") + if session.RoleFromCookie(cookie) != "visitor" { + next := loginDest(r, st.oidcFallbackNext(r)) + needsDesk := strings.HasPrefix(next, "/admin") || strings.HasPrefix(next, "/desk") + held := session.PermissionsFromCookie(cookie) + if needsDesk && !session.PermissionAllowed(held, []string{"desk:access"}) { + http.Redirect(w, r, "/", http.StatusSeeOther) + return + } + http.Redirect(w, r, next, http.StatusSeeOther) + return + } + if err := st.ensureOIDCEndpoints(); err != nil { + http.Error(w, "oidc discovery failed: "+err.Error(), http.StatusBadGateway) + return + } + sid, _, setCookie := resolveSession(r) + state, err := oidc.RandomURLString(24) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + verifier, err := oidc.RandomURLString(32) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + session.SetValue(sid, "oidc_state", state) + session.SetValue(sid, "oidc_verifier", verifier) + next := loginDest(r, st.oidcFallbackNext(r)) + session.SetValue(sid, "oidc_next", next) + loc, err := st.oidc.AuthorizeRedirect(state, oidc.PKCEChallengeS256(verifier)) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + appendSetCookie(w, setCookie) + w.Header().Add("Set-Cookie", session.IssueCookie(sid)) + http.Redirect(w, r, loc, http.StatusFound) +} + +func (st *state) handleOIDCCallback(w http.ResponseWriter, r *http.Request) { + if !st.oidcEnabled() { + http.NotFound(w, r) + return + } + if err := st.ensureOIDCEndpoints(); err != nil { + http.Error(w, "oidc discovery failed: "+err.Error(), http.StatusBadGateway) + return + } + q := r.URL.Query() + if errCode := q.Get("error"); errCode != "" { + msg := errCode + if d := q.Get("error_description"); d != "" { + msg = errCode + ": " + d + } + http.Error(w, "oidc: "+msg, http.StatusBadRequest) + return + } + code := q.Get("code") + state := q.Get("state") + if code == "" || state == "" { + http.Error(w, "oidc: missing code or state", http.StatusBadRequest) + return + } + sid, _, setCookie := resolveSession(r) + want, _ := session.GetValue(sid, "oidc_state") + wantS, _ := want.(string) + if wantS == "" || wantS != state { + http.Error(w, "oidc: state mismatch", http.StatusBadRequest) + return + } + verifier, _ := session.GetValue(sid, "oidc_verifier") + verifierS, _ := verifier.(string) + nextVal, _ := session.GetValue(sid, "oidc_next") + next, _ := nextVal.(string) + if next == "" { + next = st.auth.loginRedirect + } + session.DelKey(sid, "oidc_state") + session.DelKey(sid, "oidc_verifier") + session.DelKey(sid, "oidc_next") + + tok, err := st.oidc.ExchangeCode(oidcClient(), code, verifierS) + if err != nil { + http.Error(w, "oidc token exchange: "+err.Error(), http.StatusBadGateway) + return + } + info, err := st.oidc.FetchUserInfo(oidcClient(), tok.AccessToken) + if err != nil { + http.Error(w, "oidc userinfo: "+err.Error(), http.StatusBadGateway) + return + } + username := info.LocalUsername() + if username == "" { + http.Error(w, "oidc: empty username", http.StatusBadGateway) + return + } + role := info.LocalRole(st.auth.defaultRole) + if role == "admin" { + // System RBAC seed uses superadmin; keep session role "admin" for ExpandRole. + if st.dbURL != "" && st.auth.rbac { + _ = rbac.EnsureUserWithRole(st.dbURL, username, oidcPasswordSentinel, "superadmin") + } + } else if st.dbURL != "" && st.auth.rbac { + _ = rbac.EnsureUserWithRole(st.dbURL, username, oidcPasswordSentinel, role) + } + newID := session.NewID(st.auth.sessionTTL) + session.SetValue(newID, "username", username) + session.SetValue(newID, "role", role) + session.SetValue(newID, "oidc_sub", info.Sub) + if info.Email != "" { + session.SetValue(newID, "email", info.Email) + } + if info.AdminRole != "" { + session.SetValue(newID, "admin_role", info.AdminRole) + } + st.attachOIDCPermissions(newID, username, role) + + held := session.PermissionsFromSession(newID) + if (strings.HasPrefix(next, "/desk") || strings.HasPrefix(next, "/admin")) && + !session.PermissionAllowed(held, []string{"desk:access"}) { + next = "/" + } + appendSetCookie(w, setCookie) + w.Header().Add("Set-Cookie", session.IssueCookie(newID)) + http.Redirect(w, r, next, http.StatusSeeOther) +} + +func (st *state) attachOIDCPermissions(sessID, username, role string) { + // Prefer IdP-derived role expansion so platform admins always get desk access + // even before local RBAC rows catch up. + perms := rbac.ExpandRole(role) + if len(perms) == 0 { + perms = expandLegacyRole(role) + } + if st.dbURL != "" && st.auth.rbac { + if dbPerms, err := rbac.PermissionsForUser(st.dbURL, username); err == nil && len(dbPerms) > 0 { + // Union IdP role perms with any local grants. + seen := map[string]bool{} + var out []string + for _, p := range append(perms, dbPerms...) { + if p == "" || seen[p] { + continue + } + seen[p] = true + out = append(out, p) + } + perms = out + } + } + auth.AttachPermissions(sessID, perms) +} diff --git a/plugins/web/internal/httpx/listen.go b/plugins/web/internal/httpx/listen.go index 2ea1169..6925d68 100644 --- a/plugins/web/internal/httpx/listen.go +++ b/plugins/web/internal/httpx/listen.go @@ -22,6 +22,7 @@ import ( "github.com/marqdo/marqdo/plugins/web/internal/db" "github.com/marqdo/marqdo/plugins/web/internal/form" "github.com/marqdo/marqdo/plugins/web/internal/middleware" + "github.com/marqdo/marqdo/plugins/web/internal/oidc" "github.com/marqdo/marqdo/plugins/web/internal/ratelimit" "github.com/marqdo/marqdo/plugins/web/internal/rbac" "github.com/marqdo/marqdo/plugins/web/internal/render" @@ -122,6 +123,7 @@ func NewHandler(appBag map[string]any, entryDir string) (http.Handler, error) { proxyRoutes: routeMapOf(appBag, "proxy_routes"), invokeRoutes: routeMapOf(appBag, "invoke_routes"), auth: authCfg, + oidc: oidc.ParseConfig(appBag), tenant: tenant.FromBag(appBag), } @@ -306,6 +308,7 @@ type state struct { proxyRoutes map[string]any invokeRoutes map[string]any auth authConfig + oidc oidc.Config tenant tenant.Config } @@ -361,7 +364,7 @@ func (st *state) attachCSRF(page map[string]any, r *http.Request) *string { if page == nil || r == nil { return nil } - if st.auth.users == nil && !st.auth.rbac { + if st.auth.users == nil && !st.auth.rbac && !st.oidcEnabled() { return nil } _, csrf, setCookie := resolveSession(r) @@ -372,6 +375,10 @@ func (st *state) attachCSRF(page map[string]any, r *http.Request) *string { } func (st *state) writePage(w http.ResponseWriter, r *http.Request, page map[string]any) { + if st.oidcEnabled() && st.isOIDCEntryPath(r.URL.Path) { + st.handleOIDCStart(w, r) + return + } p := st.preparePage(page, r) if st.authEntryRedirect(w, r, p) { return diff --git a/plugins/web/internal/oidc/oidc.go b/plugins/web/internal/oidc/oidc.go new file mode 100644 index 0000000..695e19b --- /dev/null +++ b/plugins/web/internal/oidc/oidc.go @@ -0,0 +1,341 @@ +// Package oidc implements OAuth 2.0 authorization-code + OIDC userinfo for ext/web. +package oidc + +import ( + "crypto/rand" + "crypto/sha256" + "encoding/base64" + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" + "strings" + "time" +) + +// Config is the relying-party settings (CFLMY IdP or any OIDC provider). +type Config struct { + Issuer string + ClientID string + ClientSecret string + RedirectURI string + Scopes string + CallbackPath string + // AuthorizeURL / TokenURL / UserInfoURL override discovery when set. + AuthorizeURL string + TokenURL string + UserInfoURL string +} + +// Enabled reports whether the minimum OIDC fields are present. +func (c Config) Enabled() bool { + return strings.TrimSpace(c.ClientID) != "" && + strings.TrimSpace(c.ClientSecret) != "" && + strings.TrimSpace(c.RedirectURI) != "" && + (strings.TrimSpace(c.Issuer) != "" || strings.TrimSpace(c.AuthorizeURL) != "") +} + +// 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 != "" { + return u.Path + } + return "/oidc/callback" + } + if !strings.HasPrefix(p, "/") { + p = "/" + p + } + return p +} + +type discoveryDoc struct { + AuthorizationEndpoint string `json:"authorization_endpoint"` + TokenEndpoint string `json:"token_endpoint"` + UserinfoEndpoint string `json:"userinfo_endpoint"` +} + +// ResolveEndpoints fills Authorize/Token/UserInfo from discovery when missing. +func (c *Config) ResolveEndpoints(client *http.Client) error { + if c.AuthorizeURL != "" && c.TokenURL != "" && c.UserInfoURL != "" { + return nil + } + issuer := strings.TrimRight(strings.TrimSpace(c.Issuer), "/") + if issuer == "" { + return fmt.Errorf("oidc: issuer or explicit endpoints required") + } + if client == nil { + client = &http.Client{Timeout: 15 * time.Second} + } + discURL := issuer + "/.well-known/openid-configuration" + res, err := client.Get(discURL) + if err != nil { + return fmt.Errorf("oidc discovery: %w", err) + } + defer res.Body.Close() + body, err := io.ReadAll(io.LimitReader(res.Body, 1<<20)) + if err != nil { + return err + } + if res.StatusCode >= 300 { + return fmt.Errorf("oidc discovery HTTP %d: %s", res.StatusCode, truncate(string(body), 200)) + } + var doc discoveryDoc + if err := json.Unmarshal(body, &doc); err != nil { + return fmt.Errorf("oidc discovery json: %w", err) + } + if c.AuthorizeURL == "" { + c.AuthorizeURL = doc.AuthorizationEndpoint + } + if c.TokenURL == "" { + c.TokenURL = doc.TokenEndpoint + } + if c.UserInfoURL == "" { + c.UserInfoURL = doc.UserinfoEndpoint + } + if c.AuthorizeURL == "" || c.TokenURL == "" || c.UserInfoURL == "" { + return fmt.Errorf("oidc: incomplete discovery endpoints") + } + return nil +} + +// ScopesCSV returns space-separated scopes (default openid profile email). +func (c Config) ScopesCSV() string { + s := strings.TrimSpace(c.Scopes) + if s == "" { + return "openid profile email" + } + return s +} + +// RandomURLString returns a URL-safe random string of n bytes (base64url, no pad). +func RandomURLString(n int) (string, error) { + b := make([]byte, n) + if _, err := rand.Read(b); err != nil { + return "", err + } + return base64.RawURLEncoding.EncodeToString(b), nil +} + +// PKCEChallengeS256 returns code_challenge for a verifier. +func PKCEChallengeS256(verifier string) string { + sum := sha256.Sum256([]byte(verifier)) + return base64.RawURLEncoding.EncodeToString(sum[:]) +} + +// AuthorizeRedirect builds the browser redirect to the IdP authorize endpoint. +func (c Config) AuthorizeRedirect(state, codeChallenge string) (string, error) { + if c.AuthorizeURL == "" { + return "", fmt.Errorf("oidc: authorize URL not resolved") + } + q := url.Values{} + q.Set("response_type", "code") + q.Set("client_id", c.ClientID) + q.Set("redirect_uri", c.RedirectURI) + q.Set("scope", c.ScopesCSV()) + q.Set("state", state) + if codeChallenge != "" { + q.Set("code_challenge", codeChallenge) + q.Set("code_challenge_method", "S256") + } + sep := "?" + if strings.Contains(c.AuthorizeURL, "?") { + sep = "&" + } + return c.AuthorizeURL + sep + q.Encode(), nil +} + +// TokenResponse is the OAuth token endpoint JSON. +type TokenResponse struct { + AccessToken string `json:"access_token"` + TokenType string `json:"token_type"` + ExpiresIn int `json:"expires_in"` + RefreshToken string `json:"refresh_token"` + IDToken string `json:"id_token"` + Scope string `json:"scope"` + Error string `json:"error"` + ErrorDesc string `json:"error_description"` +} + +// ExchangeCode swaps authorization code for tokens (client_secret_post). +func (c Config) ExchangeCode(client *http.Client, code, codeVerifier string) (*TokenResponse, error) { + if c.TokenURL == "" { + return nil, fmt.Errorf("oidc: token URL not resolved") + } + 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("client_id", c.ClientID) + form.Set("client_secret", c.ClientSecret) + if codeVerifier != "" { + form.Set("code_verifier", codeVerifier) + } + req, err := http.NewRequest(http.MethodPost, c.TokenURL, strings.NewReader(form.Encode())) + if err != nil { + return nil, err + } + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + req.Header.Set("Accept", "application/json") + res, err := client.Do(req) + if err != nil { + return nil, fmt.Errorf("oidc token: %w", err) + } + defer res.Body.Close() + body, err := io.ReadAll(io.LimitReader(res.Body, 1<<20)) + if err != nil { + return nil, err + } + var tok TokenResponse + if err := json.Unmarshal(body, &tok); err != nil { + return nil, fmt.Errorf("oidc token json: %w (%s)", err, truncate(string(body), 200)) + } + if tok.Error != "" { + return nil, fmt.Errorf("oidc token: %s (%s)", tok.Error, tok.ErrorDesc) + } + if tok.AccessToken == "" { + return nil, fmt.Errorf("oidc token: empty access_token (HTTP %d)", res.StatusCode) + } + return &tok, nil +} + +// UserInfo is the subset we need from /oauth2/userinfo (CFLMY + standard OIDC). +type UserInfo struct { + Sub string `json:"sub"` + Email string `json:"email"` + PreferredUsername string `json:"preferred_username"` + Name string `json:"name"` + Picture string `json:"picture"` + IsAdmin bool `json:"is_admin"` + AdminRole string `json:"admin_role"` +} + +// FetchUserInfo calls the userinfo endpoint with a bearer access token. +func (c Config) FetchUserInfo(client *http.Client, accessToken string) (*UserInfo, error) { + if c.UserInfoURL == "" { + return nil, fmt.Errorf("oidc: userinfo URL not resolved") + } + if client == nil { + client = &http.Client{Timeout: 15 * time.Second} + } + req, err := http.NewRequest(http.MethodGet, c.UserInfoURL, nil) + if err != nil { + return nil, err + } + req.Header.Set("Authorization", "Bearer "+accessToken) + req.Header.Set("Accept", "application/json") + res, err := client.Do(req) + if err != nil { + return nil, fmt.Errorf("oidc userinfo: %w", err) + } + defer res.Body.Close() + body, err := io.ReadAll(io.LimitReader(res.Body, 1<<20)) + if err != nil { + return nil, err + } + if res.StatusCode >= 300 { + return nil, fmt.Errorf("oidc userinfo HTTP %d: %s", res.StatusCode, truncate(string(body), 200)) + } + var info UserInfo + if err := json.Unmarshal(body, &info); err != nil { + return nil, fmt.Errorf("oidc userinfo json: %w", err) + } + if info.Sub == "" { + return nil, fmt.Errorf("oidc userinfo: missing sub") + } + return &info, nil +} + +// LocalUsername picks a stable display username for sessions / RBAC. +func (u *UserInfo) LocalUsername() string { + if u == nil { + return "" + } + if s := strings.TrimSpace(u.PreferredUsername); s != "" { + return s + } + if s := strings.TrimSpace(u.Email); s != "" { + if i := strings.IndexByte(s, '@'); i > 0 { + return s[:i] + } + return s + } + if s := strings.TrimSpace(u.Name); s != "" { + return s + } + sub := strings.TrimSpace(u.Sub) + if len(sub) > 32 { + return sub[:32] + } + return sub +} + +// IsIdPAdmin reports whether CFLMY IdP marks this user as an administrator. +func (u *UserInfo) IsIdPAdmin() bool { + if u == nil { + return false + } + if u.IsAdmin { + return true + } + return strings.TrimSpace(u.AdminRole) != "" +} + +// LocalRole maps IdP admin → site admin; otherwise defaultRole (member). +func (u *UserInfo) LocalRole(defaultRole string) string { + if defaultRole == "" { + defaultRole = "member" + } + if u.IsIdPAdmin() { + return "admin" + } + return defaultRole +} + +func truncate(s string, n int) string { + if len(s) <= n { + return s + } + return s[:n] + "…" +} + +// ParseConfig reads oidc bag from app / auth options (EN + ZH keys). +func ParseConfig(m map[string]any) Config { + if m == nil { + return Config{} + } + if nested, ok := m["oidc"].(map[string]any); ok { + 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", "用户信息地址"), + } + return c +} + +func firstStr(m map[string]any, keys ...string) string { + for _, k := range keys { + if v, ok := m[k]; ok { + switch t := v.(type) { + case string: + if s := strings.TrimSpace(t); s != "" && !strings.EqualFold(s, "none") { + return s + } + } + } + } + return "" +} diff --git a/plugins/web/internal/oidc/oidc_test.go b/plugins/web/internal/oidc/oidc_test.go new file mode 100644 index 0000000..df57968 --- /dev/null +++ b/plugins/web/internal/oidc/oidc_test.go @@ -0,0 +1,49 @@ +package oidc_test + +import ( + "testing" + + "github.com/marqdo/marqdo/plugins/web/internal/oidc" +) + +func TestUserInfoLocalRole(t *testing.T) { + u := &oidc.UserInfo{PreferredUsername: "alice", IsAdmin: false} + if u.LocalRole("member") != "member" { + t.Fatal("expected member") + } + u.IsAdmin = true + if u.LocalRole("member") != "admin" { + t.Fatal("expected admin from is_admin") + } + u.IsAdmin = false + u.AdminRole = "super_admin" + if u.LocalRole("member") != "admin" { + t.Fatal("expected admin from admin_role") + } + if u.LocalUsername() != "alice" { + t.Fatalf("username=%s", u.LocalUsername()) + } +} + +func TestPKCEAndParse(t *testing.T) { + v, err := oidc.RandomURLString(32) + if err != nil || v == "" { + t.Fatal(err) + } + ch := oidc.PKCEChallengeS256(v) + if len(ch) < 20 { + t.Fatalf("challenge=%q", ch) + } + c := oidc.ParseConfig(map[string]any{ + "发行方": "https://id.example.com", + "客户端编号": "app_x", + "客户端密钥": "secret", + "回调": "http://localhost:18085/oidc/callback", + }) + if !c.Enabled() { + t.Fatal("expected enabled") + } + if c.Callback() != "/oidc/callback" { + t.Fatalf("callback=%s", c.Callback()) + } +} diff --git a/plugins/web/internal/render/render.go b/plugins/web/internal/render/render.go index 8ed963a..29898c8 100644 --- a/plugins/web/internal/render/render.go +++ b/plugins/web/internal/render/render.go @@ -1356,6 +1356,9 @@ func RenderPage(page map[string]any, dbURL string, partID string) string { side := resolveLinks(page["sidebar"], dbURL, page) foot := resolveLinks(page["footer"], dbURL, page) intro, items, total := resolveMain(page, dbURL) + if params, ok := page["params"].(map[string]any); ok && len(params) > 0 && intro != "" { + intro = ResolveRouteParams(intro, params) + } navCSS, mqPairs := navMediaClassMapMany(nav, side, foot) extra, _ := page["styles_css"].(string) if navCSS != "" { diff --git a/plugins/web/plugin.go b/plugins/web/plugin.go index 6470289..0f550b1 100644 --- a/plugins/web/plugin.go +++ b/plugins/web/plugin.go @@ -111,6 +111,7 @@ extern int web_auth_check(char *args_json, char **out_json, char **err_msg); extern int web_auth_logout(char *args_json, char **out_json, char **err_msg); extern int web_auth_new(char *args_json, char **out_json, char **err_msg); extern int web_app_auth(char *args_json, char **out_json, char **err_msg); +extern int web_app_oidc(char *args_json, char **out_json, char **err_msg); extern int web_app_gate(char *args_json, char **out_json, char **err_msg); extern int web_app_rbac(char *args_json, char **out_json, char **err_msg); extern int web_app_tenant(char *args_json, char **out_json, char **err_msg); @@ -221,6 +222,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_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", 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;