ProofedMesh/services/dummy-sink/internal/sink/storage.go
CTO (Paperclip) b45ad34169
All checks were successful
validate / JSON Schema (ajv) (push) Successful in 19s
build-images / signing-service image (push) Successful in 22s
validate / Rego (opa fmt + opa test) (push) Successful in 13s
validate / DB (migrate up/down dry-run) (push) Successful in 26s
validate / Go (vet + test) (push) Successful in 1m13s
dummy-sink: Phase-1 mock sink (sink:dummy-sink) (DEV-611)
Trivial Senken-Adapter per §7 of architecture V1.1. Accepts
{decision_id, payload_hash, payload, approval_ref, transform_ref}
on POST /api/v1/sink/dummy/deliver; calls verification-service's
/api/v1/verify/chain and branches:

- valid=true → atomic .tmp+rename write of payload to
  /data/dummy-sink/<decision_id>.json, builds a
  basicstack.de/attestations/handover/v1 statement, signs via
  signing-service with the double identity flow (Pocket-ID bearer
  + projected SA token), submits DSSE envelope to the TLog and
  returns 201 {handover_ref, log_index}.
- valid=false & replay=true → 409.
- valid=false → 403 {reasons:[…]}.

Replay protection lives in verification-service per the parent plan;
dummy-sink keeps no local replay store. The payload_hash field is
verified against both the raw and canonical form so a verifier can
reproduce either hash.

Tests use httptest-backed fakes for verify / sign / tlog and cover
the DEV-611 acceptance criteria plus the bad-request shapes:
- happy path writes the file, calls signer with the handover
  statement, submits the envelope to the TLog
- 403 keeps the disk and never calls signer/tlog
- replay returns 409 without re-signing
- payload_hash mismatch rejects before verify
- malformed bodies return 400
- verify unavailable → 502, signing denied → 403

Co-Authored-By: Paperclip <noreply@paperclip.ing>
2026-10-25 20:20:40 +00:00

85 lines
2.8 KiB
Go

// Package sink persists verified payloads to local storage. It is the
// trivial "write a file and be done" tail of the Phase-1 trust chain:
// each delivery writes `<DataDir>/<decision_id>.json` atomically via
// `.tmp` + rename so a crash cannot leave a half-written file.
package sink
import (
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"regexp"
)
// decisionIDPattern is deliberately strict so decision_id can safely be
// pasted into a filesystem path. Approval- and verification-services
// generate decision_id values from UUIDs / sha256 digests, so this covers
// their output and nothing dangerous.
var decisionIDPattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$`)
// Store is a filesystem-backed payload store. All writes land in DataDir.
type Store struct {
DataDir string
}
// WriteResult is the record of an atomic payload write.
type WriteResult struct {
Path string
}
// ErrInvalidDecisionID is returned when decision_id would escape or
// otherwise be unsafe on the filesystem.
var ErrInvalidDecisionID = errors.New("sink: decision_id is not filesystem-safe")
// Write atomically writes payload to <DataDir>/<decisionID>.json.
// It writes to a sibling `<decisionID>.json.tmp` first and renames.
// Repeated calls with the same (decisionID) replace the file; replay
// protection is enforced by the verification-service per the Phase-1
// contract.
func (s Store) Write(decisionID string, payload any) (WriteResult, error) {
if s.DataDir == "" {
return WriteResult{}, errors.New("sink.Store: DataDir is required")
}
if !decisionIDPattern.MatchString(decisionID) {
return WriteResult{}, fmt.Errorf("%w: %q", ErrInvalidDecisionID, decisionID)
}
if err := os.MkdirAll(s.DataDir, 0o755); err != nil {
return WriteResult{}, fmt.Errorf("sink: ensure data dir: %w", err)
}
body, err := json.MarshalIndent(payload, "", " ")
if err != nil {
return WriteResult{}, fmt.Errorf("sink: marshal payload: %w", err)
}
body = append(body, '\n')
final := filepath.Join(s.DataDir, decisionID+".json")
tmp := final + ".tmp"
// Open with O_TRUNC so a crashed previous .tmp cannot taint the write.
f, err := os.OpenFile(tmp, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o640)
if err != nil {
return WriteResult{}, fmt.Errorf("sink: open tmp: %w", err)
}
if _, err := f.Write(body); err != nil {
_ = f.Close()
_ = os.Remove(tmp)
return WriteResult{}, fmt.Errorf("sink: write tmp: %w", err)
}
if err := f.Sync(); err != nil {
_ = f.Close()
_ = os.Remove(tmp)
return WriteResult{}, fmt.Errorf("sink: fsync tmp: %w", err)
}
if err := f.Close(); err != nil {
_ = os.Remove(tmp)
return WriteResult{}, fmt.Errorf("sink: close tmp: %w", err)
}
if err := os.Rename(tmp, final); err != nil {
_ = os.Remove(tmp)
return WriteResult{}, fmt.Errorf("sink: rename to final: %w", err)
}
return WriteResult{Path: final}, nil
}