From 410f36f7193c7759d919a1dd5d50e7b714633617 Mon Sep 17 00:00:00 2001 From: cflmy Date: Fri, 18 Sep 2026 14:53:16 +0800 Subject: [PATCH] feat(web): Postgres CRUD and fix stale-session CSRF login Wire pgx for postgres:// DB URLs, dialect-aware RBAC/sessions, and replace dead marqdo_sid cookies so login forms always get a fresh CSRF token. Co-authored-by: Cursor --- plugins/web/go.mod | 6 + plugins/web/go.sum | 16 +++ plugins/web/internal/db/db.go | 110 ++++++++++++++-- plugins/web/internal/db/dialect.go | 144 +++++++++++++++++++++ plugins/web/internal/db/txn.go | 23 +++- plugins/web/internal/httpx/helpers.go | 14 +- plugins/web/internal/httpx/helpers_test.go | 37 +++++- plugins/web/internal/rbac/rbac.go | 115 ++++++++++++---- plugins/web/internal/session/session.go | 12 +- 9 files changed, 423 insertions(+), 54 deletions(-) create mode 100644 plugins/web/internal/db/dialect.go diff --git a/plugins/web/go.mod b/plugins/web/go.mod index 998a487..0591bec 100644 --- a/plugins/web/go.mod +++ b/plugins/web/go.mod @@ -15,13 +15,19 @@ require ( github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/dustin/go-humanize v1.0.1 // indirect github.com/google/uuid v1.6.0 // indirect + github.com/jackc/pgpassfile v1.0.0 // indirect + github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect + github.com/jackc/pgx/v5 v5.7.4 // indirect + github.com/jackc/puddle/v2 v2.2.2 // indirect github.com/mattn/go-isatty v0.0.24 // indirect github.com/ncruces/go-strftime v1.0.0 // indirect github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect github.com/yuin/goldmark v1.7.8 // indirect github.com/yuin/gopher-lua v1.1.1 // indirect go.uber.org/atomic v1.11.0 // indirect + golang.org/x/sync v0.22.0 // indirect golang.org/x/sys v0.47.0 // indirect + golang.org/x/text v0.28.0 // indirect modernc.org/libc v1.75.6 // indirect modernc.org/mathutil v1.7.1 // indirect modernc.org/memory v1.12.1 // indirect diff --git a/plugins/web/go.sum b/plugins/web/go.sum index 5568d5f..8410434 100644 --- a/plugins/web/go.sum +++ b/plugins/web/go.sum @@ -8,6 +8,7 @@ github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA= github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0= github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= @@ -20,6 +21,14 @@ github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aN github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k= github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM= +github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= +github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= +github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= +github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= +github.com/jackc/pgx/v5 v5.7.4 h1:9wKznZrhWa2QiHL+NjTSPP6yjl3451BX3imWDnokYlg= +github.com/jackc/pgx/v5 v5.7.4/go.mod h1:ncY89UGWxg82EykZUwSpUKEfccBGGYq1xjrOpsbsfGQ= +github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo= +github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= github.com/klauspost/cpuid/v2 v2.2.10 h1:tBs3QSyvjDyFTq3uoc/9xFpCuOsJQFNPiAhYdw2skhE= github.com/klauspost/cpuid/v2 v2.2.10/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0= github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI= @@ -32,8 +41,11 @@ github.com/redis/go-redis/v9 v9.22.0 h1:laDvpYXTJtZLloinw1fA5Kqd6HAEH2XKxOkG/PDq github.com/redis/go-redis/v9 v9.22.0/go.mod h1:y2g0Wj8rQvuK0ELM+oxSudcLtC09JScs98I/X9gRWY4= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk= github.com/yuin/goldmark v1.7.8 h1:iERMLn0/QJeHFhxSt3p6PeN9mGnvIKSpG9YYorDMnic= github.com/yuin/goldmark v1.7.8/go.mod h1:uzxRWxtg69N339t3louHJ7+O03ezfj6PlliRlaOzY1E= github.com/yuin/gopher-lua v1.1.1 h1:kYKnWBjvbNP4XLT3+bPEwAXJx262OhaHDWDVOPjL46M= @@ -50,8 +62,12 @@ golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek= golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs= golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= +golang.org/x/text v0.28.0 h1:rhazDwis8INMIwQ4tpjLDzUhx6RlXqZNPEM0huQojng= +golang.org/x/text v0.28.0/go.mod h1:U8nCwOR8jO/marOQ0QbDiOngZVEBB7MAiitBuMjXiNU= golang.org/x/tools v0.48.0 h1:3+hClM1aLL5mjMKm5ovokw9epgRXPuu2tILgismM6RE= golang.org/x/tools v0.48.0/go.mod h1:08xX0orndb/F7jJxGDicx061tyd5pcMto75YMAXr6lk= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= modernc.org/cc/v4 v4.29.2 h1:h6+9ciCnPKutf4I03CvheAvDLX7+IHlqR6Iy6J+cgd8= modernc.org/cc/v4 v4.29.2/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI= modernc.org/ccgo/v4 v4.35.0 h1:F+TUsmw09QxLzmi3aeYYGxjAXarmZaKgj3mKQHNaA8w= diff --git a/plugins/web/internal/db/db.go b/plugins/web/internal/db/db.go index c03ed46..3a35ab7 100644 --- a/plugins/web/internal/db/db.go +++ b/plugins/web/internal/db/db.go @@ -12,6 +12,7 @@ import ( "time" "github.com/marqdo/marqdo/plugins/web/internal/table" + _ "github.com/jackc/pgx/v5/stdlib" _ "modernc.org/sqlite" ) @@ -54,13 +55,27 @@ func pathOf(url string) string { } func open(url string) (*sql.DB, error) { - path := pathOf(url) poolMu.Lock() defer poolMu.Unlock() key := ResolveURL(url) if db, ok := pool[key]; ok { return db, nil } + if IsPostgres(url) { + db, err := sql.Open("pgx", key) + if err != nil { + return nil, err + } + db.SetMaxOpenConns(16) + db.SetMaxIdleConns(4) + if err := db.Ping(); err != nil { + _ = db.Close() + return nil, fmt.Errorf("postgres ping: %w", err) + } + pool[key] = db + return db, nil + } + path := pathOf(url) if parent := filepath.Dir(path); parent != "" && parent != "." { if err := os.MkdirAll(parent, 0o755); err != nil { return nil, err @@ -78,8 +93,8 @@ func open(url string) (*sql.DB, error) { return db, nil } -// OpenSQL returns a pooled *sql.DB for sqlite: (and existing) URLs. -// Used by packages that need raw SQL beyond CRUD helpers (e.g. rbac). +// OpenSQL returns a pooled *sql.DB (sqlite or postgres). Prefer OpenSQLDB when +// issuing `?` placeholders against Postgres (RBAC). func OpenSQL(url string) (*sql.DB, error) { return open(url) } @@ -123,6 +138,17 @@ func sqlType(t string) string { } } +func sqlTypeFor(url, t string) string { + ty := sqlType(t) + if IsPostgres(url) && ty == "REAL" { + return "DOUBLE PRECISION" + } + if IsPostgres(url) && ty == "BLOB" { + return "BYTEA" + } + return ty +} + func cellStr(v any) string { switch t := v.(type) { case nil: @@ -242,11 +268,15 @@ func Init(url, name string, fields any) (map[string]any, error) { nullable := boolField(m, []string{"nullable", "可空"}, true) unique := boolField(m, []string{"unique", "唯一"}, false) index := boolField(m, []string{"index", "索引"}, false) - col := fmt.Sprintf(`"%s" %s`, colName, sqlType(ty)) + col := fmt.Sprintf(`"%s" %s`, colName, sqlTypeFor(url, ty)) if colName == "id" && !hasPK { - col += " PRIMARY KEY" - if sqlType(ty) == "INTEGER" { - col += " AUTOINCREMENT" + if IsPostgres(url) && sqlType(ty) == "INTEGER" { + col = fmt.Sprintf(`"%s" INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY`, colName) + } else { + col += " PRIMARY KEY" + if sqlType(ty) == "INTEGER" { + col += " AUTOINCREMENT" + } } hasPK = true } else if !nullable { @@ -298,7 +328,26 @@ func Init(url, name string, fields any) (map[string]any, error) { }, nil } -func columnNames(c dbConn, tableName string) ([]string, error) { +func columnNames(c dbConn, tableName string, dbURL string) ([]string, error) { + if IsPostgres(dbURL) { + rows, err := c.Query(` +SELECT column_name FROM information_schema.columns +WHERE table_schema = current_schema() AND table_name = ? +ORDER BY ordinal_position`, tableName) + if err != nil { + return nil, err + } + defer rows.Close() + var out []string + for rows.Next() { + var name string + if err := rows.Scan(&name); err != nil { + return nil, err + } + out = append(out, name) + } + return out, rows.Err() + } rows, err := c.Query(fmt.Sprintf(`PRAGMA table_info("%s")`, tableName)) if err != nil { return nil, err @@ -380,7 +429,7 @@ func Insert(url, tableName string, rows any, txnID ...string) (map[string]any, e if err != nil { return nil, err } - colsPresent, err := columnNames(c, tn) + colsPresent, err := columnNames(c, tn, url) if err != nil { return nil, err } @@ -875,7 +924,7 @@ func Update(url, tableName, id string, row any, txnID ...string) (map[string]any if err != nil { return nil, err } - colsPresent, err := columnNames(c, tn) + colsPresent, err := columnNames(c, tn, url) if err != nil { return nil, err } @@ -996,17 +1045,52 @@ type ColumnInfo struct { PK bool } -// TableInfo returns column metadata for a SQLite table. +// TableInfo returns column metadata for a table (SQLite or Postgres). func TableInfo(url, tableName string) ([]ColumnInfo, error) { tn, err := ident(tableName) if err != nil { return nil, err } - db, err := open(url) + c, err := connFor(url, "") if err != nil { return nil, err } - rows, err := db.Query(fmt.Sprintf(`PRAGMA table_info("%s")`, tn)) + if IsPostgres(url) { + rows, err := c.Query(` +SELECT c.column_name, c.data_type, c.is_nullable, + CASE WHEN tc.constraint_type = 'PRIMARY KEY' THEN 1 ELSE 0 END AS is_pk +FROM information_schema.columns c +LEFT JOIN information_schema.key_column_usage kcu + ON c.table_schema = kcu.table_schema AND c.table_name = kcu.table_name AND c.column_name = kcu.column_name +LEFT JOIN information_schema.table_constraints tc + ON kcu.constraint_name = tc.constraint_name AND kcu.table_schema = tc.table_schema + AND tc.constraint_type = 'PRIMARY KEY' +WHERE c.table_schema = current_schema() AND c.table_name = ? +ORDER BY c.ordinal_position`, tn) + if err != nil { + return nil, err + } + defer rows.Close() + var out []ColumnInfo + for rows.Next() { + var name, dtype, nullable string + var pk int + if err := rows.Scan(&name, &dtype, &nullable, &pk); err != nil { + return nil, err + } + if dtype == "" { + dtype = "TEXT" + } + out = append(out, ColumnInfo{ + Name: name, + SQLType: dtype, + NotNull: strings.EqualFold(nullable, "NO"), + PK: pk != 0, + }) + } + return out, rows.Err() + } + rows, err := c.Query(fmt.Sprintf(`PRAGMA table_info("%s")`, tn)) if err != nil { return nil, err } diff --git a/plugins/web/internal/db/dialect.go b/plugins/web/internal/db/dialect.go new file mode 100644 index 0000000..039bfcb --- /dev/null +++ b/plugins/web/internal/db/dialect.go @@ -0,0 +1,144 @@ +package db + +import ( + "database/sql" + "strings" +) + +// IsPostgres reports whether url selects the Postgres backend. +func IsPostgres(url string) bool { + lower := strings.ToLower(strings.TrimSpace(url)) + return strings.HasPrefix(lower, "postgres://") || strings.HasPrefix(lower, "postgresql://") +} + +// RewritePlaceholdersPG turns `?` into `$1,$2,…` for Postgres. +func RewritePlaceholdersPG(sqlStmt string) string { + var b strings.Builder + b.Grow(len(sqlStmt) + 8) + n := 0 + for _, c := range sqlStmt { + if c == '?' { + n++ + b.WriteByte('$') + b.WriteString(itoa(n)) + } else { + b.WriteRune(c) + } + } + return b.String() +} + +func itoa(n int) string { + // small positive ints only + if n < 10 { + return string(rune('0' + n)) + } + var buf [12]byte + i := len(buf) + for n > 0 { + i-- + buf[i] = byte('0' + n%10) + n /= 10 + } + return string(buf[i:]) +} + +// rewritingDB rewrites `?` placeholders when talking to Postgres. +type rewritingDB struct { + db *sql.DB + pg bool +} + +func (d *rewritingDB) Exec(query string, args ...any) (sql.Result, error) { + if d.pg { + query = RewritePlaceholdersPG(query) + } + return d.db.Exec(query, args...) +} + +func (d *rewritingDB) Query(query string, args ...any) (*sql.Rows, error) { + if d.pg { + query = RewritePlaceholdersPG(query) + } + return d.db.Query(query, args...) +} + +func (d *rewritingDB) QueryRow(query string, args ...any) *sql.Row { + if d.pg { + query = RewritePlaceholdersPG(query) + } + return d.db.QueryRow(query, args...) +} + +func (d *rewritingDB) Begin() (*sql.Tx, error) { + return d.db.Begin() +} + +func (d *rewritingDB) Underlying() *sql.DB { return d.db } + +type rewritingTx struct { + tx *sql.Tx + pg bool +} + +func (t *rewritingTx) Exec(query string, args ...any) (sql.Result, error) { + if t.pg { + query = RewritePlaceholdersPG(query) + } + return t.tx.Exec(query, args...) +} + +func (t *rewritingTx) Query(query string, args ...any) (*sql.Rows, error) { + if t.pg { + query = RewritePlaceholdersPG(query) + } + return t.tx.Query(query, args...) +} + +func (t *rewritingTx) QueryRow(query string, args ...any) *sql.Row { + if t.pg { + query = RewritePlaceholdersPG(query) + } + return t.tx.QueryRow(query, args...) +} + +func (t *rewritingTx) Commit() error { return t.tx.Commit() } +func (t *rewritingTx) Rollback() error { return t.tx.Rollback() } + +// SQLDB is *sql.DB with optional Postgres `?` rewrite (RBAC / admin). +type SQLDB interface { + Exec(query string, args ...any) (sql.Result, error) + Query(query string, args ...any) (*sql.Rows, error) + QueryRow(query string, args ...any) *sql.Row + Begin() (SQLTx, error) +} + +// SQLTx is a transaction with optional placeholder rewrite. +type SQLTx interface { + Exec(query string, args ...any) (sql.Result, error) + Query(query string, args ...any) (*sql.Rows, error) + QueryRow(query string, args ...any) *sql.Row + Commit() error + Rollback() error +} + +type sqlDBHandle struct { + *rewritingDB +} + +func (h *sqlDBHandle) Begin() (SQLTx, error) { + tx, err := h.rewritingDB.Begin() + if err != nil { + return nil, err + } + return &rewritingTx{tx: tx, pg: h.pg}, nil +} + +// OpenSQLDB returns a pooled handle that rewrites `?` on Postgres. +func OpenSQLDB(url string) (SQLDB, error) { + raw, err := open(url) + if err != nil { + return nil, err + } + return &sqlDBHandle{rewritingDB: &rewritingDB{db: raw, pg: IsPostgres(url)}}, nil +} diff --git a/plugins/web/internal/db/txn.go b/plugins/web/internal/db/txn.go index 6305d92..7666c48 100644 --- a/plugins/web/internal/db/txn.go +++ b/plugins/web/internal/db/txn.go @@ -23,14 +23,23 @@ type txnConn struct { } func (t *txnConn) Exec(query string, args ...any) (sql.Result, error) { + if IsPostgres(t.url) { + query = RewritePlaceholdersPG(query) + } return t.conn.ExecContext(context.Background(), query, args...) } func (t *txnConn) Query(query string, args ...any) (*sql.Rows, error) { + if IsPostgres(t.url) { + query = RewritePlaceholdersPG(query) + } return t.conn.QueryContext(context.Background(), query, args...) } func (t *txnConn) QueryRow(query string, args ...any) *sql.Row { + if IsPostgres(t.url) { + query = RewritePlaceholdersPG(query) + } return t.conn.QueryRowContext(context.Background(), query, args...) } @@ -74,7 +83,11 @@ func connFor(url, txnID string) (dbConn, error) { } return t, nil } - return open(url) + raw, err := open(url) + if err != nil { + return nil, err + } + return &rewritingDB{db: raw, pg: IsPostgres(url)}, nil } func takeTxn(txnID string) (*txnConn, error) { @@ -98,7 +111,7 @@ func resetTxns() { } } -// Begin starts a SQLite transaction (BEGIN IMMEDIATE). +// Begin starts a transaction (BEGIN IMMEDIATE on SQLite, BEGIN on Postgres). // Returns {"_type":"txn","txn":id,"url":url,"事务":id,"地址":url}. func Begin(url string) (map[string]any, error) { db, err := open(url) @@ -109,7 +122,11 @@ func Begin(url string) (map[string]any, error) { if err != nil { return nil, err } - if _, err := conn.ExecContext(context.Background(), "BEGIN IMMEDIATE"); err != nil { + beginSQL := "BEGIN IMMEDIATE" + if IsPostgres(url) { + beginSQL = "BEGIN" + } + if _, err := conn.ExecContext(context.Background(), beginSQL); err != nil { _ = conn.Close() return nil, err } diff --git a/plugins/web/internal/httpx/helpers.go b/plugins/web/internal/httpx/helpers.go index d08f536..1b19fa9 100644 --- a/plugins/web/internal/httpx/helpers.go +++ b/plugins/web/internal/httpx/helpers.go @@ -67,15 +67,13 @@ func goMuxPattern(path string) string { func resolveSession(r *http.Request) (sid, csrf string, setCookie *string) { cookieHdr := r.Header.Get("Cookie") id, hadCookie := session.IDFromCookie(cookieHdr) - if hadCookie { - ok := true - if ok && id != "" { - sid = id - if tok, ok := session.CSRFFor(sid); ok { - csrf = tok - } - return sid, csrf, nil + if hadCookie && id != "" { + if tok, ok := session.CSRFFor(id); ok && tok != "" { + return id, tok, nil } + // Stale/expired/missing session: mint a fresh session and replace the cookie. + // Previously we returned the dead sid with empty CSRF, so login forms had no + // _csrf while POST still saw hadCookie=true → "登录令牌失效". } sid = session.NewID(0) tok, _ := session.CSRFFor(sid) diff --git a/plugins/web/internal/httpx/helpers_test.go b/plugins/web/internal/httpx/helpers_test.go index 30d4d9c..6f01dfd 100644 --- a/plugins/web/internal/httpx/helpers_test.go +++ b/plugins/web/internal/httpx/helpers_test.go @@ -1,6 +1,12 @@ package httpx -import "testing" +import ( + "net/http/httptest" + "strings" + "testing" + + "github.com/marqdo/marqdo/plugins/web/internal/session" +) func TestGoMuxPattern(t *testing.T) { if got := goMuxPattern("/_media/{*key}"); got != "/_media/{key...}" { @@ -22,3 +28,32 @@ func TestPathParamNamesIncludesID(t *testing.T) { } } +func TestResolveSessionReplacesStaleCookie(t *testing.T) { + session.Configure(session.Config{TTLSec: 3600}) + session.Reset(3600) + + req := httptest.NewRequest("GET", "/login", nil) + req.Header.Set("Cookie", "marqdo_sid="+strings.Repeat("ab", 32)) + sid, csrf, setCookie := resolveSession(req) + if sid == "" || csrf == "" { + t.Fatalf("expected fresh sid+csrf, got sid=%q csrf=%q", sid, csrf) + } + if setCookie == nil || !strings.Contains(*setCookie, "marqdo_sid=") { + t.Fatalf("expected Set-Cookie for replacement session, got %#v", setCookie) + } + if !session.ValidateCSRF(sid, csrf) { + t.Fatal("csrf should validate for new session") + } + + // Live session should keep the same id without re-issuing cookie. + req2 := httptest.NewRequest("GET", "/login", nil) + req2.Header.Set("Cookie", "marqdo_sid="+sid) + sid2, csrf2, setCookie2 := resolveSession(req2) + if sid2 != sid || csrf2 != csrf { + t.Fatalf("live session should be stable: %q/%q vs %q/%q", sid, csrf, sid2, csrf2) + } + if setCookie2 != nil { + t.Fatalf("live session should not Set-Cookie again") + } +} + diff --git a/plugins/web/internal/rbac/rbac.go b/plugins/web/internal/rbac/rbac.go index 2987c27..89b0920 100644 --- a/plugins/web/internal/rbac/rbac.go +++ b/plugins/web/internal/rbac/rbac.go @@ -111,7 +111,7 @@ func MergeUnique(lists ...[]string) []string { return out } -const schemaSQL = ` +const schemaSQLSqlite = ` CREATE TABLE IF NOT EXISTS web_permissions ( code TEXT PRIMARY KEY, resource TEXT NOT NULL, @@ -147,6 +147,49 @@ CREATE TABLE IF NOT EXISTS web_user_roles ( ); ` +var schemaSQLPostgres = []string{ + `CREATE TABLE IF NOT EXISTS web_permissions ( + code TEXT PRIMARY KEY, + resource TEXT NOT NULL, + action TEXT NOT NULL, + description TEXT +)`, + `CREATE TABLE IF NOT EXISTS web_roles ( + id INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, + name TEXT NOT NULL UNIQUE, + is_system INTEGER NOT NULL DEFAULT 0, + tenant_id TEXT +)`, + `CREATE TABLE IF NOT EXISTS web_role_permissions ( + role_id INTEGER NOT NULL, + permission_code TEXT NOT NULL, + PRIMARY KEY (role_id, permission_code), + FOREIGN KEY (role_id) REFERENCES web_roles(id) ON DELETE CASCADE, + FOREIGN KEY (permission_code) REFERENCES web_permissions(code) ON DELETE CASCADE +)`, + `CREATE TABLE IF NOT EXISTS web_users ( + id INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, + username TEXT NOT NULL UNIQUE, + password_hash TEXT NOT NULL, + created_at TEXT +)`, + `CREATE TABLE IF NOT EXISTS web_user_roles ( + user_id INTEGER NOT NULL, + role_id INTEGER NOT NULL, + tenant_id TEXT NOT NULL DEFAULT '', + PRIMARY KEY (user_id, role_id, tenant_id), + FOREIGN KEY (user_id) REFERENCES web_users(id) ON DELETE CASCADE, + FOREIGN KEY (role_id) REFERENCES web_roles(id) ON DELETE CASCADE +)`, +} + +func insertIgnoreSQL(dbURL, table, cols, placeholders, conflict string) string { + if db.IsPostgres(dbURL) { + return fmt.Sprintf(`INSERT INTO %s(%s) VALUES(%s) ON CONFLICT %s DO NOTHING`, table, cols, placeholders, conflict) + } + return fmt.Sprintf(`INSERT OR IGNORE INTO %s(%s) VALUES(%s)`, table, cols, placeholders) +} + // EnsureSchema creates RBAC tables and seeds default catalog + system roles. func EnsureSchema(dbURL string) error { if strings.TrimSpace(dbURL) == "" { @@ -156,25 +199,29 @@ func EnsureSchema(dbURL string) error { if err != nil { return err } - if _, err := sqlDB.Exec(schemaSQL); err != nil { + if db.IsPostgres(dbURL) { + for _, stmt := range schemaSQLPostgres { + if _, err := sqlDB.Exec(stmt); err != nil { + return err + } + } + } else if _, err := sqlDB.Exec(schemaSQLSqlite); err != nil { return err } + permSQL := insertIgnoreSQL(dbURL, "web_permissions", "code, resource, action, description", "?,?,?,?", "(code)") for _, p := range DefaultCatalog() { - _, _ = sqlDB.Exec( - `INSERT OR IGNORE INTO web_permissions(code, resource, action, description) VALUES(?,?,?,?)`, - p.Code, p.Resource, p.Action, p.Description, - ) + _, _ = sqlDB.Exec(permSQL, p.Code, p.Resource, p.Action, p.Description) } - if err := ensureSystemRole(sqlDB, "superadmin", true, AllCodes()); err != nil { + if err := ensureSystemRole(sqlDB, dbURL, "superadmin", true, AllCodes()); err != nil { return err } - if err := ensureSystemRole(sqlDB, "member", true, []string{"comments:create", "comments:delete_own"}); err != nil { + if err := ensureSystemRole(sqlDB, dbURL, "member", true, []string{"comments:create", "comments:delete_own"}); err != nil { return err } return nil } -func ensureSystemRole(sqlDB *sql.DB, name string, isSystem bool, perms []string) error { +func ensureSystemRole(sqlDB db.SQLDB, dbURL, name string, isSystem bool, perms []string) error { var id int64 err := sqlDB.QueryRow(`SELECT id FROM web_roles WHERE name = ?`, name).Scan(&id) if err == sql.ErrNoRows { @@ -182,22 +229,27 @@ func ensureSystemRole(sqlDB *sql.DB, name string, isSystem bool, perms []string) if isSystem { sys = 1 } - res, err := sqlDB.Exec(`INSERT INTO web_roles(name, is_system) VALUES(?,?)`, name, sys) - if err != nil { - return err - } - id, err = res.LastInsertId() - if err != nil { - return err + if db.IsPostgres(dbURL) { + err = sqlDB.QueryRow(`INSERT INTO web_roles(name, is_system) VALUES(?,?) RETURNING id`, name, sys).Scan(&id) + if err != nil { + return err + } + } else { + res, err := sqlDB.Exec(`INSERT INTO web_roles(name, is_system) VALUES(?,?)`, name, sys) + if err != nil { + return err + } + id, err = res.LastInsertId() + if err != nil { + return err + } } } else if err != nil { return err } + rpSQL := insertIgnoreSQL(dbURL, "web_role_permissions", "role_id, permission_code", "?,?", "(role_id, permission_code)") for _, code := range perms { - _, _ = sqlDB.Exec( - `INSERT OR IGNORE INTO web_role_permissions(role_id, permission_code) VALUES(?,?)`, - id, code, - ) + _, _ = sqlDB.Exec(rpSQL, id, code) } return nil } @@ -243,7 +295,7 @@ func AssignRole(dbURL, username, roleName string) error { return fmt.Errorf("rbac assign: role %q: %w", roleName, err) } _, err = sqlDB.Exec( - `INSERT OR IGNORE INTO web_user_roles(user_id, role_id, tenant_id) VALUES(?,?,?)`, + insertIgnoreSQL(dbURL, "web_user_roles", "user_id, role_id, tenant_id", "?,?,?", "(user_id, role_id, tenant_id)"), uid, rid, "", ) return err @@ -258,6 +310,11 @@ func CreateRole(dbURL, name string) (int64, error) { if err != nil { return 0, err } + if db.IsPostgres(dbURL) { + var id int64 + err = sqlDB.QueryRow(`INSERT INTO web_roles(name, is_system) VALUES(?,0) RETURNING id`, name).Scan(&id) + return id, err + } res, err := sqlDB.Exec(`INSERT INTO web_roles(name, is_system) VALUES(?,0)`, name) if err != nil { return 0, err @@ -325,8 +382,17 @@ func CreateUser(dbURL, username, passwordHash string) (int64, error) { if err != nil { return 0, err } + now := "datetime('now')" + if db.IsPostgres(dbURL) { + var id int64 + err = sqlDB.QueryRow( + `INSERT INTO web_users(username, password_hash, created_at) VALUES(?,?,to_char(now() AT TIME ZONE 'UTC','YYYY-MM-DD HH24:MI:SS')) RETURNING id`, + username, passwordHash, + ).Scan(&id) + return id, err + } res, err := sqlDB.Exec( - `INSERT INTO web_users(username, password_hash, created_at) VALUES(?,?,datetime('now'))`, + `INSERT INTO web_users(username, password_hash, created_at) VALUES(?,?,`+now+`)`, username, passwordHash, ) if err != nil { @@ -504,7 +570,6 @@ func SetRolePermissionsByName(dbURL, roleName string, codes, grantable []string) return SetRolePermissions(dbURL, id, codes, grantable) } -func openDB(dbURL string) (*sql.DB, error) { - // Reuse db package pool via a no-op select path: open through Ensure-compatible helper. - return db.OpenSQL(dbURL) +func openDB(dbURL string) (db.SQLDB, error) { + return db.OpenSQLDB(dbURL) } diff --git a/plugins/web/internal/session/session.go b/plugins/web/internal/session/session.go index 6b0ca14..bfde136 100644 --- a/plugins/web/internal/session/session.go +++ b/plugins/web/internal/session/session.go @@ -220,13 +220,17 @@ func Reset(ttlSec uint64) { } func ensureSessionTable(url string) error { - _, err := db.Exec(url, fmt.Sprintf(` + create := fmt.Sprintf(` CREATE TABLE IF NOT EXISTS "%s" ( id TEXT PRIMARY KEY, expires_at INTEGER NOT NULL, data TEXT NOT NULL -); -CREATE INDEX IF NOT EXISTS idx_marqdo_sessions_exp ON "%s"(expires_at);`, sessionTable, sessionTable), nil) +)`, sessionTable) + if _, err := db.Exec(url, create, nil); err != nil { + return err + } + idx := fmt.Sprintf(`CREATE INDEX IF NOT EXISTS idx_marqdo_sessions_exp ON "%s"(expires_at)`, sessionTable) + _, err := db.Exec(url, idx, nil) return err } @@ -315,7 +319,7 @@ func saveSQL(url, id string, exp uint64, data map[string]any) error { } _, err = db.Exec(url, fmt.Sprintf(` INSERT INTO "%s" (id, expires_at, data) VALUES (?, ?, ?) -ON CONFLICT(id) DO UPDATE SET expires_at = excluded.expires_at, data = excluded.data`, sessionTable), +ON CONFLICT (id) DO UPDATE SET expires_at = excluded.expires_at, data = excluded.data`, sessionTable), []any{id, int64(exp), string(raw)}) return err }