Files
knowledge-governance/internal/libraryrelease/restore_dispatch_activation.go
T
姚章浩 6209072e43 fix(library): 跨SHA兼容需受信证明默认拒绝
原实现把 ProtocolEpoch 相等当作构建兼容证明:任何 40 位小写 hex SHA 加一个非空
display 都会被记成 compatible_upgrade 并允许激活,换一个 SHA 即可绕开同 SHA 的
display 绑定,构建身份仍是声明式。

收口为精确绑定运行完整 SHA:同 SHA 必须 display 相符,不同 SHA 一律失败关闭,
错误明确写"cross-sha compatible activation is disabled without a verifiable
protocol build membership proof"。不新建签名基础设施,也不引入第二份 allowlist;
使用点与激活点调用同一函数,行为一致。台账不重写、旧激活行保留(不匹配即 held)。
2026-11-02 21:16:45 +08:00

231 lines
11 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
// 证据文档 schema 版本与语义兼容批次是两件事:
// - ProtocolVersion:这份 JSON 的字段形状(解析契约);
// - ProtocolEpoch:派发协议语义批次;不同批次必须重新登记。它只约束派发语义,
// 不能证明某个构建 SHA 属于该批次 —— 当前构建身份仍精确绑定运行 SHA,跨 SHA
// 自动兼容在没有受信批次成员证明前保持关闭。
//
// 构建身份用完整 40 位 SHA,不用 display:开发号会随提交数变化,两个不同二进制
// 完全可能都叫 0.1.322。
const RestoreDispatchActivationProtocolVersion = 3
const RestoreDispatchProtocolEpoch = 3
// RestoreDispatchGovernanceAuthority 是治理库的**权威域**身份:系统标识(集群)
// 加库 OID。只看 current_database() 无法区分"同名但另一个集群/另一份克隆"。
// primary 由 Store 现场读 pg_is_in_recovery() 得出,不采信调用方声明。
type RestoreDispatchGovernanceAuthority struct {
SystemIdentifier string `json:"system_identifier"`
DatabaseOID string `json:"database_oid"`
}
// 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"`
ProtocolEpoch int `json:"protocol_epoch"`
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"`
GovernanceAuthority RestoreDispatchGovernanceAuthority `json:"governance_authority"`
ProtocolBuild string `json:"protocol_build"`
ProtocolBuildSHA string `json:"protocol_build_sha"`
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)
}
// 兼容批次不同 = 派发语义不兼容:即使 display 相同也不能共用激活证据。
if e.ProtocolEpoch != RestoreDispatchProtocolEpoch {
return fmt.Errorf("restore dispatch activation protocol epoch %d is not compatible with %d",
e.ProtocolEpoch, RestoreDispatchProtocolEpoch)
}
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)
}
}
// 构建身份必须是完整 SHA;display 可以随提交数变化,不能作为身份。
if !isFullSHA(e.ProtocolBuildSHA) {
return errors.New("restore dispatch activation build identity is not a full 40-character commit sha")
}
// 治理权威域必须是可读回的 PG 事实形状:集群系统标识 + 库 OID,两个都是十进制数字。
if !isDecimal(e.GovernanceAuthority.SystemIdentifier) || !isDecimal(e.GovernanceAuthority.DatabaseOID) {
return errors.New("restore dispatch activation governance authority is not a cluster/database identity")
}
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
}
func isFullSHA(value string) bool {
if len(value) != 40 || strings.ToLower(value) != value {
return false
}
_, err := hex.DecodeString(value)
return err == nil
}
func isDecimal(value string) bool {
if value == "" || len(value) > 20 {
return false
}
for _, r := range value {
if r < '0' || r > '9' {
return false
}
}
return true
}
// 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
}