Release 2.7.0: executable handbooks and native user-site workflows

This commit is contained in:
cflmy committed 2026-11-10 17:03:06 +08:00
1 parent aa0c4d0f55
commit d9aef957f7
562 files changed
+21064 -20387

No files matched your search

+44 -3
View File
@@ -6,11 +6,13 @@ import (
"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"
@@ -372,7 +374,7 @@ func (st *state) hasPageRoute(path string) bool {
return ok
}
func (st *state) mountAuthRoutes(mux *http.ServeMux) {
func (st *state) mountAuthRoutes(mux routeRegistrar) {
st.mountOIDCRoutes(mux)
if st.auth.users == nil && !(st.auth.rbac && st.auth.register) && !st.oidcEnabled() {
return
@@ -416,6 +418,9 @@ func (st *state) mountAuthRoutes(mux *http.ServeMux) {
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)
}
}
@@ -501,7 +506,6 @@ func (st *state) handleLoginPost(w http.ResponseWriter, r *http.Request) {
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 {
@@ -558,8 +562,45 @@ func (st *state) handleLogout(w http.ResponseWriter, r *http.Request) {
}
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(`<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Admin</title></head><body><h1>Admin</h1><p>Mounted forms and their current business records (up to 100 rows per table).</p><nav><a href="/">Site</a></nav>`)
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, `<section><h2>%s</h2><p><a href="/_form/%s">Open form</a></p>`, esc(id), esc(url.PathEscape(id)))
if tableName != "" && st.dbURL != "" && !seen[tableName] {
current, err := db.Select(st.dbURL, tableName, 100, db.SelectOpts{})
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
var data strings.Builder
encoder := json.NewEncoder(&data)
encoder.SetIndent("", " ")
encoder.SetEscapeHTML(false)
if err := encoder.Encode(current["rows"]); err != nil {
http.Error(w, "cannot encode admin records", http.StatusInternalServerError)
return
}
// Escape once for HTML, preserving readable literal angle brackets
// instead of displaying JSON's optional Unicode escape sequences.
fmt.Fprintf(&body, `<h3>%s</h3><pre style="white-space:pre-wrap;overflow-wrap:anywhere">%s</pre>`, esc(tableName), esc(data.String()))
seen[tableName] = true
}
body.WriteString("</section>")
}
if len(st.forms) == 0 {
body.WriteString("<p>No forms are mounted.</p>")
}
body.WriteString("</body></html>")
w.Header().Set("Content-Type", "text/html; charset=utf-8")
_, _ = io.WriteString(w, "<!doctype html><html><body><h1>Admin</h1><p>Site administration.</p></body></html>")
_, _ = io.WriteString(w, body.String())
}
func loginDest(r *http.Request, fallback string) string {
+1 -1
View File
@@ -114,7 +114,7 @@ func (st *state) writeRegisterFailure(w http.ResponseWriter, r *http.Request, ms
_, _ = io.WriteString(w, registerPageHTML(st.auth.registerPath, &loc, csrf))
}
func (st *state) mountExtraLoginPosts(mux *http.ServeMux, already map[string]bool) {
func (st *state) mountExtraLoginPosts(mux routeRegistrar, already map[string]bool) {
for path, pageV := range st.routes {
if already[path] {
continue
+1 -1
View File
@@ -74,7 +74,7 @@ func (st *state) oidcFallbackNext(r *http.Request) string {
return "/"
}
func (st *state) mountOIDCRoutes(mux *http.ServeMux) {
func (st *state) mountOIDCRoutes(mux routeRegistrar) {
if !st.oidcEnabled() {
return
}
@@ -56,4 +56,3 @@ func TestResolveSessionReplacesStaleCookie(t *testing.T) {
t.Fatalf("live session should not Set-Cookie again")
}
}
+171
View File
@@ -0,0 +1,171 @@
package httpx
import (
"fmt"
"net/http"
"regexp"
"sort"
"strings"
"github.com/marqdo/marqdo/plugins/web/internal/app"
"github.com/marqdo/marqdo/plugins/web/internal/artifact"
"github.com/marqdo/marqdo/plugins/web/internal/middleware"
"github.com/marqdo/marqdo/plugins/web/internal/oidc"
)
type recordedMux struct {
validate *http.ServeMux
patterns []string
}
func (mux *recordedMux) Handle(pattern string, _ http.Handler) {
// Validate registration conflicts without retaining or running handlers.
mux.validate.HandleFunc(pattern, func(http.ResponseWriter, *http.Request) {})
mux.patterns = append(mux.patterns, pattern)
}
func (mux *recordedMux) HandleFunc(pattern string, handler func(http.ResponseWriter, *http.Request)) {
mux.Handle(pattern, http.HandlerFunc(handler))
}
var tailWildcard = regexp.MustCompile(`\{([^{}]+)\.\.\.\}`)
func inspectionPath(path string) string {
path = strings.TrimSuffix(path, "{$}")
return tailWildcard.ReplaceAllString(path, "{*$1}")
}
// InspectApp executes only trusted registration logic. It does not create a
// session, reset global runtime state, query a DB, run Documents or listen.
func InspectApp(bag map[string]any) (report map[string]any, err error) {
defer func() {
if recovered := recover(); recovered != nil {
report = nil
err = fmt.Errorf("web.inspect: invalid route registration: %v", recovered)
}
}()
if bag == nil {
bag = map[string]any{}
}
routes := routeMapOf(bag, "routes")
page, _ := bag["page"].(map[string]any)
forms := map[string]any{}
if existing, ok := bag["forms"].(map[string]any); ok {
for key, value := range existing {
forms[key] = value
}
}
collectPageForms(page, forms)
for _, value := range routes {
if page, ok := value.(map[string]any); ok {
collectPageForms(page, forms)
}
}
root := strOpt(bag, "artifact_root", "")
staticDir := strOpt(bag, "static_dir", "")
if staticDir != "" {
staticDir = resolvePath(staticDir, root)
}
icons, err := iconRoutesFromBag(bag, root, staticDir)
if err != nil {
return nil, err
}
st := &state{
page: page, routes: routes, forms: forms, mw: middleware.Parse(bag), entryDir: root,
iconRoutes: icons, redirects: redirectsOf(bag), sitemapRoutes: sitemapRoutesOf(bag),
robotsBody: robotsBodyOf(bag), page404: pageOf(bag, "page_404"), page500: pageOf(bag, "page_500"),
uploadRoutes: routeMapOf(bag, "upload_routes"), downloadRoutes: routeMapOf(bag, "download_routes"),
wsRoutes: routeMapOf(bag, "ws_routes"), galleryRoutes: routeMapOf(bag, "gallery_routes"),
proxyRoutes: routeMapOf(bag, "proxy_routes"), invokeRoutes: routeMapOf(bag, "invoke_routes"),
artifactRoutes: routeMapOf(bag, "artifact_routes"), auth: authConfigOf(bag), oidc: oidc.ParseConfig(bag),
}
// Only a nonempty DB URL determines whether DB-backed routes are enabled.
// Its existence and contents are intentionally not inspected here.
st.dbURL = dbURLOf(bag)
staticMount := app.NormalizeStaticMount(strOpt(bag, "static_mount", "/static"))
mux := &recordedMux{validate: http.NewServeMux()}
st.registerRoutes(mux, staticDir, staticMount, false)
report = artifact.InspectBag(bag, nil)
declarations := map[string]map[string]any{}
byPath := map[string]map[string]any{}
for _, row := range report["declared"].([]map[string]any) {
path := inspectionPath(goMuxPattern(fmt.Sprint(row["path"])))
method := fmt.Sprint(row["method"])
declarations[method+" "+path] = row
if _, exists := byPath[path]; !exists {
byPath[path] = row
}
}
// Classification uses the explicitly supplied Resource paths; the method
// and presence still come from the actual recorded registration.
for group, kind := range map[string]string{
"ws_routes": "websocket", "upload_routes": "upload", "download_routes": "download",
"gallery_routes": "gallery", "proxy_routes": "proxy", "redirects": "redirect", "sitemap_routes": "sitemap",
} {
for key, value := range routeMapOf(bag, group) {
spec, _ := value.(map[string]any)
path := strOpt(spec, "path", key)
if parts := strings.SplitN(path, " ", 2); len(parts) == 2 {
path = parts[1]
}
path = inspectionPath(goMuxPattern(path))
byPath[path] = map[string]any{"path": path, "kind": kind}
}
}
for _, query := range st.mw.JSONRoutes {
row := map[string]any{"path": query.Path, "method": query.Method, "kind": "data_query"}
declarations[query.Method+" "+query.Path] = row
}
var declared, system []map[string]any
seen := map[string]bool{}
for _, pattern := range mux.patterns {
method, path := "*", pattern
if parts := strings.SplitN(pattern, " ", 2); len(parts) == 2 {
method, path = parts[0], parts[1]
}
path = inspectionPath(path)
if method == "*" && (path == staticMount || path == staticMount+"/") && strOpt(bag, "static_dir", "") != "" {
method = "GET|HEAD"
}
key := method + " " + path
if seen[key] {
continue
}
seen[key] = true
row := map[string]any{"method": method, "path": path, "kind": "system"}
source, found := declarations[key]
if !found {
source, found = byPath[path]
}
if found {
for key, value := range source {
if key != "method" && key != "path" {
row[key] = value
}
}
declared = append(declared, row)
} else {
system = append(system, row)
}
}
less := func(rows []map[string]any) {
sort.Slice(rows, func(i, j int) bool {
a, b := fmt.Sprint(rows[i]["path"]), fmt.Sprint(rows[j]["path"])
if a != b {
return a < b
}
return fmt.Sprint(rows[i]["method"]) < fmt.Sprint(rows[j]["method"])
})
}
less(declared)
less(system)
if declared == nil {
declared = []map[string]any{}
}
if system == nil {
system = []map[string]any{}
}
report["scope"] = "registered"
report["declared"] = declared
report["system"] = system
return report, nil
}
@@ -0,0 +1,101 @@
package httpx
import (
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
"github.com/marqdo/marqdo/plugins/web/internal/app"
"github.com/marqdo/marqdo/plugins/web/internal/form"
"github.com/marqdo/marqdo/plugins/web/internal/session"
)
func TestInspectionUsesActualRegistrationsAfterResourceBindingsWithoutExecutingThem(t *testing.T) {
filename := filepath.Join(t.TempDir(), "must-not-create.db")
bag := app.New(map[string]any{"page": map[string]any{"title": "Home"},
"db": map[string]any{"url": "sqlite:" + filename}, "admin": true})
bag["artifact_declared"] = []any{map[string]any{"method": "GET", "path": "/", "kind": "web", "file": "index.mq.md"}}
// A cached observation is deliberately stale and must never be returned.
bag["inspect"] = map[string]any{"declared": []any{map[string]any{"path": "/stale"}}}
var err error
bag, err = app.Route(bag, "/post/{id}", map[string]any{"title": "Post"})
if err != nil {
t.Fatal(err)
}
before, err := InspectApp(bag)
if err != nil {
t.Fatal(err)
}
bag, err = app.Auth(bag, []any{map[string]any{"username": "fixture", "password": "never-return-this-secret"}}, map[string]any{"login_path": "/members/login"})
if err != nil {
t.Fatal(err)
}
bag, err = app.MountForm(bag, "article", form.New("articles", "insert", ""))
if err != nil {
t.Fatal(err)
}
bag["ws_routes"] = map[string]any{"/live/{id}": map[string]any{"mode": "echo"}}
bag["middleware"] = map[string]any{"json_routes": map[string]any{"api/items": map[string]any{"table": "items", "method": "GET"}}}
bag["artifact_routes"] = map[string]any{"GET /api/ping": map[string]any{"method": "GET", "path": "/api/ping", "file": "/never-run.mq.md"}}
bag["static_dir"] = "."
bag["static_mount"] = "/assets"
session.Configure(session.Config{TTLSec: 3600})
session.Reset(3600)
sid := session.NewID(3600)
session.SetValue(sid, "inspection_marker", "retained")
report, err := InspectApp(bag)
if err != nil {
t.Fatal(err)
}
if report["scope"] != "registered" {
t.Fatal(report)
}
type route struct{ method, path string }
observed := map[route]string{}
for _, group := range []string{"declared", "system"} {
for _, row := range report[group].([]map[string]any) {
key := route{row["method"].(string), row["path"].(string)}
if _, seen := observed[key]; seen {
t.Fatalf("duplicate registered route: %#v", key)
}
observed[key] = group
}
}
for _, key := range []route{{"GET", "/"}, {"GET", "/post/{id}"}, {"GET", "/live/{id}"}, {"GET", "/api/items"}, {"GET", "/api/ping"}} {
if observed[key] != "declared" {
t.Fatalf("missing current Resource declaration %#v: %#v", key, report)
}
}
for _, key := range []route{{"POST", "/_md"}, {"GET", "/_form/{id}"}, {"POST", "/_form/{id}"},
{"GET", "/post/{id}/_part/{part}"}, {"GET", "/members/login"}, {"POST", "/members/login"},
{"GET", "/admin/login"}, {"GET", "/admin"}, {"GET", "/admin/"}, {"GET|HEAD", "/assets/"}} {
if observed[key] != "system" {
t.Fatalf("missing actual system route %#v: %#v", key, report)
}
}
encoded, _ := json.Marshal(report)
if strings.Contains(string(encoded), "never-return-this-secret") || strings.Contains(string(encoded), "/stale") {
t.Fatalf("inspection leaked unrelated app state: %s", encoded)
}
if value, ok := session.GetValue(sid, "inspection_marker"); !ok || value != "retained" {
t.Fatal("inspection reset runtime sessions")
}
if _, err := os.Stat(filename); !os.IsNotExist(err) {
t.Fatalf("inspection opened a database: %v", err)
}
prior, _ := json.Marshal(before)
if strings.Contains(string(prior), "/live/") {
t.Fatal("inspection mutated an earlier returned observation")
}
}
func TestInspectionRejectsActualRouteConflictsWithoutStartingTheServer(t *testing.T) {
bag := app.New(map[string]any{"page": map[string]any{}})
bag["routes"] = map[string]any{"/_md": map[string]any{}}
bag["artifact_routes"] = map[string]any{"POST /_md": map[string]any{"method": "POST", "path": "/_md", "file": "never-run.mq.md"}}
if _, err := InspectApp(bag); err == nil || !strings.Contains(err.Error(), "invalid route registration") {
t.Fatalf("conflicting routes were advertised as usable: %v", err)
}
}
+90 -17
View File
@@ -18,6 +18,7 @@ import (
"time"
"github.com/marqdo/marqdo/plugins/web/internal/app"
"github.com/marqdo/marqdo/plugins/web/internal/artifact"
"github.com/marqdo/marqdo/plugins/web/internal/assets"
"github.com/marqdo/marqdo/plugins/web/internal/db"
"github.com/marqdo/marqdo/plugins/web/internal/form"
@@ -129,6 +130,23 @@ func NewHandler(appBag map[string]any, entryDir string) (http.Handler, error) {
}
mux := http.NewServeMux()
st.registerRoutes(mux, staticDir, staticMount, true)
handler := withMiddleware(mux, mw)
handler = withRBAC(handler, authCfg.gates, authCfg.loginPath)
handler = withTenant(handler, st.tenant)
handler = withStripTrailingSlash(handler)
return handler, nil
}
// routeRegistrar is shared by the real server and its read-only inventory.
// Recording registrations does not invoke any captured handler.
type routeRegistrar interface {
Handle(string, http.Handler)
HandleFunc(string, func(http.ResponseWriter, *http.Request))
}
func (st *state) registerRoutes(mux routeRegistrar, staticDir, staticMount string, logSetup bool) {
mux.HandleFunc("GET /{$}", st.handleHome)
// Part slot uses {part} (not {id}) so dynamic routes like /desk/posts/{id}
// do not collide with Go ServeMux duplicate wildcard names.
@@ -137,10 +155,10 @@ func NewHandler(appBag map[string]any, entryDir string) (http.Handler, error) {
mux.HandleFunc("POST /_form/{id}", st.handleFormPost)
mux.HandleFunc("POST /_md", st.handleMarkdownPreview)
paths := sortedKeys(routes)
paths := sortedKeys(st.routes)
for _, p := range paths {
routePath := p
pageV, _ := routes[routePath].(map[string]any)
pageV, _ := st.routes[routePath].(map[string]any)
if pageV == nil {
pageV = map[string]any{}
}
@@ -158,7 +176,7 @@ func NewHandler(appBag map[string]any, entryDir string) (http.Handler, error) {
}
}
for _, jr := range mw.JSONRoutes {
for _, jr := range st.mw.JSONRoutes {
route := jr
pattern := route.Method + " " + route.Path
mux.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) {
@@ -168,16 +186,20 @@ func NewHandler(appBag map[string]any, entryDir string) (http.Handler, error) {
// Icon routes before the static prefix so /static/favicon.svg does not
// conflict with Go 1.22+ ServeMux method/path overlap rules.
for _, ir := range iconRoutes {
for _, ir := range st.iconRoutes {
url := ir.URL
path := ir.Path
ct := ir.ContentType
if staticDir != "" && (url == staticMount || strings.HasPrefix(url, staticMount+"/")) {
// FileServer under staticMount already serves these paths.
fmt.Fprintf(os.Stderr, "marqdo web icon: %s → static %s (via %s)\n", url, path, staticMount)
if logSetup {
fmt.Fprintf(os.Stderr, "marqdo web icon: %s → static %s (via %s)\n", url, path, staticMount)
}
continue
}
fmt.Fprintf(os.Stderr, "marqdo web icon: %s → %s (%s)\n", url, path, ct)
if logSetup {
fmt.Fprintf(os.Stderr, "marqdo web icon: %s → %s (%s)\n", url, path, ct)
}
mux.HandleFunc("GET "+url, func(w http.ResponseWriter, r *http.Request) {
st.serveIcon(w, path, ct)
})
@@ -187,7 +209,9 @@ func NewHandler(appBag map[string]any, entryDir string) (http.Handler, error) {
}
if staticDir != "" {
fmt.Fprintf(os.Stderr, "marqdo web static: %s → %s\n", staticMount, staticDir)
if logSetup {
fmt.Fprintf(os.Stderr, "marqdo web static: %s → %s\n", staticMount, staticDir)
}
fs := http.StripPrefix(staticMount, http.FileServer(http.Dir(staticDir)))
// Register without method so GET+HEAD share one pattern (avoids conflicts
// with more-specific GET/HEAD icon paths under the same prefix).
@@ -245,11 +269,6 @@ func NewHandler(appBag map[string]any, entryDir string) (http.Handler, error) {
mux.HandleFunc("/{path...}", st.handleNotFound)
handler := withMiddleware(mux, mw)
handler = withRBAC(handler, authCfg.gates, authCfg.loginPath)
handler = withTenant(handler, st.tenant)
handler = withStripTrailingSlash(handler)
return handler, nil
}
// Listen binds host:port from the app bag and serves until interrupt/kill.
@@ -392,7 +411,19 @@ func (st *state) writePage(w http.ResponseWriter, r *http.Request, page map[stri
p["_auth_next"] = next
}
setCookie := st.attachCSRF(p, r)
html := render.RenderPage(p, st.dbURL, "")
html := ""
if nodes, ok := p["artifact_nodes"]; ok {
document, err := artifact.RenderViewDocument(strOpt(p, "title", ""), nodes, func(resource map[string]any) (string, error) {
return st.renderViewResource(resource, p, r)
})
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
html = document
} else {
html = render.RenderPage(p, st.dbURL, "")
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
appendSetCookie(w, setCookie)
_, _ = io.WriteString(w, html)
@@ -401,7 +432,32 @@ func (st *state) writePage(w http.ResponseWriter, r *http.Request, page map[stri
func (st *state) writePart(w http.ResponseWriter, r *http.Request, page map[string]any, id string) {
p := st.preparePage(page, r)
setCookie := st.attachCSRF(p, r)
html := render.RenderPage(p, st.dbURL, id)
html := ""
if nodes, ok := p["artifact_nodes"]; ok {
selected, found, err := artifact.FindSlot(nodes, id)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if !found {
if id != "main" {
http.NotFound(w, r)
return
}
// Keep the existing main-fragment fallback for a View without a
// named main region; never expose the Document's program source.
selected = nodes
}
html, err = artifact.RenderNodesWithResources(selected, func(resource map[string]any) (string, error) {
return st.renderViewResource(resource, p, r)
})
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
} else {
html = render.RenderPage(p, st.dbURL, id)
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
appendSetCookie(w, setCookie)
_, _ = io.WriteString(w, html)
@@ -500,7 +556,11 @@ func (st *state) handleFormGet(w http.ResponseWriter, r *http.Request) {
_, _ = io.WriteString(w, fmt.Sprintf("<p>unknown form %s</p>", id))
return
}
html := form.Render(frm, id, nil, nil, "")
page := map[string]any{}
setCookie := st.attachCSRF(page, r)
csrf, _ := page["_csrf"].(string)
html := form.Render(frm, id, nil, nil, csrf)
appendSetCookie(w, setCookie)
w.Header().Set("Content-Type", "text/html; charset=utf-8")
_, _ = io.WriteString(w, html)
}
@@ -522,6 +582,19 @@ func (st *state) handleFormPost(w http.ResponseWriter, r *http.Request) {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
csrf := ""
if st.auth.users != nil || st.auth.rbac || st.oidcEnabled() {
sid, token, setCookie := resolveSession(r)
appendSetCookie(w, setCookie)
csrf = token
_, hadCookie := session.IDFromCookie(r.Header.Get("Cookie"))
if hadCookie || r.FormValue("_csrf") != "" {
if !session.ValidateCSRF(sid, r.FormValue("_csrf")) {
http.Error(w, "Invalid or missing CSRF token", http.StatusForbidden)
return
}
}
}
data := map[string]any{}
for k, vs := range r.PostForm {
if len(vs) > 0 {
@@ -547,13 +620,13 @@ func (st *state) handleFormPost(w http.ResponseWriter, r *http.Request) {
// Prefer an explicit form redirect (e.g. cancel_href list URL) over the
// composing page path stamped as _mq_return.
redir := strOpt(res, "redirect", "/")
if (redir == "" || redir == "/") && ctx.ReturnPath != "" {
if (redir == "" || redir == "/") && ctx.ReturnPath != "" && strOpt(frm, "cancel_href", "") == "" {
redir = ctx.ReturnPath
}
http.Redirect(w, r, redir, http.StatusSeeOther)
return
}
html := form.RenderBodyCtx(frm, id, data, res["errors"], "", ctx)
html := form.RenderBodyCtx(frm, id, data, res["errors"], csrf, ctx)
w.Header().Set("Content-Type", "text/html; charset=utf-8")
_, _ = io.WriteString(w, html)
}
@@ -33,7 +33,7 @@ func parseArtifactRoute(v any) artifactRoute {
}
}
func (st *state) mountArtifactRoutes(mux *http.ServeMux) {
func (st *state) mountArtifactRoutes(mux routeRegistrar) {
for _, key := range sortedKeys(st.artifactRoutes) {
cfg := parseArtifactRoute(st.artifactRoutes[key])
if cfg.File == "" || cfg.Path == "" {
@@ -131,7 +131,7 @@ func (st *state) handleArtifact(w http.ResponseWriter, r *http.Request, route ar
}
}
value, err := plugin.RunArtifact(route.File, payload)
value, err := plugin.RunArtifactAtRoot(route.File, payload, st.entryDir)
if err != nil {
jsonErr(w, http.StatusInternalServerError, err.Error())
return
+1 -1
View File
@@ -63,7 +63,7 @@ func parseInvokeRoute(v any) invokeRoute {
}
}
func (st *state) mountInvokeRoutes(mux *http.ServeMux) {
func (st *state) mountInvokeRoutes(mux routeRegistrar) {
for _, key := range sortedKeys(st.invokeRoutes) {
cfg := parseInvokeRoute(st.invokeRoutes[key])
path := routePathKey(key)
+3 -3
View File
@@ -47,7 +47,7 @@ func parseDownloadRoute(v any) downloadRoute {
}
}
func (st *state) mountUploadRoutes(mux *http.ServeMux) {
func (st *state) mountUploadRoutes(mux routeRegistrar) {
for _, path := range sortedKeys(st.uploadRoutes) {
routePath := path
cfg := parseUploadRoute(st.uploadRoutes[path])
@@ -57,7 +57,7 @@ func (st *state) mountUploadRoutes(mux *http.ServeMux) {
}
}
func (st *state) mountDownloadRoutes(mux *http.ServeMux) {
func (st *state) mountDownloadRoutes(mux routeRegistrar) {
for _, path := range sortedKeys(st.downloadRoutes) {
routePath := path
cfg := parseDownloadRoute(st.downloadRoutes[path])
@@ -68,7 +68,7 @@ func (st *state) mountDownloadRoutes(mux *http.ServeMux) {
}
}
func (st *state) mountGalleryRoutes(mux *http.ServeMux) {
func (st *state) mountGalleryRoutes(mux routeRegistrar) {
for _, path := range sortedKeys(st.galleryRoutes) {
cfg, _ := st.galleryRoutes[path].(map[string]any)
mux.HandleFunc("GET "+path, func(w http.ResponseWriter, r *http.Request) {
+1 -1
View File
@@ -90,7 +90,7 @@ func parseHeadersFromEnvStr(s string) []envHeader {
return out
}
func (st *state) mountProxyRoutes(mux *http.ServeMux) {
func (st *state) mountProxyRoutes(mux routeRegistrar) {
for _, key := range sortedKeys(st.proxyRoutes) {
cfg := parseProxyRoute(st.proxyRoutes[key])
path := routePathKey(key)
+1 -1
View File
@@ -13,7 +13,7 @@ import (
// System runtime control routes (M-R3 / M-R4). Cancel and event replay do not
// enter the Marqdo interpreter lock.
func (st *state) mountRuntimeRoutes(mux *http.ServeMux) {
func (st *state) mountRuntimeRoutes(mux routeRegistrar) {
mux.HandleFunc("POST /_runtime/tasks", st.handleRuntimeAdmit)
mux.HandleFunc("GET /_runtime/tasks/{id}", st.handleRuntimeGet)
mux.HandleFunc("POST /_runtime/tasks/{id}/cancel", st.handleRuntimeCancel)
+1 -1
View File
@@ -28,7 +28,7 @@ func sameOrigin(r *http.Request) bool {
return err == nil && strings.EqualFold(u.Host, r.Host)
}
func (st *state) mountWSRoutes(mux *http.ServeMux) {
func (st *state) mountWSRoutes(mux routeRegistrar) {
for _, path := range sortedKeys(st.wsRoutes) {
spec := ws.ParseRouteSpec(st.wsRoutes[path]) // mode + optional room_key / on_message
routePath := path
@@ -0,0 +1,185 @@
package httpx
import (
"fmt"
"net/http"
"regexp"
"strings"
"github.com/marqdo/marqdo/plugins/web/internal/artifact"
"github.com/marqdo/marqdo/plugins/web/internal/db"
"github.com/marqdo/marqdo/plugins/web/internal/form"
"github.com/marqdo/marqdo/plugins/web/internal/render"
"github.com/marqdo/marqdo/plugins/web/internal/tenant"
)
// ValidateViewResource validates the closed Resource contracts without IO.
// Assembly calls this before listening; request rendering validates again.
func ValidateViewResource(resource map[string]any) (string, error) {
kind, _ := resource["_type"].(string)
switch kind {
case "document_head":
_, err := artifact.ParseDocumentHead(resource)
return "", err
case "data_query":
if source, ok := resource["source"].(string); !ok || strings.TrimSpace(source) == "" {
return "", fmt.Errorf("data_query: source must be a nonempty table name")
}
for _, key := range []string{"order", "link_prefix"} {
if value, exists := resource[key]; exists {
if _, ok := value.(string); !ok {
return "", fmt.Errorf("data_query: %s must be text", key)
}
}
}
for _, key := range []string{"detail", "tenant_scope"} {
if value, exists := resource[key]; exists {
if _, ok := value.(bool); !ok {
return "", fmt.Errorf("data_query: %s must be boolean", key)
}
}
}
if raw, exists := resource["limit"]; exists {
n, ok := raw.(float64)
if !ok || n < 1 || n > 1000 || n != float64(int64(n)) {
return "", fmt.Errorf("data_query: limit must be an integer in 1..1000")
}
}
if prefix, _ := resource["link_prefix"].(string); prefix != "" && (!strings.HasPrefix(prefix, "/") || strings.HasPrefix(prefix, "//")) {
return "", fmt.Errorf("data_query: link_prefix must be site-relative")
}
if where := resource["where"]; where != nil {
switch where.(type) {
case map[string]any, []any:
default:
return "", fmt.Errorf("data_query: where must be a native condition map or list")
}
}
case "form_ref":
if id, ok := resource["id"].(string); !ok || strings.TrimSpace(id) == "" {
return "", fmt.Errorf("form_ref: id must name an explicitly mounted form")
}
case "view_navigation":
region, _ := resource["region"].(string)
if region != "nav" && region != "sidebar" && region != "footer" {
return "", fmt.Errorf("view_navigation: region must be nav, sidebar or footer")
}
switch resource["items"].(type) {
case map[string]any, []any:
default:
return "", fmt.Errorf("view_navigation: items must be link records")
}
default:
return "", fmt.Errorf("unsupported View Resource %q", kind)
}
return "", nil
}
var viewParameter = regexp.MustCompile(`\{([^{}]+)\}`)
// Copy parameterized conditions without mutating the retained startup nodes.
func resourceWhere(value any, params map[string]any) (any, error) {
switch value := value.(type) {
case string:
var missing string
out := viewParameter.ReplaceAllStringFunc(value, func(token string) string {
key := token[1 : len(token)-1]
actual, ok := params[key]
if !ok {
missing = key
return token
}
return fmt.Sprint(actual)
})
if missing != "" {
return nil, fmt.Errorf("data_query: missing route parameter %q", missing)
}
return out, nil
case map[string]any:
out := make(map[string]any, len(value))
for key, item := range value {
resolved, err := resourceWhere(item, params)
if err != nil {
return nil, err
}
out[key] = resolved
}
return out, nil
case []any:
out := make([]any, len(value))
for i, item := range value {
resolved, err := resourceWhere(item, params)
if err != nil {
return nil, err
}
out[i] = resolved
}
return out, nil
default:
return value, nil
}
}
func (st *state) renderViewResource(resource, page map[string]any, request *http.Request) (string, error) {
if _, err := ValidateViewResource(resource); err != nil {
return "", err
}
switch resource["_type"] {
case "document_head":
return "", nil
case "data_query":
if st.dbURL == "" {
return "", fmt.Errorf("data_query: the application has no database resource")
}
params, _ := page["params"].(map[string]any)
where, err := resourceWhere(resource["where"], params)
if err != nil {
return "", err
}
scoped, _ := resource["tenant_scope"].(bool)
if scoped && !st.tenant.Enabled() {
return "", fmt.Errorf("data_query: scoped query requires a tenant policy")
}
if scoped || st.tenant.DefaultScope {
id := tenant.FromContext(request.Context())
if id == "" {
return "", fmt.Errorf("data_query: tenant required")
}
where = tenant.MergeWhere(where, st.tenant.Column, id)
}
limit := int64(50)
if n, ok := resource["limit"].(float64); ok {
limit = int64(n)
}
order, _ := resource["order"].(string)
rows, err := db.Select(st.dbURL, resource["source"].(string), limit, db.SelectOpts{Where: where, Order: order})
if err != nil {
return "", err
}
detail, _ := resource["detail"].(bool)
prefix, _ := resource["link_prefix"].(string)
return render.RenderQueryRows(rows["rows"], detail, prefix), nil
case "form_ref":
id := resource["id"].(string)
selected, ok := st.forms[id].(map[string]any)
if !ok {
return "", fmt.Errorf("form_ref: form %q was not explicitly mounted", id)
}
csrf, _ := page["_csrf"].(string)
return form.RenderBodyCtx(selected, id, nil, nil, csrf, st.requestContext(request, nil)), nil
case "view_navigation":
region := resource["region"].(string)
navigation := map[string]any{region: resource["items"]}
if region == "nav" {
navigation["nav"] = resource["items"]
}
if logged, ok := page["_logged_in"]; ok {
navigation["_logged_in"] = logged
}
if user, ok := page["_nav_user"]; ok {
navigation["_nav_user"] = user
}
return render.RenderPage(navigation, "", region), nil
}
return "", fmt.Errorf("unsupported View Resource")
}
@@ -0,0 +1,205 @@
package httpx
import (
"net/http"
"net/http/httptest"
"net/url"
"path/filepath"
"regexp"
"strings"
"testing"
"github.com/marqdo/marqdo/plugins/web/internal/app"
"github.com/marqdo/marqdo/plugins/web/internal/artifact"
"github.com/marqdo/marqdo/plugins/web/internal/db"
"github.com/marqdo/marqdo/plugins/web/internal/form"
"github.com/marqdo/marqdo/plugins/web/internal/session"
)
func resourceNode(resource map[string]any) map[string]any {
return map[string]any{"type": "resource", "value": resource, "slot": "content"}
}
func TestViewResourcesObserveRequestsFormsAndNavigation(t *testing.T) {
uri := "sqlite:" + filepath.Join(t.TempDir(), "view.db")
fields := []any{
map[string]any{"name": "id", "type": "integer", "nullable": false},
map[string]any{"name": "title", "type": "text", "nullable": false},
map[string]any{"name": "slug", "type": "text", "nullable": true},
map[string]any{"name": "summary", "type": "text", "nullable": true},
map[string]any{"name": "body", "type": "text", "nullable": true},
}
if _, err := db.Init(uri, "articles", fields); err != nil {
t.Fatal(err)
}
if _, err := db.Insert(uri, "articles", map[string]any{
"title": "Original <title>", "slug": "first", "summary": "Short summary", "body": "Full article body",
}); err != nil {
t.Fatal(err)
}
query := map[string]any{"_type": "data_query", "source": "articles", "limit": float64(50), "link_prefix": "/post/"}
navigation := map[string]any{"_type": "view_navigation", "region": "nav", "items": []any{
map[string]any{"label": "Guest login", "href": "/admin/login", "when": "guest"},
map[string]any{"label": "Private desk", "href": "/admin", "when": "auth"},
}}
page := map[string]any{"title": "View resources", "artifact_nodes": []any{
resourceNode(navigation), resourceNode(query),
resourceNode(map[string]any{"_type": "form_ref", "id": "article"}),
}}
bag := app.New(map[string]any{"page": page, "db": map[string]any{"url": uri}})
var err error
bag, err = app.Auth(bag, []any{map[string]any{"username": "admin", "password": "secret", "role": "admin"}}, nil)
if err != nil {
t.Fatal(err)
}
selected := form.SetFields(form.New("articles", "insert", ""), fields[1:2])
selected = form.SetRules(selected, []any{map[string]any{"field": "title", "rule": "required", "message": "Title required"}})
selected = form.SetLabels(selected, "Publish", "Cancel", "/")
bag, err = app.MountForm(bag, "article", selected)
if err != nil {
t.Fatal(err)
}
detailed := map[string]any{"_type": "data_query", "source": "articles", "detail": true,
"where": map[string]any{"slug": "{slug}"}}
bag, err = app.Route(bag, "/post/{slug}", map[string]any{"title": "Article", "artifact_nodes": []any{resourceNode(detailed)}})
if err != nil {
t.Fatal(err)
}
handler, err := NewHandler(bag, "")
if err != nil {
t.Fatal(err)
}
call := func(method, path, body, cookie string) *httptest.ResponseRecorder {
request := httptest.NewRequest(method, path, strings.NewReader(body))
if body != "" {
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
}
if cookie != "" {
request.Header.Set("Cookie", cookie)
}
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, request)
return recorder
}
initial := call("GET", "/", "", "")
if initial.Code != http.StatusOK {
t.Fatalf("initial: %d %s", initial.Code, initial.Body.String())
}
text := initial.Body.String()
if !strings.Contains(text, "Guest login") || strings.Contains(text, "Private desk") ||
!strings.Contains(text, "Short summary") || strings.Contains(text, "Full article body") ||
!strings.Contains(text, "Original &lt;title&gt;") {
t.Fatal(text)
}
cookies := initial.Result().Cookies()
if len(cookies) == 0 {
t.Fatal("rendered form has no actual session cookie")
}
cookie := cookies[0].Name + "=" + cookies[0].Value
match := regexp.MustCompile(`name="_csrf" value="([^"]+)"`).FindStringSubmatch(text)
if len(match) != 2 {
t.Fatal("resource form omitted its CSRF token")
}
token := match[1]
bad := call("POST", "/_form/article", "title=Rejected&_csrf=wrong", cookie)
if bad.Code != http.StatusForbidden {
t.Fatalf("bad csrf accepted: %d %s", bad.Code, bad.Body.String())
}
invalid := call("POST", "/_form/article", url.Values{"_csrf": {token}, "title": {""}}.Encode(), cookie)
if invalid.Code != http.StatusOK || !strings.Contains(invalid.Body.String(), "Title required") ||
!strings.Contains(invalid.Body.String(), `name="_csrf" value="`+token+`"`) {
t.Fatalf("validation retry: %d %s", invalid.Code, invalid.Body.String())
}
valid := call("POST", "/_form/article", url.Values{"_csrf": {token}, "title": {"Inserted after startup"}, "_mq_return": {"/new"}}.Encode(), cookie)
if valid.Code != http.StatusSeeOther || valid.Header().Get("Location") != "/" {
t.Fatalf("submit: %d %s", valid.Code, valid.Body.String())
}
current := call("GET", "/", "", cookie)
if !strings.Contains(current.Body.String(), "Inserted after startup") {
t.Fatal("query cached startup rows")
}
fragment := call("GET", "/_part/main", "", cookie)
if fragment.Code != http.StatusOK || !strings.Contains(fragment.Body.String(), "Inserted after startup") ||
!strings.Contains(fragment.Body.String(), `name="_csrf" value="`+token+`"`) ||
strings.Contains(fragment.Body.String(), "<!DOCTYPE") {
t.Fatalf("request fragment lost context: %d %s", fragment.Code, fragment.Body.String())
}
unknown := call("GET", "/_part/not-declared", "", cookie)
if unknown.Code != http.StatusNotFound {
t.Fatalf("unknown View slot: %d", unknown.Code)
}
detail := call("GET", "/post/first?slug=other", "", cookie)
if detail.Code != http.StatusOK || !strings.Contains(detail.Body.String(), "Full article body") ||
strings.Contains(detail.Body.String(), "Short summary") {
t.Fatal(detail.Body.String())
}
if detailed["where"].(map[string]any)["slug"] != "{slug}" {
t.Fatal("request mutated retained Resource")
}
sid, ok := session.IDFromCookie(cookie)
if !ok || !session.SetValue(sid, "username", "admin") {
t.Fatal("could not establish fixture session")
}
logged := call("GET", "/", "", cookie)
if strings.Contains(logged.Body.String(), "Guest login") || !strings.Contains(logged.Body.String(), "Private desk") {
t.Fatal(logged.Body.String())
}
}
func TestViewResourceValidationDoesNotQueryAndFailuresRemainVisible(t *testing.T) {
query := map[string]any{"_type": "data_query", "source": "missing"}
if _, err := artifact.RenderNodesWithResources([]any{resourceNode(query)}, ValidateViewResource); err != nil {
t.Fatalf("startup unexpectedly queried missing DB: %v", err)
}
for _, resource := range []map[string]any{
{"_type": "invented"}, {"_type": "data_query", "source": "items", "limit": 1.5},
{"_type": "data_query", "source": "items", "link_prefix": "javascript:"},
{"_type": "form_ref", "id": ""},
} {
if _, err := ValidateViewResource(resource); err == nil {
t.Fatalf("bad resource accepted: %#v", resource)
}
}
if _, err := artifact.RenderNodes([]any{resourceNode(query)}); err == nil {
t.Fatal("offline render invented request context")
}
bag := app.New(map[string]any{"page": map[string]any{"artifact_nodes": []any{resourceNode(query)}}})
handler, err := NewHandler(bag, "")
if err != nil {
t.Fatal(err)
}
response := httptest.NewRecorder()
handler.ServeHTTP(response, httptest.NewRequest("GET", "/", nil))
if response.Code != http.StatusInternalServerError || !strings.Contains(response.Body.String(), "no database") {
t.Fatalf("missing backend became successful empty content: %d %s", response.Code, response.Body.String())
}
}
func TestViewHeadResourcesServeInHeadAndNeverLeakIntoFragments(t *testing.T) {
nodes := []any{
map[string]any{"type": "resource", "value": map[string]any{"_type": "document_head", "meta": map[string]any{"key": "description", "value": "Actual SEO"}, "links": []any{map[string]any{"rel": "stylesheet", "href": "/theme.css"}}}},
map[string]any{"type": "markdown", "slot": "content", "value": "# Real content"},
}
bag := app.New(map[string]any{"page": map[string]any{"title": "Head test", "artifact_nodes": nodes}})
handler, err := NewHandler(bag, "")
if err != nil {
t.Fatal(err)
}
for _, path := range []string{"/", "/_part/main", "/_part/content"} {
response := httptest.NewRecorder()
handler.ServeHTTP(response, httptest.NewRequest("GET", path, nil))
body := response.Body.String()
if response.Code != http.StatusOK || !strings.Contains(body, "Real content") {
t.Fatalf("%s %d %s", path, response.Code, body)
}
if path == "/" {
head, rest, _ := strings.Cut(body, "</head>")
if !strings.Contains(head, `<meta name="description" content="Actual SEO"`) || !strings.Contains(head, `href="/theme.css"`) || strings.Contains(rest, "Actual SEO") {
t.Fatal(body)
}
} else if strings.Contains(body, "Actual SEO") || strings.Contains(body, "<head") || strings.Contains(body, "theme.css") {
t.Fatal(body)
}
}
}