Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
feat(confluence): support personal access token authentication (#4549)
Jarvis0c3c7c5cc8bd
diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.tsindex 2ca86854a..70c2c3877 100755--- a/frontend/src/i18n/locales/en-US.ts+++ b/frontend/src/i18n/locales/en-US.ts@@ -7877,6 +7877,8 @@ export default {confluenceEditionCloud: 'Cloud',confluenceBaseUrl: 'Confluence URL',confluenceUsername: 'Username or email',+ confluencePat: 'Server/DC personal access token (PAT)',+ confluencePatHint: 'Optional. When provided, uses Bearer authentication; username and password are not required.',confluencePassword: 'Server/DC password',confluenceApiToken: 'Cloud API token',imaClientId: 'IMA ClientID',diff --git a/frontend/src/i18n/locales/ja-JP.ts b/frontend/src/i18n/locales/ja-JP.tsindex a3d5ed280..5ff715141 100644--- a/frontend/src/i18n/locales/ja-JP.ts+++ b/frontend/src/i18n/locales/ja-JP.ts@@ -7877,6 +7877,8 @@ export default {confluenceEditionCloud: 'Cloud',confluenceBaseUrl: 'Confluence URL',confluenceUsername: 'ユーザー名またはメールアドレス',+ confluencePat: 'Server/DC 個人アクセストークン(PAT)',+ confluencePatHint: '任意。指定すると Bearer 認証を使用し、ユーザー名とパスワードは不要です。',confluencePassword: 'Server/DC パスワード',confluenceApiToken: 'Cloud API トークン',imaClientId: 'IMA ClientID',diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.tsindex 1873a86a5..13faf00e3 100755--- a/frontend/src/i18n/locales/ko-KR.ts+++ b/frontend/src/i18n/locales/ko-KR.ts@@ -1352,6 +1352,8 @@ export default {confluenceEditionCloud: 'Cloud',confluenceBaseUrl: 'Confluence URL',confluenceUsername: '사용자 이름 또는 이메일',+ confluencePat: 'Server/DC 개인 액세스 토큰(PAT)',+ confluencePatHint: '선택 사항입니다. 입력하면 Bearer 인증을 사용하며 사용자 이름과 비밀번호가 필요하지 않습니다.',confluencePassword: 'Server/DC 비밀번호',confluenceApiToken: 'Cloud API 토큰',clientId: 'Client ID',diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.tsindex 0a932e510..fd88fa57e 100755--- a/frontend/src/i18n/locales/ru-RU.ts+++ b/frontend/src/i18n/locales/ru-RU.ts@@ -1352,6 +1352,8 @@ export default {confluenceEditionCloud: 'Cloud',confluenceBaseUrl: 'URL Confluence',confluenceUsername: 'Имя пользователя или эл. почта',+ confluencePat: 'Персональный токен Server/DC (PAT)',+ confluencePatHint: 'Необязательно. При указании используется Bearer-аутентификация; имя пользователя и пароль не требуются.',confluencePassword: 'Пароль Server/DC',confluenceApiToken: 'API-токен Cloud',clientId: 'Client ID',diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.tsindex 1a9af0592..8a0cbf179 100755--- a/frontend/src/i18n/locales/zh-CN.ts+++ b/frontend/src/i18n/locales/zh-CN.ts@@ -1354,6 +1354,8 @@ export default {confluenceEditionCloud: 'Cloud',confluenceBaseUrl: 'Confluence 地址',confluenceUsername: '用户名或邮箱',+ confluencePat: 'Server/DC 个人访问令牌(PAT)',+ confluencePatHint: '选填。填写后使用 Bearer 认证,无需用户名和密码。',confluencePassword: 'Server/DC 密码',confluenceApiToken: 'Cloud API 令牌',clientId: 'Client ID',diff --git a/frontend/src/i18n/locales/zh-TW.ts b/frontend/src/i18n/locales/zh-TW.tsindex 26ea1a82d..1c7c72507 100644--- a/frontend/src/i18n/locales/zh-TW.ts+++ b/frontend/src/i18n/locales/zh-TW.ts@@ -1354,6 +1354,8 @@ export default {confluenceEditionCloud: 'Cloud',confluenceBaseUrl: 'Confluence 地址',confluenceUsername: '使用者名或電子信箱',+ confluencePat: 'Server/DC 個人存取權杖(PAT)',+ confluencePatHint: '選填。填寫後使用 Bearer 驗證,無需使用者名稱和密碼。',confluencePassword: 'Server/DC 密碼',confluenceApiToken: 'Cloud API 權杖',clientId: 'Client ID',diff --git a/frontend/src/views/knowledge/settings/DataSourceEditorDialog.test.ts b/frontend/src/views/knowledge/settings/DataSourceEditorDialog.test.tsindex 9028866e5..138bbd820 100644--- a/frontend/src/views/knowledge/settings/DataSourceEditorDialog.test.ts+++ b/frontend/src/views/knowledge/settings/DataSourceEditorDialog.test.ts@@ -45,7 +45,7 @@ async function fixture({const api = {async validateCredentials(type: string, credentials: Record<string, string>) {calls.push({ method: 'validateCredentials', args: [type, { ...credentials }] })- if (credentials.access_token !== 'rotated-token') throw new Error('gitlab API /user: status 401')+ if (type !== 'confluence' && credentials.access_token !== 'rotated-token') throw new Error('gitlab API /user: status 401')},async validateConnection(id: string) {calls.push({ method: 'validateConnection', args: [id] })@@ -435,3 +435,61 @@ test('new Feishu sources keep the blocks default and do not leak it to another cassert.equal(f.vm.form.config.settings.parse_mode, undefined)} finally { f.close() }})+++test('Confluence PAT permits connection testing and saving without Basic credentials', async () => {+ const f = await fixture({ create: true, configured: false, settings: {} })+ try {+ f.vm.selectType(f.vm.connectorDefs.find((def: any) => def.type === 'confluence'))+ f.vm.form.config.credentials = { edition: 'server', base_url: 'https://confluence.test/wiki', token: 'pat-value' }+ await nextTick()+ const fields = f.vm.displayedCredentialFields+ assert.equal(fields.find((field: any) => field.key === 'token').secret, true)+ assert.equal(fields.find((field: any) => field.key === 'username').optional, true)+ assert.equal(fields.find((field: any) => field.key === 'password').optional, true)+ assert.equal(fields.some((field: any) => field.key === 'api_token'), false)+ await f.vm.testConnection()+ assert.equal(f.vm.testResult, 'success')+ assert.equal(f.calls.find(c => c.method === 'validateCredentials')?.args[1].token, 'pat-value')+ await f.vm.loadResources()+ const created = f.calls.find(c => c.method === 'createDataSource')?.args[0]+ assert.equal(created.config.credentials.token, 'pat-value')+ assert.equal(created.config.settings.token, undefined)+ assert.deepEqual(f.warnings, [])+ } finally { f.close() }+})++test('Confluence requires Basic credentials without a PAT and hides PAT in Cloud', async () => {+ const f = await fixture({ type: 'confluence', configured: false, settings: {} })+ try {+ f.vm.form.config.credentials = { edition: 'server', base_url: 'https://confluence.test/wiki', token: ' ' }+ await nextTick()+ assert.equal(f.vm.displayedCredentialFields.find((field: any) => field.key === 'username').optional, false)+ assert.equal(f.vm.displayedCredentialFields.find((field: any) => field.key === 'password').optional, false)+ await f.vm.testConnection()+ assert.equal(f.calls.some(c => c.method === 'validateCredentials'), false)+ f.vm.form.config.credentials.edition = 'cloud'+ f.vm.form.config.credentials.token = 'stale-server-token'+ await nextTick()+ assert.deepEqual(Array.from(f.vm.displayedCredentialFields, (field: any) => field.key), ['base_url', 'username', 'api_token'])+ assert.equal(f.vm.displayedCredentialFields.find((field: any) => field.key === 'username').optional, false)+ } finally { f.close() }+})+++test('Confluence PAT replacement uses the credentials subresource and keeps the token out of settings', async () => {+ const f = await fixture({ type: 'confluence', settings: { edition: 'server', base_url: 'https://confluence.test/wiki' } })+ try {+ f.vm.enterReplaceCredentials()+ f.vm.form.config.credentials.token = 'replacement-pat'+ await nextTick()+ await f.vm.testConnection()+ assert.equal(f.vm.testResult, 'success')+ await f.vm.handleSubmit()+ const replacement = f.calls.find(c => c.method === 'putDataSourceCredentials')+ assert.equal(replacement?.args[1].token, 'replacement-pat')+ const update = f.calls.find(c => c.method === 'updateDataSource')?.args[1]+ assert.deepEqual(update.config.credentials, {})+ assert.equal(update.config.settings.token, undefined)+ } finally { f.close() }+})diff --git a/frontend/src/views/knowledge/settings/DataSourceEditorDialog.vue b/frontend/src/views/knowledge/settings/DataSourceEditorDialog.vueindex 8be7b6555..94d9409d0 100644--- a/frontend/src/views/knowledge/settings/DataSourceEditorDialog.vue+++ b/frontend/src/views/knowledge/settings/DataSourceEditorDialog.vue@@ -698,6 +698,7 @@ const connectorDefs = computed<ConnectorDef[]>(() => [fields: [{ key: 'base_url', labelKey: 'datasource.field.confluenceBaseUrl', placeholder: 'https://confluence.example.com or https://team.atlassian.net/wiki' },{ key: 'username', labelKey: 'datasource.field.confluenceUsername', placeholder: 'name or email' },+ { key: 'token', labelKey: 'datasource.field.confluencePat', placeholder: 'Server/DC PAT', secret: true, optional: true, hintKey: 'datasource.field.confluencePatHint' },{ key: 'password', labelKey: 'datasource.field.confluencePassword', placeholder: 'Server/DC password', secret: true },{ key: 'api_token', labelKey: 'datasource.field.confluenceApiToken', placeholder: 'Cloud API token', secret: true },],@@ -785,9 +786,16 @@ const displayedCredentialFields = computed(() => {if (form.value.type !== "confluence") return fieldsreturn fields.filter((field) => {- if (field.key === "password") return form.value.config.credentials.edition !== "cloud"+ if (field.key === "password" || field.key === "token") return form.value.config.credentials.edition !== "cloud"if (field.key === "api_token") return form.value.config.credentials.edition === "cloud"return true+ }).map((field) => {+ const hasPAT = form.value.config.credentials.edition !== "cloud" &&+ !!String(form.value.config.credentials.token || "").trim()+ if (field.key === "username" || field.key === "password") {+ return { ...field, optional: hasPAT }+ }+ return field})})diff --git a/internal/datasource/connector/confluence/client.go b/internal/datasource/connector/confluence/client.goindex 66fa29ab4..161d1b671 100644--- a/internal/datasource/connector/confluence/client.go+++ b/internal/datasource/connector/confluence/client.go@@ -67,6 +67,15 @@ func newClient(cfg config) (*client, error) {return &client{cfg: cfg, http: datasource.NewConnectorHTTPClient(60 * time.Second)}, nil}+// authenticate applies the selected credentials to both API and private image requests.+func (c *client) authenticate(req *http.Request) {+ if c.cfg.usePAT {+ req.Header.Set("Authorization", "Bearer "+c.cfg.secret)+ return+ }+ req.SetBasicAuth(c.cfg.username, c.cfg.secret)+}+func (c *client) get(ctx context.Context, endpoint string, output interface{}) error {fullURL, err := c.resolveEndpoint(endpoint)if err != nil {@@ -77,7 +86,7 @@ func (c *client) get(ctx context.Context, endpoint string, output interface{}) eif err != nil {return err}- req.SetBasicAuth(c.cfg.username, c.cfg.secret)+ c.authenticate(req)req.Header.Set("Accept", "application/json")resp, err := c.http.Do(req)if err == nil {@@ -278,7 +287,7 @@ func (c *client) downloadImage(ctx context.Context, absURL string) ([]byte, striif err != nil {return nil, "", err}- req.SetBasicAuth(c.cfg.username, c.cfg.secret)+ c.authenticate(req)req.Header.Set("Accept", "image/*,*/*;q=0.8")resp, err := c.imageHTTPClient().Do(req)if err != nil {diff --git a/internal/datasource/connector/confluence/connector.go b/internal/datasource/connector/confluence/connector.goindex 083d5bf13..0bf20cf51 100644--- a/internal/datasource/connector/confluence/connector.go+++ b/internal/datasource/connector/confluence/connector.go@@ -80,7 +80,8 @@ func (c *Connector) pickerSpaces(ctx context.Context, client *client, cfg config// never becomes a map key retained in process memory or appears in diagnostics.func pickerSpaceCacheKey(cfg config) string {fingerprint := sha256.Sum256([]byte(cfg.secret))- return cfg.edition + "\x00" + cfg.baseURL + "\x00" + cfg.username + "\x00" + fmt.Sprintf("%x", fingerprint)+ return cfg.edition + "\x00" + cfg.baseURL + "\x00" + cfg.username + "\x00" ++ fmt.Sprintf("%t:%x", cfg.usePAT, fingerprint)}// Type returns the connector type identifier.diff --git a/internal/datasource/connector/confluence/pat_test.go b/internal/datasource/connector/confluence/pat_test.gonew file mode 100644index 000000000..81ff635f4--- /dev/null+++ b/internal/datasource/connector/confluence/pat_test.go@@ -0,0 +1,196 @@+package confluence++import (+ "context"+ "encoding/base64"+ "errors"+ "net/http"+ "strings"+ "testing"++ "github.com/Tencent/WeKnora/internal/datasource"+ "github.com/Tencent/WeKnora/internal/types"+)++func TestPATAuthentication(t *testing.T) {+ for _, tc := range []struct {+ name string+ credentials map[string]interface{}+ want string+ invalid bool+ }{+ {+ name: "PAT without username",+ credentials: map[string]interface{}{+ "token": " pat-value ",+ },+ want: "Bearer pat-value",+ },+ {+ name: "PAT overrides password",+ credentials: map[string]interface{}{+ "username": "reader",+ "password": "password",+ "token": "pat-value",+ },+ want: "Bearer pat-value",+ },+ {+ name: "legacy Basic",+ credentials: map[string]interface{}{+ "username": "reader",+ "password": "password",+ },+ want: "Basic " + base64.StdEncoding.EncodeToString([]byte("reader:password")),+ },+ {+ name: "blank PAT falls back to Basic",+ credentials: map[string]interface{}{+ "username": "reader",+ "password": "password",+ "token": " ",+ },+ want: "Basic " + base64.StdEncoding.EncodeToString([]byte("reader:password")),+ },+ {+ name: "Cloud ignores Server PAT",+ credentials: map[string]interface{}{+ "edition": "cloud",+ "username": "reader",+ "api_token": "cloud-token",+ "token": "pat-value",+ },+ want: "Basic " + base64.StdEncoding.EncodeToString([]byte("reader:cloud-token")),+ },+ {+ name: "Cloud still requires username",+ credentials: map[string]interface{}{+ "edition": "cloud",+ "api_token": "cloud-token",+ "token": "pat-value",+ },+ invalid: true,+ },+ {+ name: "Cloud still requires API token",+ credentials: map[string]interface{}{+ "edition": "cloud",+ "username": "reader",+ "token": "pat-value",+ },+ invalid: true,+ },+ {+ name: "Basic still requires username",+ credentials: map[string]interface{}{+ "password": "password",+ },+ invalid: true,+ },+ {+ name: "Basic still requires password",+ credentials: map[string]interface{}{+ "username": "reader",+ },+ invalid: true,+ },+ } {+ t.Run(tc.name, func(t *testing.T) {+ tc.credentials["base_url"] = testBaseURL+ cfg, err := parseConfig(&types.DataSourceConfig{Credentials: tc.credentials})+ if tc.invalid {+ if !errors.Is(err, datasource.ErrInvalidCredentials) {+ t.Fatalf("expected invalid credentials, got %v", err)+ }+ return+ }+ if err != nil {+ t.Fatal(err)+ }+ var calls int+ transport := roundTripper(func(req *http.Request) (*http.Response, error) {+ calls+++ if got := req.Header.Get("Authorization"); got != tc.want {+ t.Errorf("authorization = %q, want %q", got, tc.want)+ }+ if strings.Contains(req.URL.Path, "download") {+ return imageResp(http.StatusOK, "image/png", testPNG), nil+ }+ return imageResp(http.StatusOK, "application/json", []byte("{}")), nil+ })+ c := &client{cfg: cfg, http: &http.Client{Transport: transport}}+ if err := c.ping(context.Background()); err != nil {+ t.Fatal(err)+ }+ if _, _, err := c.downloadImage(context.Background(), testBaseURL+"/download/image.png"); err != nil {+ t.Fatal(err)+ }+ if calls != 2 {+ t.Fatalf("got %d requests, want API and image requests", calls)+ }+ })+ }+}++func TestPATPickerCachePartitionsAuthentication(t *testing.T) {+ keys := make(map[string]bool)+ for _, creds := range []map[string]interface{}{+ {"username": "reader", "password": "same-secret"},+ {"username": "reader", "token": "same-secret"},+ {"username": "reader", "token": "rotated-secret"},+ } {+ creds["base_url"] = testBaseURL+ cfg, err := parseConfig(&types.DataSourceConfig{Credentials: creds})+ if err != nil {+ t.Fatal(err)+ }+ key := pickerSpaceCacheKey(cfg)+ if keys[key] {+ t.Fatal("different authentication contexts share a cache key")+ }+ if strings.Contains(key, "same-secret") || strings.Contains(key, "rotated-secret") {+ t.Fatal("cache key contains credential text")+ }+ keys[key] = true+ }+}++func TestPATImageRedirectBoundaries(t *testing.T) {+ for _, target := range []string{+ testBaseURL + "/download/final.png",+ "https://other.test/image.png",+ "https://confluence.test/other-app/image.png",+ } {+ t.Run(target, func(t *testing.T) {+ cfg, err := parseConfig(&types.DataSourceConfig{Credentials: map[string]interface{}{+ "base_url": testBaseURL, "token": "pat-value",+ }})+ if err != nil {+ t.Fatal(err)+ }+ calls := 0+ transport := roundTripper(func(req *http.Request) (*http.Response, error) {+ calls+++ if !strings.HasPrefix(req.URL.String(), testBaseURL+"/") {+ t.Fatal("request escaped configured Confluence scope")+ }+ if req.Header.Get("Authorization") != "Bearer pat-value" {+ t.Error("missing PAT")+ }+ if calls == 1 {+ return redirectResp(target), nil+ }+ return imageResp(http.StatusOK, "image/png", testPNG), nil+ })+ c := &client{cfg: cfg, http: &http.Client{Transport: transport}}+ _, _, err = c.downloadImage(context.Background(), testBaseURL+"/download/start.png")+ if strings.HasPrefix(target, testBaseURL+"/") {+ if err != nil || calls != 2 {+ t.Fatalf("same-scope redirect: calls=%d err=%v", calls, err)+ }+ } else if !errors.Is(err, errImageRedirectOffOrigin) || calls != 1 {+ t.Fatalf("unsafe redirect: calls=%d err=%v", calls, err)+ }+ })+ }+}diff --git a/internal/datasource/connector/confluence/types.go b/internal/datasource/connector/confluence/types.goindex 498288083..a23e7880b 100644--- a/internal/datasource/connector/confluence/types.go+++ b/internal/datasource/connector/confluence/types.go@@ -18,6 +18,7 @@ const (type config struct {edition, baseURL, username, secret string+ usePAT bool}func (c config) cloud() bool { return c.edition == editionCloud }@@ -52,7 +53,11 @@ func parseConfig(ds *types.DataSourceConfig) (config, error) {if cfg.edition != editionServer && cfg.edition != editionCloud {return config{}, fmt.Errorf("%w: unsupported edition %q", datasource.ErrInvalidCredentials, cfg.edition)}- if cfg.username == "" {+ if !cfg.cloud() {+ cfg.secret = configValue(ds, "token")+ cfg.usePAT = cfg.secret != ""+ }+ if cfg.username == "" && !cfg.usePAT {return config{}, fmt.Errorf("%w: base_url and username are required", datasource.ErrInvalidCredentials)}normalized, err := normalizeBaseURL(cfg.baseURL, cfg.cloud())@@ -62,7 +67,7 @@ func parseConfig(ds *types.DataSourceConfig) (config, error) {cfg.baseURL = normalizedif cfg.cloud() {cfg.secret = configValue(ds, "api_token")- } else {+ } else if !cfg.usePAT {cfg.secret = configValue(ds, "password")}if cfg.secret == "" {diff --git a/website-docs/03-features/10-datasource.md b/website-docs/03-features/10-datasource.mdindex 8d90188ba..8bdfaa65e 100644--- a/website-docs/03-features/10-datasource.md+++ b/website-docs/03-features/10-datasource.md@@ -184,22 +184,25 @@#### Confluence(`connector/confluence/`)-支持 Confluence Server / Data Center 与 Confluence Cloud,均使用 HTTP Basic 认证。+支持 Confluence Server / Data Center 与 Confluence Cloud。Server/DC 可使用个人访问令牌(PAT,Bearer 认证)或用户名与密码(HTTP Basic);Cloud 使用邮箱与 API token(HTTP Basic)。| 字段 | 必填 | 说明 || --- | --- | --- || `edition` | 否 | `server`(默认,Server / Data Center)或 `cloud` || `base_url` | 是 | Confluence 地址,缺少协议时补 `https://`;Cloud 填 `https://<站点>.atlassian.net` 时自动补 `/wiki` |-| `username` | 是 | Server/DC 用户名;Cloud 为 Atlassian 账号邮箱 |-| `password` | Server/DC 必填 | Server/DC 账号密码 |+| `username` | Basic 认证必填 | Server/DC 用户名;Cloud 为 Atlassian 账号邮箱;Server/DC 使用 PAT 时可留空 |+| `token` | 否 | Server/DC 个人访问令牌;填写后优先使用 Bearer 认证,无需用户名和密码;Cloud 不使用此字段 |+| `password` | Server/DC 未填 PAT 时必填 | Server/DC 账号密码 || `api_token` | Cloud 必填 | 在 Atlassian 账号的 API tokens 页面创建 |-`edition`、`base_url`、`username` 不属于密钥,界面会同时写入 Settings 以便编辑时回显;`password` / `api_token` 只存加密凭据。+`edition`、`base_url`、`username` 不属于密钥,界面会同时写入 Settings 以便编辑时回显;`token` / `password` / `api_token` 只存加密凭据。++Server/DC PAT 适用于 Confluence 7.9 及以上版本,可在个人设置的 Personal access tokens 中创建,详见 [Atlassian 官方说明](https://confluence.atlassian.com/enterprise/using-personal-access-tokens-1026032365.html)。连接测试、空间与页面读取以及同源私有图片下载使用同一种认证方式。<Screenshot- src="/screenshots/datasource-confluence.png"- caption="Confluence 数据源:版本选择与凭据填写"- hint="数据源编辑弹窗选中 Confluence,展示「Confluence 版本」下拉(Server / Data Center、Cloud)、地址、用户名与 Cloud API 令牌字段,以及测试连接后的空间选择列表。" />+ src="/screenshots/datasource-confluence-pat.png"+ caption="Confluence Server/DC 数据源:使用个人访问令牌"+ hint="Server / Data Center 凭据表单:填写 PAT 后,用户名和密码可留空。截图使用本地模拟配置和示例令牌。" />- **范围**:资源列表是凭据可见的空间(扁平列表),至少选择一个空间;同步空间内全部已发布页面,不导入附件和博客文章。- **内容**:取页面渲染后的 HTML 转为 Markdown(每页一个 `.md` 条目),正文为空时仅保留标题。条目 metadata 带 `space_key`、`space_name`、`page_id`,有作者时带 `creator`。diff --git a/website-docs/public/screenshots/datasource-confluence-pat.png b/website-docs/public/screenshots/datasource-confluence-pat.pngnew file mode 100644index 000000000..39edf8fdbBinary files /dev/null and b/website-docs/public/screenshots/datasource-confluence-pat.png differ