feat(web): Go W-G12 rooms, Redis session, and API keys
Add mode=room with room_key hub APIs, optional redis:// session backend, and web_api_key_check (sha256 pepper:key) for anlian primitives. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
26955f4f36
commit
12d2c7be69
15 files changed
+541
-13
No files matched your search
@@ -397,7 +397,7 @@ scripts/build-web-plugin.sh # go build -buildmode=c-shared -o …/libweb.so
|
||||
| **W-G9** | Postgres + Redis cache + file/S3 storage | ✅ `web-drivers-smoke` |
|
||||
| **W-G10** | proxy + invoke + nested plugin | ✅ `web-proxy-invoke` / hosting live |
|
||||
| **W-G11** | 定制 C2–C4 shell/layout/style/nav | ✅ `web-c2`–`c4` |
|
||||
| **W-G12** | G 增强 WS rooms + Redis session/pubsub + API key 原语 | 单测 + anlian chat 切片 |
|
||||
| **W-G12** | G 增强 WS rooms + Redis session/pubsub + API key 原语 | ✅ 单测 + `web-g12-api-key-smoke` |
|
||||
| **W-G13** | 默认切换 Go `libweb`;归档 Rust;更新发版与 ext CLI | 全量 `tests/ext/web-*` 绿 |
|
||||
| **W-G14** | anlian Marqdo 重写主路径(可分仓或 `examples/anlian-mq/`) | §8 矩阵主路径可演示 |
|
||||
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
package main
|
||||
|
||||
/*
|
||||
#cgo CFLAGS: -I${SRCDIR}/abi
|
||||
#include "marqdo_abi_cgo.h"
|
||||
|
||||
extern int web_api_key_check(char *args_json, char **out_json, char **err_msg);
|
||||
*/
|
||||
import "C"
|
||||
|
||||
import (
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/apikey"
|
||||
)
|
||||
|
||||
//export web_api_key_check
|
||||
func web_api_key_check(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int {
|
||||
args, err := parseArgs(argsJSON)
|
||||
if err != nil {
|
||||
return replyJSON(outJSON, errMsg, nil, err)
|
||||
}
|
||||
key, _ := argStr(args, "key", "密钥")
|
||||
auth, _ := argStr(args, "authorization", "auth", "授权")
|
||||
pepper, _ := argStr(args, "pepper", "椒盐")
|
||||
keys := args["keys"]
|
||||
if keys == nil {
|
||||
keys = args["hashes"]
|
||||
}
|
||||
out := apikey.Check(key, auth, pepper, keys)
|
||||
return replyJSON(outJSON, errMsg, out, nil)
|
||||
}
|
||||
@@ -10,12 +10,15 @@ require (
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/alicebob/gopher-json v0.0.0-20230218143504-906a9b012302 // indirect
|
||||
github.com/alicebob/miniredis/v2 v2.34.0 // indirect
|
||||
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/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/gopher-lua v1.1.1 // indirect
|
||||
go.uber.org/atomic v1.11.0 // indirect
|
||||
golang.org/x/sys v0.47.0 // indirect
|
||||
modernc.org/libc v1.75.6 // indirect
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
github.com/alicebob/gopher-json v0.0.0-20230218143504-906a9b012302 h1:uvdUDbHQHO85qeSydJtItA4T55Pw6BtAejd0APRJOCE=
|
||||
github.com/alicebob/gopher-json v0.0.0-20230218143504-906a9b012302/go.mod h1:SGnFV6hVsYE877CKEZ6tDNTjaSXYUk6QqoIK6PrAtcc=
|
||||
github.com/alicebob/miniredis/v2 v2.34.0 h1:mBFWMaJSNL9RwdGRyEDoAAv8OQc5UlEhLDQggTglU/0=
|
||||
github.com/alicebob/miniredis/v2 v2.34.0/go.mod h1:kWShP4b58T1CW0Y5dViCd5ztzrDqRWqM3nksiyXk5s8=
|
||||
github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
|
||||
github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=
|
||||
github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
|
||||
@@ -30,6 +34,8 @@ github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
|
||||
github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/yuin/gopher-lua v1.1.1 h1:kYKnWBjvbNP4XLT3+bPEwAXJx262OhaHDWDVOPjL46M=
|
||||
github.com/yuin/gopher-lua v1.1.1/go.mod h1:GBR0iDaNXjAgGg9zfCvksxSRnQx76gclCIb7kdAd1Pw=
|
||||
github.com/zeebo/xxh3 v1.1.0 h1:s7DLGDK45Dyfg7++yxI0khrfwq9661w9EN78eP/UZVs=
|
||||
github.com/zeebo/xxh3 v1.1.0/go.mod h1:IisAie1LELR4xhVinxWS5+zf1lA4p0MW4T+w+W07F5s=
|
||||
go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE=
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
// Package apikey implements Bearer API key verification (G-API1).
|
||||
//
|
||||
// Hash formula: sha256 hex of pepper + ":" + key (documented for anlian apikeys).
|
||||
package apikey
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/table"
|
||||
)
|
||||
|
||||
var (
|
||||
hashKeys = []string{"hash", "哈希", "key_hash", "密钥哈希"}
|
||||
scopeKeys = []string{"scopes", "scope", "作用域", "权限"}
|
||||
)
|
||||
|
||||
// Hash returns the stored digest for pepper+key (sha256 hex of "pepper:key").
|
||||
func Hash(pepper, key string) string {
|
||||
sum := sha256.Sum256([]byte(pepper + ":" + key))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
// BearerToken strips a Bearer prefix from an Authorization header value.
|
||||
func BearerToken(authorization string) string {
|
||||
s := strings.TrimSpace(authorization)
|
||||
if s == "" {
|
||||
return ""
|
||||
}
|
||||
const prefix = "Bearer "
|
||||
if len(s) > len(prefix) && strings.EqualFold(s[:len(prefix)], prefix) {
|
||||
return strings.TrimSpace(s[len(prefix):])
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// Check verifies a raw key or Authorization header against a GFM keys table.
|
||||
// Args: key or authorization, pepper, keys (rows with hash + scopes).
|
||||
// Returns {"ok":true,"scopes":[...]} or {"ok":false}.
|
||||
func Check(key, authorization, pepper string, keys any) map[string]any {
|
||||
raw := strings.TrimSpace(key)
|
||||
if raw == "" {
|
||||
raw = BearerToken(authorization)
|
||||
}
|
||||
if raw == "" || pepper == "" {
|
||||
return map[string]any{"ok": false}
|
||||
}
|
||||
digest := Hash(pepper, raw)
|
||||
rowsAny := table.AsRows(keys)
|
||||
rows, ok := rowsAny.([]any)
|
||||
if !ok {
|
||||
return map[string]any{"ok": false}
|
||||
}
|
||||
for _, row := range rows {
|
||||
m, ok := row.(map[string]any)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
stored := pickCell(m, hashKeys)
|
||||
if stored == "" || !strings.EqualFold(stored, digest) {
|
||||
continue
|
||||
}
|
||||
return map[string]any{"ok": true, "scopes": parseScopes(pickCell(m, scopeKeys))}
|
||||
}
|
||||
return map[string]any{"ok": false}
|
||||
}
|
||||
|
||||
func pickCell(m map[string]any, keys []string) string {
|
||||
for _, k := range keys {
|
||||
if v, ok := m[k]; ok && v != nil {
|
||||
return strings.TrimSpace(fmt.Sprint(v))
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func parseScopes(raw string) []any {
|
||||
raw = strings.TrimSpace(raw)
|
||||
if raw == "" {
|
||||
return []any{}
|
||||
}
|
||||
parts := strings.Split(raw, ",")
|
||||
out := make([]any, 0, len(parts))
|
||||
for _, p := range parts {
|
||||
p = strings.TrimSpace(p)
|
||||
if p != "" {
|
||||
out = append(out, p)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package apikey_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/apikey"
|
||||
)
|
||||
|
||||
func TestHashFormula(t *testing.T) {
|
||||
got := apikey.Hash("pep", "secret-key")
|
||||
want := apikey.Hash("pep", "secret-key")
|
||||
if got != want || got == "" {
|
||||
t.Fatalf("hash=%q", got)
|
||||
}
|
||||
if got == apikey.Hash("pep", "other") {
|
||||
t.Fatal("different keys should differ")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckMatchAndScopes(t *testing.T) {
|
||||
pepper := "site-pepper"
|
||||
key := "live-key-1"
|
||||
digest := apikey.Hash(pepper, key)
|
||||
keys := []any{
|
||||
map[string]any{
|
||||
"hash": digest,
|
||||
"scopes": "read,write",
|
||||
},
|
||||
}
|
||||
out := apikey.Check("", "Bearer "+key, pepper, keys)
|
||||
if out["ok"] != true {
|
||||
t.Fatalf("match: %v", out)
|
||||
}
|
||||
scopes, _ := out["scopes"].([]any)
|
||||
if len(scopes) != 2 || scopes[0] != "read" || scopes[1] != "write" {
|
||||
t.Fatalf("scopes=%v", scopes)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckMiss(t *testing.T) {
|
||||
keys := []any{
|
||||
map[string]any{"hash": apikey.Hash("p", "stored"), "scopes": "admin"},
|
||||
}
|
||||
out := apikey.Check("wrong", "", "p", keys)
|
||||
if out["ok"] != false {
|
||||
t.Fatalf("expected miss: %v", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckKeyParam(t *testing.T) {
|
||||
pepper := "p"
|
||||
key := "direct"
|
||||
digest := apikey.Hash(pepper, key)
|
||||
keys := []any{map[string]any{"hash": digest, "scopes": "api"}}
|
||||
out := apikey.Check(key, "", pepper, keys)
|
||||
if out["ok"] != true {
|
||||
t.Fatalf("%v", out)
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
package session
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
@@ -11,6 +12,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/db"
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -21,7 +23,8 @@ const (
|
||||
|
||||
// Config controls session backend.
|
||||
type Config struct {
|
||||
DBURL string
|
||||
DBURL string // sqlite:… or legacy SQL session table
|
||||
RedisURL string // redis:// or rediss:// (G-SESS1)
|
||||
TTLSec uint64
|
||||
CookieSecure bool
|
||||
}
|
||||
@@ -33,6 +36,10 @@ var (
|
||||
memMu sync.Mutex
|
||||
mem = map[string]memRec{}
|
||||
memTTL uint64 = defaultTTL
|
||||
|
||||
redisMu sync.Mutex
|
||||
redisClient *redis.Client
|
||||
redisURL string
|
||||
)
|
||||
|
||||
type memRec struct {
|
||||
@@ -52,21 +59,142 @@ func cloneData(m map[string]any) map[string]any {
|
||||
return out
|
||||
}
|
||||
|
||||
func isRedisURL(url string) bool {
|
||||
u := strings.ToLower(strings.TrimSpace(url))
|
||||
return strings.HasPrefix(u, "redis://") || strings.HasPrefix(u, "rediss://")
|
||||
}
|
||||
|
||||
func isSQLiteURL(url string) bool {
|
||||
u := strings.TrimSpace(url)
|
||||
return u != "" && !isRedisURL(u)
|
||||
}
|
||||
|
||||
// Configure sets session backend before listen or offline ABI calls.
|
||||
// RedisURL or a redis:// DBURL selects the Redis backend; sqlite DBURL keeps SQL table storage.
|
||||
func Configure(c Config) {
|
||||
ttl := c.TTLSec
|
||||
if ttl == 0 {
|
||||
ttl = defaultTTL
|
||||
}
|
||||
c.TTLSec = ttl
|
||||
if c.DBURL != "" {
|
||||
if c.RedisURL == "" && isRedisURL(c.DBURL) {
|
||||
c.RedisURL = strings.TrimSpace(c.DBURL)
|
||||
c.DBURL = ""
|
||||
}
|
||||
if isSQLiteURL(c.DBURL) {
|
||||
_ = ensureSessionTable(c.DBURL)
|
||||
}
|
||||
if c.RedisURL != "" {
|
||||
_ = openRedis(c.RedisURL)
|
||||
} else {
|
||||
closeRedis()
|
||||
}
|
||||
cfgMu.Lock()
|
||||
cfg = c
|
||||
cfgMu.Unlock()
|
||||
}
|
||||
|
||||
func openRedis(url string) error {
|
||||
redisMu.Lock()
|
||||
defer redisMu.Unlock()
|
||||
if redisClient != nil && redisURL == url {
|
||||
return nil
|
||||
}
|
||||
if redisClient != nil {
|
||||
_ = redisClient.Close()
|
||||
redisClient = nil
|
||||
}
|
||||
opts, err := redis.ParseURL(url)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
redisClient = redis.NewClient(opts)
|
||||
redisURL = url
|
||||
return nil
|
||||
}
|
||||
|
||||
func closeRedis() {
|
||||
redisMu.Lock()
|
||||
defer redisMu.Unlock()
|
||||
if redisClient != nil {
|
||||
_ = redisClient.Close()
|
||||
redisClient = nil
|
||||
redisURL = ""
|
||||
}
|
||||
}
|
||||
|
||||
// CloseRedis releases the Redis client (plugin shutdown / tests).
|
||||
func CloseRedis() {
|
||||
closeRedis()
|
||||
}
|
||||
|
||||
func redisKey(id string) string {
|
||||
return "marqdo:session:" + id
|
||||
}
|
||||
|
||||
type redisBlob struct {
|
||||
Data map[string]any `json:"data"`
|
||||
}
|
||||
|
||||
func loadRedis(id string) (map[string]any, bool) {
|
||||
client := redisClientForRead()
|
||||
if client == nil {
|
||||
return nil, false
|
||||
}
|
||||
ctx := context.Background()
|
||||
raw, err := client.Get(ctx, redisKey(id)).Result()
|
||||
if err == redis.Nil || err != nil {
|
||||
return nil, false
|
||||
}
|
||||
var blob redisBlob
|
||||
if err := json.Unmarshal([]byte(raw), &blob); err != nil {
|
||||
return nil, false
|
||||
}
|
||||
if blob.Data == nil {
|
||||
blob.Data = map[string]any{}
|
||||
}
|
||||
return blob.Data, true
|
||||
}
|
||||
|
||||
func saveRedis(id string, ttl uint64, data map[string]any) bool {
|
||||
client := redisClientForRead()
|
||||
if client == nil {
|
||||
return false
|
||||
}
|
||||
raw, err := json.Marshal(redisBlob{Data: cloneData(data)})
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
ctx := context.Background()
|
||||
if ttl == 0 {
|
||||
ttl = defaultTTL
|
||||
}
|
||||
if err := client.SetEx(ctx, redisKey(id), raw, time.Duration(ttl)*time.Second).Err(); err != nil {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func deleteRedis(id string) {
|
||||
client := redisClientForRead()
|
||||
if client == nil {
|
||||
return
|
||||
}
|
||||
ctx := context.Background()
|
||||
_, _ = client.Del(ctx, redisKey(id)).Result()
|
||||
}
|
||||
|
||||
func redisClientForRead() *redis.Client {
|
||||
redisMu.Lock()
|
||||
defer redisMu.Unlock()
|
||||
return redisClient
|
||||
}
|
||||
|
||||
func usingRedis() bool {
|
||||
c := getCfg()
|
||||
return c.RedisURL != ""
|
||||
}
|
||||
|
||||
func getCfg() Config {
|
||||
cfgMu.Lock()
|
||||
defer cfgMu.Unlock()
|
||||
@@ -203,6 +331,13 @@ func touchExpiry(ttl uint64) uint64 {
|
||||
func getRecord(id string) (map[string]any, bool) {
|
||||
c := getCfg()
|
||||
now := nowSecs()
|
||||
if usingRedis() {
|
||||
data, ok := loadRedis(id)
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
return cloneData(data), true
|
||||
}
|
||||
if c.DBURL != "" {
|
||||
pruneSQL(c.DBURL)
|
||||
exp, data, ok := loadSQL(c.DBURL, id)
|
||||
@@ -231,6 +366,16 @@ func getRecord(id string) (map[string]any, bool) {
|
||||
|
||||
func putRecord(id string, exp uint64, data map[string]any) bool {
|
||||
c := getCfg()
|
||||
if usingRedis() {
|
||||
ttl := c.TTLSec
|
||||
if ttl == 0 {
|
||||
ttl = defaultTTL
|
||||
}
|
||||
if exp > nowSecs() {
|
||||
ttl = exp - nowSecs()
|
||||
}
|
||||
return saveRedis(id, ttl, data)
|
||||
}
|
||||
if c.DBURL != "" {
|
||||
return saveSQL(c.DBURL, id, exp, data) == nil
|
||||
}
|
||||
@@ -262,7 +407,10 @@ func NewID(ttlSec uint64) string {
|
||||
data := map[string]any{}
|
||||
_, _ = ensureCSRF(data)
|
||||
exp := touchExpiry(ttl)
|
||||
if c.DBURL != "" {
|
||||
if usingRedis() {
|
||||
ttl := ttl
|
||||
_ = saveRedis(id, ttl, data)
|
||||
} else if c.DBURL != "" {
|
||||
pruneSQL(c.DBURL)
|
||||
_ = saveSQL(c.DBURL, id, exp, data)
|
||||
} else {
|
||||
@@ -344,6 +492,10 @@ func Destroy(id string) map[string]any {
|
||||
// DestroyID is the low-level destroyer.
|
||||
func DestroyID(id string) bool {
|
||||
c := getCfg()
|
||||
if usingRedis() {
|
||||
deleteRedis(id)
|
||||
return true
|
||||
}
|
||||
if c.DBURL != "" {
|
||||
deleteSQL(c.DBURL, id)
|
||||
return true
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/alicebob/miniredis/v2"
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/db"
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/session"
|
||||
)
|
||||
@@ -84,3 +85,38 @@ func TestNewABI(t *testing.T) {
|
||||
t.Fatal(out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigureRedisURLNoPanic(t *testing.T) {
|
||||
session.CloseRedis()
|
||||
session.Configure(session.Config{RedisURL: "redis://127.0.0.1:16379/0", TTLSec: 60})
|
||||
session.CloseRedis()
|
||||
}
|
||||
|
||||
func TestConfigureRedisViaDBURL(t *testing.T) {
|
||||
session.CloseRedis()
|
||||
session.Configure(session.Config{DBURL: "redis://127.0.0.1:16379/1", TTLSec: 60})
|
||||
session.CloseRedis()
|
||||
}
|
||||
|
||||
func TestSessionPersistsInRedis(t *testing.T) {
|
||||
mr, err := miniredis.Run()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer mr.Close()
|
||||
url := "redis://" + mr.Addr() + "/0"
|
||||
session.CloseRedis()
|
||||
session.Configure(session.Config{RedisURL: url, TTLSec: 3600})
|
||||
session.Reset(3600)
|
||||
id := session.NewID(0)
|
||||
if !session.SetValue(id, "lang", "zh") {
|
||||
t.Fatal("set")
|
||||
}
|
||||
session.CloseRedis()
|
||||
session.Configure(session.Config{RedisURL: url, TTLSec: 3600})
|
||||
v, ok := session.GetValue(id, "lang")
|
||||
if !ok || v != "zh" {
|
||||
t.Fatalf("persist get=%v ok=%v", v, ok)
|
||||
}
|
||||
session.CloseRedis()
|
||||
}
|
||||
@@ -45,6 +45,21 @@ func unsubscribe(path string, ch chan string) {
|
||||
room.mu.Unlock()
|
||||
}
|
||||
|
||||
// JoinRoom subscribes to a named room (G-WS1). Same backing store as path broadcast.
|
||||
func JoinRoom(room string) chan string {
|
||||
return subscribe(room)
|
||||
}
|
||||
|
||||
// LeaveRoom unsubscribes from a named room (G-WS1).
|
||||
func LeaveRoom(room string, ch chan string) {
|
||||
unsubscribe(room, ch)
|
||||
}
|
||||
|
||||
// PublishRoom fans out text to all subscribers in a named room (G-WS1).
|
||||
func PublishRoom(room string, text string) {
|
||||
Publish(room, text)
|
||||
}
|
||||
|
||||
// Publish fans out text to all subscribers on path (Rust ws_hub::publish).
|
||||
func Publish(path string, text string) {
|
||||
globalHub.mu.Lock()
|
||||
|
||||
@@ -5,6 +5,21 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestNamedRoomJoinPublishLeave(t *testing.T) {
|
||||
room := "chat.room.42"
|
||||
ch := JoinRoom(room)
|
||||
ch2 := JoinRoom(room)
|
||||
PublishRoom(room, "hello-room")
|
||||
if got := readOne(ch); got != "hello-room" {
|
||||
t.Fatalf("ch1=%q", got)
|
||||
}
|
||||
if got := readOne(ch2); got != "hello-room" {
|
||||
t.Fatalf("ch2=%q", got)
|
||||
}
|
||||
LeaveRoom(room, ch)
|
||||
LeaveRoom(room, ch2)
|
||||
}
|
||||
|
||||
func TestBroadcastFanout(t *testing.T) {
|
||||
path := "/t-fanout-go"
|
||||
ch := subscribe(path)
|
||||
|
||||
@@ -12,6 +12,7 @@ const (
|
||||
ModeEcho Mode = "echo"
|
||||
ModeBroadcast Mode = "broadcast"
|
||||
ModeDrain Mode = "drain"
|
||||
ModeRoom Mode = "room"
|
||||
)
|
||||
|
||||
// ParseMode mirrors Rust ws_hub::WsMode::parse.
|
||||
@@ -26,6 +27,8 @@ func ParseMode(v any) Mode {
|
||||
switch strings.TrimSpace(strings.ToLower(t)) {
|
||||
case "broadcast", "广播":
|
||||
return ModeBroadcast
|
||||
case "room", "房间":
|
||||
return ModeRoom
|
||||
case "drain", "false", "0", "no", "drain_only":
|
||||
return ModeDrain
|
||||
default:
|
||||
|
||||
@@ -2,27 +2,50 @@ package ws
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/app"
|
||||
)
|
||||
|
||||
// RouteWS registers path → {mode} on app.ws_routes (Rust web_app_route_ws).
|
||||
// RouteSpec is one ws_routes entry (mode + optional room_key template).
|
||||
type RouteSpec struct {
|
||||
Mode Mode
|
||||
RoomKey string
|
||||
}
|
||||
|
||||
// RouteWS registers path → {mode, room_key?} on app.ws_routes (Rust web_app_route_ws).
|
||||
func RouteWS(appBag map[string]any, path string, args map[string]any) (map[string]any, error) {
|
||||
path, err := app.NormalizeRoutePath(path, appBag)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
mode := ModeFromArgs(args)
|
||||
roomKey := RoomKeyFromArgs(args)
|
||||
if mode == ModeRoom && roomKey == "" {
|
||||
return nil, fmt.Errorf("mode=room requires room_key")
|
||||
}
|
||||
out := clone(appBag)
|
||||
wsRoutes := map[string]any{}
|
||||
if r, ok := out["ws_routes"].(map[string]any); ok {
|
||||
wsRoutes = clone(r)
|
||||
}
|
||||
wsRoutes[path] = map[string]any{"mode": string(mode)}
|
||||
spec := map[string]any{"mode": string(mode)}
|
||||
if roomKey != "" {
|
||||
spec["room_key"] = roomKey
|
||||
}
|
||||
wsRoutes[path] = spec
|
||||
out["ws_routes"] = wsRoutes
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// RoomKeyFromArgs reads room_key / 房间 from route_ws ABI args.
|
||||
func RoomKeyFromArgs(args map[string]any) string {
|
||||
if v, ok := first(args, "room_key", "房间"); ok {
|
||||
return strings.TrimSpace(fmt.Sprint(v))
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// RoutesOf reads ws_routes from an app bag.
|
||||
func RoutesOf(appBag map[string]any) map[string]Mode {
|
||||
out := map[string]Mode{}
|
||||
@@ -57,19 +80,42 @@ func clone(m map[string]any) map[string]any {
|
||||
|
||||
// ModeOf returns the mode for one ws route path, or error if missing.
|
||||
func ModeOf(appBag map[string]any, path string) (Mode, error) {
|
||||
spec, err := RouteSpecOf(appBag, path)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return spec.Mode, nil
|
||||
}
|
||||
|
||||
// RouteSpecOf returns mode and room_key for one ws route path.
|
||||
func RouteSpecOf(appBag map[string]any, path string) (RouteSpec, error) {
|
||||
routes, ok := appBag["ws_routes"].(map[string]any)
|
||||
if !ok {
|
||||
return "", fmt.Errorf("missing ws route %s", path)
|
||||
return RouteSpec{}, fmt.Errorf("missing ws route %s", path)
|
||||
}
|
||||
spec, ok := routes[path]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("missing ws route %s", path)
|
||||
return RouteSpec{}, fmt.Errorf("missing ws route %s", path)
|
||||
}
|
||||
if m, ok := spec.(map[string]any); ok {
|
||||
if mode, ok := m["mode"]; ok {
|
||||
return ParseMode(mode), nil
|
||||
return parseRouteSpec(spec), nil
|
||||
}
|
||||
|
||||
func parseRouteSpec(spec any) RouteSpec {
|
||||
out := RouteSpec{Mode: ModeEcho}
|
||||
switch t := spec.(type) {
|
||||
case map[string]any:
|
||||
if mode, ok := t["mode"]; ok {
|
||||
out.Mode = ParseMode(mode)
|
||||
} else {
|
||||
out.Mode = ParseMode(t)
|
||||
}
|
||||
return ParseMode(m), nil
|
||||
if rk, ok := t["room_key"]; ok {
|
||||
out.RoomKey = strings.TrimSpace(fmt.Sprint(rk))
|
||||
}
|
||||
case string:
|
||||
out.Mode = ParseMode(t)
|
||||
default:
|
||||
out.Mode = ParseMode(spec)
|
||||
}
|
||||
return ParseMode(spec), nil
|
||||
return out
|
||||
}
|
||||
@@ -68,6 +68,8 @@ func TestParseModeVariants(t *testing.T) {
|
||||
{"broadcast", ws.ModeBroadcast},
|
||||
{"广播", ws.ModeBroadcast},
|
||||
{"drain", ws.ModeDrain},
|
||||
{"room", ws.ModeRoom},
|
||||
{"房间", ws.ModeRoom},
|
||||
{"nope", ws.ModeEcho},
|
||||
}
|
||||
for _, c := range cases {
|
||||
@@ -77,6 +79,40 @@ func TestParseModeVariants(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestRouteWSRoomModeWithKey(t *testing.T) {
|
||||
a := app.New(nil)
|
||||
out, err := ws.RouteWS(a, "/chat", map[string]any{
|
||||
"mode": "room",
|
||||
"room_key": "chat.room.{id}",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
spec, err := ws.RouteSpecOf(out, "/chat")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if spec.Mode != ws.ModeRoom {
|
||||
t.Fatalf("mode=%q want room", spec.Mode)
|
||||
}
|
||||
if spec.RoomKey != "chat.room.{id}" {
|
||||
t.Fatalf("room_key=%q", spec.RoomKey)
|
||||
}
|
||||
routes := out["ws_routes"].(map[string]any)
|
||||
room := routes["/chat"].(map[string]any)
|
||||
if room["mode"] != "room" || room["room_key"] != "chat.room.{id}" {
|
||||
t.Fatalf("bag=%v", room)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRouteWSRoomRequiresKey(t *testing.T) {
|
||||
a := app.New(nil)
|
||||
_, err := ws.RouteWS(a, "/chat", map[string]any{"mode": "room"})
|
||||
if err == nil {
|
||||
t.Fatal("expected error without room_key")
|
||||
}
|
||||
}
|
||||
|
||||
func TestConnectRefusesBadURL(t *testing.T) {
|
||||
out := ws.Connect("http://127.0.0.1:1", "hi", nil, 1)
|
||||
if out["ok"] == true {
|
||||
|
||||
@@ -132,6 +132,7 @@ extern int web_cache_exists(char *args_json, char **out_json, char **err_msg);
|
||||
extern int web_cache_ttl(char *args_json, char **out_json, char **err_msg);
|
||||
extern int web_app_proxy(char *args_json, char **out_json, char **err_msg);
|
||||
extern int web_app_invoke(char *args_json, char **out_json, char **err_msg);
|
||||
extern int web_api_key_check(char *args_json, char **out_json, char **err_msg);
|
||||
|
||||
static int register_core(void) {
|
||||
if (host_register((char *)"web_go_ready", (char *)"", web_go_ready) != 0) return 1;
|
||||
@@ -217,6 +218,7 @@ static int register_core(void) {
|
||||
if (host_register((char *)"web_cache_ttl", (char *)"url,key", web_cache_ttl) != 0) return 1;
|
||||
if (host_register((char *)"web_app_proxy", (char *)"app,path,upstream,stream,strip_prefix,methods,headers_from_env,timeout_ms", web_app_proxy) != 0) return 1;
|
||||
if (host_register((char *)"web_app_invoke", (char *)"app,path,method,fn,body,return", web_app_invoke) != 0) return 1;
|
||||
if (host_register((char *)"web_api_key_check", (char *)"key,authorization,pepper,keys", web_api_key_check) != 0) return 1;
|
||||
return 0;
|
||||
}
|
||||
*/
|
||||
@@ -237,6 +239,7 @@ import (
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/page"
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/plugin"
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/render"
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/session"
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/style"
|
||||
)
|
||||
|
||||
@@ -257,6 +260,7 @@ func marqdo_plugin_init(host *C.MarqdoHostApi) C.int {
|
||||
|
||||
//export marqdo_plugin_shutdown
|
||||
func marqdo_plugin_shutdown() {
|
||||
session.CloseRedis()
|
||||
db.ResetPool()
|
||||
plugin.Shutdown()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
---
|
||||
title: web G12 API key smoke (W-G12)
|
||||
description: Offline web_api_key_check via Go libweb.so.
|
||||
import plugin:lib/plugin.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
*p = "../../plugins/web/build/libweb.so"*
|
||||
> plugin.load path=`p`
|
||||
|
||||
*pepper = "smoke-pepper"*
|
||||
|
||||
`keys` =
|
||||
|
||||
| hash | scopes |
|
||||
|------|--------|
|
||||
| 0ae9134cca7eff9d756fbf52402ee28ae0c2be22f01e53653e4fe86021479703 | read,api |
|
||||
|
||||
*ok = > web_api_key_check key="smoke-secret" authorization="" pepper=`pepper` keys=`keys`*
|
||||
1. ok[^ok]
|
||||
> print text=api-key-ok
|
||||
2. *
|
||||
> print text=api-key-fail
|
||||
|
||||
*bad = > web_api_key_check key="wrong" authorization="" pepper=`pepper` keys=`keys`*
|
||||
1. bad[^ok]
|
||||
> print text=api-key-bad-ok
|
||||
2. *
|
||||
> print text=api-key-bad-fail
|
||||
Reference in new issue
Block a user