Files
knowledge-governance/internal/httpapi/production_action_test.go
T
姚章浩 86732ca987 fix(api): 执行明细补齐 action 与目标知识库字段
逐项明细 DTO 漏了 action(前端 parseReleaseItemExecution 必需),点
「查看结果」整个明细区报 invalid release item execution。同时把遷移 000044
的 target_knowledge_base_id 读出来透出,页面逐项结果显示「目标库」,
让'目标知识库可选'在界面上可核对。测试:Go 契约用例 + 前端解析回归用例。
2026-10-08 17:26:26 +08:00

189 lines
8.0 KiB
Go

package httpapi
import (
"bytes"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"knowledge-governance/internal/governance"
)
// productionActionHandler builds a handler with both gates open and one
// configurable production execution result.
func productionActionHandler(t *testing.T) (http.Handler, *fakeJobStore) {
t.Helper()
now := time.Date(2026, time.October, 8, 9, 0, 0, 0, time.UTC)
store := &fakeJobStore{authorizeReleaseResult: governance.ReleaseExecution{
ID: "rx-safe", ReleaseBatchID: "rb-safe", Operation: governance.ReleaseOperationPublish,
State: governance.ReleaseExecutionPending, TargetEnvironment: "production", AuthorizedBy: "release-owner",
AuthorizationCode: "production_release_authorized", JobID: "job-safe", ItemCount: 1, CreatedAt: now,
}}
handler, err := NewHandler(Config{
Store: store, Now: func() time.Time { return now },
ProductionReleaseRequestsEnabled: true, ProductionBackupRestoreVerified: true,
ProductionReleaseAuthorizerRef: "release-owner", ProductionReleaseAuthorizationToken: "safe-token",
})
if err != nil {
t.Fatal(err)
}
return handler, store
}
func authorizeProductionRequest(t *testing.T, identity *sessionIdentity) *http.Request {
t.Helper()
request := httptest.NewRequest(http.MethodPost, "/api/v1/release-batches/rb-safe/authorize-production",
bytes.NewBufferString(`{"confirmation":"publish-to-production"}`))
request.Header.Set("Content-Type", "application/json")
request.Header.Set("Idempotency-Key", "op-page-authorize")
if identity != nil {
request = request.WithContext(context.WithValue(request.Context(), sessionKey{}, *identity))
}
return request
}
// The page path: an ADMIN session plus the fixed confirmation phrase authorizes
// a production release without the Bearer token, and the audit names the
// operator who clicked.
func TestProductionActionAcceptsAdminSessionWithConfirmation(t *testing.T) {
handler, store := productionActionHandler(t)
response := httptest.NewRecorder()
handler.ServeHTTP(response, authorizeProductionRequest(t, &sessionIdentity{Username: "yaozhanghao", Role: roleAdmin}))
if response.Code != http.StatusAccepted {
t.Fatalf("status=%d body=%s", response.Code, response.Body.String())
}
if store.authorizeReleaseRequest.AuthorizedBy != "yaozhanghao" {
t.Fatalf("authorized_by=%q, want the page operator", store.authorizeReleaseRequest.AuthorizedBy)
}
}
// The ops path is unchanged: a Bearer token authorizes and records the fixed
// configured authorizer.
func TestProductionActionAcceptsBearerTokenWithoutSession(t *testing.T) {
handler, store := productionActionHandler(t)
request := authorizeProductionRequest(t, nil)
request.Header.Set("Authorization", "Bearer safe-token")
response := httptest.NewRecorder()
handler.ServeHTTP(response, request)
if response.Code != http.StatusAccepted {
t.Fatalf("status=%d body=%s", response.Code, response.Body.String())
}
if store.authorizeReleaseRequest.AuthorizedBy != "release-owner" {
t.Fatalf("authorized_by=%q, want the configured authorizer", store.authorizeReleaseRequest.AuthorizedBy)
}
}
// Neither a non-admin session nor a wrong token may authorize anything.
func TestProductionActionRejectsNonAdminAndUnsignedRequests(t *testing.T) {
tests := []struct {
name string
identity *sessionIdentity
token string
confirm string
}{
{name: "engineer session", identity: &sessionIdentity{Username: "engineer", Role: roleEngineer}},
{name: "viewer session", identity: &sessionIdentity{Username: "viewer", Role: roleViewer}},
{name: "no credentials at all", identity: nil},
{name: "wrong bearer token", identity: nil, token: "Bearer other-token", confirm: "publish-to-production"},
{name: "admin session with wrong phrase", identity: &sessionIdentity{Username: "yaozhanghao", Role: roleAdmin}, confirm: "publish"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
handler, store := productionActionHandler(t)
request := httptest.NewRequest(http.MethodPost, "/api/v1/release-batches/rb-safe/authorize-production",
bytes.NewBufferString(`{"confirmation":"`+tt.confirm+`"}`))
request.Header.Set("Content-Type", "application/json")
request.Header.Set("Idempotency-Key", "op-page-authorize")
if tt.identity != nil {
request = request.WithContext(context.WithValue(request.Context(), sessionKey{}, *tt.identity))
}
if tt.token != "" {
request.Header.Set("Authorization", tt.token)
}
response := httptest.NewRecorder()
handler.ServeHTTP(response, request)
if response.Code == http.StatusAccepted || store.authorizeReleaseCalled {
t.Fatalf("status=%d called=%v body=%s", response.Code, store.authorizeReleaseCalled, response.Body.String())
}
})
}
}
// The gates themselves are untouched: with the request gate closed the page path
// is blocked too, and the page must never be able to run a release on its own.
func TestProductionActionPagePathStillRespectsGates(t *testing.T) {
store := &fakeJobStore{}
handler, err := NewHandler(Config{Store: store, ProductionReleaseRequestsEnabled: true,
ProductionBackupRestoreVerified: false, ProductionReleaseAuthorizerRef: "release-owner", ProductionReleaseAuthorizationToken: "safe-token"})
if err != nil {
t.Fatal(err)
}
response := httptest.NewRecorder()
handler.ServeHTTP(response, authorizeProductionRequest(t, &sessionIdentity{Username: "yaozhanghao", Role: roleAdmin}))
if response.Code != http.StatusPreconditionFailed || store.authorizeReleaseCalled {
t.Fatalf("status=%d called=%v body=%s", response.Code, store.authorizeReleaseCalled, response.Body.String())
}
if !strings.Contains(response.Body.String(), "backup restore") {
t.Fatalf("body=%s", response.Body.String())
}
}
// 前端 parseReleaseItemExecution 要求每项明细都带 action,列表还要求批次进度字段;
// DTO 一旦漏字段,一条不合法就让整块明细/列表报 invalid release ...(线上就是这样)。
func TestReleaseExecutionDetailExposesItemFieldsThePageRequires(t *testing.T) {
now := time.Date(2026, time.October, 8, 9, 0, 0, 0, time.UTC)
store := &fakeJobStore{releaseExecutionDetailResult: governance.ReleaseExecutionDetail{
ReleaseExecution: governance.ReleaseExecution{
ID: "rx-1", ReleaseBatchID: "rb-1", Operation: governance.ReleaseOperationPublish,
State: governance.ReleaseExecutionCompleted, TargetEnvironment: "production",
AuthorizedBy: "admin", JobID: "job-1", BatchSize: 50, CurrentBatch: 1, TotalBatches: 1,
ItemCount: 1, CompletedItemCount: 1, CreatedAt: now,
},
Items: []governance.ReleaseItemExecutionView{{
PublicationID: "tp-1", Title: "手册.pdf", Action: "upsert", State: "verified",
ProductionRevision: "rv-1", TargetKnowledgeBaseID: "kb-target-1", CreatedAt: now,
}},
}}
handler, err := NewHandler(Config{Store: store, Now: func() time.Time { return now }})
if err != nil {
t.Fatal(err)
}
response := httptest.NewRecorder()
handler.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/api/v1/release-executions/rx-1", nil))
if response.Code != http.StatusOK {
t.Fatalf("status=%d body=%s", response.Code, response.Body.String())
}
var payload struct {
Data struct {
BatchSize float64 `json:"batch_size"`
TotalBatch float64 `json:"total_batches"`
Items []struct {
Action string `json:"action"`
TargetKnowledgeBase string `json:"target_knowledge_base_id"`
ProductionRevision string `json:"production_revision"`
PreviousProductionRV string `json:"previous_production_revision"`
} `json:"items"`
} `json:"data"`
}
if err := json.Unmarshal(response.Body.Bytes(), &payload); err != nil {
t.Fatal(err)
}
if payload.Data.BatchSize != 50 || payload.Data.TotalBatch != 1 {
t.Fatalf("batch progress missing: %+v", payload.Data)
}
if len(payload.Data.Items) != 1 {
t.Fatalf("items=%+v", payload.Data.Items)
}
item := payload.Data.Items[0]
if item.Action != "upsert" {
t.Fatalf("action=%q, want upsert (前端解析必需)", item.Action)
}
if item.TargetKnowledgeBase != "kb-target-1" {
t.Fatalf("target_knowledge_base_id=%q", item.TargetKnowledgeBase)
}
}