feat(release): 生产授权支持页面通道(管理员会话 + 固定确认语句)
页面原本没有任何生产入口,授权/重排/回滚只能带 Bearer 调接口,实际还要 admin 会话。 现在三个端点支持两条通道,门禁语义不变: - 运维通道:Authorization: Bearer <token>,审计记 PRODUCTION_RELEASE_AUTHORIZER_REF - 页面通道:已认证 admin 会话 + 固定确认语句,审计记该管理员用户名 - 请求门禁 / 备份恢复门禁 / Release Worker 执行门禁三者不受影响 - 发布管理第 6–8 步加「授权发布 / 重排 / 回滚」按钮,点击需逐字输入确认语句, 仅 admin 可见;重排沿用原执行授权人,不改写历史 - openapi 与 P6 契约同步;测试:双通道各一条 + 非 admin/错短语拒绝 + 前端按钮与确认门禁
This commit is contained in:
@@ -0,0 +1,132 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"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())
|
||||
}
|
||||
}
|
||||
@@ -1654,7 +1654,8 @@ func authorizeProductionRelease(w http.ResponseWriter, r *http.Request, config C
|
||||
writeJSON(w, http.StatusPreconditionFailed, map[string]string{"error": "production backup restore verification is required"})
|
||||
return
|
||||
}
|
||||
if !productionReleaseAuthorized(r, config.ProductionReleaseAuthorizationToken) {
|
||||
actor, releaseAuthorized := productionReleaseActor(r, config)
|
||||
if !releaseAuthorized {
|
||||
writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "production release authorization required"})
|
||||
return
|
||||
}
|
||||
@@ -1668,7 +1669,7 @@ func authorizeProductionRelease(w http.ResponseWriter, r *http.Request, config C
|
||||
return
|
||||
}
|
||||
execution, replayed, err := config.Store.AuthorizeReleaseBatchWithOperation(r.Context(), governance.AuthorizeReleaseBatchRequest{
|
||||
BatchID: r.PathValue("id"), AuthorizedBy: productionAuthorizer(r, config),
|
||||
BatchID: r.PathValue("id"), AuthorizedBy: actor,
|
||||
AuthorizationCode: "production_release_authorized", Now: config.Now().UTC(),
|
||||
}, operationID)
|
||||
switch {
|
||||
@@ -1699,7 +1700,8 @@ func authorizeProductionRollback(w http.ResponseWriter, r *http.Request, config
|
||||
writeJSON(w, http.StatusForbidden, map[string]string{"error": "production release requests are disabled"})
|
||||
return
|
||||
}
|
||||
if !productionReleaseAuthorized(r, config.ProductionReleaseAuthorizationToken) {
|
||||
actor, releaseAuthorized := productionReleaseActor(r, config)
|
||||
if !releaseAuthorized {
|
||||
writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "production release authorization required"})
|
||||
return
|
||||
}
|
||||
@@ -1713,7 +1715,7 @@ func authorizeProductionRollback(w http.ResponseWriter, r *http.Request, config
|
||||
return
|
||||
}
|
||||
execution, replayed, err := config.Store.AuthorizeReleaseRollbackWithOperation(r.Context(), governance.AuthorizeReleaseRollbackRequest{
|
||||
PriorExecutionID: r.PathValue("id"), AuthorizedBy: productionAuthorizer(r, config),
|
||||
PriorExecutionID: r.PathValue("id"), AuthorizedBy: actor,
|
||||
AuthorizationCode: "production_rollback_authorized", Now: config.Now().UTC(),
|
||||
}, operationID)
|
||||
switch {
|
||||
@@ -1744,7 +1746,8 @@ func retryProductionRelease(w http.ResponseWriter, r *http.Request, config Confi
|
||||
writeJSON(w, http.StatusForbidden, map[string]string{"error": "production release requests are disabled"})
|
||||
return
|
||||
}
|
||||
if !productionReleaseAuthorized(r, config.ProductionReleaseAuthorizationToken) {
|
||||
// 重排沿用原执行的授权人记录(改写它会篡改历史),因此这里只取授权结果。
|
||||
if _, releaseAuthorized := productionReleaseActor(r, config); !releaseAuthorized {
|
||||
writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "production release authorization required"})
|
||||
return
|
||||
}
|
||||
@@ -1788,6 +1791,25 @@ func productionAuthorizer(r *http.Request, config Config) string {
|
||||
return config.ProductionReleaseAuthorizerRef
|
||||
}
|
||||
|
||||
// productionReleaseActor authorises a production action and names who performed
|
||||
// it. Two sanctioned paths behind the same gates:
|
||||
// - the deployment Bearer token (ops scripts) — recorded under the configured
|
||||
// fixed authorizer ref;
|
||||
// - an authenticated ADMIN session plus the fixed confirmation phrase (the
|
||||
// page's 授权发布 / 重排 / 回滚 buttons) — recorded under that operator.
|
||||
//
|
||||
// The request gate, the backup-restore gate and the worker's execution gate stay
|
||||
// independent of this choice: relaxing "who may call" must not relax "may it run".
|
||||
func productionReleaseActor(r *http.Request, config Config) (string, bool) {
|
||||
if productionReleaseAuthorized(r, config.ProductionReleaseAuthorizationToken) {
|
||||
return config.ProductionReleaseAuthorizerRef, true
|
||||
}
|
||||
if identity, ok := sessionFrom(r.Context()); ok && identity.Role == roleAdmin {
|
||||
return identity.Username, true
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
func productionReleaseAuthorized(r *http.Request, token string) bool {
|
||||
provided := r.Header.Get("Authorization")
|
||||
expected := "Bearer " + token
|
||||
|
||||
@@ -25,6 +25,12 @@ type TargetContractInspectorConfig struct {
|
||||
KnowledgeBaseID string
|
||||
TenantID uint64
|
||||
IndexName string
|
||||
// ReadTestedBase makes the inspector read the TESTED base (the source side
|
||||
// of a release) instead of the 源库 → 目标库 mapped base. The exporter and
|
||||
// the target share this inspector type, so the side must be explicit: with
|
||||
// a mapping in play, "which base do I read" is not the same question on
|
||||
// both ends.
|
||||
ReadTestedBase bool
|
||||
}
|
||||
|
||||
type TargetContractInspector struct {
|
||||
@@ -64,10 +70,14 @@ func (inspector *TargetContractInspector) Contract(ctx context.Context, item rel
|
||||
if item.TestKnowledgeBaseID != inspector.config.KnowledgeBaseID {
|
||||
return releasebundle.TargetContract{}, errors.New("release plan knowledge base does not match target contract")
|
||||
}
|
||||
// The route is keyed by the TESTED base (where the content was verified);
|
||||
// the contract is read for the base this release actually writes into —
|
||||
// the 源库 → 目标库 mapping when the item carries one, else the same base.
|
||||
// The route is keyed by the TESTED base (where the content was verified). The
|
||||
// contract is read for the base this side actually owns: the source side reads
|
||||
// the tested base (what the bundle is exported from), the target side reads the
|
||||
// 源库 → 目标库 mapped base (what the release writes into).
|
||||
targetKnowledgeBaseID := item.TargetBase()
|
||||
if inspector.config.ReadTestedBase {
|
||||
targetKnowledgeBaseID = item.TestKnowledgeBaseID
|
||||
}
|
||||
if !validSearchIdentifier(targetKnowledgeBaseID) {
|
||||
return releasebundle.TargetContract{}, errors.New("invalid release target knowledge base")
|
||||
}
|
||||
|
||||
@@ -45,13 +45,58 @@ func TestTargetContractInspectorRejectsMismatchedPlanKB(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// With a 源库 → 目标库 mapping the two sides must read DIFFERENT bases: the
|
||||
// target reads the mapped one, the source keeps reading the tested one. Reading
|
||||
// the mapped base on the source plane made a real release fail with
|
||||
// "source WeKnora release contract mismatch" (the target base is unknown there).
|
||||
func TestTargetContractInspectorSidesPickTheRightBase(t *testing.T) {
|
||||
row := contractRow{values: []any{74, false, uint64(10000), "bge-m3", 1024, "elasticsearch", "chunks"}}
|
||||
mapping := &mappingInspector{sha: strings.Repeat("a", 64)}
|
||||
plan := releasePlanForArchive()
|
||||
plan.TargetKnowledgeBaseID = "prod-kb"
|
||||
|
||||
targetDB := &contractDB{row: row}
|
||||
targetInspector, err := NewTargetContractInspector(TargetContractInspectorConfig{DB: targetDB, Mapping: mapping, KnowledgeBaseID: "kb-safe", TenantID: 10000, IndexName: "chunks"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
targetContract, err := targetInspector.Contract(context.Background(), plan)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if targetContract.KnowledgeBaseID != "prod-kb" {
|
||||
t.Fatalf("target contract kb=%q, want the mapped base", targetContract.KnowledgeBaseID)
|
||||
}
|
||||
if len(targetDB.args) != 1 || targetDB.args[0] != "prod-kb" {
|
||||
t.Fatalf("target read base=%v, want prod-kb", targetDB.args)
|
||||
}
|
||||
|
||||
sourceDB := &contractDB{row: row}
|
||||
sourceInspector, err := NewTargetContractInspector(TargetContractInspectorConfig{DB: sourceDB, Mapping: mapping, KnowledgeBaseID: "kb-safe", TenantID: 10000, IndexName: "chunks", ReadTestedBase: true})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sourceContract, err := sourceInspector.Contract(context.Background(), plan)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if sourceContract.KnowledgeBaseID != "kb-safe" {
|
||||
t.Fatalf("source contract kb=%q, want the tested base", sourceContract.KnowledgeBaseID)
|
||||
}
|
||||
if len(sourceDB.args) != 1 || sourceDB.args[0] != "kb-safe" {
|
||||
t.Fatalf("source read base=%v, want kb-safe", sourceDB.args)
|
||||
}
|
||||
}
|
||||
|
||||
type contractDB struct {
|
||||
row contractRow
|
||||
query string
|
||||
args []any
|
||||
}
|
||||
|
||||
func (d *contractDB) QueryRow(_ context.Context, query string, args ...any) pgx.Row {
|
||||
d.query = query
|
||||
d.args = args
|
||||
return d.row
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user