Remove online update subsystem
parent
92ace142d1
commit
a587346d43
@ -1,17 +0,0 @@
|
||||
{
|
||||
"socket_path": "/run/virt-cloud/update.sock",
|
||||
"repository_dir": "/home/virt-cloud",
|
||||
"remote_url": "https://g.luoli.live/root/virt.git",
|
||||
"branch": "go",
|
||||
"state_path": "/home/virt-cloud/runtime/update/state.json",
|
||||
"service_secret": "REPLACE_ME",
|
||||
"php_command": "/usr/bin/php",
|
||||
"php_fpm_unit": "php-fpm.service",
|
||||
"service_units": [
|
||||
"virt-cloud-worker.service",
|
||||
"virt-cloud-lifecycle.service",
|
||||
"virt-cloud-policy-worker@1.service",
|
||||
"virt-cloud-policy-worker@2.service",
|
||||
"virt-cloud-agent-gateway.service"
|
||||
]
|
||||
}
|
||||
@ -1,28 +0,0 @@
|
||||
[Unit]
|
||||
Description=Virt Cloud privileged update helper
|
||||
After=network-online.target mariadb.service
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=root
|
||||
Group=apache
|
||||
WorkingDirectory=/home/virt-cloud
|
||||
ExecStart=/home/virt-cloud/bin/virt-cloud-update --config /home/virt-cloud/runtime/update.json
|
||||
Restart=on-failure
|
||||
RestartSec=5
|
||||
UMask=0007
|
||||
# UMask/RuntimeDirectoryMode only harden newly created files; the helper does
|
||||
# not audit the owner, group, or mode of its readable JSON configuration.
|
||||
RuntimeDirectory=virt-cloud
|
||||
RuntimeDirectoryMode=0750
|
||||
NoNewPrivileges=true
|
||||
PrivateTmp=true
|
||||
ProtectHome=false
|
||||
ProtectSystem=strict
|
||||
ReadWritePaths=/home/virt-cloud /run/virt-cloud
|
||||
LimitCORE=0
|
||||
TimeoutStopSec=10min
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@ -1,98 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"path/filepath"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"git.luoli.live/root/virt/gateway/update"
|
||||
)
|
||||
|
||||
func main() {
|
||||
configPath := flag.String("config", "", "absolute path to the JSON configuration")
|
||||
flag.Parse()
|
||||
if *configPath == "" || !filepath.IsAbs(*configPath) {
|
||||
log.Fatal("--config must be an absolute path")
|
||||
}
|
||||
config, err := update.LoadConfig(*configPath)
|
||||
if err != nil {
|
||||
log.Fatalf("update configuration is invalid: %v", err)
|
||||
}
|
||||
state, err := update.OpenConfiguredState(config)
|
||||
if err != nil {
|
||||
log.Fatalf("update state is unavailable: %v", err)
|
||||
}
|
||||
manager, err := update.NewManager(config, state, update.OSCommandExecutor{})
|
||||
if err != nil {
|
||||
log.Fatalf("update manager cannot start: %v", err)
|
||||
}
|
||||
handler, err := update.NewServer(manager, state, []byte(config.ServiceSecret))
|
||||
if err != nil {
|
||||
log.Fatalf("update API cannot start: %v", err)
|
||||
}
|
||||
listener, err := listenUnix(config.SocketPath)
|
||||
if err != nil {
|
||||
log.Fatalf("update socket cannot start: %v", err)
|
||||
}
|
||||
defer func() {
|
||||
_ = listener.Close()
|
||||
_ = os.Remove(config.SocketPath)
|
||||
}()
|
||||
server := &http.Server{Handler: handler, ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 15 * time.Second,
|
||||
WriteTimeout: 45 * time.Second, IdleTimeout: 30 * time.Second, MaxHeaderBytes: 32 << 10}
|
||||
stop := make(chan os.Signal, 1)
|
||||
signal.Notify(stop, syscall.SIGINT, syscall.SIGTERM)
|
||||
go func() {
|
||||
<-stop
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
_ = server.Shutdown(ctx)
|
||||
}()
|
||||
log.Printf("virt-cloud-update listening on %s", config.SocketPath)
|
||||
if err := server.Serve(listener); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||
log.Fatalf("update API stopped unexpectedly: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func listenUnix(path string) (net.Listener, error) {
|
||||
if path != update.RequiredSocketPath {
|
||||
return nil, errors.New("refusing non-standard update socket")
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0o750); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if info, err := os.Lstat(path); err == nil {
|
||||
if info.Mode()&os.ModeSocket == 0 {
|
||||
return nil, errors.New("update socket path exists and is not a socket")
|
||||
}
|
||||
connection, dialErr := net.DialTimeout("unix", path, 250*time.Millisecond)
|
||||
if dialErr == nil {
|
||||
_ = connection.Close()
|
||||
return nil, errors.New("another update helper is already listening")
|
||||
}
|
||||
if err := os.Remove(path); err != nil {
|
||||
return nil, fmt.Errorf("remove stale update socket: %w", err)
|
||||
}
|
||||
} else if !errors.Is(err, os.ErrNotExist) {
|
||||
return nil, err
|
||||
}
|
||||
listener, err := net.Listen("unix", path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := os.Chmod(path, 0o660); err != nil {
|
||||
_ = listener.Close()
|
||||
_ = os.Remove(path)
|
||||
return nil, err
|
||||
}
|
||||
return listener, nil
|
||||
}
|
||||
@ -1,135 +0,0 @@
|
||||
package update
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const (
|
||||
RequiredSocketPath = "/run/virt-cloud/update.sock"
|
||||
RequiredRemoteURL = "https://g.luoli.live/root/virt.git"
|
||||
RequiredBranch = "go"
|
||||
maxConfigBytes = 64 << 10
|
||||
)
|
||||
|
||||
var unitPattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9_.@:-]{0,127}\.service$`)
|
||||
|
||||
type Config struct {
|
||||
SocketPath string `json:"socket_path"`
|
||||
RepositoryDir string `json:"repository_dir"`
|
||||
RemoteURL string `json:"remote_url"`
|
||||
Branch string `json:"branch"`
|
||||
StatePath string `json:"state_path"`
|
||||
ServiceSecret string `json:"service_secret"`
|
||||
PHPCommand string `json:"php_command"`
|
||||
PHPFPMUnit string `json:"php_fpm_unit"`
|
||||
ServiceUnits []string `json:"service_units"`
|
||||
}
|
||||
|
||||
func LoadConfig(path string) (Config, error) {
|
||||
file, err := os.Open(path)
|
||||
if err != nil {
|
||||
return Config{}, fmt.Errorf("open update configuration: %w", err)
|
||||
}
|
||||
defer file.Close()
|
||||
raw, err := io.ReadAll(io.LimitReader(file, maxConfigBytes+1))
|
||||
if err != nil {
|
||||
return Config{}, fmt.Errorf("read update configuration: %w", err)
|
||||
}
|
||||
if len(raw) > maxConfigBytes {
|
||||
return Config{}, errors.New("update configuration exceeds 65536 bytes")
|
||||
}
|
||||
decoder := json.NewDecoder(bytes.NewReader(raw))
|
||||
decoder.DisallowUnknownFields()
|
||||
var config Config
|
||||
if err := decoder.Decode(&config); err != nil {
|
||||
return Config{}, fmt.Errorf("decode update configuration: %w", err)
|
||||
}
|
||||
if err := requireEOF(decoder); err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
if err := config.Validate(); err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
return config, nil
|
||||
}
|
||||
|
||||
func requireEOF(decoder *json.Decoder) error {
|
||||
var extra any
|
||||
if err := decoder.Decode(&extra); !errors.Is(err, io.EOF) {
|
||||
if err == nil {
|
||||
return errors.New("configuration contains multiple JSON values")
|
||||
}
|
||||
return fmt.Errorf("configuration has trailing data: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c Config) Validate() error {
|
||||
var problems []string
|
||||
if c.SocketPath != RequiredSocketPath {
|
||||
problems = append(problems, "socket_path must be "+RequiredSocketPath)
|
||||
}
|
||||
if c.RemoteURL != RequiredRemoteURL {
|
||||
problems = append(problems, "remote_url must identify the fixed Virt Cloud repository")
|
||||
}
|
||||
if c.Branch != RequiredBranch {
|
||||
problems = append(problems, "branch must be go")
|
||||
}
|
||||
if err := safeAbsolutePath(c.RepositoryDir); err != nil {
|
||||
problems = append(problems, "repository_dir "+err.Error())
|
||||
}
|
||||
if err := safeAbsolutePath(c.StatePath); err != nil {
|
||||
problems = append(problems, "state_path "+err.Error())
|
||||
} else if c.RepositoryDir != "" && c.StatePath != filepath.Join(c.RepositoryDir, "runtime", "update", "state.json") {
|
||||
problems = append(problems, "state_path must be repository_dir/runtime/update/state.json")
|
||||
}
|
||||
if len(c.ServiceSecret) < 32 || strings.ContainsAny(c.ServiceSecret, "\x00\r\n") {
|
||||
problems = append(problems, "service_secret must contain at least 32 non-line-breaking bytes")
|
||||
}
|
||||
if err := safeAbsolutePath(c.PHPCommand); err != nil {
|
||||
problems = append(problems, "php_command "+err.Error())
|
||||
}
|
||||
if !unitPattern.MatchString(c.PHPFPMUnit) {
|
||||
problems = append(problems, "php_fpm_unit is invalid")
|
||||
}
|
||||
if len(c.ServiceUnits) == 0 || len(c.ServiceUnits) > 32 {
|
||||
problems = append(problems, "service_units must contain between 1 and 32 units")
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for _, unit := range c.ServiceUnits {
|
||||
if !unitPattern.MatchString(unit) || unit == c.PHPFPMUnit || seen[unit] || unit == "virt-cloud-update.service" {
|
||||
problems = append(problems, "service_units contains an invalid, duplicate, or self-referential unit")
|
||||
break
|
||||
}
|
||||
seen[unit] = true
|
||||
}
|
||||
parsed, err := url.Parse(c.RemoteURL)
|
||||
if err != nil || parsed.Scheme != "https" || parsed.Hostname() != "g.luoli.live" || parsed.User != nil || parsed.RawQuery != "" || parsed.Fragment != "" {
|
||||
problems = append(problems, "remote_url is not the approved HTTPS repository")
|
||||
}
|
||||
if len(problems) != 0 {
|
||||
return errors.New(strings.Join(problems, "; "))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func safeAbsolutePath(value string) error {
|
||||
if value == "" || !filepath.IsAbs(value) || filepath.Clean(value) != value || value == string(filepath.Separator) || strings.ContainsAny(value, "\x00\r\n") {
|
||||
return errors.New("must be a clean absolute non-root path")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func pathWithin(parent, child string) bool {
|
||||
relative, err := filepath.Rel(parent, child)
|
||||
return err == nil && relative != "." && relative != ".." && !strings.HasPrefix(relative, ".."+string(filepath.Separator))
|
||||
}
|
||||
@ -1,89 +0,0 @@
|
||||
package update
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func validTestConfig(directory string) Config {
|
||||
return Config{
|
||||
SocketPath: RequiredSocketPath, RepositoryDir: directory, RemoteURL: RequiredRemoteURL,
|
||||
Branch: RequiredBranch, StatePath: filepath.Join(directory, "runtime", "update", "state.json"),
|
||||
ServiceSecret: strings.Repeat("s", 32), PHPCommand: "/usr/bin/php", PHPFPMUnit: "php-fpm.service",
|
||||
ServiceUnits: []string{"virt-cloud-worker.service", "virt-cloud-agent-gateway.service"},
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadConfigDoesNotRejectFileMode(t *testing.T) {
|
||||
directory := t.TempDir()
|
||||
path := filepath.Join(directory, "update.json")
|
||||
config := `{"socket_path":"/run/virt-cloud/update.sock","repository_dir":"` + directory + `","remote_url":"https://g.luoli.live/root/virt.git","branch":"go","state_path":"` + filepath.Join(directory, "runtime/update/state.json") + `","service_secret":"0123456789abcdef0123456789abcdef","php_command":"/usr/bin/php","php_fpm_unit":"php-fpm.service","service_units":["virt-cloud-worker.service"]}`
|
||||
if err := os.WriteFile(path, []byte(config), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := LoadConfig(path); err != nil {
|
||||
t.Fatalf("readable 0644 configuration rejected: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadConfigRejectsDataPastSizeLimit(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "update.json")
|
||||
raw := []byte(`{}` + strings.Repeat(" ", maxConfigBytes))
|
||||
if err := os.WriteFile(path, raw, 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := LoadConfig(path); err == nil || !strings.Contains(err.Error(), "exceeds") {
|
||||
t.Fatalf("oversized update configuration error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigIsStrictAndFixed(t *testing.T) {
|
||||
config := validTestConfig(t.TempDir())
|
||||
config.Branch = "dev"
|
||||
if err := config.Validate(); err == nil || !strings.Contains(err.Error(), "branch must be go") {
|
||||
t.Fatalf("wrong branch error = %v", err)
|
||||
}
|
||||
config = validTestConfig(t.TempDir())
|
||||
config.StatePath = "/tmp/outside-state.json"
|
||||
if err := config.Validate(); err == nil || !strings.Contains(err.Error(), "repository_dir/runtime/update/state.json") {
|
||||
t.Fatalf("outside state error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenConfiguredStateRejectsRuntimeSymlinkEscape(t *testing.T) {
|
||||
repository := filepath.Join(t.TempDir(), "repository")
|
||||
outside := filepath.Join(t.TempDir(), "outside")
|
||||
if err := os.MkdirAll(repository, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.MkdirAll(outside, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Symlink(outside, filepath.Join(repository, "runtime")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
config := validTestConfig(repository)
|
||||
if _, err := OpenConfiguredState(config); err == nil || !strings.Contains(err.Error(), "escapes") {
|
||||
t.Fatalf("runtime symlink escape error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenConfiguredStateRejectsStateFileSymlink(t *testing.T) {
|
||||
repository := filepath.Join(t.TempDir(), "repository")
|
||||
stateDirectory := filepath.Join(repository, "runtime", "update")
|
||||
if err := os.MkdirAll(stateDirectory, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
target := filepath.Join(t.TempDir(), "outside-state.json")
|
||||
if err := os.WriteFile(target, []byte(`{}`), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Symlink(target, filepath.Join(stateDirectory, "state.json")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := OpenConfiguredState(validTestConfig(repository)); err == nil || !strings.Contains(err.Error(), "regular file") {
|
||||
t.Fatalf("state symlink error = %v", err)
|
||||
}
|
||||
}
|
||||
@ -1,624 +0,0 @@
|
||||
package update
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
const maxCommandOutput = 2 << 20
|
||||
|
||||
var commitPattern = regexp.MustCompile(`^[0-9a-f]{40,64}$`)
|
||||
|
||||
type CommandExecutor interface {
|
||||
Run(ctx context.Context, directory string, environment []string, command string, arguments ...string) ([]byte, error)
|
||||
}
|
||||
|
||||
type OSCommandExecutor struct{}
|
||||
|
||||
func (OSCommandExecutor) Run(ctx context.Context, directory string, environment []string, command string, arguments ...string) ([]byte, error) {
|
||||
if command == "git" {
|
||||
arguments = append([]string{"-c", "core.hooksPath=/dev/null", "-c", "core.fsmonitor=false", "-c", "credential.helper="}, arguments...)
|
||||
}
|
||||
cmd := exec.CommandContext(ctx, command, arguments...)
|
||||
cmd.Dir = directory
|
||||
cmd.Env = commandEnvironment(environment)
|
||||
var output bytes.Buffer
|
||||
writer := &limitedWriter{writer: &output, remaining: maxCommandOutput}
|
||||
cmd.Stdout = writer
|
||||
cmd.Stderr = writer
|
||||
err := cmd.Run()
|
||||
return output.Bytes(), err
|
||||
}
|
||||
|
||||
func commandEnvironment(overrides []string) []string {
|
||||
values := make(map[string]string, len(os.Environ())+len(overrides))
|
||||
for _, entry := range os.Environ() {
|
||||
key, value, ok := strings.Cut(entry, "=")
|
||||
if !ok || unsafeCommandEnvironmentKey(key) {
|
||||
continue
|
||||
}
|
||||
values[key] = value
|
||||
}
|
||||
for _, entry := range overrides {
|
||||
key, value, ok := strings.Cut(entry, "=")
|
||||
if ok && key != "" {
|
||||
values[key] = value
|
||||
}
|
||||
}
|
||||
result := make([]string, 0, len(values))
|
||||
for key, value := range values {
|
||||
result = append(result, key+"="+value)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func unsafeCommandEnvironmentKey(key string) bool {
|
||||
if strings.HasPrefix(key, "GIT_CONFIG_KEY_") || strings.HasPrefix(key, "GIT_CONFIG_VALUE_") ||
|
||||
strings.HasPrefix(key, "DYLD_") {
|
||||
return true
|
||||
}
|
||||
switch key {
|
||||
case "GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE", "GIT_OBJECT_DIRECTORY",
|
||||
"GIT_ALTERNATE_OBJECT_DIRECTORIES", "GIT_CONFIG", "GIT_CONFIG_COUNT",
|
||||
"GIT_SSH", "GIT_SSH_COMMAND", "GIT_PROXY_COMMAND", "LD_PRELOAD":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
type limitedWriter struct {
|
||||
mu sync.Mutex
|
||||
writer *bytes.Buffer
|
||||
remaining int
|
||||
}
|
||||
|
||||
func (w *limitedWriter) Write(value []byte) (int, error) {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
original := len(value)
|
||||
if w.remaining > 0 {
|
||||
amount := len(value)
|
||||
if amount > w.remaining {
|
||||
amount = w.remaining
|
||||
}
|
||||
_, _ = w.writer.Write(value[:amount])
|
||||
w.remaining -= amount
|
||||
}
|
||||
return original, nil
|
||||
}
|
||||
|
||||
type CheckResult struct {
|
||||
Repository string `json:"repository"`
|
||||
CurrentCommit string `json:"current_commit"`
|
||||
RemoteCommit string `json:"remote_commit"`
|
||||
UpdateAvailable bool `json:"update_available"`
|
||||
Status string `json:"status"`
|
||||
Branch string `json:"branch"`
|
||||
MaintenanceLock bool `json:"maintenance_lock"`
|
||||
}
|
||||
|
||||
type SettingsResult struct {
|
||||
Repository string `json:"repository"`
|
||||
Branch string `json:"branch"`
|
||||
CurrentCommit string `json:"current_commit"`
|
||||
CheckoutReady bool `json:"checkout_ready"`
|
||||
CheckoutError string `json:"checkout_error,omitempty"`
|
||||
TokenConfigured bool `json:"token_configured"`
|
||||
ActiveJobID string `json:"active_job_id,omitempty"`
|
||||
LastJobID string `json:"last_job_id,omitempty"`
|
||||
MaintenanceLock bool `json:"maintenance_lock"`
|
||||
}
|
||||
|
||||
type Manager struct {
|
||||
config Config
|
||||
state *StateStore
|
||||
executor CommandExecutor
|
||||
timeout time.Duration
|
||||
healthTimeout time.Duration
|
||||
healthPollInterval time.Duration
|
||||
}
|
||||
|
||||
func NewManager(config Config, state *StateStore, executor CommandExecutor) (*Manager, error) {
|
||||
if err := config.Validate(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if state == nil || executor == nil {
|
||||
return nil, errors.New("update state and command executor are required")
|
||||
}
|
||||
return &Manager{
|
||||
config: config,
|
||||
state: state,
|
||||
executor: executor,
|
||||
timeout: 10 * time.Minute,
|
||||
healthTimeout: 60 * time.Second,
|
||||
healthPollInterval: time.Second,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (m *Manager) Check(ctx context.Context) (CheckResult, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
|
||||
defer cancel()
|
||||
current, err := m.validateLocalRepository(ctx)
|
||||
if err != nil {
|
||||
return CheckResult{}, err
|
||||
}
|
||||
remote, err := m.remoteCommit(ctx)
|
||||
if err != nil {
|
||||
return CheckResult{}, err
|
||||
}
|
||||
status := "current"
|
||||
if current != remote {
|
||||
status = "update_available"
|
||||
}
|
||||
return CheckResult{Repository: RequiredRemoteURL, CurrentCommit: current, RemoteCommit: remote, UpdateAvailable: current != remote, Status: status,
|
||||
Branch: RequiredBranch, MaintenanceLock: m.state.MaintenanceLocked()}, nil
|
||||
}
|
||||
|
||||
func (m *Manager) Settings(ctx context.Context) SettingsResult {
|
||||
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
|
||||
defer cancel()
|
||||
active, last := m.state.JobPointers()
|
||||
result := SettingsResult{Repository: RequiredRemoteURL, Branch: RequiredBranch,
|
||||
TokenConfigured: m.state.TokenConfigured(), ActiveJobID: active, LastJobID: last,
|
||||
MaintenanceLock: m.state.MaintenanceLocked()}
|
||||
commit, err := m.validateLocalRepository(ctx)
|
||||
if err != nil {
|
||||
result.CheckoutError = "仓库分支、远端或工作树状态不符合更新要求"
|
||||
return result
|
||||
}
|
||||
result.CurrentCommit = commit
|
||||
result.CheckoutReady = true
|
||||
return result
|
||||
}
|
||||
|
||||
func (m *Manager) StartApply(expectedCurrent, expectedRemote string) (Job, error) {
|
||||
if !commitPattern.MatchString(expectedCurrent) || !commitPattern.MatchString(expectedRemote) {
|
||||
return Job{}, errors.New("expected commits must be lowercase full object IDs")
|
||||
}
|
||||
if expectedCurrent == expectedRemote {
|
||||
return Job{}, errors.New("remote commit does not contain an update")
|
||||
}
|
||||
id, err := randomID()
|
||||
if err != nil {
|
||||
return Job{}, err
|
||||
}
|
||||
job := Job{ID: id, ExpectedCurrentCommit: expectedCurrent, ExpectedRemoteCommit: expectedRemote}
|
||||
if err := m.state.CreateJob(job); err != nil {
|
||||
return Job{}, err
|
||||
}
|
||||
job, _ = m.state.Job(id)
|
||||
go m.runApply(id)
|
||||
return job, nil
|
||||
}
|
||||
|
||||
func (m *Manager) runApply(id string) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), m.timeout)
|
||||
defer cancel()
|
||||
job, ok := m.state.Job(id)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
failSafe := func(code string) {
|
||||
if err := m.state.UpdateJob(id, func(value *Job) {
|
||||
value.Status = "failed"
|
||||
value.ErrorCode = code
|
||||
}); err != nil {
|
||||
m.state.ForceManual(id, "state_persistence_failed")
|
||||
}
|
||||
}
|
||||
failUncertain := func(code string) {
|
||||
if err := m.state.UpdateJob(id, func(value *Job) {
|
||||
value.Status = "manual_intervention"
|
||||
value.ErrorCode = code
|
||||
}); err != nil {
|
||||
m.state.ForceManual(id, "state_persistence_failed")
|
||||
}
|
||||
}
|
||||
checkpoint := func(name string) error {
|
||||
err := m.state.UpdateJob(id, func(value *Job) {
|
||||
value.Status = "running"
|
||||
value.Checkpoint = name
|
||||
})
|
||||
if err != nil {
|
||||
m.state.ForceManual(id, "state_persistence_failed")
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
if err := checkpoint("validating_repository"); err != nil {
|
||||
return
|
||||
}
|
||||
current, err := m.validateLocalRepository(ctx)
|
||||
if err != nil || current != job.ExpectedCurrentCommit {
|
||||
failSafe("local_repository_precondition_failed")
|
||||
return
|
||||
}
|
||||
if err := checkpoint("fetching_expected_commit"); err != nil {
|
||||
return
|
||||
}
|
||||
if err := m.fetch(ctx); err != nil {
|
||||
failSafe("remote_fetch_failed")
|
||||
return
|
||||
}
|
||||
remote, err := m.remoteTrackingCommit(ctx)
|
||||
if err != nil || remote != job.ExpectedRemoteCommit {
|
||||
failSafe("remote_commit_changed")
|
||||
return
|
||||
}
|
||||
if err := m.ensureFastForward(ctx, current, remote); err != nil {
|
||||
failSafe("non_fast_forward_update_rejected")
|
||||
return
|
||||
}
|
||||
changed, err := m.changedPaths(ctx, current, remote)
|
||||
if err != nil {
|
||||
failSafe("change_inspection_failed")
|
||||
return
|
||||
}
|
||||
if deniedChangedPath(changed) {
|
||||
failSafe("manual_upgrade_required")
|
||||
return
|
||||
}
|
||||
if err := checkpoint("preflight"); err != nil {
|
||||
return
|
||||
}
|
||||
if err := m.preflight(ctx, remote); err != nil {
|
||||
failSafe("host_preflight_failed")
|
||||
return
|
||||
}
|
||||
if err := m.state.UpdateJob(id, func(value *Job) { value.PreviousCommit = current }); err != nil {
|
||||
m.state.ForceManual(id, "state_persistence_failed")
|
||||
return
|
||||
}
|
||||
|
||||
// Every checkpoint below precedes a host mutation. A crash or any error is
|
||||
// deliberately considered uncertain and holds the maintenance lock.
|
||||
if err := checkpoint("stopping_services"); err != nil {
|
||||
return
|
||||
}
|
||||
if err := m.stopServices(ctx); err != nil {
|
||||
failUncertain("service_stop_requires_reconciliation")
|
||||
return
|
||||
}
|
||||
if err := checkpoint("updating_source"); err != nil {
|
||||
return
|
||||
}
|
||||
if _, err := m.run(ctx, nil, "git", "merge", "--ff-only", "refs/remotes/origin/"+RequiredBranch); err != nil {
|
||||
failUncertain("source_update_requires_reconciliation")
|
||||
return
|
||||
}
|
||||
if err := m.state.UpdateJob(id, func(value *Job) {
|
||||
value.Status = "running"
|
||||
value.Checkpoint = "source_updated"
|
||||
value.AppliedCommit = remote
|
||||
}); err != nil {
|
||||
m.state.ForceManual(id, "state_persistence_failed")
|
||||
return
|
||||
}
|
||||
if err := checkpoint("schema_init_started"); err != nil {
|
||||
return
|
||||
}
|
||||
webDirectory, err := m.webDirectory()
|
||||
if err != nil {
|
||||
failUncertain("schema_init_result_uncertain")
|
||||
return
|
||||
}
|
||||
if _, err := m.runAt(ctx, webDirectory, nil, m.config.PHPCommand, "xcat", "cloudInit"); err != nil {
|
||||
failUncertain("schema_init_result_uncertain")
|
||||
return
|
||||
}
|
||||
if err := checkpoint("schema_init_completed"); err != nil {
|
||||
return
|
||||
}
|
||||
if err := checkpoint("starting_services"); err != nil {
|
||||
return
|
||||
}
|
||||
if err := m.startServices(ctx); err != nil {
|
||||
failUncertain("service_start_requires_reconciliation")
|
||||
return
|
||||
}
|
||||
if err := checkpoint("health_checking"); err != nil {
|
||||
return
|
||||
}
|
||||
if err := m.healthCheck(ctx); err != nil {
|
||||
failUncertain("post_update_health_check_failed")
|
||||
return
|
||||
}
|
||||
if err := m.state.UpdateJob(id, func(value *Job) {
|
||||
value.Status = "succeeded"
|
||||
value.Checkpoint = "completed"
|
||||
value.ErrorCode = ""
|
||||
}); err != nil {
|
||||
m.state.ForceManual(id, "state_persistence_failed")
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Manager) validateLocalRepository(ctx context.Context) (string, error) {
|
||||
repository, err := filepath.EvalSymlinks(m.config.RepositoryDir)
|
||||
if err != nil {
|
||||
return "", errors.New("repository is unavailable")
|
||||
}
|
||||
root, err := m.gitLine(ctx, "rev-parse", "--show-toplevel")
|
||||
if err != nil {
|
||||
return "", errors.New("repository cannot be identified")
|
||||
}
|
||||
resolvedRoot, err := filepath.EvalSymlinks(root)
|
||||
if err != nil || resolvedRoot != repository {
|
||||
return "", errors.New("repository path does not match its Git root")
|
||||
}
|
||||
branch, err := m.gitLine(ctx, "symbolic-ref", "--short", "HEAD")
|
||||
if err != nil || branch != RequiredBranch {
|
||||
return "", errors.New("repository is not on the go branch")
|
||||
}
|
||||
remote, err := m.gitLine(ctx, "remote", "get-url", "origin")
|
||||
if err != nil || remote != RequiredRemoteURL {
|
||||
return "", errors.New("repository origin is not approved")
|
||||
}
|
||||
statePath, err := filepath.EvalSymlinks(m.config.StatePath)
|
||||
if err != nil {
|
||||
return "", errors.New("update state is unavailable")
|
||||
}
|
||||
stateRelative, err := filepath.Rel(repository, statePath)
|
||||
if err != nil || strings.HasPrefix(stateRelative, ".."+string(filepath.Separator)) {
|
||||
return "", errors.New("update state is outside the repository runtime directory")
|
||||
}
|
||||
if _, err := m.run(ctx, nil, "git", "check-ignore", "-q", "--", filepath.ToSlash(stateRelative)); err != nil {
|
||||
return "", errors.New("update state path is not ignored by Git")
|
||||
}
|
||||
status, err := m.run(ctx, nil, "git", "status", "--porcelain=v1", "--untracked-files=normal")
|
||||
if err != nil || len(status) != 0 {
|
||||
return "", errors.New("repository worktree is not clean")
|
||||
}
|
||||
commit, err := m.gitLine(ctx, "rev-parse", "HEAD")
|
||||
if err != nil || !commitPattern.MatchString(commit) {
|
||||
return "", errors.New("current commit is invalid")
|
||||
}
|
||||
return commit, nil
|
||||
}
|
||||
|
||||
func (m *Manager) remoteCommit(ctx context.Context) (string, error) {
|
||||
environment, cleanup, err := m.gitEnvironment()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer cleanup()
|
||||
output, err := m.run(ctx, environment, "git", "ls-remote", "--exit-code", "--heads", RequiredRemoteURL, "refs/heads/"+RequiredBranch)
|
||||
if err != nil {
|
||||
return "", errors.New("remote branch check failed")
|
||||
}
|
||||
fields := strings.Fields(string(output))
|
||||
if len(fields) != 2 || fields[1] != "refs/heads/"+RequiredBranch || !commitPattern.MatchString(fields[0]) {
|
||||
return "", errors.New("remote branch response was invalid")
|
||||
}
|
||||
return fields[0], nil
|
||||
}
|
||||
|
||||
func (m *Manager) fetch(ctx context.Context) error {
|
||||
environment, cleanup, err := m.gitEnvironment()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer cleanup()
|
||||
_, err = m.run(ctx, environment, "git", "fetch", "--no-tags", "--prune", "origin",
|
||||
"+refs/heads/"+RequiredBranch+":refs/remotes/origin/"+RequiredBranch)
|
||||
return err
|
||||
}
|
||||
|
||||
func (m *Manager) gitEnvironment() ([]string, func(), error) {
|
||||
directory := filepath.Dir(m.config.StatePath)
|
||||
if err := os.MkdirAll(directory, 0o700); err != nil {
|
||||
return nil, func() {}, errors.New("cannot prepare Git credential helper")
|
||||
}
|
||||
file, err := os.CreateTemp(directory, ".git-askpass-*.sh")
|
||||
if err != nil {
|
||||
return nil, func() {}, errors.New("cannot prepare Git credential helper")
|
||||
}
|
||||
path := file.Name()
|
||||
cleanup := func() { _ = os.Remove(path) }
|
||||
script := "#!/bin/sh\ncase \"$1\" in\n*sername*) printf '%s\\n' 'oauth2' ;;\n*) printf '%s\\n' \"$VIRT_CLOUD_UPDATE_TOKEN\" ;;\nesac\n"
|
||||
if err := file.Chmod(0o700); err != nil {
|
||||
file.Close()
|
||||
cleanup()
|
||||
return nil, func() {}, errors.New("cannot protect Git credential helper")
|
||||
}
|
||||
if _, err := file.WriteString(script); err != nil {
|
||||
file.Close()
|
||||
cleanup()
|
||||
return nil, func() {}, errors.New("cannot write Git credential helper")
|
||||
}
|
||||
if err := file.Close(); err != nil {
|
||||
cleanup()
|
||||
return nil, func() {}, errors.New("cannot finish Git credential helper")
|
||||
}
|
||||
return []string{"GIT_TERMINAL_PROMPT=0", "GIT_ASKPASS=" + path, "VIRT_CLOUD_UPDATE_TOKEN=" + m.state.AccessToken()}, cleanup, nil
|
||||
}
|
||||
|
||||
func (m *Manager) remoteTrackingCommit(ctx context.Context) (string, error) {
|
||||
return m.gitLine(ctx, "rev-parse", "refs/remotes/origin/"+RequiredBranch)
|
||||
}
|
||||
|
||||
func (m *Manager) ensureFastForward(ctx context.Context, current, remote string) error {
|
||||
_, err := m.run(ctx, nil, "git", "merge-base", "--is-ancestor", current, remote)
|
||||
return err
|
||||
}
|
||||
|
||||
func (m *Manager) changedPaths(ctx context.Context, current, remote string) ([]string, error) {
|
||||
output, err := m.run(ctx, nil, "git", "diff", "--name-only", "-z", current+".."+remote)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
parts := strings.Split(string(output), "\x00")
|
||||
if len(parts) > 0 && parts[len(parts)-1] == "" {
|
||||
parts = parts[:len(parts)-1]
|
||||
}
|
||||
return parts, nil
|
||||
}
|
||||
|
||||
func deniedChangedPath(paths []string) bool {
|
||||
for _, path := range paths {
|
||||
clean := filepath.ToSlash(filepath.Clean(path))
|
||||
if clean == "." || clean == ".gitignore" || clean != path || strings.HasPrefix(clean, "../") || strings.HasPrefix(clean, "deploy/") {
|
||||
return true
|
||||
}
|
||||
base := strings.ToLower(filepath.Base(clean))
|
||||
if base == "go.mod" || base == "go.sum" || base == "composer.json" || base == "composer.lock" ||
|
||||
base == "package.json" || base == "package-lock.json" || base == "yarn.lock" || base == "pnpm-lock.yaml" ||
|
||||
base == "cargo.toml" || base == "cargo.lock" || strings.HasPrefix(base, "requirements") && strings.HasSuffix(base, ".txt") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (m *Manager) preflight(ctx context.Context, targetCommit string) error {
|
||||
if _, err := m.webDirectory(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := m.targetHasSchemaInitCommand(ctx, targetCommit); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := m.run(ctx, nil, m.config.PHPCommand, "--version"); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, unit := range append([]string{m.config.PHPFPMUnit}, m.config.ServiceUnits...) {
|
||||
output, err := m.run(ctx, nil, "systemctl", "show", "--property=LoadState", "--property=ActiveState", unit)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
properties := parseSystemdProperties(output)
|
||||
if properties["LoadState"] != "loaded" || properties["ActiveState"] != "active" {
|
||||
return errors.New("required service is not loaded and active")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Manager) webDirectory() (string, error) {
|
||||
repository, err := filepath.EvalSymlinks(m.config.RepositoryDir)
|
||||
if err != nil {
|
||||
return "", errors.New("repository is unavailable")
|
||||
}
|
||||
webDirectory, err := filepath.EvalSymlinks(filepath.Join(m.config.RepositoryDir, "web"))
|
||||
if err != nil || !pathWithin(repository, webDirectory) {
|
||||
return "", errors.New("web directory is unavailable or escapes the repository")
|
||||
}
|
||||
xcatPath := filepath.Join(webDirectory, "xcat")
|
||||
info, err := os.Lstat(xcatPath)
|
||||
if err != nil || !info.Mode().IsRegular() || info.Mode()&os.ModeSymlink != 0 {
|
||||
return "", errors.New("web/xcat must be a regular file")
|
||||
}
|
||||
return webDirectory, nil
|
||||
}
|
||||
|
||||
func (m *Manager) targetHasSchemaInitCommand(ctx context.Context, targetCommit string) error {
|
||||
output, err := m.run(ctx, nil, "git", "ls-tree", "-z", targetCommit, "--", "web/xcat")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
line := strings.TrimSuffix(string(output), "\x00")
|
||||
metadata, path, ok := strings.Cut(line, "\t")
|
||||
fields := strings.Fields(metadata)
|
||||
if !ok || path != "web/xcat" || len(fields) != 3 ||
|
||||
(fields[0] != "100644" && fields[0] != "100755") || fields[1] != "blob" || !commitPattern.MatchString(fields[2]) {
|
||||
return errors.New("target does not contain a regular web/xcat command")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func parseSystemdProperties(output []byte) map[string]string {
|
||||
properties := make(map[string]string)
|
||||
for _, line := range strings.Split(strings.TrimSpace(string(output)), "\n") {
|
||||
key, value, ok := strings.Cut(strings.TrimSpace(line), "=")
|
||||
if ok && key != "" {
|
||||
properties[key] = value
|
||||
}
|
||||
}
|
||||
return properties
|
||||
}
|
||||
|
||||
func (m *Manager) stopServices(ctx context.Context) error {
|
||||
for _, unit := range append(append([]string(nil), m.config.ServiceUnits...), m.config.PHPFPMUnit) {
|
||||
if _, err := m.run(ctx, nil, "systemctl", "stop", unit); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Manager) startServices(ctx context.Context) error {
|
||||
if _, err := m.run(ctx, nil, "systemctl", "start", m.config.PHPFPMUnit); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := m.waitUnitsActive(ctx, []string{m.config.PHPFPMUnit}); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, unit := range m.config.ServiceUnits {
|
||||
if _, err := m.run(ctx, nil, "systemctl", "start", unit); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Manager) healthCheck(ctx context.Context) error {
|
||||
return m.waitUnitsActive(ctx, append([]string{m.config.PHPFPMUnit}, m.config.ServiceUnits...))
|
||||
}
|
||||
|
||||
func (m *Manager) waitUnitsActive(ctx context.Context, units []string) error {
|
||||
deadline := time.Now().Add(m.healthTimeout)
|
||||
for {
|
||||
allActive := true
|
||||
for _, unit := range units {
|
||||
if _, err := m.run(ctx, nil, "systemctl", "is-active", "--quiet", unit); err != nil {
|
||||
allActive = false
|
||||
break
|
||||
}
|
||||
}
|
||||
if allActive {
|
||||
return nil
|
||||
}
|
||||
if !time.Now().Before(deadline) {
|
||||
return errors.New("service health deadline exceeded")
|
||||
}
|
||||
timer := time.NewTimer(m.healthPollInterval)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
timer.Stop()
|
||||
return ctx.Err()
|
||||
case <-timer.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Manager) gitLine(ctx context.Context, arguments ...string) (string, error) {
|
||||
output, err := m.run(ctx, nil, "git", arguments...)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
value := strings.TrimSpace(string(output))
|
||||
if value == "" || strings.ContainsAny(value, "\x00\r\n") {
|
||||
return "", errors.New("Git returned a non-canonical value")
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func (m *Manager) run(ctx context.Context, environment []string, command string, arguments ...string) ([]byte, error) {
|
||||
return m.runAt(ctx, m.config.RepositoryDir, environment, command, arguments...)
|
||||
}
|
||||
|
||||
func (m *Manager) runAt(ctx context.Context, directory string, environment []string, command string, arguments ...string) ([]byte, error) {
|
||||
output, err := m.executor.Run(ctx, directory, environment, command, arguments...)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("update command failed")
|
||||
}
|
||||
return output, nil
|
||||
}
|
||||
@ -1,252 +0,0 @@
|
||||
package update
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
testCurrent = "1111111111111111111111111111111111111111"
|
||||
testRemote = "2222222222222222222222222222222222222222"
|
||||
)
|
||||
|
||||
type recordedCommand struct {
|
||||
directory string
|
||||
command string
|
||||
args []string
|
||||
env []string
|
||||
}
|
||||
|
||||
type fakeExecutor struct {
|
||||
directory string
|
||||
changed string
|
||||
failMatch string
|
||||
mu sync.Mutex
|
||||
calls []recordedCommand
|
||||
}
|
||||
|
||||
func (f *fakeExecutor) Run(_ context.Context, directory string, environment []string, command string, arguments ...string) ([]byte, error) {
|
||||
f.mu.Lock()
|
||||
f.calls = append(f.calls, recordedCommand{directory: directory, command: command, args: append([]string(nil), arguments...), env: append([]string(nil), environment...)})
|
||||
f.mu.Unlock()
|
||||
joined := command + " " + strings.Join(arguments, " ")
|
||||
if f.failMatch != "" && strings.Contains(joined, f.failMatch) {
|
||||
return nil, errors.New("sensitive fake command diagnostic")
|
||||
}
|
||||
if command == "git" {
|
||||
switch {
|
||||
case strings.HasPrefix(strings.Join(arguments, " "), "rev-parse --show-toplevel"):
|
||||
return []byte(f.directory + "\n"), nil
|
||||
case strings.HasPrefix(strings.Join(arguments, " "), "symbolic-ref"):
|
||||
return []byte("go\n"), nil
|
||||
case strings.HasPrefix(strings.Join(arguments, " "), "remote get-url"):
|
||||
return []byte(RequiredRemoteURL + "\n"), nil
|
||||
case strings.HasPrefix(strings.Join(arguments, " "), "status"):
|
||||
return nil, nil
|
||||
case strings.Join(arguments, " ") == "rev-parse HEAD":
|
||||
return []byte(testCurrent + "\n"), nil
|
||||
case strings.HasPrefix(strings.Join(arguments, " "), "ls-remote"):
|
||||
return []byte(testRemote + "\trefs/heads/go\n"), nil
|
||||
case strings.Join(arguments, " ") == "rev-parse refs/remotes/origin/go":
|
||||
return []byte(testRemote + "\n"), nil
|
||||
case strings.HasPrefix(strings.Join(arguments, " "), "diff --name-only"):
|
||||
return []byte(f.changed), nil
|
||||
case strings.HasPrefix(strings.Join(arguments, " "), "ls-tree -z"):
|
||||
return []byte("100644 blob 3333333333333333333333333333333333333333\tweb/xcat\x00"), nil
|
||||
default:
|
||||
return nil, nil
|
||||
}
|
||||
}
|
||||
if command == "systemctl" && len(arguments) > 0 && arguments[0] == "show" {
|
||||
return []byte("LoadState=loaded\nActiveState=active\n"), nil
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func newTestManager(t *testing.T, executor *fakeExecutor) (*Manager, *StateStore) {
|
||||
t.Helper()
|
||||
directory := t.TempDir()
|
||||
executor.directory = directory
|
||||
if err := os.MkdirAll(filepath.Join(directory, "web"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(directory, "web", "xcat"), []byte("<?php\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
config := validTestConfig(directory)
|
||||
state, err := OpenState(config.StatePath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
manager, err := NewManager(config, state, executor)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return manager, state
|
||||
}
|
||||
|
||||
func waitJob(t *testing.T, state *StateStore, id string) Job {
|
||||
t.Helper()
|
||||
deadline := time.Now().Add(3 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
job, _ := state.Job(id)
|
||||
if job.Status == "succeeded" || job.Status == "failed" || job.Status == "manual_intervention" {
|
||||
return job
|
||||
}
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
}
|
||||
job, _ := state.Job(id)
|
||||
t.Fatalf("job did not finish: %#v", job)
|
||||
return Job{}
|
||||
}
|
||||
|
||||
func TestCheckIsReadOnlyAndDoesNotPutTokenInArguments(t *testing.T) {
|
||||
executor := &fakeExecutor{}
|
||||
manager, state := newTestManager(t, executor)
|
||||
if err := state.SetAccessToken("private-token-value"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
result, err := manager.Check(context.Background())
|
||||
if err != nil || result.CurrentCommit != testCurrent || result.RemoteCommit != testRemote || !result.UpdateAvailable ||
|
||||
result.Status != "update_available" || result.Repository != RequiredRemoteURL {
|
||||
t.Fatalf("check result=%#v err=%v", result, err)
|
||||
}
|
||||
for _, call := range executor.calls {
|
||||
if strings.Contains(strings.Join(call.args, " "), "private-token-value") {
|
||||
t.Fatal("access token was placed in process arguments")
|
||||
}
|
||||
if call.command == "git" && len(call.args) > 0 && call.args[0] == "fetch" {
|
||||
t.Fatal("read-only check fetched into the repository")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyRunsCheckpointedFastForward(t *testing.T) {
|
||||
executor := &fakeExecutor{changed: "web/app.php\x00gateway/update/server.go\x00"}
|
||||
manager, state := newTestManager(t, executor)
|
||||
expectedWebDirectory, err := filepath.EvalSymlinks(filepath.Join(executor.directory, "web"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
job, err := manager.StartApply(testCurrent, testRemote)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
job = waitJob(t, state, job.ID)
|
||||
if job.Status != "succeeded" || job.Checkpoint != "completed" || job.PreviousCommit != testCurrent || job.AppliedCommit != testRemote {
|
||||
t.Fatalf("unexpected completed job: %#v", job)
|
||||
}
|
||||
for _, call := range executor.calls {
|
||||
if call.command == "/usr/bin/php" && strings.Join(call.args, " ") == "xcat cloudInit" &&
|
||||
call.directory != expectedWebDirectory {
|
||||
t.Fatalf("schema initialization ran in %q instead of web directory", call.directory)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyRejectsDependencyAndDeployChangesBeforeStopping(t *testing.T) {
|
||||
for _, changed := range []string{"deploy/virt-cloud.service\x00", "gateway/go.sum\x00", "web/composer.lock\x00"} {
|
||||
executor := &fakeExecutor{changed: changed}
|
||||
manager, state := newTestManager(t, executor)
|
||||
job, err := manager.StartApply(testCurrent, testRemote)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
job = waitJob(t, state, job.ID)
|
||||
if job.Status != "failed" || job.ErrorCode != "manual_upgrade_required" {
|
||||
t.Fatalf("changed=%q job=%#v", changed, job)
|
||||
}
|
||||
for _, call := range executor.calls {
|
||||
if call.command == "systemctl" {
|
||||
t.Fatalf("services were touched for denied change %q", changed)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSchemaInitializationFailureHoldsMaintenanceLock(t *testing.T) {
|
||||
executor := &fakeExecutor{changed: "web/app.php\x00", failMatch: "/usr/bin/php xcat cloudInit"}
|
||||
manager, state := newTestManager(t, executor)
|
||||
job, err := manager.StartApply(testCurrent, testRemote)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
job = waitJob(t, state, job.ID)
|
||||
if job.Status != "manual_intervention" || job.ErrorCode != "schema_init_result_uncertain" || !state.MaintenanceLocked() {
|
||||
t.Fatalf("schema initialization failure was not fail-closed: %#v lock=%v", job, state.MaintenanceLocked())
|
||||
}
|
||||
if _, err := manager.StartApply(testCurrent, testRemote); err == nil {
|
||||
t.Fatal("new apply accepted while manual reconciliation is required")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPreflightFailureStopsBeforeAnyMutation(t *testing.T) {
|
||||
executor := &fakeExecutor{changed: "web/app.php\x00", failMatch: "systemctl show"}
|
||||
manager, state := newTestManager(t, executor)
|
||||
job, err := manager.StartApply(testCurrent, testRemote)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
job = waitJob(t, state, job.ID)
|
||||
if job.Status != "failed" || job.ErrorCode != "host_preflight_failed" || state.MaintenanceLocked() {
|
||||
t.Fatalf("preflight failure was not a safe failure: %#v lock=%v", job, state.MaintenanceLocked())
|
||||
}
|
||||
for _, call := range executor.calls {
|
||||
if call.command == "systemctl" && len(call.args) > 0 && (call.args[0] == "stop" || call.args[0] == "start") {
|
||||
t.Fatalf("preflight failure mutated service state: %#v", call)
|
||||
}
|
||||
if call.command == "git" && len(call.args) > 0 && call.args[0] == "merge" {
|
||||
t.Fatalf("preflight failure mutated the checkout: %#v", call)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPreflightRejectsSchemaInitializerSymlink(t *testing.T) {
|
||||
executor := &fakeExecutor{changed: "web/app.php\x00"}
|
||||
manager, state := newTestManager(t, executor)
|
||||
xcat := filepath.Join(executor.directory, "web", "xcat")
|
||||
if err := os.Remove(xcat); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Symlink("elsewhere", xcat); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
job, err := manager.StartApply(testCurrent, testRemote)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
job = waitJob(t, state, job.ID)
|
||||
if job.Status != "failed" || job.ErrorCode != "host_preflight_failed" {
|
||||
t.Fatalf("schema initializer symlink was not rejected before mutation: %#v", job)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyRejectsNoOpCommitPair(t *testing.T) {
|
||||
manager, _ := newTestManager(t, &fakeExecutor{})
|
||||
if _, err := manager.StartApply(testCurrent, testCurrent); err == nil {
|
||||
t.Fatal("no-op update was accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCommandEnvironmentDropsGitAndLoaderInjection(t *testing.T) {
|
||||
t.Setenv("GIT_DIR", "/attacker/repository")
|
||||
t.Setenv("GIT_CONFIG_KEY_0", "core.hooksPath")
|
||||
t.Setenv("GIT_CONFIG_VALUE_0", "/attacker/hooks")
|
||||
t.Setenv("DYLD_INSERT_LIBRARIES", "/attacker/library")
|
||||
values := commandEnvironment([]string{"GIT_TERMINAL_PROMPT=0"})
|
||||
joined := strings.Join(values, "\n")
|
||||
for _, forbidden := range []string{"GIT_DIR=", "GIT_CONFIG_KEY_0=", "GIT_CONFIG_VALUE_0=", "DYLD_INSERT_LIBRARIES="} {
|
||||
if strings.Contains(joined, forbidden) {
|
||||
t.Fatalf("unsafe environment survived: %s", forbidden)
|
||||
}
|
||||
}
|
||||
if !strings.Contains(joined, "GIT_TERMINAL_PROMPT=0") {
|
||||
t.Fatal("explicit safe override was lost")
|
||||
}
|
||||
}
|
||||
@ -1,311 +0,0 @@
|
||||
package update
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.luoli.live/root/virt/gateway/internal/protocol"
|
||||
)
|
||||
|
||||
const maxAPIRequestBody = 64 << 10
|
||||
|
||||
var jobIDPattern = regexp.MustCompile(`^[A-Za-z0-9_-]{32}$`)
|
||||
|
||||
type Server struct {
|
||||
manager *Manager
|
||||
state *StateStore
|
||||
authenticator *protocol.Authenticator
|
||||
}
|
||||
|
||||
type jobResponse struct {
|
||||
JobID string `json:"job_id"`
|
||||
Status string `json:"status"`
|
||||
Phase string `json:"phase"`
|
||||
Error string `json:"error,omitempty"`
|
||||
ErrorCode string `json:"error_code,omitempty"`
|
||||
NewCommit string `json:"new_commit,omitempty"`
|
||||
RollbackRef string `json:"rollback_ref,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
func NewServer(manager *Manager, state *StateStore, secret []byte) (*Server, error) {
|
||||
if manager == nil || state == nil {
|
||||
return nil, errors.New("update manager and state are required")
|
||||
}
|
||||
authenticator, err := protocol.NewAuthenticator(secret, 60*time.Second, 2*time.Minute, state)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Server{manager: manager, state: state, authenticator: authenticator}, nil
|
||||
}
|
||||
|
||||
func (s *Server) ServeHTTP(response http.ResponseWriter, request *http.Request) {
|
||||
response.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
response.Header().Set("Cache-Control", "no-store")
|
||||
response.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
body, err := readRequestBody(response, request)
|
||||
if err != nil {
|
||||
writeAPIError(response, http.StatusBadRequest, "invalid_request")
|
||||
return
|
||||
}
|
||||
actor, err := s.authenticator.Authenticate(request, body)
|
||||
if err != nil {
|
||||
if errors.Is(err, protocol.ErrNonceStore) {
|
||||
writeAPIError(response, http.StatusServiceUnavailable, "authentication_state_unavailable")
|
||||
return
|
||||
}
|
||||
writeAPIError(response, http.StatusUnauthorized, "authentication_failed")
|
||||
return
|
||||
}
|
||||
if !actor.IsAdmin || !actor.IsSuperAdmin || !actor.CanManage || actor.UserID <= 0 || actor.Service != "" {
|
||||
writeAPIError(response, http.StatusForbidden, "super_admin_required")
|
||||
return
|
||||
}
|
||||
s.route(response, request, body)
|
||||
}
|
||||
|
||||
func (s *Server) route(response http.ResponseWriter, request *http.Request, body []byte) {
|
||||
if request.URL.RawQuery != "" {
|
||||
writeAPIError(response, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
switch {
|
||||
case request.URL.Path == "/v1/health" && request.Method == http.MethodGet:
|
||||
writeJSON(response, http.StatusOK, map[string]any{"status": "ok", "maintenance_lock": s.state.MaintenanceLocked()})
|
||||
case request.URL.Path == "/v1/settings" && request.Method == http.MethodGet:
|
||||
writeJSON(response, http.StatusOK, s.manager.Settings(request.Context()))
|
||||
case request.URL.Path == "/v1/settings" && request.Method == http.MethodPut:
|
||||
s.updateSettings(response, request, body)
|
||||
case request.URL.Path == "/v1/settings/token" && request.Method == http.MethodDelete:
|
||||
if len(bytes.TrimSpace(body)) != 0 {
|
||||
writeAPIError(response, http.StatusBadRequest, "body_not_allowed")
|
||||
return
|
||||
}
|
||||
if err := s.state.SetAccessToken(""); err != nil {
|
||||
writeAPIError(response, http.StatusServiceUnavailable, "state_unavailable")
|
||||
return
|
||||
}
|
||||
writeJSON(response, http.StatusOK, s.manager.Settings(request.Context()))
|
||||
case request.URL.Path == "/v1/check" && request.Method == http.MethodPost:
|
||||
if !emptyJSONObject(body) {
|
||||
writeAPIError(response, http.StatusBadRequest, "invalid_request")
|
||||
return
|
||||
}
|
||||
result, err := s.manager.Check(request.Context())
|
||||
if err != nil {
|
||||
writeAPIError(response, http.StatusConflict, "update_check_failed")
|
||||
return
|
||||
}
|
||||
writeJSON(response, http.StatusOK, result)
|
||||
case request.URL.Path == "/v1/apply" && request.Method == http.MethodPost:
|
||||
s.apply(response, body)
|
||||
case request.URL.Path == "/v1/jobs" && request.Method == http.MethodGet:
|
||||
jobs := s.state.Jobs()
|
||||
result := make([]jobResponse, 0, len(jobs))
|
||||
for _, job := range jobs {
|
||||
result = append(result, publicJob(job))
|
||||
}
|
||||
writeJSON(response, http.StatusOK, map[string]any{"jobs": result, "maintenance_lock": s.state.MaintenanceLocked()})
|
||||
case strings.HasPrefix(request.URL.Path, "/v1/jobs/"):
|
||||
s.job(response, request, body)
|
||||
default:
|
||||
writeAPIError(response, http.StatusNotFound, "not_found")
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) updateSettings(response http.ResponseWriter, request *http.Request, body []byte) {
|
||||
var input struct {
|
||||
AccessToken *string `json:"access_token"`
|
||||
ClearToken *bool `json:"clear_token"`
|
||||
}
|
||||
if err := decodeJSONObject(body, &input); err != nil || (input.AccessToken == nil && input.ClearToken == nil) ||
|
||||
(input.ClearToken != nil && *input.ClearToken && input.AccessToken != nil && *input.AccessToken != "") {
|
||||
writeAPIError(response, http.StatusUnprocessableEntity, "invalid_access_token")
|
||||
return
|
||||
}
|
||||
if input.ClearToken != nil && *input.ClearToken {
|
||||
if err := s.state.SetAccessToken(""); err != nil {
|
||||
writeAPIError(response, http.StatusServiceUnavailable, "state_unavailable")
|
||||
return
|
||||
}
|
||||
} else if input.AccessToken != nil && *input.AccessToken != "" {
|
||||
if !validAccessToken(*input.AccessToken) {
|
||||
writeAPIError(response, http.StatusUnprocessableEntity, "invalid_access_token")
|
||||
return
|
||||
}
|
||||
if err := s.state.SetAccessToken(*input.AccessToken); err != nil {
|
||||
writeAPIError(response, http.StatusServiceUnavailable, "state_unavailable")
|
||||
return
|
||||
}
|
||||
} else if input.AccessToken == nil {
|
||||
writeAPIError(response, http.StatusUnprocessableEntity, "invalid_access_token")
|
||||
return
|
||||
}
|
||||
if input.ClearToken != nil && !*input.ClearToken && input.AccessToken == nil {
|
||||
writeAPIError(response, http.StatusUnprocessableEntity, "invalid_access_token")
|
||||
return
|
||||
}
|
||||
writeJSON(response, http.StatusOK, s.manager.Settings(request.Context()))
|
||||
}
|
||||
|
||||
func (s *Server) apply(response http.ResponseWriter, body []byte) {
|
||||
var input struct {
|
||||
ExpectedCurrentCommit string `json:"expected_current_commit"`
|
||||
ExpectedRemoteCommit string `json:"expected_remote_commit"`
|
||||
}
|
||||
if err := decodeJSONObject(body, &input); err != nil {
|
||||
writeAPIError(response, http.StatusBadRequest, "invalid_request")
|
||||
return
|
||||
}
|
||||
job, err := s.manager.StartApply(input.ExpectedCurrentCommit, input.ExpectedRemoteCommit)
|
||||
if err != nil {
|
||||
writeAPIError(response, http.StatusConflict, "update_precondition_failed")
|
||||
return
|
||||
}
|
||||
writeJSON(response, http.StatusAccepted, publicJob(job))
|
||||
}
|
||||
|
||||
func (s *Server) job(response http.ResponseWriter, request *http.Request, body []byte) {
|
||||
remainder := strings.TrimPrefix(request.URL.Path, "/v1/jobs/")
|
||||
parts := strings.Split(remainder, "/")
|
||||
if len(parts) == 1 && request.Method == http.MethodGet && jobIDPattern.MatchString(parts[0]) {
|
||||
job, ok := s.state.Job(parts[0])
|
||||
if !ok {
|
||||
writeAPIError(response, http.StatusNotFound, "job_not_found")
|
||||
return
|
||||
}
|
||||
writeJSON(response, http.StatusOK, publicJob(job))
|
||||
return
|
||||
}
|
||||
if len(parts) == 2 && parts[1] == "resolve" && request.Method == http.MethodPost && jobIDPattern.MatchString(parts[0]) {
|
||||
var input struct {
|
||||
Resolution string `json:"resolution"`
|
||||
Evidence string `json:"evidence"`
|
||||
}
|
||||
if err := decodeJSONObject(body, &input); err != nil ||
|
||||
(input.Resolution != "completed" && input.Resolution != "rolled_back") ||
|
||||
!validEvidence(input.Evidence) {
|
||||
writeAPIError(response, http.StatusUnprocessableEntity, "invalid_resolution")
|
||||
return
|
||||
}
|
||||
if err := s.state.ResolveJob(parts[0], input.Resolution, input.Evidence); err != nil {
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
writeAPIError(response, http.StatusNotFound, "job_not_found")
|
||||
} else {
|
||||
writeAPIError(response, http.StatusConflict, "job_not_reconcilable")
|
||||
}
|
||||
return
|
||||
}
|
||||
job, _ := s.state.Job(parts[0])
|
||||
writeJSON(response, http.StatusOK, publicJob(job))
|
||||
return
|
||||
}
|
||||
writeAPIError(response, http.StatusNotFound, "not_found")
|
||||
}
|
||||
|
||||
func publicJob(job Job) jobResponse {
|
||||
status := job.Status
|
||||
if status == "manual_intervention" {
|
||||
status = "blocked"
|
||||
} else if status == "resolved" {
|
||||
if job.Resolution == "completed" {
|
||||
status = "succeeded"
|
||||
} else {
|
||||
status = "failed"
|
||||
}
|
||||
}
|
||||
result := jobResponse{JobID: job.ID, Status: status, Phase: job.Checkpoint,
|
||||
ErrorCode: job.ErrorCode, NewCommit: job.AppliedCommit, RollbackRef: job.PreviousCommit,
|
||||
CreatedAt: job.CreatedAt, UpdatedAt: job.UpdatedAt}
|
||||
if job.Status == "manual_intervention" {
|
||||
result.Error = "更新状态不确定,必须通过 SSH 核对后再处理"
|
||||
} else if job.Status == "failed" {
|
||||
result.Error = "更新已在主机变更前安全终止"
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func readRequestBody(response http.ResponseWriter, request *http.Request) ([]byte, error) {
|
||||
request.Body = http.MaxBytesReader(response, request.Body, maxAPIRequestBody)
|
||||
body, err := io.ReadAll(request.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return body, nil
|
||||
}
|
||||
|
||||
func decodeJSONObject(body []byte, destination any) error {
|
||||
if len(bytes.TrimSpace(body)) == 0 {
|
||||
return errors.New("JSON object required")
|
||||
}
|
||||
decoder := json.NewDecoder(bytes.NewReader(body))
|
||||
decoder.DisallowUnknownFields()
|
||||
if err := decoder.Decode(destination); err != nil {
|
||||
return err
|
||||
}
|
||||
var extra any
|
||||
if err := decoder.Decode(&extra); !errors.Is(err, io.EOF) {
|
||||
return errors.New("trailing JSON data")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func emptyJSONObject(body []byte) bool {
|
||||
if len(bytes.TrimSpace(body)) == 0 {
|
||||
return true
|
||||
}
|
||||
var value map[string]any
|
||||
return decodeJSONObject(body, &value) == nil && len(value) == 0
|
||||
}
|
||||
|
||||
func validAccessToken(value string) bool {
|
||||
if len(value) < 8 || len(value) > 4096 {
|
||||
return false
|
||||
}
|
||||
for _, character := range value {
|
||||
if character < 0x21 || character == 0x7f {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func validEvidence(value string) bool {
|
||||
value = strings.TrimSpace(value)
|
||||
if len(value) < 8 || len(value) > 500 || !strings.Contains(value, ":") {
|
||||
return false
|
||||
}
|
||||
for _, character := range value {
|
||||
if character < 0x20 || character == 0x7f {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func randomID() (string, error) {
|
||||
random := make([]byte, 24)
|
||||
if _, err := rand.Read(random); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return base64.RawURLEncoding.EncodeToString(random), nil
|
||||
}
|
||||
|
||||
func writeAPIError(response http.ResponseWriter, status int, code string) {
|
||||
writeJSON(response, status, map[string]any{"error": map[string]string{"code": code}})
|
||||
}
|
||||
|
||||
func writeJSON(response http.ResponseWriter, status int, value any) {
|
||||
response.WriteHeader(status)
|
||||
_ = json.NewEncoder(response).Encode(value)
|
||||
}
|
||||
@ -1,82 +0,0 @@
|
||||
package update
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.luoli.live/root/virt/gateway/internal/protocol"
|
||||
)
|
||||
|
||||
func TestSettingsNeverEchoAccessTokenAndRejectReplay(t *testing.T) {
|
||||
executor := &fakeExecutor{}
|
||||
manager, state := newTestManager(t, executor)
|
||||
secret := []byte(strings.Repeat("x", 32))
|
||||
server, err := NewServer(manager, state, secret)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
token := "glpat-this-must-never-appear-in-response"
|
||||
body := []byte(`{"access_token":"` + token + `"}`)
|
||||
request := signedAPIRequest(t, http.MethodPut, "/v1/settings", body, secret, "0123456789abcdef0123456789abcdef")
|
||||
response := httptest.NewRecorder()
|
||||
server.ServeHTTP(response, request)
|
||||
if response.Code != http.StatusOK || strings.Contains(response.Body.String(), token) {
|
||||
t.Fatalf("settings response status=%d body=%q", response.Code, response.Body.String())
|
||||
}
|
||||
var payload map[string]any
|
||||
if err := json.Unmarshal(response.Body.Bytes(), &payload); err != nil || payload["token_configured"] != true || payload["repository"] != RequiredRemoteURL {
|
||||
t.Fatalf("settings payload=%#v err=%v", payload, err)
|
||||
}
|
||||
replay := httptest.NewRecorder()
|
||||
server.ServeHTTP(replay, request)
|
||||
if replay.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("replay status=%d", replay.Code)
|
||||
}
|
||||
raw, err := os.ReadFile(state.path)
|
||||
if err != nil || !bytes.Contains(raw, []byte(token)) {
|
||||
t.Fatal("token was not durably stored")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSettingsBlankPreservesAndClearTokenRemovesCredential(t *testing.T) {
|
||||
executor := &fakeExecutor{}
|
||||
manager, state := newTestManager(t, executor)
|
||||
secret := []byte(strings.Repeat("x", 32))
|
||||
server, _ := NewServer(manager, state, secret)
|
||||
if err := state.SetAccessToken("existing-private-token"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
preserveBody := []byte(`{"access_token":""}`)
|
||||
preserve := httptest.NewRecorder()
|
||||
server.ServeHTTP(preserve, signedAPIRequest(t, http.MethodPut, "/v1/settings", preserveBody, secret,
|
||||
"11111111111111111111111111111111"))
|
||||
if preserve.Code != http.StatusOK || state.AccessToken() != "existing-private-token" ||
|
||||
strings.Contains(preserve.Body.String(), "existing-private-token") {
|
||||
t.Fatalf("blank preserve status=%d token=%q body=%q", preserve.Code, state.AccessToken(), preserve.Body.String())
|
||||
}
|
||||
|
||||
clearBody := []byte(`{"clear_token":true}`)
|
||||
clear := httptest.NewRecorder()
|
||||
server.ServeHTTP(clear, signedAPIRequest(t, http.MethodPut, "/v1/settings", clearBody, secret,
|
||||
"22222222222222222222222222222222"))
|
||||
if clear.Code != http.StatusOK || state.TokenConfigured() || strings.Contains(clear.Body.String(), "existing-private-token") {
|
||||
t.Fatalf("clear status=%d configured=%v body=%q", clear.Code, state.TokenConfigured(), clear.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func signedAPIRequest(t *testing.T, method, path string, body, secret []byte, nonce string) *http.Request {
|
||||
t.Helper()
|
||||
request := httptest.NewRequest(method, "http://unix"+path, bytes.NewReader(body))
|
||||
actor := protocol.Actor{UserID: 1, IsAdmin: true, IsSuperAdmin: true, CanManage: true}
|
||||
if err := protocol.Sign(request, body, actor, secret, time.Now(), nonce); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return request
|
||||
}
|
||||
@ -1,418 +0,0 @@
|
||||
package update
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"sort"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Job struct {
|
||||
ID string `json:"id"`
|
||||
Status string `json:"status"`
|
||||
Checkpoint string `json:"checkpoint"`
|
||||
ExpectedCurrentCommit string `json:"expected_current_commit"`
|
||||
ExpectedRemoteCommit string `json:"expected_remote_commit"`
|
||||
PreviousCommit string `json:"previous_commit,omitempty"`
|
||||
AppliedCommit string `json:"applied_commit,omitempty"`
|
||||
ErrorCode string `json:"error_code,omitempty"`
|
||||
Resolution string `json:"resolution,omitempty"`
|
||||
ResolutionEvidence string `json:"resolution_evidence,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
type diskState struct {
|
||||
Version int `json:"version"`
|
||||
AccessToken string `json:"access_token,omitempty"`
|
||||
Maintenance bool `json:"maintenance_lock"`
|
||||
Jobs map[string]Job `json:"jobs"`
|
||||
Nonces map[string]time.Time `json:"nonces"`
|
||||
}
|
||||
|
||||
type StateStore struct {
|
||||
path string
|
||||
now func() time.Time
|
||||
mu sync.Mutex
|
||||
data diskState
|
||||
}
|
||||
|
||||
const maxStateBytes = 8 << 20
|
||||
|
||||
var (
|
||||
stateNoncePattern = regexp.MustCompile(`^[A-Za-z0-9_-]{16,128}$`)
|
||||
stateCheckpointPattern = regexp.MustCompile(`^[a-z][a-z0-9_]{0,63}$`)
|
||||
)
|
||||
|
||||
func OpenState(path string) (*StateStore, error) {
|
||||
store := &StateStore{path: path, now: time.Now, data: diskState{Version: 1, Jobs: map[string]Job{}, Nonces: map[string]time.Time{}}}
|
||||
if err := store.load(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return store, nil
|
||||
}
|
||||
|
||||
// OpenConfiguredState verifies that the fixed runtime directories do not
|
||||
// escape the checkout through symlinks before creating or opening state.
|
||||
func OpenConfiguredState(config Config) (*StateStore, error) {
|
||||
if err := config.Validate(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
repository, err := filepath.EvalSymlinks(config.RepositoryDir)
|
||||
if err != nil {
|
||||
return nil, errors.New("repository directory is unavailable")
|
||||
}
|
||||
runtimePath := filepath.Join(config.RepositoryDir, "runtime")
|
||||
if err := os.Mkdir(runtimePath, 0o700); err != nil && !errors.Is(err, os.ErrExist) {
|
||||
return nil, fmt.Errorf("create runtime directory: %w", err)
|
||||
}
|
||||
runtimeResolved, err := filepath.EvalSymlinks(runtimePath)
|
||||
if err != nil || !pathWithin(repository, runtimeResolved) {
|
||||
return nil, errors.New("runtime directory escapes the repository")
|
||||
}
|
||||
updatePath := filepath.Join(runtimePath, "update")
|
||||
if err := os.Mkdir(updatePath, 0o700); err != nil && !errors.Is(err, os.ErrExist) {
|
||||
return nil, fmt.Errorf("create update state directory: %w", err)
|
||||
}
|
||||
updateResolved, err := filepath.EvalSymlinks(updatePath)
|
||||
if err != nil || !pathWithin(runtimeResolved, updateResolved) {
|
||||
return nil, errors.New("update state directory escapes runtime")
|
||||
}
|
||||
if info, err := os.Lstat(config.StatePath); err == nil {
|
||||
if info.Mode()&os.ModeSymlink != 0 || !info.Mode().IsRegular() {
|
||||
return nil, errors.New("update state path must be a regular file")
|
||||
}
|
||||
} else if !errors.Is(err, os.ErrNotExist) {
|
||||
return nil, fmt.Errorf("inspect update state path: %w", err)
|
||||
}
|
||||
return OpenState(config.StatePath)
|
||||
}
|
||||
|
||||
func (s *StateStore) SetClockForTesting(now func() time.Time) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.now = now
|
||||
}
|
||||
|
||||
func (s *StateStore) load() error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
file, err := os.Open(s.path)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return s.persistLocked()
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("open update state: %w", err)
|
||||
}
|
||||
defer file.Close()
|
||||
raw, err := io.ReadAll(io.LimitReader(file, maxStateBytes+1))
|
||||
if err != nil {
|
||||
return fmt.Errorf("read update state: %w", err)
|
||||
}
|
||||
if len(raw) > maxStateBytes {
|
||||
return errors.New("update state exceeds 8388608 bytes")
|
||||
}
|
||||
decoder := json.NewDecoder(bytes.NewReader(raw))
|
||||
decoder.DisallowUnknownFields()
|
||||
var loaded diskState
|
||||
if err := decoder.Decode(&loaded); err != nil {
|
||||
return fmt.Errorf("decode update state: %w", err)
|
||||
}
|
||||
if err := requireEOF(decoder); err != nil {
|
||||
return fmt.Errorf("decode update state: %w", err)
|
||||
}
|
||||
if err := validateDiskState(loaded); err != nil {
|
||||
return err
|
||||
}
|
||||
now := s.now().UTC()
|
||||
changed := false
|
||||
for id, job := range loaded.Jobs {
|
||||
if job.Status == "queued" || job.Status == "running" {
|
||||
job.Status = "manual_intervention"
|
||||
job.ErrorCode = "interrupted_update_requires_reconciliation"
|
||||
job.UpdatedAt = now
|
||||
loaded.Jobs[id] = job
|
||||
loaded.Maintenance = true
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
s.data = loaded
|
||||
if changed {
|
||||
return s.persistLocked()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateDiskState(state diskState) error {
|
||||
if state.Version != 1 || state.Jobs == nil || state.Nonces == nil {
|
||||
return errors.New("update state has an unsupported or incomplete format")
|
||||
}
|
||||
if state.AccessToken != "" && !validAccessToken(state.AccessToken) {
|
||||
return errors.New("update state contains an invalid access token")
|
||||
}
|
||||
if len(state.Jobs) > 10_000 || len(state.Nonces) > 100_000 {
|
||||
return errors.New("update state exceeds its safe entry limit")
|
||||
}
|
||||
hasManual := false
|
||||
for id, job := range state.Jobs {
|
||||
if id != job.ID || !jobIDPattern.MatchString(id) || !commitPattern.MatchString(job.ExpectedCurrentCommit) ||
|
||||
!commitPattern.MatchString(job.ExpectedRemoteCommit) || !stateCheckpointPattern.MatchString(job.Checkpoint) ||
|
||||
job.CreatedAt.IsZero() || job.UpdatedAt.IsZero() {
|
||||
return errors.New("update state contains an invalid job")
|
||||
}
|
||||
switch job.Status {
|
||||
case "queued", "running", "succeeded", "failed":
|
||||
case "manual_intervention":
|
||||
hasManual = true
|
||||
case "resolved":
|
||||
if (job.Resolution != "completed" && job.Resolution != "rolled_back") || !validEvidence(job.ResolutionEvidence) {
|
||||
return errors.New("update state contains an invalid resolution")
|
||||
}
|
||||
default:
|
||||
return errors.New("update state contains an unknown job status")
|
||||
}
|
||||
}
|
||||
if state.Maintenance != hasManual {
|
||||
return errors.New("update state maintenance lock is inconsistent")
|
||||
}
|
||||
for nonce, expiry := range state.Nonces {
|
||||
if !stateNoncePattern.MatchString(nonce) || expiry.IsZero() {
|
||||
return errors.New("update state contains an invalid nonce")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *StateStore) UseNonce(nonce string, now, expiresAt time.Time) (bool, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
for value, expiry := range s.data.Nonces {
|
||||
if !expiry.After(now) {
|
||||
delete(s.data.Nonces, value)
|
||||
}
|
||||
}
|
||||
if expiry, exists := s.data.Nonces[nonce]; exists && expiry.After(now) {
|
||||
return false, nil
|
||||
}
|
||||
s.data.Nonces[nonce] = expiresAt
|
||||
if err := s.persistLocked(); err != nil {
|
||||
delete(s.data.Nonces, nonce)
|
||||
return false, err
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (s *StateStore) TokenConfigured() bool {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return s.data.AccessToken != ""
|
||||
}
|
||||
|
||||
func (s *StateStore) AccessToken() string {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return s.data.AccessToken
|
||||
}
|
||||
|
||||
func (s *StateStore) SetAccessToken(token string) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
old := s.data.AccessToken
|
||||
s.data.AccessToken = token
|
||||
if err := s.persistLocked(); err != nil {
|
||||
s.data.AccessToken = old
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *StateStore) CreateJob(job Job) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if s.data.Maintenance {
|
||||
return errors.New("maintenance lock is active")
|
||||
}
|
||||
if _, exists := s.data.Jobs[job.ID]; exists {
|
||||
return errors.New("update job ID already exists")
|
||||
}
|
||||
for _, existing := range s.data.Jobs {
|
||||
if existing.Status == "queued" || existing.Status == "running" {
|
||||
return errors.New("an update job is already active")
|
||||
}
|
||||
}
|
||||
now := s.now().UTC()
|
||||
job.Status = "queued"
|
||||
job.Checkpoint = "accepted"
|
||||
job.CreatedAt = now
|
||||
job.UpdatedAt = now
|
||||
s.data.Jobs[job.ID] = job
|
||||
if err := s.persistLocked(); err != nil {
|
||||
delete(s.data.Jobs, job.ID)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *StateStore) UpdateJob(id string, mutate func(*Job)) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
job, ok := s.data.Jobs[id]
|
||||
if !ok {
|
||||
return os.ErrNotExist
|
||||
}
|
||||
old := job
|
||||
oldMaintenance := s.data.Maintenance
|
||||
mutate(&job)
|
||||
job.UpdatedAt = s.now().UTC()
|
||||
s.data.Jobs[id] = job
|
||||
if job.Status == "manual_intervention" {
|
||||
s.data.Maintenance = true
|
||||
}
|
||||
if err := s.persistLocked(); err != nil {
|
||||
s.data.Jobs[id] = old
|
||||
s.data.Maintenance = oldMaintenance
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ForceManual updates only process memory when durable state cannot be
|
||||
// written. The previously persisted queued/running record will also be
|
||||
// converted to manual_intervention on restart, so both the live process and a
|
||||
// replacement fail closed.
|
||||
func (s *StateStore) ForceManual(id, code string) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
job, ok := s.data.Jobs[id]
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
job.Status = "manual_intervention"
|
||||
job.ErrorCode = code
|
||||
job.UpdatedAt = s.now().UTC()
|
||||
s.data.Jobs[id] = job
|
||||
s.data.Maintenance = true
|
||||
}
|
||||
|
||||
func (s *StateStore) ResolveJob(id, resolution, evidence string) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
job, ok := s.data.Jobs[id]
|
||||
if !ok {
|
||||
return os.ErrNotExist
|
||||
}
|
||||
if job.Status != "manual_intervention" {
|
||||
return errors.New("only a manual-intervention job can be resolved")
|
||||
}
|
||||
oldJob := job
|
||||
oldMaintenance := s.data.Maintenance
|
||||
job.Status = "resolved"
|
||||
job.Checkpoint = "operator_reconciled"
|
||||
job.Resolution = resolution
|
||||
job.ResolutionEvidence = evidence
|
||||
job.UpdatedAt = s.now().UTC()
|
||||
s.data.Jobs[id] = job
|
||||
s.data.Maintenance = false
|
||||
for otherID, other := range s.data.Jobs {
|
||||
if otherID != id && other.Status == "manual_intervention" {
|
||||
s.data.Maintenance = true
|
||||
}
|
||||
}
|
||||
if err := s.persistLocked(); err != nil {
|
||||
s.data.Jobs[id] = oldJob
|
||||
s.data.Maintenance = oldMaintenance
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *StateStore) Job(id string) (Job, bool) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
job, ok := s.data.Jobs[id]
|
||||
return job, ok
|
||||
}
|
||||
|
||||
func (s *StateStore) Jobs() []Job {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
jobs := make([]Job, 0, len(s.data.Jobs))
|
||||
for _, job := range s.data.Jobs {
|
||||
jobs = append(jobs, job)
|
||||
}
|
||||
sort.Slice(jobs, func(i, j int) bool { return jobs[i].CreatedAt.After(jobs[j].CreatedAt) })
|
||||
return jobs
|
||||
}
|
||||
|
||||
func (s *StateStore) JobPointers() (active, last string) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
var activeAt, lastAt time.Time
|
||||
for _, job := range s.data.Jobs {
|
||||
if last == "" || job.CreatedAt.After(lastAt) {
|
||||
last = job.ID
|
||||
lastAt = job.CreatedAt
|
||||
}
|
||||
if job.Status == "queued" || job.Status == "running" || job.Status == "manual_intervention" {
|
||||
if active == "" || job.CreatedAt.After(activeAt) {
|
||||
active = job.ID
|
||||
activeAt = job.CreatedAt
|
||||
}
|
||||
}
|
||||
}
|
||||
return active, last
|
||||
}
|
||||
|
||||
func (s *StateStore) MaintenanceLocked() bool {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return s.data.Maintenance
|
||||
}
|
||||
|
||||
func (s *StateStore) persistLocked() error {
|
||||
directory := filepath.Dir(s.path)
|
||||
if err := os.MkdirAll(directory, 0o700); err != nil {
|
||||
return fmt.Errorf("create update state directory: %w", err)
|
||||
}
|
||||
data, err := json.MarshalIndent(s.data, "", " ")
|
||||
if err != nil {
|
||||
return fmt.Errorf("encode update state: %w", err)
|
||||
}
|
||||
temporary, err := os.CreateTemp(directory, ".state-*.tmp")
|
||||
if err != nil {
|
||||
return fmt.Errorf("create temporary update state: %w", err)
|
||||
}
|
||||
temporaryPath := temporary.Name()
|
||||
defer os.Remove(temporaryPath)
|
||||
if err := temporary.Chmod(0o600); err != nil {
|
||||
temporary.Close()
|
||||
return err
|
||||
}
|
||||
if _, err := temporary.Write(append(data, '\n')); err != nil {
|
||||
temporary.Close()
|
||||
return err
|
||||
}
|
||||
if err := temporary.Sync(); err != nil {
|
||||
temporary.Close()
|
||||
return err
|
||||
}
|
||||
if err := temporary.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.Rename(temporaryPath, s.path); err != nil {
|
||||
return fmt.Errorf("replace update state: %w", err)
|
||||
}
|
||||
directoryHandle, err := os.Open(directory)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer directoryHandle.Close()
|
||||
return directoryHandle.Sync()
|
||||
}
|
||||
@ -1,54 +0,0 @@
|
||||
package update
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestInterruptedJobBecomesManualIntervention(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "state.json")
|
||||
state, err := OpenState(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
job := Job{ID: "abcdefghijklmnopqrstuvwxyzABCDEF", ExpectedCurrentCommit: testCurrent, ExpectedRemoteCommit: testRemote}
|
||||
if err := state.CreateJob(job); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reopened, err := OpenState(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, ok := reopened.Job(job.ID)
|
||||
if !ok || got.Status != "manual_intervention" || got.Checkpoint != "accepted" || !reopened.MaintenanceLocked() {
|
||||
t.Fatalf("interrupted job was not failed closed: %#v lock=%v", got, reopened.MaintenanceLocked())
|
||||
}
|
||||
if _, ok := reopened.Job("missing"); ok {
|
||||
t.Fatal("missing job unexpectedly exists")
|
||||
}
|
||||
}
|
||||
|
||||
func TestManualInterventionUsesStableBlockedDTO(t *testing.T) {
|
||||
job := Job{ID: "abcdefghijklmnopqrstuvwxyzABCDEF", Status: "manual_intervention",
|
||||
Checkpoint: "schema_init_started", PreviousCommit: testCurrent, AppliedCommit: testRemote,
|
||||
ErrorCode: "schema_init_result_uncertain"}
|
||||
result := publicJob(job)
|
||||
if result.Status != "blocked" || result.Phase != "schema_init_started" ||
|
||||
result.RollbackRef != testCurrent || result.NewCommit != testRemote || result.Error == "" {
|
||||
t.Fatalf("unexpected blocked DTO: %#v", result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenStateRejectsDataPastSizeLimit(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "state.json")
|
||||
raw := []byte(`{"version":1,"maintenance_lock":false,"jobs":{},"nonces":{}}` +
|
||||
strings.Repeat(" ", maxStateBytes))
|
||||
if err := os.WriteFile(path, raw, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := OpenState(path); err == nil || !strings.Contains(err.Error(), "exceeds") {
|
||||
t.Fatalf("oversized update state error = %v", err)
|
||||
}
|
||||
}
|
||||
Binary file not shown.
@ -1,140 +0,0 @@
|
||||
<?php
|
||||
namespace App\Controllers;
|
||||
|
||||
use App\Services\Cloud\CloudAccess;
|
||||
use App\Services\Cloud\CloudError;
|
||||
use App\Services\Cloud\CloudInput;
|
||||
use App\Services\Cloud\CloudOperationErrorCatalog;
|
||||
use App\Services\Cloud\CloudUpdateHelperClient;
|
||||
|
||||
/** Super-admin-only proxy for the root-owned local update helper. */
|
||||
final class AdminUpdateController
|
||||
{
|
||||
private function actor($request): array
|
||||
{
|
||||
$actor = $request->getAttribute('cloud_actor') ?? CloudAccess::actor();
|
||||
CloudAccess::manage($actor);
|
||||
return $actor;
|
||||
}
|
||||
|
||||
private function helper(): CloudUpdateHelperClient
|
||||
{
|
||||
return new CloudUpdateHelperClient();
|
||||
}
|
||||
|
||||
private function credentialTransportIsSecure($request): bool
|
||||
{
|
||||
if (strtolower((string) $request->getUri()->getScheme()) === 'https') {
|
||||
return true;
|
||||
}
|
||||
// Permit a direct loopback request for local setup and tests. Do not
|
||||
// trust forwarding headers here: proxy scheme handling belongs in the
|
||||
// web server / PSR-7 request construction boundary.
|
||||
$host = strtolower(rtrim((string) $request->getUri()->getHost(), '.'));
|
||||
return in_array((string) $request->getServerParam('REMOTE_ADDR', ''), ['127.0.0.1', '::1'], true)
|
||||
&& in_array($host, ['localhost', '127.0.0.1', '::1'], true);
|
||||
}
|
||||
|
||||
private function json($response, array $result, int $status = 200)
|
||||
{
|
||||
return $response->withJson($this->withoutAccessToken($result), $status)
|
||||
->withHeader('Cache-Control', 'no-store');
|
||||
}
|
||||
|
||||
/** Defence in depth: a secret is never returned if the helper regresses. */
|
||||
private function withoutAccessToken(array $value): array
|
||||
{
|
||||
foreach ($value as $key => $item) {
|
||||
$name = strtolower((string) $key);
|
||||
if (in_array($name, ['access_token', 'gitea_access_token'], true)) {
|
||||
unset($value[$key]);
|
||||
} elseif (CloudOperationErrorCatalog::isDiagnosticKey($name)) {
|
||||
// Do not recursively pass arbitrary validation/error maps
|
||||
// through: a nested non-diagnostic key can still carry a
|
||||
// host path, command, URL, or credential. The updater UI only
|
||||
// needs one bounded diagnostic sentence, so discard complex
|
||||
// diagnostic payloads and retain a scalar redacted summary.
|
||||
if (!is_scalar($item)) {
|
||||
unset($value[$key]);
|
||||
continue;
|
||||
}
|
||||
$summary = CloudOperationErrorCatalog::adminSummary(null, null, $item);
|
||||
if ($summary === null) {
|
||||
unset($value[$key]);
|
||||
} else {
|
||||
$value[$key] = $summary;
|
||||
}
|
||||
} elseif (is_array($item)) {
|
||||
$value[$key] = $this->withoutAccessToken($item);
|
||||
}
|
||||
}
|
||||
return $value;
|
||||
}
|
||||
|
||||
public function settings($request, $response)
|
||||
{
|
||||
$actor = $this->actor($request);
|
||||
if ($request->getMethod() === 'GET') {
|
||||
return $this->json($response, $this->helper()->request(
|
||||
'GET', '/v1/settings', $actor
|
||||
));
|
||||
}
|
||||
|
||||
$body = CloudInput::object($request, 8192);
|
||||
CloudInput::only($body, ['access_token', 'clear_token']);
|
||||
if (array_key_exists('access_token', $body) && !is_string($body['access_token'])) {
|
||||
throw new CloudError('访问令牌格式无效');
|
||||
}
|
||||
if (array_key_exists('clear_token', $body) && !is_bool($body['clear_token'])) {
|
||||
throw new CloudError('清除令牌选项无效');
|
||||
}
|
||||
if (($body['clear_token'] ?? false) === true && ($body['access_token'] ?? '') !== '') {
|
||||
throw new CloudError('不能同时设置并清除访问令牌');
|
||||
}
|
||||
if (($body['access_token'] ?? '') !== '' && !$this->credentialTransportIsSecure($request)) {
|
||||
throw new CloudError('访问令牌只能通过 HTTPS 或本机回环地址提交', 403);
|
||||
}
|
||||
|
||||
return $this->json($response, $this->helper()->request(
|
||||
'PUT', '/v1/settings', $actor, $body
|
||||
));
|
||||
}
|
||||
|
||||
public function check($request, $response)
|
||||
{
|
||||
$actor = $this->actor($request);
|
||||
$body = CloudInput::object($request, 1024);
|
||||
CloudInput::only($body, []);
|
||||
return $this->json($response, $this->helper()->request(
|
||||
'POST', '/v1/check', $actor, $body
|
||||
));
|
||||
}
|
||||
|
||||
public function apply($request, $response)
|
||||
{
|
||||
$actor = $this->actor($request);
|
||||
$body = CloudInput::object($request, 4096);
|
||||
CloudInput::only($body, ['expected_current_commit', 'expected_remote_commit']);
|
||||
foreach (['expected_current_commit', 'expected_remote_commit'] as $field) {
|
||||
if (!isset($body[$field]) || !is_string($body[$field])
|
||||
|| preg_match('/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/D', $body[$field]) !== 1) {
|
||||
throw new CloudError('更新提交标识无效');
|
||||
}
|
||||
}
|
||||
return $this->json($response, $this->helper()->request(
|
||||
'POST', '/v1/apply', $actor, $body
|
||||
), 202);
|
||||
}
|
||||
|
||||
public function job($request, $response, $args)
|
||||
{
|
||||
$actor = $this->actor($request);
|
||||
$jobId = (string) ($args['id'] ?? '');
|
||||
if (preg_match('/^[A-Za-z0-9_-]{16,64}$/D', $jobId) !== 1) {
|
||||
throw new CloudError('更新任务编号无效', 404);
|
||||
}
|
||||
return $this->json($response, $this->helper()->request(
|
||||
'GET', '/v1/jobs/' . rawurlencode($jobId), $actor
|
||||
));
|
||||
}
|
||||
}
|
||||
@ -1,114 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Cloud;
|
||||
|
||||
use App\Services\Config;
|
||||
use GuzzleHttp\Client;
|
||||
|
||||
/** Authenticated PHP client for the root-owned local update helper. */
|
||||
final class CloudUpdateHelperClient
|
||||
{
|
||||
private const SOCKET_PATH = '/run/virt-cloud/update.sock';
|
||||
private const BASE_URI = 'http://localhost';
|
||||
|
||||
private Client $client;
|
||||
private string $secret;
|
||||
|
||||
public function __construct(?Client $client = null, ?string $secret = null)
|
||||
{
|
||||
$this->secret = $secret ?? (string) Config::get(
|
||||
'cloud_update_helper_secret',
|
||||
''
|
||||
);
|
||||
if (strlen($this->secret) < 32
|
||||
|| str_contains($this->secret, "\0")
|
||||
|| str_contains($this->secret, "\r")
|
||||
|| str_contains($this->secret, "\n")) {
|
||||
throw new CloudError('本机更新助手密钥尚未正确配置', 503);
|
||||
}
|
||||
if ($client !== null) {
|
||||
$this->client = $client;
|
||||
return;
|
||||
}
|
||||
if (!defined('CURLOPT_UNIX_SOCKET_PATH')) {
|
||||
throw new CloudError('PHP cURL 不支持本机 Unix Socket 更新助手', 503);
|
||||
}
|
||||
$this->client = new Client([
|
||||
'base_uri' => self::BASE_URI,
|
||||
'connect_timeout' => 3,
|
||||
'timeout' => 95,
|
||||
'http_errors' => false,
|
||||
'allow_redirects' => false,
|
||||
]);
|
||||
}
|
||||
|
||||
public function request(
|
||||
string $method,
|
||||
string $target,
|
||||
array $actor,
|
||||
?array $payload = null
|
||||
): array {
|
||||
if (!preg_match('#^/v1(?:/[A-Za-z0-9_-]+)*$#D', $target)) {
|
||||
throw new \InvalidArgumentException('Invalid update-helper target');
|
||||
}
|
||||
$body = $payload === null ? '' : json_encode(
|
||||
$payload === [] ? (object) [] : $payload,
|
||||
JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES
|
||||
| JSON_UNESCAPED_UNICODE
|
||||
);
|
||||
$options = [
|
||||
'headers' => CloudAgentClient::headers(
|
||||
$method,
|
||||
$target,
|
||||
$body,
|
||||
$actor,
|
||||
$this->secret
|
||||
),
|
||||
'body' => $body,
|
||||
'allow_redirects' => false,
|
||||
'http_errors' => false,
|
||||
'proxy' => '',
|
||||
'timeout' => 95,
|
||||
];
|
||||
if (defined('CURLOPT_UNIX_SOCKET_PATH')) {
|
||||
$options['curl'] = [constant('CURLOPT_UNIX_SOCKET_PATH') => self::SOCKET_PATH];
|
||||
}
|
||||
try {
|
||||
$response = $this->client->request(
|
||||
strtoupper($method),
|
||||
self::BASE_URI . $target,
|
||||
$options
|
||||
);
|
||||
} catch (\Throwable $error) {
|
||||
throw new CloudError('本机更新助手不可用,请通过 SSH 检查服务状态', 503);
|
||||
}
|
||||
$status = $response->getStatusCode();
|
||||
$raw = (string) $response->getBody();
|
||||
if (strlen($raw) > 262144) {
|
||||
throw new CloudError('本机更新助手响应过大', 502);
|
||||
}
|
||||
$result = json_decode($raw, true);
|
||||
if (!is_array($result) || ($result !== [] && array_is_list($result))) {
|
||||
throw new CloudError('本机更新助手返回了无效响应', 502);
|
||||
}
|
||||
if ($status < 200 || $status >= 300) {
|
||||
$code = is_string($result['error']['code'] ?? null)
|
||||
? $result['error']['code'] : '';
|
||||
$message = match ($status) {
|
||||
401 => '本机更新助手身份验证失败',
|
||||
403 => '只有超级管理员可以执行在线更新',
|
||||
404 => '更新任务不存在',
|
||||
409 => '更新前置条件不满足或状态需要人工核对',
|
||||
422 => '更新请求参数无效',
|
||||
503 => '本机更新助手状态不可用',
|
||||
default => '在线更新请求未成功',
|
||||
};
|
||||
if ($code === 'update_precondition_failed') {
|
||||
$message = '代码、服务或依赖状态不满足安全更新条件';
|
||||
}
|
||||
throw new CloudError($message, in_array($status,
|
||||
[403, 404, 409, 422, 503], true) ? $status : 502);
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
@ -1,94 +0,0 @@
|
||||
{assign var=admin_title value='在线更新'}
|
||||
{assign var=admin_active value='update'}
|
||||
{include file='admin/static_header.tpl'}
|
||||
|
||||
<link rel="stylesheet" href="/cloud/admin.css?v={$venix_asset_version}">
|
||||
<section class="cloud-admin cloud-update" aria-labelledby="update-page-title">
|
||||
<div class="py-3 d-flex align-items-sm-center flex-sm-row flex-column cloud-admin-page-head">
|
||||
<div class="flex-grow-1">
|
||||
<p class="admin-eyebrow mb-1">System</p>
|
||||
<h4 id="update-page-title" class="fs-20 fw-semibold mb-1">在线更新</h4>
|
||||
<p class="text-muted mb-0">安全检查固定私有仓库与分支,并执行受约束的快进更新。</p>
|
||||
</div>
|
||||
<div class="text-sm-end mt-3 mt-sm-0 cloud-admin-actions">
|
||||
<p id="update-page-status" class="alert alert-info cloud-admin-notice" role="status" aria-live="polite">正在读取更新配置…</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="alert alert-warning cloud-admin-guidance" role="note">
|
||||
<i class="mdi mdi-alert-outline"></i>
|
||||
<span>在线更新不会安装 Composer 或 Go 依赖,也不会改写 systemd unit。若目标版本修改 <code>web/composer.json</code>、锁文件、Go module 文件或 <code>deploy/**</code>,系统会在停服前拒绝,请改用 SSH 升级。</span>
|
||||
</div>
|
||||
|
||||
<div class="cloud-admin-grid cloud-update-grid">
|
||||
<form id="update-settings-form" class="card cloud-update-card" autocomplete="off">
|
||||
<div class="card-body">
|
||||
<div class="cloud-admin-card-head">
|
||||
<div>
|
||||
<p class="admin-eyebrow mb-1">Repository</p>
|
||||
<h5 class="mb-1">更新源与凭据</h5>
|
||||
<p class="text-muted mb-0">仓库与分支由服务器固定,网页只维护访问令牌。</p>
|
||||
</div>
|
||||
<span class="cloud-admin-card-icon"><i class="mdi mdi-source-branch"></i></span>
|
||||
</div>
|
||||
<dl class="cloud-update-details">
|
||||
<div><dt>固定仓库</dt><dd id="update-repository">正在读取…</dd></div>
|
||||
<div><dt>固定分支</dt><dd id="update-branch">正在读取…</dd></div>
|
||||
<div><dt>当前提交</dt><dd id="update-current-commit">正在读取…</dd></div>
|
||||
<div><dt>检出状态</dt><dd id="update-checkout-state">正在读取…</dd></div>
|
||||
</dl>
|
||||
<div class="cloud-update-credential">
|
||||
<label for="update-access-token" class="form-label">Gitea 私有仓库访问令牌</label>
|
||||
<input id="update-access-token" class="form-control admin-mono" type="password" maxlength="4096" autocomplete="new-password" spellcheck="false" placeholder="留空即保留现有令牌">
|
||||
<div class="form-text">令牌只在保存请求中发送,不会回显或保存在浏览器中。</div>
|
||||
<label class="form-check mt-3 mb-0" for="update-clear-token"><input id="update-clear-token" class="form-check-input" type="checkbox"><span class="form-check-label">明确清除已保存的访问令牌</span></label>
|
||||
</div>
|
||||
<div class="cloud-admin-form-actions"><button id="update-settings-save" class="btn btn-primary" type="submit"><i class="mdi mdi-content-save-outline me-1"></i>保存令牌设置</button></div>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<div class="card cloud-update-card">
|
||||
<div class="card-body">
|
||||
<div class="cloud-admin-card-head">
|
||||
<div>
|
||||
<p class="admin-eyebrow mb-1">Deploy</p>
|
||||
<h5 class="mb-1">检查并执行</h5>
|
||||
<p class="text-muted mb-0">每次执行前都必须重新检查并锁定本地与远端提交。</p>
|
||||
</div>
|
||||
<span class="cloud-admin-card-icon is-warning"><i class="mdi mdi-update"></i></span>
|
||||
</div>
|
||||
<dl class="cloud-update-details">
|
||||
<div><dt>检查状态</dt><dd id="update-check-status">尚未检查</dd></div>
|
||||
<div><dt>已锁定本地提交</dt><dd id="update-checked-current">—</dd></div>
|
||||
<div><dt>已锁定远端提交</dt><dd id="update-checked-remote">—</dd></div>
|
||||
</dl>
|
||||
<div class="cloud-update-actions">
|
||||
<button id="update-check" class="btn btn-outline-primary" type="button"><i class="mdi mdi-source-branch-check me-1"></i>检查更新</button>
|
||||
<button id="update-apply" class="btn btn-danger" type="button" disabled><i class="mdi mdi-update me-1"></i>执行在线更新</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card mt-3 cloud-update-job-card">
|
||||
<div class="card-body">
|
||||
<div class="cloud-admin-card-head">
|
||||
<div>
|
||||
<p class="admin-eyebrow mb-1">Progress</p>
|
||||
<h5 class="mb-1">更新任务</h5>
|
||||
<p class="text-muted mb-0">PHP 与私有引擎重启期间会自动只读恢复任务,请保留本页面且不要重复提交。</p>
|
||||
</div>
|
||||
<span class="cloud-admin-card-icon"><i class="mdi mdi-timeline-clock-outline"></i></span>
|
||||
</div>
|
||||
<dl class="cloud-update-details cloud-update-job-details">
|
||||
<div><dt>任务编号</dt><dd id="update-job-id">—</dd></div>
|
||||
<div><dt>任务状态</dt><dd id="update-job-status">—</dd></div>
|
||||
<div><dt>当前阶段</dt><dd id="update-job-phase">—</dd></div>
|
||||
<div><dt>结果</dt><dd id="update-job-result">—</dd></div>
|
||||
</dl>
|
||||
<p class="cloud-update-warning mb-0"><i class="mdi mdi-lock-alert-outline"></i><span>若任务进入 <code>blocked</code>,维护锁会保持启用。全新数据库结构校验中断时仅回退源码不会解除维护锁,必须通过 SSH 完成核对并验证服务后再协调状态。</span></p>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
<script type="module" src="/cloud/update.js?v={$venix_asset_version}"></script>
|
||||
{include file='admin/static_footer.tpl'}
|
||||
@ -1,147 +0,0 @@
|
||||
<?php
|
||||
|
||||
// Static contract test: exercising the proxy itself would require a live,
|
||||
// HMAC-authenticated local update helper. These assertions keep the browser/PHP
|
||||
// security boundary reviewable without application boot or network access.
|
||||
$root = dirname(__DIR__);
|
||||
$read = static function (string $relative) use ($root): string {
|
||||
$contents = file_get_contents($root . '/' . $relative);
|
||||
if ($contents === false) {
|
||||
throw new RuntimeException('Cannot read ' . $relative);
|
||||
}
|
||||
return $contents;
|
||||
};
|
||||
$assert = static function ($condition, string $message): void {
|
||||
if (!$condition) {
|
||||
throw new RuntimeException($message);
|
||||
}
|
||||
};
|
||||
|
||||
$routes = $read('config/routes.php');
|
||||
$apiRoutes = $read('config/routes_cloud.php');
|
||||
$controller = $read('app/Controllers/AdminUpdateController.php');
|
||||
$helperClient = $read('app/Services/Cloud/CloudUpdateHelperClient.php');
|
||||
$header = $read('resources/views/venix/admin/static_header.tpl');
|
||||
$template = $read('resources/views/venix/admin/update.tpl');
|
||||
$script = $read('public/cloud/update.js');
|
||||
|
||||
$assert(str_contains(
|
||||
$routes,
|
||||
"\$this->get('/update', 'App\\Controllers\\Admin\\CloudPageController:update')->add(new SuperAdmin());"
|
||||
), 'The update page is not protected by the SuperAdmin middleware.');
|
||||
$assert(str_contains($header, "{if \$admin_can_manage|default:false}<li><a")
|
||||
&& str_contains($header, 'href="/admin/update"'),
|
||||
'The Venix update navigation is not limited by admin_can_manage.');
|
||||
|
||||
foreach ([
|
||||
"['GET', 'PUT'], '/admin/update/settings'",
|
||||
"post('/admin/update/check'",
|
||||
"post('/admin/update/apply'",
|
||||
"get('/admin/update/jobs/{id:[A-Za-z0-9_-]{16,64}}'",
|
||||
] as $routeContract) {
|
||||
$assert(str_contains($apiRoutes, $routeContract), 'Missing update API route: ' . $routeContract);
|
||||
}
|
||||
$assert(substr_count($controller, '$actor = $this->actor($request);') === 4,
|
||||
'Every update controller action must resolve the managed actor.');
|
||||
$assert(str_contains($controller, 'CloudAccess::manage($actor);'),
|
||||
'Update API actions do not force CloudAccess::manage.');
|
||||
$assert(str_contains($controller, "'GET', '/v1/settings'")
|
||||
&& str_contains($controller, "'POST', '/v1/check'")
|
||||
&& str_contains($controller, "'POST', '/v1/apply'")
|
||||
&& str_contains($controller, "'GET', '/v1/jobs/' . rawurlencode(\$jobId)"),
|
||||
'The PHP proxy does not use fixed local-helper update paths.');
|
||||
$assert(str_contains($controller, "CloudInput::only(\$body, ['access_token', 'clear_token']);")
|
||||
&& str_contains($controller, "['expected_current_commit', 'expected_remote_commit']"),
|
||||
'The update proxy request allowlists changed.');
|
||||
$assert(str_contains($controller, 'new CloudUpdateHelperClient()')
|
||||
&& str_contains($controller, '), 202);'),
|
||||
'Update requests must use the local helper and apply must return HTTP 202.');
|
||||
$assert(str_contains($controller, "['access_token', 'gitea_access_token']")
|
||||
&& str_contains($controller, "withHeader('Cache-Control', 'no-store')"),
|
||||
'Update responses are not defensively stripped/no-store.');
|
||||
$assert(str_contains($controller, "getUri()->getScheme()) === 'https'")
|
||||
&& str_contains($controller, "getServerParam('REMOTE_ADDR', '')")
|
||||
&& str_contains($controller, "getUri()->getHost()")
|
||||
&& str_contains($controller, "['localhost', '127.0.0.1', '::1']")
|
||||
&& str_contains($controller, "['127.0.0.1', '::1']")
|
||||
&& !str_contains($controller, 'X-Forwarded-Proto'),
|
||||
'The PHP proxy may accept a repository token over an untrusted transport.');
|
||||
|
||||
$assert(str_contains($helperClient, "private const SOCKET_PATH = '/run/virt-cloud/update.sock'")
|
||||
&& str_contains($helperClient, 'CURLOPT_UNIX_SOCKET_PATH')
|
||||
&& str_contains($helperClient, 'CloudAgentClient::headers(')
|
||||
&& str_contains($helperClient, "'allow_redirects' => false")
|
||||
&& !str_contains($helperClient, 'CloudEngineClient'),
|
||||
'The updater must use only the authenticated fixed Unix socket.');
|
||||
|
||||
$assert(str_contains($template, 'id="update-repository"')
|
||||
&& str_contains($template, 'id="update-branch"')
|
||||
&& !str_contains($template, 'https://g.luoli.live/root/virt.git'),
|
||||
'The fixed repository and branch must be rendered from the API response.');
|
||||
$assert(preg_match('/<input id="update-access-token"[^>]*type="password"[^>]*>/s', $template, $tokenInput) === 1
|
||||
&& !str_contains($tokenInput[0], ' value='),
|
||||
'The access token field must be an empty password input.');
|
||||
$assert(str_contains($template, 'id="update-clear-token"')
|
||||
&& str_contains($template, '/cloud/update.js?v={$venix_asset_version}')
|
||||
&& !str_contains($template, '/cloud/admin.js'),
|
||||
'The page needs explicit token clearing and its independent update script.');
|
||||
$assert(str_contains($template, 'web/composer.json')
|
||||
&& str_contains($template, 'Go module')
|
||||
&& str_contains($template, 'deploy/**')
|
||||
&& str_contains($template, '不会安装 Composer 或 Go 依赖')
|
||||
&& str_contains($template, '不会改写 systemd unit')
|
||||
&& !str_contains($template, 'Python'),
|
||||
'The page must describe the code-only update boundary and all rejected paths.');
|
||||
$assert(str_contains($template, '<code>blocked</code>')
|
||||
&& str_contains($template, '维护锁会保持启用')
|
||||
&& str_contains($template, '仅回退源码不会解除维护锁')
|
||||
&& str_contains($template, '必须通过 SSH 完成核对并验证服务后再协调状态'),
|
||||
'Blocked updates must direct the operator to SSH recovery without unlocking mutations.');
|
||||
|
||||
foreach (['innerHTML', 'insertAdjacentHTML', 'localStorage', 'sessionStorage', 'document.cookie'] as $unsafeBrowserApi) {
|
||||
$assert(!str_contains($script, $unsafeBrowserApi),
|
||||
'Update UI must not use unsafe rendering or durable browser storage: ' . $unsafeBrowserApi);
|
||||
}
|
||||
$assert(str_contains($script, '.textContent =')
|
||||
&& str_contains($script, "headers['X-Admin-CSRF-Token'] = csrfToken")
|
||||
&& str_contains($script, "credentials: 'same-origin'"),
|
||||
'Safe rendering, CSRF, or same-origin credentials are missing.');
|
||||
$assert(str_contains($script, "const body = clearToken ? { clear_token: true } : { access_token: token };")
|
||||
&& str_contains($script, "tokenInput.value = ''"),
|
||||
'Blank-token preservation, explicit clearing, or credential cleanup changed.');
|
||||
$assert(str_contains($script, "window.location.protocol === 'https:'")
|
||||
&& str_contains($script, "['localhost', '127.0.0.1', '::1', '[::1]']"),
|
||||
'The browser may send a repository token over an insecure transport.');
|
||||
$assert(str_contains($script, 'state.checkedCommits = Object.freeze({')
|
||||
&& str_contains($script, 'expected_current_commit: result.current_commit')
|
||||
&& str_contains($script, 'expected_remote_commit: result.remote_commit')
|
||||
&& str_contains($script, "state.updateAvailable = result.status === 'update_available'")
|
||||
&& str_contains($script, 'state.checkedCommits === null || !state.updateAvailable')
|
||||
&& str_contains($script, 'state.maintenanceBlocked || !state.updateAvailable'),
|
||||
'Check results do not pin both commits for apply.');
|
||||
$assert(str_contains($script, 'settings.token_configured === true && settings.checkout_ready === true')
|
||||
&& str_contains($script, 'window.confirm(')
|
||||
&& str_contains($script, '仅快进应用代码')
|
||||
&& str_contains($script, '不会安装 Composer 或 Go 依赖,也不会修改 systemd 配置')
|
||||
&& str_contains($script, '依赖或部署文件变更必须通过 SSH 升级')
|
||||
&& str_contains($script, '执行全新数据库结构校验'),
|
||||
'Update readiness or the destructive-impact confirmation changed.');
|
||||
$assert(substr_count($script, "api('/apply', { method: 'POST', body: pinned })") === 1
|
||||
&& str_contains($script, "api(`/jobs/\${encodeURIComponent(jobId)}`, { method: 'GET' })")
|
||||
&& str_contains($script, 'transientFailures > 30')
|
||||
&& str_contains($script, 'recoverJobAfterApply')
|
||||
&& str_contains($script, '正在只读恢复任务')
|
||||
&& str_contains($script, 'job.rollback_ref')
|
||||
&& str_contains($script, '人工恢复回滚引用')
|
||||
&& str_contains($script, '请勿重复提交'),
|
||||
'Apply must be single-shot while job polling survives service restarts.');
|
||||
$assert(str_contains($script, "new Set(['succeeded', 'failed', 'blocked'])")
|
||||
&& str_contains($script, 'state.maintenanceBlocked = true')
|
||||
&& str_contains($script, "job.status === 'blocked'")
|
||||
&& str_contains($script, '代码或数据库状态尚未确认')
|
||||
&& str_contains($script, '若任务在全新数据库结构校验期间中断')
|
||||
&& str_contains($script, '仅回退源码不会解除维护锁')
|
||||
&& str_contains($script, 'busy || state.maintenanceBlocked'),
|
||||
'Blocked is a polling terminal state but must keep every mutation control locked.');
|
||||
|
||||
echo "Admin online-update page, proxy, and browser contracts passed.\n";
|
||||
@ -1,86 +0,0 @@
|
||||
<?php
|
||||
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
|
||||
use App\Services\Cloud\CloudError;
|
||||
use App\Services\Cloud\CloudUpdateHelperClient;
|
||||
use GuzzleHttp\Client;
|
||||
use GuzzleHttp\Handler\MockHandler;
|
||||
use GuzzleHttp\HandlerStack;
|
||||
use GuzzleHttp\Middleware;
|
||||
use GuzzleHttp\Psr7\Response;
|
||||
|
||||
$assert = static function (bool $condition, string $message): void {
|
||||
if (!$condition) {
|
||||
throw new RuntimeException($message);
|
||||
}
|
||||
};
|
||||
|
||||
$history = [];
|
||||
$mock = new MockHandler([
|
||||
new Response(200, ['Content-Type' => 'application/json'], json_encode([
|
||||
'repository' => 'https://g.luoli.live/root/virt.git',
|
||||
'branch' => 'go',
|
||||
'checkout_ready' => true,
|
||||
'token_configured' => false,
|
||||
'maintenance_lock' => false,
|
||||
], JSON_THROW_ON_ERROR)),
|
||||
new Response(409, ['Content-Type' => 'application/json'], json_encode([
|
||||
'error' => ['code' => 'update_precondition_failed'],
|
||||
], JSON_THROW_ON_ERROR)),
|
||||
]);
|
||||
$stack = HandlerStack::create($mock);
|
||||
$stack->push(Middleware::history($history));
|
||||
$secret = 'update-helper-test-secret-at-least-32-bytes';
|
||||
$client = new CloudUpdateHelperClient(
|
||||
new Client(['handler' => $stack]),
|
||||
$secret
|
||||
);
|
||||
$actor = [
|
||||
'user_id' => 7,
|
||||
'is_admin' => true,
|
||||
'is_super_admin' => true,
|
||||
'can_manage' => true,
|
||||
'session_id' => 'must-not-cross-the-local-helper-boundary',
|
||||
];
|
||||
$settings = $client->request('GET', '/v1/settings', $actor);
|
||||
$assert(($settings['branch'] ?? null) === 'go' && count($history) === 1,
|
||||
'Update helper settings response did not round-trip.');
|
||||
$request = $history[0]['request'];
|
||||
$assert((string) $request->getUri() === 'http://localhost/v1/settings'
|
||||
&& $request->getHeaderLine('X-Virt-Content-SHA256') === hash('sha256', '')
|
||||
&& preg_match('/^[a-f0-9]{64}$/D',
|
||||
$request->getHeaderLine('X-Virt-Signature')) === 1
|
||||
&& $request->getHeaderLine('X-Virt-Actor') !== ''
|
||||
&& $request->getHeaderLine('X-Cloud-Signature') === '',
|
||||
'Update helper request did not use the fixed signed X-Virt contract.');
|
||||
$encoded = $request->getHeaderLine('X-Virt-Actor');
|
||||
$raw = base64_decode(strtr($encoded, '-_', '+/')
|
||||
. str_repeat('=', (4 - strlen($encoded) % 4) % 4), true);
|
||||
$forwardedActor = json_decode((string) $raw, true, 8, JSON_THROW_ON_ERROR);
|
||||
$assert(!array_key_exists('session_id', $forwardedActor)
|
||||
&& ($forwardedActor['is_super_admin'] ?? false) === true,
|
||||
'Panel session data crossed into the privileged update helper.');
|
||||
|
||||
try {
|
||||
$client->request('POST', '/v1/apply', $actor, [
|
||||
'expected_current_commit' => str_repeat('a', 40),
|
||||
'expected_remote_commit' => str_repeat('b', 40),
|
||||
]);
|
||||
throw new RuntimeException('Unsafe update precondition was accepted.');
|
||||
} catch (CloudError $error) {
|
||||
$assert($error->httpStatus === 409
|
||||
&& !str_contains($error->getMessage(), 'update_precondition_failed'),
|
||||
'Update helper error was not safely mapped.');
|
||||
}
|
||||
|
||||
foreach (['/internal/v1/update', '/v1/jobs/../settings', '/v1/check?x=1'] as $unsafe) {
|
||||
try {
|
||||
$client->request('GET', $unsafe, $actor);
|
||||
throw new RuntimeException('Unsafe helper target accepted: ' . $unsafe);
|
||||
} catch (InvalidArgumentException $expected) {
|
||||
// Expected before transport.
|
||||
}
|
||||
}
|
||||
|
||||
echo "Authenticated fixed Unix-socket update helper client contract passed.\n";
|
||||
Loading…
Reference in New Issue