Compare commits

...
7 Commits
Author SHA1 Message Date
cflmy f6374d1593 release: ext pack v1.3.2 trailing slash route fix 2026-10-13 15:37:42 +08:00
cflmy 9ede4bc63d fix(web): strip trailing slash so /post/foo/ matches /post/foo
Go ServeMux does exact-match routing; a trailing slash caused dynamic
routes like /post/{slug} to fall through to the 404 catch-all. Add
withStripTrailingSlash middleware as the outermost handler wrapper so
all downstream middleware (RBAC, tenant, mux) see the normalized path.

Tested: static routes, dynamic routes, root path, query-string preservation.
2026-10-13 15:24:26 +08:00
cflmyandCursor 3ae8f2c843 release: ext pack v1.3.1 OIDC path redirect_uri
Bump ext/VERSION only; CLI remains 1.3.0.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-08 11:42:08 +08:00
cflmyandCursor e9c1a8a730 feat(web): resolve OIDC redirect_uri from request Host
Allow path-style redirect_uri (/oidc/callback) so apex/www and
proxied HTTPS share one config; persist the absolute URI for token exchange.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-08 11:35:12 +08:00
cflmyandCursor 5554b1642c feat(run): add --fs-root / MARQDO_FS_ROOT for subdirectory entries
marqdo run cli/… sandboxes to the entry directory by default; repo-root
sandbox+cwd lets qdagent keep thin CLI wrappers under cli/ without
escaping .marqdo or polluting cli/.marqdo.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-28 22:17:24 +08:00
cflmyandCursor fe15603a91 fix(llm): hoist ask result fields out of the return table
Table cells shadowed self/column names (model, usage), so [model](self)
and [total_tokens](usage) raised "footnote index needs list or map" and
blocked live agent.step / qdagent BUILD.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-28 22:08:48 +08:00
cflmyandCursor 1418742655 Skip docker/data/.cursor when compiling engineering knowledge.
Packaging trees and runtime vaults were inflating EKC with duplicate noise; dogfood agents should index product sources only.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-28 21:50:58 +08:00
15 changed files with 477 additions and 25 deletions

No files matched your search

