PP 增加受控凭据更新、真实登录与目录检查,待验证修改不会替换生效配置;扫描与取件共享生效修订。 钉钉来源向导、校验与登记共用 DWS 授权,支持中途恢复与换账号保护,取消旧扫码自动回落。 认证审计复用已有来源审计页,配置响应不回传密码;补齐运行镜像脚本与权限。 验证:make verify 退出 0;PP/DWS/httpapi 目标 race 回归通过;隔离 HTTP 服务验证 PP 协议及扫描/取件消费者。 尚未部署;真实 PP 凭据与目录可用性在测试站部署后验证。
This commit is contained in:
@@ -2,12 +2,15 @@ package dingtalkdiscovery
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
)
|
||||
|
||||
// CredentialStatus contains metadata only, never credential values.
|
||||
type CredentialStatus struct {
|
||||
Identity string `json:"identity,omitempty"`
|
||||
Authenticated bool `json:"authenticated"`
|
||||
RefreshTokenValid bool `json:"refresh_token_valid"`
|
||||
ExpiresAt string `json:"expires_at,omitempty"`
|
||||
@@ -23,16 +26,23 @@ func ReadCredentialStatus(ctx context.Context, runner Runner) (CredentialStatus,
|
||||
return CredentialStatus{}, errors.New("could not read DWS credential status")
|
||||
}
|
||||
var decoded struct {
|
||||
Authenticated *bool `json:"authenticated"`
|
||||
RefreshTokenValid bool `json:"refresh_token_valid"`
|
||||
ExpiresAt string `json:"expires_at"`
|
||||
RefreshExpiresAt string `json:"refresh_expires_at"`
|
||||
CorpName string `json:"corp_name"`
|
||||
UserName string `json:"user_name"`
|
||||
Reason string `json:"reason"`
|
||||
CorpID json.RawMessage `json:"corp_id"`
|
||||
UserID json.RawMessage `json:"user_id"`
|
||||
Authenticated *bool `json:"authenticated"`
|
||||
RefreshTokenValid bool `json:"refresh_token_valid"`
|
||||
ExpiresAt string `json:"expires_at"`
|
||||
RefreshExpiresAt string `json:"refresh_expires_at"`
|
||||
CorpName string `json:"corp_name"`
|
||||
UserName string `json:"user_name"`
|
||||
Reason string `json:"reason"`
|
||||
}
|
||||
if json.Unmarshal(raw, &decoded) != nil || decoded.Authenticated == nil {
|
||||
return CredentialStatus{}, errors.New("invalid DWS credential status")
|
||||
}
|
||||
return CredentialStatus{Authenticated: *decoded.Authenticated, RefreshTokenValid: decoded.RefreshTokenValid, ExpiresAt: decoded.ExpiresAt, RefreshExpiresAt: decoded.RefreshExpiresAt, CorpName: decoded.CorpName, UserName: decoded.UserName, StatusKnown: decoded.Reason == ""}, nil
|
||||
identity := ""
|
||||
if len(decoded.CorpID) > 0 && len(decoded.UserID) > 0 && string(decoded.CorpID) != "null" && string(decoded.UserID) != "null" {
|
||||
sum := sha256.Sum256(append(append(decoded.CorpID, 0), decoded.UserID...))
|
||||
identity = hex.EncodeToString(sum[:])
|
||||
}
|
||||
return CredentialStatus{Identity: identity, Authenticated: *decoded.Authenticated, RefreshTokenValid: decoded.RefreshTokenValid, ExpiresAt: decoded.ExpiresAt, RefreshExpiresAt: decoded.RefreshExpiresAt, CorpName: decoded.CorpName, UserName: decoded.UserName, StatusKnown: decoded.Reason == ""}, nil
|
||||
}
|
||||
|
||||
@@ -21,6 +21,7 @@ import (
|
||||
|
||||
// KnowledgeBase 是一个钉钉知识库(wiki 空间)。URL 是 alidocs 空间链接,直接可用于登记来源。
|
||||
type KnowledgeBase struct {
|
||||
Registered bool `json:"registered"`
|
||||
Name string `json:"name"`
|
||||
SpaceID string `json:"space_id"`
|
||||
SpaceType string `json:"space_type"`
|
||||
@@ -30,6 +31,7 @@ type KnowledgeBase struct {
|
||||
|
||||
// DriveSpace 是一个钉盘空间(我的文件 = mySpace;组织空间 = orgSpace)。
|
||||
type DriveSpace struct {
|
||||
Registered bool `json:"registered"`
|
||||
Name string `json:"name"`
|
||||
SpaceID string `json:"space_id"`
|
||||
RootFolderID string `json:"root_folder_id,omitempty"`
|
||||
@@ -38,6 +40,7 @@ type DriveSpace struct {
|
||||
|
||||
// Result 是一次发现的结果。
|
||||
type Result struct {
|
||||
Identity string `json:"identity,omitempty"`
|
||||
KnowledgeBases []KnowledgeBase `json:"knowledge_bases"`
|
||||
DriveSpaces []DriveSpace `json:"drive_spaces"`
|
||||
// KnowledgeNotice / DriveNotice 说明「这一类为什么不全」:权限不足、未登录、或被上限截断。
|
||||
@@ -70,21 +73,26 @@ func SpaceListArgs(spaceType string) []string {
|
||||
// 知识库整体列不出来 → 返回 ErrUnavailable(页面必须提示「列不出来」,不能装成空列表)。
|
||||
// 单独一类失败、钉盘失败、或结果被上限截断 → 只丢那一部分,把原因写进对应的 Notice。
|
||||
func Discover(ctx context.Context, runner Runner) (Result, error) {
|
||||
result := Result{FetchedAt: time.Now().UTC()}
|
||||
result := Result{FetchedAt: time.Now().UTC(), KnowledgeBases: []KnowledgeBase{}, DriveSpaces: []DriveSpace{}}
|
||||
successful := 0
|
||||
causes := []error{}
|
||||
|
||||
failures := make([]string, 0, len(knowledgeSpaceTypes))
|
||||
seenKnowledge := map[string]bool{}
|
||||
for _, spaceType := range knowledgeSpaceTypes {
|
||||
raw, err := runner.RunDWS(ctx, SpaceListArgs(spaceType)...)
|
||||
if err != nil {
|
||||
failures = append(failures, describe(spaceType, err))
|
||||
failures = append(failures, describe(spaceType, failureCause(raw, err)))
|
||||
causes = append(causes, failureCause(raw, err))
|
||||
continue
|
||||
}
|
||||
bases, notice, err := parseKnowledgeBases(raw, spaceType)
|
||||
if err != nil {
|
||||
failures = append(failures, describe(spaceType, err))
|
||||
failures = append(failures, describe(spaceType, failureCause(raw, err)))
|
||||
causes = append(causes, failureCause(raw, err))
|
||||
continue
|
||||
}
|
||||
successful++
|
||||
if notice != "" {
|
||||
result.KnowledgeNotice = notice
|
||||
}
|
||||
@@ -96,9 +104,6 @@ func Discover(ctx context.Context, runner Runner) (Result, error) {
|
||||
result.KnowledgeBases = append(result.KnowledgeBases, base)
|
||||
}
|
||||
}
|
||||
if len(result.KnowledgeBases) == 0 && len(failures) > 0 {
|
||||
return result, fmt.Errorf("%w: %s", ErrUnavailable, strings.Join(failures, ";"))
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
result.KnowledgeNotice = strings.Join(append([]string{result.KnowledgeNotice}, failures...), ";")
|
||||
}
|
||||
@@ -107,14 +112,17 @@ func Discover(ctx context.Context, runner Runner) (Result, error) {
|
||||
for _, spaceType := range []string{"mySpace", "orgSpace"} {
|
||||
raw, err := runner.RunDWS(ctx, "wiki", "space", "list", "--type", spaceType)
|
||||
if err != nil {
|
||||
result.DriveNotice = err.Error()
|
||||
result.DriveNotice = "钉盘目录暂时不可用,请检查该范围权限"
|
||||
causes = append(causes, failureCause(raw, err))
|
||||
continue
|
||||
}
|
||||
spaces, err := parseDriveSpaces(raw, spaceType)
|
||||
if err != nil {
|
||||
result.DriveNotice = err.Error()
|
||||
result.DriveNotice = "钉盘目录暂时不可用,请检查该范围权限"
|
||||
causes = append(causes, failureCause(raw, err))
|
||||
continue
|
||||
}
|
||||
successful++
|
||||
for _, space := range spaces {
|
||||
if seenDrive[space.SpaceType+":"+space.SpaceID] {
|
||||
continue
|
||||
@@ -123,11 +131,21 @@ func Discover(ctx context.Context, runner Runner) (Result, error) {
|
||||
result.DriveSpaces = append(result.DriveSpaces, space)
|
||||
}
|
||||
}
|
||||
if successful == 0 && len(causes) > 0 {
|
||||
return result, fmt.Errorf("%w: %w", ErrUnavailable, errors.Join(causes...))
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func describe(scope string, err error) string {
|
||||
return scope + ":" + err.Error()
|
||||
reason := "读取失败,请重试"
|
||||
if errors.Is(err, ErrCredentials) {
|
||||
reason = "DWS 授权已失效"
|
||||
}
|
||||
if errors.Is(err, ErrPermission) {
|
||||
reason = "当前范围权限不足"
|
||||
}
|
||||
return scope + ":" + reason
|
||||
}
|
||||
|
||||
// parseKnowledgeBases 解析 `dws wiki +space-list`:
|
||||
|
||||
@@ -127,7 +127,7 @@ func TestDiscoverKeepsKnowledgeBasesWhenDriveIsDenied(t *testing.T) {
|
||||
if len(result.DriveSpaces) != 0 {
|
||||
t.Fatalf("drive spaces = %d, want 0", len(result.DriveSpaces))
|
||||
}
|
||||
if !strings.Contains(result.DriveNotice, "permission denied") {
|
||||
if !strings.Contains(result.DriveNotice, "权限") {
|
||||
t.Fatalf("drive notice = %q", result.DriveNotice)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
package dingtalkdiscovery
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var ErrCredentials = errors.New("DWS authorization required")
|
||||
var ErrPermission = errors.New("DWS directory permission denied")
|
||||
|
||||
// failureCause inspects only structured CLI errors; no upstream text is returned.
|
||||
func failureCause(raw []byte, cause error) error {
|
||||
var v struct {
|
||||
Error struct {
|
||||
Type string `json:"type"`
|
||||
Code any `json:"code"`
|
||||
Message string `json:"message"`
|
||||
} `json:"error"`
|
||||
}
|
||||
if json.Unmarshal(raw, &v) != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
text := strings.ToLower(v.Error.Type + " " + fmt.Sprint(v.Error.Code) + " " + v.Error.Message)
|
||||
for _, key := range []string{"permission", "forbidden", "scope", "access denied", "权限", "403"} {
|
||||
if strings.Contains(text, key) {
|
||||
return ErrPermission
|
||||
}
|
||||
}
|
||||
for _, key := range []string{"unauth", "not_logged_in", "not logged", "login_required", "login required", "authentication", "auth_required", "credential", "token_expired", "invalid_token", "token expired", "invalid_grant", "未登录", "授权已过期", "授权失效"} {
|
||||
if strings.Contains(text, key) {
|
||||
return ErrCredentials
|
||||
}
|
||||
}
|
||||
if errors.Is(cause, ErrCredentials) || errors.Is(cause, ErrPermission) {
|
||||
return cause
|
||||
}
|
||||
return ErrUnavailable
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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})
|
||||
|
||||
@@ -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())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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 == ""
|
||||
}
|
||||
@@ -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())
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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})
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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) })
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/url"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// RegisteredDingtalkSpaceIDs also covers historical connections whose root key
|
||||
// predates DWS; a source name is never an identity.
|
||||
func (s *Store) RegisteredDingtalkSpaceIDs(ctx context.Context) (map[string]bool, error) {
|
||||
rows, err := s.db.Query(ctx, "SELECT base_url FROM source_connections WHERE source_type='dingtalk' AND archived_at IS NULL")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
result := map[string]bool{}
|
||||
for rows.Next() {
|
||||
var raw string
|
||||
if err := rows.Scan(&raw); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
u, err := url.Parse(raw)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
space := u.Query().Get("space")
|
||||
if space == "" && strings.HasPrefix(u.Path, "spaces/") {
|
||||
space = strings.TrimPrefix(u.Path, "spaces/")
|
||||
}
|
||||
if space != "" {
|
||||
result[space] = true
|
||||
}
|
||||
}
|
||||
return result, rows.Err()
|
||||
}
|
||||
@@ -0,0 +1,356 @@
|
||||
package ppauth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Credentials struct {
|
||||
ID string `json:"id"`
|
||||
BaseURL string `json:"base_url"`
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
type Draft struct {
|
||||
BaseURL string `json:"base_url"`
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password,omitempty"`
|
||||
PendingID string `json:"pending_id,omitempty"`
|
||||
Revision int `json:"revision"`
|
||||
}
|
||||
type Observation struct {
|
||||
State string `json:"state"`
|
||||
Message string `json:"message"`
|
||||
CheckedAt string `json:"checked_at"`
|
||||
Previous *Observation `json:"previous,omitempty"`
|
||||
}
|
||||
type Metadata struct {
|
||||
ID string `json:"id"`
|
||||
BaseURL string `json:"base_url"`
|
||||
Username string `json:"username"`
|
||||
PasswordConfigured bool `json:"password_configured"`
|
||||
}
|
||||
type View struct {
|
||||
Revision int `json:"revision"`
|
||||
Active *Metadata `json:"active"`
|
||||
Pending *Metadata `json:"pending"`
|
||||
Observation *Observation `json:"observation"`
|
||||
PendingObservation *Observation `json:"pending_observation"`
|
||||
}
|
||||
type AuditEvent struct {
|
||||
ID string `json:"id"`
|
||||
SourceName string `json:"source_name"`
|
||||
Action string `json:"action"`
|
||||
Actor string `json:"actor"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
Detail string `json:"detail"`
|
||||
}
|
||||
type State struct {
|
||||
Revision int `json:"revision"`
|
||||
Active *Credentials `json:"active"`
|
||||
Pending *Credentials `json:"pending"`
|
||||
Observation *Observation `json:"observation"`
|
||||
PendingObservation *Observation `json:"pending_observation"`
|
||||
Audit []AuditEvent `json:"audit"`
|
||||
}
|
||||
type Manager struct {
|
||||
Path string
|
||||
LegacyPath string
|
||||
Probe func(context.Context, Credentials) Observation
|
||||
}
|
||||
|
||||
var ErrRejected = errors.New("PP 配置校验未通过,原配置保留")
|
||||
var ErrInvalid = errors.New("API 地址必须为 HTTPS 根地址,且不能包含凭据、查询参数或片段")
|
||||
var ErrConflict = errors.New("配置已被更新,请刷新后重新提交")
|
||||
|
||||
func ValidateBaseURL(raw string) bool {
|
||||
u, err := url.Parse(raw)
|
||||
return err == nil && len(raw) <= 300 && strings.TrimSpace(raw) == raw && u.Scheme == "https" && u.Host != "" && u.Hostname() != "" && u.Opaque == "" && u.User == nil && u.RawQuery == "" && !u.ForceQuery && u.Fragment == "" && !strings.Contains(raw, "#") && (u.Path == "" || u.Path == "/")
|
||||
}
|
||||
func metadata(c *Credentials) *Metadata {
|
||||
if c == nil {
|
||||
return nil
|
||||
}
|
||||
return &Metadata{ID: c.ID, BaseURL: c.BaseURL, Username: c.Username, PasswordConfigured: c.Password != ""}
|
||||
}
|
||||
func view(s State) View {
|
||||
return View{Revision: s.Revision, Active: metadata(s.Active), Pending: metadata(s.Pending), Observation: s.Observation, PendingObservation: s.PendingObservation}
|
||||
}
|
||||
func randomID() string {
|
||||
var b [16]byte
|
||||
if _, err := rand.Read(b[:]); err != nil {
|
||||
panic("secure random unavailable")
|
||||
}
|
||||
return hex.EncodeToString(b[:])
|
||||
}
|
||||
func (m *Manager) locked(ctx context.Context, fn func(*State) (bool, error)) error {
|
||||
if !filepath.IsAbs(m.Path) {
|
||||
return errors.New("PP credential storage path is invalid")
|
||||
}
|
||||
dir := filepath.Dir(m.Path)
|
||||
if err := os.MkdirAll(dir, 0700); err != nil {
|
||||
return errors.New("PP 配置存储不可用")
|
||||
}
|
||||
info, err := os.Lstat(dir)
|
||||
if err != nil || !info.IsDir() || info.Mode().Perm()&0077 != 0 {
|
||||
return errors.New("PP 配置目录权限必须为 0700")
|
||||
}
|
||||
lockPath := m.Path + ".lock"
|
||||
if info, e := os.Lstat(lockPath); e == nil && (info.Mode()&os.ModeSymlink != 0 || info.Mode().Perm()&0077 != 0) {
|
||||
return errors.New("PP 配置锁权限不安全")
|
||||
}
|
||||
lock, err := os.OpenFile(lockPath, os.O_CREATE|os.O_RDWR, 0600)
|
||||
if err != nil {
|
||||
return errors.New("PP 配置存储不可用")
|
||||
}
|
||||
defer lock.Close()
|
||||
for {
|
||||
err = syscall.Flock(int(lock.Fd()), syscall.LOCK_EX|syscall.LOCK_NB)
|
||||
if err == nil {
|
||||
break
|
||||
}
|
||||
if err != syscall.EWOULDBLOCK {
|
||||
return errors.New("PP 配置锁不可用")
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-time.After(20 * time.Millisecond):
|
||||
}
|
||||
}
|
||||
defer syscall.Flock(int(lock.Fd()), syscall.LOCK_UN)
|
||||
var s State
|
||||
info, err = os.Lstat(m.Path)
|
||||
if err == nil {
|
||||
if info.Mode()&os.ModeSymlink != 0 || !info.Mode().IsRegular() || info.Mode().Perm()&0077 != 0 || info.Size() > 16<<20 {
|
||||
return errors.New("PP 凭据文件权限或格式不安全")
|
||||
}
|
||||
raw, e := os.ReadFile(m.Path)
|
||||
if e != nil || json.Unmarshal(raw, &s) != nil {
|
||||
return errors.New("无法读取 PP 配置")
|
||||
}
|
||||
} else if !errors.Is(err, os.ErrNotExist) {
|
||||
return errors.New("无法读取 PP 配置")
|
||||
} else if m.LegacyPath != "" {
|
||||
raw, e := os.ReadFile(m.LegacyPath)
|
||||
if e == nil {
|
||||
var c Credentials
|
||||
if json.Unmarshal(raw, &c) != nil {
|
||||
return errors.New("旧 PP 配置格式不正确")
|
||||
}
|
||||
if c.BaseURL == "" {
|
||||
c.BaseURL = "https://api.dobot.cn"
|
||||
}
|
||||
c.ID = "legacy"
|
||||
s.Active = &c
|
||||
} else if !errors.Is(e, os.ErrNotExist) {
|
||||
return errors.New("无法读取旧 PP 配置")
|
||||
}
|
||||
}
|
||||
changed, err := fn(&s)
|
||||
if err != nil || !changed {
|
||||
return err
|
||||
}
|
||||
raw, err := json.Marshal(s)
|
||||
if err != nil {
|
||||
return errors.New("PP 配置保存失败")
|
||||
}
|
||||
f, err := os.CreateTemp(dir, ".pp-next-")
|
||||
if err != nil {
|
||||
return errors.New("PP 配置保存失败")
|
||||
}
|
||||
tmp := f.Name()
|
||||
defer os.Remove(tmp)
|
||||
if err = f.Chmod(0600); err == nil {
|
||||
_, err = f.Write(raw)
|
||||
}
|
||||
if err == nil {
|
||||
err = f.Sync()
|
||||
}
|
||||
closeErr := f.Close()
|
||||
if err == nil {
|
||||
err = closeErr
|
||||
}
|
||||
if err == nil {
|
||||
err = os.Rename(tmp, m.Path)
|
||||
}
|
||||
if err != nil {
|
||||
return errors.New("PP 配置保存失败")
|
||||
}
|
||||
d, e := os.Open(dir)
|
||||
if e != nil {
|
||||
return errors.New("PP 配置持久化未确认")
|
||||
}
|
||||
defer d.Close()
|
||||
if d.Sync() != nil {
|
||||
return errors.New("PP 配置持久化未确认")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (m *Manager) View() (v View, err error) {
|
||||
err = m.locked(context.Background(), func(s *State) (bool, error) { v = view(*s); return false, nil })
|
||||
return
|
||||
}
|
||||
func (m *Manager) snapshot(ctx context.Context) (s State, err error) {
|
||||
err = m.locked(ctx, func(state *State) (bool, error) { s = *state; return false, nil })
|
||||
return
|
||||
}
|
||||
func candidate(s State, d Draft) (Credentials, error) {
|
||||
if !ValidateBaseURL(d.BaseURL) {
|
||||
return Credentials{}, ErrInvalid
|
||||
}
|
||||
if len(d.Username) > 255 || strings.ContainsAny(d.Username, "\n\r\x00") || len(d.Password) > 8192 {
|
||||
return Credentials{}, errors.New("账号或密码格式不正确")
|
||||
}
|
||||
c := Credentials{ID: randomID(), BaseURL: strings.TrimRight(d.BaseURL, "/"), Username: strings.TrimSpace(d.Username), Password: d.Password}
|
||||
if c.Password == "" && d.PendingID != "" {
|
||||
if s.Pending == nil || s.Pending.ID != d.PendingID {
|
||||
return Credentials{}, ErrConflict
|
||||
}
|
||||
c.Password = s.Pending.Password
|
||||
} else if c.Password == "" && s.Active != nil {
|
||||
c.Password = s.Active.Password
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
func same(a, b *Credentials) bool {
|
||||
return a != nil && b != nil && a.BaseURL == b.BaseURL && a.Username == b.Username && a.Password == b.Password
|
||||
}
|
||||
func (m *Manager) probe(ctx context.Context, c Credentials) Observation {
|
||||
o := Observation{State: "incomplete", Message: "配置未完成,请填写账号和密码"}
|
||||
if c.Username != "" && c.Password != "" {
|
||||
if m.Probe == nil {
|
||||
o = Observation{State: "unavailable", Message: "PP 检查服务未接通"}
|
||||
} else {
|
||||
o = m.Probe(ctx, c)
|
||||
}
|
||||
}
|
||||
switch o.State {
|
||||
case "valid", "auth_failed", "permission_denied", "incomplete", "unavailable", "invalid_response":
|
||||
default:
|
||||
o = Observation{State: "unavailable", Message: "检查结果不可识别,请重试"}
|
||||
}
|
||||
if o.CheckedAt == "" {
|
||||
o.CheckedAt = time.Now().UTC().Format(time.RFC3339Nano)
|
||||
}
|
||||
return o
|
||||
}
|
||||
func addAudit(s *State, source, action, actor, detail string) {
|
||||
s.Audit = append(s.Audit, AuditEvent{ID: "auth-" + randomID(), SourceName: source, Action: action, Actor: actor, CreatedAt: time.Now().UTC(), Detail: detail})
|
||||
}
|
||||
func retainObservation(old *Observation, next Observation) *Observation {
|
||||
if next.State == "unavailable" && old != nil {
|
||||
if old.State == "unavailable" && old.Previous != nil {
|
||||
next.Previous = old.Previous
|
||||
} else {
|
||||
next.Previous = old
|
||||
}
|
||||
}
|
||||
return &next
|
||||
}
|
||||
func (m *Manager) Save(ctx context.Context, d Draft, actor string) (v View, err error) {
|
||||
s, err := m.snapshot(ctx)
|
||||
if err != nil {
|
||||
return v, err
|
||||
}
|
||||
if s.Revision != d.Revision {
|
||||
return v, ErrConflict
|
||||
}
|
||||
c, err := candidate(s, d)
|
||||
if err != nil {
|
||||
return v, err
|
||||
}
|
||||
o := m.probe(ctx, c)
|
||||
rejected := o.State == "auth_failed" || o.State == "permission_denied" || o.State == "invalid_response"
|
||||
err = m.locked(ctx, func(current *State) (bool, error) {
|
||||
if current.Revision != s.Revision {
|
||||
return false, ErrConflict
|
||||
}
|
||||
if rejected {
|
||||
if same(current.Active, &c) {
|
||||
current.Observation = retainObservation(current.Observation, o)
|
||||
}
|
||||
addAudit(current, "PP 资料下载中心", "credential_rejected", actor, o.Message)
|
||||
v = view(*current)
|
||||
return true, nil
|
||||
}
|
||||
current.Revision++
|
||||
if o.State == "valid" {
|
||||
current.Active = &c
|
||||
current.Pending = nil
|
||||
current.Observation = retainObservation(current.Observation, o)
|
||||
current.PendingObservation = nil
|
||||
} else {
|
||||
current.Pending = &c
|
||||
current.PendingObservation = &o
|
||||
}
|
||||
detail := "认证配置已保存并生效"
|
||||
if o.State != "valid" {
|
||||
detail = "修改已保存为待验证,未替换生效配置"
|
||||
}
|
||||
if d.Password != "" {
|
||||
detail += ";密码已更新"
|
||||
}
|
||||
addAudit(current, "PP 资料下载中心", "credential_configured", actor, detail)
|
||||
v = view(*current)
|
||||
return true, nil
|
||||
})
|
||||
if err == nil && rejected {
|
||||
err = fmt.Errorf("%w:%s", ErrRejected, o.Message)
|
||||
}
|
||||
return
|
||||
}
|
||||
func (m *Manager) Test(ctx context.Context, d Draft, actor string) (o Observation, err error) {
|
||||
s, err := m.snapshot(ctx)
|
||||
if err != nil {
|
||||
return o, err
|
||||
}
|
||||
if s.Revision != d.Revision {
|
||||
return o, ErrConflict
|
||||
}
|
||||
c, err := candidate(s, d)
|
||||
if err != nil {
|
||||
return o, err
|
||||
}
|
||||
o = m.probe(ctx, c)
|
||||
err = m.locked(ctx, func(current *State) (bool, error) {
|
||||
if current.Revision != s.Revision {
|
||||
return false, ErrConflict
|
||||
}
|
||||
if same(current.Active, &c) {
|
||||
current.Observation = retainObservation(current.Observation, o)
|
||||
}
|
||||
addAudit(current, "PP 资料下载中心", "credential_test", actor, o.Message)
|
||||
return true, nil
|
||||
})
|
||||
return
|
||||
}
|
||||
func (m *Manager) Audit(ctx context.Context, source, action, actor, detail string) error {
|
||||
return m.locked(ctx, func(s *State) (bool, error) { addAudit(s, source, action, actor, detail); return true, nil })
|
||||
}
|
||||
func (m *Manager) AuditOnce(ctx context.Context, id, source, action, actor, detail string) error {
|
||||
return m.locked(ctx, func(s *State) (bool, error) {
|
||||
for _, e := range s.Audit {
|
||||
if e.ID == id {
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
addAudit(s, source, action, actor, detail)
|
||||
s.Audit[len(s.Audit)-1].ID = id
|
||||
return true, nil
|
||||
})
|
||||
}
|
||||
func (m *Manager) Events(ctx context.Context) (events []AuditEvent, err error) {
|
||||
err = m.locked(ctx, func(s *State) (bool, error) { events = append(events, s.Audit...); return false, nil })
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package ppauth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSaveValidatesBeforeActivationAndTransientKeepsActive(t *testing.T) {
|
||||
state := "valid"
|
||||
seen := ""
|
||||
manager := &Manager{Path: t.TempDir() + "/credentials/settings.json", Probe: func(_ context.Context, c Credentials) Observation {
|
||||
seen = c.Password
|
||||
return Observation{State: state, Message: state}
|
||||
}}
|
||||
view, err := manager.Save(context.Background(), Draft{BaseURL: "https://api.example.invalid", Username: "example", Password: "example-password", Revision: 0}, "tester")
|
||||
if err != nil || view.Active == nil || view.Active.Username != "example" || !view.Active.PasswordConfigured || seen != "example-password" {
|
||||
t.Fatalf("validated save did not activate: %+v %v", view, err)
|
||||
}
|
||||
activeID := view.Active.ID
|
||||
state = "unavailable"
|
||||
view, err = manager.Save(context.Background(), Draft{BaseURL: "https://changed.example.invalid", Username: "changed", Revision: view.Revision}, "tester")
|
||||
if err != nil || view.Active == nil || view.Active.ID != activeID || view.Pending == nil || view.Pending.Username != "changed" || seen != "example-password" {
|
||||
t.Fatalf("transient save replaced active or lost password: %+v %v", view, err)
|
||||
}
|
||||
state = "auth_failed"
|
||||
_, err = manager.Save(context.Background(), Draft{BaseURL: "https://changed.example.invalid", Username: "changed", Password: "bad-example", Revision: view.Revision}, "tester")
|
||||
if !errors.Is(err, ErrRejected) {
|
||||
t.Fatalf("explicit rejection allowed activation: %v", err)
|
||||
}
|
||||
after, _ := manager.View()
|
||||
if after.Active.ID != activeID {
|
||||
t.Fatal("rejection changed active config")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
package ppauth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestPendingPasswordSurvivesRevalidationWithoutReturningSecrets(t *testing.T) {
|
||||
state := "valid"
|
||||
seen := ""
|
||||
m := &Manager{Path: t.TempDir() + "/credentials/settings.json", Probe: func(_ context.Context, c Credentials) Observation {
|
||||
seen = c.Password
|
||||
return Observation{State: state, Message: state}
|
||||
}}
|
||||
v, err := m.Save(context.Background(), Draft{BaseURL: "https://api.example.invalid", Username: "example", Password: "example-old"}, "tester")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
state = "unavailable"
|
||||
v, err = m.Save(context.Background(), Draft{BaseURL: "https://api.example.invalid", Username: "example", Password: "example-new", Revision: v.Revision}, "tester")
|
||||
if err != nil || v.Pending == nil {
|
||||
t.Fatalf("pending save: %v", err)
|
||||
}
|
||||
state = "valid"
|
||||
v, err = m.Save(context.Background(), Draft{BaseURL: v.Pending.BaseURL, Username: v.Pending.Username, PendingID: v.Pending.ID, Revision: v.Revision}, "tester")
|
||||
if err != nil || seen != "example-new" || v.Pending != nil {
|
||||
t.Fatal("saved pending password was not reused")
|
||||
}
|
||||
raw, _ := json.Marshal(v)
|
||||
if strings.Contains(string(raw), "example-new") || strings.Contains(string(raw), `"password":`) {
|
||||
t.Fatal("metadata leaked secret")
|
||||
}
|
||||
info, err := os.Stat(m.Path)
|
||||
if err != nil || info.Mode().Perm() != 0600 {
|
||||
t.Fatal("secret file not mode 0600")
|
||||
}
|
||||
}
|
||||
func TestConcurrentSavesCannotOverwriteANewerRevision(t *testing.T) {
|
||||
var calls atomic.Int32
|
||||
barrier := make(chan struct{})
|
||||
m := &Manager{Path: t.TempDir() + "/credentials/settings.json", Probe: func(_ context.Context, c Credentials) Observation {
|
||||
if calls.Add(1) == 2 {
|
||||
close(barrier)
|
||||
}
|
||||
<-barrier
|
||||
return Observation{State: "valid", Message: "valid"}
|
||||
}}
|
||||
outcomes := make(chan error, 2)
|
||||
var wg sync.WaitGroup
|
||||
for _, name := range []string{"example-one", "example-two"} {
|
||||
wg.Add(1)
|
||||
go func(user string) {
|
||||
defer wg.Done()
|
||||
_, err := m.Save(context.Background(), Draft{BaseURL: "https://api.example.invalid", Username: user, Password: "example-password"}, "tester")
|
||||
outcomes <- err
|
||||
}(name)
|
||||
}
|
||||
wg.Wait()
|
||||
close(outcomes)
|
||||
success, conflict := 0, 0
|
||||
for err := range outcomes {
|
||||
if err == nil {
|
||||
success++
|
||||
} else if errors.Is(err, ErrConflict) {
|
||||
conflict++
|
||||
} else {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if success != 1 || conflict != 1 {
|
||||
t.Fatalf("success=%d conflict=%d", success, conflict)
|
||||
}
|
||||
}
|
||||
func TestFailedObservationRetainsPreviousSuccess(t *testing.T) {
|
||||
state := "valid"
|
||||
m := &Manager{Path: t.TempDir() + "/credentials/settings.json", Probe: func(_ context.Context, c Credentials) Observation { return Observation{State: state, Message: state} }}
|
||||
v, err := m.Save(context.Background(), Draft{BaseURL: "https://api.example.invalid", Username: "example", Password: "example-password"}, "tester")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
state = "unavailable"
|
||||
_, err = m.Test(context.Background(), Draft{BaseURL: v.Active.BaseURL, Username: v.Active.Username, Revision: v.Revision}, "tester")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
v, err = m.View()
|
||||
if err != nil || v.Observation.Previous == nil || v.Observation.Previous.State != "valid" {
|
||||
t.Fatal("failed check erased previous successful observation")
|
||||
}
|
||||
}
|
||||
func TestPPPythonProtocolAndConfigurationConsumers(t *testing.T) {
|
||||
command := exec.Command("python3", "-m", "unittest", "discover", "-s", "../../scripts", "-p", "test_pp_client.py", "-v")
|
||||
output, err := command.CombinedOutput()
|
||||
if err != nil {
|
||||
t.Fatalf("PP protocol regression: %v\n%s", err, output)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package ppauth
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"os/exec"
|
||||
"time"
|
||||
)
|
||||
|
||||
// CommandProbe reuses the worker's read-only PP adapter; secrets travel on stdin.
|
||||
func CommandProbe(python, script string) func(context.Context, Credentials) Observation {
|
||||
return func(ctx context.Context, c Credentials) Observation {
|
||||
ctx, cancel := context.WithTimeout(ctx, 45*time.Second)
|
||||
defer cancel()
|
||||
raw, _ := json.Marshal(c)
|
||||
command := exec.CommandContext(ctx, python, script)
|
||||
command.Stdin = bytes.NewReader(raw)
|
||||
command.Env = []string{"PATH=" + os.Getenv("PATH"), "PYTHONUNBUFFERED=1"}
|
||||
out, err := command.Output()
|
||||
if err != nil || len(out) > 8192 {
|
||||
return Observation{State: "unavailable", Message: "PP 检查服务暂不可用,请重试"}
|
||||
}
|
||||
var o Observation
|
||||
if json.Unmarshal(out, &o) != nil {
|
||||
return Observation{State: "unavailable", Message: "PP 检查结果不可识别"}
|
||||
}
|
||||
return o
|
||||
}
|
||||
}
|
||||
@@ -181,7 +181,7 @@ func NewCommandRunner(pythonPath, scriptPath, spoolRoot, spoolPrefix string, max
|
||||
// ——钉钉取件在真实链路上会整体失败(2026-10-10 端到端验收实测;脚本单跑正常,
|
||||
// 因为那只绕过了这个白名单)。
|
||||
var dwsEnvNames = []string{
|
||||
"ARTIFACT_DINGTALK_FETCHER", "DWS_BIN", "DWS_CONFIG_DIR", "DWS_HOME", "DWS_DISABLE_KEYCHAIN",
|
||||
"ARTIFACT_DINGTALK_FETCHER", "PP_AUTH_STATE_FILE", "PP_LEGACY_CREDENTIALS_FILE", "DWS_BIN", "DWS_CONFIG_DIR", "DWS_HOME", "DWS_DISABLE_KEYCHAIN",
|
||||
}
|
||||
|
||||
func forwardedDWSEnv() []string {
|
||||
|
||||
Reference in New Issue
Block a user