feat(settings): 打通 PP 认证配置并统一 DWS 来源授权
build / build (push) Successful in 2m20s

PP 增加受控凭据更新、真实登录与目录检查,待验证修改不会替换生效配置;扫描与取件共享生效修订。
钉钉来源向导、校验与登记共用 DWS 授权,支持中途恢复与换账号保护,取消旧扫码自动回落。
认证审计复用已有来源审计页,配置响应不回传密码;补齐运行镜像脚本与权限。

验证:make verify 退出 0;PP/DWS/httpapi 目标 race 回归通过;隔离 HTTP 服务验证 PP 协议及扫描/取件消费者。
尚未部署;真实 PP 凭据与目录可用性在测试站部署后验证。
This commit is contained in:
姚章浩
2026-11-17 19:08:46 +08:00
parent e0fa31c9d6
commit 3825859da6
54 changed files with 3219 additions and 639 deletions
+1 -1
View File
@@ -107,7 +107,7 @@ func classifyRole(method, path string) string {
if strings.HasPrefix(path, "/api/v1/users") || strings.HasPrefix(path, "/api/v1/qa-ops/") {
return roleAdmin
}
if strings.HasPrefix(path, "/api/v1/dws-login") {
if strings.HasPrefix(path, "/api/v1/dws-login") || strings.HasPrefix(path, "/api/v1/pp-connection") || strings.HasPrefix(path, "/api/v1/dingtalk-spaces") || strings.HasPrefix(path, "/api/v1/dingtalk-session") {
return roleAdmin
}
if method == http.MethodGet {
+63
View File
@@ -0,0 +1,63 @@
package httpapi
import (
"context"
postgresstore "knowledge-governance/internal/platform/postgres"
"knowledge-governance/internal/ppauth"
"sort"
)
// Credential events are committed with their secret revision in one atomic file.
// Merge them into the existing audit view without copying secrets into SQL.
func combinedSourceAudit(ctx context.Context, reader sourceAuditReader, manager *ppauth.Manager, limit, offset int) (postgresstore.SourceAuditPage, error) {
if manager == nil {
return reader.ListSourceAudit(ctx, limit, offset)
}
events, err := manager.Events(ctx)
if err != nil {
return postgresstore.SourceAuditPage{}, err
}
if len(events) == 0 {
return reader.ListSourceAudit(ctx, limit, offset)
}
start := offset - len(events)
if start < 0 {
start = 0
}
rows := make([]postgresstore.SourceAuditItem, 0, limit+len(events))
total := 0
for next := start; len(rows) < limit+len(events); {
take := limit + len(events) - len(rows)
if take > 100 {
take = 100
}
page, e := reader.ListSourceAudit(ctx, take, next)
if e != nil {
return postgresstore.SourceAuditPage{}, e
}
total = page.Total
rows = append(rows, page.Items...)
next += len(page.Items)
if next >= total || len(page.Items) == 0 {
break
}
}
for _, e := range events {
rows = append(rows, postgresstore.SourceAuditItem{ID: e.ID, ConnectionID: "", SourceName: e.SourceName, Action: e.Action, Actor: e.Actor, CreatedAt: e.CreatedAt, Detail: e.Detail})
}
sort.SliceStable(rows, func(i, j int) bool {
if rows[i].CreatedAt.Equal(rows[j].CreatedAt) {
return rows[i].ID > rows[j].ID
}
return rows[i].CreatedAt.After(rows[j].CreatedAt)
})
skip := offset - start
if skip > len(rows) {
skip = len(rows)
}
end := skip + limit
if end > len(rows) {
end = len(rows)
}
return postgresstore.SourceAuditPage{Items: rows[skip:end], Total: total + len(events), Limit: limit, Offset: offset}, nil
}
+5 -15
View File
@@ -2,7 +2,6 @@ package httpapi
import (
"context"
"errors"
"net/http"
"time"
@@ -25,25 +24,16 @@ func listDingtalkSources(w http.ResponseWriter, r *http.Request, config Config)
if _, ok := requireSessionIdentity(w, r); !ok {
return
}
lister := config.DingtalkSources
if lister == nil {
writeJSON(w, http.StatusNotImplemented, map[string]string{"error": "dingtalk source discovery is not wired"})
identity, _ := requireSessionIdentity(w, r)
if identity.Role != roleAdmin {
writeJSON(w, 403, map[string]string{"error": "需要管理员身份列举数据源"})
return
}
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
defer cancel()
result, err := lister.ListAvailableDingtalkSources(ctx)
result, err := availableDWS(ctx, config)
if err != nil {
if errors.Is(err, dingtalkdiscovery.ErrUnavailable) {
// 环境问题(dws 未登录 / 权限不足 / 二进制缺失):页面显示"暂时列不出来",
// 不是平台故障,也不该把内部错误细节当 500 抛出去。
writeJSON(w, http.StatusServiceUnavailable, map[string]string{
"error": "dingtalk_discovery_unavailable",
"hint": "dws 未登录或缺少租户目录读权限;请先刷新钉钉会话,或让管理员检查 dws 凭据。",
})
return
}
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "could not list dingtalk sources"})
writeDWSSourceError(w, err)
return
}
writeJSON(w, http.StatusOK, map[string]any{"data": result})
+1 -1
View File
@@ -53,7 +53,7 @@ func TestListDingtalkSourcesReportsEnvironmentProblemsAsUnavailable(t *testing.T
if rec.Code != http.StatusServiceUnavailable {
t.Fatalf("unavailable = %d, want 503 body=%s", rec.Code, rec.Body.String())
}
if !strings.Contains(rec.Body.String(), "dingtalk_discovery_unavailable") {
if !strings.Contains(rec.Body.String(), "dws_unavailable") {
t.Fatalf("body = %s", rec.Body.String())
}
}
+18 -35
View File
@@ -2,59 +2,42 @@ package httpapi
import (
"context"
"knowledge-governance/internal/dingtalkdiscovery"
postgresstore "knowledge-governance/internal/platform/postgres"
"net/http"
"net/http/httptest"
"testing"
"time"
"knowledge-governance/internal/dingtalkdiscovery"
)
func TestDWSNameConflictIsNotASuccessfulRegistration(t *testing.T) {
store := &fakeDingtalkRegistrar{fakeJobStore: &fakeJobStore{}, err: postgresstore.ErrDingtalkSpaceNameTaken}
lister := fakeDingtalkSources{result: dingtalkdiscovery.Result{KnowledgeBases: []dingtalkdiscovery.KnowledgeBase{{Name: "wiki", SpaceID: "testspace"}}}}
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/api/v1/dingtalk-spaces", nil)
registerSpaceThroughDWS(rec, req, Config{Store: store, DingtalkSources: lister, Now: time.Now}, "testspace", "test-op")
if rec.Code != http.StatusConflict {
req := httptest.NewRequest("POST", "/api/v1/dingtalk-spaces", nil)
registerDWSOnlySpace(rec, req, Config{Store: store, DingtalkSources: lister, Now: time.Now}, "testspace", "test-op")
if rec.Code != 409 {
t.Fatalf("name conflict must not claim success: %d", rec.Code)
}
}
// 登记走 dws 不是侧车:解析出来的键、名称、根节点直接决定新来源的确定性 id。
func TestResolveSpaceViaDWSUsesTheSpaceCredentialsAlreadyHeld(t *testing.T) {
lister := fakeDingtalkSources{result: dingtalkdiscovery.Result{
KnowledgeBases: []dingtalkdiscovery.KnowledgeBase{
{Name: "国内技术支持管理", SpaceID: "9JOGOLBQndOyaz4Q"},
{Name: "视觉文档", SpaceID: "9JOGO9EEOMLMWX4Q"},
},
DriveSpaces: []dingtalkdiscovery.DriveSpace{
{Name: "全员文件夹", SpaceID: "102571304", RootFolderID: "g1YGl6Pm2Db8Dr3OayClVxLq0Ee4p79a"},
},
}}
rootKey, name, rootID, spaceID, ok := resolveSpaceViaDWS(
context.Background(), lister, dingtalkdiscovery.SpaceURL("9JOGOLBQndOyaz4Q"))
if !ok || rootKey != "space-9JOGOLBQndOyaz4Q" || name != "国内技术支持管理" || rootID != "9JOGOLBQndOyaz4Q" || spaceID != "9JOGOLBQndOyaz4Q" {
t.Fatalf("knowledge base resolved as key=%q name=%q root=%q space=%q ok=%v", rootKey, name, rootID, spaceID, ok)
result := dingtalkdiscovery.Result{KnowledgeBases: []dingtalkdiscovery.KnowledgeBase{{Name: "国内技术支持管理", SpaceID: "9JOGOLBQndOyaz4Q"}}, DriveSpaces: []dingtalkdiscovery.DriveSpace{{Name: "全员文件夹", SpaceID: "102571304", RootFolderID: "drive-root"}}}
input, err := resolveDWS(result, dingtalkdiscovery.SpaceURL("9JOGOLBQndOyaz4Q"))
if err != nil || input.RootKey != "space-9JOGOLBQndOyaz4Q" || input.Name != "国内技术支持管理" || input.RootID != "9JOGOLBQndOyaz4Q" || input.SpaceID != "9JOGOLBQndOyaz4Q" {
t.Fatalf("wiki resolution=%+v %v", input, err)
}
// 钉盘的根是 rootFolderId,不是空间 id:抓取侧按它遍历。
rootKey, _, rootID, _, ok = resolveSpaceViaDWS(context.Background(), lister, dingtalkdiscovery.SpaceURL("102571304"))
if !ok || rootID != "g1YGl6Pm2Db8Dr3OayClVxLq0Ee4p79a" || rootKey != "space-102571304" {
t.Fatalf("drive space resolved as key=%q root=%q ok=%v", rootKey, rootID, ok)
input, err = resolveDWS(result, dingtalkdiscovery.SpaceURL("102571304"))
if err != nil || input.RootID != "drive-root" || input.RootKey != "space-102571304" {
t.Fatalf("drive resolution=%+v %v", input, err)
}
}
func TestResolveSpaceViaDWSLeavesUnknownSpacesToTheFallback(t *testing.T) {
lister := fakeDingtalkSources{result: dingtalkdiscovery.Result{}}
if _, _, _, _, ok := resolveSpaceViaDWS(context.Background(), lister, dingtalkdiscovery.SpaceURL("unknownspace1")); ok {
t.Fatal("an unknown space must not resolve")
func TestResolveDWSRejectsUnknownAndUnwiredWithoutBrowserFallback(t *testing.T) {
if _, err := resolveDWS(dingtalkdiscovery.Result{}, dingtalkdiscovery.SpaceURL("unknownspace1")); err == nil {
t.Fatal("unknown space resolved")
}
if _, _, _, _, ok := resolveSpaceViaDWS(context.Background(), nil, dingtalkdiscovery.SpaceURL("9JOGOLBQndOyaz4Q")); ok {
t.Fatal("without a lister nothing can resolve")
if _, err := availableDWS(context.Background(), Config{}); err == nil {
t.Fatal("unwired service resolved")
}
if _, _, _, _, ok := resolveSpaceViaDWS(context.Background(), lister, "not-a-space-url"); ok {
t.Fatal("a URL without a space id must not resolve")
if _, err := resolveDWS(dingtalkdiscovery.Result{}, "not-a-space-url"); err == nil {
t.Fatal("invalid space resolved")
}
}
+4 -154
View File
@@ -2,9 +2,7 @@ package httpapi
import (
"bytes"
"context"
"encoding/json"
"errors"
"io"
"log"
"net/http"
@@ -12,10 +10,6 @@ import (
"regexp"
"strings"
"time"
"knowledge-governance/internal/governance"
"knowledge-governance/internal/jobs"
postgresstore "knowledge-governance/internal/platform/postgres"
)
// DingTalk login proxy. The scan-code login itself lives in the
@@ -102,86 +96,15 @@ func registerDingtalkSpace(w http.ResponseWriter, r *http.Request, config Config
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "url is required"})
return
}
// dws 已经持有有效凭据(access 自动续期、refresh 一个月),登记也该走它:
// 只有 dws 解析不出这个空间时,才回落到老的扫码侧车。
if registered, ok := registerSpaceThroughDWS(w, r, config, strings.TrimSpace(input.URL), operationID); ok || registered {
return
}
payload, _ := json.Marshal(map[string]string{"url": strings.TrimSpace(input.URL)})
status, data := proxyDingtalk(http.MethodPost, "/spaces/add", payload)
if status != http.StatusOK {
if status == 0 {
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "dingtalk_login_unavailable"})
return
}
// Relay the sidecar's error (login_required / space_not_found /
// name_conflict) verbatim; bodies are machine codes, no secrets.
writeProxyResult(w, status, data)
return
}
var resolved struct {
Key string `json:"key"`
Name string `json:"name"`
Root string `json:"root"`
}
if err := json.Unmarshal(data, &resolved); err != nil || resolved.Key == "" || resolved.Name == "" || resolved.Root == "" {
writeJSON(w, http.StatusBadGateway, map[string]string{"error": "invalid sidecar registration response"})
return
}
store, ok := config.Store.(interface {
RegisterDingtalkSpace(context.Context, postgresstore.RegisterDingtalkSpaceInput) (string, error)
})
if !ok {
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "registration_unavailable"})
return
}
spaceID := extractDingtalkSpaceID(input.URL)
if spaceID == "" {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid space url"})
return
}
connectionID, err := store.RegisterDingtalkSpace(r.Context(), postgresstore.RegisterDingtalkSpaceInput{
RootKey: resolved.Key, Name: resolved.Name, SpaceID: spaceID, RootID: resolved.Root, Now: config.Now(), Actor: actorFor(r),
})
switch {
case errors.Is(err, postgresstore.ErrDingtalkSpaceNameTaken):
writeJSON(w, http.StatusConflict, map[string]string{
"error": "space_name_conflict",
"hint": "已有同名来源仍在使用(未下架):请先在该来源卡片上「去掉来源」,或确认选的是同一个知识库空间。",
})
return
case errors.Is(err, postgresstore.ErrDingtalkSpaceIdentityConflict):
writeJSON(w, http.StatusConflict, map[string]string{
"error": "space_identity_conflict",
"hint": "这个登记键已指向另一个知识库空间:请刷新列表后重试;若仍失败,把该来源「去掉来源」后再登记。",
})
return
case err != nil:
// 真正的数据库/内部故障不能伪装成"冲突":换个 500 才有人去查日志。
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "space_registration_failed"})
return
}
// First scan is enqueued right away: the new connection has no catalog
// head yet, so the generic sources/{id}/refresh endpoint would 404 until
// the first snapshot exists.
if enqueuer, ok := config.Store.(interface {
EnqueueCatalogRefreshWithOperation(context.Context, governance.CatalogSource, string, time.Time) (jobs.Job, bool, error)
}); ok {
if _, _, enqueueErr := enqueuer.EnqueueCatalogRefreshWithOperation(r.Context(), governance.CatalogSource{
ConnectionID: connectionID, SourceType: governance.SourceTypeDingTalk, Name: resolved.Name,
}, operationID+":first", config.Now().UTC()); enqueueErr != nil {
log.Printf("dingtalk space %s registered but first refresh enqueue failed: %v", connectionID, enqueueErr)
}
}
log.Printf("dingtalk space %q registered as connection %s by %s", resolved.Name, connectionID, actorFor(r))
writeJSON(w, http.StatusCreated, map[string]any{"data": map[string]string{
"connection_id": connectionID, "name": resolved.Name,
}})
registerDWSOnlySpace(w, r, config, strings.TrimSpace(input.URL), operationID)
}
var dingtalkSpacePattern = regexp.MustCompile(`/spaces/([A-Za-z0-9_-]+)`)
func extractDingtalkSpaceID(raw string) string {
if !validDingtalkURL(raw) {
return ""
}
match := dingtalkSpacePattern.FindStringSubmatch(raw)
if len(match) == 2 {
return match[1]
@@ -244,76 +167,3 @@ func proxyDingtalk(method, path string, body []byte) (int, []byte) {
}
return resp.StatusCode, data
}
// resolveSpaceViaDWS 用 dws 列举结果定位一个空间:返回确定性登记键、名称与根节点。
// 认不出就 ok=false,调用方回落到老的扫码侧车(历史空间仍能被登记)。
func resolveSpaceViaDWS(ctx context.Context, lister dingtalkSourcesLister, rawURL string) (rootKey, name, rootID, spaceID string, ok bool) {
spaceID = extractDingtalkSpaceID(rawURL)
if lister == nil || spaceID == "" {
return "", "", "", "", false
}
discovered, err := lister.ListAvailableDingtalkSources(ctx)
if err != nil {
return "", "", "", "", false
}
for _, base := range discovered.KnowledgeBases {
if base.SpaceID == spaceID {
// 知识库:URL 里的 id 就是空间 id,抓取侧按 spaces/<id> 匹配。
return "space-" + spaceID, base.Name, spaceID, spaceID, true
}
}
for _, space := range discovered.DriveSpaces {
if space.SpaceID == spaceID && space.RootFolderID != "" {
return "space-" + spaceID, space.Name, space.RootFolderID, spaceID, true
}
}
return "", "", "", "", false
}
// registerSpaceThroughDWS 用 dws 凭据直接登记来源,不再要求扫码会话。
func registerSpaceThroughDWS(w http.ResponseWriter, r *http.Request, config Config, rawURL, operationID string) (bool, bool) {
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
defer cancel()
rootKey, name, rootID, spaceID, ok := resolveSpaceViaDWS(ctx, config.DingtalkSources, rawURL)
if !ok {
return false, false
}
store, wired := config.Store.(interface {
RegisterDingtalkSpace(context.Context, postgresstore.RegisterDingtalkSpaceInput) (string, error)
})
if !wired {
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "registration_unavailable"})
return true, false
}
connectionID, err := store.RegisterDingtalkSpace(ctx, postgresstore.RegisterDingtalkSpaceInput{
RootKey: rootKey, Name: name, SpaceID: spaceID, RootID: rootID, Now: config.Now(), Actor: actorFor(r),
})
switch {
case errors.Is(err, postgresstore.ErrDingtalkSpaceNameTaken):
writeJSON(w, http.StatusConflict, map[string]string{"error": "space_name_conflict", "hint": "已有同名来源,但空间标识不一致;请核对已有来源,不能按名称判定添加成功。"})
return true, false
case errors.Is(err, postgresstore.ErrDingtalkSpaceIdentityConflict):
writeJSON(w, http.StatusConflict, map[string]string{
"error": "space_identity_conflict",
"hint": "这个登记键已指向另一个知识库空间:请刷新列表后重试。",
})
return true, false
case err != nil:
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "space_registration_failed"})
return true, false
}
if enqueuer, wired := config.Store.(interface {
EnqueueCatalogRefreshWithOperation(context.Context, governance.CatalogSource, string, time.Time) (jobs.Job, bool, error)
}); wired {
if _, _, enqueueErr := enqueuer.EnqueueCatalogRefreshWithOperation(ctx, governance.CatalogSource{
ConnectionID: connectionID, SourceType: governance.SourceTypeDingTalk, Name: name,
}, operationID+":first", config.Now().UTC()); enqueueErr != nil {
log.Printf("dingtalk space %s registered but first refresh enqueue failed: %v", connectionID, enqueueErr)
}
}
log.Printf("dingtalk space %q registered as connection %s by %s (dws)", name, connectionID, actorFor(r))
writeJSON(w, http.StatusCreated, map[string]any{"data": map[string]string{
"connection_id": connectionID, "name": name,
}})
return true, true
}
+2 -1
View File
@@ -9,6 +9,7 @@ import (
"strings"
"testing"
"knowledge-governance/internal/dingtalkdiscovery"
postgresstore "knowledge-governance/internal/platform/postgres"
)
@@ -123,7 +124,7 @@ func TestDingtalkSpaceRegistrationErrorClassification(t *testing.T) {
call := func(storeErr error) (int, string) {
store := &fakeDingtalkRegistrar{fakeJobStore: &fakeJobStore{}, err: storeErr}
handler, err := NewHandler(Config{Store: store})
handler, err := NewHandler(Config{Store: store, DingtalkSources: fakeDingtalkSources{result: dingtalkdiscovery.Result{KnowledgeBases: []dingtalkdiscovery.KnowledgeBase{{Name: "公司级技术支持知识库", SpaceID: "9JOK9EEOMLMWX4Q"}}}}})
if err != nil {
t.Fatalf("NewHandler() error = %v", err)
}
+9
View File
@@ -63,6 +63,15 @@ func handleDWSLogin(w http.ResponseWriter, r *http.Request, config Config, actio
}
return
}
if config.PPConnection != nil && (action != "get" || view.State == "succeeded" || view.State == "failed" || view.State == "expired") {
if err := config.PPConnection.AuditOnce(r.Context(), "dws-"+view.ID+"-"+string(view.State), "钉钉账号(DWS)", "dws_authorization", identity.Username, "DWS 授权状态:"+string(view.State)); err != nil {
if action == "start" {
_, _ = config.DWSLogin.Cancel(owner, view.ID)
}
writeJSON(w, 503, map[string]string{"error": "授权审计写入失败,请重试"})
return
}
}
if action != "get" {
log.Printf("DWS authorization action=%s id=%s actor=%s", action, view.ID, identity.Username)
}
+212
View File
@@ -0,0 +1,212 @@
package httpapi
import (
"context"
"errors"
"knowledge-governance/internal/dingtalkdiscovery"
"knowledge-governance/internal/governance"
"knowledge-governance/internal/jobs"
postgresstore "knowledge-governance/internal/platform/postgres"
"net/http"
"net/url"
"strings"
"time"
)
type dwsSourceError struct {
Status int
Code, Hint string
}
func (e *dwsSourceError) Error() string { return e.Hint }
func writeDWSSourceError(w http.ResponseWriter, err error) {
var e *dwsSourceError
if errors.As(err, &e) {
writeJSON(w, e.Status, map[string]string{"error": e.Code, "hint": e.Hint})
return
}
writeJSON(w, 500, map[string]string{"error": "dws_source_failed", "hint": "读取钉钉来源失败,请重试"})
}
func availableDWS(ctx context.Context, config Config) (dingtalkdiscovery.Result, error) {
identity := ""
if config.DingtalkSources == nil {
return dingtalkdiscovery.Result{}, &dwsSourceError{501, "dws_unwired", "DWS 来源服务未接通"}
}
if reader, ok := config.DingtalkSources.(interface {
ReadDWSMetadata(context.Context) (dingtalkdiscovery.CredentialStatus, error)
}); ok {
status, err := reader.ReadDWSMetadata(ctx)
if err != nil || !status.StatusKnown {
return dingtalkdiscovery.Result{}, &dwsSourceError{503, "dws_status_unavailable", "暂时无法读取 DWS 授权状态,请重试"}
}
identity = status.Identity
if !status.Authenticated && !status.RefreshTokenValid {
return dingtalkdiscovery.Result{}, &dwsSourceError{401, "dws_login_required", "DWS 未登录或授权已失效,请重新授权"}
}
}
result, err := config.DingtalkSources.ListAvailableDingtalkSources(ctx)
if err != nil {
if errors.Is(err, dingtalkdiscovery.ErrCredentials) {
return result, &dwsSourceError{401, "dws_login_required", "DWS 授权已失效,请重新授权"}
}
if errors.Is(err, dingtalkdiscovery.ErrPermission) {
return result, &dwsSourceError{403, "dws_permission_denied", "当前 DWS 账号缺少目录读取权限"}
}
if errors.Is(err, dingtalkdiscovery.ErrUnavailable) {
return result, &dwsSourceError{503, "dws_unavailable", "DWS 目录暂时无法读取,请检查连接后重试"}
}
return result, err
}
if identity != "" {
reader := config.DingtalkSources.(interface {
ReadDWSMetadata(context.Context) (dingtalkdiscovery.CredentialStatus, error)
})
fresh, e := reader.ReadDWSMetadata(ctx)
if e != nil {
return result, &dwsSourceError{503, "dws_status_unavailable", "无法确认当前账号,请重试"}
}
if fresh.Identity != identity {
return result, &dwsSourceError{409, "dws_identity_changed", "DWS 账号或组织已变化,请重新确认来源"}
}
}
result.Identity = identity
if config.Store != nil {
if page, e := config.Store.ListSourceConnections(ctx); e == nil {
seen := map[string]bool{}
for _, c := range page.Items {
seen[c.ID] = true
}
for i, kb := range result.KnowledgeBases {
in := postgresstore.RegisterDingtalkSpaceInput{RootKey: "space-" + kb.SpaceID}
result.KnowledgeBases[i].Registered = seen[in.ConnectionID()]
}
for i, space := range result.DriveSpaces {
in := postgresstore.RegisterDingtalkSpaceInput{RootKey: "space-" + space.SpaceID}
result.DriveSpaces[i].Registered = seen[in.ConnectionID()]
}
}
}
if registry, ok := config.Store.(interface {
RegisteredDingtalkSpaceIDs(context.Context) (map[string]bool, error)
}); ok {
ids, e := registry.RegisteredDingtalkSpaceIDs(ctx)
if e != nil {
return result, &dwsSourceError{503, "dws_registration_state_unavailable", "无法核对已接入空间,请重试"}
}
for i, kb := range result.KnowledgeBases {
result.KnowledgeBases[i].Registered = ids[kb.SpaceID]
}
for i, space := range result.DriveSpaces {
result.DriveSpaces[i].Registered = ids[space.SpaceID]
}
}
return result, nil
}
func resolveDWS(result dingtalkdiscovery.Result, raw string) (postgresstore.RegisterDingtalkSpaceInput, error) {
spaceID := extractDingtalkSpaceID(raw)
if spaceID == "" {
return postgresstore.RegisterDingtalkSpaceInput{}, &dwsSourceError{400, "invalid_space_url", "请输入有效的钉钉空间地址"}
}
for _, base := range result.KnowledgeBases {
if base.SpaceID == spaceID {
return postgresstore.RegisterDingtalkSpaceInput{RootKey: "space-" + spaceID, Name: base.Name, RootID: spaceID, SpaceID: spaceID}, nil
}
}
for _, space := range result.DriveSpaces {
if space.SpaceID == spaceID && space.RootFolderID != "" {
return postgresstore.RegisterDingtalkSpaceInput{RootKey: "space-" + spaceID, Name: space.Name, RootID: space.RootFolderID, SpaceID: spaceID}, nil
}
}
if result.KnowledgeNotice != "" || result.DriveNotice != "" {
return postgresstore.RegisterDingtalkSpaceInput{}, &dwsSourceError{503, "dws_scope_incomplete", "当前目录结果不完整,无法确认所选空间;请检查相应目录权限后重试"}
}
return postgresstore.RegisterDingtalkSpaceInput{}, &dwsSourceError{409, "dws_space_not_visible", "当前 DWS 账号已看不到所选空间,请刷新范围或核对账号权限"}
}
func registerDWSOnlySpace(w http.ResponseWriter, r *http.Request, config Config, raw, operationID string) {
if extractDingtalkSpaceID(raw) == "" {
writeDWSSourceError(w, &dwsSourceError{400, "invalid_space_url", "请输入有效的钉钉空间地址"})
return
}
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
defer cancel()
result, err := availableDWS(ctx, config)
if err != nil {
writeDWSSourceError(w, err)
return
}
if wanted := r.Header.Get("X-DWS-Identity"); wanted != "" && wanted != result.Identity {
writeDWSSourceError(w, &dwsSourceError{409, "dws_identity_changed", "DWS 账号或组织已变化,请重新确认来源"})
return
}
input, err := resolveDWS(result, raw)
if err != nil {
writeDWSSourceError(w, err)
return
}
input.Now = config.Now()
input.Actor = actorFor(r)
store, ok := config.Store.(interface {
RegisterDingtalkSpace(context.Context, postgresstore.RegisterDingtalkSpaceInput) (string, error)
})
if !ok {
writeJSON(w, 503, map[string]string{"error": "registration_unavailable"})
return
}
connectionID, err := store.RegisterDingtalkSpace(ctx, input)
switch {
case errors.Is(err, postgresstore.ErrDingtalkSpaceNameTaken):
writeJSON(w, 409, map[string]string{"error": "space_name_conflict", "hint": "已有同名来源仍在使用:请核对空间身份,必要时先移除旧连接(原去掉来源操作)"})
return
case errors.Is(err, postgresstore.ErrDingtalkSpaceIdentityConflict):
writeJSON(w, 409, map[string]string{"error": "space_identity_conflict", "hint": "登记键已指向另一个空间,请刷新后核对来源"})
return
case err != nil:
writeJSON(w, 500, map[string]string{"error": "space_registration_failed"})
return
}
queued := false
if queue, ok := config.Store.(interface {
EnqueueCatalogRefreshWithOperation(context.Context, governance.CatalogSource, string, time.Time) (jobs.Job, bool, error)
}); ok {
_, _, err = queue.EnqueueCatalogRefreshWithOperation(ctx, governance.CatalogSource{ConnectionID: connectionID, SourceType: governance.SourceTypeDingTalk, Name: input.Name}, "dws-source-first:"+connectionID, config.Now().UTC())
queued = err == nil
}
writeJSON(w, 201, map[string]any{"data": map[string]any{"connection_id": connectionID, "name": input.Name, "first_scan_queued": queued}})
}
func validateDWSSpace(w http.ResponseWriter, r *http.Request, config Config) {
if !credentialAdmin(w, r, "dingtalk-space") {
return
}
var input struct {
URLs []string `json:"urls"`
}
if decodeJSONStrict(r, &input) != nil || len(input.URLs) == 0 || len(input.URLs) > 100 {
writeJSON(w, 400, map[string]string{"error": "请选择有效的空间范围"})
return
}
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
defer cancel()
result, err := availableDWS(ctx, config)
if err != nil {
writeDWSSourceError(w, err)
return
}
if wanted := r.Header.Get("X-DWS-Identity"); wanted != "" && wanted != result.Identity {
writeDWSSourceError(w, &dwsSourceError{409, "dws_identity_changed", "DWS 账号或组织已变化,请重新确认来源"})
return
}
for _, raw := range input.URLs {
if _, err := resolveDWS(result, raw); err != nil {
writeDWSSourceError(w, err)
return
}
}
writeJSON(w, 200, map[string]any{"data": map[string]any{"valid": true, "checked_at": config.Now().UTC(), "count": len(input.URLs)}})
}
func validDingtalkURL(raw string) bool {
if !strings.Contains(raw, "://") {
return true
}
u, err := url.Parse(raw)
return err == nil && u.Scheme == "https" && u.Host == "alidocs.dingtalk.com" && u.User == nil && u.Fragment == ""
}
+30
View File
@@ -0,0 +1,30 @@
package httpapi
import (
"context"
"knowledge-governance/internal/dingtalkdiscovery"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
func TestDWSRegistrationNeverFallsBackToBrowserSession(t *testing.T) {
calls := 0
sidecar := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { calls++; w.WriteHeader(401) }))
defer sidecar.Close()
t.Setenv("DINGTALK_LOGIN_SIDECAR_URL", sidecar.URL)
h, err := NewHandler(Config{Store: &fakeDingtalkRegistrar{fakeJobStore: &fakeJobStore{}}, DingtalkSources: fakeDingtalkSources{err: dingtalkdiscovery.ErrUnavailable}})
if err != nil {
t.Fatal(err)
}
req := httptest.NewRequest("POST", "/api/v1/dingtalk-spaces", strings.NewReader(`{"url":"https://alidocs.dingtalk.com/i/spaces/valid-space-id/overview"}`))
req.Header.Set("Idempotency-Key", "op-dws-only")
req.Header.Set("X-Governance-Action", "dingtalk-space")
req = req.WithContext(context.WithValue(req.Context(), sessionKey{}, sessionIdentity{Username: "tester", Role: roleAdmin}))
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if calls != 0 || rec.Code != 503 || !strings.Contains(rec.Body.String(), "dws_unavailable") {
t.Fatalf("DWS failed: legacy calls=%d status=%d body=%s", calls, rec.Code, rec.Body.String())
}
}
+1 -1
View File
@@ -52,7 +52,7 @@ func TestOpenAPIContractMatchesRegisteredRoutesAndOmitsSecrets(t *testing.T) {
switch value := node.(type) {
case map[string]any:
for key, child := range value {
if key == "base_url" && path != "components.schemas.QAAISafeSettings.properties" && path != "components.schemas.QAAISaveSettings.properties" {
if key == "base_url" && path != "components.schemas.QAAISafeSettings.properties" && path != "components.schemas.QAAISaveSettings.properties" && path != "components.schemas.PPSafeMetadata.properties" && path != "components.schemas.PPConnectionDraft.properties" {
t.Fatalf("unapproved endpoint exposure at %s", path)
}
next := key
+94
View File
@@ -0,0 +1,94 @@
package httpapi
import (
"context"
"errors"
"knowledge-governance/internal/ppauth"
"net/http"
"net/url"
"time"
)
func credentialAdmin(w http.ResponseWriter, r *http.Request, action string) bool {
w.Header().Set("Cache-Control", "no-store")
identity, ok := requireSessionIdentity(w, r)
if !ok {
return false
}
if identity.Role != roleAdmin {
writeJSON(w, 403, map[string]string{"error": "需要管理员身份管理来源凭据"})
return false
}
if r.Method != "GET" {
originOK := true
if raw := r.Header.Get("Origin"); raw != "" {
u, err := url.Parse(raw)
originOK = err == nil && u.Host == r.Host && (u.Scheme == "http" || u.Scheme == "https")
}
if !originOK || r.Header.Get("Sec-Fetch-Site") == "cross-site" || r.Header.Get("X-Governance-Action") != action {
writeJSON(w, 403, map[string]string{"error": "请从本平台的数据源配置页操作"})
return false
}
}
return true
}
func writePPError(w http.ResponseWriter, err error) {
status := http.StatusBadRequest
if errors.Is(err, ppauth.ErrConflict) {
status = http.StatusConflict
}
writeJSON(w, status, map[string]string{"error": err.Error()})
}
func registerPPConnectionRoutes(mux *http.ServeMux, config Config) {
for _, pattern := range []string{"GET /api/v1/pp-connection", "PUT /api/v1/pp-connection", "POST /api/v1/pp-connection/test"} {
mux.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) {
if !credentialAdmin(w, r, "pp-connection") {
return
}
if config.PPConnection == nil {
writeJSON(w, 503, map[string]string{"error": "PP 配置服务未接通,请联系管理员"})
return
}
if r.Method == "GET" {
v, err := config.PPConnection.View()
if err != nil {
writeJSON(w, 503, map[string]string{"error": err.Error()})
return
}
writeJSON(w, 200, map[string]any{"data": v})
return
}
var draft ppauth.Draft
r.Body = http.MaxBytesReader(w, r.Body, 16384)
if decodeJSONStrict(r, &draft) != nil {
writeJSON(w, 400, map[string]string{"error": "PP 配置请求格式不正确"})
return
}
ctx, cancel := context.WithTimeout(r.Context(), 50*time.Second)
defer cancel()
if r.Method == "POST" {
result, err := config.PPConnection.Test(ctx, draft, actorFor(r))
if err != nil {
writePPError(w, err)
return
}
writeJSON(w, 200, map[string]any{"data": result})
return
}
result, err := config.PPConnection.Save(ctx, draft, actorFor(r))
if err != nil {
status := 400
if errors.Is(err, ppauth.ErrConflict) {
status = 409
}
if errors.Is(err, ppauth.ErrRejected) {
status = 422
}
writeJSON(w, status, map[string]any{"error": err.Error(), "data": result})
return
}
writeJSON(w, 200, map[string]any{"data": result})
})
}
}
+142
View File
@@ -0,0 +1,142 @@
package httpapi
import (
"context"
"encoding/json"
"fmt"
"knowledge-governance/internal/jobs"
postgresstore "knowledge-governance/internal/platform/postgres"
"knowledge-governance/internal/ppauth"
"net/http/httptest"
"os"
"path/filepath"
"sort"
"strings"
"testing"
"time"
)
type noPPJobStore struct {
*fakeJobStore
queued int
}
func (s *noPPJobStore) Enqueue(ctx context.Context, request jobs.EnqueueRequest, now time.Time) (*jobs.Job, error) {
s.queued++
return s.fakeJobStore.Enqueue(ctx, request, now)
}
func TestPPHTTPRoundTripRechecksSaveAndNeverEnqueues(t *testing.T) {
probes := 0
m := &ppauth.Manager{Path: t.TempDir() + "/credentials/settings.json", Probe: func(_ context.Context, c ppauth.Credentials) ppauth.Observation {
probes++
return ppauth.Observation{State: "valid", Message: "认证有效 · 目录可读"}
}}
store := &noPPJobStore{fakeJobStore: &fakeJobStore{}}
h, err := NewHandler(Config{Store: store, PPConnection: m})
if err != nil {
t.Fatal(err)
}
call := func(method, path, body string) *httptest.ResponseRecorder {
req := httptest.NewRequest(method, path, strings.NewReader(body))
req.Header.Set("X-Governance-Action", "pp-connection")
req = req.WithContext(context.WithValue(req.Context(), sessionKey{}, sessionIdentity{Username: "tester", Role: roleAdmin}))
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
return rec
}
draft := `{"base_url":"https://api.example.invalid","username":"example","password":"example-private","revision":0}`
for _, op := range [][2]string{{"POST", "/api/v1/pp-connection/test"}, {"PUT", "/api/v1/pp-connection"}, {"GET", "/api/v1/pp-connection"}} {
rec := call(op[0], op[1], draft)
if rec.Code != 200 {
t.Fatalf("%s status=%d body=%s", op[0], rec.Code, rec.Body)
}
if strings.Contains(rec.Body.String(), "example-private") || strings.Contains(rec.Body.String(), `"password":`) {
t.Fatal("credential leaked through response")
}
}
if probes != 2 || store.queued != 0 {
t.Fatalf("save must recheck and must not enqueue: checks=%d jobs=%d", probes, store.queued)
}
rec := call("PUT", "/api/v1/pp-connection", draft)
if rec.Code != 409 {
t.Fatalf("stale revision accepted: %d", rec.Code)
}
}
func TestPPHTTPRefusesCrossOriginBeforeProbe(t *testing.T) {
probes := 0
m := &ppauth.Manager{Path: t.TempDir() + "/credentials/settings.json", Probe: func(_ context.Context, _ ppauth.Credentials) ppauth.Observation {
probes++
return ppauth.Observation{State: "valid"}
}}
h, _ := NewHandler(Config{Store: &fakeJobStore{}, PPConnection: m})
req := httptest.NewRequest("POST", "/api/v1/pp-connection/test", strings.NewReader(`{}`))
req.Header.Set("Origin", "https://foreign.example.invalid")
req.Header.Set("X-Governance-Action", "pp-connection")
req = req.WithContext(context.WithValue(req.Context(), sessionKey{}, sessionIdentity{Username: "tester", Role: roleAdmin}))
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 403 || probes != 0 {
t.Fatal("cross-origin request reached credential probe")
}
}
type combinedAuditStore struct {
*fakeJobStore
items []postgresstore.SourceAuditItem
}
func (s *combinedAuditStore) ListSourceAudit(_ context.Context, limit, offset int) (postgresstore.SourceAuditPage, error) {
start := offset
if start > len(s.items) {
start = len(s.items)
}
end := start + limit
if end > len(s.items) {
end = len(s.items)
}
return postgresstore.SourceAuditPage{Items: s.items[start:end], Total: len(s.items), Limit: limit, Offset: offset}, nil
}
func TestPPSourceAuditSharesTheExistingPagedView(t *testing.T) {
ctx := context.Background()
m := &ppauth.Manager{Path: t.TempDir() + "/credentials/settings.json"}
if err := os.Mkdir(filepath.Dir(m.Path), 0700); err != nil {
t.Fatal(err)
}
now := time.Now().UTC()
store := &combinedAuditStore{fakeJobStore: &fakeJobStore{}}
expected := []postgresstore.SourceAuditItem{}
for i := 0; i < 8; i++ {
item := postgresstore.SourceAuditItem{ID: fmt.Sprintf("db-%02d", i), CreatedAt: now.Add(-time.Duration(i*2) * time.Minute), SourceName: "existing source"}
store.items = append(store.items, item)
expected = append(expected, item)
}
state := ppauth.State{}
for i := 0; i < 4; i++ {
event := ppauth.AuditEvent{ID: fmt.Sprintf("auth-%02d", i), CreatedAt: now.Add(-time.Duration(i*2+1) * time.Minute), SourceName: "PP", Action: "credential_test", Actor: "tester", Detail: "只读连接检查"}
state.Audit = append(state.Audit, event)
expected = append(expected, postgresstore.SourceAuditItem{ID: event.ID, CreatedAt: event.CreatedAt, SourceName: event.SourceName})
}
raw, _ := json.Marshal(state)
if err := os.WriteFile(m.Path, raw, 0600); err != nil {
t.Fatal(err)
}
sort.Slice(expected, func(i, j int) bool { return expected[i].CreatedAt.After(expected[j].CreatedAt) })
for offset := 0; offset <= len(expected); offset++ {
page, err := combinedSourceAudit(ctx, store, m, 3, offset)
if err != nil || page.Total != len(expected) {
t.Fatalf("offset=%d total=%d err=%v", offset, page.Total, err)
}
end := offset + 3
if end > len(expected) {
end = len(expected)
}
if len(page.Items) != end-offset {
t.Fatalf("wrong page length at %d", offset)
}
for i, item := range page.Items {
if item.ID != expected[offset+i].ID {
t.Fatalf("audit order mismatch at offset %d", offset)
}
}
}
}
+42
View File
@@ -0,0 +1,42 @@
package httpapi
import (
"context"
"net/http/httptest"
"testing"
)
func TestPPAuthRoutesRequireAdminAndFailClosedWhenUnwired(t *testing.T) {
h, err := NewHandler(Config{Store: &fakeJobStore{}})
if err != nil {
t.Fatal(err)
}
for _, method := range []string{"GET", "PUT", "POST"} {
path := "/api/v1/pp-connection"
if method == "POST" {
path += "/test"
}
for _, role := range []string{"", roleViewer, roleEngineer, roleAdmin} {
req := httptest.NewRequest(method, path, nil)
if role != "" {
req = req.WithContext(context.WithValue(req.Context(), sessionKey{}, sessionIdentity{UserID: "admin", Username: "tester", Role: role, SessionID: "session"}))
}
req.Header.Set("X-Governance-Action", "pp-connection")
res := httptest.NewRecorder()
h.ServeHTTP(res, req)
want := 403
if role == "" {
want = 401
}
if role == roleAdmin {
want = 503
}
if res.Code != want {
t.Errorf("%s role=%q status=%d want=%d", method, role, res.Code, want)
}
}
if got := classifyRole(method, path); got != roleAdmin {
t.Errorf("%s classified=%q; credential metadata and tests must be admin only", method, got)
}
}
}
+4
View File
@@ -20,6 +20,7 @@ import (
"knowledge-governance/internal/jobs"
"knowledge-governance/internal/monitoring"
postgresstore "knowledge-governance/internal/platform/postgres"
"knowledge-governance/internal/ppauth"
"knowledge-governance/internal/qaopsai"
"knowledge-governance/internal/qaopsmirror"
"knowledge-governance/internal/qaopsorg"
@@ -224,6 +225,7 @@ type Config struct {
// DingtalkDocuments 列在线文档/表格并校验可读(只读,dws)。
DingtalkDocuments dingtalkDocLister
DWSLogin *dingtalkdiscovery.DeviceLoginManager
PPConnection *ppauth.Manager
NewID func() (string, error)
Auth *AuthConfig
}
@@ -259,6 +261,8 @@ func NewHandler(config Config) (http.Handler, error) {
}
mux := http.NewServeMux()
registerDWSLoginRoutes(mux, config)
registerPPConnectionRoutes(mux, config)
mux.HandleFunc("POST /api/v1/dingtalk-spaces/validate", func(w http.ResponseWriter, r *http.Request) { validateDWSSpace(w, r, config) })
registerQAAIRoutes(mux, config)
mux.HandleFunc("POST /api/v1/qa-ops/departments/statistics", func(w http.ResponseWriter, r *http.Request) { qaDepartmentStatistics(w, r, config) })
mux.HandleFunc("POST /api/v1/qa-ops/dashboard", func(w http.ResponseWriter, r *http.Request) { qaOperationsDashboard(w, r, config) })
+1 -1
View File
@@ -35,7 +35,7 @@ func listSourceAudit(w http.ResponseWriter, r *http.Request, config Config) {
writeJSON(w, 501, map[string]string{"error": "audit not configured"})
return
}
page, err := reader.ListSourceAudit(r.Context(), limit, offset)
page, err := combinedSourceAudit(r.Context(), reader, config.PPConnection, limit, offset)
if err != nil {
writeJSON(w, 500, map[string]string{"error": "无法读取数据源操作记录"})
return