test(library): 隔离数据契约与 r11 身份自然键矩阵

真实本机 PG/ES/MinIO:v071 目录镜像 10 模式、结构引用/游标 15 模式、
8 表×2 外部范围身份矩阵、13 模式自然键(含软删除与合法同 parent 正例)、
备份期间三注入、收尾故障与授权撤销两个真实治理 PG 用例。

需隔离服务的用例在 test-scope.json 显式声明:普通 CI 跳过不算通过。
This commit is contained in:
姚章浩
2026-11-01 11:35:09 +08:00
parent 5eef13b615
commit 8febe12d7d
62 changed files with 7329 additions and 167 deletions
@@ -45,6 +45,21 @@ func (s *baselineMutexStore) CreateLibraryJob(ctx context.Context, job governanc
return s.fakeLibraryStore.CreateLibraryJob(ctx, job, stages, now)
}
func (s *baselineMutexStore) CreateLibraryDispatch(ctx context.Context, job governance.LibraryJob, stages []string, handoff bool, now time.Time) (governance.LibraryJob, bool, error) {
if s.activeByScope == nil {
s.activeByScope = map[string]string{}
}
if s.activeByScope[job.Scope] != "" {
return governance.LibraryJob{}, false, governance.ErrLibraryJobActive
}
created, reused, err := s.fakeLibraryStore.CreateLibraryDispatch(ctx, job, stages, handoff, now)
if err == nil {
s.activeByScope[job.Scope] = created.ID
s.enqueues++
}
return created, reused, err
}
func (s *baselineMutexStore) Enqueue(ctx context.Context, request jobs.EnqueueRequest, now time.Time) (*jobs.Job, error) {
s.enqueues++
return s.fakeLibraryStore.fakeJobStore.Enqueue(ctx, request, now)
@@ -0,0 +1,33 @@
package httpapi
import (
"context"
"knowledge-governance/internal/governance"
"knowledge-governance/internal/jobs"
"time"
)
// In-memory API fixture mirrors dispatch shape; atomicity is tested against PG.
func (s *fakeLibraryStore) CreateLibraryDispatch(ctx context.Context, job governance.LibraryJob, stages []string, handoff bool, now time.Time) (governance.LibraryJob, bool, error) {
created, reused, err := s.CreateLibraryJob(ctx, job, stages, now)
if err != nil {
return created, reused, err
}
if reused && (created.State != governance.LibraryJobPending || created.QueueJobID != "") {
return created, reused, nil
}
id, kind, payload, err := governance.LibraryQueueRequest(handoff, created.ID, created.Scope, created.TargetSnapshotID, "library."+string(created.Kind))
if err != nil {
return created, reused, err
}
queued, err := s.Enqueue(ctx, jobs.EnqueueRequest{ID: id, Type: kind, Payload: payload, AvailableAt: now, MaxAttempts: 1, IdempotencyKey: kind + ".queue:" + created.ID}, now)
if err != nil {
s.lastJob = governance.LibraryJob{}
return governance.LibraryJob{}, false, err
}
if err = s.AttachLibraryQueueJob(ctx, created.ID, queued.ID, now); err != nil {
return created, reused, err
}
created.QueueJobID = queued.ID
return created, reused, nil
}
+8
View File
@@ -18,6 +18,7 @@ import (
// 复用既有 fakeJobStore 提供 Store 的其余方法,只覆盖整库作业这几个。
type fakeLibraryStore struct {
sourceCandidate *governance.LibraryVersion
fakeJobStore
grant *governance.LibraryReleaseAuthorization
versions []governance.LibraryVersion
@@ -345,8 +346,11 @@ func TestLibrarySyncEnqueueCreatesJobOnlyWithGrant(t *testing.T) {
store.enqueueEchoRequestedID = true
config := Config{Store: store, ProductionReleaseRequestsEnabled: true, ProductionBackupRestoreVerified: true,
LibraryProductionDatabaseURL: "postgres://prod.invalid/db", LibraryProductionInternalKB: "kb-int", LibraryCapacityBudgetBytes: 1 << 40}
sourceID := bindSourceFixture(t, &config, store, &target)
digest, _ = librarySyncParamsDigest("internal", target)
body := `{"scope":"internal","target_snapshot_id":"` + target + `"}`
body = sourceRequestBody(t, body, sourceID)
// 先没有授权
recorder := httptest.NewRecorder()
librarySyncEnqueue(recorder, httptest.NewRequest(http.MethodPost, "/api/v1/library/syncs", strings.NewReader(body)), config)
@@ -393,6 +397,7 @@ func TestLibraryOverviewShowsLatestPrebackupWhenTargetDiffers(t *testing.T) {
SnapshotID: sealed, CreatedAt: now.Add(-2 * time.Hour)},
}}
config := Config{Store: store, LibraryArchiveRoot: root, LibraryCapacityBudgetBytes: 1 << 30}
bindSourceFixture(t, &config, store, &sealed)
request := httptest.NewRequest(http.MethodGet, "/api/v1/library/overview?scope=internal", nil)
recorder := httptest.NewRecorder()
libraryOverviewHandler(recorder, request, config)
@@ -510,7 +515,10 @@ func TestLibrarySyncEnqueueUsesExactCurrentVersionBeyondWindow(t *testing.T) {
config := Config{Store: store, ProductionReleaseRequestsEnabled: true, ProductionBackupRestoreVerified: true,
LibraryProductionDatabaseURL: "postgres://prod.invalid/db", LibraryProductionInternalKB: "kb-int",
LibraryCapacityBudgetBytes: 1 << 40}
sourceID := bindSourceFixture(t, &config, store, &target)
digest, _ = librarySyncParamsDigest("internal", target)
body := `{"scope":"internal","target_snapshot_id":"` + target + `"}`
body = sourceRequestBody(t, body, sourceID)
recorder := httptest.NewRecorder()
librarySyncEnqueue(recorder, httptest.NewRequest(http.MethodPost, "/api/v1/library/syncs", strings.NewReader(body)), config)
if recorder.Code != http.StatusAccepted {
+14 -5
View File
@@ -18,7 +18,8 @@ import (
// 判据:换 operation_key ⇒ 新 operation(ID 不同、作业幂等键不同);
// 同一个 operation_key ⇒ 同一 operation(重放)。
func TestLibrarySyncNewIntentReExecutesInsteadOfReusingHistory(t *testing.T) {
target := "snap-1"
root := libraryFixtureRoot(t)
target := sealSharedVersions(t, root, 1, 4)[0]
digest, err := librarySyncParamsDigest("internal", target)
if err != nil {
t.Fatal(err)
@@ -36,14 +37,19 @@ func TestLibrarySyncNewIntentReExecutesInsteadOfReusingHistory(t *testing.T) {
return store
}
config := func(store *fakeLibraryStore) Config {
return Config{Store: store, ProductionReleaseRequestsEnabled: true, ProductionBackupRestoreVerified: true,
c := Config{Store: store, LibraryArchiveRoot: root, ProductionReleaseRequestsEnabled: true, ProductionBackupRestoreVerified: true,
LibraryProductionDatabaseURL: "postgres://prod.invalid/db", LibraryProductionInternalKB: "kb-int",
LibraryCapacityBudgetBytes: 1 << 40}
bindSourceFixture(t, &c, store, &target)
return c
}
post := func(store *fakeLibraryStore, body string) *httptest.ResponseRecorder {
c := config(store)
id, _ := configuredLibrarySource(c, "internal").ID()
body = sourceRequestBody(t, body, id)
recorder := httptest.NewRecorder()
librarySyncEnqueue(recorder, httptest.NewRequest(http.MethodPost, "/api/v1/library/syncs",
strings.NewReader(body)), config(store))
strings.NewReader(body)), c)
return recorder
}
withKey := `{"scope":"internal","target_snapshot_id":"` + target + `","operation_key":"%s"}`
@@ -85,7 +91,8 @@ func TestLibrarySyncNewIntentReExecutesInsteadOfReusingHistory(t *testing.T) {
// 同一个意图键配上不同快照 = 冲突,不能悄悄共享谱系。
func TestLibrarySyncIntentKeyReusedWithAnotherSnapshotConflicts(t *testing.T) {
target := "snap-1"
root := libraryFixtureRoot(t)
target := sealSharedVersions(t, root, 1, 4)[0]
digest, _ := librarySyncParamsDigest("internal", target)
now := time.Now().UTC()
store := &fakeLibraryStore{current: &governance.LibraryVersion{ID: "ver-prod", Scope: "internal",
@@ -101,7 +108,9 @@ func TestLibrarySyncIntentKeyReusedWithAnotherSnapshotConflicts(t *testing.T) {
config := Config{Store: store, ProductionReleaseRequestsEnabled: true, ProductionBackupRestoreVerified: true,
LibraryProductionDatabaseURL: "postgres://prod.invalid/db", LibraryProductionInternalKB: "kb-int",
LibraryCapacityBudgetBytes: 1 << 40}
body := `{"scope":"internal","target_snapshot_id":"` + target + `","operation_key":"intent-1"}`
config.LibraryArchiveRoot = root
sourceID := bindSourceFixture(t, &config, store, &target)
body := sourceRequestBody(t, `{"scope":"internal","target_snapshot_id":"`+target+`","operation_key":"intent-1"}`, sourceID)
recorder := httptest.NewRecorder()
librarySyncEnqueue(recorder, httptest.NewRequest(http.MethodPost, "/api/v1/library/syncs", strings.NewReader(body)), config)
if recorder.Code != http.StatusConflict {
@@ -0,0 +1,67 @@
package httpapi
import (
"context"
"errors"
"knowledge-governance/internal/governance"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)
type legacySourceAPIStore struct {
fakeLibraryStore
calls int
actor string
source governance.LibrarySourceIdentity
err error
}
func (s *legacySourceAPIStore) BindLegacyLibrarySource(_ context.Context, _ string, _ string, source governance.LibrarySourceIdentity, actor string, _ time.Time) error {
s.calls++
s.actor = actor
s.source = source
return s.err
}
func TestContractLegacySourceAssociationAPI(t *testing.T) {
for _, role := range []string{roleViewer, roleEngineer, roleAdmin} {
store := &legacySourceAPIStore{}
config := Config{Store: store, LibrarySourceProject: "configured-project", LibrarySourceApp: "configured-app", LibrarySourceTenantID: 10000, LibrarySourceInternalKB: "configured-kb"}
request := httptest.NewRequest(http.MethodPost, "/api/v1/library/source-associations", strings.NewReader(`{"scope":"internal","snapshot_id":"exact-snapshot"}`))
request = request.WithContext(context.WithValue(request.Context(), sessionKey{}, sessionIdentity{Username: "real-session-actor", Role: role}))
response := httptest.NewRecorder()
libraryLegacySourceBind(response, request, config)
if role == roleAdmin {
if response.Code != 200 || store.calls != 1 || store.actor != "real-session-actor" || store.source.Project != "configured-project" || store.source.KnowledgeBaseID != "configured-kb" {
t.Fatal("association contract", response.Code, response.Body.String())
}
} else if response.Code != 403 || store.calls != 0 {
t.Fatal("non-admin associated source")
}
}
if classifyRole("POST", "/api/v1/library/source-associations") != roleAdmin {
t.Fatal("route is not administrator only")
}
}
func TestContractLegacySourceAssociationAPIRejectsSpoofAndEvidenceFailure(t *testing.T) {
for _, body := range []string{`{"scope":"internal","snapshot_id":"x","actor":"forged"}`, `{"scope":"internal","snapshot_id":"x","source_identity":{"project":"forged"}}`, `{"scope":"internal","snapshot_id":"x"} {}`} {
store := &legacySourceAPIStore{}
req := httptest.NewRequest("POST", "/", strings.NewReader(body))
req = req.WithContext(context.WithValue(req.Context(), sessionKey{}, sessionIdentity{Username: "admin", Role: roleAdmin}))
out := httptest.NewRecorder()
libraryLegacySourceBind(out, req, Config{Store: store})
if out.Code != 400 || store.calls != 0 {
t.Fatal("spoofed or trailing payload accepted")
}
}
store := &legacySourceAPIStore{err: errors.New("original proof mismatch")}
req := httptest.NewRequest("POST", "/", strings.NewReader(`{"scope":"internal","snapshot_id":"x"}`))
req = req.WithContext(context.WithValue(req.Context(), sessionKey{}, sessionIdentity{Username: "admin", Role: roleAdmin}))
out := httptest.NewRecorder()
libraryLegacySourceBind(out, req, Config{Store: store, LibrarySourceProject: "p", LibrarySourceApp: "app", LibrarySourceTenantID: 1, LibrarySourceInternalKB: "kb"})
if out.Code != 409 {
t.Fatal("unproven association reported success")
}
}
@@ -30,6 +30,7 @@ func TestEmptyTargetOverviewAndEnqueueAgree(t *testing.T) {
}
return true, nil, nil
}}
sourceID := bindSourceFixture(t, &config, store, &target)
rec := httptest.NewRecorder()
libraryOverviewHandler(rec, httptest.NewRequest(http.MethodGet, "/api/v1/library/overview?scope=internal", nil), config)
var overview libraryOverview
@@ -40,7 +41,7 @@ func TestEmptyTargetOverviewAndEnqueueAgree(t *testing.T) {
t.Fatalf("failed=%v gate=%+v", failed, overview.Gate)
}
rec = httptest.NewRecorder()
librarySyncEnqueue(rec, httptest.NewRequest(http.MethodPost, "/api/v1/library/syncs", strings.NewReader(`{"scope":"internal","target_snapshot_id":"`+target+`"}`)), config)
librarySyncEnqueue(rec, httptest.NewRequest(http.MethodPost, "/api/v1/library/syncs", strings.NewReader(sourceRequestBody(t, `{"scope":"internal","target_snapshot_id":"`+target+`"}`, sourceID))), config)
if failed {
if rec.Code != http.StatusServiceUnavailable || store.createN != 0 {
t.Fatalf("unreachable target enqueued: %d %s", rec.Code, rec.Body.String())
@@ -0,0 +1,23 @@
package httpapi
import (
"knowledge-governance/internal/governance"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)
func TestContractSyncRejectsUnboundSourceBeforeCreatingJob(t *testing.T) {
store := &fakeLibraryStore{current: &governance.LibraryVersion{SnapshotID: "current"}, grant: &governance.LibraryReleaseAuthorization{Scope: "internal", SnapshotID: "foreign", ExpiresAt: time.Now().Add(time.Hour)}}
digest, _ := librarySyncParamsDigest("internal", "foreign")
store.grant.ParamsDigest = digest
config := Config{Store: store, ProductionReleaseRequestsEnabled: true, ProductionBackupRestoreVerified: true, LibraryProductionDatabaseURL: "postgres://unreachable.invalid/db", LibraryCapacityBudgetBytes: 1 << 40}
request := httptest.NewRequest(http.MethodPost, "/api/v1/library/syncs", strings.NewReader(`{"scope":"internal","target_snapshot_id":"foreign"}`))
response := httptest.NewRecorder()
librarySyncEnqueue(response, request, config)
if store.createN != 0 {
t.Fatalf("unbound foreign source created %d jobs; response=%s", store.createN, response.Body.String())
}
}
@@ -0,0 +1,63 @@
package httpapi
import (
"context"
"encoding/json"
"knowledge-governance/internal/governance"
"knowledge-governance/internal/librarysnapshot"
"testing"
)
func (f *fakeLibraryStore) LibrarySourceCandidate(_ context.Context, scope, sourceID string) (governance.LibraryVersion, bool, error) {
if f.sourceCandidate != nil && f.sourceCandidate.Scope == scope && f.sourceCandidate.Evidence["source_id"] == sourceID {
return *f.sourceCandidate, true, nil
}
return governance.LibraryVersion{}, false, nil
}
// These fixtures now contain the same capture identity and real immutable
// manifest required by the production admission path. No production bypass.
func bindSourceFixture(t *testing.T, config *Config, store *fakeLibraryStore, target *string) string {
t.Helper()
if config.LibraryArchiveRoot == "" {
config.LibraryArchiveRoot = libraryFixtureRoot(t)
*target = sealSharedVersions(t, config.LibraryArchiveRoot, 1, 4)[0]
}
archive, err := librarysnapshot.Open(config.LibraryArchiveRoot, 256*1024*1024)
if err != nil {
t.Fatal(err)
}
defer archive.Close()
manifest, err := archive.Load(*target)
if err != nil {
t.Fatal(err)
}
config.LibrarySourceProject = "fixture-project"
config.LibrarySourceApp = "fixture-app"
config.LibrarySourceTenantID = manifest.TenantID
config.LibrarySourceInternalKB = manifest.KnowledgeBaseID
source := configuredLibrarySource(*config, "internal")
id, err := source.ID()
if err != nil {
t.Fatal(err)
}
store.sourceCandidate = &governance.LibraryVersion{Scope: "internal", Kind: governance.LibraryVersionTestSealed, SnapshotID: *target, Evidence: map[string]any{"source_id": id}}
if store.grant != nil {
store.grant.SnapshotID = *target
store.grant.ParamsDigest, _ = librarySyncParamsDigest("internal", *target)
}
return id
}
func sourceRequestBody(t *testing.T, body, id string) string {
t.Helper()
var v map[string]any
if err := json.Unmarshal([]byte(body), &v); err != nil {
t.Fatal(err)
}
v["source_id"] = id
raw, err := json.Marshal(v)
if err != nil {
t.Fatal(err)
}
return string(raw)
}