为什么:同步入口此前只会拒绝;授权、预备份、四类写入、验证与失败恢复都没有代码。
本轮把编排与授权实现出来,真实生产执行仍按授权闸口关闭。
- internal/libraryrelease:预备份 → 数据库/资源/索引/Wiki → 验证 → 失败恢复;
授权过期/目标不符/快照不符/参数变化在动生产前拒绝;恢复失败单独上报。
- 迁移 000067 library_release_authorizations(目标+快照+参数摘要+有效期,可撤销)。
- POST/GET /api/v1/library/authorizations 与 /{id}/revoke,仅管理员签发,5–1440 分钟。
- worker library.sync 接编排:先闸口再授权,阶段落库,只有编排成功才标成功。
- 生产目标适配器未配置时显式失败(不返回零值状态),预备份存储同。
- overview 返回授权状态,页面"生产保护与恢复"显示签发人与有效期。
- 验收矩阵区分"已实现·隔离测试通过"与"真实执行未授权"。
This commit is contained in:
@@ -0,0 +1,134 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/governance"
|
||||
)
|
||||
|
||||
// 生产发布授权:管理员把"目标 + 快照 + 参数摘要 + 有效期"钉死。
|
||||
// 换快照、换目标或改参数都会得到不同摘要,旧授权自然失效;到期或被撤销也不能用。
|
||||
type libraryAuthorizationRequest struct {
|
||||
Scope string `json:"scope"`
|
||||
SnapshotID string `json:"snapshot_id"`
|
||||
ExpiresInMinutes int `json:"expires_in_minutes"`
|
||||
}
|
||||
|
||||
type libraryAuthorizationStore interface {
|
||||
CreateLibraryAuthorization(ctx context.Context, item governance.LibraryReleaseAuthorization) error
|
||||
LibraryAuthorizations(ctx context.Context, scope string, limit int) ([]governance.LibraryReleaseAuthorization, error)
|
||||
RevokeLibraryAuthorization(ctx context.Context, id string, now time.Time) error
|
||||
}
|
||||
|
||||
func libraryAuthorizationStoreOf(config Config) (libraryAuthorizationStore, bool) {
|
||||
store, ok := config.Store.(libraryAuthorizationStore)
|
||||
return store, ok
|
||||
}
|
||||
|
||||
// librarySyncParamsDigest 与 POST /library/syncs 使用的摘要必须完全一致,
|
||||
// 否则授权永远匹配不上,或者更糟——能匹配上却对应别的参数。
|
||||
func librarySyncParamsDigest(scope, snapshotID string) (string, error) {
|
||||
return governance.LibraryRequestDigest(scope, governance.LibraryJobSync,
|
||||
map[string]any{"target_snapshot_id": snapshotID})
|
||||
}
|
||||
|
||||
func libraryAuthorizationCreate(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
if r.Method != http.MethodPost {
|
||||
writeJSON(w, http.StatusMethodNotAllowed, map[string]string{"error": "method not allowed"})
|
||||
return
|
||||
}
|
||||
identity, ok := sessionFrom(r.Context())
|
||||
if !ok || roleRank(identity.Role) < roleRank(roleAdmin) {
|
||||
writeJSON(w, http.StatusForbidden, map[string]any{"error": "生产发布授权仅管理员可签发"})
|
||||
return
|
||||
}
|
||||
store, ok := libraryAuthorizationStoreOf(config)
|
||||
if !ok {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]any{"error": "授权存储不可用"})
|
||||
return
|
||||
}
|
||||
var request libraryAuthorizationRequest
|
||||
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4096)).Decode(&request); err != nil {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid request body"})
|
||||
return
|
||||
}
|
||||
if request.Scope != "internal" && request.Scope != "external" {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "scope must be internal or external"})
|
||||
return
|
||||
}
|
||||
if strings.TrimSpace(request.SnapshotID) == "" {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "snapshot_id required"})
|
||||
return
|
||||
}
|
||||
// 有效期必须显式给出且很短:不提供"永久授权"这种危险默认值。
|
||||
if request.ExpiresInMinutes < 5 || request.ExpiresInMinutes > 24*60 {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "expires_in_minutes must be between 5 and 1440"})
|
||||
return
|
||||
}
|
||||
digest, err := librarySyncParamsDigest(request.Scope, request.SnapshotID)
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot digest params"})
|
||||
return
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
item := governance.LibraryReleaseAuthorization{
|
||||
ID: "libauth-" + request.Scope + "-" + now.Format("20060102T150405.000000"),
|
||||
Scope: request.Scope,
|
||||
SnapshotID: request.SnapshotID,
|
||||
ParamsDigest: digest,
|
||||
AuthorizedBy: identity.Username,
|
||||
ExpiresAt: now.Add(time.Duration(request.ExpiresInMinutes) * time.Minute),
|
||||
CreatedAt: now,
|
||||
}
|
||||
if err := store.CreateLibraryAuthorization(r.Context(), item); err != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot record authorization"})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, map[string]any{"authorization": item})
|
||||
}
|
||||
|
||||
func libraryAuthorizationList(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
scope, err := scopeFromQuery(r)
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
store, ok := libraryAuthorizationStoreOf(config)
|
||||
if !ok {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]any{"available": false, "reason": "授权存储不可用", "authorizations": []any{}})
|
||||
return
|
||||
}
|
||||
items, err := store.LibraryAuthorizations(r.Context(), scope, 50)
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot read authorizations"})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"available": true, "authorizations": items})
|
||||
}
|
||||
|
||||
func libraryAuthorizationRevoke(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
identity, ok := sessionFrom(r.Context())
|
||||
if !ok || roleRank(identity.Role) < roleRank(roleAdmin) {
|
||||
writeJSON(w, http.StatusForbidden, map[string]any{"error": "撤销生产发布授权仅管理员可执行"})
|
||||
return
|
||||
}
|
||||
store, ok := libraryAuthorizationStoreOf(config)
|
||||
if !ok {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]any{"error": "授权存储不可用"})
|
||||
return
|
||||
}
|
||||
id := strings.TrimSpace(r.PathValue("id"))
|
||||
if id == "" {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "authorization id required"})
|
||||
return
|
||||
}
|
||||
if err := store.RevokeLibraryAuthorization(r.Context(), id, time.Now().UTC()); err != nil {
|
||||
writeJSON(w, http.StatusConflict, map[string]any{"error": "授权不存在或已撤销"})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"revoked": id})
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/governance"
|
||||
)
|
||||
|
||||
func authorizationRequest(body string, role string, username string) *http.Request {
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/library/authorizations", strings.NewReader(body))
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
ctx := context.WithValue(request.Context(), sessionKey{}, sessionIdentity{Username: username, Role: role})
|
||||
return request.WithContext(ctx)
|
||||
}
|
||||
|
||||
func TestLibraryAuthorizationRequiresAdmin(t *testing.T) {
|
||||
store := &fakeLibraryStore{}
|
||||
recorder := httptest.NewRecorder()
|
||||
libraryAuthorizationCreate(recorder, authorizationRequest(`{"scope":"internal","snapshot_id":"snap-1","expires_in_minutes":30}`, roleEngineer, "eng"), Config{Store: store})
|
||||
if recorder.Code != http.StatusForbidden {
|
||||
t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
if store.grant != nil {
|
||||
t.Fatal("non-admin must not create an authorization")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLibraryAuthorizationBindsScopeSnapshotAndDigest(t *testing.T) {
|
||||
store := &fakeLibraryStore{}
|
||||
recorder := httptest.NewRecorder()
|
||||
libraryAuthorizationCreate(recorder, authorizationRequest(`{"scope":"internal","snapshot_id":"snap-1","expires_in_minutes":30}`, roleAdmin, "admin"), Config{Store: store})
|
||||
if recorder.Code != http.StatusCreated {
|
||||
t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
want, err := librarySyncParamsDigest("internal", "snap-1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if store.grant.ParamsDigest != want || store.grant.SnapshotID != "snap-1" || store.grant.Scope != "internal" {
|
||||
t.Fatalf("grant not bound to request params: %+v", store.grant)
|
||||
}
|
||||
// 同一个授权不能用于另一个快照:摘要不同即查不到。
|
||||
if _, found, _ := store.ActiveLibraryAuthorization(context.Background(), "internal", "snap-2", want, time.Now()); found {
|
||||
t.Fatal("grant must not authorize another snapshot")
|
||||
}
|
||||
if _, found, _ := store.ActiveLibraryAuthorization(context.Background(), "internal", "snap-1", "other-digest", time.Now()); found {
|
||||
t.Fatal("grant must not authorize different params")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLibraryAuthorizationRejectsUnboundedValidity(t *testing.T) {
|
||||
for _, body := range []string{
|
||||
`{"scope":"internal","snapshot_id":"snap-1","expires_in_minutes":0}`,
|
||||
`{"scope":"internal","snapshot_id":"snap-1","expires_in_minutes":100000}`,
|
||||
} {
|
||||
store := &fakeLibraryStore{}
|
||||
recorder := httptest.NewRecorder()
|
||||
libraryAuthorizationCreate(recorder, authorizationRequest(body, roleAdmin, "admin"), Config{Store: store})
|
||||
if recorder.Code != http.StatusBadRequest {
|
||||
t.Fatalf("body=%s status=%d", body, recorder.Code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLibraryAuthorizationExpiryIsEnforced(t *testing.T) {
|
||||
now := time.Now()
|
||||
item := governance.LibraryReleaseAuthorization{ID: "a", Scope: "internal", SnapshotID: "snap-1",
|
||||
ParamsDigest: "d", ExpiresAt: now.Add(-time.Minute)}
|
||||
if item.ValidAt(now) {
|
||||
t.Fatal("expired authorization must be invalid")
|
||||
}
|
||||
revoked := item
|
||||
revoked.ExpiresAt = now.Add(time.Hour)
|
||||
revokedAt := now
|
||||
revoked.RevokedAt = &revokedAt
|
||||
if revoked.ValidAt(now) {
|
||||
t.Fatal("revoked authorization must be invalid")
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/governance"
|
||||
"knowledge-governance/internal/jobs"
|
||||
"knowledge-governance/internal/librarydiff"
|
||||
"knowledge-governance/internal/librarysnapshot"
|
||||
)
|
||||
@@ -34,6 +35,9 @@ type libraryVersionView struct {
|
||||
SupersededAt *time.Time `json:"superseded_at,omitempty"`
|
||||
}
|
||||
|
||||
// librarySyncJobType 与 worker 的处理器类型一致;单独定义避免 API 依赖 worker 包。
|
||||
const librarySyncJobType = "library.sync"
|
||||
|
||||
type libraryKnownView struct {
|
||||
State string `json:"state"` // known | unknown
|
||||
Version *libraryVersionView `json:"version,omitempty"`
|
||||
@@ -123,24 +127,33 @@ func computeLibraryDiff(root, baseID, targetID string) (libraryDiffView, bool) {
|
||||
return view, true
|
||||
}
|
||||
|
||||
// libraryAuthorizationView 让页面能直说"有没有授权、有效期到什么时候"。
|
||||
type libraryAuthorizationView struct {
|
||||
State string `json:"state"` // active | none
|
||||
AuthorizedBy string `json:"authorized_by,omitempty"`
|
||||
ExpiresAt *time.Time `json:"expires_at,omitempty"`
|
||||
Reason string `json:"reason,omitempty"`
|
||||
}
|
||||
|
||||
type libraryGateView struct {
|
||||
SyncAllowed bool `json:"sync_allowed"`
|
||||
Reasons []string `json:"reasons"`
|
||||
}
|
||||
|
||||
type libraryOverview struct {
|
||||
Scope string `json:"scope"`
|
||||
TestSealed *librarySnapshotView `json:"test_sealed,omitempty"`
|
||||
TestSealedReason string `json:"test_sealed_reason,omitempty"`
|
||||
Production libraryKnownView `json:"production"`
|
||||
Prebackup libraryKnownView `json:"prebackup"`
|
||||
Diff libraryDiffView `json:"diff"`
|
||||
Job *governance.LibraryJob `json:"job,omitempty"`
|
||||
Jobs []governance.LibraryJob `json:"jobs"`
|
||||
Gate libraryGateView `json:"gate"`
|
||||
CaptureAvailable bool `json:"capture_available"`
|
||||
CaptureReason string `json:"capture_reason,omitempty"`
|
||||
Now time.Time `json:"now"`
|
||||
Scope string `json:"scope"`
|
||||
TestSealed *librarySnapshotView `json:"test_sealed,omitempty"`
|
||||
TestSealedReason string `json:"test_sealed_reason,omitempty"`
|
||||
Production libraryKnownView `json:"production"`
|
||||
Prebackup libraryKnownView `json:"prebackup"`
|
||||
Diff libraryDiffView `json:"diff"`
|
||||
Job *governance.LibraryJob `json:"job,omitempty"`
|
||||
Jobs []governance.LibraryJob `json:"jobs"`
|
||||
Gate libraryGateView `json:"gate"`
|
||||
Authorization libraryAuthorizationView `json:"authorization"`
|
||||
CaptureAvailable bool `json:"capture_available"`
|
||||
CaptureReason string `json:"capture_reason,omitempty"`
|
||||
Now time.Time `json:"now"`
|
||||
}
|
||||
|
||||
type libraryJobStore interface {
|
||||
@@ -160,6 +173,36 @@ func libraryStore(config Config) (libraryJobStore, bool) {
|
||||
return store, ok
|
||||
}
|
||||
|
||||
// activeGrantFor 只查"目标+快照+同一参数摘要"的未过期未撤销授权。
|
||||
func activeGrantFor(ctx context.Context, config Config, scope, snapshotID string) (governance.LibraryReleaseAuthorization, bool) {
|
||||
if snapshotID == "" {
|
||||
return governance.LibraryReleaseAuthorization{}, false
|
||||
}
|
||||
store, ok := config.Store.(interface {
|
||||
ActiveLibraryAuthorization(ctx context.Context, scope, snapshotID, paramsDigest string, now time.Time) (governance.LibraryReleaseAuthorization, bool, error)
|
||||
})
|
||||
if !ok {
|
||||
return governance.LibraryReleaseAuthorization{}, false
|
||||
}
|
||||
digest, err := librarySyncParamsDigest(scope, snapshotID)
|
||||
if err != nil {
|
||||
return governance.LibraryReleaseAuthorization{}, false
|
||||
}
|
||||
grant, found, err := store.ActiveLibraryAuthorization(ctx, scope, snapshotID, digest, time.Now().UTC())
|
||||
if err != nil || !found {
|
||||
return governance.LibraryReleaseAuthorization{}, false
|
||||
}
|
||||
return grant, true
|
||||
}
|
||||
|
||||
func authorizationViewOf(grant governance.LibraryReleaseAuthorization, found bool) libraryAuthorizationView {
|
||||
if !found {
|
||||
return libraryAuthorizationView{State: "none", Reason: "没有与目标快照匹配的有效发布授权"}
|
||||
}
|
||||
expires := grant.ExpiresAt
|
||||
return libraryAuthorizationView{State: "active", AuthorizedBy: grant.AuthorizedBy, ExpiresAt: &expires}
|
||||
}
|
||||
|
||||
func scopeFromQuery(r *http.Request) (string, error) {
|
||||
scope := strings.TrimSpace(r.URL.Query().Get("scope"))
|
||||
if scope == "" {
|
||||
@@ -180,7 +223,16 @@ func libraryVersionViewOf(item governance.LibraryVersion) libraryVersionView {
|
||||
// librarySyncGate 只依据真实存在的证据判断能不能写生产:闸口、生产端点、
|
||||
// 生产权威版本、目标快照的预备份。任何一项缺失都给出具体原因,不默认放行。
|
||||
func librarySyncGate(config Config, production libraryKnownView, prebackup libraryKnownView, target string) libraryGateView {
|
||||
return librarySyncGateWithGrant(config, production, prebackup, target, false)
|
||||
}
|
||||
|
||||
// librarySyncGateWithGrant 在原有证据之外再要求一份有效授权:
|
||||
// 授权绑定了目标、快照、参数与有效期,缺它就不能写生产。
|
||||
func librarySyncGateWithGrant(config Config, production libraryKnownView, prebackup libraryKnownView, target string, hasGrant bool) libraryGateView {
|
||||
gate := libraryGateView{SyncAllowed: false, Reasons: []string{}}
|
||||
if !hasGrant {
|
||||
gate.Reasons = append(gate.Reasons, "没有与目标快照匹配的有效发布授权")
|
||||
}
|
||||
if !config.ProductionReleaseRequestsEnabled {
|
||||
gate.Reasons = append(gate.Reasons, "生产写入闸口关闭(PRODUCTION_RELEASE_REQUESTS_ENABLED=false)")
|
||||
}
|
||||
@@ -299,7 +351,9 @@ func libraryOverviewHandler(w http.ResponseWriter, r *http.Request, config Confi
|
||||
overview.Diff = view
|
||||
}
|
||||
|
||||
overview.Gate = librarySyncGate(config, overview.Production, overview.Prebackup, target)
|
||||
grant, hasGrant := activeGrantFor(r.Context(), config, scope, target)
|
||||
overview.Authorization = authorizationViewOf(grant, hasGrant)
|
||||
overview.Gate = librarySyncGateWithGrant(config, overview.Production, overview.Prebackup, target, hasGrant)
|
||||
writeJSON(w, http.StatusOK, overview)
|
||||
}
|
||||
|
||||
@@ -384,7 +438,9 @@ func librarySyncEnqueue(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
overview.Prebackup = libraryKnownView{State: "known", Version: &view}
|
||||
}
|
||||
}
|
||||
gate := librarySyncGate(config, overview.Production, overview.Prebackup, request.Target)
|
||||
grantFound, hasGrant := activeGrantFor(r.Context(), config, request.Scope, request.Target)
|
||||
_ = grantFound
|
||||
gate := librarySyncGateWithGrant(config, overview.Production, overview.Prebackup, request.Target, hasGrant)
|
||||
if !gate.SyncAllowed {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]any{
|
||||
"code": "library_sync_blocked", "reasons": gate.Reasons,
|
||||
@@ -423,5 +479,30 @@ func librarySyncEnqueue(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot create library sync job"})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusAccepted, map[string]any{"job": job, "reused": reused})
|
||||
if reused {
|
||||
writeJSON(w, http.StatusAccepted, map[string]any{"job": job, "reused": true})
|
||||
return
|
||||
}
|
||||
// 业务作业先落库,再投递队列:投递失败就把作业标失败,不留下"看起来在跑"的空作业。
|
||||
payload, err := json.Marshal(map[string]string{
|
||||
"library_job_id": job.ID, "scope": request.Scope, "target_snapshot_id": request.Target,
|
||||
})
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot build sync payload"})
|
||||
return
|
||||
}
|
||||
queueJob, err := config.Store.Enqueue(r.Context(), jobs.EnqueueRequest{
|
||||
ID: job.ID + "-queue", Type: librarySyncJobType, Payload: payload, AvailableAt: now,
|
||||
MaxAttempts: 1, IdempotencyKey: "library.sync.queue:" + job.ID,
|
||||
}, now)
|
||||
if err != nil || queueJob == nil {
|
||||
_ = store.CancelLibraryJob(r.Context(), job.ID, "队列投递失败,未开始同步", now)
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot enqueue sync job"})
|
||||
return
|
||||
}
|
||||
if attachErr := store.AttachLibraryQueueJob(r.Context(), job.ID, queueJob.ID, now); attachErr != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot attach sync job"})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusAccepted, map[string]any{"job": job, "reused": false})
|
||||
}
|
||||
|
||||
@@ -18,6 +18,7 @@ import (
|
||||
// 复用既有 fakeJobStore 提供 Store 的其余方法,只覆盖整库作业这几个。
|
||||
type fakeLibraryStore struct {
|
||||
fakeJobStore
|
||||
grant *governance.LibraryReleaseAuthorization
|
||||
versions []governance.LibraryVersion
|
||||
jobs []governance.LibraryJob
|
||||
createN int
|
||||
@@ -69,6 +70,32 @@ func (f *fakeLibraryStore) AdvanceLibraryJob(_ context.Context, _ string, state
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeLibraryStore) CreateLibraryAuthorization(_ context.Context, item governance.LibraryReleaseAuthorization) error {
|
||||
f.grant = &item
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeLibraryStore) ActiveLibraryAuthorization(_ context.Context, scope, snapshotID, digest string, now time.Time) (governance.LibraryReleaseAuthorization, bool, error) {
|
||||
if f.grant == nil || f.grant.Scope != scope || f.grant.SnapshotID != snapshotID || f.grant.ParamsDigest != digest {
|
||||
return governance.LibraryReleaseAuthorization{}, false, nil
|
||||
}
|
||||
if !f.grant.ValidAt(now) {
|
||||
return governance.LibraryReleaseAuthorization{}, false, nil
|
||||
}
|
||||
return *f.grant, true, nil
|
||||
}
|
||||
|
||||
func (f *fakeLibraryStore) LibraryAuthorizations(context.Context, string, int) ([]governance.LibraryReleaseAuthorization, error) {
|
||||
if f.grant == nil {
|
||||
return nil, nil
|
||||
}
|
||||
return []governance.LibraryReleaseAuthorization{*f.grant}, nil
|
||||
}
|
||||
|
||||
func (f *fakeLibraryStore) RevokeLibraryAuthorization(context.Context, string, time.Time) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeLibraryStore) AttachLibraryQueueJob(_ context.Context, _, _ string, _ time.Time) error {
|
||||
return nil
|
||||
}
|
||||
@@ -130,7 +157,7 @@ func TestLibrarySyncGateRequiresEveryPieceOfEvidence(t *testing.T) {
|
||||
}
|
||||
for _, testCase := range cases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
gate := librarySyncGate(testCase.config, testCase.production, testCase.prebackup, testCase.target)
|
||||
gate := librarySyncGateWithGrant(testCase.config, testCase.production, testCase.prebackup, testCase.target, true)
|
||||
if gate.SyncAllowed != testCase.allowed {
|
||||
t.Fatalf("sync_allowed = %v, want %v (%v)", gate.SyncAllowed, testCase.allowed, gate.Reasons)
|
||||
}
|
||||
@@ -194,6 +221,54 @@ func TestLibrarySyncEnqueueRequiresPrebackupForTarget(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// 证据齐全 + 有效授权时才会真正建作业并入队;缺授权一律拒绝且不建作业。
|
||||
func TestLibrarySyncEnqueueCreatesJobOnlyWithGrant(t *testing.T) {
|
||||
target := "snap-1"
|
||||
digest, err := librarySyncParamsDigest("internal", target)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
store := &fakeLibraryStore{versions: []governance.LibraryVersion{
|
||||
{ID: "ver-prod", Scope: "internal", Kind: governance.LibraryVersionProductionEffective,
|
||||
SnapshotID: "prod-snap", VersionLabel: "prod-2026.10", CreatedAt: time.Now().UTC()},
|
||||
{ID: "ver-backup", Scope: "internal", Kind: governance.LibraryVersionProductionPrebackup,
|
||||
SnapshotID: target, CreatedAt: time.Now().UTC()},
|
||||
}}
|
||||
store.enqueueEchoRequestedID = true
|
||||
config := Config{Store: store, ProductionReleaseRequestsEnabled: true, ProductionBackupRestoreVerified: true,
|
||||
ProductionWeKnoraBaseURL: "http://prod.invalid", LibraryCapacityBudgetBytes: 1 << 40}
|
||||
body := `{"scope":"internal","target_snapshot_id":"` + target + `"}`
|
||||
|
||||
// 先没有授权
|
||||
recorder := httptest.NewRecorder()
|
||||
librarySyncEnqueue(recorder, httptest.NewRequest(http.MethodPost, "/api/v1/library/syncs", strings.NewReader(body)), config)
|
||||
if recorder.Code != http.StatusServiceUnavailable {
|
||||
t.Fatalf("without grant status=%d body=%s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
if store.createN != 0 {
|
||||
t.Fatal("must not create a job without a grant")
|
||||
}
|
||||
|
||||
// 补上绑定同一目标与快照的授权
|
||||
now := time.Now().UTC()
|
||||
store.grant = &governance.LibraryReleaseAuthorization{ID: "auth-1", Scope: "internal", SnapshotID: target,
|
||||
ParamsDigest: digest, AuthorizedBy: "admin", ExpiresAt: now.Add(30 * time.Minute), CreatedAt: now}
|
||||
recorder = httptest.NewRecorder()
|
||||
librarySyncEnqueue(recorder, httptest.NewRequest(http.MethodPost, "/api/v1/library/syncs", strings.NewReader(body)), config)
|
||||
if recorder.Code != http.StatusAccepted {
|
||||
t.Fatalf("with grant status=%d body=%s", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
if store.createN != 1 {
|
||||
t.Fatalf("created=%d, want 1", store.createN)
|
||||
}
|
||||
if store.enqueued.Type != "library.sync" {
|
||||
t.Fatalf("enqueued type=%q, want library.sync", store.enqueued.Type)
|
||||
}
|
||||
if !strings.Contains(string(store.enqueued.Payload), store.lastJob.ID) {
|
||||
t.Fatalf("queue payload must carry the library job id: %s", store.enqueued.Payload)
|
||||
}
|
||||
}
|
||||
|
||||
// 三类版本必须分开读:production_effective 才是生产当前,测试封存不能顶替。
|
||||
func TestLibraryOverviewKeepsVersionKindsSeparate(t *testing.T) {
|
||||
now := time.Now().UTC()
|
||||
|
||||
@@ -424,6 +424,16 @@ func NewHandler(config Config) (http.Handler, error) {
|
||||
mux.HandleFunc("GET /api/v1/library/jobs/{id}", func(w http.ResponseWriter, r *http.Request) {
|
||||
libraryJobDetailHandler(w, r, config)
|
||||
})
|
||||
// 生产发布授权:管理员签发,绑定目标+快照+参数摘要+有效期;可撤销。
|
||||
mux.HandleFunc("POST /api/v1/library/authorizations", func(w http.ResponseWriter, r *http.Request) {
|
||||
libraryAuthorizationCreate(w, r, config)
|
||||
})
|
||||
mux.HandleFunc("GET /api/v1/library/authorizations", func(w http.ResponseWriter, r *http.Request) {
|
||||
libraryAuthorizationList(w, r, config)
|
||||
})
|
||||
mux.HandleFunc("POST /api/v1/library/authorizations/{id}/revoke", func(w http.ResponseWriter, r *http.Request) {
|
||||
libraryAuthorizationRevoke(w, r, config)
|
||||
})
|
||||
// 生产同步唯一入口:闸口未齐不建作业,返回缺项而不是假 Accepted。
|
||||
mux.HandleFunc("POST /api/v1/library/syncs", func(w http.ResponseWriter, r *http.Request) {
|
||||
librarySyncEnqueue(w, r, config)
|
||||
|
||||
Reference in New Issue
Block a user