d-robotics 63512da71f
Some checks failed
web-ci / checks (push) Waiting to run
web-ci / checks (pull_request) Has been cancelled
🐛 Preserve confirmed annotation frames and enforce v4 time evidence
2026-10-22 12:54:08 +08:00

140 lines
6.0 KiB
Go

// Package sourceidentity verifies frozen BOS selections using object metadata.
// ETag plus size detects identity changes; it is not a cryptographic byte proof.
package sourceidentity
import (
"context"
"crypto/sha256"
"encoding/hex"
"fmt"
"path"
"reflect"
"regexp"
"sort"
"strconv"
"strings"
"time"
"droboticflow/internal/domain"
)
type Object struct {
Key, ETag string
Size int64
}
// Fingerprint preserves the capture discovery fingerprint byte for byte.
func Fingerprint(objects []Object) string {
lines := make([]string, 0, len(objects))
for _, o := range objects {
lines = append(lines, o.Key+"|"+strings.Trim(o.ETag, `"`)+"|"+strconv.FormatInt(o.Size, 10))
}
sort.Strings(lines)
sum := sha256.Sum256([]byte(strings.Join(lines, "\n")))
return hex.EncodeToString(sum[:])
}
type Selection struct {
Ref domain.ArtifactReference
Roles map[string]string
PartPrefix string
}
// FromRun uses only immutable run input evidence. The caller must resolve the
// exact original run (not a release child) through its persisted lineage.
func FromRun(run *domain.RunRecord, capture *domain.CaptureRecord) (*Selection, error) {
if run == nil || capture == nil || run.OrganizationID == "" || run.OrganizationID != capture.OrganizationID || run.ProjectID != capture.ProjectID || run.WorkflowID != capture.WorkflowID {
return nil, fmt.Errorf("original source tenant/project/workflow mismatch")
}
root, part := capture.SourcePrefix, path.Base(capture.Prefix)
if capture.ConnectionID == "" || capture.Bucket == "" || root == "." || root == "" || path.Clean(root) != root || strings.HasPrefix(root, "/") || strings.ContainsAny(root, "\\\x00\n\r|") || root == ".." || strings.HasPrefix(root, "../") || capture.Prefix != root+"/"+part || !regexp.MustCompile(`^part[0-9]{4,}$`).MatchString(part) || capture.CaptureID != path.Base(root)+"/"+part {
return nil, fmt.Errorf("invalid original capture/part scope")
}
var selected *Selection
for _, input := range run.Inputs {
ref := input.Ref
if ref == nil || ref.Provider != domain.StorageProviderBOS || ref.Kind != domain.ArtifactRefKindDirectory || ref.ConnectionID != capture.ConnectionID || ref.Bucket != capture.Bucket || ref.Prefix != root || ref.CaptureUnit != "" && ref.CaptureUnit != capture.CaptureID {
continue
}
digest, err := hex.DecodeString(ref.VersionID)
if err != nil || len(digest) != 32 || len(ref.ObjectKeys) < 8 || len(ref.ObjectKeys) > 10 {
return nil, fmt.Errorf("missing frozen original identity; explicit recovery required")
}
copyRef := *ref
copyRef.ObjectKeys = append([]string(nil), ref.ObjectKeys...)
sort.Strings(copyRef.ObjectKeys)
roles := map[string]string{}
capRE, partRE := regexp.QuoteMeta(path.Base(root)), regexp.QuoteMeta(part)
patterns := map[string]string{
"leftVideo": partRE + `/` + capRE + `_camera_left_` + partRE + `(?:_[a-z0-9_]+)?\.(?:mp4|mov|mkv)`,
"rightVideo": partRE + `/` + capRE + `_camera_right_` + partRE + `(?:_[a-z0-9_]+)?\.(?:mp4|mov|mkv)`,
"leftPts": partRE + `/` + capRE + `_camera_left_` + partRE + `(?:_[a-z0-9_]+)?_pts\.csv`,
"rightPts": partRE + `/` + capRE + `_camera_right_` + partRE + `(?:_[a-z0-9_]+)?_pts\.csv`,
"imu": partRE + `/` + capRE + `_imu_` + partRE + `\.csv`,
"cameraCalibration": capRE + `_calibration_camera\.yaml`,
"imuCalibration": capRE + `_calibration_imu\.yaml`,
"metadata": `meta_` + capRE + `\.json`,
}
for i, key := range copyRef.ObjectKeys {
if !strings.HasPrefix(key, root+"/") || path.Clean(key) != key || strings.ContainsAny(key, "\\\x00\n\r|") || i > 0 && key == copyRef.ObjectKeys[i-1] {
return nil, fmt.Errorf("unsafe/duplicate frozen source key")
}
rel := strings.TrimPrefix(key, root+"/")
matched := false
for role, pattern := range patterns {
if regexp.MustCompile(`(?i)^` + pattern + `$`).MatchString(rel) {
if roles[role] != "" {
return nil, fmt.Errorf("ambiguous frozen source role")
}
roles[role] = rel
matched = true
}
}
if !matched && !regexp.MustCompile(`(?i)^`+partRE+`/`+capRE+`_audio_`+partRE+`(?:_pts\.csv|\.wav)$`).MatchString(rel) {
return nil, fmt.Errorf("extra frozen source selection")
}
}
if len(roles) != 8 {
return nil, fmt.Errorf("incomplete frozen original source selection")
}
next := &Selection{Ref: copyRef, Roles: roles, PartPrefix: capture.Prefix}
if selected != nil && !reflect.DeepEqual(selected, next) {
return nil, fmt.Errorf("ambiguous frozen original inputs")
}
selected = next
}
if selected == nil {
return nil, fmt.Errorf("missing original run selection; explicit recovery required")
}
return selected, nil
}
func (s *Selection) MatchFiles(provider, bucket, prefix, partPrefix string, files map[string]string) error {
if provider != "BOS" || bucket != s.Ref.Bucket || prefix != s.Ref.Prefix || partPrefix != s.PartPrefix {
return fmt.Errorf("delivery original source scope mismatch")
}
if !reflect.DeepEqual(files, s.Roles) {
return fmt.Errorf("delivery original files differ from frozen run selection")
}
return nil
}
// Recheck performs at most ten sequential HEAD calls, including optional audio.
// It never lists objects or derives an expected fingerprint from current state.
func (s *Selection) Recheck(ctx context.Context, head func(context.Context, string, string) (domain.ObjectStorageObjectSummary, error)) error {
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
objects := make([]Object, 0, len(s.Ref.ObjectKeys))
for _, key := range s.Ref.ObjectKeys {
info, err := head(ctx, s.Ref.Bucket, key)
if err != nil || info.Key != key || info.Bucket != "" && info.Bucket != s.Ref.Bucket || info.Kind != "file" || info.SizeBytes <= 0 || strings.Trim(info.ETag, `"`) == "" {
return fmt.Errorf("original source HEAD missing/invalid: %s", key)
}
objects = append(objects, Object{Key: key, ETag: info.ETag, Size: info.SizeBytes})
}
if Fingerprint(objects) != s.Ref.VersionID {
return fmt.Errorf("original source identity changed; explicit recovery required")
}
return nil
}