Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

fix(embed): enforce host origin allowlists on framed pages

wizardchen801ae18f91b3
diff --git a/docs/embed-secure-mode.md b/docs/embed-secure-mode.md
index 39cf40362..9272feb4a 100644
--- a/docs/embed-secure-mode.md
+++ b/docs/embed-secure-mode.md
@@ -147,12 +147,9 @@ func embedTokenHandler(w http.ResponseWriter, r *http.Request) {
## 域名白名单怎么填?
-| 要放行的请求来源 | 白名单示例 |
-|------------------|------------|
-| 聊天 iframe 所在源站(embed 页面) | `https://app.example.com` 或 `https://embed.example.com` |
-| 你的取令牌后端(exchange 时带的 Origin) | `https://shop.example.com` |
+A 网站(例如 `https://shop.example.com`)嵌入 B 上的 WeKnora 时,只需填写 A。iframe 的正常同源 API 调用不要求把 B 额外加入白名单。
-若 embed 使用[独立子域](./embed-subdomain.md),**两条都要加**(embed 源站 + 业务后端源站)。
+业务后端调用 exchange 时,继续发送 `Origin: https://shop.example.com`,与实际宿主和渠道白名单一致。这里声明的是业务来源,不是后端机器的部署地址。完整部署及升级要求见[独立子域配置](./embed-subdomain.md#3-域名白名单填什么)。
开发环境可临时使用 `*`;**生产环境禁止 `*`**。
@@ -161,7 +158,7 @@ func embedTokenHandler(w http.ResponseWriter, r *http.Request) {
- [ ] 发布 Token 仅通过环境变量 / 密钥服务注入,未提交到 Git、未打进前端静态包
- [ ] 取令牌接口校验访客身份
- [ ] 全链路 HTTPS
-- [ ] 白名单已包含 embed 源站与 exchange 使用的 Origin
+- [ ] 白名单已包含宿主网站 A,exchange 使用同一 Origin
- [ ] 已配置限流;敏感智能体不要用普通模式把 Token 暴露在网页里
- [ ] 轮换发布 Token 后,同步更新服务端环境变量
@@ -170,7 +167,8 @@ func embedTokenHandler(w http.ResponseWriter, r *http.Request) {
| 现象 | 原因与处理 |
|------|------------|
| exchange 返回 **401** / `publish token required` | 发布 Token 错误、已轮换,或误用了 `ems_` 会话 Token |
-| exchange 或聊天 API 返回 **403** `origin not allowed` | 白名单未包含当前请求的 `Origin`;服务端 exchange 记得手动加 `Origin` 头 |
+| exchange 或聊天 API 返回 **403** `origin not allowed` | 服务端 exchange 需手动加白名单中的业务 `Origin`;同源聊天失败时检查代理是否保留 Host(含端口)、协议和 `Sec-Fetch-Site` |
+| iframe 被 **frame-ancestors** 拒绝 | 将宿主网站 A 加入渠道白名单,确认所有祖先页面均被允许;旧渠道只填 B 的配置需要更新 |
| iframe 一直「等待 Token」 | `token-endpoint` 未返回 `{ token, expiresIn }`,或 CORS 未允许 Widget 所在源站访问你的接口 |
| 取令牌接口 **502** `mint failed` | WeKnora 不可达、渠道已停用,或 exchange 响应格式不对 |
| 访客随便就能聊 | 取令牌接口未做登录校验——在 exchange 前加 Session / JWT 检查 |
diff --git a/docs/embed-subdomain.md b/docs/embed-subdomain.md
index 863b79743..e3d346ef6 100644
--- a/docs/embed-subdomain.md
+++ b/docs/embed-subdomain.md
@@ -75,17 +75,19 @@ window.__RUNTIME_CONFIG__ = {
### 3. 域名白名单填什么?
-渠道里的「域名白名单」校验的是 **API 请求的 `Origin` 头**,不是「允许哪些网站粘贴脚本」的抽象概念。
+填写**允许嵌入的宿主网站 Origin**:A 网站嵌入 B 上的 WeKnora,就填 A,例如 `https://shop.example.com`,不需要为了聊天 API 再添加 B。
-实际要填:
+- 每行一个完整 Origin(协议、域名、可选端口),不能带业务路径、查询参数或用户名。允许末尾 `/`,匹配时会规范化。
+- `*.example.com` 允许 HTTP(S) 子域名及其端口,不包含根域 `example.com`;`*.example.com:8443` 可限定端口。
+- 嵌入 HTML 的 `Content-Security-Policy: frame-ancestors` 由渠道白名单生成,由浏览器检查所有祖先页面;同源管理端预览也允许。
+- iframe 内 API 请求来自 B,正常同源请求不再要求 B 出现在宿主白名单。安全模式下业务后端换取令牌仍需手动发送 `Origin: https://shop.example.com`,与白名单一致。
+- 空白名单、无效或停用渠道拒绝加载;不要用 `*` 作为生产配置。
-1. **Embed 页面源站**(必填)——聊天 iframe 内发 API 时浏览器会带这个 Origin
- - 同域部署:`https://app.example.com`
- - 独立子域:`https://embed.example.com`
-2. **你的业务后端源站**(安全模式时建议填)——你自己写的「取令牌接口」在服务端调用 `POST .../exchange` 时,需带与白名单一致的 `Origin` 头(见 [embed-secure-mode.md](./embed-secure-mode.md))
+**部署要求**:标准前端 Nginx 的 `/embed/` 必须保留 `auth_request`、内部 `/_embed-frame-policy` 和 CSP 响应头配置。它通过后端 `/api/v1/embed-frame-policy` 获取策略,再直接返回 `embed.html`。后端不可用时拒绝返回嵌入页面。Lite 在 Go 静态页面响应上设置同一策略。自定义网关/CDN 不得移除或缓存该响应头;HTTPS 代理应保留原始 Host(含端口)、协议和 `Sec-Fetch-Site`。
-第三方商城 `https://shop.example.com` **通常不用**进白名单(它只是加载脚本,不直接调 embed API)。
-若你把 embed 反代到商城同域路径下(少见),才需要填商城域名。
+**升级已有渠道**:过去仅填写 WeKnora 的 B 地址的渠道,需改为实际宿主 A;同时更新前端 Nginx 和后端。不会自动猜测或放行未知宿主。安全模式的业务来源配置保持一致。
+
+白名单限制浏览器嵌入,不替代用户认证。直接打开链接或非浏览器客户端仍由 token、会话签名和限流保护;需控制访客身份时使用安全模式。
## Widget 跨域与 sandbox
@@ -98,7 +100,7 @@ A 与 B 同域时保持默认即可,无需 `data-sandbox`。
- [ ] `EMBED_BASE_URL` 与真实访问地址一致(含 `https`)
- [ ] embed 子域能打开 `/embed/<渠道ID>` 和 `/weknora-widget.js`
- [ ] embed 子域 `/api/` 能连到后端
-- [ ] 渠道白名单包含 embed 源站(及安全模式下的业务后端源站)
+- [ ] 渠道白名单包含实际宿主网站 A;安全模式 exchange 声明同一业务 Origin
- [ ] 管理端复制的 snippet 里 URL 已变为 embed 子域
## 相关文档
diff --git a/frontend/nginx-api-proxy.conf b/frontend/nginx-api-proxy.conf
index 0eaaedd01..394bf737e 100644
--- a/frontend/nginx-api-proxy.conf
+++ b/frontend/nginx-api-proxy.conf
@@ -9,7 +9,8 @@
# This file is copied verbatim, not run through envsubst, so $host and friends
# survive as nginx variables.
-proxy_set_header Host $host;
+# Preserve the public port for same-origin embed API checks on HTTP deployments.
+proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
diff --git a/frontend/nginx.conf b/frontend/nginx.conf
index ee1a1fddc..d964a71bf 100644
--- a/frontend/nginx.conf
+++ b/frontend/nginx.conf
@@ -7,7 +7,8 @@
# server_name embed.example.com;
# client_max_body_size ${MAX_FILE_SIZE};
# location = /weknora-widget.js { root /usr/share/nginx/html; }
-# location ^~ /embed/ { root /usr/share/nginx/html; try_files $uri $uri/ /embed.html; }
+# # Copy the /embed/, /_embed-frame-policy, and internal /embed.html
+# # locations from the server below; all are required for the host allowlist.
# location ^~ /assets/ { root /usr/share/nginx/html; add_header Cache-Control "public, max-age=31536000, immutable"; }
# location /api/ { proxy_pass http://weknora-backend:8080; proxy_set_header Host $host; }
# }
@@ -59,13 +60,30 @@ server {
# Embed widget pages may be loaded inside third-party iframes (lightweight embed.html)
location ^~ /embed/ {
root /usr/share/nginx/html;
- try_files $uri $uri/ /embed.html;
- add_header Cache-Control "no-cache, must-revalidate" always;
+ # Keep the original location through the access phase and file serving.
+ # An internal redirect to /embed.html would lose the per-channel CSP.
+ auth_request /_embed-frame-policy;
+ auth_request_set $embed_frame_csp $upstream_http_content_security_policy;
+ add_header Content-Security-Policy $embed_frame_csp always;
+ try_files /embed.html =404;
+ add_header Cache-Control "no-store" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
}
+ # Fail closed if the backend cannot resolve an enabled channel and policy.
+ location = /_embed-frame-policy {
+ internal;
+ proxy_pass ${APP_SCHEME}://${APP_HOST}:${APP_PORT}/api/v1/embed-frame-policy;
+ proxy_pass_request_body off;
+ proxy_set_header Content-Length "";
+ proxy_set_header X-Embed-Page-URI $request_uri;
+ proxy_set_header Host $http_host;
+ proxy_set_header X-Forwarded-Proto $scheme;
+ proxy_cache off;
+ }
+
# 前端静态文件
location / {
root /usr/share/nginx/html;
diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts
index f556d1629..3cdb36bac 100755
--- a/frontend/src/i18n/locales/en-US.ts
+++ b/frontend/src/i18n/locales/en-US.ts
@@ -2729,7 +2729,7 @@ export default {
welcomeMessageDesc: 'Shown in the embed chat before the visitor sends their first message; leave blank to hide',
showSuggestedQuestions: 'Suggested questions',
showSuggestedQuestionsDesc: 'Show starter prompts before the first visitor message, from agent config and linked knowledge bases',
- originsHint: 'One full origin per line (e.g. https://shop.example.com), at least one required; *.example.com subdomain wildcards supported',
+ originsHint: 'Enter the host websites allowed to embed this channel (A), not the WeKnora address (B). One full origin per line, e.g. https://shop.example.com; at least one required. Supports *.example.com.',
originsRequired: 'At least one allowed origin is required',
originsInvalid: 'Invalid origin: {origin}',
originsWildcardProd: 'Wildcard origin \'*\' is not allowed in production',
diff --git a/frontend/src/i18n/locales/ja-JP.ts b/frontend/src/i18n/locales/ja-JP.ts
index 2a12bc75b..5ff18084e 100644
--- a/frontend/src/i18n/locales/ja-JP.ts
+++ b/frontend/src/i18n/locales/ja-JP.ts
@@ -2729,7 +2729,7 @@ export default {
welcomeMessageDesc: '訪問者が最初のメッセージを送る前に埋め込みチャットに表示されます。空欄にすると非表示になります',
showSuggestedQuestions: '質問候補',
showSuggestedQuestionsDesc: '訪問者の最初のメッセージの前に、エージェント設定と連携ナレッジベースをもとにした質問候補を表示します',
- originsHint: '1行に1つの完全なオリジンを入力します(例: https://shop.example.com)。1件以上必須です。*.example.comのようなサブドメインのワイルドカードに対応しています',
+ originsHint: 'WeKnora の URL(B)ではなく、埋め込みを許可するホストサイト(A)を入力します。1 行に 1 つの Origin(例: https://shop.example.com)。1 件以上必須。*.example.com に対応。',
originsRequired: '許可オリジンを1件以上入力してください',
originsInvalid: '無効なオリジン: {origin}',
originsWildcardProd: '本番環境ではワイルドカードのオリジン「*」は使用できません',
diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts
index a9e59315c..a997210ae 100755
--- a/frontend/src/i18n/locales/ko-KR.ts
+++ b/frontend/src/i18n/locales/ko-KR.ts
@@ -4428,7 +4428,7 @@ export default {
welcomeMessageDesc: '방문자가 임베드 채팅을 열고 첫 메시지를 보내기 전에 표시됩니다. 비우면 표시하지 않습니다',
showSuggestedQuestions: '추천 질문',
showSuggestedQuestionsDesc: '방문자 첫 메시지 전에 빠른 질문을 표시합니다(에이전트 설정 및 연결된 지식베이스에서 가져옴)',
- originsHint: '한 줄에 하나의 전체 출처(예: https://shop.example.com), 최소 1개; *.example.com 서브도메인 와일드카드 지원',
+ originsHint: 'WeKnora 주소(B)가 아닌 임베드를 허용할 호스트 웹사이트(A)를 입력하세요. 한 줄에 하나의 Origin(예: https://shop.example.com), 최소 1개. *.example.com 지원.',
originsRequired: '허용 도메인을 최소 1개 입력하세요',
originsInvalid: '잘못된 도메인: {origin}',
originsWildcardProd: '프로덕션에서는 와일드카드 \'*\'를 사용할 수 없습니다',
diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts
index d9f9b5520..296372b59 100755
--- a/frontend/src/i18n/locales/ru-RU.ts
+++ b/frontend/src/i18n/locales/ru-RU.ts
@@ -4428,7 +4428,7 @@ export default {
welcomeMessageDesc: 'Показывается во встроенном чате до первого сообщения посетителя; оставьте пустым, чтобы скрыть',
showSuggestedQuestions: 'Рекомендуемые вопросы',
showSuggestedQuestionsDesc: 'Показывать быстрые вопросы до первого сообщения посетителя — из настроек агента и связанных баз знаний',
- originsHint: 'Один полный origin в строке (напр. https://shop.example.com), минимум один; поддерживаются поддомены *.example.com',
+ originsHint: 'Укажите сайты, которым разрешено встраивание (A), а не адрес WeKnora (B). Один полный Origin на строку, например https://shop.example.com; минимум один. Поддерживается *.example.com.',
originsRequired: 'Укажите хотя бы один разрешённый домен',
originsInvalid: 'Неверный домен: {origin}',
originsWildcardProd: 'В production запрещён wildcard \'*\'',
diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts
index b86905601..5d989b0db 100755
--- a/frontend/src/i18n/locales/zh-CN.ts
+++ b/frontend/src/i18n/locales/zh-CN.ts
@@ -4430,7 +4430,7 @@ export default {
welcomeMessageDesc: '访客打开嵌入聊天后、尚未发言时展示;留空则不显示',
showSuggestedQuestions: '推荐问题',
showSuggestedQuestionsDesc: '访客未发言前展示快捷提问,内容来自智能体配置与关联知识库',
- originsHint: '每行一个完整来源地址(如 https://shop.example.com),至少填写一个;支持 *.example.com 子域通配',
+ originsHint: '填写允许嵌入的宿主网站来源(A),不是 WeKnora 地址(B)。每行一个完整 Origin,如 https://shop.example.com;至少一项,支持 *.example.com 子域通配',
originsRequired: '请至少填写一个域名白名单',
originsInvalid: '域名格式无效:{origin}',
originsWildcardProd: '生产环境不允许使用通配符 *',
diff --git a/frontend/src/utils/embedAllowedOrigins.test.ts b/frontend/src/utils/embedAllowedOrigins.test.ts
new file mode 100644
index 000000000..4b06f27a5
--- /dev/null
+++ b/frontend/src/utils/embedAllowedOrigins.test.ts
@@ -0,0 +1,18 @@
+import { strict as assert } from 'node:assert'
+import { test } from 'node:test'
+import { validateAllowedOrigins } from './embedAllowedOrigins'
+
+test('accepts host origins, ports, trailing slash and subdomain patterns', () => {
+ for (const origin of ['https://shop.example.com', 'http://localhost:8080', 'https://shop.example.com/', '*.example.com', '*.example.com:8443']) {
+ assert.equal(validateAllowedOrigins([origin], true).ok, true, origin)
+ }
+})
+
+test('rejects URLs that cannot be used as origin/CSP sources', () => {
+ for (const origin of ['https://shop.example.com/path', 'https://[email protected]', 'https://shop.example.com?q=1', 'https://shop.example.com#', 'https://shop.example.com;', 'https://shop.example.com; frame-ancestors *', 'https://*', 'https://shop.example.com/../']) {
+ assert.equal(validateAllowedOrigins([origin], true).ok, false, origin)
+ }
+ assert.equal(validateAllowedOrigins([], true).ok, false)
+ assert.equal(validateAllowedOrigins(['*'], true).ok, false)
+ assert.equal(validateAllowedOrigins(['*'], false).ok, true)
+})
diff --git a/frontend/src/utils/embedAllowedOrigins.ts b/frontend/src/utils/embedAllowedOrigins.ts
index b4fd608ba..70b0879d4 100644
--- a/frontend/src/utils/embedAllowedOrigins.ts
+++ b/frontend/src/utils/embedAllowedOrigins.ts
@@ -13,7 +13,7 @@ export function parseAllowedOrigins(text: string): string[] {
export function validateAllowedOrigins(
origins: string[],
- prod = import.meta.env.PROD,
+ prod = import.meta.env?.PROD ?? false,
): { ok: true; origins: string[] } | { ok: false; error: AllowedOriginsValidationError } {
const cleaned = parseAllowedOrigins(origins.join('\n'))
if (cleaned.length === 0) {
@@ -31,8 +31,13 @@ export function validateAllowedOrigins(
host = `https://${origin.slice(2)}`
}
try {
+ if (!/^https?:\/\/[^/?#\\\s]+\/?$/i.test(host)) {
+ return { ok: false, error: { code: 'invalid', origin } }
+ }
const url = new URL(host)
- if ((url.protocol !== 'http:' && url.protocol !== 'https:') || !url.host) {
+ if ((url.protocol !== 'http:' && url.protocol !== 'https:') || !url.host ||
+ url.username || url.password || (url.pathname !== '' && url.pathname !== '/') ||
+ host.includes('?') || host.includes('#') || /[\s'";,*\\]/.test(url.host)) {
return { ok: false, error: { code: 'invalid', origin } }
}
} catch {
diff --git a/internal/embedpolicy/origin.go b/internal/embedpolicy/origin.go
new file mode 100644
index 000000000..1b13ce929
--- /dev/null
+++ b/internal/embedpolicy/origin.go
@@ -0,0 +1,115 @@
+// Package embedpolicy separates browser framing policy from API transport origins.
+package embedpolicy
+
+import (
+ "fmt"
+ "net"
+ "net/url"
+ "strings"
+)
+
+// NormalizeOrigin accepts an HTTP(S) origin, with an optional trailing slash.
+// Reject URL components that cannot appear in an Origin or CSP host source.
+func NormalizeOrigin(raw string) (string, error) {
+ raw = strings.TrimSpace(raw)
+ u, err := url.Parse(raw)
+ if err != nil || u == nil || (u.Scheme != "http" && u.Scheme != "https") || u.Hostname() == "" ||
+ u.User != nil || (u.Path != "" && u.Path != "/") || u.RawQuery != "" || u.ForceQuery ||
+ strings.Contains(raw, "#") || strings.ContainsAny(u.Host, " \t\r\n'\";,*\\") {
+ return "", fmt.Errorf("invalid allowed origin: %q", raw)
+ }
+ host := strings.ToLower(u.Host)
+ if (u.Scheme == "https" && u.Port() == "443") || (u.Scheme == "http" && u.Port() == "80") {
+ host = strings.ToLower(u.Hostname())
+ if strings.Contains(host, ":") {
+ host = "[" + host + "]"
+ }
+ }
+ return u.Scheme + "://" + host, nil
+}
+
+// NormalizePattern accepts an exact origin, a subdomain wildcard, or the development wildcard.
+func NormalizePattern(raw string) (string, error) {
+ raw = strings.TrimSpace(raw)
+ if raw == "*" {
+ return raw, nil
+ }
+ if strings.HasPrefix(raw, "*.") {
+ origin, err := NormalizeOrigin("https://" + strings.TrimPrefix(raw, "*."))
+ if err != nil {
+ return "", fmt.Errorf("invalid allowed origin: %q", raw)
+ }
+ u, _ := url.Parse(origin)
+ if net.ParseIP(u.Hostname()) != nil {
+ return "", fmt.Errorf("invalid allowed origin: %q", raw)
+ }
+ // Preserve an explicit wildcard port, including the HTTPS default port.
+ original, _ := url.Parse("https://" + strings.TrimPrefix(raw, "*."))
+ host := strings.ToLower(original.Host)
+ return "*." + host, nil
+ }
+ return NormalizeOrigin(raw)
+}
+
+// Allows matches an API origin against normalized host patterns.
+func Allows(origin string, patterns []string) bool {
+ normalized, err := NormalizeOrigin(origin)
+ if err != nil {
+ return false
+ }
+ u, _ := url.Parse(normalized)
+ for _, raw := range patterns {
+ pattern, err := NormalizePattern(raw)
+ if err != nil {
+ continue
+ }
+ if pattern == "*" || pattern == normalized {
+ return true
+ }
+ if strings.HasPrefix(pattern, "*.") {
+ wildcard, _ := url.Parse("https://" + strings.TrimPrefix(pattern, "*."))
+ port := u.Port()
+ if port == "" {
+ if u.Scheme == "https" {
+ port = "443"
+ } else {
+ port = "80"
+ }
+ }
+ if strings.HasSuffix(u.Hostname(), "."+wildcard.Hostname()) &&
+ (wildcard.Port() == "" || wildcard.Port() == port) {
+ return true
+ }
+ }
+ }
+ return false
+}
+
+// FrameAncestors also permits same-origin management previews. Empty or wholly
+// invalid legacy lists fail closed; invalid strings never reach the CSP header.
+func FrameAncestors(patterns []string) string {
+ sources := []string{}
+ for _, raw := range patterns {
+ pattern, err := NormalizePattern(raw)
+ if err != nil {
+ continue
+ }
+ if pattern == "*" {
+ return "frame-ancestors *"
+ }
+ if strings.HasPrefix(pattern, "*.") {
+ u, _ := url.Parse("https://" + strings.TrimPrefix(pattern, "*."))
+ host := pattern
+ if u.Port() == "" {
+ host += ":*"
+ }
+ sources = append(sources, "http://"+host, "https://"+host)
+ } else {
+ sources = append(sources, pattern)
+ }
+ }
+ if len(sources) == 0 {
+ return "frame-ancestors 'none'"
+ }
+ return "frame-ancestors 'self' " + strings.Join(sources, " ")
+}
diff --git a/internal/embedpolicy/origin_test.go b/internal/embedpolicy/origin_test.go
new file mode 100644
index 000000000..1094a51c5
--- /dev/null
+++ b/internal/embedpolicy/origin_test.go
@@ -0,0 +1,62 @@
+package embedpolicy
+
+import "testing"
+
+func TestOriginPatterns(t *testing.T) {
+ for _, tc := range []struct {
+ origin, pattern string
+ want bool
+ }{
+ {"https://B.example", "https://b.example/", true},
+ {"https://a.example", "https://a.example:443", true},
+ {"http://a.example:8080", "http://a.example:8080", true},
+ {"http://a.example", "https://a.example", false},
+ {"https://a.example:8443", "https://a.example", false},
+ {"https://shop.example.com:8443", "*.example.com", true},
+ {"https://SHOP.EXAMPLE.COM", "*.EXAMPLE.COM", true},
+ {"https://shop.example.com", "*.example.com:443", true},
+ {"http://shop.example.com", "*.example.com:443", false},
+ {"https://example.com", "*.example.com", false},
+ {"https://evil-example.com", "*.example.com", false},
+ {"https://example.com.evil.test", "*.example.com", false},
+ {"https://evil.test/path.example.com", "*.example.com", false},
+ {"null", "*", false},
+ {"", "*", false},
+ } {
+ t.Run(tc.origin+"/"+tc.pattern, func(t *testing.T) {
+ if got := Allows(tc.origin, []string{tc.pattern}); got != tc.want {
+ t.Fatalf("got %v want %v", got, tc.want)
+ }
+ })
+ }
+}
+
+func TestRejectInvalidPatterns(t *testing.T) {
+ for _, raw := range []string{
+ "https://a.example/path", "https://a.example?x=1", "https://a.example?", "https://a.example#",
+ "https://[email protected]", "https://a.example;", "https://a.example; frame-ancestors *",
+ "https://*", "javascript:alert(1)", "*.127.0.0.1", "https://a.example/../",
+ } {
+ if _, err := NormalizePattern(raw); err == nil {
+ t.Errorf("accepted %q", raw)
+ }
+ }
+}
+
+func TestFrameAncestors(t *testing.T) {
+ for _, tc := range []struct {
+ patterns []string
+ want string
+ }{
+ {nil, "frame-ancestors 'none'"},
+ {[]string{" ", "https://a.example;"}, "frame-ancestors 'none'"},
+ {[]string{"https://A.example:443/"}, "frame-ancestors 'self' https://a.example"},
+ {[]string{"*.example.com"}, "frame-ancestors 'self' http://*.example.com:* https://*.example.com:*"},
+ {[]string{"*.example.com:8443"}, "frame-ancestors 'self' http://*.example.com:8443 https://*.example.com:8443"},
+ {[]string{"*"}, "frame-ancestors *"},
+ } {
+ if got := FrameAncestors(tc.patterns); got != tc.want {
+ t.Errorf("%v: got %q want %q", tc.patterns, got, tc.want)
+ }
+ }
+}
diff --git a/internal/handler/embed_allowed_origins_test.go b/internal/handler/embed_allowed_origins_test.go
new file mode 100644
index 000000000..f93cdba6b
--- /dev/null
+++ b/internal/handler/embed_allowed_origins_test.go
@@ -0,0 +1,30 @@
+package handler
+
+import "testing"
+
+func TestValidateEmbedAllowedOrigins(t *testing.T) {
+ t.Setenv("GIN_MODE", "release")
+ for _, tc := range []struct {
+ origins []string
+ valid bool
+ }{
+ {nil, false},
+ {[]string{" "}, false},
+ {[]string{"*"}, false},
+ {[]string{"https://a.example"}, true},
+ {[]string{"https://a.example/"}, true},
+ {[]string{"*.example.com:8443"}, true},
+ {[]string{"https://a.example/path"}, false},
+ {[]string{"https://a.example?"}, false},
+ {[]string{"https://[email protected]"}, false},
+ {[]string{"https://a.example; frame-ancestors *"}, false},
+ } {
+ if err := validateAllowedOrigins(tc.origins); (err == nil) != tc.valid {
+ t.Errorf("%v: %v", tc.origins, err)
+ }
+ }
+ t.Setenv("GIN_MODE", "debug")
+ if err := validateAllowedOrigins([]string{"*"}); err != nil {
+ t.Fatal(err)
+ }
+}
diff --git a/internal/handler/embed_channel.go b/internal/handler/embed_channel.go
index b7579e973..1494b20f4 100644
--- a/internal/handler/embed_channel.go
+++ b/internal/handler/embed_channel.go
@@ -7,12 +7,12 @@ import (
"fmt"
"io"
"net/http"
- "net/url"
"os"
"strconv"
"strings"
"github.com/Tencent/WeKnora/internal/application/service"
+ "github.com/Tencent/WeKnora/internal/embedpolicy"
apperrors "github.com/Tencent/WeKnora/internal/errors"
"github.com/Tencent/WeKnora/internal/handler/session"
"github.com/Tencent/WeKnora/internal/logger"
@@ -91,38 +91,27 @@ func stringOrEmpty(v *string) string {
return *v
}
-// validateAllowedOrigins enforces that a public embed channel declares an
-// explicit origin allowlist. An empty list means "allow any origin" in the
-// auth middleware, which is unsafe for a publicly reachable widget, so it is
-// rejected. In production a wildcard ("*") is also rejected; each entry must be
-// a well-formed http(s) origin (optionally a "*." subdomain wildcard).
+// validateAllowedOrigins validates host-page origins before using them in CSP.
func validateAllowedOrigins(origins []string) error {
- cleaned := make([]string, 0, len(origins))
- for _, o := range origins {
- o = strings.TrimSpace(o)
- if o == "" {
- continue
- }
- cleaned = append(cleaned, o)
- }
- if len(cleaned) == 0 {
+ if len(origins) == 0 {
return fmt.Errorf("at least one allowed origin is required")
}
- for _, o := range cleaned {
- if o == "*" {
- if isProductionMode() {
- return fmt.Errorf("wildcard origin '*' is not allowed in production")
- }
+ count := 0
+ for _, raw := range origins {
+ if strings.TrimSpace(raw) == "" {
continue
}
- host := o
- if strings.HasPrefix(o, "*.") {
- host = "https://" + strings.TrimPrefix(o, "*.")
+ pattern, err := embedpolicy.NormalizePattern(raw)
+ if err != nil {
+ return err
}
- u, err := url.Parse(host)
- if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
- return fmt.Errorf("invalid allowed origin: %q", o)
+ if pattern == "*" && isProductionMode() {
+ return fmt.Errorf("wildcard origin '*' is not allowed in production")
}
+ count++
+ }
+ if count == 0 {
+ return fmt.Errorf("at least one allowed origin is required")
}
return nil
}
diff --git a/internal/middleware/embed_auth.go b/internal/middleware/embed_auth.go
index 9e02193fe..15fa4543e 100644
--- a/internal/middleware/embed_auth.go
+++ b/internal/middleware/embed_auth.go
@@ -11,6 +11,7 @@ import (
"time"
"github.com/Tencent/WeKnora/internal/application/service"
+ "github.com/Tencent/WeKnora/internal/embedpolicy"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/ratelimit"
"github.com/Tencent/WeKnora/internal/types"
@@ -117,7 +118,7 @@ func EmbedAuth(
}
origin := requestOrigin(c)
- if !originAllowed(origin, ch.AllowedOriginsList()) {
+ if !embedRequestOriginAllowed(c, origin, ch.AllowedOriginsList()) {
logger.Warnf(c.Request.Context(), "[embed_auth] origin %q not allowed for channel %s", origin, channelID)
c.JSON(http.StatusForbidden, gin.H{"error": "origin not allowed"})
c.Abort()
@@ -203,31 +204,40 @@ func requestOrigin(c *gin.Context) string {
return u.Scheme + "://" + u.Host
}
-func originAllowed(origin string, allowed []string) bool {
- // Empty allowlist rejects all origins. Management create/update requires at
- // least one origin; legacy rows with [] must be fixed before going live.
- if len(allowed) == 0 {
+// API calls execute inside the embed document, so their browser origin is the
+// embed server, not its parent. Parent restrictions belong to the HTML CSP.
+// Cross-origin API clients and server-side exchanges still use the allowlist.
+func embedRequestOriginAllowed(c *gin.Context, origin string, allowed []string) bool {
+ if embedpolicy.FrameAncestors(allowed) == "frame-ancestors 'none'" {
return false
}
- if origin == "" {
+ normalized, originErr := embedpolicy.NormalizeOrigin(origin)
+ // Fetch Metadata is browser-controlled and survives reverse-proxy host/port
+ // rewriting. Non-browser callers can forge it, just as they can forge Origin;
+ // neither replaces the channel token or the rate limits.
+ // A same-origin GET may omit both Origin and Referer under no-referrer.
+ if c.GetHeader("Sec-Fetch-Site") == "same-origin" && (origin == "" || originErr == nil) {
+ return true
+ }
+ if originErr != nil {
return false
}
- for _, pattern := range allowed {
- pattern = strings.TrimSpace(pattern)
- if pattern == "" {
- continue
- }
- if pattern == "*" || strings.EqualFold(pattern, origin) {
+ // HTTP deployments and older webviews may omit Fetch Metadata. Compare with
+ // the transport origin; the frontend proxy preserves Host including its port.
+ scheme := "http"
+ if c.Request.TLS != nil || c.GetHeader("X-Forwarded-Proto") == "https" {
+ scheme = "https"
+ }
+ if expected, err := embedpolicy.NormalizeOrigin(scheme + "://" + c.Request.Host); err == nil {
+ if normalized == expected {
return true
}
- if strings.HasPrefix(pattern, "*.") {
- suffix := strings.TrimPrefix(pattern, "*")
- if strings.HasSuffix(origin, suffix) {
- return true
- }
- }
}
- return false
+ return originAllowed(origin, allowed)
+}
+
+func originAllowed(origin string, allowed []string) bool {
+ return embedpolicy.Allows(origin, allowed)
}
// EmbedChannelFromContext returns the authenticated embed channel, if any.
diff --git a/internal/middleware/embed_auth_test.go b/internal/middleware/embed_auth_test.go
index afb853af2..ee8ce758c 100644
--- a/internal/middleware/embed_auth_test.go
+++ b/internal/middleware/embed_auth_test.go
@@ -398,3 +398,155 @@ func TestEmbedAuthSessionTokenMismatch(t *testing.T) {
t.Fatalf("status = %d, want %d, body = %s", w.Code, http.StatusUnauthorized, w.Body.String())
}
}
+
+// The host allowlist contains A; browser API requests originate in iframe B.
+func TestEmbedAuthHostAllowlist(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ for _, tc := range []struct {
+ name, method, target, origin, referer, fetchSite, forwardedProto string
+ sessionToken, emptyList bool
+ want int
+ }{
+ {
+ name: "iframe POST with only A allowed",
+ method: "POST",
+ target: "https://b.example/api",
+ origin: "https://b.example",
+ fetchSite: "same-origin",
+ want: 200,
+ },
+ {
+ name: "iframe GET referer fallback",
+ method: "GET",
+ target: "https://b.example/api",
+ referer: "https://b.example/embed/channel",
+ fetchSite: "same-origin",
+ want: 200,
+ },
+ {
+ name: "secure mode session token",
+ method: "POST",
+ target: "https://b.example/api",
+ origin: "https://b.example",
+ fetchSite: "same-origin",
+ sessionToken: true,
+ want: 200,
+ },
+ {
+ name: "HTTP custom port without fetch metadata",
+ method: "POST",
+ target: "http://b.example:8080/api",
+ origin: "http://b.example:8080",
+ want: 200,
+ },
+ {
+ name: "HTTPS proxy without fetch metadata",
+ method: "POST",
+ target: "http://b.example/api",
+ origin: "https://b.example",
+ forwardedProto: "https",
+ want: 200,
+ },
+ {
+ name: "proxy rewrites authority",
+ method: "POST",
+ target: "http://backend:8080/api",
+ origin: "https://b.example",
+ fetchSite: "same-origin",
+ want: 200,
+ },
+ {
+ name: "server exchange from allowed A",
+ method: "POST",
+ target: "https://b.example/api",
+ origin: "https://a.example",
+ want: 200,
+ },
+ {
+ name: "cross origin C rejected",
+ method: "POST",
+ target: "https://b.example/api",
+ origin: "https://c.example",
+ fetchSite: "cross-site",
+ want: 403,
+ },
+ {
+ name: "same site C rejected",
+ method: "POST",
+ target: "https://b.example/api",
+ origin: "https://c.example",
+ fetchSite: "same-site",
+ want: 403,
+ },
+ {
+ name: "wrong port rejected",
+ method: "POST",
+ target: "http://b.example:8080/api",
+ origin: "http://b.example:9090",
+ want: 403,
+ },
+ {
+ name: "opaque origin rejected",
+ method: "POST",
+ target: "https://b.example/api",
+ origin: "null",
+ fetchSite: "same-origin",
+ want: 403,
+ },
+ {
+ name: "no-referrer iframe GET",
+ method: "GET",
+ target: "https://b.example/api",
+ fetchSite: "same-origin",
+ want: 200,
+ },
+ {
+ name: "missing origin rejected",
+ method: "GET",
+ target: "https://b.example/api",
+ want: 403,
+ },
+ {
+ name: "empty allowlist still rejected",
+ method: "POST",
+ target: "https://b.example/api",
+ origin: "https://b.example",
+ fetchSite: "same-origin",
+ emptyList: true,
+ want: 403,
+ },
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ origins := []byte(`["https://a.example"]`)
+ if tc.emptyList {
+ origins = []byte(`[]`)
+ }
+ svc := &fakeEmbedChannelService{channels: map[string]*types.EmbedChannel{
+ "channel": {
+ ID: "channel", TenantID: 11, Enabled: true, PublishToken: "em_test", AllowedOrigins: origins,
+ },
+ }, sessions: map[string]string{"ems_test": "channel"}}
+ r := gin.New()
+ tenantSvc := &fakeTenantService{tenant: &types.Tenant{ID: 11}}
+ r.Any("/api/v1/embed/:channel_id/config", EmbedAuth(svc, tenantSvc, nil), func(c *gin.Context) {
+ c.Status(200)
+ })
+ req := httptest.NewRequest(tc.method, tc.target, nil)
+ req.URL.Path = "/api/v1/embed/channel/config"
+ token := "em_test"
+ if tc.sessionToken {
+ token = "ems_test"
+ }
+ req.Header.Set("Authorization", "Embed "+token)
+ req.Header.Set("Origin", tc.origin)
+ req.Header.Set("Referer", tc.referer)
+ req.Header.Set("Sec-Fetch-Site", tc.fetchSite)
+ req.Header.Set("X-Forwarded-Proto", tc.forwardedProto)
+ w := httptest.NewRecorder()
+ r.ServeHTTP(w, req)
+ if w.Code != tc.want {
+ t.Fatalf("status = %d want %d: %s", w.Code, tc.want, w.Body.String())
+ }
+ })
+ }
+}
diff --git a/internal/router/embed_frame_policy_test.go b/internal/router/embed_frame_policy_test.go
new file mode 100644
index 000000000..f6af2cd18
--- /dev/null
+++ b/internal/router/embed_frame_policy_test.go
@@ -0,0 +1,95 @@
+package router
+
+import (
+ "context"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/Tencent/WeKnora/internal/types/interfaces"
+ "github.com/gin-gonic/gin"
+ "github.com/stretchr/testify/require"
+)
+
+type framePolicyService struct{ interfaces.EmbedChannelService }
+
+func (framePolicyService) LookupEnabledChannel(_ context.Context, id string) (*types.EmbedChannel, error) {
+ switch id {
+ case "active":
+ return &types.EmbedChannel{AllowedOrigins: []byte(`["https://a.example"]`)}, nil
+ case "empty":
+ return &types.EmbedChannel{AllowedOrigins: []byte(`[]`)}, nil
+ case "invalid":
+ return &types.EmbedChannel{AllowedOrigins: []byte(`["https://a.example; frame-ancestors *"]`)}, nil
+ default:
+ return nil, fmt.Errorf("channel unavailable")
+ }
+}
+
+func TestEmbedFramePolicy(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ webDir := t.TempDir()
+ require.NoError(t, os.WriteFile(filepath.Join(webDir, "index.html"), []byte("main SPA"), 0o600))
+ require.NoError(t, os.WriteFile(filepath.Join(webDir, "embed.html"), []byte("embed entry"), 0o600))
+ t.Setenv("WEKNORA_WEB_DIR", webDir)
+ r := gin.New()
+ r.Use(embedFrameAncestorsMiddleware(framePolicyService{}))
+ serveFrontendStatic(r)
+ r.GET("/api/v1/embed-frame-policy", embedFramePolicyHandler(framePolicyService{}))
+ for _, tc := range []struct {
+ path string
+ status int
+ csp string
+ }{
+ {"/embed/active", 200, "frame-ancestors 'self' https://a.example"},
+ {"/embed/active?token=ignored", 200, "frame-ancestors 'self' https://a.example"},
+ {"/embed/empty", 403, "frame-ancestors 'none'"},
+ {"/embed/invalid", 403, "frame-ancestors 'none'"},
+ {"/embed/disabled", 403, "frame-ancestors 'none'"},
+ {"/embed/active%2F..%2Fdisabled", 403, "frame-ancestors 'none'"},
+ {"/embed/active/../disabled", 403, "frame-ancestors 'none'"},
+ {"/embed/active%252F..%252Fdisabled", 403, "frame-ancestors 'none'"},
+ } {
+ t.Run(tc.path, func(t *testing.T) {
+ // Lite returns the dedicated entry, with a fresh CSP on GET and HEAD.
+ for _, method := range []string{http.MethodGet, http.MethodHead} {
+ w := httptest.NewRecorder()
+ r.ServeHTTP(w, httptest.NewRequest(method, tc.path, nil))
+ require.Equal(t, tc.status, w.Code)
+ require.Equal(t, tc.csp, w.Header().Get("Content-Security-Policy"))
+ require.Equal(t, "no-store", w.Header().Get("Cache-Control"))
+ if tc.status == 200 && method == http.MethodGet {
+ require.Equal(t, "embed entry", w.Body.String())
+ }
+ }
+ // Nginx receives the identical policy, without exposing channel config.
+ req := httptest.NewRequest(http.MethodGet, "/api/v1/embed-frame-policy", nil)
+ req.Header.Set("X-Embed-Page-URI", tc.path)
+ w := httptest.NewRecorder()
+ r.ServeHTTP(w, req)
+ want := tc.status
+ if want == 200 {
+ want = 204
+ }
+ require.Equal(t, want, w.Code)
+ require.Equal(t, tc.csp, w.Header().Get("Content-Security-Policy"))
+ require.Empty(t, w.Body.String())
+ })
+ }
+ for _, path := range []string{"/", "/embed.html"} {
+ w := httptest.NewRecorder()
+ r.ServeHTTP(w, httptest.NewRequest(http.MethodGet, path, nil))
+ require.Equal(t, "frame-ancestors 'self'", w.Header().Get("Content-Security-Policy"))
+ }
+ for _, uri := range []string{"", "/", "/embed/", "https://evil.test/embed/active"} {
+ w := httptest.NewRecorder()
+ req := httptest.NewRequest(http.MethodGet, "/api/v1/embed-frame-policy", nil)
+ req.Header.Set("X-Embed-Page-URI", uri)
+ r.ServeHTTP(w, req)
+ require.Equal(t, 403, w.Code, uri)
+ }
+}
diff --git a/internal/router/routes_agent.go b/internal/router/routes_agent.go
index e1157b85c..991d78082 100644
--- a/internal/router/routes_agent.go
+++ b/internal/router/routes_agent.go
@@ -2,11 +2,13 @@ package router
import (
"net/http"
+ "net/url"
"strings"
"github.com/gin-gonic/gin"
"github.com/redis/go-redis/v9"
+ "github.com/Tencent/WeKnora/internal/embedpolicy"
"github.com/Tencent/WeKnora/internal/handler"
"github.com/Tencent/WeKnora/internal/middleware"
"github.com/Tencent/WeKnora/internal/types/interfaces"
@@ -229,6 +231,9 @@ func RegisterEmbedPublicRoutes(
if embedHandler == nil || embedService == nil {
return
}
+ // Nginx uses this read-only subrequest to put the channel CSP on embed.html.
+ // No token is required: framing policy must be available before JS bootstrap.
+ r.GET("/api/v1/embed-frame-policy", embedFramePolicyHandler(embedService))
embed := r.Group("/api/v1/embed/:channel_id", middleware.EmbedAuth(embedService, tenantService, redisClient))
{
embed.POST("/exchange", embedHandler.ExchangeEmbedSession)
@@ -325,56 +330,75 @@ func embedChannelIDFromPath(path string) string {
if !strings.HasPrefix(path, prefix) {
return ""
}
- rest := strings.TrimPrefix(path, prefix)
- if i := strings.IndexByte(rest, '/'); i >= 0 {
- rest = rest[:i]
+ rest := strings.TrimSuffix(strings.TrimPrefix(path, prefix), "/")
+ // Never authorize the first segment of a path that the browser/API can
+ // normalize to a different channel (including encoded slashes or dot paths).
+ if rest == "" || rest == "." || rest == ".." ||
+ strings.TrimSpace(rest) != rest || strings.ContainsAny(rest, "/\\%?#") {
+ return ""
}
- if i := strings.IndexByte(rest, '?'); i >= 0 {
- rest = rest[:i]
+ return rest
+}
+
+// embedFramePolicyHandler serves only framing policy, never channel config.
+func embedFramePolicyHandler(svc interfaces.EmbedChannelService) gin.HandlerFunc {
+ return func(c *gin.Context) {
+ c.Header("Cache-Control", "no-store")
+ c.Header("Content-Security-Policy", "frame-ancestors 'none'")
+ u, err := url.ParseRequestURI(c.GetHeader("X-Embed-Page-URI"))
+ if err != nil || u.IsAbs() || u.Host != "" {
+ c.AbortWithStatus(http.StatusForbidden)
+ return
+ }
+ channelID := embedChannelIDFromPath(u.Path)
+ if channelID == "" {
+ c.AbortWithStatus(http.StatusForbidden)
+ return
+ }
+ ch, err := svc.LookupEnabledChannel(c.Request.Context(), channelID)
+ if err != nil || ch == nil {
+ c.AbortWithStatus(http.StatusForbidden)
+ return
+ }
+ policy := embedpolicy.FrameAncestors(ch.AllowedOriginsList())
+ c.Header("Content-Security-Policy", policy)
+ if policy == "frame-ancestors 'none'" {
+ c.AbortWithStatus(http.StatusForbidden)
+ return
+ }
+ c.Status(http.StatusNoContent)
}
- return strings.TrimSpace(rest)
}
-// embedFrameAncestorsMiddleware sets a per-channel `frame-ancestors` CSP on the
-// embed SPA page so it can only be framed by the channel's allowed origins.
-// When the channel declares no origins (or "*"), no restriction is applied,
-// matching the API allowlist semantics. Only GET/HEAD page loads are handled.
+// embedFrameAncestorsMiddleware applies the same policy to Lite's HTML response.
func embedFrameAncestorsMiddleware(svc interfaces.EmbedChannelService) gin.HandlerFunc {
return func(c *gin.Context) {
if c.Request.Method != http.MethodGet && c.Request.Method != http.MethodHead {
c.Next()
return
}
+ if !strings.HasPrefix(c.Request.URL.Path, "/embed/") {
+ c.Next()
+ return
+ }
+ c.Header("Cache-Control", "no-store")
+ c.Header("Content-Security-Policy", "frame-ancestors 'none'")
channelID := embedChannelIDFromPath(c.Request.URL.Path)
if channelID == "" {
- c.Next()
+ c.AbortWithStatus(http.StatusForbidden)
return
}
ch, err := svc.LookupEnabledChannel(c.Request.Context(), channelID)
if err != nil || ch == nil {
- c.Next()
+ c.AbortWithStatus(http.StatusForbidden)
return
}
- origins := ch.AllowedOriginsList()
- sources := make([]string, 0, len(origins))
- wildcard := false
- for _, o := range origins {
- o = strings.TrimSpace(o)
- if o == "" {
- continue
- }
- if o == "*" {
- wildcard = true
- break
- }
- sources = append(sources, o)
- }
- // No explicit origins or a wildcard => do not constrain framing here.
- if wildcard || len(sources) == 0 {
- c.Next()
+ policy := embedpolicy.FrameAncestors(ch.AllowedOriginsList())
+ c.Header("Content-Security-Policy", policy)
+ if policy == "frame-ancestors 'none'" {
+ c.AbortWithStatus(http.StatusForbidden)
return
}
- c.Header("Content-Security-Policy", "frame-ancestors "+strings.Join(sources, " "))
c.Next()
}
}
diff --git a/internal/router/static.go b/internal/router/static.go
index 0f496a219..2acb63f08 100644
--- a/internal/router/static.go
+++ b/internal/router/static.go
@@ -42,6 +42,15 @@ func serveFrontendStatic(r *gin.Engine) {
c.Next()
return
}
+ // Embed pages need the dedicated entry point and the channel CSP set by
+ // embedFrameAncestorsMiddleware. Keep the main SPA same-origin only.
+ if strings.HasPrefix(path, "/embed/") {
+ c.File(filepath.Join(absDir, "embed.html"))
+ c.Abort()
+ return
+ }
+ c.Header("X-Frame-Options", "SAMEORIGIN")
+ c.Header("Content-Security-Policy", "frame-ancestors 'self'")
fullPath := filepath.Join(absDir, path)
if info, err := os.Stat(fullPath); err == nil && !info.IsDir() {
setFrontendCacheHeaders(c.Writer, path)
diff --git a/scripts/test_embed_nginx.py b/scripts/test_embed_nginx.py
new file mode 100644
index 000000000..efa2b364f
--- /dev/null
+++ b/scripts/test_embed_nginx.py
@@ -0,0 +1,112 @@
+#!/usr/bin/env python3
+"""Exercise the production embed Nginx locations with a policy backend fixture.
+
+Requires Docker. Run: python3 scripts/test_embed_nginx.py [nginx-or-ui-image]
+"""
+import json
+import subprocess
+import sys
+import tempfile
+import time
+import urllib.error
+import urllib.request
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[1]
+IMAGE = sys.argv[1] if len(sys.argv) > 1 else "nginx:alpine"
+
+
+def docker(*args):
+ return subprocess.check_output(["docker", *args], text=True).strip()
+
+
+def check():
+ with tempfile.TemporaryDirectory(prefix="weknora-embed-nginx-") as folder:
+ work = Path(folder)
+ (work / "web").mkdir()
+ (work / "web/embed.html").write_text("embed entry")
+ (work / "web/index.html").write_text("main SPA")
+ (work / "web/50x.html").write_text("backend unavailable")
+ config = (ROOT / "frontend/nginx.conf").read_text()
+ for key, value in {
+ "APP_SCHEME": "http", "APP_HOST": "127.0.0.1", "APP_PORT": "18081",
+ "MAX_FILE_SIZE": "50m", "MAX_SKILL_BUNDLE_SIZE": "100m",
+ }.items():
+ config = config.replace("${" + key + "}", value)
+ config = config.replace("/usr/share/nginx/html", "/check/web")
+ config = config.replace("/etc/nginx/api-proxy.conf", "/check/api-proxy.conf")
+ (work / "api-proxy.conf").write_text((ROOT / "frontend/nginx-api-proxy.conf").read_text())
+ # The real policy handler and token middleware are covered by Go tests.
+ # Here vary its responses to verify subrequests, fallback and fail-closed serving.
+ fixture = """
+ server {
+ listen 18081;
+ location = /api/v1/embed-frame-policy {
+ set $policy "frame-ancestors 'none'";
+ if ($http_x_embed_page_uri ~ "^/embed/active(?:[?]|$)") {
+ set $policy "frame-ancestors 'self' https://a.example";
+ }
+ add_header Content-Security-Policy $policy always;
+ if ($http_x_embed_page_uri = "/embed/unavailable") { return 500; }
+ if ($policy = "frame-ancestors 'none'") { return 403; }
+ return 204;
+ }
+ location /api/ { return 200 "$http_host"; }
+ }
+ """
+ (work / "nginx.conf").write_text(
+ "events {}\nhttp {\n" + (ROOT / "frontend/nginx-http.conf").read_text() + config + fixture + "\n}"
+ )
+ # The Nginx worker runs as an unprivileged user in the container.
+ work.chmod(0o755)
+ cid = docker("create", "-p", "127.0.0.1::80",
+ "--entrypoint", "nginx", IMAGE, "-c", "/check/nginx.conf", "-g", "daemon off;")
+ try:
+ docker("cp", str(work), cid + ":/check")
+ docker("start", cid)
+ info = json.loads(docker("inspect", cid))[0]
+ port = info["NetworkSettings"]["Ports"]["80/tcp"][0]["HostPort"]
+ base = f"http://127.0.0.1:{port}"
+
+ def request(path, method="GET"):
+ req = urllib.request.Request(base + path, method=method)
+ try:
+ return urllib.request.urlopen(req, timeout=3)
+ except urllib.error.HTTPError as error:
+ return error
+
+ for attempt in range(30):
+ try:
+ with request("/") as response:
+ assert response.status == 200
+ break
+ except (urllib.error.URLError, ConnectionError):
+ if attempt == 29:
+ raise
+ time.sleep(0.1)
+ for method in ("GET", "HEAD"):
+ for path in ("/embed/active", "/embed/active?token=ignored"):
+ with request(path, method) as response:
+ assert response.status == 200, (path, response.status)
+ assert response.headers["Content-Security-Policy"] == "frame-ancestors 'self' https://a.example"
+ assert response.headers["Cache-Control"] == "no-store"
+ assert "X-Frame-Options" not in response.headers
+ assert response.read() == (b"embed entry" if method == "GET" else b"")
+ for path, status in (("/embed/disabled", 403), ("/embed/empty", 403),
+ ("/embed/unavailable", 500), ("/_embed-frame-policy", 404),
+ ("/embed.html", 404)):
+ with request(path) as response:
+ assert response.status == status, (path, response.status)
+ assert b"embed entry" not in response.read()
+ with request("/api/probe") as response:
+ assert response.read().decode() == f"127.0.0.1:{port}", "proxy lost public port"
+ print("Embed Nginx integration checks passed")
+ except Exception:
+ print(docker("logs", cid), file=sys.stderr)
+ raise
+ finally:
+ docker("rm", "-f", cid)
+
+
+if __name__ == "__main__":
+ check()
diff --git a/website-docs/03-features/13-embed-channel.md b/website-docs/03-features/13-embed-channel.md
index a62013f78..b295a0287 100644
--- a/website-docs/03-features/13-embed-channel.md
+++ b/website-docs/03-features/13-embed-channel.md
@@ -99,12 +99,18 @@ publish token 只保存在业务后端,页面通过 `data-token-endpoint` 指
1. 按 `channel_id` 查渠道,校验 token 与 `publish_token` 匹配,或在 Redis(key `embed:session:{token}`)中查到 session token 归属该渠道;
2. 校验渠道 `enabled`;
-3. 校验请求 `Origin` 命中 `allowed_origins`(空列表拒绝一切;`*` 仅开发模式;`*.example.com` 后缀通配;其余精确匹配、大小写不敏感);
+3. 允许 iframe 内的同源 API 请求;跨源 API 请求及安全模式服务端 exchange 的 `Origin` 需命中 `allowed_origins`。空白名单仍拒绝一切;宿主限制由嵌入 HTML 的 CSP 执行;
4. 限流(Redis Lua 脚本,滑动窗口):
- 单 IP 每分钟 ≤ `RateLimitPerMinute`;
- 渠道全局每分钟 ≤ `max(RateLimitPerMinute × 20, 120)`——防止攻击者轮换 IP 绕过单 IP 限流;
- 渠道每日总量 ≤ `RateLimitPerDay`。
+### 宿主来源与部署
+
+A 网站嵌入 B 的 WeKnora 时,白名单填 A。标准 Nginx 使用 `/api/v1/embed-frame-policy` 获取渠道策略(无需 token,仅返回 CSP,不返回渠道配置),并在 `/embed/:channelId` 的 HTML 响应中设置 `frame-ancestors`;Lite 使用同一策略。该页面不缓存,策略获取失败时不返回嵌入 HTML。
+
+升级时,过去仅填 B 的渠道需改填实际宿主 A,并同时更新前后端。自定义反向代理需保留 CSP、原始 Host(含端口)、协议及 `Sec-Fetch-Site`;详见 [embed-subdomain.md](../../docs/embed-subdomain.md)。白名单限制浏览器嵌入,不能代替访客认证或阻止持有 token 的非浏览器客户端;此类访问控制使用安全模式和限流。
+
### Token 交换(安全模式核心)
`POST /api/v1/embed/:channel_id/exchange`,请求头 `Authorization: Embed em_xxx`(**只接受 publish token**,session token 会被拒绝)。响应:
@@ -185,7 +191,7 @@ type EmbedChannel struct {
| `name` | string | — | 渠道显示名称 |
| `enabled` | bool | `true` | 渠道开关,关闭后所有公开接口拒绝访问 |
| `agent_id` | string | `builtin-quick-answer` | 绑定的 Agent,决定知识库范围与对话能力 |
-| `allowed_origins` | string[] | — | **必填至少一项**。支持三种形式:完整 `http(s)://` Origin、子域名通配 `*.example.com`、全通配 `*`(仅开发模式允许,生产环境拒绝) |
+| `allowed_origins` | string[] | — | **必填至少一项,填写嵌入宿主 A,不是 WeKnora 地址 B**。支持三种形式:完整 `http(s)://` Origin、子域名通配 `*.example.com`、全通配 `*`(仅开发模式允许,生产环境拒绝) |
| `welcome_message` | string | 空 | 打开挂件时的欢迎语 |
| `rate_limit_per_minute` | int | `30` | 单 IP 每分钟请求上限 |
| `rate_limit_per_day` | int | `10000` | 渠道级每日请求总量上限 |
@@ -284,7 +290,7 @@ sequenceDiagram
### 安全要点小结
-- **Origin 白名单**:`allowed_origins` 为空时拒绝所有请求;`*` 通配仅开发模式可用;支持 `*.example.com` 子域名通配。
+- **宿主白名单**:嵌入 HTML 设置渠道级 `CSP frame-ancestors`,限制所有祖先页面;iframe 内同源 API 正常放行。`allowed_origins` 为空时拒绝所有请求;`*` 仅开发模式可用;支持 `*.example.com` 子域名通配。同源管理端预览允许。
- **双 token 体系**:安全模式下 publish token 不出服务端,浏览器只持有 30 分钟短效 `ems_` token。
- **会话签名**:`X-Embed-Session` HMAC 签名把会话绑定到(渠道、会话、当前 publish token)三元组,轮换 token 即可全量吊销。
- **三层限流**:单 IP/分钟、渠道/分钟(20 倍单 IP、下限 120)、渠道/天,Redis Lua 原子实现。