Files
knowledge-governance/internal/libraryrelease/restore_dispatch_activation.go
T
姚章浩 24608e132b fix(library): 区分维护窗口指纹与恢复目标指纹
为什么:维护窗口记录的是部署/实例指纹(journal 与 library_instance_maintenance),
observeRestoreTarget 返回的是内容/索引/桶身份;两者本来不同层(r38 实测
dbe7… vs bb3f…)。v2 证据拆成 target_fingerprint 与 restore_target_fingerprint:
前者绑定窗口与治理行,后者绑定激活时的实时只读观察,避免用一个值冒充两层。
2026-11-02 18:54:18 +08:00

177 lines
8.1 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package libraryrelease
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"os"
"strings"
"time"
)
// 恢复派发激活证据(DS01-F3,协议版本 2)。
//
// 配置开关、"三个非空字符串"或调用方自填的 `stopped=true` 都不是独占证明。v2 证据
// 只允许**指向**一份由维护窗口写下的 journal:调用方声明目标身份、维护作业、journal
// 文件名/摘要与受控 writer 的不可变实例身份;真正的事实(入口关闭与排空、后台静默、
// 每个 writer 的退出观察)由 Store 直接读 journal 字节并解析取得,再用治理库的
// library_instance_maintenance 行把作业/实例/指纹/writer 集合钉死。
//
// 因此"把调用方 JSON 再 hash 一次"不再算核实:摘要只证明"读到的是这一份 journal",
// 事实来自 journal 本体与治理库行,而不是调用方的布尔字段。
//
// 边界:代码能核验 journal 完整性、目标/实例/治理库/构建身份、writer 集合一致性与
// 新鲜度;它不独立观测"外部 writer 此刻没在运行",但 journal 的入口 drain(
// active_at_close=0)、quiesce 零点与退出码是维护链自己的受控观察,且窗口必须仍处于
// held(已恢复/释放的窗口不构成"旧 writer 已停"的证据)。
const RestoreDispatchActivationMaxAge = 2 * time.Hour
const RestoreDispatchActivationProtocolVersion = 2
// RestoreDispatchWriterDrain 是调用方对"旧 writer 集合"的声明:只给身份,不给结论。
// InstanceID 必须等于 journal 里登记的不可变 writer 身份(容器/进程 ID)。
type RestoreDispatchWriterDrain struct {
Name string `json:"name"`
Kind string `json:"kind"`
InstanceID string `json:"instance_id"`
}
type RestoreDispatchActivationEvidence struct {
ProtocolVersion int `json:"protocol_version"`
TargetIdentity string `json:"target_identity"`
// TargetFingerprint 是维护窗口/部署目标指纹(journal 与治理库维护行记录的那一个);
// RestoreTargetFingerprint 是激活时对恢复目标内容/索引/桶的实时观察值。两者是不同层,
// 不能相互替代:前者绑定"动的是哪个实例",后者绑定"恢复要写的那个目标身份"。
TargetFingerprint string `json:"target_fingerprint"`
RestoreTargetFingerprint string `json:"restore_target_fingerprint"`
TargetInstance string `json:"target_instance"`
GovernanceDatabase string `json:"governance_database"`
ProtocolBuild string `json:"protocol_build"`
AttestedBy string `json:"attested_by"`
AttestedAt time.Time `json:"attested_at"`
MaintenanceJob string `json:"maintenance_job"`
MaintenanceJournal string `json:"maintenance_journal"`
MaintenanceJournalSHA256 string `json:"maintenance_journal_sha256"`
Writers []RestoreDispatchWriterDrain `json:"writers"`
}
func (e RestoreDispatchActivationEvidence) Validate(now time.Time, maxAge time.Duration) error {
if e.ProtocolVersion != RestoreDispatchActivationProtocolVersion {
return fmt.Errorf("restore dispatch activation protocol version %d is not supported", e.ProtocolVersion)
}
for name, value := range map[string]string{
"target identity": e.TargetIdentity, "target fingerprint": e.TargetFingerprint,
"restore target fingerprint": e.RestoreTargetFingerprint,
"target instance": e.TargetInstance, "governance database": e.GovernanceDatabase,
"protocol build": e.ProtocolBuild, "attested by": e.AttestedBy,
"maintenance job": e.MaintenanceJob, "maintenance journal": e.MaintenanceJournal,
"maintenance journal digest": e.MaintenanceJournalSHA256,
} {
if strings.TrimSpace(value) == "" {
return fmt.Errorf("restore dispatch activation evidence lacks %s", name)
}
}
if !isHex64(e.TargetFingerprint) || !isHex64(e.RestoreTargetFingerprint) {
return errors.New("restore dispatch activation target fingerprints are not sha256 hex strings")
}
if !isHex64(e.MaintenanceJournalSHA256) {
return errors.New("restore dispatch activation maintenance journal digest is not a sha256 hex string")
}
if !validActivationID(e.MaintenanceJob) {
return errors.New("restore dispatch activation maintenance job id is invalid")
}
// journal 只能按作业名定位在同一受信根目录里;带路径分隔符/相对引用会绕开
// Store 配置的证据根,让"来源"变成调用方随手给的任意文件。
if e.MaintenanceJournal != e.MaintenanceJob+".json" {
return errors.New("restore dispatch activation maintenance journal is not the job journal")
}
if len(e.Writers) == 0 || len(e.Writers) > 256 {
return errors.New("restore dispatch activation lists no controlled writers")
}
names := map[string]bool{}
instances := map[string]bool{}
for _, writer := range e.Writers {
if strings.TrimSpace(writer.Name) == "" || strings.TrimSpace(writer.Kind) == "" ||
strings.TrimSpace(writer.InstanceID) == "" {
return errors.New("restore dispatch activation writer lacks name, kind or instance id")
}
if !validActivationID(writer.InstanceID) {
return errors.New("restore dispatch activation writer instance id is invalid")
}
if names[writer.Name] {
return fmt.Errorf("restore dispatch activation writer %s is listed twice", writer.Name)
}
names[writer.Name] = true
if instances[writer.InstanceID] {
return fmt.Errorf("restore dispatch activation writer instance %s is listed twice", writer.InstanceID)
}
instances[writer.InstanceID] = true
}
if e.AttestedAt.IsZero() || e.AttestedAt.After(now.Add(5*time.Minute)) {
return errors.New("restore dispatch activation attestation time is not credible")
}
if maxAge <= 0 {
maxAge = RestoreDispatchActivationMaxAge
}
if now.Sub(e.AttestedAt) > maxAge {
return fmt.Errorf("restore dispatch activation evidence is older than %s", maxAge)
}
return nil
}
// LoadRestoreDispatchActivationEvidence 读取并核验证据文件字节摘要。expectedDigest 必须
// 与文件实际 sha256 相同;不接受"文件里写的摘要"。
func LoadRestoreDispatchActivationEvidence(path, expectedDigest string, now time.Time, maxAge time.Duration) (RestoreDispatchActivationEvidence, error) {
var evidence RestoreDispatchActivationEvidence
if strings.TrimSpace(path) == "" || strings.TrimSpace(expectedDigest) == "" {
return evidence, errors.New("restore dispatch activation requires an evidence file and its digest")
}
raw, err := os.ReadFile(path)
if err != nil {
return evidence, fmt.Errorf("read restore dispatch activation evidence: %w", err)
}
sum := sha256.Sum256(raw)
if got := hex.EncodeToString(sum[:]); got != strings.ToLower(strings.TrimSpace(expectedDigest)) {
return evidence, errors.New("restore dispatch activation evidence digest does not match the file")
}
decoder := json.NewDecoder(strings.NewReader(string(raw)))
decoder.DisallowUnknownFields()
if err := decoder.Decode(&evidence); err != nil {
return RestoreDispatchActivationEvidence{}, fmt.Errorf("parse restore dispatch activation evidence: %w", err)
}
if err := evidence.Validate(now, maxAge); err != nil {
return RestoreDispatchActivationEvidence{}, err
}
return evidence, nil
}
// CanonicalBytes 是写入台账的规范字节(同一份证据只有一种序列化)。
func (e RestoreDispatchActivationEvidence) CanonicalBytes() ([]byte, error) {
return json.Marshal(e)
}
func isHex64(value string) bool {
if len(value) != 64 || strings.ToLower(value) != value {
return false
}
_, err := hex.DecodeString(value)
return err == nil
}
// validActivationID 与维护 journal 的作业/服务 ID 同一字符集:证据里出现的身份
// 必须能原样出现在 journal 中,不能靠空格/路径字符制造"看起来不同"的别名。
func validActivationID(value string) bool {
if len(value) == 0 || len(value) > 128 {
return false
}
for _, r := range value {
if !(r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' || r >= '0' && r <= '9' || r == '-' || r == '_') {
return false
}
}
return true
}