package httpx import ( "encoding/json" "fmt" "io" "net" "net/http" "net/url" "strconv" "strings" "github.com/marqdo/marqdo/plugins/web/internal/app" "github.com/marqdo/marqdo/plugins/web/internal/auth" "github.com/marqdo/marqdo/plugins/web/internal/db" "github.com/marqdo/marqdo/plugins/web/internal/password" "github.com/marqdo/marqdo/plugins/web/internal/ratelimit" "github.com/marqdo/marqdo/plugins/web/internal/rbac" "github.com/marqdo/marqdo/plugins/web/internal/session" ) type gateMatch int const ( gateMatchPrefix gateMatch = 0 gateMatchExact gateMatch = 1 ) type onDeny int const ( onDenyForbid onDeny = 0 onDenyRedirect onDeny = 1 ) type gate struct { path string roles []string permissions []string matchMode gateMatch onDeny onDeny exclude []string } type authConfig struct { users any sessionTTL uint64 cookieSecure bool admin bool adminPrefix string loginPath string loginRedirect string logoutRedirect string gates []gate rbac bool rbacDesk bool register bool registerPath string defaultRole string } func authConfigOf(appBag map[string]any) authConfig { cfg := authConfig{ admin: boolish(appBag["admin"]), adminPrefix: app.AdminPrefix(appBag), sessionTTL: 3600, } cfg.loginPath = strOpt(appBag, "login_path", "") if cfg.loginPath == "" { cfg.loginPath = cfg.adminPrefix + "/login" } cfg.loginRedirect = strOpt(appBag, "login_redirect", "") if cfg.loginRedirect == "" { cfg.loginRedirect = cfg.adminPrefix } cfg.logoutRedirect = strOpt(appBag, "logout_redirect", "") if cfg.logoutRedirect == "" { cfg.logoutRedirect = cfg.loginPath } if v, ok := appBag["cookie_secure"].(bool); ok { cfg.cookieSecure = v } cfg.registerPath = strOpt(appBag, "register_path", "") if authBag, ok := appBag["auth"].(map[string]any); ok { cfg.users = authBag["users"] if n, ok := asUint64(authBag["session_ttl"]); ok && n > 0 { cfg.sessionTTL = n } else if n, ok := asUint64(authBag["ttl"]); ok && n > 0 { cfg.sessionTTL = n } cfg.rbac = boolish(authBag["rbac"]) cfg.rbacDesk = boolish(authBag["rbac_desk"]) cfg.register = boolish(authBag["register"]) if p := strOpt(authBag, "register_path", ""); p != "" { cfg.registerPath = p } cfg.defaultRole = strOpt(authBag, "default_role", "") if cfg.defaultRole == "" { cfg.defaultRole = "member" } } if cfg.registerPath == "" { cfg.registerPath = "/register" } cfg.gates = parseGates(appBag["gates"]) return cfg } func parseGates(v any) []gate { arr, ok := v.([]any) if !ok { return nil } out := make([]gate, 0, len(arr)) for _, item := range arr { m, ok := item.(map[string]any) if !ok { continue } path := strings.TrimSpace(strOpt(m, "path", "")) if path == "" { path = strings.TrimSpace(strOpt(m, "路径", "")) } if path == "" { continue } starred := strings.HasSuffix(path, "*") if starred { path = strings.TrimSuffix(path, "*") } roles := parseGateRoles(m["roles"]) if roles == nil { roles = parseGateRoles(m["角色"]) } perms := parseGateRoles(m["permissions"]) if perms == nil { perms = parseGateRoles(m["权限"]) } if len(roles) == 0 && len(perms) == 0 { roles = []string{"admin"} } matchS := strings.ToLower(strings.TrimSpace(strOpt(m, "match", ""))) if matchS == "" { matchS = strings.ToLower(strings.TrimSpace(strOpt(m, "匹配", ""))) } matchMode := gateMatchPrefix switch matchS { case "exact", "精确": matchMode = gateMatchExact case "prefix", "前缀": matchMode = gateMatchPrefix default: if starred { matchMode = gateMatchPrefix } } denyS := strings.ToLower(strings.TrimSpace(strOpt(m, "on_deny", ""))) if denyS == "" { denyS = strings.ToLower(strings.TrimSpace(strOpt(m, "拒绝", ""))) } on := onDenyForbid switch denyS { case "redirect", "重定向", "login": on = onDenyRedirect case "forbid", "禁止", "403": on = onDenyForbid } out = append(out, gate{ path: path, roles: roles, permissions: perms, matchMode: matchMode, onDeny: on, exclude: parseExclude(m["exclude"], m["排除"]), }) } return out } func parseGateRoles(v any) []string { switch t := v.(type) { case string: return session.ParseRolesCSV(t) case []any: var out []string for _, item := range t { if s, ok := item.(string); ok && strings.TrimSpace(s) != "" { out = append(out, strings.ToLower(strings.TrimSpace(s))) } } return out case []string: var out []string for _, s := range t { if strings.TrimSpace(s) != "" { out = append(out, strings.ToLower(strings.TrimSpace(s))) } } return out default: return nil } } func parseExclude(primary, alt any) []string { if primary == nil { primary = alt } switch t := primary.(type) { case string: var out []string for _, part := range strings.Split(t, ",") { part = strings.TrimSpace(part) if part != "" { out = append(out, part) } } return out case []any: var out []string for _, item := range t { if s, ok := item.(string); ok { s = strings.TrimSpace(s) if s != "" { out = append(out, s) } } } return out default: return nil } } func gateMatches(path string, g gate) bool { pat := strings.TrimRight(strings.TrimSuffix(g.path, "*"), "/") if pat == "" { pat = "/" } switch g.matchMode { case gateMatchExact: return path == pat || path == g.path default: return path == pat || strings.HasPrefix(path, pat+"/") } } 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 } // Local logout must always run; never bounce visitors to login→IdP first. if path == "/logout" || strings.HasSuffix(path, "/logout") { return true } for _, ex := range exclude { ex = strings.TrimRight(strings.TrimSuffix(ex, "*"), "/") if ex == "" { continue } if path == ex || strings.HasPrefix(path, ex+"/") { return true } } return false } func withRBAC(next http.Handler, gates []gate, loginPath string) http.Handler { if len(gates) == 0 { return next } return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { path := r.URL.Path cookie := r.Header.Get("Cookie") for _, g := range gates { if !gateMatches(path, g) { continue } if pathExcluded(path, g.exclude, loginPath) { break } role := session.RoleFromCookie(cookie) allowed := false if len(g.permissions) > 0 { held := session.PermissionsFromCookie(cookie) if len(held) == 0 && role != "visitor" { held = expandLegacyRole(role) } allowed = session.PermissionAllowed(held, g.permissions) } else { allowed = session.RoleAllowed(role, g.roles) } if !allowed { if role == "visitor" && g.onDeny == onDenyRedirect { nextQ := urlEncodePath(path) dest := loginPath if nextQ != "" && path != loginPath { dest = loginPath + "?next=" + nextQ } http.Redirect(w, r, dest, http.StatusSeeOther) return } w.Header().Set("Content-Type", "text/html; charset=utf-8") w.WriteHeader(http.StatusForbidden) _, _ = io.WriteString(w, fmt.Sprintf( "
Role `%s` cannot access `%s`.
", esc(role), esc(path))) return } break } next.ServeHTTP(w, r) }) } func expandLegacyRole(role string) []string { switch strings.ToLower(strings.TrimSpace(role)) { case "superadmin", "admin": return []string{ "comments:create", "comments:delete", "comments:delete_own", "desk:access", "roles:manage", "posts:edit", "users:manage", } case "member", "user": return []string{"comments:create", "comments:delete_own"} case "editor", "author": return []string{"comments:create", "comments:delete_own", "posts:edit", "desk:access"} default: return nil } } func urlEncodePath(path string) string { var out strings.Builder for _, b := range []byte(path) { switch { case b >= 'A' && b <= 'Z', b >= 'a' && b <= 'z', b >= '0' && b <= '9', b == '-', b == '_', b == '.', b == '~', b == '/': out.WriteByte(b) default: out.WriteString(fmt.Sprintf("%%%02X", b)) } } return out.String() } func withNavAuth(page map[string]any, cookieHeader string) { sid, ok := session.IDFromCookie(cookieHeader) loggedIn := false var username string if ok && sid != "" { if v, has := session.GetValue(sid, "username"); has { if u, ok := v.(string); ok && u != "" { loggedIn = true username = u } } } page["_logged_in"] = loggedIn if loggedIn { page["_nav_user"] = username } else { delete(page, "_nav_user") } } func (st *state) hasPageRoute(path string) bool { if path == "" || st.routes == nil { return false } _, ok := st.routes[path] return ok } func (st *state) mountAuthRoutes(mux routeRegistrar) { 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 || st.oidcEnabled() { lp := st.auth.loginPath // Site pages may own GET /login (or /desk/login); always keep POST for auth. if !st.hasPageRoute(lp) { mux.HandleFunc("GET "+lp, st.handleLoginGet) } mux.HandleFunc("POST "+lp, st.handleLoginPost) altLogin := strings.TrimRight(st.auth.adminPrefix, "/") + "/login" if altLogin != lp { if !st.hasPageRoute(altLogin) { mux.HandleFunc("GET "+altLogin, st.handleLoginGet) } mux.HandleFunc("POST "+altLogin, st.handleLoginPost) } st.mountExtraLoginPosts(mux, map[string]bool{lp: true, altLogin: true}) logoutPath := strings.TrimRight(st.auth.adminPrefix, "/") + "/logout" mux.HandleFunc("GET "+logoutPath, st.handleLogout) } if st.auth.register && st.auth.rbac && !st.oidcEnabled() { rp := st.auth.registerPath if !st.hasPageRoute(rp) { mux.HandleFunc("GET "+rp, st.handleRegisterGet) } mux.HandleFunc("POST "+rp, st.handleRegisterPost) } // Opt-in: enable_rbac alone wires gates/schema; /_rbac HTTP surface needs desk=true. if st.auth.rbac && st.auth.rbacDesk && st.dbURL != "" { mux.HandleFunc("GET /_rbac/roles", st.handleRbacListRoles) mux.HandleFunc("GET /_rbac/permissions", st.handleRbacListPermissions) mux.HandleFunc("POST /_rbac/roles", st.handleRbacCreateRole) mux.HandleFunc("POST /_rbac/roles/{id}/permissions", st.handleRbacSetRolePerms) mux.HandleFunc("POST /_rbac/assign", st.handleRbacAssign) mux.HandleFunc("GET /_rbac/desk", st.handleRbacDesk) } if st.auth.admin { adminHome := strings.TrimRight(st.auth.adminPrefix, "/") if adminHome == "" { adminHome = "/admin" } // The canonical no-slash path must be registered too: the global // trailing-slash normalizer otherwise triggers a ServeMux redirect loop. mux.HandleFunc("GET "+adminHome, st.handleAdminHome) mux.HandleFunc("GET "+adminHome+"/{$}", st.handleAdminHome) } } 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 } cookieHdr := r.Header.Get("Cookie") if session.RoleFromCookie(cookieHdr) != "visitor" { http.Redirect(w, r, loginDest(r, st.auth.loginRedirect), http.StatusSeeOther) return } _, csrf, setCookie := resolveSession(r) html := loginPageHTML(st.auth.loginPath, nil, csrf, r.URL.Query().Get("next")) w.Header().Set("Content-Type", "text/html; charset=utf-8") appendSetCookie(w, setCookie) _, _ = io.WriteString(w, html) } 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 } if err := r.ParseForm(); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } cookieHdr := r.Header.Get("Cookie") sid, _, _ := resolveSession(r) _, hadCookie := session.IDFromCookie(cookieHdr) csrfToken := r.FormValue("_csrf") if csrfToken != "" || hadCookie { if !session.ValidateCSRF(sid, csrfToken) { st.writeAuthFailure(w, r, "Invalid or missing CSRF token. Refresh and try again.") return } } username := r.FormValue("username") password := r.FormValue("password") ip := clientIP(r) if err := ratelimit.Check(ip, username); err != nil { st.writeAuthFailure(w, r, err.Error()) return } res := st.tryLogin(username, password) if ok, _ := res["ok"].(bool); !ok { ratelimit.RecordFailure(ip, username) st.writeAuthFailure(w, r, "Invalid username or password.") return } ratelimit.ClearSuccess(ip, username) sessID, _ := res["session_id"].(string) role, _ := res["role"].(string) st.attachLoginPermissions(sessID, username, role) fallback := st.auth.loginRedirect if page := st.pageForAuthPath(r.URL.Path); page != nil { if af, ok := page["auth_form"].(map[string]any); ok { if n, ok := af["next"].(string); ok { if n = strings.TrimSpace(n); n != "" { fallback = n } } } } dest := loginDest(r, fallback) held := session.PermissionsFromSession(sessID) if (strings.HasPrefix(dest, "/desk") || strings.HasPrefix(dest, "/admin")) && !session.PermissionAllowed(held, []string{"desk:access"}) { dest = "/" } w.Header().Add("Set-Cookie", session.IssueCookie(sessID)) http.Redirect(w, r, dest, http.StatusSeeOther) } // tryLogin: GFM users first, then web_users when RBAC is on. func (st *state) tryLogin(username, password string) map[string]any { if st.auth.users != nil { res := auth.Login(username, password, st.auth.users, st.auth.sessionTTL) if ok, _ := res["ok"].(bool); ok { u, _ := res["username"].(string) role, _ := res["role"].(string) st.seedGFMUserIntoRBAC(u, password, role) return res } } if st.auth.rbac && st.dbURL != "" { role, ok, err := rbac.Authenticate(st.dbURL, username, password, passwordVerify) if err == nil && ok { id := session.NewID(st.auth.sessionTTL) session.SetValue(id, "username", username) session.SetValue(id, "role", role) return map[string]any{ "ok": true, "session_id": id, "username": username, "role": role, } } } return map[string]any{"ok": false} } func (st *state) attachLoginPermissions(sessID, username, role string) { var perms []string if st.dbURL != "" && st.auth.rbac { if dbPerms, err := rbac.PermissionsForUser(st.dbURL, username); err == nil && len(dbPerms) > 0 { perms = dbPerms } } if len(perms) == 0 { perms = rbac.ExpandRole(role) } if len(perms) == 0 { perms = expandLegacyRole(role) } auth.AttachPermissions(sessID, perms) } func (st *state) handleLogout(w http.ResponseWriter, r *http.Request) { if sid, ok := session.IDFromCookie(r.Header.Get("Cookie")); ok { auth.Logout(sid) } w.Header().Add("Set-Cookie", session.ClearCookie()) dest := strings.TrimSpace(st.auth.logoutRedirect) // With OIDC, /login (and siblings) immediately bounce to the IdP — that is // re-auth, not logout. Land on a public page instead. if dest == "" || (st.oidcEnabled() && st.isOIDCEntryPath(dest)) { dest = "/" } http.Redirect(w, r, dest, http.StatusSeeOther) } func (st *state) handleAdminHome(w http.ResponseWriter, r *http.Request) { // Only explicitly mounted forms expose their associated business tables. // Never enumerate session/credential tables just because they share a DB. var body strings.Builder body.WriteString(`Mounted forms and their current business records (up to 100 rows per table).
`) seen := map[string]bool{} for _, id := range sortedKeys(st.forms) { selected, ok := st.forms[id].(map[string]any) if !ok { continue } tableName, _ := selected["table"].(string) fmt.Fprintf(&body, `%s`, esc(tableName), esc(data.String())) seen[tableName] = true } body.WriteString("
No forms are mounted.
") } body.WriteString("") w.Header().Set("Content-Type", "text/html; charset=utf-8") _, _ = io.WriteString(w, body.String()) } func loginDest(r *http.Request, fallback string) string { next := strings.TrimSpace(r.FormValue("next")) if next == "" { next = strings.TrimSpace(r.URL.Query().Get("next")) } if next != "" && strings.HasPrefix(next, "/") && !strings.HasPrefix(next, "//") { return next } return fallback } func loginPageHTML(loginAction string, errMsg *string, csrf string, next string) string { errHTML := "" if errMsg != nil && *errMsg != "" { errHTML = fmt.Sprintf("%s
", esc(*errMsg)) } csrfField := "" if csrf != "" { csrfField = fmt.Sprintf("", esc(csrf)) } nextField := "" if next != "" && strings.HasPrefix(next, "/") && !strings.HasPrefix(next, "//") { nextField = fmt.Sprintf("", esc(next)) } return fmt.Sprintf(`%s
", esc(*errMsg)) } csrfField := "" if csrf != "" { csrfField = fmt.Sprintf("", esc(csrf)) } return fmt.Sprintf(`需 roles:manage。系统角色权限不可在此改写;可新建角色并勾选权限,或给用户赋角色。