Merge pull request #346 from Sycun/feat/self-update

feat: one-click update with a configurable source, restart, and self-recovery
This commit is contained in:
公明 2026-10-09 14:02:03 +08:00 committed by GitHub
commit 72cd8d62e3
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
73 changed files with 11473 additions and 157 deletions

33
.github/workflows/self-update.yml vendored Normal file
View File

@ -0,0 +1,33 @@
name: Self-update
on:
push:
paths: ['internal/update/**', 'internal/workflow/**', 'internal/config/**', 'internal/handler/**', 'internal/mcp/**', 'cmd/server/**', 'web/static/js/**', 'web/static/css/style.css', 'web/templates/index.html', 'upgrade.sh', 'run.sh', 'go.mod', 'go.sum', '.gitignore', '.github/workflows/self-update.yml']
pull_request:
paths: ['internal/update/**', 'internal/workflow/**', 'internal/config/**', 'internal/handler/**', 'internal/mcp/**', 'cmd/server/**', 'web/static/js/**', 'web/static/css/style.css', 'web/templates/index.html', 'upgrade.sh', 'run.sh', 'go.mod', 'go.sum', '.gitignore', '.github/workflows/self-update.yml']
permissions:
contents: read
jobs:
update:
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, macos-latest, windows-latest]
runs-on: ${{ matrix.os }}
steps:
- name: Keep source line endings consistent
run: git config --global core.autocrlf false
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version-file: go.mod
- uses: actions/setup-node@v4
with:
node-version: '22'
- run: go test -race ./internal/update ./internal/config ./internal/handler ./cmd/server ./internal/workflow
- run: go build ./...
- name: Frontend regression tests
shell: bash
run: node --test web/static/js/*.test.cjs
- name: Shell syntax
shell: bash
run: bash -n run.sh upgrade.sh

12
.gitignore vendored
View File

@ -39,6 +39,18 @@ target/
coverage.out
coverage.html
# One-click update artifacts (internal/update): machine-local, written at the install root
.update-lock
.update-rollback-pending.json
.update-rollback-pending.json.tmp
.update-staging/
.update-backup/
.update-state.json
.update-state.json.tmp
.update-build-pending
.update-build-pending.tmp
cyberstrike-ai.prev
# Logs and temporary files
/log/
*.log

View File

@ -256,10 +256,10 @@ The `run.sh` script will automatically:
**Alternative Launch Methods:**
```bash
# Direct Go run (set up env yourself); add --https to match run.sh defaults
go run cmd/server/main.go --https
go run ./cmd/server --https
# Manual build
go build -o cyberstrike-ai cmd/server/main.go
go build -o cyberstrike-ai ./cmd/server
./cyberstrike-ai --https
```
@ -269,17 +269,38 @@ If server logs show `client sent an HTTP request to an HTTPS server`, a client i
### Upgrade and Compatibility
**CyberStrikeAI one-click upgrade:**
**Prefer the platform's own one-click update** (console System settings -> One-click update, or
`./cyberstrike-ai -update` / `-check-update` / `-update-rollback`): it pulls the newest commit of the
**update source repository**'s default branch (the official repository by default; one setting points
it at your own fork or a mirror), fast-forwards, rebuilds and swaps the binary atomically, keeps your
`roles/skills/tools/agents/data/config.yaml` untouched (the result names every file it kept; only
`config.yaml`'s `version` field is synced to the new code, so the header badge matches it), and
refuses - rather than overwrites - when source is modified locally or the local history has diverged.
See the [deployment guide](docs/en-US/deployment.md).
`upgrade.sh` still works: when this directory is a git work tree it is a thin shell over the command
above; only a non-git (tarball) installation falls back to the old "download a GitHub Release and
rsync it in" path, where the source repository comes from `--repo owner/name` or `GITHUB_REPO` and the
built-in default applies only when neither is given (with a warning naming the repository).
The update source is one setting, a repository address in the `update` section of `config.yaml` or
right on the console page - the official repository, your own fork, or somebody else's fork. An
installation unpacked from a Release archive (no git) can be previewed and connected from the same
page and updates in one click from then on.
**CyberStrikeAI upgrade script:**
1. (First time) enable the script: `chmod +x upgrade.sh`
2. Upgrade with: `./upgrade.sh` (optional flags: `--tag vX.Y.Z`, `--no-venv`, `--yes`). Local `tools/`, `roles/`, and `skills/` are always preserved.
3. The script will back up your `config.yaml` and `data/`, upgrade the code from GitHub Release, update `config.yaml`'s `version`, then restart the server.
2. Upgrade with: `./upgrade.sh` (optional flags: `--check`, `--tag vX.Y.Z`, `--repo owner/name`, `--no-venv`, `--yes`). Local `tools/`, `roles/`, `skills/` and `agents/` are always preserved.
3. The script will back up your `config.yaml` and `data/`, upgrade the code, update `config.yaml`'s `version`, then restart the server.
Recommended one-liner:
`chmod +x upgrade.sh && ./upgrade.sh --yes`
If something goes wrong, you can restore from `.upgrade-backup/` (or manually copy `/data` and `config.yaml` back) and run `./run.sh` again.
If something goes wrong: inside a git work tree just run `./cyberstrike-ai -update-rollback` (back to
the commit and binary kept before that update); for a tarball installation restore from
`.upgrade-backup/` (or manually copy `data/` and `config.yaml` back) and run `./run.sh` again.
Requirements / tips:
Requirements / tips (tarball path only):
* You need `curl` or `wget` for downloading Release packages.
* `rsync` is recommended/required for the safe code sync.
* If GitHub API rate-limits you, set `export GITHUB_TOKEN="..."` before running `./upgrade.sh`.

View File

@ -255,10 +255,10 @@ chmod +x run.sh && ./run.sh
**其他启动方式:**
```bash
# 直接运行(需自行配环境);与 run.sh 默认一致可加 --https
go run cmd/server/main.go --https
go run ./cmd/server --https
# 手动编译
go build -o cyberstrike-ai cmd/server/main.go
go build -o cyberstrike-ai ./cmd/server
./cyberstrike-ai --https
```
@ -268,16 +268,32 @@ go build -o cyberstrike-ai cmd/server/main.go
### 版本升级与兼容性
**优先用平台自带的「一键更新」**(控制台「系统设置 → 一键更新」,或 `./cyberstrike-ai -update` /
`-check-update` / `-update-rollback`):它从**更新源仓库**(默认官方仓库,可一处配置改成自己的二开或镜像)
拉取默认分支的最新代码,快进后重编译并原子换二进制,你的 `roles/skills/tools/agents/data/config.yaml`
会被原样保留(结果里逐个点名保留了什么,只有 `config.yaml` 的 `version` 字段会随新代码同步,让页头版本号与代码对上),
本地源码有改动或本地历史与更新源分叉时它会拒绝而不是覆盖。
详见 [部署指南](docs/zh-CN/deployment.md)。
`upgrade.sh` 仍然可用:本目录是 git 工作树时它就是上面那条命令的薄壳;不是 git 工作树(tarball 安装)时
才回落到"下载 GitHub Release 包 + rsync"的老路径,此时源码仓库由 `--repo owner/name` 或 `GITHUB_REPO`
决定(都不给才用内置默认值,并会警告说明代码来自哪个仓库)。
更新源是 `config.yaml` `update` 段里的一个仓库地址(`repo`),也可以在控制台「一键更新」页填写保存
(跟随官方仓库、自己的二开、别人的二开或镜像都只是这一处;不写就是官方仓库);解压安装(目录里没有 git)
也能在同一页「预览并接入」后进入一键更新。
1. (首次使用)启用脚本:`chmod +x upgrade.sh`
2. 一键升级:`./upgrade.sh`(可选参数:`--tag vX.Y.Z`、`--no-venv`、`--yes`)。本地的 `tools/`、`roles/`、`skills/` 会始终保留不被覆盖。
3. 脚本会备份你的 `config.yaml` 和 `data/`,从 GitHub Release 升级代码,更新 `config.yaml` 的 `version` 字段后重启服务。
2. 升级:`./upgrade.sh`(可选参数:`--check`、`--tag vX.Y.Z`、`--repo owner/name`、`--no-venv`、`--yes`)。本地的 `tools/`、`roles/`、`skills/`、`agents/` 会始终保留不被覆盖。
3. 脚本会备份你的 `config.yaml` 和 `data/`,升级代码,更新 `config.yaml` 的 `version` 字段后重启服务。
推荐的一键指令:
`chmod +x upgrade.sh && ./upgrade.sh --yes`
如果升级失败,可以从 `.upgrade-backup/` 恢复,或按旧方式手动拷贝 `/data` 和 `config.yaml` 后再运行 `./run.sh`。
如果升级失败:git 工作树里直接 `./cyberstrike-ai -update-rollback`(回到那次更新前的提交与二进制);
tarball 安装则从 `.upgrade-backup/` 恢复,或手动拷回 `data/` 和 `config.yaml` 后再运行 `./run.sh`。
依赖/提示:
依赖/提示(只有 tarball 路径用得到):
* 需要 `curl` 或 `wget` 用于下载 GitHub Release 包。
* 建议/需要 `rsync` 用于安全同步代码。
* 如果遇到 GitHub API 限流,运行前设置 `export GITHUB_TOKEN="..."` 再执行 `./upgrade.sh`。

View File

@ -0,0 +1,223 @@
package main
import (
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"testing"
"gopkg.in/yaml.v3"
)
// Every `go build` in this repository's scripts has to target the cmd/server package.
// Building the single file cmd/server/main.go was tried once and broke the password reset
// entry: the file-based form silently leaves out sibling files of package main (it was
// update_cli.go that disappeared), and only `run.sh --reset-admin-password` used that
// build path, so nothing noticed until an operator needed it in an emergency. Compiling
// the package can never have that failure mode.
func TestScriptsBuildThePackageNotASingleFile(t *testing.T) {
root := filepath.Join("..", "..")
scripts := []string{filepath.Join(root, "run.sh"), filepath.Join(root, "upgrade.sh")}
more, err := filepath.Glob(filepath.Join(root, "scripts", "*.sh"))
if err != nil {
t.Fatal(err)
}
scripts = append(scripts, more...)
found := 0
for _, script := range scripts {
data, err := os.ReadFile(script)
if err != nil {
t.Fatalf("read %s: %v", script, err)
}
for _, line := range strings.Split(string(data), "\n") {
if !strings.Contains(line, "go build") {
continue
}
found++
if strings.Contains(line, ".go") {
t.Errorf("%s builds a single .go file; build ./cmd/server instead:\n %s",
script, strings.TrimSpace(line))
}
}
}
// A scan that finds no build command at all is looking in the wrong place, and a test
// that cannot see the thing it guards passes for the wrong reason.
if found == 0 {
t.Fatal("no `go build` command found in the scripts")
}
}
func TestUpgradeScriptUpdateConfigVersionPreservesDocumentAndMode(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("upgrade.sh requires a POSIX shell")
}
bash, err := exec.LookPath("bash")
if err != nil {
t.Skip("bash is not available")
}
if _, err := exec.LookPath("python3"); err != nil {
t.Skip("python3 is not available")
}
root := filepath.Join("..", "..")
scriptPath := filepath.Join(root, "upgrade.sh")
script, err := os.ReadFile(scriptPath)
if err != nil {
t.Fatalf("read %s: %v", scriptPath, err)
}
function := extractShellFunction(t, string(script), "update_config_version")
command := "umask 022\n" + function + "\nCONFIG_FILE=$1\nupdate_config_version \"$2\"\n"
for _, tc := range []struct {
name string
original string
wantDocumentStart bool
}{
{name: "document start", original: "---\nserver:\n port: 8088\n", wantDocumentStart: true},
{name: "commented document start", original: "# local settings\n---\nserver:\n port: 8088\n"},
{name: "directive document start", original: "%YAML 1.1\n---\nserver:\n port: 8088\n"},
{name: "private mode", original: "version: \"v1.0.0\"\nserver:\n port: 8088\n"},
} {
t.Run(tc.name, func(t *testing.T) {
dir := t.TempDir()
configPath := filepath.Join(dir, "config.yaml")
if err := os.WriteFile(configPath, []byte(tc.original), 0o600); err != nil {
t.Fatal(err)
}
if err := os.Chmod(configPath, 0o600); err != nil {
t.Fatal(err)
}
cmd := exec.Command(bash, "-c", command, "upgrade-version-test", configPath, "v1.2.3")
if output, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("update_config_version failed: %v\n%s", err, output)
}
got, err := os.ReadFile(configPath)
if err != nil {
t.Fatal(err)
}
if tc.wantDocumentStart && !strings.HasPrefix(string(got), "---\n") {
t.Errorf("YAML document start must remain first: %q", got)
}
var parsed struct {
Version string `yaml:"version"`
Server struct {
Port int `yaml:"port"`
} `yaml:"server"`
}
if err := yaml.Unmarshal(got, &parsed); err != nil {
t.Fatalf("updated config is not valid YAML: %v\n%s", err, got)
}
if parsed.Version != "v1.2.3" {
t.Errorf("version = %q, want v1.2.3", parsed.Version)
}
if parsed.Server.Port != 8088 {
t.Errorf("server.port = %d, want 8088", parsed.Server.Port)
}
info, err := os.Stat(configPath)
if err != nil {
t.Fatal(err)
}
if info.Mode().Perm() != 0o600 {
t.Errorf("mode = %v, want 0600 preserved", info.Mode().Perm())
}
})
}
}
func TestUpgradeScriptVersionRefusesUnsupportedYAML(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("upgrade.sh requires a POSIX shell")
}
if _, err := exec.LookPath("python3"); err != nil {
t.Skip("python3 unavailable")
}
script, err := os.ReadFile(filepath.Join("..", "..", "upgrade.sh"))
if err != nil {
t.Fatal(err)
}
function := extractShellFunction(t, string(script), "update_config_version")
for _, original := range []string{
"--- {server: {port: 8088}}\n",
"{server: {port: 8088}}\n",
"version: \"old\n version\"\nserver:\n port: 8088\n",
} {
path := filepath.Join(t.TempDir(), "config.yaml")
if err := os.WriteFile(path, []byte(original), 0600); err != nil {
t.Fatal(err)
}
command := function + "\nCONFIG_FILE=$1\nupdate_config_version v1.2.3\n"
if output, err := exec.Command("bash", "-c", command, "test", path).CombinedOutput(); err != nil {
t.Fatalf("writer failed: %v %s", err, output)
}
if got, err := os.ReadFile(path); err != nil || string(got) != original {
t.Fatalf("unsupported YAML was changed: %q %v", got, err)
}
}
}
// The tarball path syncs with `rsync --delete`, so every artifact a one-click update writes
// at the install root has to be on its keep list. .gitignore is exactly that list of
// machine-local artifacts, so the assertion is derived from it: a new marker cannot be
// forgotten here and silently deleted by the next package upgrade.
func TestUpgradeScriptKeepsEveryOneClickUpdateArtifact(t *testing.T) {
root := filepath.Join("..", "..")
ignore, err := os.ReadFile(filepath.Join(root, ".gitignore"))
if err != nil {
t.Fatal(err)
}
script, err := os.ReadFile(filepath.Join(root, "upgrade.sh"))
if err != nil {
t.Fatal(err)
}
var artifacts []string
inSection := false
for _, line := range strings.Split(string(ignore), "\n") {
line = strings.TrimSpace(line)
if strings.HasPrefix(line, "# One-click update artifacts") {
inSection = true
continue
}
if !inSection {
continue
}
if strings.HasPrefix(line, "#") {
break
}
if line != "" {
artifacts = append(artifacts, line)
}
}
if len(artifacts) == 0 {
t.Fatal("no update artifacts found in .gitignore: the section this test reads has moved")
}
// The script names the binary through a variable; compare against the literal name.
keeps := strings.ReplaceAll(string(script), "${BINARY_NAME}", "cyberstrike-ai")
for _, artifact := range artifacts {
if !strings.Contains(keeps, "--exclude="+artifact) {
t.Errorf("upgrade.sh syncs with rsync --delete but does not keep %s", artifact)
}
}
}
func extractShellFunction(t *testing.T, script, name string) string {
t.Helper()
startMarker := name + "() {"
start := strings.Index(script, startMarker)
if start < 0 {
t.Fatalf("function %s not found", name)
}
lines := strings.Split(script[start:], "\n")
for i := 1; i < len(lines); i++ {
if lines[i] == "}" {
return strings.Join(lines[:i+1], "\n")
}
}
t.Fatalf("function %s has no closing brace", name)
return ""
}

View File

@ -27,8 +27,15 @@ func main() {
var httpBootstrap = flag.Bool("http", false, "Force plain HTTP for the main site, overriding TLS settings in the configuration file")
var resetAdminPassword = flag.Bool("reset-admin-password", false, "Interactively reset the built-in admin password and exit")
checkIsolation := flag.Bool("check-process-isolation", false, "Probe task containment and cleanup, then exit without starting services")
checkUpdate := flag.Bool("check-update", false, "Report whether this installation's own repository has anything newer, then exit")
applyUpdate := flag.Bool("update", false, "Fast-forward this installation to its own remote, rebuild the binary, and exit")
updateRollback := flag.Bool("update-rollback", false, "Undo the last --update: back to the commit and binary kept before it")
flag.Parse()
if handled, code := updateCommandIfNeeded(strings.TrimSpace(*configPath), *checkUpdate, *applyUpdate, *updateRollback); handled {
os.Exit(code)
}
// 环境变量兼容(便于 systemd/docker 等不传参场景)
if *httpsBootstrap && *httpBootstrap {
fmt.Fprintln(os.Stderr, "--http and --https cannot be used together")

138
cmd/server/update_cli.go Normal file
View File

@ -0,0 +1,138 @@
package main
import (
"context"
"cyberstrike-ai/internal/config"
"cyberstrike-ai/internal/update"
"fmt"
"os"
"path/filepath"
"strings"
"time"
)
// The same one-click update the console page drives, for the two cases a page cannot
// serve: the process is not running at all, and somebody is ssh'd in with a keyboard.
// Keeping it in the binary rather than only in a shell script means one implementation of
// "fetch, fast-forward, rebuild, swap" instead of two that can disagree. The update
// source is read from the same config.yaml field the page saves to, so the keyboard and
// the button can never update from different repositories.
func updateCommandIfNeeded(configPath string, check, apply, rollback bool) (bool, int) {
if !check && !apply && !rollback {
return false, 0
}
root := filepath.Dir(configPath)
repo, err := config.LoadUpdateRepo(configPath)
if err != nil {
fmt.Fprintf(os.Stderr, "读取更新源失败: %v\n", err)
return true, 1
}
opts := update.Options{Root: root, Repo: repo}
ctx, cancel := context.WithTimeout(context.Background(), 45*time.Minute)
defer cancel()
source := strings.TrimSpace(repo)
if source == "" {
source = update.DefaultRepoURL + "(官方仓库默认)"
}
fmt.Printf("安装目录:%s\n", root)
fmt.Printf("更新源:%s\n", source)
switch {
case check:
snap, err := update.Check(ctx, opts)
if err != nil {
fmt.Fprintf(os.Stderr, "检查更新失败: %v\n", err)
return true, 1
}
printSnapshot(snap)
if !snap.Installed || snap.CheckError != "" {
return true, 1
}
return true, 0
case apply:
res, err := update.Apply(ctx, opts, func(s update.Step) {
fmt.Printf("[%s] %s\n", s.Phase, s.Message)
})
if res != nil {
printResult(res)
}
if err != nil {
fmt.Fprintf(os.Stderr, "更新未完成: %v\n", err)
return true, 1
}
fmt.Println("源码与二进制已就位;重启服务后新代码生效。")
return true, 0
case rollback:
res, err := update.Rollback(ctx, opts)
if err != nil {
fmt.Fprintf(os.Stderr, "回滚未完成: %v\n", err)
return true, 1
}
printResult(res)
return true, 0
}
return true, 0
}
func printSnapshot(s *update.Snapshot) {
if !s.Installed {
fmt.Printf("这个目录不是 git 工作树(%s),无法自动更新\n", s.Root)
return
}
target := s.TargetBranch
if target == "" {
target = "?"
}
fmt.Printf("本机分支 %s / 提交 %s (%s),更新源默认分支 %s\n", s.Branch, s.Commit, s.Subject, target)
if s.CheckError != "" {
fmt.Printf("检查失败:%s\n", s.CheckError)
return
}
fmt.Printf("更新源最新 %s (%s),落后 %d 个提交,本地领先 %d 个提交\n", s.RemoteCommit, s.RemoteSubject, s.Behind, s.Ahead)
for _, c := range s.Incoming {
fmt.Printf(" ○ %s %s\n", c.Commit, c.Subject)
}
if s.Behind > len(s.Incoming) {
fmt.Printf(" …(共 %d 个,只列出 %d 个)\n", s.Behind, len(s.Incoming))
}
if len(s.BlockingChanges) > 0 {
fmt.Printf("本机改过 %d 个源码文件,更新会拒绝执行:\n", len(s.BlockingChanges))
for _, c := range s.BlockingChanges {
fmt.Printf(" ! %s (%s)\n", c.Path, c.Status)
}
}
if !s.CanBuild {
fmt.Println("本机没有 Go 工具链:更新只搬源码,不会重编译")
}
if s.BuildPending {
fmt.Println("上一次更新留下了未完成的编译(源码已就位、二进制还是旧的):装好工具链后重跑更新即可补上")
}
if s.HasRollback {
fmt.Printf("可回滚到 %s\n", s.RollbackTo)
}
}
func printResult(r *update.Result) {
moved := r.Commits > 0 || r.ToCommit != r.FromCommit
if !moved && !r.BinaryBuilt {
fmt.Println("已经是最新,没有改动")
return
}
if moved {
fmt.Printf("%s → %s(%d 个提交,涉及 %d 个文件,用时 %s)\n", r.FromCommit, r.ToCommit, r.Commits, r.FilesTouched, r.Duration)
} else {
// commits == 0 but a binary was built: a retry that finished a build the previous
// attempt could not. Saying "已经是最新,没有改动" here would bury the one thing
// that did happen.
fmt.Printf("源码已经是最新(%s),本次补上了二进制\n", r.ToCommit)
}
if len(r.KeptContent) > 0 {
fmt.Printf("保留了 %d 个本机内容文件(roles/skills/tools 等,没有被上游覆盖):\n", len(r.KeptContent))
for _, p := range r.KeptContent {
fmt.Printf(" = %s\n", p)
}
}
if r.BinaryBuilt {
fmt.Printf("二进制已换新:%s(旧版本留在 %s 以便回滚)\n", r.BinaryPath, r.PrevBinary)
}
}

View File

@ -9,7 +9,8 @@
# 系统设置
# ============================================
# 前端显示的版本号(可选,不填则显示默认版本)
# 前端显示的版本号(可选,不填则显示默认版本)。一键更新完成后,会用新代码里这个文件的值
# 同步更新你的 config.yaml 的 version 字段(页头版本号与静态资源缓存随代码走)。
version: "v1.7.22"
# 服务器配置
server:
@ -589,3 +590,14 @@ project:
fact_index_path_max_runes: 10000
fact_summary_max_runes: 24000
default_inject_deprecated: false
# ============================================
# 一键更新(可选)
# ============================================
# 更新源:一个仓库地址,更新跟随该仓库自己的默认分支;不配置时就是官方仓库
# (https://github.com/AIPentest/CyberStrikeAI.git)。GitHub 访问不畅时可在这里填镜像地址,
# 想跟随自己的二开也只改这一处;控制台「系统设置 → 一键更新」页可以直接填写保存。
# 非 git 目录(解压/打包安装)不需要配置,也能在控制台「一键更新」页执行「接入更新源」,
# 把目录变成跟踪该仓库的 git 工作树,此后按正常安装一键更新。
# update:
# repo: https://github.com/AIPentest/CyberStrikeAI.git # 一个仓库地址;留空/不写 = 官方仓库

View File

@ -75,6 +75,78 @@ proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
```
## Upgrading
**Prefer the platform's own one-click update** (console System settings -> One-click update,
`POST /api/system/update/apply`, or `./cyberstrike-ai -update` at a keyboard). It pulls the newest
commit of the **update source repository**'s default branch (the official repository
`https://github.com/AIPentest/CyberStrikeAI.git` by default; one setting points it at your own fork
or a mirror): fetch, fast-forward, `go build`, atomic binary swap (the old binary is kept as
`cyberstrike-ai.prev`), while operator content - `roles/ skills/ tools/ agents/ knowledge_base/
data/ config.yaml` - is put aside and restored, and the result names every file it kept. When source
is modified locally or the local history has diverged from the source it refuses and says why
instead of forcing. See [the developer guide](developer-guide.md) for the full semantics.
When a supervisor is detected (systemd/launchd startup markers in the environment), the "exit after
updating" tick is pre-ticked: the process stands down after a successful update, the supervisor brings
the new binary back, and the page reloads itself once the service answers (sessions live in memory, so
one fresh login follows). Forgot the tick, or swapped the binary from the CLI? The console carries a
persistent banner with **Restart now** - no shell login needed.
The update source is a single repository address in the `update` section of `config.yaml` (`repo`),
or right on the console page: the official repository, your own fork, somebody else's repository or a
mirror are all just this one setting; empty means the official repository. An installation unpacked
from a Release archive (no `.git`) can be connected from the same page (no configuration needed - the
default official repository applies): the preview lists the files the target would replace and the
operator content that is kept, replaced files are backed up under
`.update-backup/<unique-backup>/overwritten/`, and confirming turns the directory into a normal
installation with one-click updates.
`upgrade.sh` still works and is now a thin shell over that implementation, with two paths decided by
the installation kind:
- **git work tree**: calls `./cyberstrike-ai -update` directly (building
`go build -o cyberstrike-ai ./cmd/server` first when there is no binary yet, and failing with
instructions on installing Go when there is neither). `--check` inspects only, through
`-check-update`.
- **not a git work tree** (Release tarball install): only here does it fall back to downloading a
Release tarball and `rsync --delete`-ing it in. The source repository then comes from
`--repo owner/name` or the `GITHUB_REPO` environment variable, and the built-in default is used only
when neither is given - with a warning naming which repository the code is coming from.
`config.yaml`, `data/`, `tools/`, `roles/`, `skills/`, `agents/`, `venv/` (skippable with
`--no-venv`) and the rollback points `.update-backup/`, `.update-state.json`, `cyberstrike-ai.prev`
are on the rsync keep list, so `--delete` cannot remove them.
Recommended flow either way:
1. Stop the service.
2. Back up `config.yaml`, `data/` and your custom directories.
3. Pull or replace the new code/binary.
4. Keep your own configuration and add fields the new `config.yaml` example introduced.
5. Start the service and check login, model test, tool list and knowledge-base status.
The one-click update performs step 3 (plus the rebuild); 1, 2, 4 and 5 stay operator decisions - a
database migration does not become compatible just because the binary changed. `upgrade.sh` suits
quick upgrades without compatibility risk; in production still back up first. Python dependencies:
`venv/` is created and managed by `run.sh`, and keeping it means an upgrade does not remove it - only
`--no-venv` deletes it and lets `run.sh` reinstall.
## Rollback
The one-click update leaves its own rollback point: `./cyberstrike-ai -update-rollback`, or the button
on the page, goes back to the commit before that update and puts `cyberstrike-ai.prev` back. It runs
only while HEAD is still the commit that update wrote, so work done afterwards is not discarded.
Content that was put aside also survives under `.update-backup/<unique-backup>/`.
Beyond that, roll back together:
- The previous binary or code.
- The pre-upgrade `config.yaml`.
- The pre-upgrade `data/`.
If the new version already wrote database schema changes, rolling back the binary alone may not be
enough; restore the whole backup.
## Deployment Decision Table
| Scenario | Recommended setup | Key settings | Avoid |

View File

@ -35,6 +35,144 @@ go run ./cmd/server --config config.yaml
The frontend is static. Most JS/CSS/template changes only require a browser refresh.
## One-Click Update: Letting an Installation Update Its Own Source
On a deployed machine the routine is "my tree moved forward by a few dozen commits -> bring this
installation up -> rebuild -> swap the binary -> restart". This used to be only `upgrade.sh`, which
pointed at one fixed upstream repository, so for anyone running a fork "upgrade" meant "overwrite
yourself with somebody else's code". The capability now lives in the platform (`internal/update`) and
the console page, the REST API and the CLI share one implementation, so the three surfaces cannot
disagree about why an update was refused.
### Three entry points
| entry | how it is used |
|---|---|
| console | System settings -> One-click update (`#system-update`, the old deep link still works). Opening this section reads the local tree only and does not go online; **Check** is what performs the fetch; **Update** starts a job the page polls; the "exit after updating" tick is pre-ticked when a supervisor is detected (launchd/systemd startup markers), and while the process is down the page watches for its return and reloads itself (sessions live in memory, so a fresh login follows); a rollback button sits below |
| REST | `GET /api/system/update` (state on disk, no network), `POST /api/system/update/check` (fetch, then report the gap), `POST /api/system/update/apply` (`202` with `job_id`, polled through `GET /api/system/update/job`), `POST /api/system/update/rollback` |
| CLI | `./cyberstrike-ai -check-update`, `./cyberstrike-ai -update`, `./cyberstrike-ai -update-rollback`. The install root is the directory holding `--config`, or the current directory when `--config` was not given |
Permissions are `update:read` (GET) and `update:apply` (the four mutating endpoints). `update:apply`
additionally requires a global (`all` scope) session: one machine has one source tree, and an
`assigned`/`own` session must not be able to move the code everybody else is running.
### Where the code comes from
From **the update source repository**: one address, the official repository
`https://github.com/AIPentest/CyberStrikeAI.git` by default, and the update follows that repository's
**own default branch** (nothing about branches is configured, and "main" is not hardcoded), so an
installation with no configuration at all still has exactly one answer to "where does an update come
from". `upgrade.sh` is now a thin shell over the same implementation: when this directory is a git
work tree it just calls `./cyberstrike-ai -update`.
### Changing the source (the update section of config.yaml)
The update source is a single field: a repository address. Empty means the official repository; to
follow your own fork, a mirror (when GitHub is hard to reach), or somebody else's repository, this is
the one place to change:
```yaml
update:
repo: https://github.com/AIPentest/CyberStrikeAI.git # one repository address; empty/absent = the official repository
```
The console's "Update source" block edits and saves this address (saving it empty goes back to the
official repository). Saving validates the address against an allowlist: https/http/ssh/git/file plus
local absolute paths - git's `ext::` transport executes commands and is rejected outright.
### Connecting a non-git installation (the tarball kind)
An installation that started as an unpacked Release archive has no `.git`; it can be connected from
the same page (the default official repository works without any configuration): the preview fetches in a throwaway repository and first lists
**the local files the target would replace** and **the operator content that will be kept**; on
confirm the directory becomes a git work tree (`git init`, origin added, the target branch checked
out), every replaced file is kept under `.update-backup/<unique-backup>/overwritten/`, operator content
is stashed and restored as usual, and the binary is rebuilt. From then on it is a normal
installation with one-click update and rollback - but note there is no git history before the
connection, so the connection itself has no earlier commit to roll back to; the first real update
writes the first rollback point.
### The version number follows the code
The repository's `config.example.yaml` carries the release version this code was cut from
(upstream bumps it in the release commit), while your `config.yaml` is operator data that no
update ever touches. So after a successful merge the update writes the new code's version back
into `config.yaml`'s `version` field (that one line only, temp file plus atomic rename; the job
log records the old and the new number). After a restart the header badge and the static
assets' `?v=` both match the code again - which is also why the frontend cache invalidates
itself on upgrade. A rollback puts the number back too (unless somebody hand-edited it in the
meantime), and connecting a tarball install syncs it as well.
### The four refusals
| situation | reason | meaning and what to do |
|---|---|---|
| product **source** modified locally (a path outside the protected list) | `local_source_edits` | An update is a download, not a conflict decision. The file names are listed; commit or restore them first |
| branch **diverged** from its remote (ahead and behind at once) | `diverged` | That is a merge decision; the counts are reported so you can resolve it by hand |
| no Go toolchain on this box | `no_toolchain` | **The source still updates**; only the binary is not swapped. Install `go` and press update again to finish |
| this directory is not a git work tree | `not_a_repo` (`installed: false` in the status) | A tarball installation has no remote to fast-forward; update it through the release package |
`apply` is asynchronous, so it always answers `202` first and the refusals above arrive in the polled
`job.failure` (`reason` / `message` / `items`). `rollback` is synchronous and maps refusals to status
codes (`local_source_edits`, `diverged`, `no_state`, `moved_since_update`, `no_binary` -> 409, anything
else -> 400). Other failures (`merge_failed`, `build_failed`, `swap_failed`) carry git's or the
compiler's own output; a failed build leaves the previous binary in place while the source has already
moved and the state file is written, so it stays rollback-able.
Check, update, adoption, rollback and restart share an operating-system file lock in the install
directory (`.update-lock`). Wait for the other operation when `update_busy` is reported. The system
releases the lock when its process exits; do not delete the lock file to bypass it.
### How operator content survives
`roles/ skills/ tools/ agents/ knowledge_base/ data/ log/ venv/ config.yaml .env` belong to the
**operator** (`update.Protected` is the judge). Before the merge, only those of those paths the
update actually writes to are copied into `.update-backup/<unique-backup>/` and removed from the tree -
your extra directories that upstream never touched are not disturbed - and they are put back
afterwards, which is what "update the code, keep my work" means. The result names every file in
`keptContent` instead of quietly dropping it: where both you and upstream changed the same file, the
version that lands is yours, and the result says so.
### Rollback
`./cyberstrike-ai -update-rollback`, or the button on the page: `git reset --hard` back to the commit
the update came from, the binary kept as `cyberstrike-ai.prev` is put back when that update swapped
one, and `.update-state.json` is removed. An update whose build failed never swapped a binary, so its
rollback moves the source only - the binary on disk already belongs to the commit it returns to. It
refuses when there is no update record (`no_state`), a swap is owed but no `cyberstrike-ai.prev` is
left (`no_binary`), a recorded commit is not in this repository (`bad_state`), the binary on disk is
not the one the record pairs with that commit (`binary_changed`), **HEAD has moved since that update**
(`moved_since_update` - a rollback undoes the update, not the work done after it), or source is
modified locally (`local_source_edits`).
Rollback writes `.update-rollback-pending.json` before changing source or binaries. Run rollback
again after an interruption to finish recovery; the console reports `rollbackPending` and pauses new
updates. Keep the recovery record, backup directory and `.prev` file. If recorded binary hashes do not
match the files on disk, recovery refuses to overwrite them.
### The two restart cases
The process only stands down (graceful `Shutdown`, then exit 0) when the request explicitly says
`restart: true` **and** a restart hook was wired at startup. Whether it actually comes back is up to a
supervisor (systemd, `run.sh`), and the page says exactly that rather than promising a boot that may
not happen. Asking for a restart with no hook wired is a `400`, instead of stopping the service and
claiming it restarted.
**A pending binary is a durable state, and it can be activated later.** The status endpoint compares
the binary identity captured at startup (size + nanosecond mtime) with what is on disk now: after an
update, a rollback or a CLI run swapped the file without a restart, `needsRestart` is true,
`binaryBuiltAt` says when it was built, and the console grows a persistent banner with **Restart now**
(`POST /api/system/update/restart`; `409 nothing_pending` when there is nothing to activate, `409`
while a job runs, `400` without a hook). The `supervised` field comes from environment markers
(launchd's `XPC_SERVICE_NAME`, systemd's `INVOCATION_ID`/`JOURNAL_STREAM`) and only decides the tick's
default.
**And the page recovers by itself.** While the process is down the console becomes a recovery view
that probes the status endpoint every 2 seconds: a 200 means the old process is still answering (keep
waiting), a dead connection means it is on its way out, and a 401 from a process that no longer knows
the session is the proof the restart happened - the page then `location.replace`s itself back to
`#system-update`. Leaving the console stops the watching instead of yanking the user back.
## Adding a Business Module
Do not add only a handler. A complete module usually needs:
@ -109,3 +247,6 @@ High-value tests:
- OpenAPI: `internal/handler/openapi.go`
- Tool executor: `internal/security/executor.go`
- Skill package: `internal/skillpackage/`
- One-click update: `internal/update/` (status, apply, rollback), HTTP surface in
`internal/handler/update.go`, CLI switches in `cmd/server/update_cli.go`, thin shell in
`upgrade.sh`

View File

@ -74,6 +74,7 @@ Permissions use `module:action`. Common actions are `read`, `write`, `delete`, a
| WebShell | `webshell:read`, `webshell:write`, `webshell:delete` |
| C2 | `c2:read`, `c2:write`, `c2:delete` |
| MCP | `mcp:read`, `mcp:execute`, `mcp:write`, `mcp:external:execute` |
| One-click update (local source) | `update:read`, `update:apply` |
| Knowledge | `knowledge:read`, `knowledge:write`, `knowledge:delete` |
| Skills | `skills:read`, `skills:write`, `skills:delete` |
| Markdown Agents | `agents:read`, `agents:write`, `agents:delete` |
@ -99,6 +100,11 @@ Important distinctions:
- `mcp:external:execute` allows Agent calls to external MCP tools and currently also requires `all` scope.
- `fofa:execute` is kept for backward compatibility, but it now protects the Reconnaissance page for FOFA, ZoomEye, Quake, and Shodan searches.
- `mcp:write` manages external MCP configuration; it is separate from external tool execution.
- One-click update is two permissions: `update:read` shows the installed version and the gap against
the update source, while `update:apply` pulls the configured source repository's default branch
(the official repository by default), rebuilds the platform binary and swaps it. The mutating side additionally requires the session to hold that permission
with `all` scope - one machine has one source tree, so an `assigned`/`own` session must not be able
to move the code everybody else is running.
- `robot:write` manages robot configuration and the test endpoint. Chatbot conversations use the bound user or configured service account's business permissions.
---
@ -143,6 +149,7 @@ Some definitions have no owner. Their mutations require the corresponding permis
- Knowledge mutations other than search.
- Global HITL allowlist, reviewer, and audit policy.
- C2 Profile mutations.
- One-click update mutations (`check`/`apply`/`rollback`, i.e. `update:apply`).
- Some global monitor statistics.
---

View File

@ -179,6 +179,37 @@ SQLite 热备份时最好先停止服务,或至少复制 `*.db`、`*.db-wal`
## 升级
**优先用平台自带的「一键更新」**(控制台「系统设置 → 一键更新」、`POST /api/system/update/apply`、
或键盘上的 `./cyberstrike-ai -update`)。它从**更新源仓库**(默认官方仓库
`https://github.com/AIPentest/CyberStrikeAI.git`,可一处配置改成自己的二开或镜像)拉取该仓库默认分支的
最新代码:fetch → 快进合并 → `go build` → 原子换二进制(旧的留作 `cyberstrike-ai.prev`),并把
`roles/ skills/ tools/ agents/ knowledge_base/ data/ config.yaml` 等运维者内容先暂存再放回,结果里点名
保留了哪些文件。本地源码有改动、或本地历史与更新源分叉时它会拒绝并说明原因,而不是硬来。
构建失败或本机没有 Go 工具链时源码照样更新、二进制保持原样:欠编译会记在安装目录(`.update-build-pending`)
并被页面标出,装好 go 后再点一次「一键更新」即补编译。
细节见 [开发者指南](developer-guide.md) 的「一键更新」一节。
检测到 systemd/launchd(环境里有对应启动标记)时,"更新完成后退出进程"默认勾选:更新成功后进程退出、
由守护拉起新二进制,页面会在服务回来时自动刷新(会话在内存里,需要重新登录一次)。忘勾、或在命令行
换过二进制时,控制台顶部有常驻横幅和「立即重启服务」补上这一步——不必再登录服务器手动重启。
更新源是 `config.yaml` `update` 段里的**一个仓库地址**(`repo`),也可以直接在控制台「一键更新」页填写保存:
想跟随官方仓库、自己的二开、别人的二开或镜像,改的都是这一处;不写就是官方仓库。**用 Release 包解压安装、
目录里没有 git 的**,在同一页点「预览并接入」(不配置也能用默认的官方仓库):预览先列出会被目标版本替换的
文件与会保留的运维者内容,被替换的都会备份在 `.update-backup/<唯一备份目录>/overwritten/`,确认后目录成为可一键
更新的正常安装。
`upgrade.sh` 仍然可用,它现在只是这条实现的薄壳,并按安装形态分两条路:
- **本目录是 git 工作树**:直接调用 `./cyberstrike-ai -update`(还没有二进制时先
`go build -o cyberstrike-ai ./cmd/server` 再更新;两者都没有就明确报错并说明怎么装 Go)。
`--check` 只检查不改动,走 `-check-update`。
- **本目录不是 git 工作树**(Release tarball 安装):才回落到"下载 Release 包 + `rsync --delete`"的老路径。
此时源码仓库取自 `--repo owner/name` 或环境变量 `GITHUB_REPO`,两者都没给才用内置默认值,
并且会打一行警告说明代码正从哪个仓库取。`config.yaml`、`data/`、`tools/`、`roles/`、`skills/`、
`agents/`、`venv/`(`--no-venv` 可关闭)以及回滚点 `.update-backup/`、`.update-state.json`、
`cyberstrike-ai.prev` 都在 rsync 的保留名单里,不会被 `--delete` 顺手删掉。
推荐流程:
1. 停止服务。
@ -187,11 +218,18 @@ SQLite 热备份时最好先停止服务,或至少复制 `*.db`、`*.db-wal`
4. 保留原配置,按新版 `config.yaml` 示例补新增字段。
5. 启动服务,检查登录、模型测试、工具列表、知识库状态。
仓库提供 `upgrade.sh`,适合无兼容性问题的快速升级;生产环境仍建议先备份再运行。
一键更新只做 3(以及需要时的换二进制),1/2/4/5 仍是运维者的判断:数据库结构变更不会因为二进制换了
就自动兼容。`upgrade.sh` 适合无兼容性问题的快速升级;生产环境仍建议先备份再运行。
Python 依赖方面:`venv/` 由 `run.sh` 自动创建和管理,保留它就不会被升级打掉;用 `--no-venv` 才会删除并由
`run.sh` 重装。
## 回滚
回滚时同时恢复:
一键更新自带回滚点:`./cyberstrike-ai -update-rollback` 或页面上的回滚按钮,会撤到那次更新前的提交并把
`cyberstrike-ai.prev` 换回原位;它只在"HEAD 仍是那次更新写下的提交"时才执行,之后的工作不会被顺手抹掉。
被暂存过的内容也留在 `.update-backup/<唯一备份目录>/` 里。
除此之外,回滚时同时恢复:
- 上一版本二进制或代码。
- 升级前的 `config.yaml`。

View File

@ -43,6 +43,120 @@ go run ./cmd/server --config config.yaml
4. 如需对外文档,更新 `internal/handler/openapi.go`。
5. 如需前端调用,更新 `web/static/js/`。
## 一键更新:让安装目录更新它自己的源码
部署现场的日常是"我的 fork 又前进了几十个提交 → 把这套安装带上去 → 重新编译 → 换二进制 → 重启"。
这件事以前只有 `upgrade.sh`,而它写死了别人的仓库:对跑 fork 的人来说"升级"等于"用别人的代码覆盖自己"。
现在这个能力做进了平台自己(`internal/update`),页面、REST 与 CLI 三条入口共用同一份实现,
所以它们给出的拒绝理由不可能各说各话。
### 三种入口
| 入口 | 怎么用 |
|---|---|
| 控制台 | 「系统设置 → 一键更新」(`#system-update` 老深链仍可用)。打开这一区只读本机状态、不联网;点「检查更新」才去 fetch;「一键更新」发起任务并轮询进度;"更新完成后退出进程"在检测到守护进程(launchd/systemd 的启动标记)时默认勾选,重启期间页面守着重连、新进程一应答就自动刷新(会话在内存里,刷新后需重新登录);另有回滚按钮 |
| REST | `GET /api/system/update`(磁盘现状,不联网)、`POST /api/system/update/check`(fetch 后报告差集)、`POST /api/system/update/apply`(`202` 返回 `job_id`,用 `GET /api/system/update/job` 轮询)、`POST /api/system/update/rollback` |
| CLI | `./cyberstrike-ai -check-update`、`./cyberstrike-ai -update`、`./cyberstrike-ai -update-rollback`。安装目录 = `--config` 所在目录,未给 `--config` 时是当前目录 |
权限是 `update:read`(GET)与 `update:apply`(四个写接口)。`update:apply` 还要求会话是 global(`all` scope):
一台机器只有一份源码,`assigned`/`own` scope 的账号不该能移动别人正在跑的代码。
### 它从哪里取代码
从**更新源仓库**:一个仓库地址,默认就是官方仓库 `https://github.com/AIPentest/CyberStrikeAI.git`;
更新跟随该仓库**自己的默认分支**(不用配置分支,也不写死 main),所以对一套没做过任何配置的安装,
「从哪更新」永远有一个明确答案。`upgrade.sh` 现在只是这条实现的薄壳:本目录是 git 工作树时它直接调
`./cyberstrike-ai -update`。
### 更换更新源(config.yaml 的 update 段)
更新源只有一个字段:仓库地址。留空 = 官方仓库;想跟随自己的二开、镜像(GitHub 访问不畅时)或别人的仓库,
只改这一处:
```yaml
update:
repo: https://github.com/AIPentest/CyberStrikeAI.git # 一个仓库地址;留空/不写 = 官方仓库
```
控制台的「一键更新 → 更新源」区块可以直接编辑并保存这个地址(留空保存 = 回到官方仓库)。
服务端保存时校验地址:只允许 https/http/ssh/git/file:// 与本机绝对路径——git 的 `ext::` 传输会执行命令,一律拒绝。
### 接入非 git 安装(解压/打包装的那类)
一开始用 Release 包解压安装、目录里没有 `.git` 的,可在同一页执行「预览并接入」(不配置也能用默认的官方仓库):
预览在临时仓库里 fetch,先列出**会被目标版本替换的本机文件**与**会保留的运维者内容**;确认后目录接入
成为 git 工作树(`git init` + 添加 origin + 落地目标分支),被替换的文件全部留底在
`.update-backup/<唯一备份目录>/overwritten/`,运维者内容照旧先暂存再放回,随后重编译二进制。
接入后它就是正常安装,一键更新与回滚都可用了;注意接入前没有 git 历史,因此「接入」本身没有可回滚的
上一提交,第一个回滚点由接入后的第一次更新写下。
### 版本号随代码走
仓库里的 `config.example.yaml` 载着这份代码对应的发布版本(上游随 release 提交一起改),而你的
`config.yaml` 是运维数据、任何一次更新都不会碰它。所以更新在合并完成后会把新代码的版本号写回
`config.yaml` 的 `version` 字段(只动这一行、临时文件 + 原子替换;进度里会有一行「版本号已随新代码
更新:v1.7.20 → v1.7.21」)。重启后页头的版本徽标与静态资源的 `?v=` 都跟代码对上——升级后前端缓存
也因此自动失效。回滚会把版本号一起还原(前提是这期间没人手改过它);解压安装「接入」时同样同步一次。
若 `version` 的写法无法行级替换(如 JSON 单行、多行标量),写入会安全跳过并提示,而不是产出打不开的
配置——读取走 YAML 解析(认 `version` / `"version"` / `'version'` 三种写法),写入的行匹配与之口径一致。
### 四种拒绝场景
| 场景 | reason | 含义与处理 |
|---|---|---|
| 本地改过**产品源码**(不在 protected 清单里的路径) | `local_source_edits` | 一键更新是"下载",不是"替你决定冲突"。点名文件,先提交或还原再重试 |
| 分支与远端**分叉**(本地既领先又落后) | `diverged` | 那是合并决策,给出 ahead/behind 数字;手工处理后再点 |
| 本机没有 Go 工具链 | `no_toolchain` | **源码照样更新**,只有二进制没换;欠编译记入 `.update-build-pending`(状态里 `buildPending`,页面照常开放「一键更新」),装好 `go` 再点一次会真的补编译 |
| 这个目录不是 git 工作树 | `not_a_repo`(状态里 `installed: false`) | tarball 安装的目录没有可快进的远端,按发布包方式更新 |
`apply` 是异步的,所以它总是先回 `202`,上表的拒绝出现在轮询到的 `job.failure`(`reason`/`message`/`items`)里;
`rollback` 是同步的,拒绝直接落到状态码(`local_source_edits`、`diverged`、`no_state`、`moved_since_update`、
`no_binary` → 409,其余 → 400)。其他失败(`merge_failed`、`build_failed`、`swap_failed`)带着 git/go 的原始输出;
编译失败时二进制保持原版本,而源码已移动、状态文件已写好,因此仍然可以回滚。
检查、更新、接入、回滚和重启共用安装目录的系统文件锁(`.update-lock`)。遇到
`update_busy` 时等待另一操作完成;进程退出后锁由系统释放,不要删除锁文件来绕过互斥。
### 运维者的内容如何被保留
`roles/ skills/ tools/ agents/ knowledge_base/ data/ log/ venv/ config.yaml .env` 是**运维者的内容**,
判定在 `update.Protected`。合并前,只有本次更新**确实会写到**的那些路径被复制到
`.update-backup/<唯一备份目录>/` 并从工作树移开(你多出来的、上游没动的目录连碰都不碰),合并后再原样放回,
于是"更新代码、留下我的工作"成立。结果里的 `keptContent` 逐个点名被保留的文件——绝不静默丢弃:
当上游与你在同一个文件上都有改动,落地的是你的版本,而这件事写在结果里。
**回滚遵循同一条规则**:`reset --hard` 会把受保护文件上现存的本地改动先暂存、重置后放回(更新前改的
和更新后改的都算,本地删除的保持删除),`keptContent` 同样点名——回滚撤的是代码,不是你的内容。
### 回滚
`./cyberstrike-ai -update-rollback` 或页面按钮:`git reset --hard` 回到那次更新前的提交,
换过二进制的那次会把 `cyberstrike-ai.prev` 放回原位,随后删除 `.update-state.json`。
编译失败的那次更新从没换过二进制,所以它的回滚只搬源码——磁盘上的二进制本来就属于要回去的那个提交。
它会拒绝的情形:没有更新记录(`no_state`)、需要换回却没有留下 `cyberstrike-ai.prev`(`no_binary`)、
记录里的提交在本仓库不存在(`bad_state`)、磁盘上的二进制不是记录里与该提交配对的那一个(`binary_changed`)、
**HEAD 自那次更新之后又动过**(`moved_since_update`:回滚只该撤到更新前,不该顺手抹掉之后的工作)、
以及存在本地源码改动(`local_source_edits`)。
回滚开始前会写入 `.update-rollback-pending.json`。中断后再次执行回滚会继续恢复;页面的
`rollbackPending` 提示会暂停新更新。保留恢复记录、备份目录和 `.prev`,不要手动删除它们。
如果记录中的二进制哈希无法与现场对应,会拒绝覆盖并保留现场。
### 重启的两种情形
进程只有在请求显式带 `restart: true`、且启动时装配了重启钩子时才会优雅退出(`Shutdown` 后退出码 0)。
能不能被拉起来取决于外部守护(systemd、`run.sh`),页面如实这么写,而不是承诺一次可能不发生的启动;
没装配钩子时要求重启是 `400`,而不是先停掉服务再自称重启了。
**待生效状态是持久的、可补重启。** 状态接口对比"启动时记下的二进制身份(大小 + 纳秒 mtime)"与磁盘
现值:更新、回滚或 CLI 换过二进制而没重启时,`needsRestart` 为真、`binaryBuiltAt` 给出构建时间,
控制台顶部出现常驻横幅与「立即重启服务」(`POST /api/system/update/restart`;没有待生效版本时
`409 nothing_pending`、有任务在跑 `409`、没钩子 `400`)。`supervised` 字段来自环境标记(launchd 的
`XPC_SERVICE_NAME`、systemd 的 `INVOCATION_ID`/`JOURNAL_STREAM`),只用来决定勾选框的默认值。
**重启后页面自己回来。** 重启期间控制台换成自恢复视图,每 2 秒探一次状态接口:旧进程还在应答(200)
就继续等;连不上说明正在退出;新进程接客但对旧会话只回 401——这就是"重启已完成"的判据,页面随即
`location.replace` 回 `#system-update` 整页刷新。离开控制台则静默停表,不把已经走开的用户拽回来。
## 数据库
默认 SQLite。新增表或字段时:

View File

@ -81,6 +81,7 @@ AI 测试角色不是安全授权边界。即使选择了“渗透测试”角
| WebShell | `webshell:read`、`webshell:write`、`webshell:delete` |
| C2 | `c2:read`、`c2:write`、`c2:delete` |
| MCP | `mcp:read`、`mcp:execute`、`mcp:write`、`mcp:external:execute` |
| 一键更新(本机源码) | `update:read`、`update:apply` |
| 知识库 | `knowledge:read`、`knowledge:write`、`knowledge:delete` |
| Skills | `skills:read`、`skills:write`、`skills:delete` |
| Markdown Agents | `agents:read`、`agents:write`、`agents:delete` |
@ -107,6 +108,8 @@ AI 测试角色不是安全授权边界。即使选择了“渗透测试”角
- `mcp:execute` 用于访问认证后的 MCP HTTP 入口。
- `mcp:external:execute` 用于 Agent 调用外部 MCP 工具,当前还要求该权限的 Scope 为 `all`。
- 管理外部 MCP 配置使用 `mcp:write`,与执行外部工具是两项权限。
- 一键更新是**两项**:`update:read` 看本机安装的版本与更新源差集;`update:apply` 拉取更新源仓库(默认官方仓库)
的默认分支、重编译并换掉平台二进制。写侧还要求会话是 `all` scope——一台机器一份源码,`assigned`/`own` 不该能移动别人正在跑的代码。
- `robot:write` 管理机器人配置和测试入口;机器人聊天本身使用绑定用户或服务账号的业务权限。
---
@ -152,6 +155,7 @@ project:write → own
- 知识库写操作(搜索除外)。
- HITL 全局白名单、默认审核方和审计策略。
- C2 Profile 写操作。
- 一键更新的写操作(`check`/`apply`/`rollback`,即 `update:apply`)。
- 部分全局监控统计。
---

View File

@ -610,6 +610,15 @@ func New(cfg *config.Config, log *logger.Logger, configPath string) (*App, error
return nil
})
// The one-click update acts on this installation's own tree, rooted where the live config
// file is. Its restart hook exits after a graceful shutdown, which is only "a restart" when
// something supervises the process - so the endpoint reports whether it is standing down or
// whether somebody has to start it again, instead of promising a boot that may not happen.
updateHandler := handler.NewUpdateHandler(configDir, log.Logger, auditSvc, func() {
app.Shutdown()
os.Exit(0)
}, configHandler.UpdateSource, configHandler.SetUpdateSource)
// 设置路由(使用 App 实例以便动态获取 handler)
setupRoutes(
router,
@ -642,6 +651,7 @@ func New(cfg *config.Config, log *logger.Logger, configPath string) (*App, error
mcpServer,
authManager,
openAPIHandler,
updateHandler,
)
return app, nil
@ -947,6 +957,7 @@ func setupRoutes(
mcpServer *mcp.Server,
authManager *security.AuthManager,
openAPIHandler *handler.OpenAPIHandler,
updateHandler *handler.UpdateHandler,
) {
// API路由
api := router.Group("/api")
@ -1123,6 +1134,16 @@ func setupRoutes(
protected.POST("/config/test-vision", configHandler.TestVision)
protected.POST("/config/list-models", configHandler.ListModels)
// 系统更新(保持本安装自身源码最新:查看、检查、应用、进度、回滚、接入、更新源)
protected.GET("/system/update", updateHandler.GetStatus)
protected.GET("/system/update/job", updateHandler.Job)
protected.POST("/system/update/check", updateHandler.Check)
protected.POST("/system/update/apply", updateHandler.Apply)
protected.POST("/system/update/restart", updateHandler.Restart)
protected.POST("/system/update/rollback", updateHandler.Rollback)
protected.POST("/system/update/adopt", updateHandler.Adopt)
protected.POST("/system/update/source", updateHandler.SaveSource)
// 系统设置 - 终端(执行命令,提高运维效率)
protected.POST("/terminal/run", terminalHandler.RunCommand)
protected.POST("/terminal/run/stream", terminalHandler.RunCommandStream)

View File

@ -9,6 +9,8 @@ import (
"net/url"
"os"
"path/filepath"
"reflect"
"regexp"
"strconv"
"strings"
@ -49,6 +51,14 @@ type Config struct {
MultiAgent MultiAgentConfig `yaml:"multi_agent,omitempty" json:"multi_agent,omitempty"`
Project ProjectConfig `yaml:"project,omitempty" json:"project,omitempty"`
Vision VisionConfig `yaml:"vision,omitempty" json:"vision,omitempty"`
Update UpdateConfig `yaml:"update,omitempty" json:"update,omitempty"`
}
// UpdateConfig 一键更新的更新源(可选):一个仓库地址,更新跟随该仓库的默认分支。
// 留空即官方仓库(internal/update.DefaultRepoURL),跟随镜像或自己的二开只需改这一处。
type UpdateConfig struct {
// Repo 更新源仓库地址(https/http/ssh/git/file:// 或本机绝对路径);留空 = 官方仓库。
Repo string `yaml:"repo,omitempty" json:"repo,omitempty"`
}
type EnsureLocalConfigResult struct {
@ -1719,6 +1729,227 @@ func validateOpenAIOutputLimits(openAI OpenAIConfig) error {
return nil
}
// LoadUpdateRepo 只读 update 段的 repo 字段,不加载也不校验文件其余部分:命令行一键更新
// 必须与页面用同一个更新源,而配置里其它段落坏掉不该拦住"把源码更新好"这条修复路径。
// 文件不存在不是错误(未配置 = 官方仓库);YAML 解析失败则报错,不去猜更新源。
func LoadUpdateRepo(path string) (string, error) {
data, err := os.ReadFile(path)
if err != nil {
if os.IsNotExist(err) {
return "", nil
}
return "", fmt.Errorf("读取配置文件失败: %w", err)
}
var thin struct {
Update struct {
Repo string `yaml:"repo"`
} `yaml:"update"`
}
if err := yaml.Unmarshal(data, &thin); err != nil {
return "", fmt.Errorf("解析配置文件失败: %w", err)
}
return strings.TrimSpace(thin.Update.Repo), nil
}
// FileVersion 读一个配置文件形态 YAML 的顶层 version 字段。仓库里的 config.example.yaml
// 载着这份代码对应的发布版本(上游随 release 提交一起改),一键更新用它把"当前跑的是什么
// 版本"同步进运维者的 config.yaml。文件或字段不存在 = 未知,不是错误。
func FileVersion(path string) (string, error) {
data, err := os.ReadFile(path)
if err != nil {
if os.IsNotExist(err) {
return "", nil
}
return "", fmt.Errorf("读取配置文件失败: %w", err)
}
version, err := parseTopVersion(data)
if err != nil {
return "", fmt.Errorf("解析配置文件失败: %w", err)
}
return version, nil
}
// parseTopVersion 从配置文本里取顶层 version。走 YAML 解析,version / "version" / 'version'
// 三种写法一视同仁——读取认得的写法,写入也必须认得,否则就会在合法的引号键配置上追加出
// 第二个 version 键(见 WriteVersion)。
func parseTopVersion(data []byte) (string, error) {
var thin struct {
Version string `yaml:"version"`
}
if err := yaml.Unmarshal(data, &thin); err != nil {
return "", err
}
return strings.TrimSpace(thin.Version), nil
}
// versionValuePattern 约束能写进配置的版本号:它来自仓库里的文件,但落到的是运维者的
// 配置上,带引号或换行的值会把 YAML 写坏。
var versionValuePattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._+-]*$`)
// topVersionKey 判断一行是不是顶层的 version 键,三种 YAML 都认的写法都在内:version:、
// "version":、'version':。缩进的同名键属于别的段落,不动。
func topVersionKey(line string) bool {
for _, key := range []string{"version", `"version"`, "'version'"} {
if strings.HasPrefix(line, key) {
return strings.HasPrefix(strings.TrimSpace(line[len(key):]), ":")
}
}
return false
}
func yamlDocumentStart(line string) bool {
line = strings.TrimPrefix(strings.TrimSuffix(line, "\r"), "\uFEFF")
if !strings.HasPrefix(line, "---") {
return false
}
rest := line[len("---"):]
if strings.Trim(rest, " \t") == "" {
return true
}
return len(rest) > 0 && (rest[0] == ' ' || rest[0] == '\t') && strings.HasPrefix(strings.TrimLeft(rest, " \t"), "#")
}
// WriteVersion 就地替换配置文件的顶层 version 字段,保留其它每一行的原样(tarball 升级
// 路径一直这么做);没有这个字段就插到文件开头(若文件以 YAML 文档标记开头,则插在标记后)。
// 返回是否真的改了。写盘走临时文件 + 原子 rename——这是运维者的活配置,不能留半截。替换后先把新文本解析回验一遍:行级替换够不着的
// 写法(JSON 单行、多行标量……)解析失败或读不回目标值就拒绝写、原文件不动。版本号停在旧值
// 只是页头显示问题,写坏配置是起不来。
func WriteVersion(path, version string) (bool, error) {
version = strings.TrimSpace(version)
if version == "" {
return false, nil
}
if len(version) > 64 || !versionValuePattern.MatchString(version) {
return false, fmt.Errorf("版本号不合法:%q", version)
}
resolved, err := filepath.EvalSymlinks(path)
if err != nil {
return false, err
}
path = resolved
data, err := os.ReadFile(path)
if err != nil {
return false, err
}
info, err := os.Stat(path)
if err != nil {
return false, err
}
lines := strings.Split(string(data), "\n")
replaced := false
for i, line := range lines {
if topVersionKey(line) {
lines[i] = `version: "` + version + `"`
replaced = true
break
}
}
if !replaced {
versionLine := `version: "` + version + `"`
insertAt := 0
for i, line := range lines {
if yamlDocumentStart(line) {
insertAt = i + 1
break
}
trimmed := strings.TrimSpace(strings.TrimPrefix(line, "\uFEFF"))
if trimmed != "" && !strings.HasPrefix(trimmed, "#") && !strings.HasPrefix(line, "%") {
break
}
}
lines = append(lines[:insertAt], append([]string{versionLine}, lines[insertAt:]...)...)
}
out := strings.Join(lines, "\n")
if out == string(data) {
return false, nil
}
if got, err := parseTopVersion([]byte(out)); err != nil || got != version {
return false, fmt.Errorf("version 的写法无法就地替换(改后配置解析失败或读回为 %q),已放弃写入,原文件未改动", got)
}
// Reading back version alone is insufficient: inserting before an inline
// document marker can create a new first document and hide every setting.
var originalSettings, nextSettings map[string]interface{}
if err := yaml.Unmarshal(data, &originalSettings); err != nil {
return false, err
}
if err := yaml.Unmarshal([]byte(out), &nextSettings); err != nil {
return false, err
}
delete(originalSettings, "version")
delete(nextSettings, "version")
if len(originalSettings) != len(nextSettings) || (len(originalSettings) > 0 && !reflect.DeepEqual(originalSettings, nextSettings)) {
return false, fmt.Errorf("版本号写入会改变其它配置,已放弃写入,原文件未改动")
}
if err := writeVersionFile(path, []byte(out), info.Mode().Perm()); err != nil {
return false, err
}
return true, nil
}
// RemoveVersion undoes a version field added by an update to an unversioned
// configuration. All other settings and the file's permissions stay intact.
func RemoveVersion(path string) (bool, error) {
resolved, err := filepath.EvalSymlinks(path)
if err != nil {
return false, err
}
path = resolved
data, err := os.ReadFile(path)
if err != nil {
return false, err
}
info, err := os.Stat(path)
if err != nil {
return false, err
}
lines := strings.Split(string(data), "\n")
for i, line := range lines {
if !topVersionKey(line) {
continue
}
out := strings.Join(append(lines[:i], lines[i+1:]...), "\n")
var before, after map[string]interface{}
if err := yaml.Unmarshal(data, &before); err != nil {
return false, err
}
if err := yaml.Unmarshal([]byte(out), &after); err != nil {
return false, err
}
delete(before, "version")
if _, present := after["version"]; present || len(before) != len(after) || (len(before) > 0 && !reflect.DeepEqual(before, after)) {
return false, fmt.Errorf("无法安全移除版本号,原配置未改动")
}
if err := writeVersionFile(path, []byte(out), info.Mode().Perm()); err != nil {
return false, err
}
return true, nil
}
return false, nil
}
func writeVersionFile(path string, data []byte, mode os.FileMode) error {
f, err := os.CreateTemp(filepath.Dir(path), ".version-*")
if err != nil {
return err
}
defer os.Remove(f.Name())
defer f.Close()
if err := f.Chmod(mode); err != nil {
return err
}
if _, err := f.Write(data); err != nil {
return err
}
if err := f.Sync(); err != nil {
return err
}
if err := f.Close(); err != nil {
return err
}
return os.Rename(f.Name(), path)
}
func EnsureLocalConfig(path string) (EnsureLocalConfigResult, error) {
path = strings.TrimSpace(path)
if path == "" {

View File

@ -3,6 +3,7 @@ package config
import (
"os"
"path/filepath"
"runtime"
"strings"
"testing"
)
@ -334,3 +335,277 @@ func TestLatestUserMessageRunesEffective(t *testing.T) {
t.Fatalf("custom latest user tail runes = %d", got)
}
}
func TestLoadUpdateRepoReadsOnlyTheSourceField(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "config.yaml")
// The rest of the file may be broken or unvalidatable; the CLI only asks for the
// update source, and a full config load must not be a precondition for updating.
if err := os.WriteFile(path, []byte("update:\n repo: https://github.com/Sycun/CyberStrikeAI.git\nserver:\n port: 8088\n"), 0o644); err != nil {
t.Fatal(err)
}
repo, err := LoadUpdateRepo(path)
if err != nil {
t.Fatal(err)
}
if repo != "https://github.com/Sycun/CyberStrikeAI.git" {
t.Fatalf("repo = %q, want the configured address", repo)
}
// Unset and missing files both mean "the official repository is the default".
if err := os.WriteFile(path, []byte("server:\n port: 8088\n"), 0o644); err != nil {
t.Fatal(err)
}
if repo, err := LoadUpdateRepo(path); err != nil || repo != "" {
t.Fatalf("repo = %q err = %v, want empty with no error", repo, err)
}
if repo, err := LoadUpdateRepo(filepath.Join(dir, "missing.yaml")); err != nil || repo != "" {
t.Fatalf("a missing config is not an error: repo = %q err = %v", repo, err)
}
// A file that is not YAML at all must fail loudly rather than silently fall back to
// the official repository (that would be an update from the wrong place).
if err := os.WriteFile(path, []byte("update: [not: a: map\n"), 0o644); err != nil {
t.Fatal(err)
}
if _, err := LoadUpdateRepo(path); err == nil {
t.Fatal("a malformed config must be an error, not a silent default")
}
}
func TestFileVersionAndWriteVersion(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "config.yaml")
// Missing file reads as "unknown", not an error.
if v, err := FileVersion(filepath.Join(dir, "missing.yaml")); err != nil || v != "" {
t.Fatalf("missing file: %q %v", v, err)
}
original := "version: \"v1.0.0\"\nserver:\n port: 8088\n # a nested word: version: should stay put\nnotes:\n version: nested-untouched\n"
if err := os.WriteFile(path, []byte(original), 0o640); err != nil {
t.Fatal(err)
}
if err := os.Chmod(path, 0o640); err != nil {
t.Fatal(err)
}
originalInfo, err := os.Stat(path)
if err != nil {
t.Fatal(err)
}
if v, err := FileVersion(path); err != nil || v != "v1.0.0" {
t.Fatalf("version = %q err = %v", v, err)
}
changed, err := WriteVersion(path, "v1.1.0")
if err != nil || !changed {
t.Fatalf("write: changed=%v err=%v", changed, err)
}
got := readTestFile(t, path)
want := "version: \"v1.1.0\"\nserver:\n port: 8088\n # a nested word: version: should stay put\nnotes:\n version: nested-untouched\n"
if got != want {
t.Fatalf("file after write:\n%q\nwant:\n%q", got, want)
}
if info, err := os.Stat(path); err != nil || info.Mode().Perm() != originalInfo.Mode().Perm() {
t.Fatalf("mode = %v err = %v, want 0640 preserved", info.Mode(), err)
}
// Idempotent: the same value is not rewritten.
if changed, err := WriteVersion(path, "v1.1.0"); err != nil || changed {
t.Fatalf("rewriting the same value: changed=%v err=%v", changed, err)
}
// No top-level field: insert at the top, nested keys stay untouched.
if err := os.WriteFile(path, []byte("server:\n port: 8088\nnotes:\n version: nested\n"), 0o644); err != nil {
t.Fatal(err)
}
if changed, err := WriteVersion(path, "v1.2.0"); err != nil || !changed {
t.Fatalf("insert: changed=%v err=%v", changed, err)
}
got = readTestFile(t, path)
if !strings.HasPrefix(got, "version: \"v1.2.0\"\n") || !strings.Contains(got, " version: nested") {
t.Fatalf("file after insert:\n%q", got)
}
// A value that would write malformed YAML is refused rather than written.
if _, err := WriteVersion(path, "v1.0.0\"\nserver: hijacked"); err == nil {
t.Fatal("a version containing a quote/newline must be refused")
}
}
func TestWriteVersionPreservesYAMLDocumentStart(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "config.yaml")
original := "---\nserver:\n port: 8088\n"
const originalMode = os.FileMode(0o600)
if err := os.WriteFile(path, []byte(original), originalMode); err != nil {
t.Fatal(err)
}
originalInfo, err := os.Stat(path)
if err != nil {
t.Fatal(err)
}
changed, err := WriteVersion(path, "v1.2.3")
if err != nil || !changed {
t.Fatalf("WriteVersion: changed=%v err=%v", changed, err)
}
got := readTestFile(t, path)
want := "---\nversion: \"v1.2.3\"\nserver:\n port: 8088\n"
if got != want {
t.Fatalf("file after write:\n%q\nwant:\n%q", got, want)
}
if !strings.HasPrefix(got, "---\n") {
t.Fatalf("YAML document start must remain first: %q", got)
}
if version, err := FileVersion(path); err != nil || version != "v1.2.3" {
t.Fatalf("FileVersion = %q, %v; want v1.2.3", version, err)
}
cfg, err := Load(path)
if err != nil {
t.Fatalf("Load after WriteVersion: %v", err)
}
if cfg.Server.Port != 8088 {
t.Fatalf("server.port = %d, want 8088", cfg.Server.Port)
}
info, err := os.Stat(path)
if err != nil {
t.Fatal(err)
}
if info.Mode().Perm() != originalInfo.Mode().Perm() {
t.Fatalf("mode = %v, want %v preserved", info.Mode().Perm(), originalMode)
}
}
// FileVersion 用 YAML 解析(引号键认得出),WriteVersion 若只认顶格裸键,合法配置就会被追加
// 出第二个 version 键、整个文件随后 Load 失败。这条测试钉死两者口径一致,以及"改不了就拒绝写"。
func TestWriteVersionRewritesQuotedKeysAndRefusesWhatItCannot(t *testing.T) {
dir := t.TempDir()
// Legal spellings of the same top-level key: replaced in place, exactly one key left.
for _, original := range []string{
"\"version\": \"v1.0.0\"\nserver:\n port: 8088\n",
"'version': v1.0.0\nserver:\n port: 8088\n",
"\"version\": v1.0.0\nserver:\n port: 8088\n",
} {
path := filepath.Join(dir, "quoted.yaml")
if err := os.WriteFile(path, []byte(original), 0o644); err != nil {
t.Fatal(err)
}
if v, err := FileVersion(path); err != nil || v != "v1.0.0" {
t.Fatalf("FileVersion(%q) = %q, %v", original, v, err)
}
changed, err := WriteVersion(path, "v1.7.22")
if err != nil || !changed {
t.Fatalf("WriteVersion(%q): changed=%v err=%v", original, changed, err)
}
got := readTestFile(t, path)
if strings.Count(got, "version") != 1 {
t.Fatalf("writing %q left %d version keys:\n%q", original, strings.Count(got, "version"), got)
}
if v, err := FileVersion(path); err != nil || v != "v1.7.22" {
t.Fatalf("after writing %q: FileVersion = %q, %v (file %q)", original, v, err, got)
}
if !strings.Contains(got, "port: 8088") {
t.Fatalf("the rest of the file must stay: %q", got)
}
}
// Forms a line-based replacement cannot rewrite: refused with the file untouched. A
// stale version number is a display artifact; a config that no longer loads is an
// installation that no longer starts.
for _, original := range []string{
"{\"version\": \"v1.0.0\", \"server\": {\"port\": 8088}}\n",
"version: >-\n v1.0.0\nserver:\n port: 8088\n",
"\"version\": \"v9.9.9\"\n\"version\": \"v1.0.0\"\n",
} {
path := filepath.Join(dir, "unwritable.yaml")
if err := os.WriteFile(path, []byte(original), 0o644); err != nil {
t.Fatal(err)
}
changed, err := WriteVersion(path, "v1.7.22")
if err == nil {
t.Fatalf("WriteVersion(%q) must refuse instead of writing: changed=%v file=%q", original, changed, readTestFile(t, path))
}
if got := readTestFile(t, path); got != original {
t.Fatalf("a refused write must not touch the file:\nbefore %q\nafter %q", original, got)
}
}
}
func readTestFile(t *testing.T, path string) string {
t.Helper()
data, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
return string(data)
}
func TestWriteVersionAfterCommentedDocumentStart(t *testing.T) {
for _, prefix := range []string{"# local settings\n---\n", "\n# local settings\n--- # config\n", "%YAML 1.1\n---\n"} {
t.Run(prefix, func(t *testing.T) {
path := filepath.Join(t.TempDir(), "config.yaml")
original := prefix + "server:\n port: 8088\n"
if err := os.WriteFile(path, []byte(original), 0600); err != nil {
t.Fatal(err)
}
if changed, err := WriteVersion(path, "v1.2.3"); err != nil || !changed {
t.Fatalf("write: %v %v", changed, err)
}
cfg, err := Load(path)
if err != nil || cfg.Server.Port != 8088 {
t.Fatalf("settings lost after version write: cfg=%+v err=%v", cfg, err)
}
if got := readTestFile(t, path); got != prefix+"version: \"v1.2.3\"\nserver:\n port: 8088\n" {
t.Fatalf("unexpected rewrite: %q", got)
}
})
}
}
func TestWriteVersionRefusesToHideAnInlineYAMLDocument(t *testing.T) {
path := filepath.Join(t.TempDir(), "config.yaml")
original := "--- {server: {port: 8088}}\n"
if err := os.WriteFile(path, []byte(original), 0600); err != nil {
t.Fatal(err)
}
if changed, err := WriteVersion(path, "v1.2.3"); err == nil || changed {
t.Fatalf("must refuse document loss: changed=%v err=%v", changed, err)
}
if got := readTestFile(t, path); got != original {
t.Fatal("refusal modified config")
}
}
func TestVersionWritePreservesConfigSymlink(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("creating symlinks requires privileges on Windows")
}
dir := t.TempDir()
target := filepath.Join(dir, "actual.yaml")
link := filepath.Join(dir, "config.yaml")
original := "server:\n port: 8088\n"
if err := os.WriteFile(target, []byte(original), 0600); err != nil {
t.Fatal(err)
}
if err := os.Symlink(target, link); err != nil {
t.Fatal(err)
}
if _, err := WriteVersion(link, "v1.2.3"); err != nil {
t.Fatal(err)
}
if info, err := os.Lstat(link); err != nil || info.Mode()&os.ModeSymlink == 0 {
t.Fatal("version write replaced config symlink")
}
if version, err := FileVersion(target); err != nil || version != "v1.2.3" {
t.Fatal("version did not reach symlink target")
}
if _, err := RemoveVersion(link); err != nil {
t.Fatal(err)
}
if got := readTestFile(t, target); got != original {
t.Fatal("version removal changed original settings")
}
}

View File

@ -1,7 +1,9 @@
package config
import (
"maps"
"os"
"slices"
"strings"
)
@ -52,6 +54,11 @@ func expandEnvVar(s string) string {
// ExpandConfigEnv 展开 ExternalMCPServerConfig 中所有支持环境变量的字段。
// 展开范围:Command、Args、Env values、URL、Headers values。
func ExpandConfigEnv(cfg *ExternalMCPServerConfig) {
// Config structs are passed by value to background MCP connections. Their
// slices and maps still share storage; expansion must not mutate that storage.
cfg.Args = slices.Clone(cfg.Args)
cfg.Env = maps.Clone(cfg.Env)
cfg.Headers = maps.Clone(cfg.Headers)
cfg.Command = expandEnvVar(cfg.Command)
for i, arg := range cfg.Args {
cfg.Args[i] = expandEnvVar(arg)

View File

@ -79,3 +79,20 @@ func TestExpandConfigEnv(t *testing.T) {
t.Errorf("Headers[Authorization] = %q, want %q", cfg.Headers["Authorization"], "Bearer secret123")
}
}
func TestExpandConfigEnvDoesNotMutateSharedConfig(t *testing.T) {
t.Setenv("CSAI_TEST_EXPAND", "expanded")
original := ExternalMCPServerConfig{
Args: []string{"${CSAI_TEST_EXPAND}"},
Env: map[string]string{"VALUE": "${CSAI_TEST_EXPAND}"},
Headers: map[string]string{"X-Value": "${CSAI_TEST_EXPAND}"},
}
copy := original
ExpandConfigEnv(&copy)
if original.Args[0] != "${CSAI_TEST_EXPAND}" || original.Env["VALUE"] != "${CSAI_TEST_EXPAND}" || original.Headers["X-Value"] != "${CSAI_TEST_EXPAND}" {
t.Fatal("expansion mutated a config shared with another goroutine")
}
if copy.Args[0] != "expanded" || copy.Env["VALUE"] != "expanded" || copy.Headers["X-Value"] != "expanded" {
t.Fatal("copied config was not expanded")
}
}

View File

@ -3,7 +3,6 @@ package handler
import (
"context"
"fmt"
"os"
"path/filepath"
"strings"
"sync"
@ -86,6 +85,7 @@ func TestCreateProgressCallback_HidesInternalEinoDiagnostics(t *testing.T) {
if err != nil {
t.Fatalf("NewDB: %v", err)
}
t.Cleanup(func() { _ = db.Close() })
conv, err := db.CreateConversation("diag-hidden", database.ConversationCreateMeta{})
if err != nil {
t.Fatalf("CreateConversation: %v", err)
@ -133,6 +133,7 @@ func TestCreateProgressCallback_PersistsRunningResponseBeforeDone(t *testing.T)
if err != nil {
t.Fatalf("NewDB: %v", err)
}
t.Cleanup(func() { _ = db.Close() })
conv, err := db.CreateConversation("refresh-running", database.ConversationCreateMeta{})
if err != nil {
t.Fatalf("CreateConversation: %v", err)
@ -178,8 +179,8 @@ func TestCreateProgressCallback_FlushesReasoningOnDone(t *testing.T) {
if err != nil {
t.Fatalf("NewDB: %v", err)
}
defer os.RemoveAll(tmp)
t.Cleanup(func() { _ = db.Close() })
conv, err := db.CreateConversation("test", database.ConversationCreateMeta{})
if err != nil {
t.Fatalf("CreateConversation: %v", err)

View File

@ -1912,6 +1912,27 @@ func (h *ConfigHandler) ApplyConfig(c *gin.Context) {
})
}
// SetUpdateSource 记录一键更新的更新源(单个仓库地址;空 = 回到官方仓库)。
// 走与其他设置相同的写入路径:备份旧文件、按 YAML 文档只改 update 段、原子落盘。
func (h *ConfigHandler) SetUpdateSource(repo string) error {
h.mu.Lock()
defer h.mu.Unlock()
previous := h.config.Update
h.config.Update = config.UpdateConfig{Repo: strings.TrimSpace(repo)}
if err := h.saveConfig(); err != nil {
h.config.Update = previous
return err
}
return nil
}
// UpdateSource 读当前配置的更新源地址(加读锁;更新处理器每次请求现读,保存后立即生效)。
func (h *ConfigHandler) UpdateSource() string {
h.mu.RLock()
defer h.mu.RUnlock()
return h.config.Update.Repo
}
// saveConfig 保存配置到文件
func (h *ConfigHandler) saveConfig() error {
configFileMu.Lock()
@ -1938,6 +1959,7 @@ func (h *ConfigHandler) saveConfig() error {
updateAIConfig(root, h.config.AI)
removeKeyFromMap(root.Content[0], "openai")
updateVisionConfig(root, h.config.Vision)
updateUpdateSourceConfig(root, h.config.Update)
updateFOFAConfig(root, h.config.FOFA)
updateSpaceSearchConfig(root, "zoomeye", h.config.ZoomEye)
updateSpaceSearchConfig(root, "quake", h.config.Quake)
@ -2065,6 +2087,20 @@ func updateMCPConfig(doc *yaml.Node, cfg config.MCPConfig) {
setIntInMap(mcpNode, "port", cfg.Port)
}
// updateUpdateSourceConfig 写入一键更新的更新源(update 段的单个 repo 字段)。
// 留空时把整段删掉,而不是留下一个空的 update: 块——"没有配置"应当就是文件里没有这一段,
// 运行时按官方仓库处理。
func updateUpdateSourceConfig(doc *yaml.Node, cfg config.UpdateConfig) {
root := doc.Content[0]
repo := strings.TrimSpace(cfg.Repo)
if repo == "" {
removeKeyFromMap(root, "update")
return
}
node := ensureMap(root, "update")
setStringInMap(node, "repo", repo)
}
func updateVisionConfig(doc *yaml.Node, cfg config.VisionConfig) {
root := doc.Content[0]
visionNode := ensureMap(root, "vision")

View File

@ -172,13 +172,6 @@ func (h *ExternalMCPHandler) AddOrUpdateExternalMCP(c *gin.Context) {
h.mu.Lock()
defer h.mu.Unlock()
// 添加或更新配置
if err := h.manager.AddOrUpdateConfig(name, req.Config); err != nil {
h.logger.Error("添加或更新外部MCP配置失败", zap.Error(err))
c.JSON(http.StatusInternalServerError, gin.H{"error": "添加或更新配置失败: " + err.Error()})
return
}
// 更新内存中的配置
if h.config.ExternalMCP.Servers == nil {
h.config.ExternalMCP.Servers = make(map[string]config.ExternalMCPServerConfig)
@ -197,6 +190,13 @@ func (h *ExternalMCPHandler) AddOrUpdateExternalMCP(c *gin.Context) {
// 展开 ${VAR} 环境变量
config.ExpandConfigEnv(&cfg)
// 添加或更新配置
if err := h.manager.AddOrUpdateConfig(name, cfg); err != nil {
h.logger.Error("添加或更新外部MCP配置失败", zap.Error(err))
c.JSON(http.StatusInternalServerError, gin.H{"error": "添加或更新配置失败: " + err.Error()})
return
}
h.config.ExternalMCP.Servers[name] = cfg
// 保存到配置文件

View File

@ -56,6 +56,34 @@ func cleanupTestConfig(configPath string) {
os.Remove(configPath + ".backup")
}
func TestExternalMCPConnectionReceivesExpandedSnapshot(t *testing.T) {
t.Setenv("CSAI_TEST_MCP_COMMAND", "not-executed")
t.Setenv("CSAI_TEST_MCP_VALUE", "expanded-test-value")
router, h, configPath := setupTestRouter()
defer cleanupTestConfig(configPath)
body, err := json.Marshal(AddOrUpdateExternalMCPRequest{Config: config.ExternalMCPServerConfig{
Command: "${CSAI_TEST_MCP_COMMAND}", Args: []string{"${CSAI_TEST_MCP_VALUE}"}, Disabled: true,
Env: map[string]string{"VALUE": "${CSAI_TEST_MCP_VALUE}"}, Headers: map[string]string{"X-Value": "${CSAI_TEST_MCP_VALUE}"},
}})
if err != nil {
t.Fatal(err)
}
req := httptest.NewRequest(http.MethodPut, "/api/external-mcp/test-env", bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("save: %d %s", w.Code, w.Body)
}
cfg := h.manager.GetConfigs()["test-env"]
if cfg.Command != "not-executed" || len(cfg.Args) != 1 || cfg.Args[0] != "expanded-test-value" || cfg.Env["VALUE"] != "expanded-test-value" || cfg.Headers["X-Value"] != "expanded-test-value" {
t.Fatalf("connection received unexpanded snapshot: %#v", cfg)
}
if !cfg.Disabled || cfg.ExternalMCPEnable {
t.Fatal("disabled connection was activated")
}
}
func TestExternalMCPHandler_AddOrUpdateExternalMCP_Stdio(t *testing.T) {
router, _, configPath := setupTestRouter()
defer cleanupTestConfig(configPath)

View File

@ -153,7 +153,8 @@ SELECT msg.id, msg.conversation_id,
SELECT MIN(later.created_at)
FROM messages later
WHERE later.conversation_id = msg.conversation_id
AND later.created_at > msg.created_at
AND (later.created_at > msg.created_at
OR (later.created_at = msg.created_at AND later.rowid > msg.rowid))
), (
SELECT MAX(pd.created_at)
FROM process_details pd
@ -177,7 +178,8 @@ WHERE msg.role = 'assistant'
OR EXISTS (
SELECT 1 FROM messages later
WHERE later.conversation_id = msg.conversation_id
AND later.created_at > msg.created_at
AND (later.created_at > msg.created_at
OR (later.created_at = msg.created_at AND later.rowid > msg.rowid))
)
)`)
if err != nil {

View File

@ -1,7 +1,6 @@
package handler
import (
"os"
"path/filepath"
"testing"
@ -16,7 +15,7 @@ func TestEnrichHitlApprovalPayload(t *testing.T) {
if err != nil {
t.Fatalf("db: %v", err)
}
defer os.RemoveAll(tmp)
t.Cleanup(func() { _ = db.Close() })
conv, err := db.CreateConversation("hitl ctx", database.ConversationCreateMeta{})
if err != nil {

View File

@ -98,9 +98,16 @@ func TestEnsureSchemaFinalizesOnlyHistoricalPlaceholdersWithTerminalEvidence(t *
if err != nil {
t.Fatalf("create superseded placeholder: %v", err)
}
if _, err := db.AddMessage(supersededConversation.ID, "user", "继续", nil); err != nil {
later, err := db.AddMessage(supersededConversation.ID, "user", "继续", nil)
if err != nil {
t.Fatalf("create later message: %v", err)
}
// Coarse clocks (notably Windows) can give consecutive messages the same
// timestamp. Match the message ordering used by GetMessages: time, then rowid.
if _, err := db.Exec(`UPDATE messages SET created_at =
(SELECT created_at FROM messages WHERE id = ?) WHERE id = ?`, superseded.ID, later.ID); err != nil {
t.Fatalf("give consecutive messages equal timestamps: %v", err)
}
timeoutConversation, err := db.CreateConversation("timeout placeholder", database.ConversationCreateMeta{})
if err != nil {
@ -136,10 +143,18 @@ func TestEnsureSchemaFinalizesOnlyHistoricalPlaceholdersWithTerminalEvidence(t *
if err != nil {
t.Fatalf("create active conversation: %v", err)
}
earlier, err := db.AddMessage(activeConversation.ID, "user", "开始", nil)
if err != nil {
t.Fatalf("create preceding message: %v", err)
}
potentiallyActive, err := db.AddMessage(activeConversation.ID, "assistant", "处理中...", nil)
if err != nil {
t.Fatalf("create potentially active placeholder: %v", err)
}
if _, err := db.Exec(`UPDATE messages SET created_at =
(SELECT created_at FROM messages WHERE id = ?) WHERE id = ?`, potentiallyActive.ID, earlier.ID); err != nil {
t.Fatalf("give preceding message equal timestamp: %v", err)
}
if err := manager.EnsureSchema(); err != nil {
t.Fatalf("reconcile historical placeholders: %v", err)

View File

@ -3418,6 +3418,59 @@ func (h *OpenAPIHandler) GetOpenAPISpec(c *gin.Context) {
},
},
},
"/api/system/update/source": map[string]interface{}{
"post": map[string]interface{}{
"tags": []string{"系统更新"},
"summary": "配置更新源(本安装从哪个仓库更新)",
"description": "把更新源写进 config.yaml 的 update 段:单个 repo 字段(仓库地址),更新跟随该仓库的默认分支。留空(或写空串)= 回到官方仓库 https://github.com/AIPentest/CyberStrikeAI.git。地址白名单为 https/http/ssh/git/file:// 与本机绝对路径(git 的 ext:: 传输会执行命令,一律拒绝)。",
"operationId": "saveUpdateSource",
"requestBody": map[string]interface{}{
"content": map[string]interface{}{
"application/json": map[string]interface{}{
"schema": map[string]interface{}{
"type": "object",
"properties": map[string]interface{}{
"repo": map[string]interface{}{"type": "string", "description": "更新源仓库地址;留空 = 官方仓库"},
},
},
},
},
},
"responses": map[string]interface{}{
"200": map[string]interface{}{"description": "已保存(返回配置值与官方默认地址)"},
"400": map[string]interface{}{"description": "仓库地址不合法"},
"401": map[string]interface{}{"description": "未授权"},
},
},
},
"/api/system/update/adopt": map[string]interface{}{
"post": map[string]interface{}{
"tags": []string{"系统更新"},
"summary": "把非 git 目录接入更新源",
"description": "解压/打包安装所在的目录接入配置好的更新源(未配置 = 官方仓库):不带 confirm 做无副作用预览(在临时仓库里 fetch,列出会被目标版本替换的文件与会保留的运维者内容);confirm=true 时异步执行(202 + job_id,用 /api/system/update/job 轮询):git init、添加 origin、落地更新源默认分支的内容,运维者内容先暂存再放回,被替换的文件全部留底到 .update-backup/<时间戳>/overwritten/。已是 git 工作树时返回 409(用一键更新而不是接入)。",
"operationId": "adoptUpdateSource",
"requestBody": map[string]interface{}{
"content": map[string]interface{}{
"application/json": map[string]interface{}{
"schema": map[string]interface{}{
"type": "object",
"properties": map[string]interface{}{
"confirm": map[string]interface{}{"type": "boolean", "description": "false/缺省=只预览;true=确认执行"},
"restart": map[string]interface{}{"type": "boolean", "description": "接入成功后退出进程交给外部守护拉起,默认 false"},
},
},
},
},
},
"responses": map[string]interface{}{
"200": map[string]interface{}{"description": "预览结果(plan:将被替换/保留的文件清单与总数)"},
"202": map[string]interface{}{"description": "接入任务已受理,返回 job_id"},
"400": map[string]interface{}{"description": "更新源地址不合法,或要求重启但没有重启钩子"},
"409": map[string]interface{}{"description": "目录已是 git 工作树;或有任务在进行中"},
"401": map[string]interface{}{"description": "未授权"},
},
},
},
"/api/config": map[string]interface{}{
"get": map[string]interface{}{
"tags": []string{"配置管理"},
@ -6449,6 +6502,110 @@ func (h *OpenAPIHandler) GetOpenAPISpec(c *gin.Context) {
},
},
},
"/api/system/update": map[string]interface{}{
"get": map[string]interface{}{
"tags": []string{"系统更新"},
"summary": "查看本安装的源码版本",
"description": "读取安装目录自己的 git 工作树(分支、远端、当前提交、本地改动、是否有 Go 工具链、是否有可回滚点),不发起任何网络请求",
"operationId": "getUpdateStatus",
"responses": map[string]interface{}{
"200": map[string]interface{}{
"description": "安装状态与最近一次更新任务",
},
"401": map[string]interface{}{
"description": "未授权",
},
},
},
},
"/api/system/update/check": map[string]interface{}{
"post": map[string]interface{}{
"tags": []string{"系统更新"},
"summary": "检查本安装的更新源有无新提交",
"description": "对配置的更新源仓库(未配置 = 官方仓库 https://github.com/AIPentest/CyberStrikeAI.git)的默认分支执行 fetch,报告落后/领先提交数与新提交列表。检查失败返回 200 且带 checkError,不把「查不了」说成「已是最新」",
"operationId": "checkUpdate",
"responses": map[string]interface{}{
"200": map[string]interface{}{
"description": "检查结果(含 checkError 时为检查未成功)",
},
"401": map[string]interface{}{
"description": "未授权",
},
},
},
},
"/api/system/update/apply": map[string]interface{}{
"post": map[string]interface{}{
"tags": []string{"系统更新"},
"summary": "一键更新源码并重编译",
"description": "快进到更新源仓库默认分支的最新提交、重新编译二进制并原子换入(旧二进制留作 .prev 以便回滚)。本机改过源码文件或分支已分叉时拒绝执行并点名;roles/skills/tools/agents/bundles/knowledge_base/data/config.yaml 等运维者内容在合并前暂存、合并后放回,被保留的文件列在 keptContent。请求立即返回 job_id,进度用 GET /api/system/update/job 轮询;已有任务在跑时返回 409",
"operationId": "applyUpdate",
"requestBody": map[string]interface{}{
"content": map[string]interface{}{
"application/json": map[string]interface{}{
"schema": map[string]interface{}{
"type": "object",
"properties": map[string]interface{}{
"restart": map[string]interface{}{
"type": "boolean",
"description": "更新成功后优雅关闭并退出进程;只在有外部守护时才会被拉起,默认 false",
},
},
},
},
},
},
"responses": map[string]interface{}{
"202": map[string]interface{}{
"description": "任务已受理,返回 job_id",
},
"400": map[string]interface{}{
"description": "请求体不合法,或要求重启但本次启动没有装配重启钩子",
},
"409": map[string]interface{}{
"description": "已有一次更新在进行中",
},
"401": map[string]interface{}{
"description": "未授权",
},
},
},
},
"/api/system/update/job": map[string]interface{}{
"get": map[string]interface{}{
"tags": []string{"系统更新"},
"summary": "查看更新任务进度",
"description": "返回正在运行或最近一次更新任务的状态、逐行进度 steps、结果 result 与失败 failure;从未更新过时 job 为 null",
"operationId": "getUpdateJob",
"responses": map[string]interface{}{
"200": map[string]interface{}{
"description": "任务状态",
},
"401": map[string]interface{}{
"description": "未授权",
},
},
},
},
"/api/system/update/rollback": map[string]interface{}{
"post": map[string]interface{}{
"tags": []string{"系统更新"},
"summary": "回滚到本次更新之前",
"description": "撤到上一次更新记录里的旧提交,并换回换入前保留的旧二进制。自那次更新之后 HEAD 已经变化、或本机有源码改动时返回 409 拒绝,而不是丢弃更新之后的工作",
"operationId": "rollbackUpdate",
"responses": map[string]interface{}{
"200": map[string]interface{}{
"description": "已回滚",
},
"409": map[string]interface{}{
"description": "没有可回滚的记录、更新进行中、或更新之后 HEAD 已被移动",
},
"401": map[string]interface{}{
"description": "未授权",
},
},
},
},
},
}

View File

@ -50,6 +50,10 @@ func toolGuardRequest(t *testing.T, handler gin.HandlerFunc, body interface{}) *
func TestToolGuardSavePersistsAndAppliesWithoutChangingHITL(t *testing.T) {
h := newToolGuardTestHandler(t)
before, err := os.Stat(h.configPath)
if err != nil {
t.Fatal(err)
}
cfg := toolguard.DefaultConfig()
cfg.Rules[0].Message = "识别到 {match},禁止攻击政府网站,请检查目标。"
w := toolGuardRequest(t, h.UpdateToolGuard, cfg)
@ -68,7 +72,7 @@ func TestToolGuardSavePersistsAndAppliesWithoutChangingHITL(t *testing.T) {
}
info, _ := os.Stat(h.configPath)
data, _ := os.ReadFile(h.configPath)
if info.Mode().Perm() != 0600 || !strings.Contains(string(data), "# keep this comment") {
if info.Mode().Perm() != before.Mode().Perm() || !strings.Contains(string(data), "# keep this comment") {
t.Fatal("file permissions or comments were lost")
}
match := h.toolGuard.Check("scan", map[string]interface{}{"target": "agency.gov.cn"})

534
internal/handler/update.go Normal file
View File

@ -0,0 +1,534 @@
package handler
import (
"context"
"cyberstrike-ai/internal/audit"
"cyberstrike-ai/internal/update"
"fmt"
"net/http"
"os"
"strings"
"sync"
"time"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
)
// updateRestartDelay is how long a stand-down waits after the response is written: the
// page that asked for the restart gets one more poll window to read the final state
// before the process it is watching goes away. A variable so tests do not sleep for it.
var updateRestartDelay = 2 * time.Second
// UpdateHandler is the "update my own source" surface: what this installation is, what
// its remote has that it does not, and one action that moves the tree and rebuilds the
// binary.
//
// It exists because the alternative was a shell script pointed at one fixed upstream
// repository, which for anyone running a fork meant "downgrade yourself to somebody
// else's code". Here the remote is whatever this directory already tracks, and the person
// at the keyboard never types git or go build.
type UpdateHandler struct {
root string // the installation to update: the directory the config file lives in
logger *zap.Logger
audit *audit.Service
// restart is the operator's own shutdown hook. It is only ever called when the
// request asked for a restart, because an unsupervised process that exits stays
// exited - "I restarted you" would be a lie on most deployments.
restart func()
// source reports the configured update source (config.yaml update.repo) as the
// operator last saved it; an empty string means "not configured" and the official
// repository is used. A function rather than a value because the config can change
// while the process runs.
source func() string
// saveSource persists a new source through the config layer; nil means this start
// has no config to write to.
saveSource func(repo string) error
// baseline is the binary this process is actually running: the file on disk at
// construction time. An update, a rollback or a CLI run that replaces it leaves a
// different file behind, and that difference is what "restart to activate" means.
baseline update.BinaryStamp
mu sync.Mutex
jobs map[string]*updateJob
order []string
active string
}
// updateJob is one running or finished apply. A build takes minutes, so the request
// returns a handle and the page polls it rather than sitting in one HTTP call until the
// compiler finishes.
type updateJob struct {
ID string `json:"id"`
Kind string `json:"kind"` // apply | adopt
State string `json:"state"` // running | succeeded | failed
Started string `json:"started"`
Finished string `json:"finished,omitempty"`
Steps []update.Step `json:"steps"`
Result *update.Result `json:"result,omitempty"`
Failure *update.Error `json:"failure,omitempty"`
Restart bool `json:"restartRequested"`
}
// view copies a job for transport, because its fields are written by the job's own
// goroutine: a response must never serialize the live struct. Callers hold h.mu.
func (j *updateJob) view() *updateJob {
out := *j
out.Steps = append([]update.Step{}, j.Steps...)
return &out
}
// NewUpdateHandler takes the audit service as a constructor argument rather than through
// a SetAudit the assembly has to remember: forgetting here is a compile error instead of
// a privileged endpoint that writes no audit records at all.
func NewUpdateHandler(root string, logger *zap.Logger, auditSvc *audit.Service, restart func(),
source func() string, saveSource func(repo string) error) *UpdateHandler {
return &UpdateHandler{
root: root,
logger: logger,
audit: auditSvc,
restart: restart,
source: source,
saveSource: saveSource,
baseline: update.StampBinary(root, update.Options{Root: root}),
jobs: map[string]*updateJob{},
}
}
// restartPending reports whether the binary on disk is no longer the one this process is
// running, and when that binary was built (empty when there is nothing on disk to run).
func (h *UpdateHandler) restartPending() (bool, string) {
stamp := update.StampBinary(h.root, h.options())
if stamp.Same(h.baseline) {
return false, ""
}
builtAt := ""
if stamp.Exists {
builtAt = stamp.ModTime.Format(time.RFC3339)
}
return true, builtAt
}
// restartSupervised reports whether something outside this process is set up to bring it
// back: launchd (XPC_SERVICE_NAME) and systemd (INVOCATION_ID / JOURNAL_STREAM) both leave
// a marker in the environment. It is only the page's default for the restart tick - the
// operator's own checkbox remains the decision.
func restartSupervised() bool {
return strings.TrimSpace(os.Getenv("XPC_SERVICE_NAME")) != "" ||
strings.TrimSpace(os.Getenv("INVOCATION_ID")) != "" ||
strings.TrimSpace(os.Getenv("JOURNAL_STREAM")) != ""
}
func (h *UpdateHandler) options() update.Options {
opts := update.Options{Root: h.root}
if h.source != nil {
opts.Repo = h.source()
}
return opts
}
// sourceView is the configured source as the page edits it: the address (empty = the
// official repository) plus the default, so the page never hardcodes a URL the server
// would disagree with.
func (h *UpdateHandler) sourceView() gin.H {
repo := ""
if h.source != nil {
repo = strings.TrimSpace(h.source())
}
return gin.H{
"repo": repo,
"configured": repo != "",
"defaultRepo": update.DefaultRepoURL,
}
}
// GetStatus answers GET /api/system/update: the install tree as it is on disk, without a
// network round trip, so opening the page is never gated on GitHub being reachable.
func (h *UpdateHandler) GetStatus(c *gin.Context) {
snap, err := update.Status(c.Request.Context(), h.options())
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
needsRestart, binaryBuiltAt := h.restartPending()
c.JSON(http.StatusOK, gin.H{
"status": snap,
"job": h.latest(),
"canRestart": h.restart != nil,
"supervised": restartSupervised(),
"needsRestart": needsRestart,
"binaryBuiltAt": binaryBuiltAt,
"source": h.sourceView(),
})
}
// Check answers POST /api/system/update/check: fetch the tracked branch and report the
// gap. A failed fetch is a 200 with checkError, not a 500 - "offline" and "bad token"
// are answers the operator needs to read, not server faults to debug.
func (h *UpdateHandler) Check(c *gin.Context) {
snap, err := update.Check(c.Request.Context(), h.options())
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
h.record(c, "update.check", resultOf(snap.CheckError), fmt.Sprintf("检查更新:%s(默认分支 %s)", snap.Repo, snap.TargetBranch), map[string]interface{}{
"commit": snap.Commit, "remote_commit": snap.RemoteCommit, "behind": snap.Behind, "error": snap.CheckError,
})
c.JSON(http.StatusOK, gin.H{"status": snap})
}
// SaveSource answers POST /api/system/update/source: the operator picks which repository
// this installation updates from - the official one, a mirror, or their own fork - and
// the choice lands in the update section of config.yaml. An empty address clears the
// setting, which means the official repository again.
func (h *UpdateHandler) SaveSource(c *gin.Context) {
var body struct {
Repo string `json:"repo"`
}
if err := c.ShouldBindJSON(&body); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "请求体不是合法 JSON"})
return
}
body.Repo = strings.TrimSpace(body.Repo)
if body.Repo != "" && !update.ValidRemoteURL(body.Repo) {
c.JSON(http.StatusBadRequest, gin.H{"error": "仓库地址不合法(只允许 https/http/ssh/git/file:// 或本机绝对路径)"})
return
}
if h.saveSource == nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "本次启动没有接入配置保存,更新源改不了"})
return
}
release, err := update.LockInstall(h.options())
if err != nil {
c.JSON(statusForError(err), errorBody(err))
return
}
defer release()
if busy := h.activeJob(); busy != nil {
c.JSON(http.StatusConflict, gin.H{"error": "更新进行中,不能切换更新源", "job": busy})
return
}
if err := h.saveSource(body.Repo); err != nil {
h.record(c, "update.source", "failure", "保存更新源失败: "+err.Error(), map[string]interface{}{"error": err.Error()})
c.JSON(http.StatusInternalServerError, gin.H{"error": "保存失败:" + err.Error()})
return
}
message := "更新源已保存:" + body.Repo
if body.Repo == "" {
message = "已恢复默认更新源(官方仓库)"
}
h.record(c, "update.source", "success", message, map[string]interface{}{"repo": body.Repo})
c.JSON(http.StatusOK, gin.H{"source": h.sourceView()})
}
// Adopt answers POST /api/system/update/adopt. Without confirm it is a side-effect-free
// preview (the fetch happens in a throwaway repository outside the install tree); with
// confirm it starts the same kind of job an update does.
func (h *UpdateHandler) Adopt(c *gin.Context) {
var body struct {
Confirm bool `json:"confirm"`
Restart bool `json:"restart"`
}
if c.Request.ContentLength > 0 {
if err := c.ShouldBindJSON(&body); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "请求体不是合法 JSON"})
return
}
}
if body.Confirm && body.Restart && h.restart == nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "本次启动没有提供重启钩子,接入完成后请由外部进程管理器重启服务"})
return
}
if !body.Confirm {
plan, err := update.Preview(c.Request.Context(), h.options())
if err != nil {
h.record(c, "update.adopt", "failure", "接入预览失败: "+err.Error(), map[string]interface{}{"error": errMessage(err)})
c.JSON(statusForError(err), errorBody(err))
return
}
c.JSON(http.StatusOK, gin.H{"plan": plan})
return
}
job, started := h.startJob("adopt", body.Restart)
if !started {
c.JSON(http.StatusConflict, gin.H{"error": "已有一次更新在进行中", "job": job})
return
}
h.record(c, "update.adopt", "started", "开始把目录接入更新源", map[string]interface{}{"job": job.ID, "restart": body.Restart})
c.JSON(http.StatusAccepted, gin.H{"job_id": job.ID, "state": job.State})
}
// Apply answers POST /api/system/update/apply. It starts one job and returns immediately;
// a second concurrent apply is refused, because two processes moving the same working
// tree and swapping the same binary is how an installation becomes unrecoverable.
func (h *UpdateHandler) Apply(c *gin.Context) {
var body struct {
Restart bool `json:"restart"`
}
if c.Request.ContentLength > 0 {
if err := c.ShouldBindJSON(&body); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "请求体不是合法 JSON"})
return
}
}
if body.Restart && h.restart == nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "本次启动没有提供重启钩子,更新完成后请由外部进程管理器重启服务"})
return
}
job, started := h.startJob("apply", body.Restart)
if !started {
c.JSON(http.StatusConflict, gin.H{"error": "已有一次更新在进行中", "job": job})
return
}
h.record(c, "update.apply", "started", "开始一键更新源码并重编译", map[string]interface{}{"job": job.ID, "restart": body.Restart})
c.JSON(http.StatusAccepted, gin.H{"job_id": job.ID, "state": job.State})
}
// Restart answers POST /api/system/update/restart: stand this process down so the binary
// already on disk - an update or a rollback that ran without one - becomes the thing
// answering requests. It refuses when there is nothing to activate, because a bounce that
// cannot change anything is a dropped service for no reason.
func (h *UpdateHandler) Restart(c *gin.Context) {
release, err := update.LockInstall(h.options())
if err != nil {
c.JSON(statusForError(err), errorBody(err))
return
}
scheduled := false
defer func() {
if !scheduled {
release()
}
}()
if busy := h.activeJob(); busy != nil {
c.JSON(http.StatusConflict, gin.H{"error": "更新进行中,等它结束再重启", "job": busy})
return
}
if h.restart == nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "本次启动没有提供重启钩子,请由外部进程管理器重启服务"})
return
}
if needsRestart, _ := h.restartPending(); !needsRestart {
c.JSON(http.StatusConflict, gin.H{"error": "磁盘上的二进制与当前进程一致,没有待生效的版本", "reason": "nothing_pending"})
return
}
if !update.StampBinary(h.root, h.options()).Exists {
c.JSON(http.StatusConflict, gin.H{"error": "磁盘上的二进制不存在,无法重启", "reason": "no_binary"})
return
}
h.record(c, "update.restart", "started", "重启安装以运行磁盘上的新二进制", nil)
c.JSON(http.StatusAccepted, gin.H{"restarting": true})
scheduled = true
time.AfterFunc(updateRestartDelay, func() { defer release(); h.restart() })
}
// Job answers GET /api/system/update/job: the running job, or the most recent one, with
// every progress line so far.
func (h *UpdateHandler) Job(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"job": h.latest()})
}
// Rollback answers POST /api/system/update/rollback: back to the commit the last update
// came from, with the binary kept before the swap. It refuses when HEAD has moved since
// that update, rather than resetting away work nobody asked it to touch.
func (h *UpdateHandler) Rollback(c *gin.Context) {
if busy := h.activeJob(); busy != nil {
c.JSON(http.StatusConflict, gin.H{"error": "更新进行中,不能同时回滚", "job": busy})
return
}
res, err := update.Rollback(c.Request.Context(), h.options())
if err != nil {
h.record(c, "update.rollback", "failure", "回滚失败: "+err.Error(), map[string]interface{}{"error": errMessage(err)})
c.JSON(statusForError(err), errorBody(err))
return
}
h.record(c, "update.rollback", "success", fmt.Sprintf("已回滚到 %s", res.ToCommit), map[string]interface{}{
"from": res.FromCommit, "to": res.ToCommit,
})
c.JSON(http.StatusOK, gin.H{"result": res})
}
func (h *UpdateHandler) startJob(kind string, restart bool) (*updateJob, bool) {
h.mu.Lock()
if h.active != "" {
return h.jobs[h.active].view(), false
}
job := &updateJob{
ID: fmt.Sprintf("upd-%d", time.Now().UnixNano()),
Kind: kind,
State: "running",
Started: time.Now().Format(time.RFC3339),
Restart: restart,
}
h.jobs[job.ID] = job
h.order = append(h.order, job.ID)
for len(h.order) > 20 {
oldest := h.order[0]
h.order = h.order[1:]
if oldest != h.active {
delete(h.jobs, oldest)
}
}
h.active = job.ID
snapshot := job.view()
opts := h.options()
h.mu.Unlock()
// The update outlives its HTTP request on purpose: the caller gets a handle, and a
// browser that closes the tab must not cancel a merge halfway through. Once the
// working tree has moved there is no going back, so the context is generous with
// time instead of inheriting the request's deadline.
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 45*time.Minute)
defer cancel()
onStep := func(s update.Step) {
h.mu.Lock()
job.Steps = append(job.Steps, s)
h.mu.Unlock()
if h.logger != nil {
h.logger.Info("更新进度", zap.String("phase", s.Phase), zap.String("message", s.Message))
}
}
var run func(context.Context, update.Options, func(update.Step)) (*update.Result, error) = update.Apply
if kind == "adopt" {
run = update.Adopt
}
res, err := run(ctx, opts, onStep)
finish := "succeeded"
if err != nil {
finish = "failed"
}
h.mu.Lock()
job.Result = res
if ue, ok := asUpdateError(err); ok {
job.Failure = ue
} else if err != nil {
job.Failure = &update.Error{Reason: "error", Message: err.Error()}
}
job.State = finish
job.Finished = time.Now().Format(time.RFC3339)
if job.Restart && finish == "succeeded" && res != nil && res.BinaryBuilt && h.restart != nil {
release, lockErr := update.LockInstall(opts)
if lockErr == nil {
h.mu.Unlock()
// Keep both CLI and HTTP writers out until the old process exits.
time.AfterFunc(updateRestartDelay, func() {
defer release()
defer func() { h.mu.Lock(); h.active = ""; h.mu.Unlock() }()
h.restart()
})
return
}
// Another process began an operation after the build. The binary is
// ready, but shutting down now would interrupt that operation.
job.Restart = false
}
h.active = ""
h.mu.Unlock()
}()
return snapshot, true
}
func (h *UpdateHandler) activeJob() *updateJob {
h.mu.Lock()
defer h.mu.Unlock()
if h.active == "" {
return nil
}
if job := h.jobs[h.active]; job != nil {
return job.view()
}
return nil
}
func (h *UpdateHandler) latest() *updateJob {
h.mu.Lock()
defer h.mu.Unlock()
if len(h.order) == 0 {
return nil
}
if job := h.jobs[h.order[len(h.order)-1]]; job != nil {
return job.view()
}
return nil
}
func (h *UpdateHandler) record(c *gin.Context, action, result, message string, detail map[string]interface{}) {
if h.audit == nil {
return
}
h.audit.Record(c, audit.Entry{
Level: auditLevelFor(result),
Category: "update",
Action: action,
Result: result,
Message: message,
ResourceType: "system",
ResourceID: h.root,
Detail: detail,
})
}
func auditLevelFor(result string) string {
if result == "failure" {
return "error"
}
return "info"
}
func resultOf(checkError string) string {
if checkError != "" {
return "failure"
}
return "success"
}
func asUpdateError(err error) (*update.Error, bool) {
if err == nil {
return nil, false
}
if ue, ok := err.(*update.Error); ok {
return ue, true
}
return nil, false
}
func errMessage(err error) string {
if err == nil {
return ""
}
return err.Error()
}
// statusForError keeps a refusal distinguishable from an accident: the precondition
// failures are the ones the page can act on (409), while anything else is a bad request it
// can show. No case maps a refusal onto a 2xx - a status that reads as accepted would
// contradict the failure the same response carries, and an asynchronous update never asks
// this function (the job's own state says whether it worked).
func statusForError(err error) int {
ue, ok := asUpdateError(err)
if !ok {
return http.StatusInternalServerError
}
switch ue.Reason {
case "local_source_edits", "diverged", "no_state", "moved_since_update", "no_binary", "already_a_repo", "update_busy", "content_path_conflict", "existing_git_metadata":
return http.StatusConflict
default:
return http.StatusBadRequest
}
}
func errorBody(err error) gin.H {
body := gin.H{"error": errMessage(err)}
if ue, ok := asUpdateError(err); ok {
body["reason"] = ue.Reason
if len(ue.Items) > 0 {
body["items"] = ue.Items
}
}
return body
}

View File

@ -0,0 +1,436 @@
package handler
import (
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"time"
"cyberstrike-ai/internal/config"
"cyberstrike-ai/internal/update"
"github.com/gin-gonic/gin"
)
// writeFakeBinary puts an executable-shaped file where update.StampBinary looks, so the
// "the process is running an older build than the disk" state can be produced for real.
func writeFakeBinary(t *testing.T, root, content string) {
t.Helper()
if err := os.WriteFile(filepath.Join(root, update.Binary), []byte(content), 0o755); err != nil {
t.Fatal(err)
}
}
// The HTTP contract of "update my own source in one click": status without a network
// round trip, an apply that returns a job handle instead of blocking a request open for
// the length of a compile, and refusals that stay distinguishable from accidents.
func newUpdateRouter(root string, restart func()) (*gin.Engine, *UpdateHandler) {
return newUpdateRouterWithSource(root, restart, nil, nil)
}
func newUpdateRouterWithSource(root string, restart func(),
source func() string, save func(string) error) (*gin.Engine, *UpdateHandler) {
gin.SetMode(gin.TestMode)
h := NewUpdateHandler(root, nil, nil, restart, source, save)
router := gin.New()
router.GET("/api/system/update", h.GetStatus)
router.GET("/api/system/update/job", h.Job)
router.POST("/api/system/update/check", h.Check)
router.POST("/api/system/update/apply", h.Apply)
router.POST("/api/system/update/restart", h.Restart)
router.POST("/api/system/update/rollback", h.Rollback)
router.POST("/api/system/update/adopt", h.Adopt)
router.POST("/api/system/update/source", h.SaveSource)
return router, h
}
func doUpdate(router *gin.Engine, method, path, body string) *httptest.ResponseRecorder {
var reader *strings.Reader
if body == "" {
reader = strings.NewReader("")
} else {
reader = strings.NewReader(body)
}
req := httptest.NewRequest(method, path, reader)
if body != "" {
req.Header.Set("Content-Type", "application/json")
}
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
return w
}
func TestUpdateStatusIsServedWithoutTouchingTheNetwork(t *testing.T) {
router, _ := newUpdateRouter(t.TempDir(), nil)
w := doUpdate(router, http.MethodGet, "/api/system/update", "")
if w.Code != http.StatusOK {
t.Fatalf("status = %d body = %s", w.Code, w.Body)
}
var body struct {
Status struct {
Root string `json:"root"`
Installed bool `json:"installed"`
CheckError string `json:"checkError"`
CanBuild bool `json:"canBuild"`
} `json:"status"`
Job *struct{ ID string } `json:"job"`
CanRestart bool `json:"canRestart"`
}
if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {
t.Fatal(err)
}
if body.Status.Root == "" || body.Status.Installed {
t.Errorf("a plain directory must report its root and that it is not a git tree: %+v", body.Status)
}
if body.Status.CheckError == "" {
t.Error("the reason an update cannot run must be readable on the page, not just a status code")
}
if body.Job != nil {
t.Error("job must be null before anything has been applied")
}
if body.CanRestart {
t.Error("canRestart must be false when no restart hook was wired")
}
}
func TestUpdateApplyReturnsAJobAndReportsAnHonestFailure(t *testing.T) {
router, _ := newUpdateRouter(t.TempDir(), nil)
w := doUpdate(router, http.MethodPost, "/api/system/update/apply", `{"restart":false}`)
if w.Code != http.StatusAccepted {
t.Fatalf("apply should be accepted and return a handle, got %d %s", w.Code, w.Body)
}
var started struct {
JobID string `json:"job_id"`
State string `json:"state"`
}
if err := json.Unmarshal(w.Body.Bytes(), &started); err != nil {
t.Fatal(err)
}
if started.JobID == "" {
t.Fatal("apply must return the job id the page polls")
}
// The job runs against a non-git directory, so it finishes with a refusal rather
// than a merge. What matters is that the reported failure is the real reason.
deadline := time.Now().Add(10 * time.Second)
var finished struct {
Job struct {
State string `json:"state"`
Failure struct {
Reason string `json:"reason"`
} `json:"failure"`
} `json:"job"`
}
for time.Now().Before(deadline) {
w = doUpdate(router, http.MethodGet, "/api/system/update/job", "")
if err := json.Unmarshal(w.Body.Bytes(), &finished); err != nil {
t.Fatal(err)
}
if finished.Job.State != "running" {
break
}
time.Sleep(20 * time.Millisecond)
}
if finished.Job.State != "failed" {
t.Fatalf("job state = %q, want failed for a non-git install", finished.Job.State)
}
if finished.Job.Failure.Reason != "not_a_repo" {
t.Errorf("failure reason = %q, want not_a_repo", finished.Job.Failure.Reason)
}
}
func TestUpdateApplyRefusesRestartWhenNothingCanStartTheProcessAgain(t *testing.T) {
router, _ := newUpdateRouter(t.TempDir(), nil)
w := doUpdate(router, http.MethodPost, "/api/system/update/apply", `{"restart":true}`)
if w.Code != http.StatusBadRequest {
t.Fatalf("status = %d, want 400: restarting without a supervisor would just stop the platform", w.Code)
}
if !strings.Contains(w.Body.String(), "重启") {
t.Errorf("the refusal must say why: %s", w.Body)
}
}
func TestUpdateApplyRejectsMalformedBody(t *testing.T) {
router, _ := newUpdateRouter(t.TempDir(), nil)
w := doUpdate(router, http.MethodPost, "/api/system/update/apply", `{"restart": "yes please"}`)
if w.Code != http.StatusBadRequest {
t.Fatalf("status = %d body = %s, want 400 for a body that is not valid JSON", w.Code, w.Body)
}
// A rejected request must not have left a job behind: the page would then poll a
// phantom update.
if job := doUpdate(router, http.MethodGet, "/api/system/update/job", ""); !strings.Contains(job.Body.String(), `"job":null`) {
t.Errorf("a 400 apply must not create a job, got %s", job.Body)
}
}
func TestUpdateRollbackWithoutARecordedUpdateIsAConflict(t *testing.T) {
root := t.TempDir()
router, _ := newUpdateRouter(root, nil)
w := doUpdate(router, http.MethodPost, "/api/system/update/rollback", "")
if w.Code != http.StatusConflict {
t.Fatalf("status = %d body = %s, want 409", w.Code, w.Body)
}
var body map[string]interface{}
if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {
t.Fatal(err)
}
if body["reason"] != "no_state" {
t.Errorf("reason = %v, want no_state so the page can say there is nothing to undo", body["reason"])
}
}
func TestUpdateSourceSaveValidatesBeforeWriting(t *testing.T) {
var saved []string
router, _ := newUpdateRouterWithSource(t.TempDir(), nil,
func() string { return "" },
func(repo string) error { saved = append(saved, repo); return nil })
// git's ext:: transport runs commands; it must never reach the config.
w := doUpdate(router, http.MethodPost, "/api/system/update/source", `{"repo":"ext::sh -c true"}`)
if w.Code != http.StatusBadRequest {
t.Fatalf("status = %d body = %s, want 400 for an ext:: address", w.Code, w.Body)
}
if len(saved) != 0 {
t.Fatalf("a refused save must not reach the config layer: %v", saved)
}
// A valid save is trimmed and lands in the config layer as one address.
w = doUpdate(router, http.MethodPost, "/api/system/update/source", `{"repo":" https://github.com/Sycun/CyberStrikeAI.git "}`)
if w.Code != http.StatusOK {
t.Fatalf("status = %d body = %s, want 200", w.Code, w.Body)
}
if len(saved) != 1 || saved[0] != "https://github.com/Sycun/CyberStrikeAI.git" {
t.Fatalf("saved = %v, want the trimmed address", saved)
}
// An empty address is the way back to the official repository, not an error.
w = doUpdate(router, http.MethodPost, "/api/system/update/source", `{"repo":""}`)
if w.Code != http.StatusOK {
t.Fatalf("status = %d body = %s, want 200 for the reset-to-default save", w.Code, w.Body)
}
if len(saved) != 2 || saved[1] != "" {
t.Fatalf("saved = %v, want the reset to reach the config layer", saved)
}
}
func TestUpdateStatusCarriesTheConfiguredSource(t *testing.T) {
router, _ := newUpdateRouterWithSource(t.TempDir(), nil,
func() string { return "https://github.com/Sycun/CyberStrikeAI.git" }, nil)
w := doUpdate(router, http.MethodGet, "/api/system/update", "")
if w.Code != http.StatusOK {
t.Fatalf("status = %d", w.Code)
}
var body struct {
Source struct {
Repo string `json:"repo"`
Configured bool `json:"configured"`
DefaultRepo string `json:"defaultRepo"`
} `json:"source"`
}
if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {
t.Fatal(err)
}
if !body.Source.Configured || body.Source.Repo != "https://github.com/Sycun/CyberStrikeAI.git" {
t.Fatalf("source = %+v, want the configured address", body.Source)
}
if body.Source.DefaultRepo != update.DefaultRepoURL {
t.Fatalf("defaultRepo = %q, want the official repository the page offers as the default", body.Source.DefaultRepo)
}
}
func TestUpdateAdoptRefusesAnAddressGitMustNeverSee(t *testing.T) {
// A plain directory with an unusable source: the refusal must come back before any
// fetch, so this test never touches the network.
router, _ := newUpdateRouterWithSource(t.TempDir(), nil,
func() string { return "ext::sh -c true" }, nil)
w := doUpdate(router, http.MethodPost, "/api/system/update/adopt", `{}`)
if w.Code != http.StatusBadRequest {
t.Fatalf("status = %d body = %s, want 400", w.Code, w.Body)
}
var body map[string]interface{}
if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {
t.Fatal(err)
}
if body["reason"] != "bad_source" {
t.Fatalf("reason = %v, want bad_source so the page can say what is wrong", body["reason"])
}
}
// The "restart to activate" contract: the page must be able to tell that the binary on
// disk is no longer the one answering requests, the supervision hint must come from the
// environment rather than a guess, and the stand-down must never run when it cannot
// change anything.
func TestUpdateStatusReportsAPendingBinaryAndSupervision(t *testing.T) {
root := t.TempDir()
writeFakeBinary(t, root, "the build this process is running")
router, _ := newUpdateRouter(root, func() {})
type statusBody struct {
NeedsRestart bool `json:"needsRestart"`
BinaryBuiltAt string `json:"binaryBuiltAt"`
Supervised bool `json:"supervised"`
Status struct {
HasBinary bool `json:"hasBinary"`
} `json:"status"`
}
read := func() statusBody {
w := doUpdate(router, http.MethodGet, "/api/system/update", "")
if w.Code != http.StatusOK {
t.Fatalf("status = %d body = %s", w.Code, w.Body)
}
var body statusBody
if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {
t.Fatal(err)
}
return body
}
if got := read(); got.NeedsRestart || got.BinaryBuiltAt != "" {
t.Fatalf("a freshly started process must call the binary it is running current: %+v", got)
}
if !read().Status.HasBinary {
t.Fatal("the fake binary has to be visible as hasBinary for this test to mean anything")
}
// A swap (update, rollback or a CLI run) replaces the file; the process is now old and
// the page has to be able to say so.
writeFakeBinary(t, root, "a different build that is now on disk")
after := read()
if !after.NeedsRestart || after.BinaryBuiltAt == "" {
t.Fatalf("replacing the binary must be reported as pending, with when it was built: %+v", after)
}
// Supervision is read from the markers launchd/systemd leave in the environment.
t.Setenv("XPC_SERVICE_NAME", "")
t.Setenv("INVOCATION_ID", "")
t.Setenv("JOURNAL_STREAM", "")
if read().Supervised {
t.Error("with no supervisor markers in the environment, supervised must be false")
}
t.Setenv("XPC_SERVICE_NAME", "com.example.thing")
if !read().Supervised {
t.Error("XPC_SERVICE_NAME is launchd's own marker; the page's default must follow it")
}
}
func TestUpdateRestartOnlyStandsDownWhenSomethingIsPending(t *testing.T) {
root := t.TempDir()
writeFakeBinary(t, root, "v1")
fired := make(chan struct{}, 1)
router, _ := newUpdateRouter(root, func() { fired <- struct{}{} })
old := updateRestartDelay
updateRestartDelay = 20 * time.Millisecond
t.Cleanup(func() { updateRestartDelay = old })
// Nothing on disk to activate: a bounce would drop the service and change nothing.
w := doUpdate(router, http.MethodPost, "/api/system/update/restart", "")
if w.Code != http.StatusConflict {
t.Fatalf("status = %d body = %s, want 409 when no binary is pending", w.Code, w.Body)
}
if !strings.Contains(w.Body.String(), "nothing_pending") {
t.Errorf("the refusal must carry its reason: %s", w.Body)
}
select {
case <-fired:
t.Fatal("a refused restart must not stand the process down")
case <-time.After(80 * time.Millisecond):
}
// A new binary is on disk now; the restart is exactly what makes it real.
writeFakeBinary(t, root, "v2")
w = doUpdate(router, http.MethodPost, "/api/system/update/restart", "")
if w.Code != http.StatusAccepted {
t.Fatalf("status = %d body = %s, want 202", w.Code, w.Body)
}
select {
case <-fired:
case <-time.After(2 * time.Second):
t.Fatal("the stand-down hook was never called")
}
}
func TestUpdateRestartRefusesWithoutAHookOrDuringAJob(t *testing.T) {
root := t.TempDir()
writeFakeBinary(t, root, "v1")
// No hook: standing down would just stop the platform.
router, _ := newUpdateRouter(root, nil)
writeFakeBinary(t, root, "v2")
w := doUpdate(router, http.MethodPost, "/api/system/update/restart", "")
if w.Code != http.StatusBadRequest {
t.Fatalf("status = %d body = %s, want 400 without a restart hook", w.Code, w.Body)
}
// A running job owns the tree; standing down halfway through a merge is how an
// installation becomes unrecoverable.
router2, h := newUpdateRouter(root, func() {})
h.mu.Lock()
h.active = "busy"
h.jobs["busy"] = &updateJob{ID: "busy", Kind: "apply", State: "running"}
h.mu.Unlock()
w = doUpdate(router2, http.MethodPost, "/api/system/update/restart", "")
if w.Code != http.StatusConflict {
t.Fatalf("status = %d body = %s, want 409 while a job is running", w.Code, w.Body)
}
if !strings.Contains(w.Body.String(), "busy") {
t.Errorf("the conflict must hand back the job that owns the tree: %s", w.Body)
}
}
func TestUpdateSourceSaveAndRestartRespectInstallLock(t *testing.T) {
root := t.TempDir()
saved := false
router, _ := newUpdateRouterWithSource(root, func() {}, nil, func(string) error { saved = true; return nil })
release, err := update.LockInstall(update.Options{Root: root})
if err != nil {
t.Fatal(err)
}
defer release()
for _, endpoint := range []string{"source", "restart"} {
w := doUpdate(router, http.MethodPost, "/api/system/update/"+endpoint, `{"repo":""}`)
if w.Code != http.StatusConflict || !strings.Contains(w.Body.String(), "update_busy") {
t.Fatalf("%s did not respect CLI lock: %d %s", endpoint, w.Code, w.Body)
}
}
if saved {
t.Fatal("source changed while another operation owned the installation")
}
}
func TestUpdateRestartRefusesMissingExecutable(t *testing.T) {
root := t.TempDir()
writeFakeBinary(t, root, "old")
router, _ := newUpdateRouter(root, func() { t.Error("missing binary must not cause shutdown") })
if err := os.Remove(filepath.Join(root, update.Binary)); err != nil {
t.Fatal(err)
}
w := doUpdate(router, http.MethodPost, "/api/system/update/restart", "")
if w.Code != http.StatusConflict || !strings.Contains(w.Body.String(), "no_binary") {
t.Fatalf("restart accepted a missing executable: %d %s", w.Code, w.Body)
}
}
func TestFailedUpdateSourceWriteKeepsActiveSource(t *testing.T) {
const original = "https://github.com/AIPentest/CyberStrikeAI.git"
h := &ConfigHandler{configPath: filepath.Join(t.TempDir(), "missing.yaml"), config: &config.Config{Update: config.UpdateConfig{Repo: original}}}
if err := h.SetUpdateSource("https://example.com/another.git"); err == nil {
t.Fatal("missing config must refuse the write")
}
if got := h.UpdateSource(); got != original {
t.Fatalf("failed save changed live update source to %q", got)
}
}

View File

@ -80,6 +80,8 @@ var PermissionCatalog = map[string]string{
"attackchain:write": "Regenerate attack chains",
"fofa:execute": "Run FOFA searches and query parsing",
"openapi:read": "Read OpenAPI aggregation results",
"update:read": "View this installation's source version and whether its own repository has anything newer",
"update:apply": "Pull this installation's own repository, rebuild the platform binary, and optionally stand the process down",
"monitor:read": "View execution monitor",
"monitor:write": "Cancel monitor executions",
"monitor:delete": "Delete monitor executions",

View File

@ -102,6 +102,13 @@ func permissionForRequest(method, fullPath string) string {
return "rbac:read"
}
return "rbac:write"
case strings.HasPrefix(path, "/system/update"):
// Reading the version of the installation is a read. Applying an update replaces the
// program that is answering the request, so it is not a flavour of write.
if method == http.MethodGet || method == http.MethodHead {
return "update:read"
}
return "update:apply"
case strings.HasPrefix(path, "/robot/wechat/status"):
return "robot:read"
case strings.HasPrefix(path, "/robot"):
@ -269,6 +276,11 @@ func isMutationMethod(method string) bool {
}
func isProcessGlobalMutationPath(path string) bool {
if strings.HasPrefix(path, "/system/update") {
// One installation, one source tree: an assigned/own-scoped session must not be able to
// move the code every other user is running.
return true
}
if strings.HasPrefix(path, "/roles") || strings.HasPrefix(path, "/skills") ||
strings.HasPrefix(path, "/external-mcp") || strings.HasPrefix(path, "/robot") {
return true

View File

@ -273,3 +273,30 @@ func TestAssignedScopeCannotMutateProcessGlobalAssets(t *testing.T) {
})
}
}
// TestUpdateApplyIsItsOwnPermissionFromReadingTheVersion: replacing the program that is
// answering the request is not a flavour of reading it, and it is process-global - one
// tree, one binary, every user of this installation.
func TestUpdateApplyIsItsOwnPermissionFromReadingTheVersion(t *testing.T) {
cases := []struct {
method, path, apiPath, want string
}{
{http.MethodGet, "/api/system/update", "/system/update", "update:read"},
{http.MethodGet, "/api/system/update/job", "/system/update/job", "update:read"},
{http.MethodPost, "/api/system/update/check", "/system/update/check", "update:apply"},
{http.MethodPost, "/api/system/update/apply", "/system/update/apply", "update:apply"},
{http.MethodPost, "/api/system/update/rollback", "/system/update/rollback", "update:apply"},
}
for _, tc := range cases {
got := permissionForRequest(tc.method, tc.path)
if got != tc.want {
t.Errorf("%s %s -> %q, want %q", tc.method, tc.path, got, tc.want)
}
if _, ok := PermissionCatalog[got]; !ok {
t.Errorf("%s %s maps to %q which is not in PermissionCatalog", tc.method, tc.path, got)
}
if tc.method != http.MethodGet && !isProcessGlobalMutationPath(tc.apiPath) {
t.Errorf("%s must require a global-scope session: it changes what every user runs", tc.path)
}
}
}

430
internal/update/adopt.go Normal file
View File

@ -0,0 +1,430 @@
package update
import (
"bytes"
"context"
"crypto/sha1"
"encoding/hex"
"fmt"
"os"
"os/exec"
"path/filepath"
"runtime"
"sort"
"strings"
"time"
)
// recoverAdoption resumes a checkout interrupted before the directory had a
// usable HEAD. It only repeats a forced checkout if every differing local file
// still matches its recorded backup; later operator edits are never overwritten.
func recoverAdoption(ctx context.Context, opts Options) error {
root, err := opts.installRoot()
if err != nil {
return err
}
pending, present, err := readBuildPending(root)
if err != nil {
return &Error{Reason: "state_unreadable", Message: "无法读取接入恢复记录:" + err.Error()}
}
if !present || pending.AdoptBranch == "" {
return nil
}
if !ValidName(pending.AdoptBranch) {
return &Error{Reason: "bad_state", Message: "接入恢复记录的分支不合法"}
}
head, headErr := gitCmd(ctx, root, "rev-parse", "HEAD")
if headErr != nil {
scan, err := scanAdoption(ctx, root, root, pending.Commit)
if err != nil {
return err
}
for _, rel := range append(scan.changed, scan.kept...) {
backup := filepath.Join(pending.BackupDir, "overwritten", filepath.FromSlash(rel))
if Protected(rel) {
backup = filepath.Join(pending.BackupDir, filepath.FromSlash(rel))
}
old, oldErr := os.ReadFile(backup)
current, currentErr := os.ReadFile(filepath.Join(root, filepath.FromSlash(rel)))
if oldErr != nil || currentErr != nil || !bytes.Equal(old, current) {
return &Error{Reason: "local_source_edits", Message: "接入中断后本地文件发生变化,已保留现场:" + rel}
}
}
if _, err := gitCmd(ctx, root, "checkout", "--force", "-B", pending.AdoptBranch, pending.Commit); err != nil {
return err
}
} else if head != pending.Commit {
return &Error{Reason: "build_state_mismatch", Message: "接入中断后 HEAD 发生变化,已保留现场"}
}
if err := restoreInterruptedProtected(ctx, root, pending, true); err != nil {
return err
}
pending.AdoptBranch = ""
pending.VersionBefore, pending.VersionAfter = plannedVersionChange(root)
return writeBuildPending(root, pending)
}
// Adopt connects a plain directory - a tarball or zip installation, or a copy carried in by
// hand - to the configured update source, so it becomes a git work tree the one-click
// update applies to from then on.
//
// The rules are the ones an update already keeps: operator content (roles/skills/tools/
// agents/knowledge_base/data/config.yaml) is put aside and put back, and nothing else is
// replaced without having been named first - the preview lists every local file whose
// content differs from the target, and each replaced file is kept under
// <backup>/overwritten/ so "the update ate my edit" always has an address.
// maxAdoptList caps the file lists a plan carries over the wire; totals are separate so a
// truncated list can never be read as the whole truth.
const maxAdoptList = 50
// AdoptPlan is the preview of connecting a directory to a source. Producing it must not
// change the directory.
type AdoptPlan struct {
Root string `json:"root"`
Source string `json:"source"`
Branch string `json:"branch"`
Commit string `json:"commit"`
Subject string `json:"subject"`
Incoming int `json:"incoming"` // files the target branch tracks
OverwrittenTotal int `json:"overwrittenTotal"`
Overwritten []string `json:"overwritten"` // differing local files the target's version will replace (capped)
ProtectedTotal int `json:"protectedTotal"`
Protected []string `json:"protected"` // operator content put aside and put back (capped)
}
// adoptionScan is the full (uncapped) comparison an adoption is based on.
type adoptionScan struct {
target map[string]string // tracked path -> blob sha
paths []string // every tracked path, sorted
changed []string // local file differs from the target and is not protected
kept []string // local file differs from the target and is protected
}
// Preview builds an adoption plan without touching the directory: the fetch happens in a
// throwaway bare repository outside it, so a failure cannot leave a half-adopted tree.
func Preview(ctx context.Context, opts Options) (*AdoptPlan, error) {
root, source, err := adoptPreflight(ctx, opts)
if err != nil {
return nil, err
}
tmp, err := os.MkdirTemp("", "csai-adopt-preview-")
if err != nil {
return nil, err
}
defer os.RemoveAll(tmp)
if _, err := gitCmd(ctx, tmp, "init", "--quiet", "--bare"); err != nil {
return nil, err
}
branch, commit, subject, err := fetchSource(ctx, tmp, source)
if err != nil {
return nil, err
}
scan, err := scanAdoption(ctx, root, tmp, "origin/"+branch)
if err != nil {
return nil, err
}
return scan.plan(root, source, branch, commit, subject), nil
}
// Adopt carries the directory onto the source. It runs its own fetch inside the directory
// (the preview's throwaway fetch cannot be reused), and on any failure removes only the
// .git it created itself, so a retry starts from the same pristine state.
func Adopt(ctx context.Context, opts Options, onStep func(Step)) (*Result, error) {
release, err := LockInstall(opts)
if err != nil {
return nil, err
}
defer release()
if onStep == nil {
onStep = func(Step) {}
}
step := func(phase, msg string) { onStep(Step{Phase: phase, Message: msg, At: time.Now().Format(time.RFC3339)}) }
start := time.Now()
root, source, err := adoptPreflight(ctx, opts)
if err != nil {
return nil, err
}
step("preflight", fmt.Sprintf("把目录 %s 接入更新源 %s", root, source))
if _, err := gitCmd(ctx, root, "init", "--quiet"); err != nil {
return nil, &Error{Reason: "init_failed", Message: "git init 失败:" + err.Error()}
}
adopted := false
defer func() {
if !adopted {
// Only the repository git just created; the directory's own files are untouched.
_ = os.RemoveAll(filepath.Join(root, ".git"))
}
}()
if _, err := gitCmd(ctx, root, "remote", "add", "origin", source); err != nil {
return nil, &Error{Reason: "init_failed", Message: "添加远端失败:" + err.Error()}
}
branch, commit, subject, err := fetchSource(ctx, root, source)
if err != nil {
return nil, err
}
ref := "origin/" + branch
scan, err := scanAdoption(ctx, root, root, ref)
if err != nil {
return nil, err
}
step("fetch", fmt.Sprintf("%s/%s(%s %s)共 %d 个文件:%d 个本机版本会被目标版本替换,%d 个运维者文件先暂存再放回",
source, branch, commit, subject, len(scan.paths), len(scan.changed), len(scan.kept)))
backupDir := ""
backupAll := append(append([]string{}, scan.changed...), scan.kept...)
if len(backupAll) > 0 {
backupDir, err = newBackupDir(root, time.Now().Format("20060102_150405"))
if err != nil {
return nil, err
}
}
for _, p := range backupAll {
abs := filepath.Join(root, filepath.FromSlash(p))
info, statErr := os.Stat(abs)
if statErr != nil || !info.Mode().IsRegular() {
return nil, &Error{Reason: "backup_failed", Message: "备份前本地文件发生变化,未执行接入:" + p}
}
dst := filepath.Join(backupDir, "overwritten", filepath.FromSlash(p))
if Protected(p) {
dst = filepath.Join(backupDir, filepath.FromSlash(p))
}
if err := copyFile(abs, dst, info.Mode()); err != nil {
return nil, &Error{Reason: "backup_failed", Message: fmt.Sprintf("备份 %s 失败:%v", p, err)}
}
}
if len(backupAll) > 0 {
step("protect", fmt.Sprintf("%d 个文件已留底(被替换的在 %s/overwritten/,运维者的会原样放回)", len(backupAll), backupDir))
}
targetCommit, err := gitCmd(ctx, root, "rev-parse", ref)
if err != nil {
return nil, err
}
pending := buildPendingState{
Commit: targetCommit,
BackupDir: backupDir,
KeptContent: append([]string(nil), scan.kept...),
OverwrittenContent: append([]string(nil), scan.changed...),
AdoptBranch: branch,
PreviousBinaryAbsent: !fileExists(filepath.Join(root, opts.binaryName())),
}
if opts.binaryName() != "none" {
bin := filepath.Join(root, opts.binaryName())
if fileExists(bin) {
pending.PreviousBinarySHA256, err = fileSHA256(bin)
if err != nil {
return nil, err
}
}
}
// Record both the target and backups before checkout can replace any file.
if err := writeBuildPending(root, pending); err != nil {
return nil, &Error{Reason: "state_unwritable", Message: "无法写入接入恢复状态:" + err.Error()}
}
adopted = true
if _, err := gitCmd(ctx, root, "checkout", "--force", "-B", branch, targetCommit); err != nil {
return nil, &Error{Reason: "checkout_failed", Message: "落地目标内容失败,已保留恢复记录,再次更新可恢复:" + err.Error()}
}
if err := restoreProtected(backupDir, scan.kept); err != nil {
return nil, err
}
pending.AdoptBranch = ""
pending.VersionBefore, pending.VersionAfter = plannedVersionChange(root)
if err := writeBuildPending(root, pending); err != nil {
return nil, &Error{Reason: "state_unwritable", Message: "无法更新接入恢复状态:" + err.Error()}
}
if _, err := gitCmd(ctx, root, "branch", "--set-upstream-to="+ref); err != nil {
return nil, &Error{Reason: "upstream_failed", Message: "设置分支跟踪失败:" + err.Error()}
}
versionBefore, versionAfter, versionErr := syncVersionToConfig(root)
versionStep(step, versionBefore, versionAfter, versionErr)
res := &Result{
ToCommit: commit,
FilesTouched: len(scan.paths),
KeptContent: scan.kept,
Overwritten: scan.changed,
BackupDir: backupDir,
Adopted: true,
NeedsRestart: true,
}
if opts.binaryName() == "none" {
if err := clearBuildPending(root); err != nil {
return res, err
}
step("done", fmt.Sprintf("目录已接入 %s/%s(%s);按请求跳过重新编译", source, branch, commit))
res.Duration = time.Since(start).Round(time.Millisecond).String()
return res, nil
}
bin := filepath.Join(root, opts.binaryName())
res.BinaryPath = bin
if _, canBuild := toolchain(ctx, root); !canBuild {
step("done", fmt.Sprintf("目录已接入 %s/%s(%s);本机没有 Go 工具链,二进制未重编", source, branch, commit))
res.Duration = time.Since(start).Round(time.Millisecond).String()
return res, &Error{
Reason: "no_toolchain",
Message: "目录已接入更新源,但本机没有 Go 工具链,无法重新编译。装好 go 后再点一次更新即可补上二进制。",
}
}
if err := buildAndSwap(ctx, root, opts, res, step, targetCommit, nil, pending); err != nil {
res.Duration = time.Since(start).Round(time.Millisecond).String()
return res, err
}
step("done", fmt.Sprintf("目录已接入 %s/%s(%s)并换好二进制", source, branch, commit))
res.Duration = time.Since(start).Round(time.Millisecond).String()
return res, nil
}
// adoptPreflight validates the operation's preconditions: a plain directory and a usable
// source address. It does not touch the directory.
func adoptPreflight(ctx context.Context, opts Options) (root, source string, err error) {
root, err = opts.installRoot()
if err != nil {
return "", "", err
}
if _, err := exec.LookPath("git"); err != nil {
return "", "", &Error{Reason: "no_git", Message: "本机没有 git,无法把目录接入更新源"}
}
if _, err := gitCmd(ctx, root, "rev-parse", "--is-inside-work-tree"); err == nil {
return "", "", &Error{Reason: "already_a_repo", Message: "这个目录已经是 git 工作树:用「一键更新」,不需要接入"}
}
if fi, statErr := os.Stat(root); statErr != nil || !fi.IsDir() {
return "", "", &Error{Reason: "bad_root", Message: "安装目录不存在:" + root}
}
if _, statErr := os.Lstat(filepath.Join(root, ".git")); !os.IsNotExist(statErr) {
return "", "", &Error{Reason: "existing_git_metadata", Message: "安装目录已存在 .git 元数据,接入不会覆盖它;请先人工检查仓库状态"}
}
source = opts.repoURL()
if !ValidRemoteURL(source) {
return "", "", &Error{Reason: "bad_source", Message: "更新源仓库地址不合法(只允许 https/http/ssh/git/file:// 或本机绝对路径)"}
}
return root, source, nil
}
// fetchSource fetches the source's default branch into repo and reports which branch
// that ended up being, its short commit and its subject. Both callers fetch into a
// repository of their own.
func fetchSource(ctx context.Context, repo, source string) (string, string, string, error) {
out, err := gitCmd(ctx, repo, "ls-remote", "--symref", source, "HEAD")
if err != nil {
return "", "", "", &Error{Reason: "fetch_failed", Message: "读取远端默认分支失败:" + err.Error()}
}
branch := parseDefaultBranch(out)
if branch == "" {
return "", "", "", &Error{Reason: "no_branch", Message: "无法确定远端默认分支:" + source}
}
if _, err := gitCmd(ctx, repo, "fetch", "--quiet", "--no-tags", "--recurse-submodules=no",
source, "+refs/heads/"+branch+":refs/remotes/origin/"+branch); err != nil {
return "", "", "", &Error{Reason: "fetch_failed", Message: "拉取失败:" + err.Error()}
}
ref := "origin/" + branch
commit, err := gitCmd(ctx, repo, "rev-parse", "--short", ref)
if err != nil {
return "", "", "", &Error{Reason: "no_branch", Message: fmt.Sprintf("远端没有分支 %s", branch)}
}
subject, _ := gitCmd(ctx, repo, "log", "-1", "--format=%s", ref)
return branch, commit, subject, nil
}
// scanAdoption compares the directory against the tracked files of ref in repo.
func scanAdoption(ctx context.Context, root, repo, ref string) (*adoptionScan, error) {
out, err := gitRaw(ctx, repo, "ls-tree", "-r", "-z", "--full-tree", ref)
if err != nil {
return nil, &Error{Reason: "diff_failed", Message: err.Error()}
}
scan := &adoptionScan{target: map[string]string{}}
targetModes := map[string]os.FileMode{}
for _, rec := range nulList(out) {
tab := strings.IndexByte(rec, '\t')
if tab < 0 {
continue
}
fields := strings.Fields(rec[:tab])
if len(fields) < 3 || fields[1] != "blob" {
continue // submodules and trees are not files this comparison replaces
}
p := rec[tab+1:]
scan.target[p] = fields[2]
targetModes[p] = 0644
if fields[0] == "100755" {
targetModes[p] = 0755
}
scan.paths = append(scan.paths, p)
}
sort.Strings(scan.paths)
for _, p := range scan.paths {
if err := validateFilePath(root, p); err != nil {
return nil, err
}
abs := filepath.Join(root, filepath.FromSlash(p))
info, err := os.Lstat(abs)
if err != nil || !info.Mode().IsRegular() {
continue
}
hash, err := gitBlobHash(abs)
if err != nil {
return nil, &Error{Reason: "backup_failed", Message: "无法读取待接入的本地文件,未修改目录:" + p + ": " + err.Error()}
}
modeChanged := runtime.GOOS != "windows" && Protected(p) && info.Mode().Perm() != targetModes[p]
if hash == scan.target[p] && !modeChanged {
continue
}
if Protected(p) {
scan.kept = append(scan.kept, p)
} else {
scan.changed = append(scan.changed, p)
}
}
return scan, nil
}
// plan renders the capped, wire-facing view of a scan.
func (s *adoptionScan) plan(root, source, branch, commit, subject string) *AdoptPlan {
p := &AdoptPlan{
Root: root, Source: source, Branch: branch, Commit: commit, Subject: subject,
Incoming: len(s.paths),
OverwrittenTotal: len(s.changed),
ProtectedTotal: len(s.kept),
Overwritten: append([]string{}, s.changed...),
Protected: append([]string{}, s.kept...),
}
if len(p.Overwritten) > maxAdoptList {
p.Overwritten = p.Overwritten[:maxAdoptList]
}
if len(p.Protected) > maxAdoptList {
p.Protected = p.Protected[:maxAdoptList]
}
if p.Overwritten == nil {
p.Overwritten = []string{}
}
if p.Protected == nil {
p.Protected = []string{}
}
return p
}
// gitBlobHash computes the object id git would give a file's content. It hashes the bytes
// as they are (no filters), because the comparison is against raw blobs in the tree. sha1 is
// not a security choice here - it is the blob-id algorithm of the repository format.
func gitBlobHash(path string) (string, error) {
data, err := os.ReadFile(path)
if err != nil {
return "", err
}
h := sha1.New()
fmt.Fprintf(h, "blob %d\x00", len(data))
h.Write(data)
return hex.EncodeToString(h.Sum(nil)), nil
}

View File

@ -0,0 +1,185 @@
package update
import (
"context"
"os"
"path/filepath"
"runtime"
"strings"
"testing"
)
// newAdoptFixture builds the shape a tarball installation has: the upstream project's files
// on disk with the repository removed, plus operator content and one locally edited
// product file that the adoption is expected to name (and keep a copy of).
func newAdoptFixture(t *testing.T) (*tree, string) {
t.Helper()
tr := newTree(t)
dir := filepath.Join(filepath.Dir(tr.upstream), "release")
mustGit(t, filepath.Dir(tr.upstream), "clone", "-q", tr.upstream, dir)
if err := os.RemoveAll(filepath.Join(dir, ".git")); err != nil {
t.Fatal(err)
}
// Operator content: the live config (never in the repository), their own role, and an
// edit to a shipped role.
writeFile(t, filepath.Join(dir, "config.yaml"), "server:\n port: 8088\n")
writeFile(t, filepath.Join(dir, "roles", "mine.yaml"), "name: mine\n")
writeFile(t, filepath.Join(dir, "roles", "shipped.yaml"), "name: shipped\ndescription: mine, do not touch\n")
// A locally edited product file.
writeFile(t, filepath.Join(dir, "run.sh"), "#!/bin/sh\necho hacked\n")
return tr, dir
}
func TestPreviewNamesWhatAdoptionWouldReplaceWithoutTouchingTheDirectory(t *testing.T) {
requireGit(t)
tr, dir := newAdoptFixture(t)
plan, err := Preview(context.Background(), Options{Root: dir, Repo: tr.upstream})
if err != nil {
t.Fatal(err)
}
if _, err := os.Stat(filepath.Join(dir, ".git")); !os.IsNotExist(err) {
t.Fatal("a preview must not create a repository")
}
if plan.Incoming < 3 {
t.Fatalf("incoming = %d, want at least the fixture's files", plan.Incoming)
}
if !contains(plan.Overwritten, "run.sh") {
t.Errorf("the edited product file must be named: %v", plan.Overwritten)
}
if contains(plan.Overwritten, "roles/shipped.yaml") {
t.Errorf("operator content must not be listed as replaced: %v", plan.Overwritten)
}
if !contains(plan.Protected, "roles/shipped.yaml") {
t.Errorf("the edited shipped role must be listed as protected: %v", plan.Protected)
}
if got := readFile(t, filepath.Join(dir, "run.sh")); !strings.Contains(got, "hacked") {
t.Errorf("preview must not change file contents: %q", got)
}
}
func TestAdoptConnectsTheDirectoryAndKeepsOperatorContent(t *testing.T) {
requireGit(t)
tr, dir := newAdoptFixture(t)
res, err := Adopt(context.Background(), Options{Root: dir, Repo: tr.upstream, BinaryName: "none"}, nil)
if err != nil {
t.Fatalf("adopt failed: %v\nresult: %+v", err, res)
}
if !res.Adopted || res.ToCommit == "" {
t.Fatalf("res = %+v, want an adopted result", res)
}
// The directory is now a work tree tracking the chosen source.
if got := mustGit(t, dir, "rev-parse", "--abbrev-ref", "HEAD"); got != "main" {
t.Errorf("HEAD branch = %q, want main", got)
}
if got := mustGit(t, dir, "rev-parse", "--abbrev-ref", "@{upstream}"); got != "origin/main" {
t.Errorf("upstream = %q, want origin/main - from here the tree tracks its source by itself", got)
}
// The target's content replaced the local edit; the local edit survives in the backup.
if got := readFile(t, filepath.Join(dir, "run.sh")); !strings.Contains(got, "echo old") {
t.Errorf("run.sh = %q, want the target's version", got)
}
if !contains(res.Overwritten, "run.sh") {
t.Errorf("result must name the replaced file: %v", res.Overwritten)
}
if got := readFile(t, filepath.Join(res.BackupDir, "overwritten", "run.sh")); !strings.Contains(got, "hacked") {
t.Errorf("the replaced file must be kept for recovery, got %q", got)
}
// Operator content survived: the live config untouched, their own role untouched, their
// edit to a shipped role restored over the target's version.
if got := readFile(t, filepath.Join(dir, "config.yaml")); !strings.Contains(got, "8088") {
t.Errorf("config.yaml was disturbed: %q", got)
}
if got := readFile(t, filepath.Join(dir, "roles", "mine.yaml")); !strings.Contains(got, "name: mine") {
t.Errorf("the operator's own role must survive: %q", got)
}
if got := readFile(t, filepath.Join(dir, "roles", "shipped.yaml")); !strings.Contains(got, "do not touch") {
t.Errorf("the operator's edit to a shipped role must win: %q", got)
}
if !contains(res.KeptContent, "roles/shipped.yaml") {
t.Errorf("keptContent = %v, want roles/shipped.yaml", res.KeptContent)
}
// From now on it is a normal installation: the next upstream commit updates it, and the
// first real update writes the first rollback point.
tr.upstreamCommit(t, "second: bump service", map[string]string{
"internal_service.go": "package service\n\nconst Version = \"2\"\n",
})
snap, err := Check(context.Background(), Options{Root: dir, Repo: tr.upstream, BinaryName: "none"})
if err != nil {
t.Fatal(err)
}
if snap.CheckError != "" || snap.Behind != 1 {
t.Fatalf("the adopted tree must update like any other: checkError=%q behind=%d", snap.CheckError, snap.Behind)
}
res2, err := Apply(context.Background(), Options{Root: dir, Repo: tr.upstream, BinaryName: "none"}, nil)
if err != nil {
t.Fatalf("apply after adopt failed: %v", err)
}
if res2.ToCommit == "" || res2.Adopted {
t.Fatalf("res2 = %+v", res2)
}
if _, ok := readState(dir); !ok {
t.Error("the first real update must write a rollback point")
}
if got := readFile(t, filepath.Join(dir, "internal_service.go")); !strings.Contains(got, "Version = \"2\"") {
t.Errorf("code after the first update = %q", got)
}
}
func TestAdoptRefusesWhatItCannotHonestlyDo(t *testing.T) {
requireGit(t)
tr := newTree(t)
// Already a work tree: that is an update, not an adoption.
if _, err := Adopt(context.Background(), Options{Root: tr.install, Repo: tr.upstream, BinaryName: "none"}, nil); asReason(err) != "already_a_repo" {
t.Errorf("err = %v, want already_a_repo", err)
}
// Nothing to adopt onto: the directory has to exist.
plain := t.TempDir()
missing := filepath.Join(plain, "not-a-directory")
if _, err := Adopt(context.Background(), Options{Root: missing}, nil); asReason(err) != "bad_root" {
t.Errorf("err = %v, want bad_root", err)
}
// An address git must never be handed. (An unset address is no longer an error: the
// official repository is the default update source.)
if _, err := Adopt(context.Background(), Options{Root: plain, Repo: "ext::sh -c true", BinaryName: "none"}, nil); asReason(err) != "bad_source" {
t.Errorf("err = %v, want bad_source", err)
}
}
func contains(list []string, want string) bool {
for _, v := range list {
if v == want {
return true
}
}
return false
}
func asReason(err error) string {
if ue, ok := err.(*Error); ok {
return ue.Reason
}
return ""
}
func TestAdoptPreservesModeOfUnchangedProtectedFile(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("POSIX permissions are not available on Windows")
}
requireGit(t)
tr, dir := newAdoptFixture(t)
role := filepath.Join(dir, "roles", "shipped.yaml")
writeFile(t, role, readFile(t, filepath.Join(tr.upstream, "roles", "shipped.yaml")))
if err := os.Chmod(role, 0600); err != nil {
t.Fatal(err)
}
if _, err := Adopt(context.Background(), Options{Root: dir, Repo: tr.upstream, BinaryName: "none"}, nil); err != nil {
t.Fatal(err)
}
info, err := os.Stat(role)
if err != nil || info.Mode().Perm() != 0600 {
t.Fatalf("adoption lost private permissions: %v %v", info, err)
}
}

1099
internal/update/apply.go Normal file

File diff suppressed because it is too large Load Diff

41
internal/update/binary.go Normal file
View File

@ -0,0 +1,41 @@
package update
import (
"os"
"path/filepath"
"time"
)
// BinaryStamp identifies the executable on disk: a rebuild, a rename-swap from an update,
// or a rollback that puts the previous build back all change it. Size plus nanosecond
// mtime is enough to tell two builds apart, and it costs one stat() on a request path -
// hashing the file would not.
type BinaryStamp struct {
Exists bool `json:"exists"`
Size int64 `json:"size,omitempty"`
ModTime time.Time `json:"modTime,omitempty"`
}
// StampBinary reads the install's binary as it is on disk right now. A missing file is a
// legitimate stamp rather than an error: a source checkout has no binary until the first
// update builds one.
func StampBinary(root string, opts Options) BinaryStamp {
info, err := os.Stat(filepath.Join(root, opts.binaryName()))
if err != nil {
return BinaryStamp{}
}
return BinaryStamp{Exists: true, Size: info.Size(), ModTime: info.ModTime()}
}
// Same reports whether two stamps describe the same file. The comparison is deliberately
// stricter than "the disk file is newer": a rollback moves an older build back into place,
// and the process running the newer one still has to restart for the rollback to be real.
func (s BinaryStamp) Same(other BinaryStamp) bool {
if s.Exists != other.Exists {
return false
}
if !s.Exists {
return true
}
return s.Size == other.Size && s.ModTime.Equal(other.ModTime)
}

182
internal/update/build.go Normal file
View File

@ -0,0 +1,182 @@
package update
import (
"context"
"crypto/sha256"
"debug/buildinfo"
"encoding/hex"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"strings"
)
// toolchain reports whether a Go compiler is reachable from the install tree. An update
// that cannot compile must still update the source and say so plainly, because "no Go on
// this box" is an environment fact the operator can fix, not a reason to refuse the pull.
func toolchain(ctx context.Context, root string) (string, bool) {
path, err := exec.LookPath("go")
if err != nil {
return "", false
}
out, err := exec.CommandContext(ctx, path, "env", "GOVERSION").Output()
if err != nil {
return path, true
}
v := strings.TrimSpace(string(out))
if v == "" {
return path, true
}
return v, true
}
// build compiles the server binary into outPath, never into the tree's own executable
// name: a build that fails halfway must not leave a truncated binary where the running
// one lives. Output is returned on failure because the operator needs the compiler's
// message, not "build failed".
func build(ctx context.Context, root, outPath string) error {
cmd := exec.CommandContext(ctx, "go", "build", "-o", outPath, "./cmd/server")
cmd.Dir = root
// The module cache goes next to the install rather than into whoever's HOME started
// the service, so a first build under a service account cannot fail on a HOME that is
// not writable.
if home := os.Getenv("HOME"); home == "" || home == "/" {
cmd.Env = append(os.Environ(), "HOME="+root)
}
out, err := cmd.CombinedOutput()
if err != nil {
msg := strings.TrimSpace(string(out))
if msg == "" {
msg = err.Error()
}
return fmt.Errorf("%s", tail(msg, 4000))
}
if _, err := os.Stat(outPath); err != nil {
return fmt.Errorf("go build reported success but produced no binary at %s", outPath)
}
return nil
}
// installBinary puts src in place of dst and keeps the previous dst as dst+".prev", which
// is what makes a rollback possible without a second download.
//
// The rename is the whole trick: a running executable's file cannot be written to on
// Linux (ETXTBSY) but renaming it aside is always allowed, so the old process keeps its
// inode and the new path is complete before anyone can observe it.
func installBinary(src, dst string) (string, error) {
// Validate the staged file before moving the live executable aside.
if err := os.Chmod(src, 0o755); err != nil {
return "", err
}
prev := ""
if fileExists(dst) {
prev = dst + ".prev"
if err := os.Remove(prev); err != nil && !os.IsNotExist(err) {
return "", err
}
if err := os.Rename(dst, prev); err != nil {
return "", fmt.Errorf("保留旧二进制失败:%w", err)
}
}
if err := os.Rename(src, dst); err != nil {
// Put the kept-previous binary back rather than leaving the install with no
// executable because one rename failed.
if prev != "" && !fileExists(dst) {
_ = os.Rename(prev, dst)
}
return "", fmt.Errorf("换入新二进制失败:%w", err)
}
return prev, nil
}
// restorePrevBinary rolls back one swap. It is deliberately not installBinary in
// reverse: renaming dst onto src first would overwrite the very .prev file being
// restored, so the current binary is discarded instead.
func restorePrevBinary(bin string) error {
prev := bin + ".prev"
if !fileExists(prev) {
return fmt.Errorf("没有旧二进制:%s", prev)
}
if err := os.Chmod(prev, 0o755); err != nil {
return err
}
return replaceBinary(prev, bin)
}
func fileSHA256(path string) (string, error) {
f, err := os.Open(path)
if err != nil {
return "", err
}
defer f.Close()
h := sha256.New()
if _, err := io.Copy(h, f); err != nil {
return "", err
}
return hex.EncodeToString(h.Sum(nil)), nil
}
func binaryRevision(path string) string {
info, err := buildinfo.ReadFile(path)
if err != nil {
return ""
}
var revision string
for _, setting := range info.Settings {
if setting.Key == "vcs.modified" && setting.Value == "true" {
return ""
}
if setting.Key == "vcs.revision" {
revision = strings.TrimSpace(setting.Value)
}
}
return revision
}
// tail keeps the last bytes of a compiler's output: the end of a build log is where the
// error is, while the beginning is where the module downloads are.
func tail(s string, n int) string {
if len(s) <= n {
return s
}
return "…(前文省略)\n" + s[len(s)-n:]
}
// copyFile is used for the operator-owned content that an update puts aside and takes
// back. It creates the parent directories because the backup tree mirrors repository
// paths, and it preserves the mode because a tool recipe or a script that lost its exec
// bit stops working in a way nothing reports.
func copyFile(src, dst string, mode os.FileMode) error {
in, err := os.Open(src)
if err != nil {
return err
}
defer in.Close()
if err := os.MkdirAll(filepath.Dir(dst), 0o755); err != nil {
return err
}
tmp := dst + ".tmp"
out, err := os.OpenFile(tmp, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, mode.Perm())
if err != nil {
return err
}
if err := out.Chmod(mode.Perm()); err != nil {
out.Close()
os.Remove(tmp)
return err
}
if _, err := io.Copy(out, in); err != nil {
out.Close()
os.Remove(tmp)
return err
}
if err := out.Close(); err != nil {
os.Remove(tmp)
return err
}
return os.Rename(tmp, dst)
}

28
internal/update/lock.go Normal file
View File

@ -0,0 +1,28 @@
package update
import (
"os"
"path/filepath"
)
// LockInstall serializes CLI and HTTP operations on the same installation. The
// file stays in place: removing it would let another process lock a new inode.
// Kernel locks are released on exit, including a crash or SIGKILL.
func LockInstall(opts Options) (func(), error) {
root, err := opts.installRoot()
if err != nil {
return nil, err
}
if info, err := os.Stat(root); err != nil || !info.IsDir() {
return nil, &Error{Reason: "bad_root", Message: "安装目录不存在或不是目录:" + root}
}
f, err := os.OpenFile(filepath.Join(root, ".update-lock"), os.O_CREATE|os.O_RDWR, 0600)
if err != nil {
return nil, &Error{Reason: "lock_failed", Message: "无法锁定安装目录:" + err.Error()}
}
if err := lockFile(f); err != nil {
f.Close()
return nil, &Error{Reason: "update_busy", Message: "此安装目录已有更新、检查或回滚正在执行,请稍后重试"}
}
return func() { f.Close() }, nil
}

View File

@ -0,0 +1,12 @@
//go:build !darwin && !linux && !freebsd && !openbsd && !netbsd && !dragonfly && !windows
package update
import (
"fmt"
"os"
)
func lockFile(f *os.File) error {
return fmt.Errorf("installation locking is unavailable on this platform")
}

View File

@ -0,0 +1,10 @@
//go:build darwin || linux || freebsd || openbsd || netbsd || dragonfly
package update
import (
"golang.org/x/sys/unix"
"os"
)
func lockFile(f *os.File) error { return unix.Flock(int(f.Fd()), unix.LOCK_EX|unix.LOCK_NB) }

View File

@ -0,0 +1,10 @@
package update
import (
"golang.org/x/sys/windows"
"os"
)
func lockFile(f *os.File) error {
return windows.LockFileEx(windows.Handle(f.Fd()), windows.LOCKFILE_EXCLUSIVE_LOCK|windows.LOCKFILE_FAIL_IMMEDIATELY, 0, 1, 0, &windows.Overlapped{})
}

33
internal/update/paths.go Normal file
View File

@ -0,0 +1,33 @@
package update
import (
"fmt"
"os"
"path/filepath"
"strings"
)
// validateFilePath refuses directory/file and symlink conflicts before git can
// remove an untracked directory or backups can follow a link outside the install.
func validateFilePath(root, rel string) error {
parts := strings.Split(filepath.ToSlash(rel), "/")
path := root
for i, part := range parts {
if part == "" || part == "." || part == ".." {
return &Error{Reason: "content_path_conflict", Message: "文件路径不合法:" + rel}
}
path = filepath.Join(path, part)
info, err := os.Lstat(path)
if os.IsNotExist(err) {
return nil
}
if err != nil {
return err
}
leaf := i == len(parts)-1
if (leaf && !info.Mode().IsRegular()) || (!leaf && !info.IsDir()) {
return &Error{Reason: "content_path_conflict", Message: fmt.Sprintf("%s 存在符号链接或目录/文件冲突,已保留本地内容,请先人工处理", rel), Items: []string{rel}}
}
}
return nil
}

View File

@ -0,0 +1,724 @@
package update
import (
"context"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"testing"
)
// fakeGo is a scripted stand-in for the Go toolchain: `go env GOVERSION` answers, and
// `go build -o <out> ...` either writes a recognisable file or fails, decided by a marker
// file the test toggles. It goes first on PATH (the real PATH stays behind it, because git
// still has to resolve), so the update's real build step runs without compiling the whole
// server inside a test.
type fakeGo struct {
marker string
}
func scriptFakeGo(t *testing.T) *fakeGo {
t.Helper()
if runtime.GOOS == "windows" {
// The scripted toolchain is a POSIX shell script: Windows would not execute it,
// LookPath would not even find it, and the scenario would silently assert
// nothing. Driving it there needs a different harness, not a different promise.
t.Skip("the scripted go toolchain needs a POSIX shell")
}
dir := t.TempDir()
marker := filepath.Join(dir, "fail-build")
f := &fakeGo{marker: marker}
script := "#!/bin/sh\n" +
"if [ \"$1\" = env ]; then echo go1.23.4; exit 0; fi\n" +
"out=\"\"\n" +
"prev=\"\"\n" +
"for a in \"$@\"; do\n" +
" if [ \"$prev\" = -o ]; then out=\"$a\"; fi\n" +
" prev=\"$a\"\n" +
"done\n" +
"if [ -f \"" + marker + "\" ]; then echo 'vet: internal/foo.go:12: fake failure' >&2; exit 1; fi\n" +
"commit=$(git rev-parse --short HEAD) || exit 1\n" +
"echo \"fake binary for $commit\" > \"$out\"\n"
if err := os.WriteFile(filepath.Join(dir, "go"), []byte(script), 0o755); err != nil {
t.Fatal(err)
}
t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH"))
return f
}
func (f *fakeGo) failBuild(t *testing.T) {
t.Helper()
if err := os.WriteFile(f.marker, []byte("x"), 0o644); err != nil {
t.Fatal(err)
}
}
func (f *fakeGo) succeed(t *testing.T) {
t.Helper()
if err := os.Remove(f.marker); err != nil && !os.IsNotExist(err) {
t.Fatal(err)
}
}
// hideToolchain takes `go` off the PATH child processes see while leaving everything else
// (git) reachable: a directory holding a symlink to the real git and nothing else.
func hideToolchain(t *testing.T) {
t.Helper()
if runtime.GOOS == "windows" {
// Same reason as scriptFakeGo: symlinks need privileges there and the bare-name
// file would not resolve through LookPath.
t.Skip("PATH surgery here needs POSIX symlinks")
}
realGit, err := exec.LookPath("git")
if err != nil {
t.Skip("git not installed")
}
dir := t.TempDir()
if err := os.Symlink(realGit, filepath.Join(dir, "git")); err != nil {
t.Fatal(err)
}
t.Setenv("PATH", dir)
}
// buildOpts drives an update with a real binary to swap - the configuration of every
// installed tree, where "the source moved but the binary did not" is even possible.
func buildOpts(tr *tree) Options {
return Options{Root: tr.install, Repo: tr.upstream, BinaryName: Binary}
}
// TestRetryAfterFailedBuildCompilesTheBinary: a failed build leaves the source updated
// (HEAD is on the new commit), so a retry sees "nothing to pull" - and used to report
// success while the old binary stayed in place. The retry has to finish the build.
func TestRetryAfterFailedBuildCompilesTheBinary(t *testing.T) {
requireGit(t)
tr := newTree(t)
fake := scriptFakeGo(t)
fake.failBuild(t)
bin := filepath.Join(tr.install, Binary)
writeFile(t, bin, "old binary bytes")
tr.upstreamCommit(t, "upstream moves", map[string]string{"internal_service.go": "package service\n\nconst Version = \"2\"\n"})
res, err := Apply(context.Background(), buildOpts(tr), nil)
ue, ok := err.(*Error)
if !ok || ue.Reason != "build_failed" {
t.Fatalf("first apply: err=%v result=%+v, want build_failed", err, res)
}
if res.BinaryBuilt {
t.Error("a failed build must not claim a binary")
}
if got := readFile(t, bin); got != "old binary bytes" {
t.Errorf("binary after the failed build = %q, want the old one untouched", got)
}
snap, err := Status(context.Background(), buildOpts(tr))
if err != nil {
t.Fatal(err)
}
if !snap.BuildPending {
t.Error("after a failed build the tree owes a compile; Status must say so")
}
// Same tree, a working toolchain: the retry compiles instead of reporting success for
// work that never happened.
fake.succeed(t)
res, err = Apply(context.Background(), buildOpts(tr), nil)
if err != nil {
t.Fatalf("retry failed: %v (result %+v)", err, res)
}
if !res.BinaryBuilt || res.Commits != 0 || res.FromCommit != res.ToCommit {
t.Errorf("retry result = %+v, want a build with no commits moved", res)
}
if got := readFile(t, bin); !strings.Contains(got, "fake binary") {
t.Errorf("binary after retry = %q, want the freshly built one", got)
}
if got := readFile(t, bin+".prev"); got != "old binary bytes" {
t.Errorf("prev binary = %q, want the one the swap kept", got)
}
if buildPending(tr.install) {
t.Error("a finished build must clear the pending marker")
}
}
// TestRetryFinishesTheBuildWhenTheStateWriteFailed: the merge landed, but the update
// aborted before the state file could be written (a full disk, a directory sitting where
// the file goes). The tree still owes a binary, and the retry must know that - the marker
// is written the moment the merge lands, not after the bookkeeping that may fail.
func TestRollbackAfterFailedBuildKeepsTheMatchingPreviousBinary(t *testing.T) {
requireGit(t)
tr := newTree(t)
fake := scriptFakeGo(t)
fake.failBuild(t)
bin := filepath.Join(tr.install, Binary)
writeFile(t, bin, "original binary")
before := mustGit(t, tr.install, "rev-parse", "HEAD")
tr.upstreamCommit(t, "upstream moves", map[string]string{"internal_service.go": "package service\n\nconst Version = \"2\"\n"})
if _, err := Apply(context.Background(), buildOpts(tr), nil); err == nil {
t.Fatal("the build must fail")
}
if fileExists(bin + ".prev") {
t.Fatal("a failed build must not create a rollback binary")
}
snap, err := Status(context.Background(), buildOpts(tr))
if err != nil {
t.Fatal(err)
}
if !snap.HasRollback {
t.Fatal("source can roll back to the commit already matching the live binary")
}
res, err := Rollback(context.Background(), buildOpts(tr))
if err != nil {
t.Fatalf("rollback failed: %v", err)
}
if got := mustGit(t, tr.install, "rev-parse", "HEAD"); got != before {
t.Fatalf("rollback source = %s, want %s", got, before)
}
if got := readFile(t, bin); got != "original binary" {
t.Fatalf("rollback changed an already-matching binary: %q", got)
}
if res.BinaryBuilt {
t.Fatalf("rollback result must not claim a binary swap: %+v", res)
}
if buildPending(tr.install) {
t.Fatal("rollback must clear the pending build marker")
}
}
func TestRetryFinishesTheBuildWhenTheStateWriteFailed(t *testing.T) {
requireGit(t)
tr := newTree(t)
fake := scriptFakeGo(t)
fake.succeed(t)
bin := filepath.Join(tr.install, Binary)
writeFile(t, bin, "old binary bytes")
tr.upstreamCommit(t, "upstream moves", map[string]string{"internal_service.go": "package service\n\nconst Version = \"2\"\n"})
// A directory where writeState's temp file goes makes the state write fail.
blocked := filepath.Join(tr.install, ".update-state.json.tmp")
if err := os.Mkdir(blocked, 0o755); err != nil {
t.Fatal(err)
}
res, err := Apply(context.Background(), buildOpts(tr), nil)
if ue, ok := err.(*Error); !ok || ue.Reason != "state_unwritable" {
t.Fatalf("want state_unwritable, got %v (result %+v)", err, res)
}
if got := readFile(t, bin); got != "old binary bytes" {
t.Errorf("no build may happen while the state write is broken: %q", got)
}
// Clear the obstruction and retry: the owed build must happen, not a success report.
if err := os.Remove(blocked); err != nil {
t.Fatal(err)
}
res, err = Apply(context.Background(), buildOpts(tr), nil)
if err != nil {
t.Fatalf("retry failed: %v (result %+v)", err, res)
}
if !res.BinaryBuilt {
t.Fatalf("retry result = %+v, want the owed build", res)
}
if got := readFile(t, bin); !strings.Contains(got, "fake binary") {
t.Errorf("binary after retry = %q, want the compiled one", got)
}
}
// TestAdoptBuildFailureIsFinishedByTheNextUpdate: an adoption that landed the source but
// failed its build leaves a work tree that has "nothing to pull" on the next click. The
// same marker has to make that click compile rather than report "already up to date".
func TestAdoptBuildFailureIsFinishedByTheNextUpdate(t *testing.T) {
requireGit(t)
tr, dir := newAdoptFixture(t)
fake := scriptFakeGo(t)
fake.failBuild(t)
o := Options{Root: dir, Repo: tr.upstream, BinaryName: Binary}
res, err := Adopt(context.Background(), o, nil)
ue, ok := err.(*Error)
if !ok || ue.Reason != "build_failed" {
t.Fatalf("adopt: err=%v result=%+v, want build_failed", err, res)
}
snap, err := Status(context.Background(), o)
if err != nil {
t.Fatal(err)
}
if !snap.BuildPending {
t.Error("the adopted tree owes a build; Status must say so")
}
fake.succeed(t)
res, err = Apply(context.Background(), o, nil)
if err != nil {
t.Fatalf("retry failed: %v (result %+v)", err, res)
}
if !res.BinaryBuilt {
t.Fatalf("retry result = %+v, want the owed build", res)
}
if got := readFile(t, filepath.Join(dir, Binary)); !strings.Contains(got, "fake binary") {
t.Errorf("binary after retry = %q, want the compiled one", got)
}
if buildPending(dir) {
t.Error("a finished build must clear the pending marker")
}
}
// TestRetryWithoutToolchainKeepsSayingSoAndThenBuilds: the no_toolchain message tells the
// operator "安装 go 后再点一次更新即可补上二进制". Until the fix that retry answered
// success without compiling; the promise is only real if the click after installing go
// actually builds - and the clicks before it keep an honest refusal.
func TestRetryWithoutToolchainKeepsSayingSoAndThenBuilds(t *testing.T) {
requireGit(t)
tr := newTree(t)
hideToolchain(t)
bin := filepath.Join(tr.install, Binary)
writeFile(t, bin, "old binary bytes")
tr.upstreamCommit(t, "upstream moves", map[string]string{"internal_service.go": "package service\n\nconst Version = \"2\"\n"})
if _, err := Apply(context.Background(), buildOpts(tr), nil); err == nil {
t.Fatal("a tree without a toolchain must refuse the build, not report success")
} else if ue, ok := err.(*Error); !ok || ue.Reason != "no_toolchain" {
t.Fatalf("want no_toolchain, got %v", err)
}
// Still no go: the retry keeps refusing.
if _, err := Apply(context.Background(), buildOpts(tr), nil); err == nil {
t.Fatal("a retry without a toolchain must keep refusing, not report success")
}
// Toolchain installed: the same click now does what the message said it would.
scriptFakeGo(t)
res, err := Apply(context.Background(), buildOpts(tr), nil)
if err != nil {
t.Fatalf("retry with a toolchain failed: %v (result %+v)", err, res)
}
if !res.BinaryBuilt {
t.Errorf("result = %+v, want the binary built on retry", res)
}
if got := readFile(t, bin); !strings.Contains(got, "fake binary") {
t.Errorf("binary = %q, want the compiled one", got)
}
}
func TestNewUpdateFinishesThePendingCommitBeforeAdvancing(t *testing.T) {
requireGit(t)
tr := newTree(t)
fake := scriptFakeGo(t)
fake.failBuild(t)
bin := filepath.Join(tr.install, Binary)
writeFile(t, bin, "original binary")
tr.upstreamCommit(t, "second", map[string]string{"internal_service.go": "package service\n\nconst Version = \"2\"\n"})
if _, err := Apply(context.Background(), buildOpts(tr), nil); err == nil {
t.Fatal("the first build must fail")
}
second := mustGit(t, tr.install, "rev-parse", "--short", "HEAD")
tr.upstreamCommit(t, "third", map[string]string{"internal_service.go": "package service\n\nconst Version = \"3\"\n"})
third := mustGit(t, tr.upstream, "rev-parse", "--short", "HEAD")
fake.succeed(t)
res, err := Apply(context.Background(), buildOpts(tr), nil)
if err != nil {
t.Fatalf("second apply failed: %v (result %+v)", err, res)
}
if got := readFile(t, bin); !strings.Contains(got, third) {
t.Fatalf("live binary = %q, want third commit %s", got, third)
}
if got := readFile(t, bin+".prev"); !strings.Contains(got, second) {
t.Fatalf("rollback binary = %q, want second commit %s", got, second)
}
if _, err := Rollback(context.Background(), buildOpts(tr)); err != nil {
t.Fatalf("rollback failed: %v", err)
}
if head := mustGit(t, tr.install, "rev-parse", "--short", "HEAD"); head != second {
t.Fatalf("rollback source = %s, want %s", head, second)
}
if got := readFile(t, bin); !strings.Contains(got, second) {
t.Fatalf("rollback binary = %q, want the same commit as source %s", got, second)
}
}
func TestResidualPendingMarkerDoesNotReplaceTheRollbackBinary(t *testing.T) {
requireGit(t)
tr := newTree(t)
scriptFakeGo(t)
bin := filepath.Join(tr.install, Binary)
writeFile(t, bin, "original binary")
before := mustGit(t, tr.install, "rev-parse", "--short", "HEAD")
tr.upstreamCommit(t, "second", map[string]string{"internal_service.go": "package service\n\nconst Version = \"2\"\n"})
if _, err := Apply(context.Background(), buildOpts(tr), nil); err != nil {
t.Fatal(err)
}
updated := mustGit(t, tr.install, "rev-parse", "--short", "HEAD")
legacy, ok := readState(tr.install)
if !ok {
t.Fatal("successful update must leave rollback state")
}
legacy.BinaryCommit = ""
legacy.BinarySHA256 = ""
legacy.PreviousBinarySHA256 = ""
if err := writeState(tr.install, legacy); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(buildPendingPath(tr.install), []byte("source is ahead of the binary\n"), 0o644); err != nil {
t.Fatal(err)
}
res, err := Apply(context.Background(), buildOpts(tr), nil)
if err != nil {
t.Fatalf("retry with a residual marker failed: %v", err)
}
if !res.BinaryBuilt || !res.NeedsRestart {
t.Fatalf("the already-installed binary must still be reported as awaiting restart: %+v", res)
}
if got := readFile(t, bin+".prev"); got != "original binary" {
t.Fatalf("residual marker replaced rollback binary with %q", got)
}
if _, err := Rollback(context.Background(), buildOpts(tr)); err != nil {
t.Fatalf("rollback failed: %v", err)
}
if head := mustGit(t, tr.install, "rev-parse", "--short", "HEAD"); head != before {
t.Fatalf("rollback source = %s, want %s (updated was %s)", head, before, updated)
}
if got := readFile(t, bin); got != "original binary" {
t.Fatalf("rollback binary = %q, want original binary", got)
}
}
func TestLegacyPendingMarkerRefusesAHeadThatMovedAgain(t *testing.T) {
requireGit(t)
tr := newTree(t)
scriptFakeGo(t)
bin := filepath.Join(tr.install, Binary)
writeFile(t, bin, "original binary")
tr.upstreamCommit(t, "second", map[string]string{"internal_service.go": "package service\n\nconst Version = \"2\"\n"})
if _, err := Apply(context.Background(), buildOpts(tr), nil); err != nil {
t.Fatal(err)
}
rollbackBinary := readFile(t, bin+".prev")
legacy, ok := readState(tr.install)
if !ok {
t.Fatal("successful update must leave rollback state")
}
legacy.BinaryCommit = ""
legacy.BinarySHA256 = ""
legacy.PreviousBinarySHA256 = ""
if err := writeState(tr.install, legacy); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(buildPendingPath(tr.install), []byte("source is ahead of the binary\n"), 0o644); err != nil {
t.Fatal(err)
}
writeFile(t, filepath.Join(tr.install, "local.go"), "package service\n")
mustGit(t, tr.install, "add", "local.go")
mustGit(t, tr.install, "-c", "user.email=t@example.com", "-c", "user.name=T", "commit", "-q", "-m", "local move after update")
if _, err := Apply(context.Background(), buildOpts(tr), nil); err == nil {
t.Fatal("a legacy marker must not be reinterpreted after HEAD moved")
} else if ue, ok := err.(*Error); !ok || ue.Reason != "build_state_mismatch" {
t.Fatalf("want build_state_mismatch, got %v", err)
}
if got := readFile(t, bin+".prev"); got != rollbackBinary {
t.Fatalf("refused migration changed rollback binary: %q", got)
}
}
// A crash between the version write and the state write leaves the new number in the live
// config with no rollback record beside it. The marker is written *before* the config, so it
// still carries the pair - which is what lets the retry rebuild that record and the rollback
// put the old number back next to the old code.
func TestRetryRebuildsTheRollbackRecordTheCrashNeverWrote(t *testing.T) {
requireGit(t)
tr := newTree(t)
fake := scriptFakeGo(t)
fake.failBuild(t)
bin := filepath.Join(tr.install, Binary)
writeFile(t, bin, "original binary")
writeFile(t, filepath.Join(tr.install, "config.yaml"), "version: \"v1.0.0\"\nserver:\n port: 8088\n")
tr.upstreamCommit(t, "release: bump version", map[string]string{
"config.example.yaml": "version: \"v1.1.0\"\n",
"internal_service.go": "package service\n\nconst Version = \"2\"\n",
})
if _, err := Apply(context.Background(), buildOpts(tr), nil); err == nil {
t.Fatal("the first build must fail")
}
pending, present, err := readBuildPending(tr.install)
if err != nil || !present {
t.Fatalf("marker = %+v present=%v err=%v", pending, present, err)
}
if pending.VersionBefore != "v1.0.0" || pending.VersionAfter != "v1.1.0" {
t.Fatalf("the marker must carry the version pair before the config is written: %+v", pending)
}
// The crash: the config already carries the new number, the state file never landed.
if err := os.Remove(statePath(tr.install)); err != nil {
t.Fatal(err)
}
fake.succeed(t)
if _, err := Apply(context.Background(), buildOpts(tr), nil); err != nil {
t.Fatalf("retry failed: %v", err)
}
st, ok := readState(tr.install)
if !ok || st.VersionBefore != "v1.0.0" || st.VersionAfter != "v1.1.0" {
t.Fatalf("the retry must rebuild the rollback record from the marker: ok=%v state=%+v", ok, st)
}
if _, err := Rollback(context.Background(), buildOpts(tr)); err != nil {
t.Fatalf("rollback failed: %v", err)
}
live := readFile(t, filepath.Join(tr.install, "config.yaml"))
if !strings.Contains(live, `version: "v1.0.0"`) || !strings.Contains(live, "port: 8088") {
t.Fatalf("live config after rollback = %q, want the old version back with the settings intact", live)
}
}
func TestRetryRestoresProtectedContentWhenInterruptedBeforeMerge(t *testing.T) {
requireGit(t)
tr := newTree(t)
scriptFakeGo(t)
bin := filepath.Join(tr.install, Binary)
writeFile(t, bin, "original binary")
role := filepath.Join(tr.install, "roles", "shipped.yaml")
writeFile(t, role, "name: shipped\ndescription: mine\n")
tr.upstreamCommit(t, "second", map[string]string{
"internal_service.go": "package service\n\nconst Version = \"2\"\n",
"roles/shipped.yaml": "name: shipped\ndescription: upstream\n",
})
snap, err := Check(context.Background(), buildOpts(tr))
if err != nil || snap.CheckError != "" {
t.Fatalf("check: %v, %s", err, snap.CheckError)
}
backupDir, kept, _, err := stashProtected(context.Background(), tr.install, snap.sourceRef())
if err != nil {
t.Fatal(err)
}
if err := removeProtected(tr.install, kept); err != nil {
t.Fatal(err)
}
if fileExists(role) {
t.Fatal("fixture must stop after the operator role was moved aside")
}
previous := mustGit(t, tr.install, "rev-parse", "HEAD")
target := mustGit(t, tr.install, "rev-parse", snap.sourceRef())
oldHash, err := fileSHA256(bin)
if err != nil {
t.Fatal(err)
}
if err := writeBuildPending(tr.install, buildPendingState{
Commit: target, PreviousCommit: previous, BackupDir: backupDir,
KeptContent: kept, PreviousBinarySHA256: oldHash,
}); err != nil {
t.Fatal(err)
}
if _, err := Apply(context.Background(), buildOpts(tr), nil); err != nil {
t.Fatalf("retry failed: %v", err)
}
if got := readFile(t, role); !strings.Contains(got, "description: mine") {
t.Fatalf("operator role was not restored: %q", got)
}
}
func TestRetryAfterMergeRestoresOnlyUntouchedProtectedContent(t *testing.T) {
for _, tc := range []struct {
name string
afterMerge string
want string
}{
{name: "merge copy untouched", want: "description: mine before crash"},
{name: "operator edited after crash", afterMerge: "name: shipped\ndescription: mine after crash\n", want: "description: mine after crash"},
} {
t.Run(tc.name, func(t *testing.T) {
requireGit(t)
tr := newTree(t)
scriptFakeGo(t)
bin := filepath.Join(tr.install, Binary)
writeFile(t, bin, "original binary")
role := filepath.Join(tr.install, "roles", "shipped.yaml")
writeFile(t, role, "name: shipped\ndescription: mine before crash\n")
tr.upstreamCommit(t, "second", map[string]string{
"internal_service.go": "package service\n\nconst Version = \"2\"\n",
"roles/shipped.yaml": "name: shipped\ndescription: upstream\n",
})
snap, err := Check(context.Background(), buildOpts(tr))
if err != nil || snap.CheckError != "" {
t.Fatalf("check: %v, %s", err, snap.CheckError)
}
backupDir, kept, _, err := stashProtected(context.Background(), tr.install, snap.sourceRef())
if err != nil {
t.Fatal(err)
}
if err := removeProtected(tr.install, kept); err != nil {
t.Fatal(err)
}
previous := mustGit(t, tr.install, "rev-parse", "HEAD")
target := mustGit(t, tr.install, "rev-parse", snap.sourceRef())
oldHash, err := fileSHA256(bin)
if err != nil {
t.Fatal(err)
}
if err := writeBuildPending(tr.install, buildPendingState{
Commit: target, PreviousCommit: previous, BackupDir: backupDir,
KeptContent: kept, PreviousBinarySHA256: oldHash,
}); err != nil {
t.Fatal(err)
}
mustGit(t, tr.install, "merge", "--ff-only", "--no-verify", snap.sourceRef())
if tc.afterMerge != "" {
writeFile(t, role, tc.afterMerge)
}
if _, err := Apply(context.Background(), buildOpts(tr), nil); err != nil {
t.Fatalf("retry failed: %v", err)
}
if got := readFile(t, role); !strings.Contains(got, tc.want) {
t.Fatalf("protected content after retry = %q, want %q", got, tc.want)
}
})
}
}
// Legacy records cannot tell an installed rebuild from a binary still owed.
// A different build of the same source must never be promoted into .prev.
func TestLegacyPendingWithUnprovableBinaryPreservesRollback(t *testing.T) {
requireGit(t)
tr := newTree(t)
scriptFakeGo(t)
bin := filepath.Join(tr.install, Binary)
writeFile(t, bin, "original binary")
tr.upstreamCommit(t, "second", map[string]string{"internal_service.go": "package service\nconst Version = \"2\"\n"})
if _, err := Apply(context.Background(), buildOpts(tr), nil); err != nil {
t.Fatal(err)
}
st, _ := readState(tr.install)
st.BinaryCommit, st.BinarySHA256, st.PreviousBinarySHA256 = "", "", ""
if err := writeState(tr.install, st); err != nil {
t.Fatal(err)
}
writeFile(t, bin, "different build of the updated commit")
writeFile(t, buildPendingPath(tr.install), "source is ahead of the binary\n")
head := mustGit(t, tr.install, "rev-parse", "HEAD")
_, err := Apply(context.Background(), buildOpts(tr), nil)
if ue, ok := err.(*Error); !ok || ue.Reason != "binary_state_unknown" {
t.Fatalf("want binary_state_unknown, got %v", err)
}
if got := readFile(t, bin+".prev"); got != "original binary" {
t.Fatalf("rollback binary overwritten: %q", got)
}
if got := readFile(t, bin); got != "different build of the updated commit" {
t.Fatalf("live binary overwritten: %q", got)
}
if got := mustGit(t, tr.install, "rev-parse", "HEAD"); got != head {
t.Fatal("refusal moved HEAD")
}
if !buildPending(tr.install) {
t.Fatal("refusal cleared recovery marker")
}
}
func TestLegacyMarkerUsesRecordedHashForADifferentInstalledBuild(t *testing.T) {
requireGit(t)
tr := newTree(t)
scriptFakeGo(t)
bin := filepath.Join(tr.install, Binary)
writeFile(t, bin, "original binary")
tr.upstreamCommit(t, "second", map[string]string{"internal_service.go": "package service\nconst Version = \"2\"\n"})
if _, err := Apply(context.Background(), buildOpts(tr), nil); err != nil {
t.Fatal(err)
}
writeFile(t, bin, "another valid build recorded by the updater")
st, _ := readState(tr.install)
var err error
st.BinarySHA256, err = fileSHA256(bin)
if err != nil {
t.Fatal(err)
}
if err := writeState(tr.install, st); err != nil {
t.Fatal(err)
}
writeFile(t, buildPendingPath(tr.install), "source is ahead of the binary\n")
if _, err := Apply(context.Background(), buildOpts(tr), nil); err != nil {
t.Fatal(err)
}
if got := readFile(t, bin+".prev"); got != "original binary" {
t.Fatalf("rollback binary overwritten: %q", got)
}
if _, err := Rollback(context.Background(), buildOpts(tr)); err != nil {
t.Fatal(err)
}
if got := readFile(t, bin); got != "original binary" {
t.Fatalf("rollback binary = %q", got)
}
}
func TestInstallBinaryMissingStagingKeepsLiveAndPrevious(t *testing.T) {
dir := t.TempDir()
bin := filepath.Join(dir, Binary)
writeFile(t, bin, "live binary")
writeFile(t, bin+".prev", "rollback binary")
if _, err := installBinary(filepath.Join(dir, "missing-staging"), bin); err == nil {
t.Fatal("missing staging must fail")
}
if got := readFile(t, bin); got != "live binary" {
t.Fatalf("live binary lost: %q", got)
}
if got := readFile(t, bin+".prev"); got != "rollback binary" {
t.Fatalf("previous binary lost: %q", got)
}
}
func TestLegacyMarkerRefusesContradictoryState(t *testing.T) {
for _, tc := range []struct {
name, reason string
badCommit bool
}{
{name: "unrelated binary commit", reason: "bad_state", badCommit: true},
{name: "changed binary hash", reason: "binary_changed"},
} {
t.Run(tc.name, func(t *testing.T) {
requireGit(t)
tr := newTree(t)
scriptFakeGo(t)
bin := filepath.Join(tr.install, Binary)
writeFile(t, bin, "original binary")
tr.upstreamCommit(t, "second", map[string]string{"internal_service.go": "package service\nconst Version = \"2\"\n"})
if _, err := Apply(context.Background(), buildOpts(tr), nil); err != nil {
t.Fatal(err)
}
st, _ := readState(tr.install)
if tc.badCommit {
st.BinaryCommit = "not-a-commit"
} else {
st.BinarySHA256 = strings.Repeat("0", 64)
}
if err := writeState(tr.install, st); err != nil {
t.Fatal(err)
}
writeFile(t, buildPendingPath(tr.install), "source is ahead of the binary\n")
live := readFile(t, bin)
stateBytes := readFile(t, statePath(tr.install))
_, err := Apply(context.Background(), buildOpts(tr), nil)
if ue, ok := err.(*Error); !ok || ue.Reason != tc.reason {
t.Fatalf("want %s, got %v", tc.reason, err)
}
if got := readFile(t, bin); got != live {
t.Fatal("refusal changed live binary")
}
if got := readFile(t, bin+".prev"); got != "original binary" {
t.Fatal("refusal changed rollback binary")
}
if got := readFile(t, statePath(tr.install)); got != stateBytes {
t.Fatal("refusal rewrote state")
}
})
}
}

View File

@ -0,0 +1,7 @@
//go:build !windows
package update
import "os"
func replaceBinary(src, dst string) error { return os.Rename(src, dst) }

View File

@ -0,0 +1,15 @@
package update
import "golang.org/x/sys/windows"
func replaceBinary(src, dst string) error {
from, err := windows.UTF16PtrFromString(src)
if err != nil {
return err
}
to, err := windows.UTF16PtrFromString(dst)
if err != nil {
return err
}
return windows.MoveFileEx(from, to, windows.MOVEFILE_REPLACE_EXISTING|windows.MOVEFILE_WRITE_THROUGH)
}

View File

@ -0,0 +1,98 @@
package update
import (
"context"
"encoding/json"
"fmt"
"os"
"path/filepath"
)
const rollbackPendingFile = ".update-rollback-pending.json"
type rollbackPendingState struct {
State State `json:"state"`
BackupDir string `json:"backup_dir"`
Kept []string `json:"kept"`
Deleted []string `json:"deleted"`
RestoreBinary bool `json:"restore_binary"`
LiveSHA256 string `json:"live_sha256"`
PreviousSHA256 string `json:"previous_sha256"`
}
func readRollbackPending(root string) (*rollbackPendingState, error) {
data, err := os.ReadFile(filepath.Join(root, rollbackPendingFile))
if os.IsNotExist(err) {
return nil, nil
}
if err != nil {
return nil, err
}
var pending rollbackPendingState
if err := json.Unmarshal(data, &pending); err != nil {
return nil, err
}
if pending.State.PreviousCommit == "" || pending.State.UpdatedCommit == "" {
return nil, fmt.Errorf("回滚恢复记录缺少提交")
}
return &pending, nil
}
func writeRollbackPending(root string, pending rollbackPendingState) error {
data, err := json.Marshal(pending)
if err != nil {
return err
}
path := filepath.Join(root, rollbackPendingFile)
if err := os.WriteFile(path+".tmp", data, 0600); err != nil {
return err
}
return os.Rename(path+".tmp", path)
}
// finishRollback can run again after a reset or binary rename was interrupted.
// Hashes distinguish the old live binary from the already-restored one.
func finishRollback(ctx context.Context, opts Options, pending rollbackPendingState) (*Result, error) {
root, err := opts.installRoot()
if err != nil {
return nil, err
}
bin := filepath.Join(root, opts.binaryName())
if pending.RestoreBinary {
current, currentErr := fileSHA256(bin)
if currentErr != nil || current != pending.PreviousSHA256 {
if currentErr == nil && current != pending.LiveSHA256 {
return nil, &Error{Reason: "binary_changed", Message: "回滚中断后现有二进制发生变化,已保留现场"}
}
previous, previousErr := fileSHA256(bin + ".prev")
if previousErr != nil || previous != pending.PreviousSHA256 {
return nil, &Error{Reason: "binary_changed", Message: "回滚备份与恢复记录不一致,已保留现场"}
}
if err := restorePrevBinary(bin); err != nil {
return nil, &Error{Reason: "swap_failed", Message: err.Error()}
}
}
} else if pending.LiveSHA256 != "" {
current, err := fileSHA256(bin)
if err != nil || current != pending.LiveSHA256 {
return nil, &Error{Reason: "binary_changed", Message: "回滚中断后现有二进制发生变化,已保留现场"}
}
}
content := buildPendingState{BackupDir: pending.BackupDir, KeptContent: pending.Kept, DeletedContent: pending.Deleted}
if err := restoreInterruptedProtected(ctx, root, content, true); err != nil {
return nil, err
}
if err := clearBuildPending(root); err != nil {
return nil, err
}
if err := restoreVersionAfterRollback(root, pending.State); err != nil {
return nil, &Error{Reason: "version_restore_failed", Message: "源码和二进制已回滚,但版本恢复失败;修复配置写入后重试回滚:" + err.Error()}
}
if err := os.Remove(statePath(root)); err != nil && !os.IsNotExist(err) {
return nil, err
}
if err := os.Remove(filepath.Join(root, rollbackPendingFile)); err != nil {
return nil, err
}
return &Result{FromCommit: shortHash(pending.State.UpdatedCommit), ToCommit: shortHash(pending.State.PreviousCommit), KeptContent: pending.Kept, BinaryPath: bin, BinaryBuilt: pending.RestoreBinary, BackupDir: pending.BackupDir, NeedsRestart: true}, nil
}

View File

@ -0,0 +1,114 @@
package update
import (
"context"
"os"
"path/filepath"
"strings"
"testing"
)
// TestRollbackKeepsOperatorEditsToProtectedFiles pins the promise docs make - a rollback
// undoes the update, not the operator's content. reset --hard discards every local change
// to tracked files, not just the update's, so both an edit made before the update and one
// made after it have to be put back on top of the old commit.
func TestRollbackKeepsOperatorEditsToProtectedFiles(t *testing.T) {
requireGit(t)
tr := newTree(t)
// Edited before the update: Apply itself keeps this one (its stash covers it), which is
// exactly the shape the rollback then used to wipe.
writeFile(t, filepath.Join(tr.install, "roles", "shipped.yaml"), "name: shipped\ndescription: mine before\n")
tr.upstreamCommit(t, "upstream moves code and rewrites roles", map[string]string{
"internal_service.go": "package service\n\nconst Version = \"2\"\n",
"roles/shipped.yaml": "name: shipped\ndescription: upstream rewrite\n",
"roles/extra.yaml": "name: extra\ndescription: upstream copy\n",
})
if _, err := Apply(context.Background(), opts(tr), nil); err != nil {
t.Fatal(err)
}
// Edited after the update: no stash ever saw this one.
writeFile(t, filepath.Join(tr.install, "roles", "extra.yaml"), "name: extra\ndescription: mine after\n")
// The binary pair a swap leaves behind, so the rollback has one to restore.
bin := filepath.Join(tr.install, Binary)
writeFile(t, bin, "new binary bytes")
writeFile(t, bin+".prev", "old binary bytes")
res, err := Rollback(context.Background(), Options{Root: tr.install})
if err != nil {
t.Fatalf("rollback failed: %v", err)
}
if got := readFile(t, filepath.Join(tr.install, "internal_service.go")); !strings.Contains(got, "Version = \"1\"") {
t.Errorf("code after rollback = %q, want the old version back", got)
}
if got := readFile(t, filepath.Join(tr.install, "roles", "shipped.yaml")); !strings.Contains(got, "mine before") {
t.Errorf("an edit made before the update was wiped by the rollback: %q", got)
}
if got := readFile(t, filepath.Join(tr.install, "roles", "extra.yaml")); !strings.Contains(got, "mine after") {
t.Errorf("an edit made after the update was wiped by the rollback: %q", got)
}
want := "roles/extra.yaml,roles/shipped.yaml"
if got := strings.Join(res.KeptContent, ","); got != want {
t.Errorf("keptContent = %v, want %s", res.KeptContent, want)
}
}
// TestRollbackKeepsAHandDeletionOfAProtectedFile: a deletion is a local change like any
// other. reset --hard would bring the old commit's copy back; the rollback has to re-apply
// the deletion instead.
func TestRollbackKeepsAHandDeletionOfAProtectedFile(t *testing.T) {
requireGit(t)
tr := newTree(t)
tr.upstreamCommit(t, "upstream moves", map[string]string{"internal_service.go": "package service\n\nconst Version = \"2\"\n"})
if _, err := Apply(context.Background(), opts(tr), nil); err != nil {
t.Fatal(err)
}
gone := filepath.Join(tr.install, "roles", "shipped.yaml")
if err := os.Remove(gone); err != nil {
t.Fatal(err)
}
bin := filepath.Join(tr.install, Binary)
writeFile(t, bin, "new binary bytes")
writeFile(t, bin+".prev", "old binary bytes")
res, err := Rollback(context.Background(), Options{Root: tr.install})
if err != nil {
t.Fatalf("rollback failed: %v", err)
}
if _, err := os.Stat(gone); !os.IsNotExist(err) {
t.Errorf("a file deleted by hand was resurrected by the rollback (%v); result %+v", err, res)
}
}
func TestRollbackKeepsProtectedFileRecreatedAfterUpstreamDeletedIt(t *testing.T) {
requireGit(t)
tr := newTree(t)
if err := os.Remove(filepath.Join(tr.upstream, "roles", "shipped.yaml")); err != nil {
t.Fatal(err)
}
writeFile(t, filepath.Join(tr.upstream, "internal_service.go"), "package service\n\nconst Version = \"2\"\n")
mustGit(t, tr.upstream, "add", "-A")
mustGit(t, tr.upstream, "-c", "user.email=t@example.com", "-c", "user.name=T", "commit", "-q", "-m", "upstream deletes the shipped role")
if _, err := Apply(context.Background(), opts(tr), nil); err != nil {
t.Fatal(err)
}
recreated := filepath.Join(tr.install, "roles", "shipped.yaml")
writeFile(t, recreated, "name: shipped\ndescription: mine after upstream deleted it\n")
bin := filepath.Join(tr.install, Binary)
writeFile(t, bin, "new binary bytes")
writeFile(t, bin+".prev", "old binary bytes")
res, err := Rollback(context.Background(), Options{Root: tr.install})
if err != nil {
t.Fatalf("rollback failed: %v", err)
}
if got := readFile(t, recreated); !strings.Contains(got, "mine after upstream deleted it") {
t.Fatalf("rollback overwrote the operator's recreated role: %q", got)
}
if got := strings.Join(res.KeptContent, ","); got != "roles/shipped.yaml" {
t.Fatalf("keptContent = %v, want the recreated role named", res.KeptContent)
}
}

View File

@ -0,0 +1,330 @@
package update
import (
"bufio"
"context"
"fmt"
"os"
"os/exec"
"path/filepath"
"testing"
"time"
)
func TestApplyRefusesRepositorySubdirectory(t *testing.T) {
requireGit(t)
tr := newTree(t)
sub := filepath.Join(tr.install, "settings")
if err := os.Mkdir(sub, 0755); err != nil {
t.Fatal(err)
}
head := mustGit(t, tr.install, "rev-parse", "HEAD")
tr.upstreamCommit(t, "second", map[string]string{"run.sh": "new script\n"})
_, err := Apply(context.Background(), Options{Root: sub, Repo: tr.upstream, BinaryName: "none"}, nil)
if err == nil {
t.Fatal("updating a repository subdirectory must be refused")
}
if got := mustGit(t, tr.install, "rev-parse", "HEAD"); got != head {
t.Fatal("refusal changed parent repository")
}
}
func TestInstallLockReleasedWhenProcessIsKilled(t *testing.T) {
if root := os.Getenv("CSAI_TEST_LOCK_ROOT"); root != "" {
release, err := LockInstall(Options{Root: root})
if err != nil {
t.Fatal(err)
}
defer release()
fmt.Println("locked")
time.Sleep(time.Hour)
return
}
root := t.TempDir()
bin, err := os.Executable()
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, bin, "-test.run=^TestInstallLockReleasedWhenProcessIsKilled$")
cmd.Env = append(os.Environ(), "CSAI_TEST_LOCK_ROOT="+root)
stdout, err := cmd.StdoutPipe()
if err != nil {
t.Fatal(err)
}
if err := cmd.Start(); err != nil {
t.Fatal(err)
}
defer cmd.Process.Kill()
line, err := bufio.NewReader(stdout).ReadString('\n')
if err != nil || line != "locked\n" {
t.Fatalf("child did not acquire lock: %q %v", line, err)
}
if release, err := LockInstall(Options{Root: root}); err == nil {
release()
t.Fatal("parent acquired child's lock")
}
if err := cmd.Process.Kill(); err != nil {
t.Fatal(err)
}
_ = cmd.Wait()
release, err := LockInstall(Options{Root: root})
if err != nil {
t.Fatalf("crashed process left a stale lock: %v", err)
}
release()
}
func TestFirstBuildDoesNotUseAnUnrelatedPreviousBinary(t *testing.T) {
requireGit(t)
tr := newTree(t)
scriptFakeGo(t)
bin := filepath.Join(tr.install, Binary)
writeFile(t, bin+".prev", "unrelated old binary")
tr.upstreamCommit(t, "second", map[string]string{"run.sh": "new script\n"})
if _, err := Apply(context.Background(), buildOpts(tr), nil); err != nil {
t.Fatal(err)
}
head := mustGit(t, tr.install, "rev-parse", "HEAD")
if _, err := Rollback(context.Background(), buildOpts(tr)); err == nil {
t.Fatal("first build must not roll back to an unrelated .prev")
}
if got := mustGit(t, tr.install, "rev-parse", "HEAD"); got != head {
t.Fatal("refusal reset source")
}
}
func TestInterruptedAdoptionCanResumeFromUnbornHead(t *testing.T) {
requireGit(t)
tr, dir := newAdoptFixture(t)
scriptFakeGo(t)
role := filepath.Join(dir, "roles", "shipped.yaml")
original := readFile(t, role)
mustGit(t, dir, "init", "-q")
mustGit(t, dir, "remote", "add", "origin", tr.upstream)
branch, _, _, err := fetchSource(context.Background(), dir, tr.upstream)
if err != nil {
t.Fatal(err)
}
scan, err := scanAdoption(context.Background(), dir, dir, "origin/"+branch)
if err != nil {
t.Fatal(err)
}
backup := filepath.Join(dir, ".update-backup", "interrupted")
for _, rel := range append(scan.changed, scan.kept...) {
dst := filepath.Join(backup, "overwritten", rel)
if Protected(rel) {
dst = filepath.Join(backup, rel)
}
if err := copyFile(filepath.Join(dir, rel), dst, 0644); err != nil {
t.Fatal(err)
}
}
target := mustGit(t, dir, "rev-parse", "origin/"+branch)
if err := writeBuildPending(dir, buildPendingState{Commit: target, AdoptBranch: branch, BackupDir: backup, KeptContent: scan.kept, OverwrittenContent: scan.changed, PreviousBinaryAbsent: true}); err != nil {
t.Fatal(err)
}
if _, err := Apply(context.Background(), Options{Root: dir, Repo: tr.upstream}, nil); err != nil {
t.Fatalf("resume: %v", err)
}
if got := readFile(t, role); got != original {
t.Fatalf("resume lost role: %q", got)
}
if buildPending(dir) {
t.Fatal("resume left a pending marker")
}
}
func TestInterruptedRollbackResumesAfterSourceReset(t *testing.T) {
for _, swapped := range []bool{false, true} {
t.Run(fmt.Sprint(swapped), func(t *testing.T) {
requireGit(t)
tr := newTree(t)
scriptFakeGo(t)
bin := filepath.Join(tr.install, Binary)
writeFile(t, bin, "original binary")
tr.upstreamCommit(t, "second", map[string]string{"run.sh": "new script\n"})
if _, err := Apply(context.Background(), buildOpts(tr), nil); err != nil {
t.Fatal(err)
}
st, _ := readState(tr.install)
role := filepath.Join(tr.install, "roles", "shipped.yaml")
writeFile(t, role, "name: operator edit after update\n")
changes, _, _ := localChanges(context.Background(), tr.install)
backup, kept, deleted, err := stashProtectedEdits(context.Background(), tr.install, st.PreviousCommit, changes)
if err != nil {
t.Fatal(err)
}
liveHash, _ := fileSHA256(bin)
previousHash, _ := fileSHA256(bin + ".prev")
pending := rollbackPendingState{State: st, BackupDir: backup, Kept: kept, Deleted: deleted, RestoreBinary: true, LiveSHA256: liveHash, PreviousSHA256: previousHash}
if err := writeRollbackPending(tr.install, pending); err != nil {
t.Fatal(err)
}
mustGit(t, tr.install, "reset", "--hard", st.PreviousCommit)
if swapped {
if err := restorePrevBinary(bin); err != nil {
t.Fatal(err)
}
}
if _, err := Apply(context.Background(), buildOpts(tr), nil); err == nil {
t.Fatal("update must refuse an interrupted rollback")
}
if _, err := Rollback(context.Background(), buildOpts(tr)); err != nil {
t.Fatalf("resume rollback: %v", err)
}
if got := readFile(t, bin); got != "original binary" {
t.Fatalf("wrong binary after resume: %q", got)
}
if got := readFile(t, role); got != "name: operator edit after update\n" {
t.Fatalf("role lost after resume: %q", got)
}
if pending, err := readRollbackPending(tr.install); err != nil || pending != nil {
t.Fatal("rollback journal not cleared")
}
})
}
}
func TestRollbackRemovesVersionInsertedIntoUnversionedConfig(t *testing.T) {
requireGit(t)
tr := newTree(t)
scriptFakeGo(t)
writeFile(t, filepath.Join(tr.install, Binary), "old binary")
before := readFile(t, filepath.Join(tr.install, "config.yaml"))
tr.upstreamCommit(t, "release", map[string]string{"config.example.yaml": "version: v2.0.0\n"})
if _, err := Apply(context.Background(), buildOpts(tr), nil); err != nil {
t.Fatal(err)
}
if _, err := Rollback(context.Background(), buildOpts(tr)); err != nil {
t.Fatal(err)
}
if got := readFile(t, filepath.Join(tr.install, "config.yaml")); got != before {
t.Fatalf("rollback did not restore an unversioned config: %q", got)
}
}
func TestApplyRefusesIgnoredSourceCollision(t *testing.T) {
requireGit(t)
tr := newTree(t)
writeFile(t, filepath.Join(tr.install, ".git", "info", "exclude"), "local.go\n")
writeFile(t, filepath.Join(tr.install, "local.go"), "package operator\n")
head := mustGit(t, tr.install, "rev-parse", "HEAD")
tr.upstreamCommit(t, "add source", map[string]string{"local.go": "package upstream\n"})
if _, err := Apply(context.Background(), opts(tr), nil); err == nil {
t.Fatal("ignored source collision must be refused")
}
if got := readFile(t, filepath.Join(tr.install, "local.go")); got != "package operator\n" {
t.Fatal("ignored source was lost")
}
if got := mustGit(t, tr.install, "rev-parse", "HEAD"); got != head {
t.Fatal("refusal changed HEAD")
}
}
func TestBuildRefusesSourceChangesMadeAfterPreflight(t *testing.T) {
requireGit(t)
tr := newTree(t)
scriptFakeGo(t)
bin := filepath.Join(tr.install, Binary)
writeFile(t, bin, "old binary")
tr.upstreamCommit(t, "second", map[string]string{"run.sh": "new script\n"})
_, err := Apply(context.Background(), buildOpts(tr), func(step Step) {
if step.Phase == "build" {
writeFile(t, filepath.Join(tr.install, "run.sh"), "operator edit during build\n")
}
})
if ue, ok := err.(*Error); !ok || ue.Reason != "local_source_edits" {
t.Fatalf("want refusal of changed source, got %v", err)
}
if got := readFile(t, bin); got != "old binary" {
t.Fatal("unmatched binary installed")
}
if !buildPending(tr.install) {
t.Fatal("refusal must keep the recovery marker")
}
}
func TestApplyKeepsProtectedDeletion(t *testing.T) {
requireGit(t)
tr := newTree(t)
role := filepath.Join(tr.install, "roles", "shipped.yaml")
if err := os.Remove(role); err != nil {
t.Fatal(err)
}
tr.upstreamCommit(t, "rewrite role", map[string]string{"roles/shipped.yaml": "name: new upstream\n"})
if _, err := Apply(context.Background(), opts(tr), nil); err != nil {
t.Fatal(err)
}
if _, err := os.Lstat(role); !os.IsNotExist(err) {
t.Fatalf("deleted role resurrected: %v", err)
}
}
func TestAdoptRefusesExistingInvalidGitMetadata(t *testing.T) {
requireGit(t)
tr, dir := newAdoptFixture(t)
metadata := filepath.Join(dir, ".git", "operator-note")
writeFile(t, metadata, "keep this metadata")
_, err := Adopt(context.Background(), Options{Root: dir, Repo: tr.upstream, BinaryName: "none"}, nil)
if err == nil {
t.Fatal("existing .git must never be taken over")
}
if got := readFile(t, metadata); got != "keep this metadata" {
t.Fatal("existing metadata changed")
}
}
func TestAdoptionRefusesFileDirectoryConflict(t *testing.T) {
requireGit(t)
tr, dir := newAdoptFixture(t)
if err := os.Remove(filepath.Join(dir, "run.sh")); err != nil {
t.Fatal(err)
}
valuable := filepath.Join(dir, "run.sh", "local-note")
writeFile(t, valuable, "operator content")
if _, err := Preview(context.Background(), Options{Root: dir, Repo: tr.upstream}); err == nil {
t.Fatal("preview must report a directory conflict")
}
if _, err := Adopt(context.Background(), Options{Root: dir, Repo: tr.upstream, BinaryName: "none"}, nil); err == nil {
t.Fatal("adoption must refuse a directory conflict")
}
if got := readFile(t, valuable); got != "operator content" {
t.Fatal("directory content lost")
}
}
func TestApplyKeepsIgnoredConfigWhenUpstreamStartsTrackingIt(t *testing.T) {
requireGit(t)
tr := newTree(t)
writeFile(t, filepath.Join(tr.install, ".git", "info", "exclude"), "config.yaml\n")
before := readFile(t, filepath.Join(tr.install, "config.yaml"))
tr.upstreamCommit(t, "track example config", map[string]string{"config.yaml": "server:\n port: 9999\n"})
if _, err := Apply(context.Background(), opts(tr), nil); err != nil {
t.Fatal(err)
}
if got := readFile(t, filepath.Join(tr.install, "config.yaml")); got != before {
t.Fatalf("ignored config overwritten: %q", got)
}
}
func TestUpdateOperationsShareInstallationLock(t *testing.T) {
requireGit(t)
tr := newTree(t)
release, err := LockInstall(opts(tr))
if err != nil {
t.Fatal(err)
}
defer release()
for _, run := range []func() error{
func() error { _, err := Check(context.Background(), opts(tr)); return err },
func() error { _, err := Apply(context.Background(), opts(tr), nil); return err },
func() error { _, err := Rollback(context.Background(), opts(tr)); return err },
func() error { _, err := Adopt(context.Background(), opts(tr), nil); return err },
} {
if ue, ok := run().(*Error); !ok || ue.Reason != "update_busy" {
t.Fatalf("concurrent operation was not refused: %v", ue)
}
}
}

View File

@ -0,0 +1,164 @@
package update
import (
"context"
"path/filepath"
"strings"
"testing"
)
// The update source is one address (config.yaml update.repo): the official repository by
// default, changeable in one field to a mirror, a fork or a second-development
// repository. The branch that is followed is the source's own default branch, so nothing
// about branches needs configuring. These tests keep that path honest: the configured
// address must be what git is pointed at, the default must be the official repository,
// the followed branch must come from the source itself, and git's ext:: transport (which
// executes commands) must never get through.
func TestValidRemoteURL(t *testing.T) {
yes := []string{
"https://github.com/Sycun/CyberStrikeAI.git",
"http://example.com/x.git",
"ssh://git@example.com/x.git",
"git://example.com/x.git",
"file:///srv/repos/x.git",
"/Volumes/code/CyberStrikeAI/开发版-CyberStrikeAI",
}
no := []string{
"",
"-u./evil",
"ext::sh -c whoami",
"ext::touch /tmp/x",
"a\nb",
"javascript:alert(1)",
"ftp://example.com/x",
" https://github.com/x/y.git",
strings.Repeat("a", 600),
}
for _, s := range yes {
if !ValidRemoteURL(s) {
t.Errorf("%q must be accepted as a fetch source", s)
}
}
for _, s := range no {
if ValidRemoteURL(s) {
t.Errorf("%q must be rejected before it reaches git", s)
}
}
}
func TestDefaultRepoIsTheOfficialRepository(t *testing.T) {
requireGit(t)
tr := newTree(t)
snap, err := Status(context.Background(), Options{Root: tr.install})
if err != nil {
t.Fatal(err)
}
if snap.Repo != DefaultRepoURL || snap.RepoConfigured {
t.Fatalf("repo = %q configured=%v, want the official default %q without configuration",
snap.Repo, snap.RepoConfigured, DefaultRepoURL)
}
if DefaultRepoURL != "https://github.com/AIPentest/CyberStrikeAI.git" {
t.Errorf("DefaultRepoURL = %q, want the official repository", DefaultRepoURL)
}
}
func TestCheckAndApplyFromTheConfiguredRepo(t *testing.T) {
requireGit(t)
tr := newTree(t)
// No remote at all: the source is purely the configured address.
mustGit(t, tr.install, "remote", "remove", "origin")
urlOpts := Options{Root: tr.install, Repo: tr.upstream, BinaryName: "none"}
snap, err := Status(context.Background(), urlOpts)
if err != nil {
t.Fatal(err)
}
if !snap.Installed || snap.Repo != tr.upstream || !snap.RepoConfigured {
t.Fatalf("source must resolve to the configured address: installed=%v repo=%q configured=%v",
snap.Installed, snap.Repo, snap.RepoConfigured)
}
if snap.Branch != "main" {
t.Fatalf("local branch = %q, want main", snap.Branch)
}
tr.upstreamCommit(t, "second: bump service", map[string]string{
"internal_service.go": "package service\n\nconst Version = \"2\"\n",
})
snap, err = Check(context.Background(), urlOpts)
if err != nil {
t.Fatal(err)
}
if snap.CheckError != "" {
t.Fatalf("check failed: %s", snap.CheckError)
}
if !snap.UpdateAvailable || snap.Behind != 1 {
t.Fatalf("behind=%d available=%v, want 1/true", snap.Behind, snap.UpdateAvailable)
}
if snap.TargetBranch != "main" {
t.Fatalf("targetBranch = %q, want the source's own default branch", snap.TargetBranch)
}
res, err := Apply(context.Background(), urlOpts, nil)
if err != nil {
t.Fatalf("apply failed: %v\nresult: %+v", err, res)
}
if res.Commits != 1 {
t.Fatalf("res = %+v, want one commit moved", res)
}
if got := readFile(t, filepath.Join(tr.install, "internal_service.go")); !strings.Contains(got, "Version = \"2\"") {
t.Fatalf("code was not updated: %q", got)
}
// The configured source parks its ref in a namespace of its own; it must not fabricate a
// remote the operator never configured.
if remotes := strings.TrimSpace(mustGit(t, tr.install, "remote")); remotes != "" {
t.Fatalf("a configured repo must not create a remote, got %q", remotes)
}
}
func TestSourceFollowsTheRepositoriesDefaultBranch(t *testing.T) {
requireGit(t)
tr := newTree(t)
// The source publishes a default branch that is not "main": the update follows what
// the source itself names, so nothing about branches needs configuring.
mustGit(t, tr.upstream, "checkout", "-q", "-b", "stable")
tr.upstreamCommit(t, "stable: bump service", map[string]string{
"internal_service.go": "package service\n\nconst Version = \"2\"\n",
})
snap, err := Check(context.Background(), Options{Root: tr.install, Repo: tr.upstream, BinaryName: "none"})
if err != nil {
t.Fatal(err)
}
if snap.CheckError != "" {
t.Fatalf("check failed: %s", snap.CheckError)
}
if snap.TargetBranch != "stable" {
t.Fatalf("targetBranch = %q, want the source's default branch stable", snap.TargetBranch)
}
if !snap.UpdateAvailable || snap.Behind != 1 {
t.Fatalf("behind=%d available=%v, want 1/true against the source's default branch", snap.Behind, snap.UpdateAvailable)
}
res, err := Apply(context.Background(), Options{Root: tr.install, Repo: tr.upstream, BinaryName: "none"}, nil)
if err != nil {
t.Fatalf("apply failed: %v\nresult: %+v", err, res)
}
if got := readFile(t, filepath.Join(tr.install, "internal_service.go")); !strings.Contains(got, "Version = \"2\"") {
t.Fatalf("code was not updated from the source's default branch: %q", got)
}
}
func TestInvalidRemoteURLIsAReadableStateNotAnError(t *testing.T) {
requireGit(t)
tr := newTree(t)
snap, err := Status(context.Background(), Options{Root: tr.install, Repo: "ext::sh -c true"})
if err != nil {
t.Fatalf("a bad configured source is a state the page can show, not a fault: %v", err)
}
if !strings.Contains(snap.CheckError, "不合法") {
t.Fatalf("checkError = %q, want the illegality named", snap.CheckError)
}
}

514
internal/update/update.go Normal file
View File

@ -0,0 +1,514 @@
// Package update makes "bring this installation up to the newest commit of the
// repository it updates from" one action: fetch, move the working tree, rebuild the
// binary, swap it in.
//
// The update source is one thing: a repository address. It defaults to the official
// repository and can be pointed at a mirror, a fork or a second-development repository
// with one config field (config.yaml update.repo); the branch that is followed is that
// repository's own default branch, so there is nothing else to configure and nothing to
// guess. The platform has to answer "is there anything new" and "take it" with nobody
// typing git or go.
//
// Two properties hold the design down:
//
// - Nothing destructive happens by default. Local source edits, or a tree that has
// diverged from the incoming history, stop with the file names and commit counts in
// the error instead of being reset to match.
// - Content the operator owns is not ours to overwrite. roles/, skills/, tools/,
// agents/, bundles/, knowledge_base/, data/, config.yaml and friends are put aside
// and restored on top of the merge, so an update moves code while the roles and
// skills created from the console last week survive it. The result names what was
// kept rather than quietly dropping it on the floor.
package update
import (
"context"
"fmt"
"os"
"os/exec"
"path/filepath"
"regexp"
"sort"
"strings"
)
// Binary is the default executable name an update replaces.
const Binary = "cyberstrike-ai"
// DefaultRepoURL is where an installation updates from unless config.yaml says
// otherwise. Keeping the official repository as the default is what makes the feature
// work with no configuration at all; forks and mirrors change this one value.
const DefaultRepoURL = "https://github.com/AIPentest/CyberStrikeAI.git"
// urlRefNamespace is where a fetch parks its remote-tracking ref. A fixed name no
// remote can shadow keeps every installation reading the same shape.
const urlRefNamespace = "update-source"
// maxIncoming caps how many commits a status page lists; the count is reported
// separately so "37 new commits, showing 50" is impossible.
const maxIncoming = 50
// namePattern guards remote and branch names before they reach git's argv. Git treats a
// leading dash as an option, and an argument like this one comes from the working tree
// rather than from a request - but the same validator is used for both, so there is one
// rule instead of one that is stricter in the case nobody attacks.
var namePattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._/@-]*$`)
// urlSchemePattern is the allowlist of fetch schemes. git also accepts "ext::" URLs, which
// run the command written after the colons, so this is an allowlist rather than "whatever
// git accepts"; every other "::" form is rejected outright.
var urlSchemePattern = regexp.MustCompile(`^(https?|ssh|git|file)://`)
// maxRemoteURLLength caps what a config file can put on a git command line.
const maxRemoteURLLength = 512
// ValidRemoteURL reports whether s may be used as a fetch source. Local absolute paths are
// allowed on purpose: they are how this project's own trees point at each other in tests
// and on one machine.
func ValidRemoteURL(s string) bool {
if s == "" || len(s) > maxRemoteURLLength {
return false
}
if strings.HasPrefix(s, "-") {
return false
}
for _, r := range s {
if r < 0x20 || r == 0x7f {
return false
}
}
if strings.Contains(s, "::") {
return false
}
if strings.HasPrefix(s, "/") || filepath.IsAbs(s) {
return true
}
return urlSchemePattern.MatchString(s)
}
// protectedDirs are install-tree directories whose contents the operator may have
// changed through the console or by hand. An update never overwrites them.
var protectedDirs = []string{
"roles/", "skills/", "tools/", "agents/", "bundles/", "knowledge_base/",
"data/", "log/", "logs/", "tmp/", "venv/", ".venv/", "chat_uploads/", ".upgrade-backup/",
}
// protectedFiles are single files with the same rule - most importantly the live
// configuration, which is never in the repository in the first place.
var protectedFiles = []string{"config.yaml", "config.yml", "config.local.yaml", ".env"}
// Protected reports whether a repository-relative path belongs to the operator rather
// than to the product.
func Protected(rel string) bool {
rel = filepath.ToSlash(rel)
for _, f := range protectedFiles {
if rel == f {
return true
}
}
for _, d := range protectedDirs {
if strings.HasPrefix(rel, d) {
return true
}
}
return false
}
// Options describes which installation to act on. Root is the only required field; Repo
// is the update source (config.yaml update.repo) - a repository address to fetch from.
// Empty means the official repository, so an installation with no configuration at all
// still has exactly one answer to "where does an update come from".
type Options struct {
Root string
Repo string
// BinaryName overrides the executable swapped after a successful update. Empty
// means "cyberstrike-ai" in Root; "none" means leave the binary alone.
BinaryName string
}
// repoURL is the effective update source. Trimmed here once so every caller sees the
// same decision: configured address if there is one, the official repository otherwise.
func (o Options) repoURL() string {
if repo := strings.TrimSpace(o.Repo); repo != "" {
return repo
}
return DefaultRepoURL
}
func (o Options) binaryName() string {
if o.BinaryName == "" {
return Binary
}
return o.BinaryName
}
// installRoot resolves the configured directory to an absolute path. A relative config path
// arrives as "." from filepath.Dir, and while git answers it correctly the page would show
// an installation rooted at "." - and an operator reading the refusal cannot tell which
// directory was actually inspected.
func (o Options) installRoot() (string, error) {
root := strings.TrimSpace(o.Root)
if root == "" {
return "", fmt.Errorf("update: install root is required")
}
if abs, err := filepath.Abs(root); err == nil {
return abs, nil
}
return root, nil
}
// Change is one locally modified or deleted tracked file.
type Change struct {
Path string `json:"path"`
Status string `json:"status"`
Protected bool `json:"protected"`
}
// Commit is one line of the incoming history.
type Commit struct {
Commit string `json:"commit"`
Subject string `json:"subject"`
}
// Snapshot is everything a person needs to decide whether to press the button.
type Snapshot struct {
Root string `json:"root"`
Installed bool `json:"installed"`
// Branch is the local branch the install tree is on, for display only.
Branch string `json:"branch"`
// Repo is the effective update source address, and RepoConfigured says whether it
// came from config.yaml or is the built-in official repository.
Repo string `json:"repo"`
RepoConfigured bool `json:"repoConfigured"`
// TargetBranch is the update source's own default branch, learned from the source
// itself when the network answer arrives (empty until then).
TargetBranch string `json:"targetBranch,omitempty"`
Commit string `json:"commit"`
Subject string `json:"subject"`
CommittedAt string `json:"committedAt"`
Behind int `json:"behind"`
Ahead int `json:"ahead"`
// Diverged means this tree has commits the incoming history does not. Updating then
// is a merge decision, not a download, so Apply refuses it.
Diverged bool `json:"diverged"`
UpdateAvailable bool `json:"updateAvailable"`
RemoteCommit string `json:"remoteCommit"`
RemoteSubject string `json:"remoteSubject"`
Incoming []Commit `json:"incoming"`
IncomingTotal int `json:"incomingTotal"`
LocalChanges []Change `json:"localChanges"`
// BlockingChanges are local edits to product source. Content edits are not
// blocking: they are preserved across the update.
BlockingChanges []Change `json:"blockingChanges"`
GoToolchain string `json:"goToolchain"`
CanBuild bool `json:"canBuild"`
HasBinary bool `json:"hasBinary"`
HasRollback bool `json:"hasRollback"`
// RollbackTo is the commit the previous update came from, when there is one.
RollbackTo string `json:"rollbackTo"`
// BuildPending says the last update moved the source but never replaced the binary (a
// failed compile, or a machine without a toolchain). Such a tree has nothing left to
// pull and still owes a build, which is why this is visible without a network round
// trip: the page has to offer the click the failure message told the operator to make.
BuildPending bool `json:"buildPending"`
RollbackPending bool `json:"rollbackPending"`
// CheckError carries a fetch or parse failure to the page instead of turning the
// whole endpoint into a 500: "offline" and "your token expired" are answers, not
// server faults.
CheckError string `json:"checkError,omitempty"`
}
// git runs one git command in the install tree. Everything goes through argv, never
// through a shell, so a repository name with a metacharacter in it is inert.
func gitCmd(ctx context.Context, root string, args ...string) (string, error) {
out, err := gitRaw(ctx, root, args...)
return strings.TrimSpace(out), err
}
// gitRaw is the untrimmed form, and the difference is load-bearing: in a `--porcelain -z`
// record the first two bytes are the X and Y columns, and an unstaged modification is
// " M" - trimming the whole blob eats that leading space and shifts every path one byte
// to the left, so "internal/x.go" arrives as "nternal/x.go". Callers that parse the
// machine formats must use this, not gitCmd.
func gitRaw(ctx context.Context, root string, args ...string) (string, error) {
cmd := exec.CommandContext(ctx, "git", append([]string{"-C", root}, args...)...)
out, err := cmd.Output()
if err != nil {
if ee, ok := err.(*exec.ExitError); ok {
return string(out), fmt.Errorf("git %s: %s", strings.Join(args, " "), strings.TrimSpace(string(ee.Stderr)))
}
return string(out), fmt.Errorf("git %s: %w", strings.Join(args, " "), err)
}
return string(out), nil
}
// nulList splits a `-z` machine-readable git output into its records.
func nulList(blob string) []string {
var out []string
for _, rec := range strings.Split(blob, "\x00") {
if rec != "" {
out = append(out, rec)
}
}
return out
}
// ValidName reports whether s can safely reach git's argv as a branch name.
func ValidName(s string) bool { return namePattern.MatchString(s) }
// Status reads the install tree without touching the network.
func Status(ctx context.Context, opts Options) (*Snapshot, error) {
root, err := opts.installRoot()
if err != nil {
return nil, err
}
snap := &Snapshot{
Root: root,
Repo: opts.repoURL(),
RepoConfigured: strings.TrimSpace(opts.Repo) != "",
Incoming: []Commit{},
LocalChanges: []Change{},
BlockingChanges: []Change{},
}
if !ValidRemoteURL(snap.Repo) {
snap.CheckError = "配置的更新源仓库地址不合法(只允许 https/http/ssh/git/file:// 或本机绝对路径)"
return snap, nil
}
if _, err := gitCmd(ctx, root, "rev-parse", "--is-inside-work-tree"); err != nil {
// Not a git tree: the page still has to say something useful, so this is a
// state rather than an error.
snap.Installed = false
snap.CheckError = "这个目录不是 git 工作树:可以先配置更新源仓库再接入,或按发布包方式更新"
snap.GoToolchain, snap.CanBuild = toolchain(ctx, root)
snap.HasBinary = fileExists(filepath.Join(root, opts.binaryName()))
return snap, nil
}
snap.Installed = true
if err := repositoryRoot(ctx, root); err != nil {
snap.CheckError = err.Error()
return snap, nil
}
for _, q := range []struct {
args []string
dest *string
}{
{[]string{"rev-parse", "--abbrev-ref", "HEAD"}, &snap.Branch},
{[]string{"rev-parse", "--short", "HEAD"}, &snap.Commit},
{[]string{"log", "-1", "--format=%s"}, &snap.Subject},
{[]string{"log", "-1", "--format=%ci"}, &snap.CommittedAt},
} {
if v, err := gitCmd(ctx, root, q.args...); err == nil {
*q.dest = v
}
}
var changeErr error
snap.LocalChanges, snap.BlockingChanges, changeErr = localChanges(ctx, root)
if changeErr != nil {
snap.CheckError = "无法检查本地改动:" + changeErr.Error()
return snap, nil
}
snap.GoToolchain, snap.CanBuild = toolchain(ctx, root)
bin := filepath.Join(root, opts.binaryName())
snap.HasBinary = fileExists(bin)
snap.BuildPending = buildPending(root)
if st, ok := readState(root); ok {
binaryAlreadyMatchesTarget := st.BinaryCommit != "" && st.BinaryCommit == st.PreviousCommit
snap.HasRollback = st.UpdatedCommit != "" && !st.PreviousBinaryAbsent && (binaryAlreadyMatchesTarget || fileExists(bin+".prev"))
snap.RollbackTo = st.PreviousCommit
}
if pending, err := readRollbackPending(root); err != nil {
snap.CheckError = "回滚恢复记录无法读取:" + err.Error()
} else if pending != nil {
snap.HasRollback = true
snap.RollbackPending = true
snap.RollbackTo = pending.State.PreviousCommit
}
return snap, nil
}
// sourceRef is the remote-tracking ref a status or an update compares against.
func (s *Snapshot) sourceRef() string { return urlRefNamespace + "/" + s.TargetBranch }
// sourceLabel is the human-facing name of where an update would come from.
func (s *Snapshot) sourceLabel() string { return s.Repo }
// localChanges lists modified and deleted tracked files, and splits them by who owns
// the path.
func localChanges(ctx context.Context, root string) (all, blocking []Change, err error) {
out, err := gitRaw(ctx, root, "status", "--porcelain=v1", "-z", "--no-renames", "--untracked-files=no")
if err != nil {
return all, blocking, err
}
for _, entry := range nulList(out) {
if len(entry) < 4 {
continue
}
status, path := entry[:2], filepath.ToSlash(entry[3:])
if status == "??" || strings.HasPrefix(status, "!") {
continue
}
c := Change{Path: path, Status: changeVerb(status), Protected: Protected(path)}
all = append(all, c)
if !c.Protected {
blocking = append(blocking, c)
}
}
sort.Slice(all, func(i, j int) bool { return all[i].Path < all[j].Path })
sort.Slice(blocking, func(i, j int) bool { return blocking[i].Path < blocking[j].Path })
return all, blocking, nil
}
func changeVerb(status string) string {
switch {
case strings.Contains(status, "D"):
return "deleted"
case strings.Contains(status, "A"):
return "added"
default:
return "modified"
}
}
// Check asks the update source what it has and reports the gap. The two source calls are
// the only network operations in this package, and a failure is a readable answer rather
// than a fault: the page has to distinguish "up to date" from "could not look".
func Check(ctx context.Context, opts Options) (*Snapshot, error) {
release, err := LockInstall(opts)
if err != nil {
return nil, err
}
defer release()
return check(ctx, opts)
}
func check(ctx context.Context, opts Options) (*Snapshot, error) {
snap, err := Status(ctx, opts)
if err != nil {
return nil, err
}
if !snap.Installed || snap.CheckError != "" {
return snap, nil
}
root := snap.Root
// The branch to follow is the source repository's own default branch, so the
// operator never names one and a fork whose default differs from main still works.
target, err := resolveDefaultBranch(ctx, root, snap.Repo)
if err != nil {
snap.CheckError = err.Error()
return snap, nil
}
snap.TargetBranch = target
// --recurse-submodules=no and --prune keep the fetch to this repository's own
// history. A branch-scoped fetch means a source with many refs cannot turn the
// update check into a full clone.
if _, err := gitCmd(ctx, root, "fetch", "--quiet", "--no-tags", "--prune", "--recurse-submodules=no",
snap.Repo, "+refs/heads/"+target+":refs/remotes/"+urlRefNamespace+"/"+target); err != nil {
snap.CheckError = err.Error()
return snap, nil
}
ref := snap.sourceRef()
if v, err := gitCmd(ctx, root, "rev-parse", "--short", ref); err == nil {
snap.RemoteCommit = v
} else {
snap.CheckError = err.Error()
return snap, nil
}
snap.RemoteSubject, _ = gitCmd(ctx, root, "log", "-1", "--format=%s", ref)
counts, err := gitCmd(ctx, root, "rev-list", "--left-right", "--count", "HEAD..."+ref)
if err != nil {
snap.CheckError = err.Error()
return snap, nil
}
var ahead, behind int
if _, err := fmt.Sscanf(counts, "%d %d", &ahead, &behind); err != nil {
snap.CheckError = "无法解析更新提交差异:" + err.Error()
return snap, nil
}
snap.Ahead, snap.Behind = ahead, behind
snap.Diverged = ahead > 0 && behind > 0
snap.UpdateAvailable = snap.Behind > 0
snap.IncomingTotal = snap.Behind
logs, err := gitCmd(ctx, root, "log", "--format=%h\x1f%s", "-n", fmt.Sprint(maxIncoming), "HEAD.."+ref)
if err == nil {
for _, line := range strings.Split(logs, "\n") {
if line == "" {
continue
}
parts := strings.SplitN(line, "\x1f", 2)
c := Commit{Commit: parts[0]}
if len(parts) > 1 {
c.Subject = parts[1]
}
snap.Incoming = append(snap.Incoming, c)
}
}
return snap, nil
}
// resolveDefaultBranch asks the source repository which branch it publishes as its
// default. It is the one naming decision in the update path, and the source makes it,
// so nothing needs configuring and a source whose default is not "main" still works.
func resolveDefaultBranch(ctx context.Context, root, source string) (string, error) {
out, err := gitCmd(ctx, root, "ls-remote", "--symref", source, "HEAD")
if err != nil {
return "", fmt.Errorf("无法访问更新源仓库 %s:%s", source, strings.TrimSpace(err.Error()))
}
branch := parseDefaultBranch(out)
if branch == "" {
return "", fmt.Errorf("无法确定更新源仓库的默认分支:%s", source)
}
return branch, nil
}
// parseDefaultBranch reads "ref: refs/heads/<name>\tHEAD" out of ls-remote --symref output.
func parseDefaultBranch(out string) string {
for _, line := range strings.Split(out, "\n") {
line = strings.TrimSpace(line)
if !strings.HasPrefix(line, "ref: refs/heads/") {
continue
}
rest := strings.TrimPrefix(line, "ref: refs/heads/")
if i := strings.IndexAny(rest, "\t "); i >= 0 {
rest = rest[:i]
}
if ValidName(rest) {
return rest
}
}
return ""
}
// Git accepts any descendant of a work tree, but file backups and binary swaps
// are rooted at the installation. Refuse descendants before touching that tree.
func repositoryRoot(ctx context.Context, root string) error {
top, err := gitCmd(ctx, root, "rev-parse", "--show-toplevel")
if err != nil {
return err
}
actual, err := os.Stat(root)
if err != nil {
return err
}
expected, err := os.Stat(top)
if err != nil {
return err
}
if !os.SameFile(actual, expected) {
return &Error{Reason: "bad_root", Message: "更新只能操作 git 仓库根目录,请使用:" + top}
}
return nil
}

View File

@ -0,0 +1,586 @@
package update
import (
"context"
"cyberstrike-ai/internal/config"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
)
// These tests drive real git repositories in temporary directories. A fake would let the
// thing this package exists for - "git says no because your files would be overwritten" -
// pass silently.
func requireGit(t *testing.T) {
t.Helper()
if _, err := exec.LookPath("git"); err != nil {
t.Skip("git not installed")
}
}
type tree struct {
upstream string
install string
}
// newTree builds an upstream repository with one code file and one shipped role, then
// clones it the way an operator would (the clone's origin is the user's own fork, not a
// fixed third-party repository).
func newTree(t *testing.T) *tree {
t.Helper()
root := t.TempDir()
up := filepath.Join(root, "fork")
install := filepath.Join(root, "install")
mustGit(t, root, "init", "-q", "-b", "main", up)
writeFile(t, filepath.Join(up, "internal_service.go"), "package service\n\nconst Version = \"1\"\n")
writeFile(t, filepath.Join(up, "roles", "shipped.yaml"), "name: shipped\ndescription: upstream copy\n")
writeFile(t, filepath.Join(up, "run.sh"), "#!/bin/sh\necho old\n")
mustGit(t, up, "add", ".")
mustGit(t, up, "-c", "user.email=t@example.com", "-c", "user.name=T", "commit", "-q", "-m", "first")
mustGit(t, root, "clone", "-q", up, install)
mustGit(t, install, "-c", "user.email=t@example.com", "-c", "user.name=T", "commit", "--allow-empty", "-m", "clone marker")
// The clone's own commit makes HEAD and origin/main differ only by the operator's
// history; drop it so the tree starts exactly level with its remote.
mustGit(t, install, "reset", "--hard", "--quiet", "origin/main")
// The live config file is operator data that is never in the repository.
writeFile(t, filepath.Join(install, "config.yaml"), "server:\n port: 8088\n")
return &tree{upstream: up, install: install}
}
func (t *tree) upstreamCommit(t2 *testing.T, message string, files map[string]string) {
t2.Helper()
for path, content := range files {
writeFile(t2, filepath.Join(t.upstream, path), content)
}
mustGit(t2, t.upstream, "add", ".")
mustGit(t2, t.upstream, "-c", "user.email=t@example.com", "-c", "user.name=T", "commit", "-q", "-m", message)
}
// opts points an update at the tree's own source repository: the explicit address is
// now the whole configuration, so tests name it the way an operator would.
func opts(tr *tree) Options {
return Options{Root: tr.install, Repo: tr.upstream, BinaryName: "none"}
}
func TestStatusWithoutNetworkDescribesTheTree(t *testing.T) {
requireGit(t)
tr := newTree(t)
snap, err := Status(context.Background(), opts(tr))
if err != nil {
t.Fatal(err)
}
if !snap.Installed {
t.Fatal("a clone must be reported as an installable tree")
}
if snap.Branch != "main" {
t.Errorf("local branch = %q, want main", snap.Branch)
}
if snap.Repo != tr.upstream || !snap.RepoConfigured {
t.Errorf("repo = %q configured=%v, want the configured source %q", snap.Repo, snap.RepoConfigured, tr.upstream)
}
if snap.Commit == "" {
t.Error("commit is empty")
}
// config.yaml is operator data and is untracked, so it is not a blocking change.
if len(snap.BlockingChanges) != 0 {
t.Errorf("untracked config.yaml must not block an update: %+v", snap.BlockingChanges)
}
}
func TestStatusReportsTheInstallRootInAbsoluteForm(t *testing.T) {
requireGit(t)
tr := newTree(t)
// A relative config path gives filepath.Dir as "."; the page must still be able to say
// which directory is being updated.
t.Chdir(tr.install)
snap, err := Status(context.Background(), Options{Root: ".", Repo: tr.upstream, BinaryName: "none"})
if err != nil {
t.Fatal(err)
}
if !filepath.IsAbs(snap.Root) || filepath.Base(snap.Root) != "install" {
t.Errorf("root = %q, want the absolute install directory", snap.Root)
}
if _, err := Status(context.Background(), Options{Root: " "}); err == nil {
t.Error("an empty install root must be an error, not a scan of the process CWD")
}
if _, err := Rollback(context.Background(), Options{Root: ""}); err == nil {
t.Error("rollback must refuse an empty install root for the same reason")
}
}
func TestStatusOnNonGitTreeIsAStateNotAnError(t *testing.T) {
requireGit(t)
dir := t.TempDir()
snap, err := Status(context.Background(), Options{Root: dir})
if err != nil {
t.Fatalf("a tarball install is a readable state, not a fault: %v", err)
}
if snap.Installed || snap.CheckError == "" {
t.Errorf("installed=%v checkError=%q, want false with a reason", snap.Installed, snap.CheckError)
}
if snap.Repo != DefaultRepoURL || snap.RepoConfigured {
t.Errorf("repo = %q configured=%v, want the official repository by default", snap.Repo, snap.RepoConfigured)
}
}
func TestCheckFetchesAndListsIncoming(t *testing.T) {
requireGit(t)
tr := newTree(t)
tr.upstreamCommit(t, "second: bump service", map[string]string{"internal_service.go": "package service\n\nconst Version = \"2\"\n"})
tr.upstreamCommit(t, "third: new role", map[string]string{"roles/extra.yaml": "name: extra\n"})
snap, err := Check(context.Background(), opts(tr))
if err != nil {
t.Fatal(err)
}
if snap.CheckError != "" {
t.Fatalf("check failed: %s", snap.CheckError)
}
if !snap.UpdateAvailable || snap.Behind != 2 || snap.Ahead != 0 || snap.Diverged {
t.Errorf("behind=%d ahead=%d available=%v diverged=%v, want 2/0/true/false", snap.Behind, snap.Ahead, snap.UpdateAvailable, snap.Diverged)
}
if len(snap.Incoming) != 2 || snap.Incoming[0].Subject != "third: new role" {
t.Errorf("incoming = %+v, want the two new commits newest first", snap.Incoming)
}
if snap.IncomingTotal != 2 {
t.Errorf("incomingTotal = %d, want 2", snap.IncomingTotal)
}
}
// TestApplyKeepsOperatorContentIsThePointOfTheWholePackage: an update moves code and does
// not destroy the roles, skills or tools the operator made or edited from the console.
func TestApplyKeepsOperatorContentAndMovesCode(t *testing.T) {
requireGit(t)
tr := newTree(t)
// The operator edits a shipped role and adds their own; upstream later rewrites that
// same role and takes the untracked file's name for itself.
writeFile(t, filepath.Join(tr.install, "roles", "shipped.yaml"), "name: shipped\ndescription: mine, do not touch\n")
writeFile(t, filepath.Join(tr.install, "roles", "mine.yaml"), "name: mine\n")
tr.upstreamCommit(t, "upstream rewrites roles and code", map[string]string{
"roles/shipped.yaml": "name: shipped\ndescription: upstream rewrite\n",
"roles/mine.yaml": "name: mine\ndescription: upstream stole the name\n",
"internal_service.go": "package service\n\nconst Version = \"3\"\n",
})
res, err := Apply(context.Background(), opts(tr), nil)
if err != nil {
t.Fatalf("apply failed: %v\nresult: %+v", err, res)
}
if res.Commits == 0 || res.FromCommit == res.ToCommit {
t.Errorf("nothing moved: %+v", res)
}
if got := readFile(t, filepath.Join(tr.install, "internal_service.go")); !strings.Contains(got, "Version = \"3\"") {
t.Errorf("code was not updated, got %q", got)
}
if got := readFile(t, filepath.Join(tr.install, "roles", "shipped.yaml")); !strings.Contains(got, "mine, do not touch") {
t.Errorf("the operator's role was overwritten by upstream: %q", got)
}
if _, err := os.Stat(filepath.Join(tr.install, "roles", "mine.yaml")); err != nil {
t.Errorf("the operator's own role must survive: %v", err)
}
if got := readFile(t, filepath.Join(tr.install, "config.yaml")); !strings.Contains(got, "8088") {
t.Errorf("config.yaml was disturbed: %q", got)
}
if len(res.KeptContent) == 0 {
t.Error("keptContent must name the files that were protected, not silently drop them")
}
found := false
for _, p := range res.KeptContent {
if p == "roles/shipped.yaml" {
found = true
}
}
if !found {
t.Errorf("keptContent = %v, want roles/shipped.yaml in it", res.KeptContent)
}
if res.BinaryBuilt {
t.Error("BinaryName none must not claim a build")
}
if !res.NeedsRestart {
t.Error("an update that moved code reports that a restart is needed")
}
if _, ok := readState(tr.install); !ok {
t.Error("state file missing: rollback would be unavailable")
}
}
func TestApplyRefusesLocalSourceEdits(t *testing.T) {
requireGit(t)
tr := newTree(t)
tr.upstreamCommit(t, "new upstream", map[string]string{"internal_service.go": "package service\n\nconst Version = \"9\"\n"})
writeFile(t, filepath.Join(tr.install, "internal_service.go"), "package service\n\nconst Version = \"local hand edit\"\n")
_, err := Apply(context.Background(), opts(tr), nil)
ue, ok := err.(*Error)
if !ok {
t.Fatalf("want *Error, got %v", err)
}
if ue.Reason != "local_source_edits" {
t.Errorf("reason = %q, want local_source_edits", ue.Reason)
}
if !strings.Contains(strings.Join(ue.Items, " "), "internal_service.go") {
t.Errorf("the refusal must name the file, got %v", ue.Items)
}
if got := readFile(t, filepath.Join(tr.install, "internal_service.go")); !strings.Contains(got, "local hand edit") {
t.Errorf("a refused update must not touch anything, got %q", got)
}
}
func TestApplyRefusesDivergedBranch(t *testing.T) {
requireGit(t)
tr := newTree(t)
tr.upstreamCommit(t, "upstream moves", map[string]string{"internal_service.go": "package service\n\nconst Version = \"9\"\n"})
writeFile(t, filepath.Join(tr.install, "my_patch.go"), "package service\n")
mustGit(t, tr.install, "add", "my_patch.go")
mustGit(t, tr.install, "-c", "user.email=t@example.com", "-c", "user.name=T", "commit", "-q", "-m", "my own commit")
_, err := Apply(context.Background(), opts(tr), nil)
ue, ok := err.(*Error)
if !ok || ue.Reason != "diverged" {
t.Fatalf("a branch with its own commits is a merge decision, not a download; got %v", err)
}
}
func TestApplyWhenAlreadyUpToDateIsANoOp(t *testing.T) {
requireGit(t)
tr := newTree(t)
res, err := Apply(context.Background(), opts(tr), nil)
if err != nil {
t.Fatalf("up to date must not be an error: %v", err)
}
if res.Commits != 0 || res.ToCommit != res.FromCommit {
t.Errorf("res = %+v, want zero movement", res)
}
if _, err := os.Stat(statePath(tr.install)); !os.IsNotExist(err) {
t.Error("a no-op update must not write a rollback state")
}
}
func TestRollbackMovesBackToTheRecordedCommit(t *testing.T) {
requireGit(t)
tr := newTree(t)
before := mustGit(t, tr.install, "rev-parse", "HEAD")
tr.upstreamCommit(t, "upstream new", map[string]string{"internal_service.go": "package service\n\nconst Version = \"7\"\n"})
if _, err := Apply(context.Background(), opts(tr), nil); err != nil {
t.Fatal(err)
}
// Rollback restores the binary kept before a swap; stand one up the way installBinary
// would have left it.
bin := filepath.Join(tr.install, Binary)
writeFile(t, bin, "new binary bytes")
writeFile(t, bin+".prev", "old binary bytes")
res, err := Rollback(context.Background(), Options{Root: tr.install})
if err != nil {
t.Fatalf("rollback failed: %v", err)
}
if got := mustGit(t, tr.install, "rev-parse", "HEAD"); got != strings.TrimSpace(before) {
t.Errorf("HEAD after rollback = %s, want %s", got, before)
}
if got := readFile(t, bin); !strings.Contains(got, "old binary") {
t.Errorf("binary after rollback = %q, want the kept previous one", got)
}
if res.ToCommit == "" {
t.Error("rollback must report where it went")
}
if _, err := os.Stat(statePath(tr.install)); !os.IsNotExist(err) {
t.Error("a completed rollback must clear the state file")
}
}
func TestRollbackRefusesWhenHeadMoved(t *testing.T) {
requireGit(t)
tr := newTree(t)
tr.upstreamCommit(t, "upstream new", map[string]string{"internal_service.go": "package service\n\nconst Version = \"7\"\n"})
if _, err := Apply(context.Background(), opts(tr), nil); err != nil {
t.Fatal(err)
}
bin := filepath.Join(tr.install, Binary)
writeFile(t, bin, "new")
writeFile(t, bin+".prev", "old")
// Somebody else moved the tree after the update.
writeFile(t, filepath.Join(tr.install, "extra.go"), "package service\n")
mustGit(t, tr.install, "add", "extra.go")
mustGit(t, tr.install, "-c", "user.email=t@example.com", "-c", "user.name=T", "commit", "-q", "-m", "later work")
_, err := Rollback(context.Background(), Options{Root: tr.install})
ue, ok := err.(*Error)
if !ok || ue.Reason != "moved_since_update" {
t.Fatalf("rollback must refuse rather than discard work done after the update, got %v", err)
}
if _, err := os.Stat(bin + ".prev"); err != nil {
t.Error("a refused rollback must leave the .prev binary where it was")
}
}
func TestProtectedCoversOperatorDataAndNotCode(t *testing.T) {
yes := []string{"roles/CTF.yaml", "skills/x/SKILL.md", "tools/semgrep.yaml", "agents/a.md", "bundles/pack/bundle.yaml",
"knowledge_base/note.md", "data/conversations.db", "log/server.log", "config.yaml", ".env", "venv/bin/python"}
no := []string{"internal/handler/plugin.go", "web/static/js/plugins.js", "cmd/server/main.go", "Makefile", "docs/zh-CN/c2.md"}
for _, p := range yes {
if !Protected(p) {
t.Errorf("%s must be protected from an update", p)
}
}
for _, p := range no {
if Protected(p) {
t.Errorf("%s is product source and must be updated", p)
}
}
}
func TestValidNameRejectsArgumentInjection(t *testing.T) {
for _, bad := range []string{"", "-C", "--upload-pack=touch /tmp/x", "a b", "a;b", "a\nb", "-x/y", "/abs/path", "../evil"} {
if ValidName(bad) {
t.Errorf("%q must be rejected before it reaches git's argv", bad)
}
}
for _, good := range []string{"origin", "mine", "main", "feature/docker", "v1.2.3"} {
if !ValidName(good) {
t.Errorf("%q is a legitimate remote or branch name", good)
}
}
}
func TestInstallBinaryKeepsPrevAndRestoresOnFailedSwap(t *testing.T) {
dir := t.TempDir()
dst := filepath.Join(dir, "cyberstrike-ai")
src := filepath.Join(dir, "new")
writeFile(t, dst, "old")
writeFile(t, src, "new")
prev, err := installBinary(src, dst)
if err != nil {
t.Fatal(err)
}
if readFile(t, dst) != "new" || readFile(t, prev) != "old" {
t.Errorf("swap result: dst=%q prev=%q", readFile(t, dst), readFile(t, prev))
}
if err := restorePrevBinary(dst); err != nil {
t.Fatal(err)
}
if readFile(t, dst) != "old" {
t.Errorf("rollback binary = %q, want old", readFile(t, dst))
}
if fileExists(dst + ".prev") {
t.Error("restoring the previous binary must consume the .prev file")
}
}
func TestTailKeepsTheEndOfABuildLog(t *testing.T) {
long := strings.Repeat("download\n", 500) + "vet: real error at the end"
got := tail(long, 200)
if !strings.Contains(got, "real error at the end") {
t.Error("tail must keep the compiler's actual error")
}
if len(got) > 260 {
t.Errorf("tail did not truncate: %d bytes", len(got))
}
}
func writeFile(t *testing.T, path, content string) {
t.Helper()
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
t.Fatal(err)
}
}
func readFile(t *testing.T, path string) string {
t.Helper()
data, err := os.ReadFile(path)
if err != nil {
t.Fatalf("read %s: %v", path, err)
}
return string(data)
}
func mustGit(t *testing.T, dir string, args ...string) string {
t.Helper()
cmd := exec.Command("git", append([]string{"-C", dir}, args...)...)
cmd.Env = append(os.Environ(), "GIT_CONFIG_GLOBAL=/dev/null", "GIT_CONFIG_SYSTEM=/dev/null", "GIT_TERMINAL_PROMPT=0")
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("git %s: %v\n%s", strings.Join(args, " "), err, out)
}
return strings.TrimSpace(string(out))
}
// The release version rides with the code: after an update the live config has to say the
// version of the code now on disk (the header badge reads it), and a rollback has to put
// the old number back next to the old code.
func TestApplySyncsTheReleaseVersionIntoTheLiveConfig(t *testing.T) {
requireGit(t)
tr := newTree(t)
writeFile(t, filepath.Join(tr.install, "config.yaml"), "version: \"v1.0.0\"\nserver:\n port: 8088\n")
tr.upstreamCommit(t, "release: bump version", map[string]string{
"config.example.yaml": "version: \"v1.1.0\"\nserver:\n port: 8088\n",
"internal_service.go": "package service\n\nconst Version = \"2\"\n",
})
res, err := Apply(context.Background(), opts(tr), nil)
if err != nil {
t.Fatalf("apply failed: %v\nresult: %+v", err, res)
}
live := readFile(t, filepath.Join(tr.install, "config.yaml"))
if !strings.Contains(live, `version: "v1.1.0"`) || !strings.Contains(live, "port: 8088") {
t.Fatalf("live config after update = %q, want the new version with everything else untouched", live)
}
st, ok := readState(tr.install)
if !ok || st.VersionBefore != "v1.0.0" || st.VersionAfter != "v1.1.0" {
t.Fatalf("state = %+v, want the version change recorded for the rollback", st)
}
// Rollback puts the number back with the code.
bin := filepath.Join(tr.install, Binary)
writeFile(t, bin, "new binary bytes")
writeFile(t, bin+".prev", "old binary bytes")
if _, err := Rollback(context.Background(), Options{Root: tr.install}); err != nil {
t.Fatalf("rollback failed: %v", err)
}
live = readFile(t, filepath.Join(tr.install, "config.yaml"))
if !strings.Contains(live, `version: "v1.0.0"`) {
t.Fatalf("live config after rollback = %q, want the old version back", live)
}
}
// The same sync end to end, with the key spelled the way issue #4 was filed about: a legal
// quoted key must be replaced in place (not appended next to), and the rollback must still
// find a config it can read.
func TestApplySyncsTheReleaseVersionIntoAQuotedKeyConfig(t *testing.T) {
requireGit(t)
tr := newTree(t)
live := filepath.Join(tr.install, "config.yaml")
writeFile(t, live, "\"version\": \"v1.0.0\"\nserver:\n port: 8088\n")
tr.upstreamCommit(t, "release: bump version", map[string]string{
"config.example.yaml": "version: \"v1.1.0\"\n",
"internal_service.go": "package service\n\nconst Version = \"2\"\n",
})
if _, err := Apply(context.Background(), opts(tr), nil); err != nil {
t.Fatalf("apply failed: %v", err)
}
got := readFile(t, live)
if strings.Count(got, "version") != 1 {
t.Fatalf("live config gained a duplicate version key:\n%q", got)
}
if v, err := config.FileVersion(live); err != nil || v != "v1.1.0" {
t.Fatalf("live config after apply reads %q (%v), want v1.1.0:\n%q", v, err, got)
}
if !strings.Contains(got, "port: 8088") {
t.Fatalf("the rest of the config must stay:\n%q", got)
}
bin := filepath.Join(tr.install, Binary)
writeFile(t, bin, "new binary bytes")
writeFile(t, bin+".prev", "old binary bytes")
if _, err := Rollback(context.Background(), Options{Root: tr.install}); err != nil {
t.Fatalf("rollback failed: %v", err)
}
got = readFile(t, live)
if strings.Count(got, "version") != 1 {
t.Fatalf("rollback left a broken config:\n%q", got)
}
if v, err := config.FileVersion(live); err != nil || v != "v1.0.0" {
t.Fatalf("live config after rollback reads %q (%v), want v1.0.0:\n%q", v, err, got)
}
}
func TestRollbackDoesNotClobberAManuallyChangedVersion(t *testing.T) {
requireGit(t)
tr := newTree(t)
writeFile(t, filepath.Join(tr.install, "config.yaml"), "version: \"v1.0.0\"\nserver:\n port: 8088\n")
tr.upstreamCommit(t, "release: bump version", map[string]string{
"config.example.yaml": "version: \"v1.1.0\"\n",
})
if _, err := Apply(context.Background(), opts(tr), nil); err != nil {
t.Fatal(err)
}
// Somebody pins their own version after the update; a rollback is not theirs to undo.
writeFile(t, filepath.Join(tr.install, "config.yaml"), "version: \"v9.9.9-mine\"\nserver:\n port: 8088\n")
bin := filepath.Join(tr.install, Binary)
writeFile(t, bin, "new")
writeFile(t, bin+".prev", "old")
if _, err := Rollback(context.Background(), Options{Root: tr.install}); err != nil {
t.Fatal(err)
}
if live := readFile(t, filepath.Join(tr.install, "config.yaml")); !strings.Contains(live, "v9.9.9-mine") {
t.Fatalf("a hand-set version must survive a rollback, got %q", live)
}
}
func TestApplyLeavesTheVersionAloneWhenTheTreeCarriesNone(t *testing.T) {
requireGit(t)
tr := newTree(t)
// The fixture's upstream has no config.example.yaml at all: nothing to sync, and the
// live config must not be rewritten with a guess.
writeFile(t, filepath.Join(tr.install, "config.yaml"), "version: \"v1.0.0\"\nserver:\n port: 8088\n")
tr.upstreamCommit(t, "second: bump service", map[string]string{
"internal_service.go": "package service\n\nconst Version = \"2\"\n",
})
if _, err := Apply(context.Background(), opts(tr), nil); err != nil {
t.Fatal(err)
}
if live := readFile(t, filepath.Join(tr.install, "config.yaml")); !strings.Contains(live, "v1.0.0") {
t.Fatalf("live config = %q, want it untouched", live)
}
if st, _ := readState(tr.install); st.VersionAfter != "" || st.VersionBefore != "" {
t.Fatalf("state = %+v, want no version fields when nothing changed", st)
}
}
func TestAdoptSyncsTheReleaseVersionIntoTheLiveConfig(t *testing.T) {
requireGit(t)
tr, dir := newAdoptFixture(t)
writeFile(t, filepath.Join(dir, "config.yaml"), "version: \"v0.9.0\"\nserver:\n port: 8088\n")
tr.upstreamCommit(t, "release: bump version", map[string]string{
"config.example.yaml": "version: \"v1.1.0\"\n",
})
res, err := Adopt(context.Background(), Options{Root: dir, Repo: tr.upstream, BinaryName: "none"}, nil)
if err != nil {
t.Fatalf("adopt failed: %v\nresult: %+v", err, res)
}
live := readFile(t, filepath.Join(dir, "config.yaml"))
if !strings.Contains(live, `version: "v1.1.0"`) || !strings.Contains(live, "port: 8088") {
t.Fatalf("live config after adopt = %q, want the connected code's version with the rest untouched", live)
}
}
// A tree that is already current still gets its bookkeeping aligned: the version field is
// the one thing an update may correct with no commits to move (that is exactly the state a
// pre-feature installation is in).
func TestApplyAlignsTheVersionEvenWithNothingToPull(t *testing.T) {
requireGit(t)
tr := newTree(t)
writeFile(t, filepath.Join(tr.install, "config.yaml"), "version: \"v0.9.0\"\nserver:\n port: 8088\n")
writeFile(t, filepath.Join(tr.install, "config.example.yaml"), "version: \"v1.1.0\"\n")
res, err := Apply(context.Background(), opts(tr), nil)
if err != nil {
t.Fatalf("no-op apply failed: %v", err)
}
if res.Commits != 0 {
t.Fatalf("res = %+v, want zero movement", res)
}
if live := readFile(t, filepath.Join(tr.install, "config.yaml")); !strings.Contains(live, `version: "v1.1.0"`) {
t.Fatalf("live config = %q, want the version aligned even though nothing moved", live)
}
// Bookkeeping only: a version-only correction writes no rollback state.
if _, ok := readState(tr.install); ok {
t.Fatal("a version-only alignment must not claim to be a rollback point")
}
}

129
internal/update/version.go Normal file
View File

@ -0,0 +1,129 @@
package update
import (
"cyberstrike-ai/internal/config"
"fmt"
"path/filepath"
)
// The release version travels with the code: config.example.yaml ships in the repository
// and upstream bumps its version field in the release commit, but the live config.yaml is
// the operator's file and no merge ever touches it. So without the steps below an updated
// installation keeps showing the version it was born with - the header badge and the
// static-asset cache buster would both say v-old while the tree runs v-new. The fix is
// deliberately small: read the version the new code carries, write it into the live
// config's version line (byte-for-byte otherwise untouched, atomic rename), and let a
// rollback put the old number back with the old code.
// liveConfigFile names the operator's configuration inside an install tree: the
// conventional config.yaml, then config.yml. Empty when neither exists (a source
// checkout, where there is nothing to sync).
func liveConfigFile(root string) string {
for _, name := range []string{"config.yaml", "config.yml"} {
path := filepath.Join(root, name)
if fileExists(path) {
return path
}
}
return ""
}
// installVersion is the release version the code sitting in root carries, read from the
// shipped config.example.yaml; empty when the tree does not say.
func installVersion(root string) string {
version, err := config.FileVersion(filepath.Join(root, "config.example.yaml"))
if err != nil {
return ""
}
return version
}
// syncVersionToConfig writes the code's release version into the live configuration and
// returns (before, after, error) - both empty when there was nothing to do. A tree
// without a live config, or without a shipped version, is left alone; a current value
// that already matches is not rewritten.
func syncVersionToConfig(root string) (before, after string, err error) {
path := liveConfigFile(root)
if path == "" {
return "", "", nil
}
target := installVersion(root)
if target == "" {
return "", "", nil
}
current, err := config.FileVersion(path)
if err != nil {
return "", "", err
}
if current == target {
return "", "", nil
}
changed, err := config.WriteVersion(path, target)
if err != nil {
return current, "", err
}
if !changed {
return "", "", nil
}
return current, target, nil
}
// plannedVersionChange reports the change a sync is about to make, before it makes it: the
// live config's current number and the one the code on disk carries. Empty when there is
// nothing to do. An update records this in its pending marker *before* writing the config,
// so a crash between the two still leaves a rollback that can put the old number back.
func plannedVersionChange(root string) (before, after string) {
path := liveConfigFile(root)
if path == "" {
return "", ""
}
target := installVersion(root)
if target == "" {
return "", ""
}
current, err := config.FileVersion(path)
if err != nil || current == target {
return "", ""
}
return current, target
}
// versionStep renders the sync outcome as one progress line; no lines for "nothing to
// do", a warning when the write failed (the update itself still stands).
func versionStep(step func(string, string), before, after string, err error) {
if err != nil {
step("version", "版本号写入 config.yaml 失败(不影响本次更新):"+err.Error())
return
}
if after == "" {
return
}
if before == "" {
step("version", fmt.Sprintf("版本号随新代码写入 config.yaml:%s(重启后页头生效)", after))
return
}
step("version", fmt.Sprintf("版本号已随新代码更新:%s → %s(config.yaml,重启后页头生效)", before, after))
}
// restoreVersionAfterRollback puts the old number back with the old code - but only while
// the live config still carries exactly what the update wrote: a version someone edited by
// hand after the update belongs to them, not to the rollback.
func restoreVersionAfterRollback(root string, st State) error {
if st.VersionAfter == "" {
return nil
}
path := liveConfigFile(root)
if path == "" {
return nil
}
current, err := config.FileVersion(path)
if err != nil || current != st.VersionAfter {
return nil
}
if st.VersionBefore == "" {
_, err := config.RemoveVersion(path)
return err
}
_, err = config.WriteVersion(path, st.VersionBefore)
return err
}

View File

@ -86,6 +86,14 @@ func runToolNode(ctx context.Context, args RunArgs, node graphNode, state *Workf
if err == nil && toolCtx.Err() != nil {
err = toolCtx.Err()
}
// The MCP worker and caller have timers for the same absolute deadline.
// The worker may finish first while the caller's Done notification is still
// waiting to run; the deadline itself is authoritative in either ordering.
if err == nil {
if deadline, ok := toolCtx.Deadline(); ok && !time.Now().Before(deadline) {
err = context.DeadlineExceeded
}
}
if err != nil {
errText := err.Error()
return outputMap(envelope("tool", node.ID, node.Type, "failed", ""), map[string]any{"tool_name": toolName, "arguments": toolArgs, "error": errText}), false, "failed", errText

View File

@ -107,8 +107,12 @@ func endOutputMap(node graphNode, value any) map[string]any {
}
func toolOutputMap(node graphNode, output string, toolName string, args map[string]any, executionID string, isError bool) map[string]any {
status := "completed"
if isError {
status = "failed"
}
typed := ToolOutput{
NodeOutputEnvelope: envelope("tool", node.ID, node.Type, "completed", output),
NodeOutputEnvelope: envelope("tool", node.ID, node.Type, status, output),
ToolName: toolName,
Arguments: args,
ExecutionID: executionID,

View File

@ -88,3 +88,14 @@ func TestRunToolNodeAppliesTimeoutToActualMCPExecution(t *testing.T) {
t.Fatal("actual MCP handler was not executed")
}
}
func TestFailedToolOutputDoesNotClaimCompletedStatus(t *testing.T) {
out := toolOutputMap(graphNode{ID: "tool-1", Type: "tool"}, "tool failed", "lookup", nil, "exec-1", true)
if out["status"] != "failed" {
t.Fatalf("failed output claimed success: %#v", out)
}
typed, ok := out["typed"].(ToolOutput)
if !ok || typed.Status != "failed" || !typed.IsError {
t.Fatalf("typed output disagrees with failure: %#v", out["typed"])
}
}

4
run.sh
View File

@ -313,7 +313,7 @@ build_go_project() {
(
set +e # disable errexit in subshell
export GOPROXY="$GOPROXY"
go build -o "$BINARY_NAME" cmd/server/main.go >"$GO_BUILD_LOG" 2>&1
go build -o "$BINARY_NAME" ./cmd/server >"$GO_BUILD_LOG" 2>&1
echo $? > "${GO_BUILD_LOG}.exit"
) &
GO_BUILD_PID=$!
@ -374,7 +374,7 @@ build_go_project_quiet() {
rm -f "$GO_DOWNLOAD_LOG"
GO_BUILD_LOG=$(mktemp)
if ! GOPROXY="$GOPROXY" go build -o "$BINARY_NAME" cmd/server/main.go >"$GO_BUILD_LOG" 2>&1; then
if ! GOPROXY="$GOPROXY" go build -o "$BINARY_NAME" ./cmd/server >"$GO_BUILD_LOG" 2>&1; then
error "Build failed"
echo ""
info "Build error details:"

View File

@ -1,15 +1,34 @@
#!/usr/bin/env bash
set -euo pipefail
# CyberStrikeAI GitHub one-click upgrade script (Release/Tag)
# CyberStrikeAI upgrade entry point.
#
# Two installation kinds, decided at runtime from this directory itself:
#
# 1. git work tree (the normal case):
# the update is delegated to the platform binary, `./cyberstrike-ai -update`, which
# fetches the configured update source (config.yaml update.repo; empty = the official
# repository, and one field points it at a fork or a mirror) and follows that
# repository's own default branch, fast-forwards, rebuilds with `go build` and swaps
# the binary in atomically. The CLI reads the same config field the console page
# saves, so the keyboard and the button update from the same place.
# Refusals (local source edits, diverged history) come from that same implementation
# and name the files/commits involved.
#
# 2. Plain directory (Release tarball install, no git): falls back to downloading a
# Release tarball and synchronizing it with `rsync --delete`. Here the source
# repository must be named, so it is taken from --repo, else the GITHUB_REPO
# environment variable, and only if neither is set from the built-in default - with a
# warning that says out loud which repository the code is coming from.
#
# Default preserves:
# - config.yaml
# - data/
# - venv/ (disabled with --no-venv)
# - tools/ (user extensions; never overwritten by upgrade)
# - roles/
# - skills/
# - roles/, skills/, agents/
# - the rollback points of an earlier one-click update:
# .update-backup/, .update-state.json, .update-build-pending, cyberstrike-ai.prev
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$ROOT_DIR"
@ -23,32 +42,61 @@ KNOWLEDGE_BASE_DIR="$ROOT_DIR/knowledge_base"
BACKUP_BASE_DIR="$ROOT_DIR/.upgrade-backup"
UPGRADE_TMP_DIR=""
GITHUB_REPO="Ed1s0nZ/CyberStrikeAI"
# Built-in fallback, used ONLY when this directory is not a git work tree and neither
# --repo nor GITHUB_REPO was given. See resolve_repo().
DEFAULT_GITHUB_REPO="AIPentest/CyberStrikeAI"
GITHUB_REPO="${GITHUB_REPO:-}"
REPO_ARG=""
TAG=""
PRESERVE_VENV=1
STOP_SERVICE=1
FORCE_STOP=0
YES=0
CHECK_ONLY=0
# Set by resolve_install_kind(): "git" or "tarball".
INSTALL_KIND=""
usage() {
cat <<EOF
cat <<'EOF'
Usage:
./upgrade.sh [--tag vX.Y.Z] [--no-venv] [--no-stop]
[--force-stop] [--yes]
./upgrade.sh [--check] [--yes] [--no-venv] [--no-stop] [--force-stop]
[--tag vX.Y.Z] [--repo <owner/name>]
What it does depends on the installation kind (detected automatically):
git work tree Updates from the configured source repository (config.yaml
update.repo; empty = the official repository) by calling
./cyberstrike-ai -update (fetch, fast-forward, go build, swap binary).
--tag/--repo are ignored on this path. Your own roles/skills/tools/
agents/data/config are put aside and restored by the platform;
local source edits or diverged history stop the update instead of
being overwritten.
plain directory (Release tarball install, no git) Downloads the Release tarball and
syncs it in with rsync --delete. --repo / GITHUB_REPO apply here.
Options:
--tag <tag> Specify GitHub Release tag (e.g. v1.3.28).
If omitted, the script uses the latest release.
--no-venv Do not preserve venv/ (Python deps will be re-installed).
--no-stop Do not try to stop the running service.
--force-stop If no process matching current directory is found, also stop
any cyberstrike-ai processes (use with caution).
--yes Do not ask for confirmation.
--check Report only, change nothing: never stops the service, never writes.
git tree: ./cyberstrike-ai -check-update, or
go run ./cmd/server -check-update while there is no binary yet.
plain directory: prints the newest Release tag and the version
recorded in config.yaml.
--repo <owner/name> Release repository to read (tarball installs only). Takes precedence
over $GITHUB_REPO. Without either, the built-in default is used and
the script warns about it.
--tag <tag> Specify GitHub Release tag (e.g. v1.3.28).
If omitted, the script uses the latest release.
--no-venv Do not preserve venv/ (Python deps will be re-installed).
--no-stop Do not stop the running service, and do not start it afterwards
(use this under systemd or any supervisor; restart the unit yourself).
--force-stop If no process matching current directory is found, also stop
any cyberstrike-ai processes (use with caution).
--yes Do not ask for confirmation.
Description:
The script backs up config.yaml/data/tools/roles/skills/ (and optionally venv/) to
.upgrade-backup/
Rollback:
./cyberstrike-ai -update-rollback
Undoes the last one-click update (back to the commit and the binary kept before it).
EOF
}
@ -78,6 +126,68 @@ http_get() {
fi
}
physical_path() {
# $1: existing directory; symlinks resolved, so paths reported by git compare cleanly
# (macOS /tmp and /var are symlinks).
( cd "$1" 2>/dev/null && pwd -P ) || true
}
is_git_work_tree() {
# $1: directory
have_cmd git && git -C "$1" rev-parse --is-inside-work-tree >/dev/null 2>&1
}
resolve_install_kind() {
if ! have_cmd git; then
INSTALL_KIND="tarball"
info "git is not installed: treating this directory as a tarball install (Release download)."
return 0
fi
if ! is_git_work_tree "$ROOT_DIR"; then
INSTALL_KIND="tarball"
info "This directory is not a git work tree: using the Release tarball path."
return 0
fi
local raw_top top_phys root_phys
raw_top="$(git -C "$ROOT_DIR" rev-parse --show-toplevel 2>/dev/null || true)"
if [[ -n "$raw_top" ]]; then
top_phys="$(physical_path "$raw_top")"
root_phys="$(physical_path "$ROOT_DIR")"
if [[ -n "$top_phys" && "$top_phys" != "$root_phys" ]]; then
err "This script lives in ${ROOT_DIR}, which is a subdirectory of the repository root ${raw_top}."
err "One-click update only ever moves a repository root, so run the upgrade from ${raw_top}."
exit 1
fi
fi
INSTALL_KIND="git"
}
show_git_source() {
# Say out loud where the code is coming from: that is the whole point of this path.
# The source itself is one field (config.yaml update.repo, empty = the official
# repository) and the binary is the one that reads it - `-check-update` prints the
# exact repository and branch that would land, without changing anything.
local branch
branch="$(git -C "$ROOT_DIR" rev-parse --abbrev-ref HEAD 2>/dev/null || true)"
info "Install directory: ${ROOT_DIR}"
info "Local branch: ${branch:-unknown}"
info "Update source: config.yaml update.repo (empty = the official repository); ./${BINARY_NAME} -check-update prints it exactly."
}
explain_no_go() {
err "No compiled ${BINARY_NAME} binary in ${ROOT_DIR} and no Go toolchain on PATH."
err "One of the two is required: an existing binary rebuilds itself, a source-only"
err "checkout needs Go to produce the first binary."
err "Install Go (this module requires Go 1.25 or newer):"
err " download: https://go.dev/dl/"
err " macOS: brew install go"
err " Debian/Ubuntu: sudo apt install golang-go (or the official tarball in /usr/local/go)"
err "Then re-run: ./upgrade.sh"
}
stop_service() {
# Try to stop the service that is running from the current project directory.
# If nothing is found and --force-stop is enabled, stop all cyberstrike-ai processes.
@ -129,6 +239,187 @@ stop_service() {
return 0
}
start_service() {
if [[ "$STOP_SERVICE" -ne 1 ]]; then
info "--no-stop: the service was left untouched. Restart it yourself (for example: systemctl restart cyberstrikeai)."
return 0
fi
if [[ ! -f "$ROOT_DIR/run.sh" ]]; then
warn "run.sh not found: starting the service is left to you."
return 0
fi
info "Starting service..."
chmod +x ./run.sh
./run.sh
}
confirm_or_exit() {
if [[ "$YES" -eq 1 ]]; then
return 0
fi
if [[ ! -t 0 ]]; then
err "Non-interactive terminal detected. Please add --yes to continue."
exit 1
fi
if [[ "$INSTALL_KIND" == "git" ]]; then
warn "About to update this installation from its configured update source:"
info " - git fetch + fast-forward of ${ROOT_DIR}"
info " (refused with file names if source files are modified locally, or if the"
info " local history has diverged from the source - that is a merge decision, not a download)"
info " - go build, then the binary is swapped; the previous one is kept as ${BINARY_NAME}.prev"
info " - your content (roles/skills/tools/agents/knowledge_base/data/config.yaml)"
info " is put aside before the merge and restored after it; the result lists what was kept"
info " - rollback stays available: .update-backup/<timestamp>/ + .update-state.json"
info " - Stop service: ${STOP_SERVICE}"
else
warn "About to perform upgrade:"
info " - Source repository: ${GITHUB_REPO:-unset} (this directory is not a git work tree)"
info " - Preserve config.yaml: yes"
info " - Preserve data/: yes"
if [[ "$PRESERVE_VENV" -eq 1 ]]; then
info " - Preserve venv/: yes"
else
info " - Preserve venv/: no (will remove old venv and re-install deps)"
fi
info " - Preserve tools/: yes (always)"
info " - Preserve roles/skills/agents: yes (always)"
info " - Preserve rollback points (.update-backup/, .update-state.json, .update-build-pending, ${BINARY_NAME}.prev): yes"
info " - Stop service: ${STOP_SERVICE}"
fi
echo ""
read -r -p "Continue? (y/N) " ans
if [[ "${ans:-N}" != "y" && "${ans:-N}" != "Y" ]]; then
err "Cancelled."
exit 1
fi
}
run_platform_update_cli() {
# $1: '-check-update' or '-update'. Same implementation the console page drives, so a
# keyboard session and the API cannot disagree about what an update means.
local flag="$1"
if [[ ! -f "$ROOT_DIR/$BINARY_NAME" ]]; then
err "Expected ${BINARY_NAME} in ${ROOT_DIR} but it is not there."
err "Run ./upgrade.sh again (it builds the binary first) or use --check."
return 1
fi
if [[ ! -x "$ROOT_DIR/$BINARY_NAME" ]]; then
chmod +x "./$BINARY_NAME"
fi
info "Running: ./${BINARY_NAME} ${flag}"
local rc=0
./"$BINARY_NAME" "$flag" || rc=$?
return "$rc"
}
report_update_refusal() {
# $1: exit code. The platform already printed the exact reason and the file names above;
# this only says what it means for the tree, because the two outcomes look the same.
warn "${BINARY_NAME} exited with code $1. Read the reason printed above."
info " - Local source edits / diverged branch: nothing was moved. Commit or restore your"
info " own source changes (or merge by hand), then run ./upgrade.sh again."
info " - No Go toolchain: the source DID move and your content was kept; the binary is"
info " still the previous one. Install Go and run ./upgrade.sh again to finish."
info " - Undo the last successful update: ./${BINARY_NAME} -update-rollback"
}
build_first_binary() {
info "No ${BINARY_NAME} binary yet: building one before updating (./cmd/server, first run may download modules)."
if ! have_cmd go; then
explain_no_go
exit 1
fi
if ! go build -o "$BINARY_NAME" ./cmd/server; then
err "The first build failed, so the platform has no binary to update itself with."
err "Fix the build (see the compiler output above) and run ./upgrade.sh again."
exit 1
fi
if [[ ! -f "$BINARY_NAME" ]]; then
err "go build reported success but produced no ${BINARY_NAME} in ${ROOT_DIR}."
exit 1
fi
chmod +x "./$BINARY_NAME"
}
check_git_install() {
# Read-only path: never stops or starts the service.
if [[ -f "$ROOT_DIR/$BINARY_NAME" ]]; then
local rc=0
run_platform_update_cli "-check-update" || rc=$?
if [[ "$rc" -ne 0 ]]; then
report_update_refusal "$rc"
fi
return "$rc"
fi
if have_cmd go; then
info "No ${BINARY_NAME} binary yet, so the check is asked of the source tree: go run compiles into the build cache and leaves this directory untouched."
local rc=0
go run ./cmd/server -check-update || rc=$?
if [[ "$rc" -ne 0 ]]; then
report_update_refusal "$rc"
fi
return "$rc"
fi
explain_no_go
exit 1
}
update_git_install() {
confirm_or_exit
stop_service
if [[ ! -f "$ROOT_DIR/$BINARY_NAME" ]]; then
build_first_binary
fi
if ! have_cmd go; then
warn "No Go toolchain on PATH: the update will move the source and keep your content, but it cannot rebuild the binary."
warn "Install Go and run ./upgrade.sh again to swap in the new binary."
fi
# A fast-forward may rewrite this script as well; harmless, the running copy is already
# open, and the next invocation reads the updated file.
local rc=0
run_platform_update_cli "-update" || rc=$?
if [[ "$rc" -ne 0 ]]; then
report_update_refusal "$rc"
return "$rc"
fi
info "Source and binary are in place (the running process is still the old one until it is restarted)."
start_service
}
ensure_git_style_env() {
# No hard requirement; just a sanity check.
if [[ ! -f "$CONFIG_FILE" ]]; then
err "Could not find ${CONFIG_FILE}. Please verify you are in the correct project directory."
exit 1
fi
}
resolve_repo() {
# Tarball path only: without a repository of our own, the source has to be named, and
# naming it silently is how a fork gets overwritten. --repo beats GITHUB_REPO, and the
# built-in default is a last resort that says so.
if [[ -n "$REPO_ARG" ]]; then
GITHUB_REPO="$REPO_ARG"
fi
if [[ -z "${GITHUB_REPO:-}" ]]; then
GITHUB_REPO="$DEFAULT_GITHUB_REPO"
warn "Neither --repo nor GITHUB_REPO was given, so the built-in default repository is used."
fi
if [[ ! "$GITHUB_REPO" =~ ^[A-Za-z0-9._-]+/[A-Za-z0-9._-]+$ ]]; then
err "Invalid repository: ${GITHUB_REPO} (expected the form owner/name)."
exit 1
fi
warn "Not a git work tree: code will be downloaded from https://github.com/${GITHUB_REPO} (a Release tarball), not from this directory's own remote."
warn "If this installation is meant to track your fork, make it a git clone; ./upgrade.sh then pulls from the remote it already has."
}
backup_dir_tgz() {
# $1: label, $2: path
local label="$1"
@ -145,43 +436,6 @@ backup_config() {
fi
}
ensure_git_style_env() {
# No hard requirement; just a sanity check.
if [[ ! -f "$CONFIG_FILE" ]]; then
err "Could not find ${CONFIG_FILE}. Please verify you are in the correct project directory."
exit 1
fi
}
confirm_or_exit() {
if [[ "$YES" -eq 1 ]]; then
return 0
fi
if [[ ! -t 0 ]]; then
err "Non-interactive terminal detected. Please add --yes to continue."
exit 1
fi
warn "About to perform upgrade:"
info " - Preserve config.yaml: yes"
info " - Preserve data/: yes"
if [[ "$PRESERVE_VENV" -eq 1 ]]; then
info " - Preserve venv/: yes"
else
info " - Preserve venv/: no (will remove old venv and re-install deps)"
fi
info " - Preserve tools/: yes (always)"
info " - Preserve roles/skills: yes (always)"
info " - Stop service: ${STOP_SERVICE}"
echo ""
read -r -p "Continue? (y/N) " ans
if [[ "${ans:-N}" != "y" && "${ans:-N}" != "Y" ]]; then
err "Cancelled."
exit 1
fi
}
resolve_tag() {
if [[ -n "$TAG" ]]; then
info "Using specified tag: $TAG"
@ -234,31 +488,97 @@ PY
info "Latest Release tag: $TAG"
}
check_tarball_install() {
# Nothing to fast-forward without a repository of our own: report the newest published
# tag against the version recorded in config.yaml, and change no file.
resolve_tag
local current=""
if [[ -f "$CONFIG_FILE" ]]; then
current="$(grep -m1 -E '^[[:space:]]*version[[:space:]]*:' "$CONFIG_FILE" 2>/dev/null | cut -d: -f2- | tr -d ' "' || true)"
fi
info "Newest Release tag of ${GITHUB_REPO}: ${TAG}"
info "Version recorded in config.yaml: ${current:-unknown}"
info "Report only: nothing was stopped, downloaded or written. Run ./upgrade.sh without --check to apply."
}
update_config_version() {
# Replace config.yaml's version: ... with the specified tag.
# Replace config.yaml's top-level version with the specified tag. The line matching
# mirrors the Go writer (internal/config.WriteVersion): top-level key only, in every
# spelling YAML accepts (version / "version" / 'version'), first occurrence only - a
# nested key or a later duplicate belongs to the file's own structure and must not be
# rewritten. A value the line cannot replace safely (block scalar / multi-line scalar)
# leaves the file alone on purpose: a stale version number is a display problem, a
# config that no longer loads is an installation that no longer starts.
local new_tag="$1"
python3 - "$CONFIG_FILE" "$new_tag" <<PY
import re, sys
path=sys.argv[1]
tag=sys.argv[2]
python3 - "$CONFIG_FILE" "$new_tag" <<'PY'
import os, re, stat, sys, tempfile
path = sys.argv[1]
tag = sys.argv[2]
# Same value rule as the Go writer (internal/config.versionValuePattern): what lands here
# is a live config, and a tag with a quote or newline in it must never reach it.
if not re.match(r"^[A-Za-z0-9][A-Za-z0-9._+-]*$", tag):
sys.stderr.write("版本号 %r 不合法(只允许字母、数字与 . _ + -),未写入 config.yaml\n" % tag)
sys.exit(0)
with open(path, "r", encoding="utf-8") as f:
lines=f.readlines()
lines = f.readlines()
out=[]
replaced=False
for line in lines:
if re.match(r'^\s*version\s*:', line):
out.append(f'version: "{tag}"\\n')
replaced=True
else:
out.append(line)
key = re.compile(r"^(['\"]?version['\"]?)\s*:(.*)$")
replaced = False
refused = False
out = []
for i, line in enumerate(lines):
if not replaced:
m = key.match(line)
if m:
value = m.group(2).strip()
nxt = lines[i + 1] if i + 1 < len(lines) else ""
# Without a YAML parser, only replace a complete scalar on one
# line. An open quote or flow/anchor value may continue below.
simple_value = re.fullmatch(r"(?:[A-Za-z0-9._+-]+|'[^'\n]*'|\"[^\"\\\n]*\")?(?:[ \t]+#.*)?", value)
if simple_value is None or (value == "" and nxt[:1] in (" ", "\t")):
sys.stderr.write("版本号未写入:config.yaml 的 version 是多行/块标量写法,无法就地替换(原文件未改动)\n")
refused = True
break
out.append('version: "%s"\n' % tag)
replaced = True
continue
out.append(line)
if not replaced:
# If no version field is found, insert at the beginning (near the top).
out.insert(0, f'version: "{tag}"\\n')
if not refused:
if not replaced:
insert_at = 0
for i, line in enumerate(lines):
first = line.rstrip("\r\n").lstrip("\ufeff")
rest = first[3:] if first.startswith("---") else None
if rest is not None and (not rest.strip(" \t") or rest[:1] in (" ", "\t") and rest.lstrip(" \t").startswith("#")):
insert_at = i + 1
if not line.endswith(("\n", "\r")):
out[i] += "\n"
break
trimmed = first.strip()
if trimmed and not trimmed.startswith("#") and not first.startswith("%"):
# Only a block mapping at column zero can accept a new key.
if not re.match(r"^[A-Za-z_][A-Za-z0-9_-]*[ \t]*:", first):
sys.stderr.write("版本号未写入:无法安全地在此 YAML 文档插入字段,原文件未改动\n")
sys.exit(0)
break
out.insert(insert_at, 'version: "%s"\n' % tag)
with open(path, "w", encoding="utf-8") as f:
f.writelines(out)
original_mode = stat.S_IMODE(os.stat(path).st_mode)
tmp_fd, tmp = tempfile.mkstemp(prefix=os.path.basename(path) + ".", suffix=".tmp", dir=os.path.dirname(os.path.abspath(path)))
try:
with os.fdopen(tmp_fd, "w", encoding="utf-8") as f:
f.writelines(out)
f.flush()
os.fchmod(f.fileno(), original_mode)
os.replace(tmp, path)
except BaseException:
try:
os.unlink(tmp)
except FileNotFoundError:
pass
raise
PY
}
@ -276,9 +596,9 @@ sync_code() {
local -a rsync_excludes
rsync_excludes+=( "--exclude=.upgrade-backup/" )
rsync_excludes+=( "--exclude=config.yaml" )
rsync_excludes+=( "--exclude=config.yaml" "--exclude=config.yml" "--exclude=config.local.yaml" "--exclude=.env" )
rsync_excludes+=( "--exclude=data/" )
rsync_excludes+=( "--exclude=tmp/" )
rsync_excludes+=( "--exclude=tmp/" "--exclude=chat_uploads/" "--exclude=log/" "--exclude=logs/" "--exclude=bundles/" "--exclude=.venv/" )
if [[ "$PRESERVE_VENV" -eq 1 ]]; then
rsync_excludes+=( "--exclude=venv/" )
@ -293,6 +613,20 @@ sync_code() {
rsync_excludes+=( "--exclude=tools/" )
rsync_excludes+=( "--exclude=roles/" )
rsync_excludes+=( "--exclude=skills/" )
# Markdown agents are operator content too, and the platform's own update protects the
# same set.
rsync_excludes+=( "--exclude=agents/" )
# Rollback points written by a one-click update: an rsync --delete that ate them would
# leave the installation with no way back - and eating .update-build-pending would make it
# forget a compile it still owes, so the next click reports "already up to date".
rsync_excludes+=( "--exclude=.update-backup/" )
rsync_excludes+=( "--exclude=.update-staging/" )
rsync_excludes+=( "--exclude=.update-state.json" "--exclude=.update-lock" "--exclude=.update-rollback-pending.json" "--exclude=.update-rollback-pending.json.tmp" )
rsync_excludes+=( "--exclude=.update-state.json.tmp" )
rsync_excludes+=( "--exclude=.update-build-pending" )
rsync_excludes+=( "--exclude=.update-build-pending.tmp" )
rsync_excludes+=( "--exclude=${BINARY_NAME}.prev" )
# Ensure this upgrade script itself is not deleted.
rsync_excludes+=( "--exclude=upgrade.sh" )
@ -304,43 +638,8 @@ sync_code() {
"${new_src_dir}/" "${ROOT_DIR}/"
}
main() {
update_tarball_install() {
ensure_git_style_env
while [[ $# -gt 0 ]]; do
case "$1" in
--tag)
TAG="${2:-}"
shift 2
;;
--no-venv)
PRESERVE_VENV=0
shift 1
;;
--no-stop)
STOP_SERVICE=0
shift 1
;;
--force-stop)
FORCE_STOP=1
shift 1
;;
--yes)
YES=1
shift 1
;;
-h|--help)
usage
exit 0
;;
*)
err "Unknown parameter: $1"
usage
exit 1
;;
esac
done
confirm_or_exit
stop_service
@ -375,6 +674,9 @@ main() {
if [[ -d "$ROOT_DIR/skills" ]]; then
backup_dir_tgz "skills" "$ROOT_DIR/skills"
fi
if [[ -d "$ROOT_DIR/agents" ]]; then
backup_dir_tgz "agents" "$ROOT_DIR/agents"
fi
UPGRADE_TMP_DIR="$(mktemp -d)"
trap 'rm -rf "${UPGRADE_TMP_DIR:-}" >/dev/null 2>&1 || true' EXIT
@ -403,9 +705,78 @@ main() {
update_config_version "$TAG"
fi
info "Upgrade complete. Starting service..."
chmod +x ./run.sh
./run.sh
info "Upgrade complete."
start_service
}
main() {
while [[ $# -gt 0 ]]; do
case "$1" in
--check)
CHECK_ONLY=1
shift 1
;;
--repo)
REPO_ARG="${2:-}"
shift 2
;;
--tag)
TAG="${2:-}"
shift 2
;;
--no-venv)
PRESERVE_VENV=0
shift 1
;;
--no-stop)
STOP_SERVICE=0
shift 1
;;
--force-stop)
FORCE_STOP=1
shift 1
;;
--yes)
YES=1
shift 1
;;
-h|--help)
usage
exit 0
;;
*)
err "Unknown parameter: $1"
usage
exit 1
;;
esac
done
resolve_install_kind
if [[ "$INSTALL_KIND" == "git" ]]; then
if [[ -n "$TAG" ]]; then
warn "--tag names a GitHub Release and is ignored here: this directory fast-forwards to its own remote, not to a tag."
fi
if [[ -n "$REPO_ARG" ]]; then
warn "--repo names a GitHub Release repository and is ignored here: the remote is the one this directory already tracks."
fi
show_git_source
if [[ "$CHECK_ONLY" -eq 1 ]]; then
check_git_install
return 0
fi
update_git_install
return 0
fi
# Tarball install: the source has to be named, and naming it out loud comes first.
resolve_repo
if [[ "$CHECK_ONLY" -eq 1 ]]; then
check_tarball_install
return 0
fi
update_tarball_install
}
main "$@"

View File

@ -46756,3 +46756,408 @@ html[data-theme="dark"] { --tool-blocked-color: #f4bc62; }
white-space: nowrap;
line-height: 1.5;
}
/* ---------------------------------------------------------------------------
一键更新控制台(系统设置页的 settings-section-update 分区):这里说的每一句状态都要能被眼睛分区——
本机事实、远端比较、能不能点、正在跑的进度、以及跑完的结论。
ok/warn/danger 三色是给"说谎"留的对照组:查不了必须是 warn/danger,不能长得像 ok。
--------------------------------------------------------------------------- */
.update-console {
display: flex;
flex-direction: column;
gap: 20px;
}
/* 分区标题行:标题在左、刷新在右;窄屏放不下就换行,别把标题压扁 */
.update-section-head {
display: flex;
align-items: center;
justify-content: space-between;
flex-wrap: wrap;
gap: 8px;
}
/* 待生效横幅:磁盘二进制与运行进程不一致时的常驻出口(忘勾重启也有救) */
.update-restart-banner {
display: flex;
align-items: center;
justify-content: space-between;
flex-wrap: wrap;
gap: 10px;
padding: 12px 14px;
border: 1px solid rgba(217, 130, 43, 0.45);
border-radius: 10px;
background: rgba(217, 130, 43, 0.12);
}
.update-restart-banner-text {
flex: 1 1 240px;
min-width: 0;
font-size: 13px;
color: #b06a17;
}
.update-restart-btn {
flex: 0 0 auto;
white-space: nowrap;
}
/* 自恢复视图:重启期间控制台让位给这一屏,新进程应答后整页刷新 */
.update-overlay {
display: flex;
flex-direction: column;
align-items: center;
gap: 10px;
padding: 32px 16px;
text-align: center;
}
.update-overlay-spinner {
width: 28px;
height: 28px;
border: 3px solid rgba(58, 110, 197, 0.25);
border-top-color: #2d5bb0;
border-radius: 50%;
animation: update-spin 0.9s linear infinite;
}
@keyframes update-spin {
to { transform: rotate(360deg); }
}
.update-overlay-title {
font-size: 15px;
font-weight: 600;
color: var(--text-primary);
}
.update-overlay-body {
max-width: 460px;
font-size: 13px;
color: var(--text-secondary);
}
.update-overlay-slow {
max-width: 460px;
font-size: 13px;
color: #b06a17;
}
.update-overlay-actions {
margin-top: 4px;
}
.update-intro {
color: var(--text-secondary);
margin: 0 0 12px;
}
.update-section-title {
font-size: 15px;
margin: 0 0 10px;
}
.update-sub-title {
font-size: 13px;
font-weight: 600;
margin: 14px 0 6px;
color: var(--text-secondary);
}
.update-facts {
display: flex;
flex-wrap: wrap;
gap: 8px 20px;
padding: 12px 16px;
background: var(--bg-primary);
border: 1px solid var(--border-color);
border-radius: 12px;
}
.update-fact {
display: flex;
align-items: baseline;
gap: 8px;
font-size: 13px;
color: var(--text-secondary);
min-width: 0;
max-width: 100%;
}
.update-fact code {
color: var(--text-primary);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
max-width: 420px;
}
.update-marks {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin-top: 10px;
}
.update-chip {
display: inline-block;
padding: 2px 8px;
border-radius: 999px;
font-size: 12px;
border: 1px solid var(--border-color);
color: var(--text-secondary);
}
.update-chip-ok {
background: rgba(37, 168, 112, 0.14);
border-color: rgba(37, 168, 112, 0.4);
color: #1f8a5b;
}
.update-chip-warn {
background: rgba(217, 130, 43, 0.14);
border-color: rgba(217, 130, 43, 0.4);
color: #b06a17;
cursor: help;
}
.update-chip-danger {
background: rgba(192, 57, 43, 0.14);
border-color: rgba(192, 57, 43, 0.4);
color: var(--danger-color, #c0392b);
}
.update-chip-running {
background: rgba(58, 110, 197, 0.14);
border-color: rgba(58, 110, 197, 0.4);
color: #2d5bb0;
}
.update-ok {
color: #1f8a5b;
font-size: 13px;
}
.update-behind {
font-size: 14px;
font-weight: 600;
color: var(--text-primary);
}
.update-hint {
color: var(--text-secondary);
font-size: 13px;
line-height: 1.6;
margin: 6px 0;
}
.update-warn {
background: rgba(217, 130, 43, 0.12);
border: 1px solid rgba(217, 130, 43, 0.35);
border-radius: 8px;
padding: 8px 12px;
font-size: 13px;
color: #b06a17;
margin: 6px 0;
}
.update-error {
background: rgba(192, 57, 43, 0.1);
border: 1px solid rgba(192, 57, 43, 0.32);
border-radius: 8px;
padding: 8px 12px;
color: var(--danger-color, #c0392b);
font-size: 13px;
margin: 6px 0;
}
/* 「检查失败」那一行是这一页最不该被看漏的字,所以它比别的错误横幅再重一档。 */
.update-check-failed {
font-weight: 600;
}
/* 这三个按钮的名字既是样式钩子也是测试钩子:禁用态要看得出是禁用,而不是"点了没反应"。 */
.update-apply-btn:disabled,
.update-check-btn:disabled,
.update-rollback-btn:disabled {
cursor: not-allowed;
opacity: .55;
}
.update-actions {
display: flex;
gap: 8px;
flex-wrap: wrap;
margin: 10px 0;
}
.update-restart-choice {
display: flex;
align-items: flex-start;
gap: 8px;
font-size: 13px;
color: var(--text-primary);
cursor: pointer;
margin: 4px 0;
}
.update-restart-choice input {
margin-top: 2px;
}
.update-restart-preview {
border-left: 3px solid var(--border-color);
padding-left: 10px;
}
.update-blocker-list {
margin: 6px 0 0;
padding-left: 18px;
font-size: 13px;
}
.update-commit-list,
.update-kept-list,
.update-item-list {
margin: 0;
padding-left: 18px;
font-size: 13px;
line-height: 1.8;
}
.update-commit-list code,
.update-kept-list code,
.update-item-list code {
color: var(--text-primary);
}
.update-commit-subject {
color: var(--text-secondary);
}
.update-table {
width: 100%;
border-collapse: collapse;
font-size: 13px;
}
.update-table th,
.update-table td {
text-align: left;
padding: 6px 8px;
border-bottom: 1px solid var(--border-color);
word-break: break-all;
}
.update-row-blocking td {
background: rgba(192, 57, 43, 0.06);
}
.update-row-kept td {
background: rgba(37, 168, 112, 0.06);
}
.update-job-head {
display: flex;
align-items: center;
gap: 10px;
flex-wrap: wrap;
font-size: 13px;
color: var(--text-secondary);
}
.update-job-time {
font-size: 12px;
color: var(--text-secondary);
}
.update-step-list {
margin: 10px 0 0;
padding: 10px 12px;
list-style: decimal inside;
background: var(--bg-primary);
border: 1px solid var(--border-color);
border-radius: 10px;
font-family: var(--font-mono, ui-monospace, SFMono-Regular, Menlo, monospace);
font-size: 12.5px;
}
.update-step {
display: flex;
flex-wrap: wrap;
gap: 8px;
padding: 3px 0;
border-bottom: 1px dashed var(--border-color);
}
.update-step:last-child {
border-bottom: none;
}
.update-step-phase {
color: #2d5bb0;
flex: 0 0 auto;
}
.update-step-message {
color: var(--text-primary);
flex: 1 1 320px;
white-space: pre-wrap;
word-break: break-word;
}
.update-step-at {
color: var(--text-secondary);
flex: 0 0 auto;
}
.update-result {
margin-top: 12px;
}
.update-failure-title {
font-weight: 600;
margin-bottom: 4px;
}
.update-failure-message {
white-space: pre-wrap;
word-break: break-word;
}
/* 更新源区块:一行一个输入(label 上、输入下),与平台的设置表单同构。 */
.update-source-form {
display: flex;
flex-direction: column;
gap: 10px;
}
.update-source-form label {
display: flex;
flex-direction: column;
gap: 4px;
font-size: 13px;
color: var(--text-secondary);
}
.update-source-input {
padding: 8px 10px;
border: 1px solid var(--border-color);
border-radius: 6px;
background: var(--bg-primary);
color: var(--text-primary);
font-size: 14px;
}
.update-source-url,
.update-source-remote,
.update-source-branch {
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
}
.update-source-save-btn,
.update-adopt-preview-btn,
.update-adopt-confirm-btn {
align-self: flex-start;
}

View File

@ -99,6 +99,139 @@
"passwordPlaceholder": "Enter password",
"submit": "Sign in"
},
"update": {
"title": "One-Click Update",
"intro": "This page changes the very installation that is answering your requests: it pulls the newest commit of the update source's default branch (the official repository unless configured), rebuilds the binary and swaps it in. The roles/skills/tools and configuration you maintain here are not overwritten.",
"loading": "Reading this installation's state",
"loadFailed": "Failed to read this installation's state: {{reason}}",
"installTitle": "This installation",
"remoteTitle": "Against the update source",
"applyTitle": "One-click update",
"jobTitle": "Update progress",
"rollbackTitle": "Rollback",
"root": "Install directory",
"branch": "Local branch",
"commit": "Current commit",
"committedAt": "Committed at",
"subject": "Commit subject",
"gitTree": "git work tree",
"notGitTree": "Not a git work tree",
"toolchainFound": "Go toolchain present",
"toolchainMissing": "No Go toolchain",
"toolchainMissingHint": "No go command found: an update can only move the source, the build needs another machine",
"binaryPresent": "Binary present",
"binaryMissing": "Binary missing",
"rollbackPresent": "Rollback point exists",
"rollbackMissing": "No rollback point",
"notChecked": "The update source has not been consulted yet. Opening this page queues one automatic check (once per session); press Check for updates to ask again any time.",
"checkBtn": "Check for updates",
"checking": "Checking the update source...",
"checkFailed": "Check failed: {{reason}}",
"applyFailed": "Failed to start the update: {{reason}}",
"rollbackFailed": "Rollback failed: {{reason}}",
"behindCount": "{{n}} commits behind",
"aheadCount": "{{n}} commits ahead locally",
"upToDate": "Up to date: local {{commit}} matches the update source",
"remoteHead": "Source head",
"remoteSubject": "Source commit subject",
"incomingTitle": "Incoming commits",
"incomingTruncated": "{{total}} new commits in total; only the first {{shown}} are listed",
"applyBtn": "Update now",
"jobRunningHint": "An update is already running; its progress is below.",
"noToolchainWarn": "No Go toolchain here: the source will be updated but the binary will not be replaced; build it externally, then restart.",
"rollbackPendingHint": "The previous rollback is incomplete. Click Roll back to finish recovery before updating.",
"buildPendingHint": "The last update moved the source but never replaced the binary (the build failed, or there was no Go toolchain): press Update to finish that build.",
"blockedNotGitTree": "This directory is not a git work tree, so it cannot be updated automatically.",
"blockedJobRunning": "An update is already running; wait for it to finish.",
"blockedLocalEdits": "{{n}} product source files are edited locally and an update will not overwrite them: commit or revert them first.",
"blockedDiverged": "Local history is {{ahead}} commits ahead and {{behind}} behind: that is a merge, not a download, so handle it by hand.",
"blockedNoUpdate": "The update source has nothing newer than this machine (press Check for updates if you have not looked yet).",
"restartChoiceLabel": "Exit the process after the update (only an external supervisor such as systemd or run.sh will bring it back; restart it yourself if nothing supervises it)",
"restartNotWired": "This start did not provide a restart hook: restart the service yourself after the update.",
"confirmRestartYes": "Selected: the process exits once the update succeeds, and only an external supervisor (systemd, run.sh, ...) will bring it back.",
"confirmRestartNo": "Not selected: the process keeps running the old binary until you restart it yourself.",
"confirmApply": "About to run: update from {{repo}} to {{target}} ({{n}} new commits, this machine is at {{commit}}) -> rebuild the binary -> back up and replace the old one.",
"confirmBuildPending": "About to run: build the missing binary for the source already in place (this machine is at {{commit}}) -> rebuild -> back up and replace the old binary.",
"applyAccepted": "Update started (job {{id}}); progress refreshes every 1.5 seconds.",
"localChangesTitle": "Local changes",
"localChangesHint": "Files marked local content are kept exactly as they are; files marked product source block the automatic update.",
"noLocalChanges": "Working tree clean: no tracked file is modified or deleted.",
"colPath": "File",
"colChangeStatus": "State",
"colOwner": "Owner",
"keptFile": "Local content (kept by the update)",
"productSource": "Product source (blocks the update)",
"noJob": "No update has run yet",
"noSteps": "The job has not produced a progress line yet",
"pollingHint": "Progress is read every {{sec}} seconds",
"stateRunning": "Running",
"stateSucceeded": "Succeeded",
"stateFailed": "Failed",
"stateUnknown": "Unknown state",
"restartRequested": "Exit after completion requested",
"jobPollFailed": "Failed to read the progress: {{reason}}",
"jobDoneToast": "Update finished",
"buildDoneToast": "Build finished",
"jobFailedToast": "Update failed",
"needsRestartToast": "The binary was replaced; it takes effect after a restart",
"restartBanner": "Updated to {{commit}}, but this process is still running the old build (the binary on disk was built at {{builtAt}}). It takes effect after a restart.",
"restartBannerNoCommit": "The binary on disk was replaced (built at {{builtAt}}), but this process is still running the old build; it takes effect after a restart.",
"restartNowBtn": "Restart now",
"restartNowConfirm": "The service process will exit; with a supervisor (systemd/launchd) the new version is back in seconds and this page reloads itself. Without one the service stays stopped until you start it. Restart now?",
"restartRequestedToast": "Restart requested: the supervisor brings it back and this page recovers by itself",
"restartFailed": "Restart request failed: {{reason}}",
"restartOverlayTitle": "Restarting the service…",
"restartOverlayBody": "This page reloads by itself once the new process answers (your session will be gone, so a fresh login follows).",
"restartOverlaySlowRunning": "The service is still answering as the old process - the restart does not seem to have happened. Use the button below to look at the current state.",
"restartOverlaySlowDown": "The service has not come back. If nothing supervises it (systemd/launchd) it will not start by itself; start it, then refresh this page.",
"restartOverlayRefresh": "Refresh this page",
"failureNoMessage": "The server gave no failure message",
"resultTitle": "Update result",
"resultFrom": "From",
"resultTo": "To",
"resultCommits": "Commits brought in",
"resultFiles": "Files touched",
"resultDuration": "Duration",
"resultBackup": "Backup directory",
"keptTitle": "Local content files that were kept",
"nothingKept": "No local content file had to be moved aside",
"binarySwapped": "Binary replaced",
"binaryNotSwapped": "Binary unchanged",
"restartNeeded": "A restart is needed to run the new version",
"restartNotNeeded": "No restart needed",
"failureTitle": "Why it failed",
"noRollback": "No rollback point: one exists only after an update has run",
"rollbackTarget": "Rollback target: {{commit}} (where this tree stood before the last update)",
"rollbackBtn": "Roll back the update",
"confirmRollback": "Roll back to {{commit}}? The source returns to before that update and the previous binary is restored.",
"rollbackDone": "Rolled back to {{commit}}",
"sourceTitle": "Update source",
"sourceFromConfig": "The update source is configured in config.yaml.",
"sourceIsDefault": "No update source configured: the official repository {{repo}} is used.",
"sourceUrl": "Update source",
"sourceBranch": "Source default branch",
"sourceUrlLabel": "Update source repository address",
"sourceRepoHint": "Leave empty to use the official repository; point it at your own fork or a mirror to follow that instead.",
"sourceSaveBtn": "Save source",
"sourceSaveOk": "Update source saved",
"sourceSaveFailed": "Failed to save the update source: {{reason}}",
"adoptHint": "This directory is not a git work tree yet. Connecting it to the update source turns it into a normal installation that updates in one click.",
"adoptPreviewBtn": "Preview and connect",
"adoptIncoming": "Files in the target branch",
"adoptOverwrittenTotal": "Will be replaced by the target",
"adoptProtectedTotal": "Operator content (kept)",
"adoptCommit": "Target commit",
"adoptOverwrittenTitle": "Local files that will be replaced",
"adoptProtectedTitle": "Operator content that will be kept",
"adoptBackupNote": "Every replaced file is kept under .update-backup/<timestamp>/overwritten/ and can be restored from there.",
"adoptConfirmBtn": "Connect",
"adoptConfirmText": "Connecting replaces {{overwritten}} local files with the target versions (of {{incoming}} files in total; {{protectedFiles}} operator files are kept). Continue?",
"adoptAccepted": "Connecting started (job {{id}}); progress refreshes every 1.5 seconds.",
"adoptFailed": "Connecting failed: {{reason}}",
"adoptedNoPreviousCommit": "This is an adoption result: there was no git history before it, so there is no earlier commit to roll back to; the next update writes the first rollback point.",
"resultOverwrittenTitle": "Local files that were replaced (copies under overwritten/)",
"rollbackItems": "Files that were not rolled back"
},
"nav": {
"security": "Security",
"toolGuard": "Call blocking",
@ -1817,6 +1950,7 @@
"rbac": "Platform permissions",
"audit": "Audit logs",
"storage": "Storage cleanup",
"update": "One-Click Update",
"infocollect": "Asset management"
},
"infocollect": {

View File

@ -99,6 +99,139 @@
"passwordPlaceholder": "Введите пароль",
"submit": "Войти"
},
"update": {
"title": "Обновление в один клик",
"intro": "Эта страница изменяет саму установку, которая отвечает на ваши запросы: она подтягивает свежий коммит ветки по умолчанию репозитория-источника (по умолчанию — официальный репозиторий), пересобирает бинарный файл и подменяет его. Ваши roles/skills/tools и конфигурация не перезаписываются.",
"loading": "Чтение состояния этой установки",
"loadFailed": "Не удалось прочитать состояние установки: {{reason}}",
"installTitle": "Эта установка",
"remoteTitle": "Сравнение с источником обновлений",
"applyTitle": "Обновление в один клик",
"jobTitle": "Ход обновления",
"rollbackTitle": "Откат",
"root": "Каталог установки",
"branch": "Локальная ветка",
"commit": "Текущий коммит",
"committedAt": "Дата коммита",
"subject": "Заголовок коммита",
"gitTree": "git-рабочее дерево",
"notGitTree": "Не git-рабочее дерево",
"toolchainFound": "Инструментарий Go на месте",
"toolchainMissing": "Нет инструментария Go",
"toolchainMissingHint": "Команда go не найдена: обновление сможет только перенести исходники, для сборки нужна другая машина",
"binaryPresent": "Бинарный файл на месте",
"binaryMissing": "Бинарный файл отсутствует",
"rollbackPresent": "Точка отката есть",
"rollbackMissing": "Точки отката нет",
"notChecked": "Источник обновлений ещё не проверялся. При открытии страницы запускается одна автоматическая проверка (по одной за сессию); нажмите «Проверить обновления», чтобы спросить ещё раз.",
"checkBtn": "Проверить обновления",
"checking": "Проверка источника обновлений...",
"checkFailed": "Проверка не удалась: {{reason}}",
"applyFailed": "Не удалось запустить обновление: {{reason}}",
"rollbackFailed": "Откат не удался: {{reason}}",
"behindCount": "Отставание на {{n}} коммитов",
"aheadCount": "Локально на {{n}} коммитов впереди",
"upToDate": "Всё актуально: локальный {{commit}} совпадает с источником обновлений",
"remoteHead": "Вершина источника",
"remoteSubject": "Заголовок коммита источника",
"incomingTitle": "Входящие коммиты",
"incomingTruncated": "Всего новых коммитов: {{total}}; показаны только первые {{shown}}",
"applyBtn": "Обновить сейчас",
"jobRunningHint": "Обновление уже выполняется; его ход показан ниже.",
"noToolchainWarn": "Здесь нет инструментария Go: исходники будут обновлены, но бинарный файл не заменится; соберите его извне и перезапустите службу.",
"rollbackPendingHint": "Предыдущий откат не завершён. Нажмите «Откатить», чтобы закончить восстановление перед обновлением.",
"buildPendingHint": "Прошлое обновление перенесло исходники, но не заменило бинарный файл (сборка не удалась или тогда не было инструментария Go): нажмите «Обновить», чтобы завершить эту сборку.",
"blockedNotGitTree": "Этот каталог не является git-рабочим деревом, автоматическое обновление невозможно.",
"blockedJobRunning": "Обновление уже выполняется; дождитесь его завершения.",
"blockedLocalEdits": "{{n}} файлов исходного кода изменены локально, и обновление не будет их перезаписывать: сначала закоммитьте или отмените изменения.",
"blockedDiverged": "Локальная история впереди на {{ahead}} коммитов и отстаёт на {{behind}}: это слияние, а не загрузка, разберитесь вручную.",
"blockedNoUpdate": "В источнике обновлений нет ничего новее этой машины (нажмите «Проверить обновления», если ещё не смотрели).",
"restartChoiceLabel": "Завершить процесс после обновления (вернуть его сможет только внешний супервизор, например systemd или run.sh; если ничего не супервизит — запустите сами)",
"restartNotWired": "При этом запуске хук перезапуска не предоставлен: перезапустите службу сами после обновления.",
"confirmRestartYes": "Выбрано: процесс завершится после успешного обновления, и вернуть его сможет только внешний супервизор (systemd, run.sh, ...).",
"confirmRestartNo": "Не выбрано: процесс продолжит работать со старым бинарным файлом, пока вы сами его не перезапустите.",
"confirmApply": "Сейчас будет выполнено: обновление из {{repo}} до {{target}} ({{n}} новых коммитов, эта машина на {{commit}}) -> пересборка бинарного файла -> резервная копия и замена старого.",
"confirmBuildPending": "Сейчас будет выполнено: сборка недостающего бинарного файла для уже установленных исходников (эта машина на {{commit}}) -> пересборка -> резервная копия и замена старого бинарного файла.",
"applyAccepted": "Обновление запущено (задача {{id}}); ход обновляется каждые 1,5 секунды.",
"localChangesTitle": "Локальные изменения",
"localChangesHint": "Файлы, помеченные как локальное содержимое, сохраняются как есть; файлы, помеченные как исходный код продукта, блокируют автоматическое обновление.",
"noLocalChanges": "Рабочее дерево чистое: ни один отслеживаемый файл не изменён и не удалён.",
"colPath": "Файл",
"colChangeStatus": "Состояние",
"colOwner": "Владелец",
"keptFile": "Локальное содержимое (сохраняется при обновлении)",
"productSource": "Исходный код продукта (блокирует обновление)",
"noJob": "Обновление ещё не запускалось",
"noSteps": "Задача ещё не выдала ни одной строки о ходе выполнения",
"pollingHint": "Ход читается каждые {{sec}} секунд",
"stateRunning": "Выполняется",
"stateSucceeded": "Успешно",
"stateFailed": "Не удалось",
"stateUnknown": "Неизвестное состояние",
"restartRequested": "Запрошено завершение после выполнения",
"jobPollFailed": "Не удалось прочитать ход выполнения: {{reason}}",
"jobDoneToast": "Обновление завершено",
"buildDoneToast": "Сборка завершена",
"jobFailedToast": "Обновление не удалось",
"needsRestartToast": "Бинарный файл заменён; он вступит в силу после перезапуска",
"restartBanner": "Обновлено до {{commit}}, но процесс всё ещё работает на старой сборке (бинарник на диске собран {{builtAt}}). Изменения вступят в силу после перезапуска.",
"restartBannerNoCommit": "Бинарник на диске заменён (собран {{builtAt}}), но процесс всё ещё работает на старой сборке; изменения вступят в силу после перезапуска.",
"restartNowBtn": "Перезапустить сейчас",
"restartNowConfirm": "Процесс службы завершится; при наличии супервизора (systemd/launchd) новая версия поднимется через несколько секунд, и страница обновится сама. Без супервизора служба останется остановленной. Перезапустить сейчас?",
"restartRequestedToast": "Перезапуск запрошен: супервизор поднимет службу, страница восстановится сама",
"restartFailed": "Не удалось запросить перезапуск: {{reason}}",
"restartOverlayTitle": "Перезапуск службы…",
"restartOverlayBody": "Страница обновится сама, как только новый процесс начнёт отвечать (сессия будет сброшена — потребуется войти заново).",
"restartOverlaySlowRunning": "Служба по-прежнему отвечает старым процессом — перезапуск, похоже, не произошёл. Нажмите кнопку ниже, чтобы увидеть текущее состояние.",
"restartOverlaySlowDown": "Служба не вернулась. Если её ничто не супервизит (systemd/launchd), она не запустится сама — запустите её и обновите страницу.",
"restartOverlayRefresh": "Обновить страницу",
"failureNoMessage": "Сервер не передал сообщение об ошибке",
"resultTitle": "Результат обновления",
"resultFrom": "От",
"resultTo": "До",
"resultCommits": "Принято коммитов",
"resultFiles": "Затронуто файлов",
"resultDuration": "Длительность",
"resultBackup": "Каталог резервных копий",
"keptTitle": "Сохранённые файлы локального содержимого",
"nothingKept": "Ни один файл локального содержимого не пришлось откладывать",
"binarySwapped": "Бинарный файл заменён",
"binaryNotSwapped": "Бинарный файл не изменён",
"restartNeeded": "Для запуска новой версии нужен перезапуск",
"restartNotNeeded": "Перезапуск не требуется",
"failureTitle": "Почему не удалось",
"noRollback": "Точки отката нет: она появляется только после выполненного обновления",
"rollbackTarget": "Цель отката: {{commit}} (где это дерево было до последнего обновления)",
"rollbackBtn": "Откатить обновление",
"confirmRollback": "Откатиться до {{commit}}? Исходники вернутся к состоянию до того обновления, а прежний бинарный файл будет восстановлен.",
"rollbackDone": "Откат выполнен до {{commit}}",
"sourceTitle": "Источник обновления",
"sourceFromConfig": "Источник обновлений настроен в config.yaml.",
"sourceIsDefault": "Источник обновлений не настроен: используется официальный репозиторий {{repo}}.",
"sourceUrl": "Репозиторий-источник",
"sourceBranch": "Ветка по умолчанию источника",
"sourceUrlLabel": "Адрес репозитория-источника",
"sourceRepoHint": "Оставьте пустым, чтобы использовать официальный репозиторий; укажите свой форк или зеркало, чтобы следовать за ним.",
"sourceSaveBtn": "Сохранить источник",
"sourceSaveOk": "Источник обновления сохранён",
"sourceSaveFailed": "Не удалось сохранить источник обновления: {{reason}}",
"adoptHint": "Этот каталог ещё не git-рабочее дерево. После подключения к источнику обновлений он станет обычной установкой с обновлением в один клик.",
"adoptPreviewBtn": "Предпросмотр и подключение",
"adoptIncoming": "Файлов в целевой ветке",
"adoptOverwrittenTotal": "Будут заменены целевой версией",
"adoptProtectedTotal": "Содержимое оператора (сохраняется)",
"adoptCommit": "Целевой коммит",
"adoptOverwrittenTitle": "Локальные файлы, которые будут заменены",
"adoptProtectedTitle": "Содержимое оператора, которое сохранится",
"adoptBackupNote": "Все заменённые файлы сохраняются в .update-backup/<отметка времени>/overwritten/ и могут быть восстановлены оттуда.",
"adoptConfirmBtn": "Подключить",
"adoptConfirmText": "Подключение заменит {{overwritten}} локальных файлов целевыми версиями (всего {{incoming}} файлов; {{protectedFiles}} файлов оператора сохраняются). Продолжить?",
"adoptAccepted": "Подключение запущено (задача {{id}}); ход обновляется каждые 1,5 секунды.",
"adoptFailed": "Не удалось подключить: {{reason}}",
"adoptedNoPreviousCommit": "Это результат подключения: до него git-истории не было, поэтому откатываться не к чему; первый откат запишет следующее обновление.",
"resultOverwrittenTitle": "Заменённые локальные файлы (копии в overwritten/)",
"rollbackItems": "Файлы, которые не были откачены"
},
"nav": {
"security": "Безопасность",
"toolGuard": "Блокировка вызовов",
@ -1830,6 +1963,7 @@
"rbac": "Права платформы",
"audit": "Журнал аудита",
"storage": "Очистка хранилища",
"update": "Обновление в один клик",
"infocollect": "Управление активами"
},
"infocollect": {

View File

@ -99,6 +99,139 @@
"passwordPlaceholder": "输入登录密码",
"submit": "登录"
},
"update": {
"title": "一键更新",
"intro": "这一页改的就是当前正在应答请求的这套安装:从更新源仓库(默认官方仓库)拉取默认分支的最新代码、重新编译、换掉二进制。你本机维护的 roles/skills/tools 与配置不会被覆盖。",
"loading": "正在读取本机安装状态",
"loadFailed": "读取本机安装状态失败:{{reason}}",
"installTitle": "本机安装",
"remoteTitle": "与更新源比较",
"applyTitle": "一键更新",
"jobTitle": "更新进度",
"rollbackTitle": "回滚",
"root": "安装目录",
"branch": "本机分支",
"commit": "当前提交",
"committedAt": "提交时间",
"subject": "提交说明",
"gitTree": "git 工作树",
"notGitTree": "不是 git 工作树",
"toolchainFound": "有 Go 工具链",
"toolchainMissing": "没有 Go 工具链",
"toolchainMissingHint": "未检测到 go 命令:更新只能挪源码,编译要另找机器",
"binaryPresent": "本机有二进制",
"binaryMissing": "本机没有二进制",
"rollbackPresent": "有可回滚点",
"rollbackMissing": "无可回滚点",
"notChecked": "还没查过更新源。进入本页后会自动查一次(每个会话只查一次);也可以随时点「检查更新」。",
"checkBtn": "检查更新",
"checking": "正在检查更新源…",
"checkFailed": "检查失败:{{reason}}",
"applyFailed": "启动更新失败:{{reason}}",
"rollbackFailed": "回滚失败:{{reason}}",
"behindCount": "落后 {{n}} 个提交",
"aheadCount": "本地领先 {{n}} 个提交",
"upToDate": "已是最新:本机 {{commit}} 已与更新源一致",
"remoteHead": "更新源最新提交",
"remoteSubject": "更新源提交说明",
"incomingTitle": "待并入的提交",
"incomingTruncated": "共 {{total}} 个新提交,这里只列出前 {{shown}} 个",
"applyBtn": "一键更新",
"jobRunningHint": "已有一次更新在进行中,下面是它的进度。",
"noToolchainWarn": "本机没有 Go 工具链:源码会更新,二进制不会更换,要由外部构建产出后再重启。",
"rollbackPendingHint": "上一次回滚尚未完成,请先点「回滚」继续恢复,再执行更新。",
"buildPendingHint": "上一次更新只搬了源码、没能换二进制(编译失败或当时没有 Go 工具链):点「一键更新」会补上这次编译。",
"blockedNotGitTree": "这个目录不是 git 工作树,无法自动更新。",
"blockedJobRunning": "已有更新在进行中,请等它结束。",
"blockedLocalEdits": "有 {{n}} 个产品源码文件被本地改过,自动更新不会覆盖它们:先提交或还原。",
"blockedDiverged": "本地领先 {{ahead}} 个提交、落后 {{behind}} 个提交:这是合并而不是下载,请先手工处理。",
"blockedNoUpdate": "更新源没有比本机更新的提交(还没查过就先点「检查更新」)。",
"restartChoiceLabel": "更新完成后退出进程(需 systemd/run.sh 等外部守护才会自动拉起;无人守护请手动重启)",
"restartNotWired": "本次启动没有提供重启钩子:更新完成后请自己重启服务。",
"confirmRestartYes": "已勾选:更新成功后本进程会退出,只有外部守护(systemd/run.sh 等)才会把它再拉起来。",
"confirmRestartNo": "未勾选:进程不退出,运行的仍是旧二进制,需要你自行重启。",
"confirmApply": "将要执行:从更新源 {{repo}} 更新到 {{target}}({{n}} 个新提交,本机当前 {{commit}})→ 重新编译二进制 → 备份并替换旧二进制。",
"confirmBuildPending": "将要执行:为已经就位的源码补上二进制(本机当前 {{commit}})→ 重新编译 → 备份并替换旧二进制。",
"applyAccepted": "更新已开始(任务 {{id}}),进度每 1.5 秒刷新一次。",
"localChangesTitle": "本机改动",
"localChangesHint": "标为「本机内容」的文件更新后原样保留;标为「产品源码」的文件会阻止自动更新。",
"noLocalChanges": "工作树干净:没有被修改或被删除的受跟踪文件。",
"colPath": "文件",
"colChangeStatus": "状态",
"colOwner": "归属",
"keptFile": "本机内容(更新保留)",
"productSource": "产品源码(会阻止更新)",
"noJob": "还没有更新记录",
"noSteps": "任务刚起来,还没有进度输出",
"pollingHint": "每 {{sec}} 秒读取一次进度",
"stateRunning": "进行中",
"stateSucceeded": "已完成",
"stateFailed": "失败",
"stateUnknown": "未知状态",
"restartRequested": "已要求在完成后退出",
"jobPollFailed": "进度读取失败:{{reason}}",
"jobDoneToast": "更新完成",
"buildDoneToast": "补编译完成",
"jobFailedToast": "更新失败",
"needsRestartToast": "二进制已换新,重启后才会生效",
"restartBanner": "已更新到 {{commit}},但当前进程仍在运行旧版本(磁盘上的二进制构建于 {{builtAt}})。重启后新版本才会生效。",
"restartBannerNoCommit": "磁盘上的二进制已换新(构建于 {{builtAt}}),但当前进程仍在运行旧版本;重启后新版本才会生效。",
"restartNowBtn": "立即重启服务",
"restartNowConfirm": "服务进程会退出;有守护进程(systemd/launchd)时几秒内会自动拉起新版本,本页随后自动刷新。没有守护时服务会保持停止,需要手动启动。确定现在重启?",
"restartRequestedToast": "已请求重启:进程退出后由守护进程拉起,页面会自动恢复",
"restartFailed": "重启请求失败:{{reason}}",
"restartOverlayTitle": "正在重启服务…",
"restartOverlayBody": "新进程接客后本页会自动刷新(会话会失效,需要重新登录)。无需手动操作。",
"restartOverlaySlowRunning": "服务仍在以旧进程应答——重启似乎没有发生。可点下方按钮刷新页面查看当前状态。",
"restartOverlaySlowDown": "服务还没有回来。若本机没有守护进程(systemd/launchd),它不会自己启动;手动启动服务后再刷新本页。",
"restartOverlayRefresh": "立即刷新页面",
"failureNoMessage": "服务端没有给出失败说明",
"resultTitle": "更新结果",
"resultFrom": "从",
"resultTo": "到",
"resultCommits": "并入提交数",
"resultFiles": "改动文件数",
"resultDuration": "用时",
"resultBackup": "备份目录",
"keptTitle": "保留下来的本机内容文件",
"nothingKept": "没有本机内容文件被挪动过",
"binarySwapped": "二进制已换新",
"binaryNotSwapped": "二进制未更换",
"restartNeeded": "需要重启才会运行新版本",
"restartNotNeeded": "不需要重启",
"failureTitle": "失败原因",
"noRollback": "没有可回滚点:更新过一次之后才会有",
"rollbackTarget": "回滚目标:{{commit}}(上一次更新之前的提交)",
"rollbackBtn": "回滚到更新前",
"confirmRollback": "确定回滚到 {{commit}} 吗?源码回到那次更新之前,二进制用回备份的那一份。",
"rollbackDone": "已回滚到 {{commit}}",
"sourceTitle": "更新源",
"sourceFromConfig": "更新源已配置(config.yaml 的 update 段)。",
"sourceIsDefault": "未配置更新源:使用官方仓库 {{repo}}。",
"sourceUrl": "更新源仓库",
"sourceBranch": "源默认分支",
"sourceUrlLabel": "更新源仓库地址",
"sourceRepoHint": "留空即使用官方仓库;可改为自己的二开或镜像地址。",
"sourceSaveBtn": "保存更新源",
"sourceSaveOk": "更新源已保存",
"sourceSaveFailed": "保存更新源失败:{{reason}}",
"adoptHint": "这个目录还不是 git 工作树。接入更新源后,它就成为可一键更新的正常安装。",
"adoptPreviewBtn": "预览并接入",
"adoptIncoming": "目标分支文件数",
"adoptOverwrittenTotal": "将被目标版本替换",
"adoptProtectedTotal": "运维者内容(保留)",
"adoptCommit": "目标提交",
"adoptOverwrittenTitle": "将被替换的本机文件",
"adoptProtectedTitle": "会保留的运维者内容",
"adoptBackupNote": "被替换的文件全部备份在 .update-backup/<时间戳>/overwritten/ 下,可从那里找回。",
"adoptConfirmBtn": "确认接入",
"adoptConfirmText": "接入会把 {{overwritten}} 个本机文件替换成目标版本(共 {{incoming}} 个文件;{{protectedFiles}} 个运维者文件保留)。确定继续?",
"adoptAccepted": "接入已开始(任务 {{id}}),进度每 1.5 秒刷新。",
"adoptFailed": "接入失败:{{reason}}",
"adoptedNoPreviousCommit": "这是「接入」结果:接入前没有 git 历史,因此没有上一提交可回滚;下一次更新会写下第一个回滚点。",
"resultOverwrittenTitle": "被替换的本机文件(备份在 overwritten/ 下)",
"rollbackItems": "未能回滚的文件"
},
"nav": {
"security": "安全防护",
"toolGuard": "调用拦截",
@ -1805,6 +1938,7 @@
"rbac": "平台权限",
"audit": "日志审计",
"storage": "存储清理",
"update": "一键更新",
"infocollect": "资产管理"
},
"infocollect": {

View File

@ -521,11 +521,18 @@ function applyPermissionElement(el) {
const allowed = permissionAllowedForElement(el);
el.hidden = !allowed;
el.classList.toggle('rbac-permission-denied', !allowed);
// Permission decides whether this user may ever use the control; it does not decide
// whether the control is ready. A page that disables one for a reason of its own marks
// it with data-state-disabled, because writing el.disabled = !allowed here otherwise
// re-enables it for exactly the users who are allowed - and a button whose preconditions
// are unmet is then pressed, and fails.
const blockedByState = el.dataset && el.dataset.stateDisabled === 'true';
const disabled = !allowed || blockedByState;
if ('disabled' in el) {
el.disabled = !allowed;
el.disabled = disabled;
}
el.setAttribute('aria-hidden', allowed ? 'false' : 'true');
el.setAttribute('aria-disabled', allowed ? 'false' : 'true');
el.setAttribute('aria-disabled', disabled ? 'true' : 'false');
}
let permissionClickGuardInstalled = false;

View File

@ -158,7 +158,7 @@ test('登录成功后重新加载曾因未授权失败的项目侧栏', () => {
assert.notEqual(conversationsIndex, -1);
assert.ok(projectRetryIndex > conversationsIndex);
assert.match(refreshSource, /typeof window\.refreshChatProjectSelector === 'function'/);
assert.match(html, /\/static\/js\/auth\.js\?v=20260907-blocked-1/);
assert.match(html, /\/static\/js\/auth\.js\?v=[A-Za-z0-9._-]+/);
});
test('用户真正滑到底部后恢复自动跟随且不会提前强制跳底', () => {
@ -533,5 +533,5 @@ test('暗色模式对话三点悬浮不会触发浅色父行背景', () => {
const css = fs.readFileSync('web/static/css/style.css', 'utf8');
assert.match(css, /html\[data-theme="dark"\] \.project-conversation-row:hover \.project-conversation-item/);
assert.match(css, /html\[data-theme="dark"\] \.project-folder-action:hover,[\s\S]*?background: rgba\(71, 85, 105, 0\.28\);[\s\S]*?box-shadow: none;/);
assert.match(html, /style\.css\?v=20260907-blocked-1/);
assert.match(html, /style\.css\?v=[A-Za-z0-9._-]+/);
});

View File

@ -41,7 +41,9 @@ test('刷新恢复会话时先完成权威审批配置同步再允许发送', ()
assert.match(chat, /await waitForHitlConfigReady\(hitlConversationAtSendStart\)/);
assert.match(chat, /hitlConfigSyncConversationId = conversationId;[\s\S]{0,240}await hitlConfigSyncPromise;/);
assert.match(chat, /await hitlConfigSyncPromise;[\s\S]{0,220}seq !== loadConversationRequestSeq/);
assert.match(fs.readFileSync('web/static/js/hitl.js', 'utf8'), /window\.csaiHitlDefaultReviewerReady = initHitlDefaultReviewerFromServer\(\)/);
const hitlPage = fs.readFileSync('web/static/js/hitl.js', 'utf8');
assert.match(hitlPage, /window\.csaiHitlDefaultConfigReady = initHitlDefaultReviewerFromServer\(\)/);
assert.match(hitlPage, /window\.csaiHitlDefaultReviewerReady = window\.csaiHitlDefaultConfigReady/);
});
test('同一会话的审批配置写入串行化以防止旧请求后到覆盖新选择', () => {
@ -294,7 +296,7 @@ test('多对话并发时释放隐藏主流且旧请求不能覆盖新对话状
assert.match(template, /monitor\.js\?v=20260907-blocked-1/);
assert.match(template, /chat-scroll\.js\?v=20260815-1/);
assert.match(template, /chat\.js\?v=20260907-blocked-1/);
assert.match(template, /style\.css\?v=20260907-blocked-1/);
assert.match(template, /style\.css\?v=[A-Za-z0-9._-]+/);
});
test('彻底停止始终使用弹窗锁定的会话且状态刷新后仍会取消', () => {

View File

@ -25,8 +25,12 @@ test('已有会话缺少本地配置时不会继承其他会话的最近审批
test('服务端默认审批人只更新默认值,不覆盖最近会话选择', () => {
const source = functionSource(hitl, 'applyHitlDefaultReviewerFromServer', 'fetchHitlDefaultReviewer');
assert.match(source, /window\.csaiHitlDefaultReviewer = v/);
assert.match(source, /return applyHitlDefaultConfigFromServer\(\{ defaultReviewer: reviewer \}\)/);
const configSource = functionSource(hitl, 'applyHitlDefaultConfigFromServer', 'fetchHitlDefaultConfig');
assert.match(configSource, /const reviewer = hitlReviewerNormalize\(src\.defaultReviewer \|\| src\.reviewer \|\| 'human'\)/);
assert.match(configSource, /window\.csaiHitlDefaultReviewer = reviewer/);
assert.doesNotMatch(source, /saveHitlLastGlobalConfig/);
assert.doesNotMatch(configSource, /saveHitlLastGlobalConfig|saveHitlConversationConfig/);
});
test('恢复会话审批配置时保留该会话自己的审批人', () => {

View File

@ -0,0 +1,133 @@
// The platform's permission gate must not re-enable a control a page disabled for a reason
// of its own.
//
// How the bug looked in a real browser: the 一键更新 page rendered an *enabled* apply button
// directly under the text "有 53 个产品源码文件被本地改过,自动更新不会覆盖它们". Nothing in
// the page's own tests could see it, because the page really does write `disabled` - the
// gate then runs over every [data-require-permission] element afterwards and writes
// `el.disabled = !allowed`, which for an administrator is `false`. Permission says whether a
// user may ever use a control; it does not say whether the control is ready.
const test = require('node:test');
const assert = require('node:assert');
const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
const AUTH = fs.readFileSync(path.join(__dirname, 'auth.js'), 'utf8');
const UPDATE = fs.readFileSync(path.join(__dirname, 'update.js'), 'utf8');
function sourceOf(name, src) {
const at = src.indexOf('function ' + name + '(');
assert.ok(at >= 0, `${name} is not in auth.js any more - this test is where the gate lives`);
let depth = 0;
for (let i = src.indexOf('{', at); i < src.length; i++) {
if (src[i] === '{') depth++;
else if (src[i] === '}') {
depth--;
if (depth === 0) return src.slice(at, i + 1);
}
}
assert.fail(`${name}: unbalanced`);
}
function element(attrs = {}) {
const el = {
hidden: false,
disabled: false,
dataset: {},
_attrs: { ...attrs },
classList: { classes: new Set(), toggle(c, on) { on ? this.classes.add(c) : this.classes.delete(c); } },
getAttribute(k) { return this._attrs[k] ?? null; },
setAttribute(k, v) { this._attrs[k] = String(v); },
};
if (attrs['data-state-disabled']) el.dataset.stateDisabled = attrs['data-state-disabled'];
// Buttons in a DOM have a `disabled` property; a plain object only gets one if the page
// asked for it, and the gate's `if ('disabled' in el)` is what decides whether state
// survives - so it is the part worth keeping honest.
return el;
}
function makeGate(granted) {
const sandbox = {
hasPermission: (p) => granted.has(p),
hasAnyPermission: (list) => list.some((p) => granted.has(p)),
console,
};
vm.createContext(sandbox);
vm.runInContext(sourceOf('permissionAllowedForElement', AUTH) + '\n' + sourceOf('applyPermissionElement', AUTH), sandbox);
return sandbox.applyPermissionElement;
}
test('a state-disabled control stays disabled for a user who holds the permission', () => {
const gate = makeGate(new Set(['update:apply']));
const el = element({ 'data-require-permission': 'update:apply', 'data-state-disabled': 'true' });
el.disabled = true;
gate(el);
assert.strictEqual(el.disabled, true, 'permission granted must not re-enable a control the page blocked');
assert.strictEqual(el.getAttribute('aria-disabled'), 'true', 'the assistive state must agree with the real one');
assert.strictEqual(el.hidden, false);
});
test('a permitted and ready control is enabled, and an unpermitted one is not', () => {
const gate = makeGate(new Set(['update:apply']));
const ready = element({ 'data-require-permission': 'update:apply' });
gate(ready);
assert.strictEqual(ready.disabled, false);
assert.strictEqual(ready.getAttribute('aria-disabled'), 'false');
// applyPermissionElement returns nothing, so the assertions read the element itself.
const deniedEl = element({ 'data-require-permission': 'update:apply' });
makeGate(new Set())(deniedEl);
assert.strictEqual(deniedEl.hidden, true);
assert.strictEqual(deniedEl.disabled, true);
assert.strictEqual(deniedEl.classList.classes.has('rbac-permission-denied'), true);
});
test('every control the update page disables by state carries the marker the gate honors', () => {
// The other half of the pair: a page that writes `disabled` without the marker silently
// loses it the moment the gate runs. Asserted over the rendered strings rather than by
// reading the source, so a refactor that drops the attribute is what fails.
const sandbox = {
console,
escapeHtml: (v) => String(v),
updateT: (key) => key,
renderUpdateRestartChoice: () => '',
renderUpdateChangesTable: () => '<div class="update-changes"></div>',
isUpdateJobRunning: () => true,
updateApplyBlockers: (status) => (status.blockingChanges || []).length ? ['blocked'] : [],
updateChecking: true,
};
vm.createContext(sandbox);
for (const fn of ['renderUpdateApplyBody', 'renderUpdateRollbackBody']) {
vm.runInContext(sourceOf(fn, UPDATE), sandbox);
}
const withBlocker = sandbox.renderUpdateApplyBody(
{ installed: true, canBuild: true, blockingChanges: [{ path: 'a.go' }], updateAvailable: true, diverged: false }, null);
const noBlocker = sandbox.renderUpdateApplyBody(
{ installed: true, canBuild: true, blockingChanges: [], updateAvailable: true, diverged: false }, null);
const rollbackRunning = sandbox.renderUpdateRollbackBody({ hasRollback: true, rollbackTo: 'abc' });
for (const [label, html] of [['apply(blocked)', withBlocker], ['rollback(running)', rollbackRunning]]) {
const buttons = html.match(/<button[^>]*>/g) || [];
assert.ok(buttons.length > 0, `${label}: rendered no button`);
const disabledTags = buttons.filter((t) => / disabled/.test(t));
assert.ok(disabledTags.length > 0, `${label}: expected a disabled button`);
for (const tag of disabledTags) {
assert.match(tag, /data-state-disabled="true"/, `${label}: state-disabled must carry the marker the gate reads: ${tag}`);
assert.match(tag, /data-require-permission=/, `${label}: the marker only matters on a permission-gated control: ${tag}`);
}
}
// And the *apply* control of an unblocked install must not advertise itself as blocked,
// or the gate would keep it dead for someone who can legitimately press it. Other buttons
// in the same render may still be state-disabled (checking is one), which is why this
// asserts about the apply button by name.
const applyTag = (noBlocker.match(/<button[^>]*update-apply-btn[^>]*>/) || [])[0];
assert.ok(applyTag, 'no apply button rendered when nothing blocks it');
assert.ok(!/disabled/.test(applyTag), `a ready apply control must not be disabled: ${applyTag}`);
for (const tag of (noBlocker.match(/<button[^>]*>/g) || [])) {
if (/ disabled/.test(tag)) {
assert.match(tag, /data-state-disabled="true"/, `every state-disabled control needs the marker: ${tag}`);
}
}
});

View File

@ -0,0 +1,48 @@
// The console's own hash form is `#system-update`, not `#/system-update` - and before this,
// typing or sharing the slashed form silently did nothing: the id missed the whitelist and
// the router stayed on whatever page had loaded, with no message anywhere. Since every bit of
// documentation (and every human habit) writes the slashed form, the router now normalizes it
// instead of rejecting it.
const test = require('node:test');
const assert = require('node:assert');
const fs = require('node:fs');
const path = require('node:path');
const ROUTER = fs.readFileSync(path.join(__dirname, 'router.js'), 'utf8');
test('both hash entry points strip a leading slash before the whitelist', () => {
// Two parsers exist (initial load and hash change); fixing only one is how this class of
// bug survives a "works for me" check.
const sites = [...ROUTER.matchAll(/let pageId = hashParts\[0\]([^\n]*)/g)];
assert.ok(sites.length >= 2, `expected two hash parsers, found ${sites.length}`);
for (const s of sites) {
assert.match(s[1], /replace\(\/\^#\?\\\/\//, 'this parser does not normalize the slashed form: ' + s[0]);
}
});
test('the slashed form resolves to the same page id as the plain one', () => {
// Mirrors the router exactly: it takes location.hash.slice(1), so the '#' is already gone
// before the split. A helper here that expected the '#' would "pass" the wrong rule.
const normalize = (fullHash) => {
const raw = fullHash.startsWith('#') ? fullHash.slice(1) : fullHash;
return raw.split('?')[0].replace(/^#?\//, '');
};
for (const page of ['system-update', 'plugins-management', 'dashboard', 'chat']) {
assert.strictEqual(normalize('#' + page), page);
assert.strictEqual(normalize('#/' + page), page);
}
// Query-carrying hashes must keep working the same way they did.
assert.strictEqual(normalize('#chat?conversation=abc'), 'chat');
});
test('the docs use a form the router actually accepts', () => {
const docs = ['../../../docs/zh-CN/developer-guide.md', '../../../docs/en-US/developer-guide.md'];
for (const rel of docs) {
const p = path.join(__dirname, rel);
const text = fs.readFileSync(p, 'utf8');
// Not a style preference: `#/x` was a dead link when it was written, so a doc that
// tells an operator to open it is telling them to open nothing.
assert.ok(!/#\/system-update/.test(text), `${rel} still advertises the dead #/system-update form`);
assert.match(text, /#system-update/, `${rel} must name the form that works`);
}
});

View File

@ -108,10 +108,16 @@ function initRouter() {
const hash = window.location.hash.slice(1);
if (hash) {
const hashParts = hash.split('?');
let pageId = hashParts[0];
let pageId = hashParts[0].replace(/^#?\//, '');
if (pageId === 'c2') pageId = 'c2-listeners';
// 一键更新已并进系统设置页的分区菜单:#system-update 这条老深链落到设置页的那一区。
const settingsSection = pageId === 'system-update' ? 'update' : '';
if (settingsSection) pageId = 'settings';
if (pageId && ['dashboard', 'chat', 'hitl', 'tool-guard', 'asset-overview', 'asset-library', 'info-collect', 'projects', 'vulnerabilities', 'webshell', 'chat-files', 'mcp-monitor', 'mcp-management', 'knowledge-management', 'knowledge-retrieval-logs', 'roles-management', 'platform-rbac', 'workflows', 'skills-monitor', 'skills-management', 'agents-management', 'settings', 'tasks', 'c2-listeners', 'c2-sessions', 'c2-tasks', 'c2-payloads', 'c2-events', 'c2-profiles'].includes(pageId)) {
switchPage(pageId);
if (settingsSection && typeof switchSettingsSection === 'function') {
switchSettingsSection(settingsSection);
}
if (pageId === 'chat') {
scheduleChatConversationFromHash(0);
}
@ -529,6 +535,12 @@ async function initPage(pageId) {
if (typeof loadConfig === 'function') {
loadConfig(false);
}
// 回到设置页时若停在「一键更新」分区,重新读一遍安装状态并把进度轮询接上——
// 离开设置页时轮询已被停掉,不接的话画面上会留一份不再动的进度。
const updateSection = document.getElementById('settings-section-update');
if (updateSection && updateSection.classList.contains('active') && typeof loadUpdateConsole === 'function') {
loadUpdateConsole();
}
break;
case 'roles-management':
// 初始化角色管理页面
@ -605,6 +617,11 @@ async function initPage(pageId) {
if (pageId !== 'tasks' && typeof cleanupTasksPage === 'function') {
cleanupTasksPage();
}
// 一键更新的进度轮询同理:它现在住在系统设置页里,离开设置页就没必要每 1.5 秒读一次任务了
// (同一页内切到别的分区由 settings.js 的 switchSettingsSection 负责停)。
if (pageId !== 'settings' && typeof stopUpdatePolling === 'function') {
stopUpdatePolling();
}
}
// 页面加载完成后初始化路由
@ -618,11 +635,17 @@ document.addEventListener('DOMContentLoaded', function() {
const hash = window.location.hash.slice(1);
// 处理带参数的hash(如 chat?conversation=xxx)
const hashParts = hash.split('?');
let pageId = hashParts[0];
let pageId = hashParts[0].replace(/^#?\//, '');
if (pageId === 'c2') pageId = 'c2-listeners';
// 与首屏解析同一套别名:#system-update 落到系统设置页的「一键更新」分区。
const settingsSection = pageId === 'system-update' ? 'update' : '';
if (settingsSection) pageId = 'settings';
if (pageId && ['dashboard', 'chat', 'hitl', 'tool-guard', 'asset-overview', 'asset-library', 'info-collect', 'projects', 'tasks', 'workflows', 'vulnerabilities', 'webshell', 'chat-files', 'mcp-monitor', 'mcp-management', 'knowledge-management', 'knowledge-retrieval-logs', 'roles-management', 'platform-rbac', 'skills-monitor', 'skills-management', 'agents-management', 'settings', 'c2-listeners', 'c2-sessions', 'c2-tasks', 'c2-payloads', 'c2-events', 'c2-profiles'].includes(pageId)) {
switchPage(pageId);
if (settingsSection && typeof switchSettingsSection === 'function') {
switchSettingsSection(settingsSection);
}
if (pageId === 'chat') {
scheduleChatConversationFromHash(0);
}

View File

@ -691,6 +691,14 @@ function switchSettingsSection(section) {
if (section === 'storage' && typeof initStorageSection === 'function') {
setTimeout(initStorageSection, 0);
}
if (section === 'update') {
if (typeof loadUpdateConsole === 'function') {
loadUpdateConsole();
}
} else if (typeof stopUpdatePolling === 'function') {
// 离开更新分区就停掉进度轮询;服务端的任务照跑,回来时 loadUpdateConsole 会接着读。
stopUpdatePolling();
}
}
// 打开设置

File diff suppressed because it is too large Load Diff

1016
web/static/js/update.js Normal file

File diff suppressed because it is too large Load Diff

View File

@ -3629,6 +3629,9 @@
<div class="settings-nav-item" data-section="storage" onclick="switchSettingsSection('storage')">
<span data-i18n="settings.nav.storage">存储清理</span>
</div>
<div class="settings-nav-item" data-section="update" data-require-permission="update:read" onclick="switchSettingsSection('update')">
<span data-i18n="settings.nav.update">一键更新</span>
</div>
</nav>
</aside>
@ -5198,6 +5201,16 @@
</div>
</div>
<!-- 一键更新 -->
<div id="settings-section-update" class="settings-section-content" data-require-permission="update:read">
<div class="settings-section-header update-section-head">
<h3 data-i18n="update.title">一键更新</h3>
<button class="btn-secondary" type="button" onclick="loadUpdateConsole()" data-i18n="common.refresh">刷新</button>
</div>
<p class="update-intro" data-i18n="update.intro">这一页改的就是当前正在应答请求的这套安装:拉取它自己跟踪的远端、重新编译、换掉二进制。你本机维护的 roles/skills/tools 与配置不会被覆盖。</p>
<div id="update-console" class="update-console"></div>
</div>
</div>
</div>
</div>
@ -6985,6 +6998,7 @@
<script src="/static/js/tasks.js"></script>
<script src="/static/js/workflow-package-client.js"></script>
<script src="/static/js/workflows.js"></script>
<script src="/static/js/update.js?v={{.Version}}"></script>
<script src="/static/js/roles.js"></script>
<script src="/static/js/rbac.js"></script>
<script src="/static/js/c2.js"></script>