+34
View File
@@ -8,6 +8,40 @@
### Changed
## Ext pack v1.3.2 — 2026-10-13
### Highlights
**Trailing slash 路由修复(CLI 仍为 v1.3.0)**:Go `ServeMux` 精确匹配导致 `/post/foo/`(带尾部斜杠)落入 404。新增 `withStripTrailingSlash` 中间件作为最外层 handler wrapper,所有下游中间件(RBAC、Tenant、路由)均看到规范化路径。覆盖静态路由、动态路由、根路径、查询参数保留。
```bash
marqdo ext add web # CDN latest → 1.3.2
# 或:MARQDO_EXT_VERSION=1.3.2 marqdo ext add web
```
### Fixed
- **web**: `/post/foo/` trailing slash now routes the same as `/post/foo` (dynamic and static routes). Root `/` unchanged. Query strings preserved after normalization.
## Ext pack v1.3.1 — 2026-10-08
### Highlights
**OIDC 路径型 `redirect_uri`(CLI 仍为 v1.3.0)**:`redirect_uri=/oidc/callback` 按请求 Host / `X-Forwarded-*` 拼绝对回调,写入会话供 token 交换;可选 `redirect_origins` allowlist。apex / www 多域名无需写死单一绝对 URI。
```bash
marqdo ext add web # CDN latest → 1.3.1
# 或:MARQDO_EXT_VERSION=1.3.1 marqdo ext add web
```
### Added
- **路径型 redirect_uri**:绝对 URL 行为不变;路径模式解析 public origin,session 键 `oidc_redirect_uri`。
- **`redirect_origins` / `回调来源`**:逗号分隔 origin allowlist(路径模式)。
- **ABI**:`web_app_oidc` 透传 `redirect_origins`;`ext/security/oidc.attach` 文档同步。
### Changed
- 扩展包 SemVer **1.3.1**(`ext/VERSION`);与 CLI **v1.3.0** 可独立安装。
## v1.3.0 — 2026-09-28
### Highlights
+1 -1
View File
@@ -1 +1 @@
1.3.0
1.3.2
+10 -1
View File
@@ -289,11 +289,20 @@ Semantic ask → **LLMResult** (`text`, `model`, `finish`, `backend`, `usage`, `
2. *
**_ = 1**
Hoist receiver fields before the result table — table cells can shadow `self` /
column names (`model`, `usage`), so `[model](self)` / `[total_tokens](usage)`
inside the table is unsafe.
**mdl = [model](self)**
**b = [backend](self)**
**nm = [name](self)**
**tt = [total_tokens](usage)**
`result` =
| text | model | finish | backend | usage | name | llm_calls | tokens | tool_calls |
|------|-------|--------|---------|-------|------|-----------|--------|------------|
| `text` | [model](self) | `finish` | [backend](self) | `usage` | [name](self) | 1 | [total_tokens](usage) | `tc` |
| `text` | `mdl` | `finish` | `b` | `usage` | `nm` | 1 | `tt` | `tc` |
*result*
+8 -1
View File
@@ -240,11 +240,18 @@ import openai:ext/ai/llm/openai.mq.md
2. *
**_ = 1**
表单元格会遮蔽 `自` / 列名,先取出字段再组结果表。
**mdl = [model](自)**
**b = [backend](自)**
**nm = [name](自)**
**tt = [total_tokens](usage)**
`result` =
| text | model | finish | backend | usage | name | llm_calls | tokens | tool_calls |
|------|-------|--------|---------|-------|------|-----------|--------|------------|
| `text` | [model](自) | `finish` | [backend](自) | `usage` | [name](自) | 1 | [total_tokens](usage) | `tc` |
| `text` | `mdl` | `finish` | `b` | `usage` | `nm` | 1 | `tt` | `tc` |
*result*
+11 -1
View File
@@ -21,11 +21,21 @@ import sys:lib/sys.mq.md
+ `client_id`
+ `client_secret`
+ `redirect_uri`
+ `redirect_origins`=None
+ `scopes`="openid profile email"
+ `callback_path`=None
+ `authorize_url`=None
+ `token_url`=None
+ `userinfo_url`=None
`redirect_uri` may be an absolute URL (`https://qdqc.com/oidc/callback`) or a path
(`/oidc/callback`). Path mode resolves the absolute callback from the login request
Host (`X-Forwarded-Proto` / `X-Forwarded-Host` when behind a reverse proxy) and stores
it in the session so token exchange uses the same string.
Optional `redirect_origins` is a comma-separated allowlist
(`https://qdqc.com,https://www.qdqc.com`). When set, path-mode origins must match.
The IdP must still register every absolute callback URL that will be used.
> _load
*> web_app_oidc app=`app` issuer=`issuer` client_id=`client_id` client_secret=`client_secret` redirect_uri=`redirect_uri` scopes=`scopes` callback_path=`callback_path` authorize_url=`authorize_url` token_url=`token_url` userinfo_url=`userinfo_url`*
*> web_app_oidc app=`app` issuer=`issuer` client_id=`client_id` client_secret=`client_secret` redirect_uri=`redirect_uri` redirect_origins=`redirect_origins` scopes=`scopes` callback_path=`callback_path` authorize_url=`authorize_url` token_url=`token_url` userinfo_url=`userinfo_url`*
+3
View File
@@ -256,6 +256,9 @@ func OIDC(appBag map[string]any, opts map[string]any) (map[string]any, error) {
"scopes": cfg.ScopesCSV(),
"callback_path": cfg.Callback(),
}
if cfg.RedirectOrigins != "" {
bag["redirect_origins"] = cfg.RedirectOrigins
}
if cfg.AuthorizeURL != "" {
bag["authorize_url"] = cfg.AuthorizeURL
}
+18 -2
View File
@@ -117,11 +117,17 @@ func (st *state) handleOIDCStart(w http.ResponseWriter, r *http.Request) {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
redirectURI, err := st.oidc.ResolveRedirectURI(r)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
session.SetValue(sid, "oidc_state", state)
session.SetValue(sid, "oidc_verifier", verifier)
session.SetValue(sid, "oidc_redirect_uri", redirectURI)
next := loginDest(r, st.oidcFallbackNext(r))
session.SetValue(sid, "oidc_next", next)
loc, err := st.oidc.AuthorizeRedirect(state, oidc.PKCEChallengeS256(verifier))
loc, err := st.oidc.AuthorizeRedirect(state, oidc.PKCEChallengeS256(verifier), redirectURI)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
@@ -164,6 +170,15 @@ func (st *state) handleOIDCCallback(w http.ResponseWriter, r *http.Request) {
}
verifier, _ := session.GetValue(sid, "oidc_verifier")
verifierS, _ := verifier.(string)
redirVal, _ := session.GetValue(sid, "oidc_redirect_uri")
redirectURI, _ := redirVal.(string)
if redirectURI == "" && !st.oidc.IsPathRedirect() {
redirectURI = strings.TrimSpace(st.oidc.RedirectURI)
}
if redirectURI == "" {
http.Error(w, "oidc: missing redirect_uri in session", http.StatusBadRequest)
return
}
nextVal, _ := session.GetValue(sid, "oidc_next")
next, _ := nextVal.(string)
if next == "" {
@@ -171,9 +186,10 @@ func (st *state) handleOIDCCallback(w http.ResponseWriter, r *http.Request) {
}
session.DelKey(sid, "oidc_state")
session.DelKey(sid, "oidc_verifier")
session.DelKey(sid, "oidc_redirect_uri")
session.DelKey(sid, "oidc_next")
tok, err := st.oidc.ExchangeCode(oidcClient(), code, verifierS)
tok, err := st.oidc.ExchangeCode(oidcClient(), code, verifierS, redirectURI)
if err != nil {
http.Error(w, "oidc token exchange: "+err.Error(), http.StatusBadGateway)
return
+16
View File
@@ -247,6 +247,7 @@ func NewHandler(appBag map[string]any, entryDir string) (http.Handler, error) {
handler := withMiddleware(mux, mw)
handler = withRBAC(handler, authCfg.gates, authCfg.loginPath)
handler = withTenant(handler, st.tenant)
handler = withStripTrailingSlash(handler)
return handler, nil
}
@@ -641,6 +642,21 @@ func withTenant(next http.Handler, cfg tenant.Config) http.Handler {
})
}
// withStripTrailingSlash rewrites request URLs so that paths like /post/foo/
// are routed as /post/foo. The root path "/" is left unchanged.
func withStripTrailingSlash(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
path := r.URL.Path
if len(path) > 1 && path[len(path)-1] == '/' {
r.URL.Path = strings.TrimRight(path, "/")
if r.URL.Path == "" {
r.URL.Path = "/"
}
}
next.ServeHTTP(w, r)
})
}
func withMiddleware(next http.Handler, mw middleware.Config) http.Handler {
h := next
if mw.BodyLimit != nil && *mw.BodyLimit > 0 {
+62
View File
@@ -152,3 +152,65 @@ func TestNewHandlerIconsRedirectSitemap404(t *testing.T) {
t.Fatalf("home missing icon link: %s", rec.Body.String())
}
}
func TestTrailingSlashNormalization(t *testing.T) {
page := map[string]any{"title": "Home", "intro": "<p>home</p>"}
a := app.New(map[string]any{"page": page})
about := map[string]any{"title": "About", "intro": "<h1>About</h1>", "_route": "/about"}
var err error
a, err = app.Route(a, "/about", about)
if err != nil {
t.Fatal(err)
}
// Dynamic route: /post/{slug}
post := map[string]any{"title": "Post", "intro": "<h1>Post</h1>", "_route": "/post/{slug}"}
a, err = app.Route(a, "/post/{slug}", post)
if err != nil {
t.Fatal(err)
}
h, err := httpx.NewHandler(a, "")
if err != nil {
t.Fatal(err)
}
// Static route: /about should work with and without trailing slash.
rec := httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/about", nil))
if rec.Code != 200 || !strings.Contains(rec.Body.String(), "About") {
t.Fatalf("about (no slash) code=%d body=%q", rec.Code, rec.Body.String())
}
rec = httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/about/", nil))
if rec.Code != 200 || !strings.Contains(rec.Body.String(), "About") {
t.Fatalf("about (trailing slash) code=%d body=%q", rec.Code, rec.Body.String())
}
// Dynamic route: /post/hello should work with and without trailing slash.
rec = httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/post/hello", nil))
if rec.Code != 200 {
t.Fatalf("post/hello (no slash) code=%d body=%q", rec.Code, rec.Body.String())
}
rec = httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/post/hello/", nil))
if rec.Code != 200 {
t.Fatalf("post/hello (trailing slash) code=%d body=%q", rec.Code, rec.Body.String())
}
// Root path "/" should still work.
rec = httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/", nil))
if rec.Code != 200 || !strings.Contains(rec.Body.String(), "Home") {
t.Fatalf("root code=%d body=%q", rec.Code, rec.Body.String())
}
// Query string should be preserved after trailing slash strip.
rec = httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/about/?foo=bar", nil))
if rec.Code != 200 || !strings.Contains(rec.Body.String(), "About") {
t.Fatalf("about (trailing slash + query) code=%d body=%q", rec.Code, rec.Body.String())
}
}
+139 -16
View File
@@ -20,8 +20,11 @@ type Config struct {
ClientID string
ClientSecret string
RedirectURI string
Scopes string
CallbackPath string
// RedirectOrigins is an optional comma-separated allowlist of origins
// (e.g. "https://qdqc.com,https://www.qdqc.com") used when RedirectURI is a path.
RedirectOrigins string
Scopes string
CallbackPath string
// AuthorizeURL / TokenURL / UserInfoURL override discovery when set.
AuthorizeURL string
TokenURL string
@@ -36,11 +39,35 @@ func (c Config) Enabled() bool {
(strings.TrimSpace(c.Issuer) != "" || strings.TrimSpace(c.AuthorizeURL) != "")
}
// IsPathRedirect reports whether RedirectURI is a path (resolved per request Host).
func (c Config) IsPathRedirect() bool {
s := strings.TrimSpace(c.RedirectURI)
if s == "" {
return false
}
if strings.HasPrefix(s, "/") {
return true
}
u, err := url.Parse(s)
if err != nil {
return false
}
// scheme-relative or bare path without host
return u.Scheme == "" && u.Host == "" && u.Path != ""
}
// Callback reports the local path (default /oidc/callback).
func (c Config) Callback() string {
p := strings.TrimSpace(c.CallbackPath)
if p == "" {
if u, err := url.Parse(c.RedirectURI); err == nil && u.Path != "" {
ru := strings.TrimSpace(c.RedirectURI)
if c.IsPathRedirect() {
if !strings.HasPrefix(ru, "/") {
ru = "/" + ru
}
return ru
}
if u, err := url.Parse(ru); err == nil && u.Path != "" {
return u.Path
}
return "/oidc/callback"
@@ -51,6 +78,91 @@ func (c Config) Callback() string {
return p
}
// PublicOrigin derives scheme://host from a login/callback request.
// Prefers X-Forwarded-Proto + X-Forwarded-Host (first value), else Host + TLS.
func PublicOrigin(r *http.Request) (string, error) {
if r == nil {
return "", fmt.Errorf("oidc: nil request")
}
scheme := strings.TrimSpace(r.Header.Get("X-Forwarded-Proto"))
if i := strings.IndexByte(scheme, ','); i >= 0 {
scheme = strings.TrimSpace(scheme[:i])
}
if scheme == "" {
if r.TLS != nil {
scheme = "https"
} else {
scheme = "http"
}
}
host := strings.TrimSpace(r.Header.Get("X-Forwarded-Host"))
if i := strings.IndexByte(host, ','); i >= 0 {
host = strings.TrimSpace(host[:i])
}
if host == "" {
host = strings.TrimSpace(r.Host)
}
if host == "" {
return "", fmt.Errorf("oidc: empty Host")
}
return scheme + "://" + host, nil
}
// ResolveRedirectURI returns the absolute redirect_uri for this request.
// Absolute RedirectURI is returned unchanged; path RedirectURI is joined to the request origin.
func (c Config) ResolveRedirectURI(r *http.Request) (string, error) {
ru := strings.TrimSpace(c.RedirectURI)
if ru == "" {
return "", fmt.Errorf("oidc: empty redirect_uri")
}
if !c.IsPathRedirect() {
return ru, nil
}
origin, err := PublicOrigin(r)
if err != nil {
return "", err
}
path := ru
if !strings.HasPrefix(path, "/") {
path = "/" + path
}
abs := origin + path
if err := c.checkOriginAllowlist(origin); err != nil {
return "", err
}
return abs, nil
}
// AllowedOrigins returns trimmed non-empty origins from RedirectOrigins.
func (c Config) AllowedOrigins() []string {
raw := strings.TrimSpace(c.RedirectOrigins)
if raw == "" {
return nil
}
var out []string
for _, p := range strings.Split(raw, ",") {
p = strings.TrimRight(strings.TrimSpace(p), "/")
if p != "" {
out = append(out, p)
}
}
return out
}
func (c Config) checkOriginAllowlist(origin string) error {
allowed := c.AllowedOrigins()
if len(allowed) == 0 {
return nil
}
origin = strings.TrimRight(strings.TrimSpace(origin), "/")
for _, a := range allowed {
if strings.EqualFold(a, origin) {
return nil
}
}
return fmt.Errorf("oidc: origin %q not in redirect_origins", origin)
}
type discoveryDoc struct {
AuthorizationEndpoint string `json:"authorization_endpoint"`
TokenEndpoint string `json:"token_endpoint"`
@@ -126,14 +238,19 @@ func PKCEChallengeS256(verifier string) string {
}
// AuthorizeRedirect builds the browser redirect to the IdP authorize endpoint.
func (c Config) AuthorizeRedirect(state, codeChallenge string) (string, error) {
// redirectURI must be the absolute URI used for this login (same value later for token exchange).
func (c Config) AuthorizeRedirect(state, codeChallenge, redirectURI string) (string, error) {
if c.AuthorizeURL == "" {
return "", fmt.Errorf("oidc: authorize URL not resolved")
}
redirectURI = strings.TrimSpace(redirectURI)
if redirectURI == "" {
return "", fmt.Errorf("oidc: empty redirect_uri")
}
q := url.Values{}
q.Set("response_type", "code")
q.Set("client_id", c.ClientID)
q.Set("redirect_uri", c.RedirectURI)
q.Set("redirect_uri", redirectURI)
q.Set("scope", c.ScopesCSV())
q.Set("state", state)
if codeChallenge != "" {
@@ -160,17 +277,22 @@ type TokenResponse struct {
}
// ExchangeCode swaps authorization code for tokens (client_secret_post).
func (c Config) ExchangeCode(client *http.Client, code, codeVerifier string) (*TokenResponse, error) {
// redirectURI must match the absolute URI sent in AuthorizeRedirect.
func (c Config) ExchangeCode(client *http.Client, code, codeVerifier, redirectURI string) (*TokenResponse, error) {
if c.TokenURL == "" {
return nil, fmt.Errorf("oidc: token URL not resolved")
}
redirectURI = strings.TrimSpace(redirectURI)
if redirectURI == "" {
return nil, fmt.Errorf("oidc: empty redirect_uri")
}
if client == nil {
client = &http.Client{Timeout: 15 * time.Second}
}
form := url.Values{}
form.Set("grant_type", "authorization_code")
form.Set("code", code)
form.Set("redirect_uri", c.RedirectURI)
form.Set("redirect_uri", redirectURI)
form.Set("client_id", c.ClientID)
form.Set("client_secret", c.ClientSecret)
if codeVerifier != "" {
@@ -313,15 +435,16 @@ func ParseConfig(m map[string]any) Config {
m = nested
}
c := Config{
Issuer: firstStr(m, "issuer", "发行方", "issuer_url"),
ClientID: firstStr(m, "client_id", "客户端编号", "客户端id", "clientId"),
ClientSecret: firstStr(m, "client_secret", "客户端密钥", "clientSecret"),
RedirectURI: firstStr(m, "redirect_uri", "回调", "回调地址", "redirect"),
Scopes: firstStr(m, "scopes", "范围", "scope"),
CallbackPath: firstStr(m, "callback_path", "回调路径"),
AuthorizeURL: firstStr(m, "authorize_url", "授权地址"),
TokenURL: firstStr(m, "token_url", "令牌地址"),
UserInfoURL: firstStr(m, "userinfo_url", "用户信息地址"),
Issuer: firstStr(m, "issuer", "发行方", "issuer_url"),
ClientID: firstStr(m, "client_id", "客户端编号", "客户端id", "clientId"),
ClientSecret: firstStr(m, "client_secret", "客户端密钥", "clientSecret"),
RedirectURI: firstStr(m, "redirect_uri", "回调", "回调地址", "redirect"),
RedirectOrigins: firstStr(m, "redirect_origins", "回调来源", "redirect_origin"),
Scopes: firstStr(m, "scopes", "范围", "scope"),
CallbackPath: firstStr(m, "callback_path", "回调路径"),
AuthorizeURL: firstStr(m, "authorize_url", "授权地址"),
TokenURL: firstStr(m, "token_url", "令牌地址"),
UserInfoURL: firstStr(m, "userinfo_url", "用户信息地址"),
}
return c
}
+138
View File
@@ -1,6 +1,10 @@
package oidc_test
import (
"crypto/tls"
"net/http"
"net/url"
"strings"
"testing"
"github.com/marqdo/marqdo/plugins/web/internal/oidc"
@@ -46,4 +50,138 @@ func TestPKCEAndParse(t *testing.T) {
if c.Callback() != "/oidc/callback" {
t.Fatalf("callback=%s", c.Callback())
}
if c.IsPathRedirect() {
t.Fatal("absolute redirect should not be path mode")
}
}
func TestPathRedirectParseAndCallback(t *testing.T) {
c := oidc.ParseConfig(map[string]any{
"issuer": "https://id.example.com",
"client_id": "app_x",
"client_secret": "secret",
"redirect_uri": "/oidc/callback",
"redirect_origins": "https://qdqc.com,https://www.qdqc.com",
})
if !c.Enabled() {
t.Fatal("expected enabled")
}
if !c.IsPathRedirect() {
t.Fatal("expected path mode")
}
if c.Callback() != "/oidc/callback" {
t.Fatalf("callback=%s", c.Callback())
}
origins := c.AllowedOrigins()
if len(origins) != 2 || origins[0] != "https://qdqc.com" {
t.Fatalf("origins=%v", origins)
}
}
func TestResolveRedirectURIAbsolute(t *testing.T) {
c := oidc.Config{RedirectURI: "https://qdqc.com/oidc/callback"}
r, _ := http.NewRequest(http.MethodGet, "http://www.qdqc.com/oidc/login", nil)
r.Host = "www.qdqc.com"
got, err := c.ResolveRedirectURI(r)
if err != nil {
t.Fatal(err)
}
if got != "https://qdqc.com/oidc/callback" {
t.Fatalf("got=%s", got)
}
}
func TestResolveRedirectURIPathFromHost(t *testing.T) {
c := oidc.Config{RedirectURI: "/oidc/callback"}
r, _ := http.NewRequest(http.MethodGet, "http://qdqc.com/oidc/login", nil)
r.Host = "qdqc.com"
got, err := c.ResolveRedirectURI(r)
if err != nil {
t.Fatal(err)
}
if got != "http://qdqc.com/oidc/callback" {
t.Fatalf("got=%s", got)
}
}
func TestResolveRedirectURIPathTLS(t *testing.T) {
c := oidc.Config{RedirectURI: "/oidc/callback"}
r, _ := http.NewRequest(http.MethodGet, "https://qdqc.com/oidc/login", nil)
r.Host = "qdqc.com"
r.TLS = &tls.ConnectionState{}
got, err := c.ResolveRedirectURI(r)
if err != nil {
t.Fatal(err)
}
if got != "https://qdqc.com/oidc/callback" {
t.Fatalf("got=%s", got)
}
}
func TestResolveRedirectURIXForwarded(t *testing.T) {
c := oidc.Config{RedirectURI: "/oidc/callback"}
r, _ := http.NewRequest(http.MethodGet, "http://127.0.0.1:18085/oidc/login", nil)
r.Host = "127.0.0.1:18085"
r.Header.Set("X-Forwarded-Proto", "https")
r.Header.Set("X-Forwarded-Host", "www.qdqc.com, other.example")
got, err := c.ResolveRedirectURI(r)
if err != nil {
t.Fatal(err)
}
if got != "https://www.qdqc.com/oidc/callback" {
t.Fatalf("got=%s", got)
}
}
func TestResolveRedirectURIAllowlistReject(t *testing.T) {
c := oidc.Config{
RedirectURI: "/oidc/callback",
RedirectOrigins: "https://qdqc.com,https://www.qdqc.com",
}
r, _ := http.NewRequest(http.MethodGet, "https://evil.example/oidc/login", nil)
r.Host = "evil.example"
r.Header.Set("X-Forwarded-Proto", "https")
_, err := c.ResolveRedirectURI(r)
if err == nil || !strings.Contains(err.Error(), "redirect_origins") {
t.Fatalf("expected allowlist error, got %v", err)
}
}
func TestResolveRedirectURIAllowlistOK(t *testing.T) {
c := oidc.Config{
RedirectURI: "/oidc/callback",
RedirectOrigins: "https://qdqc.com,https://www.qdqc.com",
}
r, _ := http.NewRequest(http.MethodGet, "https://www.qdqc.com/oidc/login", nil)
r.Host = "www.qdqc.com"
r.Header.Set("X-Forwarded-Proto", "https")
got, err := c.ResolveRedirectURI(r)
if err != nil {
t.Fatal(err)
}
if got != "https://www.qdqc.com/oidc/callback" {
t.Fatalf("got=%s", got)
}
}
func TestAuthorizeRedirectUsesExplicitURI(t *testing.T) {
c := oidc.Config{
ClientID: "app_x",
AuthorizeURL: "https://id.example.com/oauth2/authorize",
RedirectURI: "/oidc/callback",
}
loc, err := c.AuthorizeRedirect("st", "ch", "https://www.qdqc.com/oidc/callback")
if err != nil {
t.Fatal(err)
}
u, err := url.Parse(loc)
if err != nil {
t.Fatal(err)
}
if got := u.Query().Get("redirect_uri"); got != "https://www.qdqc.com/oidc/callback" {
t.Fatalf("redirect_uri=%s", got)
}
if u.Query().Get("state") != "st" {
t.Fatal("state")
}
}
+1 -1
View File
@@ -219,7 +219,7 @@ static int register_core(void) {
if (host_register((char *)"web_auth_logout", (char *)"session_id", web_auth_logout) != 0) return 1;
if (host_register((char *)"web_auth_new", (char *)"users,session_ttl", web_auth_new) != 0) return 1;
if (host_register((char *)"web_app_auth", (char *)"app,users,session_ttl,admin_prefix,login_redirect,logout_redirect,login_path,register,register_path,default_role,session_url", web_app_auth) != 0) return 1;
if (host_register((char *)"web_app_oidc", (char *)"app,issuer,client_id,client_secret,redirect_uri,scopes,callback_path,authorize_url,token_url,userinfo_url", web_app_oidc) != 0) return 1;
if (host_register((char *)"web_app_oidc", (char *)"app,issuer,client_id,client_secret,redirect_uri,redirect_origins,scopes,callback_path,authorize_url,token_url,userinfo_url", web_app_oidc) != 0) return 1;
if (host_register((char *)"web_app_gate", (char *)"app,path,roles,permissions,match,on_deny,exclude", web_app_gate) != 0) return 1;
if (host_register((char *)"web_app_rbac", (char *)"app,catalog,desk", web_app_rbac) != 0) return 1;
if (host_register((char *)"web_app_tenant", (char *)"app,mode,param,column,default_scope", web_app_tenant) != 0) return 1;
+14 -2
View File
@@ -164,7 +164,13 @@ fn collect_mq_md(
let p = entry.path();
if p.is_dir() {
let name = p.file_name().and_then(|s| s.to_str()).unwrap_or("");
if name == "target" || name == ".git" || name == "node_modules" {
if name == "target"
|| name == ".git"
|| name == "node_modules"
|| name == "docker"
|| name == "data"
|| name == ".cursor"
{
continue;
}
if let Ok(canon) = p.canonicalize() {
@@ -204,7 +210,13 @@ fn walk_knowledge_md(
let p = entry.path();
if p.is_dir() {
let name = p.file_name().and_then(|s| s.to_str()).unwrap_or("");
if name == "target" || name == ".git" || name == ".marqdo" {
if name == "target"
|| name == ".git"
|| name == ".marqdo"
|| name == "docker"
|| name == "data"
|| name == ".cursor"
{
continue;
}
if let Ok(canon) = p.canonicalize() {
+12
View File
@@ -207,6 +207,10 @@ pub fn run_file(path: &Path, opts: &RunOptions) -> Result<i32> {
let mut host = HostContext::for_run(Some(path), opts.host_caps(), opts.argv.clone());
host.set_entry_source(Some(path), &source);
host.entry_metadata = module.metadata.clone();
if let Some(root) = &opts.fs_root {
host.fs_root = Some(root.clone());
host.cwd = root.clone();
}
let mut interp = Interpreter::new(Some(path), opts.trace_eval)
.with_stdin(stdin_lines.clone())
.with_host(host);
@@ -229,6 +233,10 @@ pub fn run_file(path: &Path, opts: &RunOptions) -> Result<i32> {
let mut host = HostContext::for_run(Some(path), opts.host_caps(), opts.argv.clone());
host.set_entry_source(Some(path), &source);
host.entry_metadata = module.metadata.clone();
if let Some(root) = &opts.fs_root {
host.fs_root = Some(root.clone());
host.cwd = root.clone();
}
let mut vm = Vm::new(Some(path))
.with_stdin(stdin_lines)
.with_trace(opts.trace_eval)
@@ -283,6 +291,7 @@ pub fn run_file_capture(path: &Path, opts: &RunOptions) -> Result<RunCapture> {
host.entry_metadata = module.metadata.clone();
if let Some(root) = &opts.fs_root {
host.fs_root = Some(root.clone());
host.cwd = root.clone();
}
if let Some(lim) = opts.sleep_limit_ms {
host.sleep_limit_ms = Some(lim);
@@ -307,6 +316,7 @@ pub fn run_file_capture(path: &Path, opts: &RunOptions) -> Result<RunCapture> {
host.entry_metadata = module.metadata.clone();
if let Some(root) = &opts.fs_root {
host.fs_root = Some(root.clone());
host.cwd = root.clone();
}
if let Some(lim) = opts.sleep_limit_ms {
host.sleep_limit_ms = Some(lim);
@@ -341,6 +351,7 @@ pub fn run_source(source: &str, opts: &RunOptions) -> Result<RunCapture> {
host.entry_metadata = module.metadata.clone();
if let Some(root) = &opts.fs_root {
host.fs_root = Some(root.clone());
host.cwd = root.clone();
}
if let Some(lim) = opts.sleep_limit_ms {
host.sleep_limit_ms = Some(lim);
@@ -365,6 +376,7 @@ pub fn run_source(source: &str, opts: &RunOptions) -> Result<RunCapture> {
host.entry_metadata = module.metadata.clone();
if let Some(root) = &opts.fs_root {
host.fs_root = Some(root.clone());
host.cwd = root.clone();
}
if let Some(lim) = opts.sleep_limit_ms {
host.sleep_limit_ms = Some(lim);
+10
View File
@@ -78,6 +78,11 @@ enum Commands {
#[arg(long = "bind", value_name = "KEY=VALUE")]
binds: Vec<String>,
/// Filesystem sandbox + process cwd root (default: entry file's directory).
/// Also read from env `MARQDO_FS_ROOT`. Use repo root when running `cli/…` entries.
#[arg(long = "fs-root", value_name = "DIR")]
fs_root: Option<PathBuf>,
/// Emit diagnostics as JSON on stderr (machine-readable; AI/MLSP 面).
#[arg(long)]
json: bool,
@@ -412,6 +417,7 @@ fn try_main(cli: Cli) -> Result<i32> {
stdin_file,
emit_result,
binds,
fs_root,
json: _,
} => {
let path = file.unwrap_or_else(|| PathBuf::from("index.mq.md"));
@@ -423,11 +429,14 @@ fn try_main(cli: Cli) -> Result<i32> {
for b in &binds {
bind_pairs.push(marqdo::binding::parse_bind_kv(b)?);
}
let env_fs_root = std::env::var_os("MARQDO_FS_ROOT").map(PathBuf::from);
let fs_root = fs_root.or(env_fs_root);
let mut opts = if dump_all {
RunOptions {
stdin_lines: stdin_lines.clone(),
emit_result: emit_result.clone(),
binds: bind_pairs.clone(),
fs_root: fs_root.clone(),
..RunOptions::dump_all()
}
} else {
@@ -442,6 +451,7 @@ fn try_main(cli: Cli) -> Result<i32> {
stdin_lines,
emit_result,
binds: bind_pairs,
fs_root,
..RunOptions::default()
}
};