feat: harden greenfield agent storage and shadow transport
parent
7436561ae9
commit
779102e422
@ -0,0 +1,37 @@
|
||||
package capability
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"g.luoli.live/root/virt/agent/internal/hypervisor"
|
||||
)
|
||||
|
||||
func TestBackendProviderSeparatesAgentStartupScriptFromHostObservation(t *testing.T) {
|
||||
caps := hypervisor.DefaultCapabilitySnapshot()
|
||||
caps.Backend = "libvirt-domcapabilities"
|
||||
caps.CloudInit = false
|
||||
caps.StartupScript = false
|
||||
snapshot := snapshotFromCapabilities("host-103", "v1", caps)
|
||||
if snapshot.Features["cloud_init"] {
|
||||
t.Fatal("cloud_init must remain the unproven host/guest observation")
|
||||
}
|
||||
for _, key := range []string{"startup_script", "startup_script_agent", "nocloud_seed_artifact"} {
|
||||
if !snapshot.Features[key] {
|
||||
t.Fatalf("feature %q = false, Agent artifact implementation should advertise it", key)
|
||||
}
|
||||
}
|
||||
if snapshot.Features["startup_script_host"] {
|
||||
t.Fatal("startup_script_host must preserve the false host observation")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBackendProviderDoesNotUseStaticProviderForHostFeatures(t *testing.T) {
|
||||
snapshot, err := (StaticProvider{AgentID: "host-103", ProtocolVersion: "v1"}).Snapshot(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if snapshot.Features["startup_script"] || snapshot.Features["nocloud_seed_artifact"] {
|
||||
t.Fatal("static development provider must remain conservative")
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,213 @@
|
||||
// Package storagepolicy validates host paths referenced by file-backed
|
||||
// libvirt disks. The panel may submit domain XML, but it must never be able
|
||||
// to choose an arbitrary host path. A policy is immutable after construction
|
||||
// and every validation re-checks the host filesystem immediately before the
|
||||
// caller hands the XML to libvirt.
|
||||
package storagepolicy
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrPolicyViolation identifies a definitive, pre-host rejection. Callers
|
||||
// should not retry a request with the same path after this error.
|
||||
ErrPolicyViolation = errors.New("storage path policy violation")
|
||||
// ErrNotConfigured means that a domain references a file-backed disk while
|
||||
// the agent has no explicitly configured storage root. Empty roots are a
|
||||
// deliberate fail-closed posture, not an implicit allow-all mode.
|
||||
ErrNotConfigured = errors.New("file-backed storage roots are not configured")
|
||||
// ErrRootUnavailable means that a configured root cannot be proven to be a
|
||||
// real directory at validation time.
|
||||
ErrRootUnavailable = errors.New("configured storage root is unavailable")
|
||||
// ErrPathUnavailable means that a referenced disk path cannot be proven to
|
||||
// be an existing regular file.
|
||||
ErrPathUnavailable = errors.New("file-backed disk path is unavailable")
|
||||
// ErrPathSymlink means that the root, a root ancestor, a disk path, or a
|
||||
// disk path ancestor is a symbolic link. Rejecting aliases prevents a
|
||||
// later replacement from redirecting libvirt outside the allowlist.
|
||||
ErrPathSymlink = errors.New("file-backed storage path contains a symbolic link")
|
||||
// ErrPathOutsideRoot means that realpath resolution leaves every configured
|
||||
// root, including the root itself.
|
||||
ErrPathOutsideRoot = errors.New("file-backed disk path is outside configured storage roots")
|
||||
)
|
||||
|
||||
// IsDefinitive reports path errors that prove a define request is not
|
||||
// acceptable under the agent's current storage contract. Callers should
|
||||
// record these as a typed rejection rather than an ambiguous host timeout;
|
||||
// a later request may only proceed after its XML or host storage policy has
|
||||
// changed. ErrRootUnavailable is intentionally excluded because an operator
|
||||
// may still mount/provision the configured root and then reconcile safely.
|
||||
func IsDefinitive(err error) bool {
|
||||
return errors.Is(err, ErrPolicyViolation) ||
|
||||
errors.Is(err, ErrNotConfigured) ||
|
||||
errors.Is(err, ErrPathUnavailable) ||
|
||||
errors.Is(err, ErrPathSymlink) ||
|
||||
errors.Is(err, ErrPathOutsideRoot)
|
||||
}
|
||||
|
||||
// Policy is an immutable list of canonical, absolute storage roots. The
|
||||
// roots are syntax-checked by New and filesystem-checked by ValidatePaths so a
|
||||
// host can mount a configured directory after process startup without making
|
||||
// configuration loading itself perform I/O.
|
||||
type Policy struct {
|
||||
roots []string
|
||||
}
|
||||
|
||||
// New constructs a policy from absolute, canonical paths. It deliberately
|
||||
// does not follow or create roots; the existence and symlink checks happen at
|
||||
// each define boundary in ValidatePaths.
|
||||
func New(roots []string) (Policy, error) {
|
||||
if len(roots) == 0 {
|
||||
return Policy{}, nil
|
||||
}
|
||||
result := make([]string, 0, len(roots))
|
||||
seen := make(map[string]struct{}, len(roots))
|
||||
for _, raw := range roots {
|
||||
root := strings.TrimSpace(raw)
|
||||
if root == "" {
|
||||
return Policy{}, fmt.Errorf("%w: storage root is empty", ErrPolicyViolation)
|
||||
}
|
||||
if err := validateCanonicalAbsolute(root, "storage root"); err != nil {
|
||||
return Policy{}, err
|
||||
}
|
||||
if root == string(filepath.Separator) {
|
||||
return Policy{}, fmt.Errorf("%w: storage root may not be the filesystem root", ErrPolicyViolation)
|
||||
}
|
||||
if _, exists := seen[root]; exists {
|
||||
return Policy{}, fmt.Errorf("%w: duplicate storage root %q", ErrPolicyViolation, root)
|
||||
}
|
||||
seen[root] = struct{}{}
|
||||
result = append(result, root)
|
||||
}
|
||||
return Policy{roots: result}, nil
|
||||
}
|
||||
|
||||
// Roots returns a defensive copy for diagnostics and configuration tests.
|
||||
func (p Policy) Roots() []string {
|
||||
return append([]string(nil), p.roots...)
|
||||
}
|
||||
|
||||
// ValidatePaths checks every file-backed disk source against the configured
|
||||
// roots. No paths means no storage access is required, so firmware-only
|
||||
// definitions remain usable even when storage has not been configured yet.
|
||||
// A referenced path must already exist as a regular file. VM image creation
|
||||
// belongs to a separate, explicitly scoped storage operation; accepting a
|
||||
// missing path here would make a later libvirt start depend on an unreviewed
|
||||
// path-creation boundary.
|
||||
func (p Policy) ValidatePaths(paths []string) error {
|
||||
if len(paths) == 0 {
|
||||
return nil
|
||||
}
|
||||
if len(p.roots) == 0 {
|
||||
return fmt.Errorf("%w: %w", ErrPolicyViolation, ErrNotConfigured)
|
||||
}
|
||||
|
||||
rootRealpaths := make([]string, 0, len(p.roots))
|
||||
for _, root := range p.roots {
|
||||
realRoot, err := verifyRoot(root)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
rootRealpaths = append(rootRealpaths, realRoot)
|
||||
}
|
||||
for _, rawPath := range paths {
|
||||
path := strings.TrimSpace(rawPath)
|
||||
if path == "" {
|
||||
return fmt.Errorf("%w: empty disk path", ErrPolicyViolation)
|
||||
}
|
||||
if err := validateCanonicalAbsolute(path, "disk path"); err != nil {
|
||||
return err
|
||||
}
|
||||
info, err := os.Lstat(path)
|
||||
if err != nil {
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return fmt.Errorf("%w: %q", ErrPathUnavailable, path)
|
||||
}
|
||||
return fmt.Errorf("%w: inspect %q: %v", ErrPathUnavailable, path, err)
|
||||
}
|
||||
if info.Mode()&os.ModeSymlink != 0 {
|
||||
return fmt.Errorf("%w: %q", ErrPathSymlink, path)
|
||||
}
|
||||
if !info.Mode().IsRegular() {
|
||||
return fmt.Errorf("%w: %q is not a regular file", ErrPathUnavailable, path)
|
||||
}
|
||||
if info.Mode().Perm()&0o022 != 0 || info.Mode()&(os.ModeSetuid|os.ModeSetgid|os.ModeSticky) != 0 {
|
||||
return fmt.Errorf("%w: %q is writable by group/other or has special mode bits", ErrPathUnavailable, path)
|
||||
}
|
||||
realPath, err := filepath.EvalSymlinks(path)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%w: resolve %q: %v", ErrPathUnavailable, path, err)
|
||||
}
|
||||
if realPath != path {
|
||||
return fmt.Errorf("%w: %q resolves to %q", ErrPathSymlink, path, realPath)
|
||||
}
|
||||
|
||||
inside := false
|
||||
for _, realRoot := range rootRealpaths {
|
||||
if pathWithinRoot(realRoot, realPath) {
|
||||
inside = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !inside {
|
||||
return fmt.Errorf("%w: %q", ErrPathOutsideRoot, path)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// validateCanonicalAbsolute rejects paths that filepath.Clean would silently
|
||||
// reinterpret. This keeps the path presented in XML identical to the path
|
||||
// checked by the policy and makes traversal attempts auditable.
|
||||
func validateCanonicalAbsolute(value, label string) error {
|
||||
if !filepath.IsAbs(value) || filepath.Clean(value) != value || strings.ContainsAny(value, "\x00\r\n\t\\") {
|
||||
return fmt.Errorf("%w: %s must be a canonical absolute path", ErrPolicyViolation, label)
|
||||
}
|
||||
for _, component := range strings.Split(value, string(filepath.Separator)) {
|
||||
if component == "." || component == ".." {
|
||||
return fmt.Errorf("%w: %s contains a traversal component", ErrPolicyViolation, label)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func verifyRoot(root string) (string, error) {
|
||||
info, err := os.Lstat(root)
|
||||
if err != nil {
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return "", fmt.Errorf("%w: %q", ErrRootUnavailable, root)
|
||||
}
|
||||
return "", fmt.Errorf("%w: inspect %q: %v", ErrRootUnavailable, root, err)
|
||||
}
|
||||
if info.Mode()&os.ModeSymlink != 0 {
|
||||
return "", fmt.Errorf("%w: root %q", ErrPathSymlink, root)
|
||||
}
|
||||
if !info.IsDir() {
|
||||
return "", fmt.Errorf("%w: root %q is not a directory", ErrRootUnavailable, root)
|
||||
}
|
||||
if info.Mode().Perm()&0o022 != 0 || info.Mode()&(os.ModeSetuid|os.ModeSetgid|os.ModeSticky) != 0 {
|
||||
return "", fmt.Errorf("%w: root %q is writable by group/other or has special mode bits", ErrRootUnavailable, root)
|
||||
}
|
||||
realRoot, err := filepath.EvalSymlinks(root)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("%w: resolve root %q: %v", ErrRootUnavailable, root, err)
|
||||
}
|
||||
if realRoot != root {
|
||||
return "", fmt.Errorf("%w: root %q resolves to %q", ErrPathSymlink, root, realRoot)
|
||||
}
|
||||
return realRoot, nil
|
||||
}
|
||||
|
||||
func pathWithinRoot(root, candidate string) bool {
|
||||
rel, err := filepath.Rel(root, candidate)
|
||||
if err != nil || rel == "." || rel == ".." {
|
||||
return false
|
||||
}
|
||||
parent := ".." + string(filepath.Separator)
|
||||
return !strings.HasPrefix(rel, parent)
|
||||
}
|
||||
@ -0,0 +1,194 @@
|
||||
package storagepolicy
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func canonicalTempDir(t *testing.T) string {
|
||||
t.Helper()
|
||||
path := t.TempDir()
|
||||
resolved, err := filepath.EvalSymlinks(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return resolved
|
||||
}
|
||||
|
||||
func TestNewRejectsNonCanonicalOrDuplicateRoots(t *testing.T) {
|
||||
base := canonicalTempDir(t)
|
||||
tests := []struct {
|
||||
name string
|
||||
roots []string
|
||||
}{
|
||||
{name: "relative", roots: []string{"relative/root"}},
|
||||
{name: "traversal", roots: []string{base + string(filepath.Separator) + ".." + string(filepath.Separator) + filepath.Base(base)}},
|
||||
{name: "duplicate", roots: []string{base, base}},
|
||||
{name: "empty entry", roots: []string{base, ""}},
|
||||
{name: "backslash", roots: []string{base + `\\escape`}},
|
||||
{name: "filesystem root", roots: []string{string(filepath.Separator)}},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if _, err := New(tt.roots); !errors.Is(err, ErrPolicyViolation) {
|
||||
t.Fatalf("New(%v) error = %v, want ErrPolicyViolation", tt.roots, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidatePathsRequiresConfiguredRoot(t *testing.T) {
|
||||
path := filepath.Join(canonicalTempDir(t), "disk.qcow2")
|
||||
if err := os.WriteFile(path, []byte("image"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := (Policy{}).ValidatePaths([]string{path}); !errors.Is(err, ErrNotConfigured) {
|
||||
t.Fatalf("ValidatePaths() error = %v, want ErrNotConfigured", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsDefinitiveDistinguishesPolicyAndUnavailableRoot(t *testing.T) {
|
||||
if !IsDefinitive(fmt.Errorf("wrapped: %w", ErrNotConfigured)) {
|
||||
t.Fatal("ErrNotConfigured must be a definitive request rejection")
|
||||
}
|
||||
if !IsDefinitive(fmt.Errorf("wrapped: %w", ErrPathOutsideRoot)) {
|
||||
t.Fatal("ErrPathOutsideRoot must be a definitive request rejection")
|
||||
}
|
||||
if IsDefinitive(fmt.Errorf("wrapped: %w", ErrRootUnavailable)) {
|
||||
t.Fatal("ErrRootUnavailable should remain retryable after host provisioning")
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidatePathsAcceptsExistingRegularFileInsideRoot(t *testing.T) {
|
||||
root := canonicalTempDir(t)
|
||||
path := filepath.Join(root, "vm", "disk.qcow2")
|
||||
if err := os.Mkdir(filepath.Dir(path), 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(path, []byte("image"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
policy, err := New([]string{root})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := policy.ValidatePaths([]string{path}); err != nil {
|
||||
t.Fatalf("ValidatePaths() error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidatePathsRejectsOutsideTraversalMissingAndNonRegular(t *testing.T) {
|
||||
root := canonicalTempDir(t)
|
||||
outside := filepath.Join(canonicalTempDir(t), "outside.qcow2")
|
||||
if err := os.WriteFile(outside, []byte("image"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
inside := filepath.Join(root, "disk.qcow2")
|
||||
if err := os.WriteFile(inside, []byte("image"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
policy, err := New([]string{root})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
path string
|
||||
want error
|
||||
}{
|
||||
{name: "outside", path: outside, want: ErrPathOutsideRoot},
|
||||
{name: "traversal", path: root + string(filepath.Separator) + "nested" + string(filepath.Separator) + ".." + string(filepath.Separator) + "disk.qcow2", want: ErrPolicyViolation},
|
||||
{name: "missing", path: filepath.Join(root, "missing.qcow2"), want: ErrPathUnavailable},
|
||||
{name: "directory", path: root, want: ErrPathUnavailable},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if err := policy.ValidatePaths([]string{tt.path}); !errors.Is(err, tt.want) {
|
||||
t.Fatalf("ValidatePaths(%q) error = %v, want %v", tt.path, err, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
if err := policy.ValidatePaths([]string{inside}); err != nil {
|
||||
t.Fatalf("valid path became invalid after negative cases: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidatePathsRejectsSymlinkRootAndDiskAliases(t *testing.T) {
|
||||
root := canonicalTempDir(t)
|
||||
actual := filepath.Join(root, "actual")
|
||||
if err := os.Mkdir(actual, 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
disk := filepath.Join(actual, "disk.qcow2")
|
||||
if err := os.WriteFile(disk, []byte("image"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
link := filepath.Join(root, "disk-link.qcow2")
|
||||
if err := os.Symlink(disk, link); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
policy, err := New([]string{actual})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := policy.ValidatePaths([]string{link}); !errors.Is(err, ErrPathSymlink) {
|
||||
t.Fatalf("symlink disk error = %v, want ErrPathSymlink", err)
|
||||
}
|
||||
|
||||
rootLink := filepath.Join(root, "root-link")
|
||||
if err := os.Symlink(actual, rootLink); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
linkedPolicy, err := New([]string{rootLink})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := linkedPolicy.ValidatePaths([]string{disk}); !errors.Is(err, ErrPathSymlink) {
|
||||
t.Fatalf("symlink root error = %v, want ErrPathSymlink", err)
|
||||
}
|
||||
|
||||
parentLink := filepath.Join(root, "parent-link")
|
||||
if err := os.Symlink(actual, parentLink); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
parentLinkedPath := filepath.Join(parentLink, "disk.qcow2")
|
||||
if err := policy.ValidatePaths([]string{parentLinkedPath}); !errors.Is(err, ErrPathSymlink) {
|
||||
t.Fatalf("symlink parent error = %v, want ErrPathSymlink", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidatePathsAllowsNoPathWithoutFilesystemRoot(t *testing.T) {
|
||||
if err := (Policy{}).ValidatePaths(nil); err != nil {
|
||||
t.Fatalf("ValidatePaths(nil) error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidatePathsRejectsGroupWritableRootAndDisk(t *testing.T) {
|
||||
root := canonicalTempDir(t)
|
||||
disk := filepath.Join(root, "disk.qcow2")
|
||||
if err := os.WriteFile(disk, []byte("image"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
policy, err := New([]string{root})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Chmod(root, 0o770); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := policy.ValidatePaths([]string{disk}); !errors.Is(err, ErrRootUnavailable) {
|
||||
t.Fatalf("group-writable root error = %v, want ErrRootUnavailable", err)
|
||||
}
|
||||
if err := os.Chmod(root, 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Chmod(disk, 0o660); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := policy.ValidatePaths([]string{disk}); !errors.Is(err, ErrPathUnavailable) {
|
||||
t.Fatalf("group-writable disk error = %v, want ErrPathUnavailable", err)
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
/** Plaintext Agent registry metadata; credentials are resolved elsewhere. */
|
||||
final class CloudAgent extends Model
|
||||
{
|
||||
protected $connection = 'default';
|
||||
protected $table = 'cloud_agents';
|
||||
protected $casts = [
|
||||
'id' => 'int',
|
||||
'host_id' => 'int',
|
||||
'desired_revision' => 'int',
|
||||
'observed_revision' => 'int',
|
||||
'last_seen_at' => 'int',
|
||||
'created_at' => 'int',
|
||||
'updated_at' => 'int',
|
||||
];
|
||||
}
|
||||
@ -0,0 +1,56 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Cloud;
|
||||
|
||||
/** Fail-closed endpoint validation for registry-provided Agent URLs. */
|
||||
final class CloudAgentEndpointPolicy
|
||||
{
|
||||
public static function validate(string $endpoint, ?callable $resolveHost = null): string
|
||||
{
|
||||
$endpoint = rtrim(trim($endpoint), '/');
|
||||
$parts = parse_url($endpoint);
|
||||
if (!is_array($parts) || ($parts['scheme'] ?? '') !== 'https'
|
||||
|| !is_string($parts['host'] ?? null) || trim($parts['host']) === ''
|
||||
|| isset($parts['user'], $parts['pass'], $parts['query'], $parts['fragment'])
|
||||
|| (($parts['path'] ?? '') !== '' && ($parts['path'] ?? '') !== '/')
|
||||
|| preg_match('/[\x00-\x20\x7f\\]/', $endpoint) === 1) {
|
||||
throw new CloudError('宿主机 Agent 地址必须为安全的 HTTPS 地址', 422);
|
||||
}
|
||||
$host = strtolower(rtrim($parts['host'], '.'));
|
||||
$ipHost = trim($host, '[]');
|
||||
if ($host === 'localhost' || str_ends_with($host, '.localhost')
|
||||
|| str_ends_with($host, '.local') || $host === '0.0.0.0') {
|
||||
throw new CloudError('宿主机 Agent 地址被安全策略拒绝', 422);
|
||||
}
|
||||
if (filter_var($ipHost, FILTER_VALIDATE_IP) !== false
|
||||
&& filter_var($ipHost, FILTER_VALIDATE_IP,
|
||||
FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false) {
|
||||
throw new CloudError('宿主机 Agent 地址被安全策略拒绝', 422);
|
||||
}
|
||||
if ($resolveHost === null) {
|
||||
throw new CloudError('宿主机 Agent 主机未通过显式解析器允许', 422);
|
||||
}
|
||||
try {
|
||||
// Literal IPs use the same injected policy as DNS names. This
|
||||
// lets deployment pin the exact public destination and avoids a
|
||||
// second, weaker endpoint path.
|
||||
$addresses = $resolveHost($ipHost);
|
||||
} catch (\Throwable) {
|
||||
throw new CloudError('宿主机 Agent 主机解析失败', 422);
|
||||
}
|
||||
if (!is_array($addresses) || $addresses === []) {
|
||||
throw new CloudError('宿主机 Agent 主机解析失败', 422);
|
||||
}
|
||||
foreach ($addresses as $address) {
|
||||
if (!is_string($address) || filter_var($address, FILTER_VALIDATE_IP,
|
||||
FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false) {
|
||||
throw new CloudError('宿主机 Agent 主机解析到不安全地址', 422);
|
||||
}
|
||||
}
|
||||
$port = $parts['port'] ?? 443;
|
||||
if (!is_int($port) || $port < 1 || $port > 65535) {
|
||||
throw new CloudError('宿主机 Agent 端口无效', 422);
|
||||
}
|
||||
return $endpoint;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,10 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Cloud;
|
||||
|
||||
/** Resolves an allowlisted Agent hostname to IPs; failures must be fail-closed. */
|
||||
interface CloudAgentHostResolver
|
||||
{
|
||||
/** @return list<string> */
|
||||
public function resolve(string $hostname): array;
|
||||
}
|
||||
@ -0,0 +1,14 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Cloud;
|
||||
|
||||
/**
|
||||
* Supplies host-local Agent credentials without coupling them to the registry.
|
||||
* Implementations must not read secret material from cloud_agents or legacy
|
||||
* engine tables.
|
||||
*/
|
||||
interface CloudAgentSecretResolver
|
||||
{
|
||||
/** @return array{hmac_key:string,ca_file?:string,cert_file?:string,key_file?:string}|null */
|
||||
public function resolve(string $agentId): ?array;
|
||||
}
|
||||
@ -0,0 +1,112 @@
|
||||
<?php
|
||||
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
|
||||
use App\Services\Cloud\CloudAgentEndpointPolicy;
|
||||
use App\Services\Cloud\CloudAgentHostResolver;
|
||||
use App\Services\Cloud\CloudAgentRegistryHealthService;
|
||||
use App\Services\Cloud\CloudAgentSecretResolver;
|
||||
use App\Services\Cloud\CloudError;
|
||||
|
||||
$assert = static function ($condition, string $message): void {
|
||||
if (!$condition) {
|
||||
throw new RuntimeException($message);
|
||||
}
|
||||
};
|
||||
|
||||
$empty = (new CloudAgentRegistryHealthService(static fn (): array => []))->snapshot(1700000000);
|
||||
$assert($empty['status'] === 'disabled' && $empty['agents'] === [],
|
||||
'An absent Agent registry must be disabled and must not probe an endpoint.');
|
||||
|
||||
$duplicate = new CloudAgentRegistryHealthService(static fn (): array => [
|
||||
['host_id' => 7, 'agent_id' => 'a-1', 'endpoint' => 'https://agent.example.test'],
|
||||
['host_id' => 7, 'agent_id' => 'a-2', 'endpoint' => 'https://agent-2.example.test'],
|
||||
]);
|
||||
$duplicateResult = $duplicate->snapshot(1700000000);
|
||||
$assert($duplicateResult['status'] === 'unknown' && $duplicateResult['agents'] === [],
|
||||
'A host_id may map to exactly one registered Agent.');
|
||||
|
||||
foreach (['http://agent.example.test', 'https://127.0.0.1', 'https://localhost',
|
||||
'https://[::1]', 'https://user:pass@agent.example.test', 'https://agent.example.test/path?q=1'] as $unsafe) {
|
||||
try {
|
||||
CloudAgentEndpointPolicy::validate($unsafe);
|
||||
throw new RuntimeException('Unsafe Agent endpoint accepted: ' . $unsafe);
|
||||
} catch (CloudError $expected) {
|
||||
$assert($expected->httpStatus === 422, 'Unsafe endpoint returned an unexpected status.');
|
||||
}
|
||||
}
|
||||
|
||||
$resolver = new class implements CloudAgentSecretResolver {
|
||||
public array $requested = [];
|
||||
public function resolve(string $agentId): ?array
|
||||
{
|
||||
$this->requested[] = $agentId;
|
||||
return null;
|
||||
}
|
||||
};
|
||||
$resolverContract = new class implements CloudAgentHostResolver {
|
||||
public function resolve(string $hostname): array { return ['8.8.8.8']; }
|
||||
};
|
||||
$noSecret = new CloudAgentRegistryHealthService(static fn (): array => [
|
||||
['host_id' => 8, 'agent_id' => 'a-8', 'endpoint' => 'https://agent.example.test', 'status' => 'active'],
|
||||
], $resolver, $resolverContract);
|
||||
$noSecretResult = $noSecret->snapshot(1700000000);
|
||||
$assert($noSecretResult['status'] === 'unknown'
|
||||
&& $noSecretResult['agents'][0]['status'] === 'unknown'
|
||||
&& $resolver->requested === ['a-8'],
|
||||
'Agent health must remain unknown when host-local secret/TLS resolution is unavailable.');
|
||||
|
||||
$unknownStatus = new CloudAgentRegistryHealthService(static fn (): array => [
|
||||
['host_id' => 9, 'agent_id' => 'a-9', 'endpoint' => 'https://agent.example.test', 'status' => 'mystery'],
|
||||
]);
|
||||
$unknownStatusResult = $unknownStatus->snapshot(1700000000);
|
||||
$assert($unknownStatusResult['agents'][0]['status'] === 'unknown',
|
||||
'Unknown registry statuses must fail closed.');
|
||||
|
||||
$inactive = new CloudAgentRegistryHealthService(static fn (): array => [
|
||||
['host_id' => 10, 'agent_id' => 'a-10', 'endpoint' => 'https://agent.example.test', 'status' => 'disabled'],
|
||||
], $resolver, $resolverContract);
|
||||
$inactiveResult = $inactive->snapshot(1700000000);
|
||||
$assert($inactiveResult['agents'][0]['status'] === 'disabled' && $resolver->requested === ['a-8'],
|
||||
'Disabled Agents must not make network requests and must be reported disabled.');
|
||||
|
||||
try {
|
||||
CloudAgentEndpointPolicy::validate('https://agent.example.test');
|
||||
throw new RuntimeException('DNS hostname was accepted without an explicit resolver.');
|
||||
} catch (CloudError $expected) {
|
||||
$assert($expected->httpStatus === 422, 'Missing endpoint resolver returned an unexpected status.');
|
||||
}
|
||||
|
||||
$publicResolver = static fn (string $host): array => ['8.8.8.8'];
|
||||
$assert(CloudAgentEndpointPolicy::validate('https://8.8.8.8', $publicResolver) === 'https://8.8.8.8',
|
||||
'A public literal endpoint with an explicit resolver should be accepted.');
|
||||
try {
|
||||
CloudAgentEndpointPolicy::validate('https://127.0.0.1', $publicResolver);
|
||||
throw new RuntimeException('A private literal endpoint was accepted despite a public resolver result.');
|
||||
} catch (CloudError $expected) {
|
||||
$assert($expected->httpStatus === 422, 'Private literal endpoint returned an unexpected status.');
|
||||
}
|
||||
try {
|
||||
CloudAgentEndpointPolicy::validate('https://8.8.8.8', static fn (string $host): array => ['10.0.0.8']);
|
||||
throw new RuntimeException('Resolver returned a private address but endpoint was accepted.');
|
||||
} catch (CloudError $expected) {
|
||||
$assert($expected->httpStatus === 422, 'Private resolver result returned an unexpected status.');
|
||||
}
|
||||
|
||||
$source = file_get_contents(dirname(__DIR__) . '/app/Services/Cloud/CloudAgentRegistryHealthService.php');
|
||||
$assert($source !== false && str_contains($source, 'CloudAgentSecretResolver')
|
||||
&& str_contains($source, 'CloudAgentEndpointPolicy::validate')
|
||||
&& str_contains($source, 'CloudAgentHostResolver')
|
||||
&& str_contains($source, '$resolvedAddresses')
|
||||
&& str_contains($source, 'CloudAgentClient')
|
||||
&& !str_contains($source, 'CloudEngineClient') && !str_contains($source, 'CloudSecrets')
|
||||
&& !str_contains($source, 'ssh'), 'Registry shadow crossed the legacy secret or SSH boundary.');
|
||||
|
||||
$clientSource = file_get_contents(dirname(__DIR__) . '/app/Services/Cloud/CloudAgentClient.php');
|
||||
$assert($clientSource !== false
|
||||
&& str_contains($clientSource, "'resolve'")
|
||||
&& str_contains($clientSource, 'validateResolvedAddresses')
|
||||
&& str_contains($clientSource, 'FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE'),
|
||||
'Agent transport did not retain the explicit public-address pinning contract.');
|
||||
|
||||
echo "Cloud Agent registry health shadow contract checks passed.\n";
|
||||
Loading…
Reference in New Issue