You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
636 lines
28 KiB
Go
636 lines
28 KiB
Go
// Package domaincreateattach defines the read-only host-bound boundary that
|
|
// precedes a future VM create operation.
|
|
//
|
|
// The package turns a typed, pre-host domain policy into a host-bound base XML
|
|
// (by applying a loader selected from a fresh capability observation), verifies
|
|
// an immutable NoCloud artifact, and validates already-resolved disk paths
|
|
// against the agent storage allowlist. It does not create files, allocate
|
|
// volumes, attach devices, define a domain, change power, or configure a
|
|
// network. The returned Plan is an executor input; its safe Result projection
|
|
// deliberately excludes host paths and raw XML.
|
|
package domaincreateattach
|
|
|
|
import (
|
|
"context"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io/fs"
|
|
"os"
|
|
"path/filepath"
|
|
"regexp"
|
|
"sort"
|
|
"strings"
|
|
|
|
"g.luoli.live/root/virt/agent/internal/domaincreateplan"
|
|
"g.luoli.live/root/virt/agent/internal/domainpreflight"
|
|
"g.luoli.live/root/virt/agent/internal/domainxml"
|
|
"g.luoli.live/root/virt/agent/internal/hypervisor"
|
|
"g.luoli.live/root/virt/agent/internal/startup"
|
|
"g.luoli.live/root/virt/agent/internal/storagepolicy"
|
|
)
|
|
|
|
const (
|
|
codePrefix = "domain_create_attach_"
|
|
// Kind is the reserved greenfield operation kind for a future API adapter.
|
|
Kind = "domain_create_attach"
|
|
// CommitBoundaryChecked means all immutable host-bound inputs passed the
|
|
// read-only gate; it does not mean a disk, seed, or domain was attached.
|
|
CommitBoundaryChecked = "domain_create_attach_checked"
|
|
maxDiskAttachments = 32
|
|
)
|
|
|
|
var (
|
|
// ErrInvalidRequest identifies a malformed typed request. It is definitive
|
|
// because no host mutation is needed to reject it.
|
|
ErrInvalidRequest = errors.New("invalid domain create attach request")
|
|
// ErrSeedRejected identifies a missing, malformed, or mismatched immutable
|
|
// seed. A caller must publish a new artifact instead of retrying the same
|
|
// identity after this error.
|
|
ErrSeedRejected = errors.New("domain create seed rejected")
|
|
// ErrStorageRejected identifies a disk intent that is outside the explicit
|
|
// host storage policy or otherwise cannot be accepted as an existing image.
|
|
ErrStorageRejected = errors.New("domain create storage rejected")
|
|
// ErrHostUnavailable identifies a host filesystem or loader observation that
|
|
// did not complete. Reconciliation may retry after the operator repairs the
|
|
// host; this package never retries a mutation.
|
|
ErrHostUnavailable = errors.New("domain create host attachment inputs unavailable")
|
|
// ErrCanceled identifies a caller cancellation. The operation remains
|
|
// uncertain because this boundary intentionally does not claim a mutation.
|
|
ErrCanceled = errors.New("domain create attach validation canceled")
|
|
|
|
volumeIDPattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$`)
|
|
)
|
|
|
|
// Error carries a stable operation code while retaining a local cause for
|
|
// tests and diagnostics. Message is generic and must not contain a host path,
|
|
// seed content, or another tenant-controlled secret.
|
|
type Error struct {
|
|
CodeValue string `json:"code"`
|
|
Message string `json:"message"`
|
|
Definitive bool `json:"definitive"`
|
|
Cause error `json:"-"`
|
|
}
|
|
|
|
func (e *Error) Error() string {
|
|
if e == nil {
|
|
return codePrefix + "failed"
|
|
}
|
|
if e.Message == "" {
|
|
return e.CodeValue
|
|
}
|
|
return e.CodeValue + ": " + e.Message
|
|
}
|
|
|
|
func (e *Error) Unwrap() error {
|
|
if e == nil {
|
|
return nil
|
|
}
|
|
return e.Cause
|
|
}
|
|
|
|
func newError(code, message string, definitive bool, cause error) error {
|
|
return &Error{CodeValue: code, Message: message, Definitive: definitive, Cause: cause}
|
|
}
|
|
|
|
// Code returns the stable operation code intended for operation.ErrorCode.
|
|
func Code(err error) string {
|
|
var typed *Error
|
|
if errors.As(err, &typed) && typed != nil && typed.CodeValue != "" {
|
|
return typed.CodeValue
|
|
}
|
|
return codePrefix + "failed"
|
|
}
|
|
|
|
// IsDefinitive reports whether the request was rejected without an ambiguous
|
|
// host-side mutation. Host filesystem/loader availability and cancellation are
|
|
// intentionally non-definitive.
|
|
func IsDefinitive(err error) bool {
|
|
var typed *Error
|
|
return errors.As(err, &typed) && typed != nil && typed.Definitive
|
|
}
|
|
|
|
// DiskAttachment is a host-side resolution of one opaque volume identity.
|
|
// Path must come from an agent-owned storage resolver, not directly from a
|
|
// panel payload; it is still checked against StorageRoots as defense in depth.
|
|
// Slot is translated to a device name by a later executor, which keeps device
|
|
// XML and bus choices out of this boundary.
|
|
type DiskAttachment struct {
|
|
VolumeID string `json:"volume_id"`
|
|
Slot int `json:"slot"`
|
|
Readonly bool `json:"readonly"`
|
|
Path string `json:"-"`
|
|
}
|
|
|
|
// Request is the minimal host-bound input. Domain remains typed and contains
|
|
// no XML, disk, interface, or network fields. LoaderPath must be selected by a
|
|
// fresh host capability observation; ArtifactRoot and disk Path values are
|
|
// agent-side configuration/resolver outputs and are never accepted from the
|
|
// HTTP payload directly.
|
|
type Request struct {
|
|
Domain domainpreflight.Request `json:"domain"`
|
|
LoaderPath string `json:"-"`
|
|
ArtifactRoot string `json:"-"`
|
|
StorageRoots []string `json:"-"`
|
|
SeedArtifactID string `json:"seed_artifact_id"`
|
|
SeedManifest domaincreateplan.SeedManifest `json:"seed_manifest"`
|
|
StartupScriptPresent bool `json:"first_boot_present"`
|
|
StartupScriptSHA256 string `json:"first_boot_digest"`
|
|
Disks []DiskAttachment `json:"disks,omitempty"`
|
|
}
|
|
|
|
// Result is the safe journal/API projection. It contains identities and
|
|
// counts, but no host path, raw domain XML, disk source, or seed bytes.
|
|
type Result struct {
|
|
CommitBoundary string `json:"commit_boundary"`
|
|
DomainUUID string `json:"domain_uuid"`
|
|
DomainXMLHash string `json:"domain_xml_hash"`
|
|
SeedArtifactID string `json:"seed_artifact_id"`
|
|
SeedManifest domaincreateplan.SeedManifest `json:"seed_manifest"`
|
|
StartupScriptPresent bool `json:"first_boot_present"`
|
|
StartupScriptSHA256 string `json:"first_boot_digest"`
|
|
DiskCount int `json:"disk_count"`
|
|
DiskPlanHash string `json:"disk_plan_hash"`
|
|
PlanHash string `json:"plan_hash"`
|
|
LoaderPending bool `json:"loader_pending"`
|
|
}
|
|
|
|
// Plan is the executor-only result. The unexported fields cannot be serialized
|
|
// accidentally with encoding/json. Accessors return defensive copies; an
|
|
// eventual mutating executor must perform its own open/read-back/TOCTOU checks
|
|
// immediately before define or attach.
|
|
type Plan struct {
|
|
Result
|
|
hostXML []byte
|
|
seedDirectory string
|
|
disks []DiskAttachment
|
|
}
|
|
|
|
// String deliberately renders only the safe Result projection. The executor
|
|
// plan carries host paths and raw XML in private fields; default fmt output
|
|
// must not turn an accidental diagnostic log into a host-path disclosure.
|
|
func (p Plan) String() string {
|
|
encoded, err := json.Marshal(p.Result)
|
|
if err != nil {
|
|
return "{\"plan\":\"unavailable\"}"
|
|
}
|
|
return string(encoded)
|
|
}
|
|
|
|
// GoString protects %#v diagnostics for the same reason as String.
|
|
func (p Plan) GoString() string { return p.String() }
|
|
|
|
// HostXML returns the host-bound base XML with the capability-selected loader.
|
|
// It intentionally contains no disk or network elements; a future executor
|
|
// must construct those from the typed DiskAttachments contract.
|
|
func (p Plan) HostXML() []byte { return append([]byte(nil), p.hostXML...) }
|
|
|
|
// SeedDirectory returns the immutable artifact directory selected by the
|
|
// configured root and canonical artifact UUID. It is for the host executor,
|
|
// not for a durable API result.
|
|
func (p Plan) SeedDirectory() string { return p.seedDirectory }
|
|
|
|
// DiskAttachments returns defensive copies of the already policy-checked
|
|
// resolver outputs. Path remains excluded from JSON, but the executor must
|
|
// revalidate it with an openat/O_NOFOLLOW-style boundary before attach.
|
|
func (p Plan) DiskAttachments() []DiskAttachment {
|
|
return cloneDisks(p.disks)
|
|
}
|
|
|
|
// Build validates all host-bound inputs without performing a host mutation.
|
|
// It is safe to call before durable commit; a caller should persist only Result
|
|
// and retain the operation ID, not the returned host paths/XML, in its journal.
|
|
func Build(ctx context.Context, request Request) (Plan, error) {
|
|
if ctx == nil {
|
|
ctx = context.Background()
|
|
}
|
|
if err := ctx.Err(); err != nil {
|
|
return Plan{}, newError(codePrefix+"canceled", "attach validation was canceled", false, fmt.Errorf("%w: %v", ErrCanceled, err))
|
|
}
|
|
|
|
canonicalDomain, err := domainpreflight.ValidateRequest(request.Domain)
|
|
if err != nil {
|
|
return Plan{}, newError(codePrefix+"invalid_domain", "domain policy is invalid", true, fmt.Errorf("%w: %v", ErrInvalidRequest, err))
|
|
}
|
|
request.Domain = canonicalDomain
|
|
if err := validateArtifactRoot(request.ArtifactRoot); err != nil {
|
|
return Plan{}, err
|
|
}
|
|
artifactID, err := canonicalArtifactID(request.SeedArtifactID)
|
|
if err != nil {
|
|
return Plan{}, newError(codePrefix+"invalid_seed_artifact", "seed artifact identity is invalid", true, fmt.Errorf("%w: %v", ErrInvalidRequest, err))
|
|
}
|
|
request.SeedArtifactID = artifactID
|
|
if err := validateExpectedManifest(request.SeedManifest); err != nil {
|
|
return Plan{}, newError(codePrefix+"invalid_seed_manifest", "seed manifest identity is invalid", true, fmt.Errorf("%w: %v", ErrInvalidRequest, err))
|
|
}
|
|
if err := validateStartupExpectation(request.StartupScriptPresent, request.StartupScriptSHA256); err != nil {
|
|
return Plan{}, err
|
|
}
|
|
for _, root := range request.StorageRoots {
|
|
if strings.TrimSpace(root) != root || filepath.Clean(root) != root {
|
|
return Plan{}, newError(codePrefix+"storage_rejected", "storage root is not canonical", true, fmt.Errorf("%w: non-canonical storage root", ErrStorageRejected))
|
|
}
|
|
}
|
|
if err := validateDisks(request.Disks); err != nil {
|
|
return Plan{}, err
|
|
}
|
|
|
|
// Render and pin the loader before touching the artifact or disk paths. The
|
|
// raw caller cannot supply XML or a loader flag that bypasses this policy.
|
|
if request.LoaderPath == "" || strings.TrimSpace(request.LoaderPath) != request.LoaderPath || filepath.Clean(request.LoaderPath) != request.LoaderPath {
|
|
return Plan{}, newError(codePrefix+"loader_rejected", "host firmware loader path is not canonical", true, fmt.Errorf("%w: non-canonical loader path", ErrInvalidRequest))
|
|
}
|
|
preHostXML, err := domainpreflight.RenderRequest(request.Domain)
|
|
if err != nil {
|
|
return Plan{}, newError(codePrefix+"invalid_domain", "domain policy could not be rendered", true, fmt.Errorf("%w: %v", ErrInvalidRequest, err))
|
|
}
|
|
hostXML, err := domainxml.NormalizeWithLoader(preHostXML, request.LoaderPath)
|
|
if err != nil {
|
|
return Plan{}, newError(codePrefix+"loader_rejected", "host firmware loader does not satisfy policy", true, fmt.Errorf("%w: %v", ErrInvalidRequest, err))
|
|
}
|
|
if err := verifyLoaderFile(request.LoaderPath); err != nil {
|
|
return Plan{}, err
|
|
}
|
|
if err := domainxml.Validate(hostXML); err != nil {
|
|
return Plan{}, newError(codePrefix+"loader_rejected", "host-bound firmware XML failed policy validation", true, fmt.Errorf("%w: %v", ErrInvalidRequest, err))
|
|
}
|
|
|
|
if err := checkContext(ctx); err != nil {
|
|
return Plan{}, err
|
|
}
|
|
seedDirectory := filepath.Join(request.ArtifactRoot, artifactID)
|
|
if filepath.Dir(seedDirectory) != request.ArtifactRoot || filepath.Base(seedDirectory) != artifactID {
|
|
return Plan{}, newError(codePrefix+"invalid_seed_artifact", "seed artifact identity is not safely scoped", true, fmt.Errorf("%w: %v", ErrInvalidRequest, hypervisor.ErrInvalidUUID))
|
|
}
|
|
verified, err := startup.VerifySeedDirectoryDetails(seedDirectory)
|
|
if err != nil {
|
|
return Plan{}, classifySeedError(err)
|
|
}
|
|
if err := checkContext(ctx); err != nil {
|
|
return Plan{}, err
|
|
}
|
|
if !manifestEqual(verified.Manifest, request.SeedManifest) ||
|
|
verified.StartupScriptIncluded != request.StartupScriptPresent ||
|
|
verified.StartupScriptSHA256 != request.StartupScriptSHA256 {
|
|
return Plan{}, newError(codePrefix+"seed_artifact_rejected", "seed artifact does not match the requested identity", true, ErrSeedRejected)
|
|
}
|
|
|
|
paths := make([]string, 0, len(request.Disks))
|
|
for _, disk := range request.Disks {
|
|
paths = append(paths, disk.Path)
|
|
}
|
|
policy, err := storagepolicy.New(request.StorageRoots)
|
|
if err != nil {
|
|
return Plan{}, newError(codePrefix+"storage_rejected", "storage policy is invalid", true, fmt.Errorf("%w: %v", ErrStorageRejected, err))
|
|
}
|
|
if err := policy.ValidatePaths(paths); err != nil {
|
|
return Plan{}, classifyStorageError(err)
|
|
}
|
|
if duplicate := duplicateDiskPath(request.Disks); duplicate {
|
|
return Plan{}, newError(codePrefix+"storage_rejected", "disk paths must resolve to distinct volumes", true, fmt.Errorf("%w: duplicate resolved path", ErrStorageRejected))
|
|
}
|
|
if err := checkContext(ctx); err != nil {
|
|
return Plan{}, err
|
|
}
|
|
|
|
xmlHash := digest(hostXML)
|
|
diskHash := digestDiskPlan(request.Disks)
|
|
planHash := digestPlan(planIdentity{
|
|
DomainUUID: request.Domain.UUID,
|
|
DomainXMLHash: xmlHash,
|
|
SeedArtifactID: request.SeedArtifactID,
|
|
SeedManifest: request.SeedManifest,
|
|
StartupScriptPresent: request.StartupScriptPresent,
|
|
StartupScriptSHA256: request.StartupScriptSHA256,
|
|
DiskPlanHash: diskHash,
|
|
})
|
|
result := Result{
|
|
CommitBoundary: CommitBoundaryChecked,
|
|
DomainUUID: request.Domain.UUID,
|
|
DomainXMLHash: xmlHash,
|
|
SeedArtifactID: request.SeedArtifactID,
|
|
SeedManifest: request.SeedManifest,
|
|
StartupScriptPresent: request.StartupScriptPresent,
|
|
StartupScriptSHA256: request.StartupScriptSHA256,
|
|
DiskCount: len(request.Disks),
|
|
DiskPlanHash: diskHash,
|
|
PlanHash: planHash,
|
|
LoaderPending: false,
|
|
}
|
|
return Plan{
|
|
Result: result,
|
|
hostXML: append([]byte(nil), hostXML...),
|
|
seedDirectory: seedDirectory,
|
|
disks: cloneDisks(request.Disks),
|
|
}, nil
|
|
}
|
|
|
|
// Validate is an alias that makes the no-side-effect behavior explicit at
|
|
// call sites that do not yet need to retain the executor plan.
|
|
func Validate(ctx context.Context, request Request) (Plan, error) {
|
|
return Build(ctx, request)
|
|
}
|
|
|
|
// BuildWithLoaderProvider obtains the firmware loader from a fresh host
|
|
// capability observation before building the host-bound plan. The caller
|
|
// cannot choose or reuse a loader path through this entry point; a provider
|
|
// failure is recoverable host unavailability, while the typed request and
|
|
// filesystem policy remain handled by Build.
|
|
func BuildWithLoaderProvider(ctx context.Context, provider hypervisor.LoaderPathProvider, request Request) (Plan, error) {
|
|
if ctx == nil {
|
|
ctx = context.Background()
|
|
}
|
|
if err := checkContext(ctx); err != nil {
|
|
return Plan{}, err
|
|
}
|
|
if provider == nil {
|
|
return Plan{}, newError(codePrefix+"loader_unavailable", "host firmware loader selection is unavailable", false, ErrHostUnavailable)
|
|
}
|
|
canonicalDomain, err := domainpreflight.ValidateRequest(request.Domain)
|
|
if err != nil {
|
|
return Plan{}, newError(codePrefix+"invalid_domain", "domain policy is invalid", true, fmt.Errorf("%w: %v", ErrInvalidRequest, err))
|
|
}
|
|
request.Domain = canonicalDomain
|
|
loaderPath, err := provider.PreferredNonSecureLoaderPath(ctx)
|
|
if err != nil {
|
|
if contextErr := ctx.Err(); contextErr != nil {
|
|
return Plan{}, newError(codePrefix+"canceled", "attach validation was canceled", false, fmt.Errorf("%w: %v", ErrCanceled, contextErr))
|
|
}
|
|
// A fresh capability observation can prove that the host has no
|
|
// acceptable non-Secure-Boot loader. That is a definitive host policy
|
|
// rejection, not a transport outcome that should be retried forever.
|
|
// Keep the hypervisor sentinel wrapped so callers can distinguish this
|
|
// from a missing/unreadable capability response.
|
|
if hypervisor.IsDefinitive(err) {
|
|
return Plan{}, newError(codePrefix+"loader_rejected", "host firmware policy does not provide a non-secure loader", true, fmt.Errorf("%w: %v", hypervisor.ErrCapabilityPolicy, err))
|
|
}
|
|
return Plan{}, newError(codePrefix+"loader_unavailable", "host firmware loader selection is unavailable", false, fmt.Errorf("%w: %v", ErrHostUnavailable, err))
|
|
}
|
|
request.LoaderPath = loaderPath
|
|
return Build(ctx, request)
|
|
}
|
|
|
|
type planIdentity struct {
|
|
DomainUUID string `json:"domain_uuid"`
|
|
DomainXMLHash string `json:"domain_xml_hash"`
|
|
SeedArtifactID string `json:"seed_artifact_id"`
|
|
SeedManifest domaincreateplan.SeedManifest `json:"seed_manifest"`
|
|
StartupScriptPresent bool `json:"first_boot_present"`
|
|
StartupScriptSHA256 string `json:"first_boot_digest"`
|
|
DiskPlanHash string `json:"disk_plan_hash"`
|
|
}
|
|
|
|
type diskIdentity struct {
|
|
VolumeID string `json:"volume_id"`
|
|
Slot int `json:"slot"`
|
|
Readonly bool `json:"readonly"`
|
|
}
|
|
|
|
func validateDisks(disks []DiskAttachment) error {
|
|
if len(disks) > maxDiskAttachments {
|
|
return newError(codePrefix+"storage_rejected", "too many disk attachments", true, fmt.Errorf("%w: disk count exceeds %d", ErrStorageRejected, maxDiskAttachments))
|
|
}
|
|
seenIDs := make(map[string]struct{}, len(disks))
|
|
seenSlots := make(map[int]struct{}, len(disks))
|
|
for _, disk := range disks {
|
|
if !volumeIDPattern.MatchString(disk.VolumeID) {
|
|
return newError(codePrefix+"storage_rejected", "disk volume identity is invalid", true, fmt.Errorf("%w: invalid volume identity", ErrStorageRejected))
|
|
}
|
|
if _, exists := seenIDs[disk.VolumeID]; exists {
|
|
return newError(codePrefix+"storage_rejected", "disk volume identities must be unique", true, fmt.Errorf("%w: duplicate volume identity", ErrStorageRejected))
|
|
}
|
|
seenIDs[disk.VolumeID] = struct{}{}
|
|
if disk.Slot < 0 || disk.Slot >= maxDiskAttachments {
|
|
return newError(codePrefix+"storage_rejected", "disk slot is invalid", true, fmt.Errorf("%w: slot out of range", ErrStorageRejected))
|
|
}
|
|
if _, exists := seenSlots[disk.Slot]; exists {
|
|
return newError(codePrefix+"storage_rejected", "disk slots must be unique", true, fmt.Errorf("%w: duplicate disk slot", ErrStorageRejected))
|
|
}
|
|
seenSlots[disk.Slot] = struct{}{}
|
|
if disk.Path == "" {
|
|
return newError(codePrefix+"storage_rejected", "disk path was not resolved by the agent", true, fmt.Errorf("%w: missing resolved disk path", ErrStorageRejected))
|
|
}
|
|
if strings.TrimSpace(disk.Path) != disk.Path || filepath.Clean(disk.Path) != disk.Path {
|
|
return newError(codePrefix+"storage_rejected", "disk path is not canonical", true, fmt.Errorf("%w: non-canonical disk path", ErrStorageRejected))
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func validateExpectedManifest(manifest domaincreateplan.SeedManifest) error {
|
|
if manifest.Version != startup.SeedManifestVersion {
|
|
return fmt.Errorf("%w: unsupported seed manifest version", ErrInvalidRequest)
|
|
}
|
|
for _, digest := range []domaincreateplan.FileDigest{manifest.User, manifest.Meta, manifest.Network} {
|
|
if digest.Bytes < 0 || digest.Bytes > startup.MaxFileBytes || len(digest.SHA256) != sha256.Size*2 || strings.ToLower(digest.SHA256) != digest.SHA256 {
|
|
return fmt.Errorf("%w: seed manifest digest is invalid", ErrInvalidRequest)
|
|
}
|
|
if _, err := hex.DecodeString(digest.SHA256); err != nil {
|
|
return fmt.Errorf("%w: seed manifest digest is invalid", ErrInvalidRequest)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func validateStartupExpectation(present bool, digestValue string) error {
|
|
if len(digestValue) != sha256.Size*2 || strings.ToLower(digestValue) != digestValue {
|
|
return newError(codePrefix+"invalid_seed_manifest", "startup-script digest identity is invalid", true, fmt.Errorf("%w: invalid startup digest", ErrInvalidRequest))
|
|
}
|
|
if _, err := hex.DecodeString(digestValue); err != nil {
|
|
return newError(codePrefix+"invalid_seed_manifest", "startup-script digest identity is invalid", true, fmt.Errorf("%w: invalid startup digest", ErrInvalidRequest))
|
|
}
|
|
emptyDigest := digest(nil)
|
|
if present == (digestValue == emptyDigest) {
|
|
return newError(codePrefix+"invalid_seed_manifest", "startup-script presence and digest disagree", true, fmt.Errorf("%w: inconsistent startup identity", ErrInvalidRequest))
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func validateArtifactRoot(root string) error {
|
|
if root == "" || strings.TrimSpace(root) != root || strings.IndexByte(root, 0) >= 0 {
|
|
return newError(codePrefix+"artifact_unavailable", "seed artifact storage is unavailable", false, fmt.Errorf("%w: %v", ErrHostUnavailable, startup.ErrArtifactPath))
|
|
}
|
|
clean := filepath.Clean(root)
|
|
if !filepath.IsAbs(root) || clean != root || clean == string(filepath.Separator) {
|
|
return newError(codePrefix+"invalid_artifact_root", "seed artifact root is invalid", true, fmt.Errorf("%w: %v", ErrInvalidRequest, startup.ErrArtifactPath))
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func canonicalArtifactID(value string) (string, error) {
|
|
canonical, err := hypervisor.CanonicalUUID(value)
|
|
if err != nil || canonical != value {
|
|
if err == nil {
|
|
err = fmt.Errorf("%w: UUID must already be canonical", hypervisor.ErrInvalidUUID)
|
|
}
|
|
return "", err
|
|
}
|
|
return canonical, nil
|
|
}
|
|
|
|
func verifyLoaderFile(path string) error {
|
|
if err := verifyLoaderAncestors(path); err != nil {
|
|
return err
|
|
}
|
|
info, err := os.Lstat(path)
|
|
if err != nil {
|
|
if errors.Is(err, fs.ErrNotExist) || errors.Is(err, fs.ErrPermission) || os.IsPermission(err) {
|
|
return newError(codePrefix+"loader_unavailable", "host firmware loader is unavailable", false, fmt.Errorf("%w: %v", ErrHostUnavailable, err))
|
|
}
|
|
return newError(codePrefix+"loader_unavailable", "host firmware loader could not be inspected", false, fmt.Errorf("%w: %v", ErrHostUnavailable, err))
|
|
}
|
|
if info.Mode()&os.ModeSymlink != 0 || !info.Mode().IsRegular() || info.Mode().Perm()&0o022 != 0 || info.Mode()&(os.ModeSetuid|os.ModeSetgid|os.ModeSticky) != 0 {
|
|
return newError(codePrefix+"loader_rejected", "host firmware loader is not a private regular file", true, fmt.Errorf("%w: %v", ErrInvalidRequest, domainxml.ErrPolicyViolation))
|
|
}
|
|
resolved, err := filepath.EvalSymlinks(path)
|
|
if err != nil {
|
|
return newError(codePrefix+"loader_unavailable", "host firmware loader could not be resolved", false, fmt.Errorf("%w: %v", ErrHostUnavailable, err))
|
|
}
|
|
if resolved != path {
|
|
return newError(codePrefix+"loader_rejected", "host firmware loader path is an alias", true, fmt.Errorf("%w: %v", ErrInvalidRequest, domainxml.ErrPolicyViolation))
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// verifyLoaderAncestors rejects caller-controlled aliases and writable
|
|
// directory components before a capability-selected loader is embedded in
|
|
// host XML. The eventual executor still has to repeat this check immediately
|
|
// before define; this is a preflight boundary, not an atomic open guarantee.
|
|
func verifyLoaderAncestors(path string) error {
|
|
clean := filepath.Clean(path)
|
|
if clean == "." || !filepath.IsAbs(clean) {
|
|
return newError(codePrefix+"loader_rejected", "host firmware loader path is not canonical", true, fmt.Errorf("%w: %v", ErrInvalidRequest, domainxml.ErrPolicyViolation))
|
|
}
|
|
root := filepath.VolumeName(clean) + string(filepath.Separator)
|
|
if filepath.VolumeName(clean) == "" {
|
|
root = string(filepath.Separator)
|
|
}
|
|
rest := strings.TrimPrefix(clean, root)
|
|
current := root
|
|
for _, component := range strings.Split(rest, string(filepath.Separator)) {
|
|
if component == "" || component == "." {
|
|
continue
|
|
}
|
|
current = filepath.Join(current, component)
|
|
info, err := os.Lstat(current)
|
|
if err != nil {
|
|
if errors.Is(err, fs.ErrNotExist) || errors.Is(err, fs.ErrPermission) || os.IsPermission(err) {
|
|
return newError(codePrefix+"loader_unavailable", "host firmware loader is unavailable", false, fmt.Errorf("%w: %v", ErrHostUnavailable, err))
|
|
}
|
|
return newError(codePrefix+"loader_unavailable", "host firmware loader could not be inspected", false, fmt.Errorf("%w: %v", ErrHostUnavailable, err))
|
|
}
|
|
if info.Mode()&os.ModeSymlink != 0 {
|
|
return newError(codePrefix+"loader_rejected", "host firmware loader path is an alias", true, fmt.Errorf("%w: %v", ErrInvalidRequest, domainxml.ErrPolicyViolation))
|
|
}
|
|
if current != clean && !info.IsDir() {
|
|
return newError(codePrefix+"loader_rejected", "host firmware loader parent is not a directory", true, fmt.Errorf("%w: %v", ErrInvalidRequest, domainxml.ErrPolicyViolation))
|
|
}
|
|
if current != clean && !safeLoaderDirectoryMode(info.Mode()) {
|
|
return newError(codePrefix+"loader_rejected", "host firmware loader parent is writable by group or other users", true, fmt.Errorf("%w: %v", ErrInvalidRequest, domainxml.ErrPolicyViolation))
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func safeLoaderDirectoryMode(mode os.FileMode) bool {
|
|
if mode&(os.ModeSetuid|os.ModeSetgid) != 0 {
|
|
return false
|
|
}
|
|
if mode.Perm()&0o022 == 0 {
|
|
return true
|
|
}
|
|
// Standard shared temporary roots are sticky-protected; the actual loader
|
|
// file is still required to be a private regular file below this boundary.
|
|
return mode&os.ModeSticky != 0
|
|
}
|
|
|
|
func classifySeedError(err error) error {
|
|
if errors.Is(err, fs.ErrPermission) || os.IsPermission(err) || errors.Is(err, startup.ErrArtifactPath) {
|
|
return newError(codePrefix+"artifact_unavailable", "seed artifact storage is unavailable", false, fmt.Errorf("%w: %v", ErrHostUnavailable, err))
|
|
}
|
|
if errors.Is(err, startup.ErrInvalidArtifact) {
|
|
return newError(codePrefix+"seed_artifact_rejected", "seed artifact is missing or invalid", true, fmt.Errorf("%w: %v", ErrSeedRejected, err))
|
|
}
|
|
return newError(codePrefix+"artifact_unavailable", "seed artifact could not be read", false, fmt.Errorf("%w: %v", ErrHostUnavailable, err))
|
|
}
|
|
|
|
func classifyStorageError(err error) error {
|
|
if errors.Is(err, storagepolicy.ErrRootUnavailable) || errors.Is(err, fs.ErrPermission) || os.IsPermission(err) {
|
|
return newError(codePrefix+"storage_unavailable", "configured storage is unavailable", false, fmt.Errorf("%w: %v", ErrHostUnavailable, err))
|
|
}
|
|
if storagepolicy.IsDefinitive(err) {
|
|
return newError(codePrefix+"storage_rejected", "disk path does not satisfy the storage policy", true, fmt.Errorf("%w: %v", ErrStorageRejected, err))
|
|
}
|
|
return newError(codePrefix+"storage_unavailable", "disk path could not be checked", false, fmt.Errorf("%w: %v", ErrHostUnavailable, err))
|
|
}
|
|
|
|
func manifestEqual(observed startup.SeedManifest, expected domaincreateplan.SeedManifest) bool {
|
|
if observed.Version != expected.Version || len(observed.Files) != 3 {
|
|
return false
|
|
}
|
|
wanted := map[string]domaincreateplan.FileDigest{
|
|
startup.UserDataFilename: expected.User,
|
|
startup.MetaDataFilename: expected.Meta,
|
|
startup.NetworkConfigFilename: expected.Network,
|
|
}
|
|
for name, want := range wanted {
|
|
got, ok := observed.Files[name]
|
|
if !ok || got.Bytes != want.Bytes || got.SHA256 != want.SHA256 {
|
|
return false
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
|
|
func digestDiskPlan(disks []DiskAttachment) string {
|
|
identities := make([]diskIdentity, 0, len(disks))
|
|
for _, disk := range disks {
|
|
identities = append(identities, diskIdentity{VolumeID: disk.VolumeID, Slot: disk.Slot, Readonly: disk.Readonly})
|
|
}
|
|
sort.Slice(identities, func(left, right int) bool {
|
|
if identities[left].Slot != identities[right].Slot {
|
|
return identities[left].Slot < identities[right].Slot
|
|
}
|
|
return identities[left].VolumeID < identities[right].VolumeID
|
|
})
|
|
data, _ := json.Marshal(identities)
|
|
return digest(data)
|
|
}
|
|
|
|
func digestPlan(identity planIdentity) string {
|
|
data, _ := json.Marshal(identity)
|
|
return digest(data)
|
|
}
|
|
|
|
func duplicateDiskPath(disks []DiskAttachment) bool {
|
|
seen := make(map[string]struct{}, len(disks))
|
|
for _, disk := range disks {
|
|
if _, exists := seen[disk.Path]; exists {
|
|
return true
|
|
}
|
|
seen[disk.Path] = struct{}{}
|
|
}
|
|
return false
|
|
}
|
|
|
|
func digest(value []byte) string {
|
|
sum := sha256.Sum256(value)
|
|
return hex.EncodeToString(sum[:])
|
|
}
|
|
|
|
func checkContext(ctx context.Context) error {
|
|
if err := ctx.Err(); err != nil {
|
|
return newError(codePrefix+"canceled", "attach validation was canceled", false, fmt.Errorf("%w: %v", ErrCanceled, err))
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func cloneDisks(disks []DiskAttachment) []DiskAttachment {
|
|
result := make([]DiskAttachment, len(disks))
|
|
copy(result, disks)
|
|
return result
|
|
}
|