Files
zapret-autotune/cmd/zapret-autotune/resource_plan_store.go
T
2026-10-14 12:21:52 +03:00

301 lines
9.2 KiB
Go

package main
import (
"bytes"
"crypto/hmac"
"crypto/rand"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"syscall"
"time"
)
const planKeyName = ".resource-plan-key"
const planRegistryName = ".resource-plan-strategies.json"
const planMatrixName = ".resource-plan-matrix.json"
// Reuse held-directory/private-entry checks, not monitor publication/lifecycle.
// Entries are write-once O_EXCL: no replacement, repair or clobber of foreign files.
type resourcePlanStore struct {
files *resourceMonitorStore
held map[string]*os.File
snapshots map[string][]byte
}
type planEnvelope struct {
Payload json.RawMessage `json:"payload"`
MAC string `json:"mac"`
}
func openResourcePlanStore(path string, create bool) (*resourcePlanStore, error) {
if managedDirectory(path) != nil {
return nil, errResourcePlan
}
fd, err := syscall.Open(path, syscall.O_RDONLY|syscall.O_DIRECTORY|syscall.O_NOFOLLOW|syscall.O_CLOEXEC, 0)
if err != nil {
return nil, err
}
s := &resourcePlanStore{files: &resourceMonitorStore{path: path, dir: os.NewFile(uintptr(fd), "plan directory")}, held: map[string]*os.File{}, snapshots: map[string][]byte{}}
fail := func(err error) (*resourcePlanStore, error) { s.close(); return nil, err }
for _, name := range []string{planKeyName, planRegistryName, planMatrixName} {
f, b, e := s.files.openEntry(name)
if e != nil && !errors.Is(e, os.ErrNotExist) {
return fail(errResourcePlan)
}
if e == nil {
s.held[name] = f
s.snapshots[name] = b
}
}
key := s.snapshots[planKeyName]
if key == nil && create && s.held[planRegistryName] == nil && s.held[planMatrixName] == nil {
key = make([]byte, 32)
if _, err = rand.Read(key); err != nil {
return fail(errResourcePlan)
}
if s.publish(planKeyName, key) != nil {
return fail(errResourcePlan)
}
}
if len(key) != 32 {
if !create && key == nil && s.held[planRegistryName] == nil && s.held[planMatrixName] == nil {
return fail(os.ErrNotExist)
}
return fail(errResourcePlan)
}
s.files.key = append([]byte(nil), key...)
if s.guard() != nil {
return fail(errResourcePlan)
}
return s, nil
}
func (s *resourcePlanStore) close() {
for _, f := range s.held {
f.Close()
}
s.files.dir.Close()
}
func (s *resourcePlanStore) guard() error {
if s.files.guard() != nil {
return errResourcePlan
}
names := map[string]bool{planKeyName: true, planRegistryName: true, planMatrixName: true}
for name := range s.held {
names[name] = true
}
for name := range names {
f := s.held[name]
if f == nil {
g, _, e := s.files.openEntry(name)
if g != nil {
g.Close()
}
if !errors.Is(e, os.ErrNotExist) {
return errResourcePlan
}
continue
}
b, e := s.files.trustedRead(name, f)
if e != nil || !bytes.Equal(b, s.snapshots[name]) {
return errResourcePlan
}
}
return nil
}
func (s *resourcePlanStore) publish(name string, b []byte) error {
if len(b) > 65536 || s.guard() != nil {
return errResourcePlan
}
fd, e := syscall.Openat(int(s.files.dir.Fd()), name, syscall.O_RDWR|syscall.O_CREAT|syscall.O_EXCL|syscall.O_NOFOLLOW|syscall.O_CLOEXEC, 0600)
if e != nil {
return errResourcePlan
}
f := os.NewFile(uintptr(fd), name)
// Keep incomplete entries on failure: never delete a possible foreign inode.
if _, e = f.Write(b); e != nil {
f.Close()
return errResourcePlan
}
if f.Sync() != nil || s.files.entryMatches(name, f) != nil {
f.Close()
return errResourcePlan
}
read, e := s.files.trustedRead(name, f)
if e != nil || !bytes.Equal(read, b) {
f.Close()
return errResourcePlan
}
s.held[name], s.snapshots[name] = f, append([]byte(nil), b...)
if s.files.dir.Sync() != nil || s.guard() != nil {
return errResourcePlan
}
return nil
}
func (s *resourcePlanStore) writeAuthenticated(name string, v interface{}) error {
b, e := json.Marshal(v)
if e != nil {
return errResourcePlan
}
envelope, e := json.Marshal(planEnvelope{Payload: b, MAC: resourceMAC(s.files.key, b)})
if e != nil {
return errResourcePlan
}
return s.publish(name, envelope)
}
func (s *resourcePlanStore) readAuthenticated(name string, dst interface{}) error {
if s.guard() != nil {
return errResourcePlan
}
if s.held[name] == nil {
return os.ErrNotExist
}
var envelope planEnvelope
if strictPlanJSON(s.snapshots[name], &envelope) != nil || !hmac.Equal([]byte(envelope.MAC), []byte(resourceMAC(s.files.key, envelope.Payload))) || strictPlanJSON(envelope.Payload, dst) != nil {
return errResourcePlan
}
return s.guard()
}
func (s *resourcePlanStore) registry() (strategyRegistry, error) {
var r strategyRegistry
if e := s.readAuthenticated(planRegistryName, &r); e != nil {
return r, e
}
b, _ := json.Marshal(r)
canonical, e := parseStrategyRegistry(b)
if e != nil || planDigest(canonical) != planDigest(r) {
return r, errResourcePlan
}
return r, nil
}
func (s *resourcePlanStore) importDefinitions(b []byte) error {
r, e := parseStrategyRegistry(b)
if e != nil {
return e
}
return s.writeAuthenticated(planRegistryName, r)
}
func (s *resourcePlanStore) saveCompleted(p completedQualification) error {
r, e := s.registry()
if e != nil || p.seal == "" || p.seal != planDigest(p.matrix) || validateMatrix(p.matrix, r) != nil {
return errResourcePlan
}
return s.writeAuthenticated(planMatrixName, p.matrix)
}
func (s *resourcePlanStore) matrix(r strategyRegistry) (qualificationMatrix, error) {
var m qualificationMatrix
e := s.readAuthenticated(planMatrixName, &m)
if e != nil {
return m, e
}
if validateMatrix(m, r) != nil {
return m, errResourcePlan
}
return m, nil
}
func resourcePlanCLI(args []string, stdout, stderr io.Writer, d managedDeps) int {
if os.Geteuid() != 0 {
fmt.Fprintln(stderr, "blocked: root target role required")
return 78
}
if _, err := managedTargetSettings(d.lookup); err != nil || d.directory != managedTargetDirectory {
fmt.Fprintln(stderr, "blocked: managed target required")
return 78
}
if len(args) == 6 && args[0] == "qualify" && args[1] == "--config" && args[3] == "--strategies" && args[5] == "--isolated" {
return qualifyResourceCLI(args[2], args[4], stdout, stderr, d)
}
if len(args) == 3 && args[0] == "qualify" && args[1] == "--config" {
fmt.Fprintln(stderr, "unknown: qualification requires --isolated and PID 1 isolated startup; no runtime changes made")
return 78
}
if len(args) == 5 && args[0] == "qualify" && args[1] == "--config" && args[3] == "--strategies" {
fmt.Fprintln(stderr, "unknown: qualification requires --isolated and PID 1 isolated startup; no runtime changes made")
return 78
}
if len(args) == 3 && args[0] == "strategy-import" && args[1] == "--strategies" {
fd, e := syscall.Open(args[2], syscall.O_RDONLY|syscall.O_NOFOLLOW|syscall.O_NONBLOCK|syscall.O_CLOEXEC, 0)
if e != nil {
fmt.Fprintln(stderr, "configerror: definitions unavailable")
return 64
}
f := os.NewFile(uintptr(fd), "definitions")
defer f.Close()
if resourcePrivateEntry(f) != nil {
fmt.Fprintln(stderr, "configerror: definitions require owned regular 0600 file")
return 64
}
b, e := io.ReadAll(io.LimitReader(f, 65537))
current, statErr := os.Lstat(args[2])
held, heldErr := f.Stat()
if e != nil || statErr != nil || heldErr != nil || !os.SameFile(current, held) || resourcePrivateEntry(f) != nil {
return 64
}
s, e := openResourcePlanStore(d.directory, true)
if e != nil {
fmt.Fprintln(stderr, "blocked: private registry unavailable")
return 78
}
defer s.close()
if s.importDefinitions(b) != nil {
fmt.Fprintln(stderr, "blocked: invalid definitions or immutable registry already exists")
return 78
}
fmt.Fprintln(stdout, "strategy definitions imported; qualification UNKNOWN")
return 0
}
if len(args) != 3 || args[0] != "plan" || args[1] != "--config" {
fmt.Fprintln(stderr, "usage: plan --config FILE | strategy-import --strategies FILE | qualify --config FILE --strategies FILE --isolated")
return 64
}
return resourcePlanProposal(args[2], stdout, stderr, d)
}
// Internal reader separated only to test the real CLI trust boundary in a
// temporary owned directory, without touching the provisioned target.
func resourcePlanProposal(configPath string, stdout, stderr io.Writer, d managedDeps) int {
key := make([]byte, 32)
registry := strategyRegistry{Version: 1, Strategies: []strategyDefinition{}}
var matrix qualificationMatrix
s, e := openResourcePlanStore(d.directory, false)
blocked := e != nil && !errors.Is(e, os.ErrNotExist)
if e == nil {
defer s.close()
key = s.files.key
registry, e = s.registry()
if e != nil {
blocked = !errors.Is(e, os.ErrNotExist)
registry = strategyRegistry{Version: 1, Strategies: []strategyDefinition{}}
}
if e == nil {
matrix, e = s.matrix(registry)
if e != nil {
blocked = !errors.Is(e, os.ErrNotExist)
matrix = qualificationMatrix{}
}
}
}
source, e := readResourceMonitorSource(configPath, d.lookup, key)
if e != nil {
fmt.Fprintln(stderr, "configerror: resource configuration unavailable")
return 64
}
p := deriveResourcePlan(source, key, registry, matrix, time.Now())
if blocked {
p.Evidence = "blocked"
}
if s != nil && s.guard() != nil {
p = deriveResourcePlan(source, key, registry, qualificationMatrix{}, time.Now())
p.Evidence = "blocked"
}
if json.NewEncoder(stdout).Encode(p) != nil {
return 1
}
if blocked || p.Evidence == "blocked" {
return 78
}
return 0
}