Files
knowledge-governance/internal/httpapi/pp_auth_roundtrip_test.go
T
姚章浩 3825859da6
build / build (push) Successful in 2m20s
feat(settings): 打通 PP 认证配置并统一 DWS 来源授权
PP 增加受控凭据更新、真实登录与目录检查,待验证修改不会替换生效配置;扫描与取件共享生效修订。
钉钉来源向导、校验与登记共用 DWS 授权,支持中途恢复与换账号保护,取消旧扫码自动回落。
认证审计复用已有来源审计页,配置响应不回传密码;补齐运行镜像脚本与权限。

验证:make verify 退出 0;PP/DWS/httpapi 目标 race 回归通过;隔离 HTTP 服务验证 PP 协议及扫描/取件消费者。
尚未部署;真实 PP 凭据与目录可用性在测试站部署后验证。
2026-11-17 19:08:46 +08:00

143 lines
5.3 KiB
Go

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)
}
}
}
}