Compare commits

...
2 Commits
Author SHA1 Message Date
ClaudeandClaude Opus 5.5 61bb21c7f3 ops(security): CPU, miner and pool-connection alerts; api/web unprivileged read-only containers; caddy pinned; read-only host audit (BUG-2416, #360)
Independent Staging Quality Gate / publish (push) Blocked by required conditions
Independent Staging Quality Gate / validate-python (push) In progress
Independent Staging Quality Gate / validate-frontend (push) In progress
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DbBXoyn7Hj3LCW3BUs5bZ8
2026-11-26 12:39:53 +08:00
ClaudeandClaude Opus 5.5 dcec206060 ci(release): branch release flow — next, release/x.y, hotfix, main; 封板 and 发版 workflows (BUG-2415)
Independent Staging Quality Gate / validate-frontend (push) Successful in 6m34s
Independent Staging Quality Gate / validate-python (push) Successful in 8m3s
Independent Staging Quality Gate / publish (push) Successful in 3m17s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DbBXoyn7Hj3LCW3BUs5bZ8
2026-11-26 11:53:14 +08:00
17 changed files with 1238 additions and 13 deletions
+3 -1
View File
@@ -5,6 +5,8 @@ on:
# truth, enforced by frontend/tests/staging-backend-workflows.test.ts). A push
# touching none of them is docs-only: it neither reruns this gate nor cancels
# a gate already running for a code push.
# BUG-2415: `next` (integration for the next version) runs the checks only; the
# publish job still deploys only refs/heads/staging, which the release workflows move.
pull_request:
paths:
- '.dockerignore'
@@ -25,7 +27,7 @@ on:
- 'vendor/**'
- 'contracts/**'
push:
branches: [staging]
branches: [staging, next]
paths:
- '.dockerignore'
- '.gitea/**'
+69
View File
@@ -0,0 +1,69 @@
name: 封板 Freeze release (cut release/x.y from next)
# BUG-2415 (owner 2026-11-26): the owner decides two things — when to freeze and when to
# ship. Freezing cuts release/<version> from the current `next` head, sets the app version on
# the release branch, and pushes it with RELEASE_PUSH_TOKEN; that push starts
# "Release branch to staging", which deploys it to the single staging environment.
on:
workflow_dispatch:
inputs:
version:
description: Version to freeze, for example 1.6
required: true
type: string
permissions:
contents: read
actions: read
concurrency:
group: release-flow
cancel-in-progress: false
jobs:
freeze:
runs-on: xiaoxin
timeout-minutes: 20
env:
GITEA_API_URL: ${{ gitea.api_url }}
GITEA_REPOSITORY: ${{ gitea.repository }}
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
RELEASE_PUSH_TOKEN: ${{ secrets.RELEASE_PUSH_TOKEN }}
VERSION: ${{ inputs.version }}
steps:
- name: Cut release branch from next
run: |
set -euo pipefail
work="$(mktemp -d "${RUNNER_TEMP:-/tmp}/jyotisha-freeze.XXXXXX")"
trap 'rm -rf -- "$work"' EXIT
flow="$work/branch-flow.sh"
curl --fail --silent --show-error --connect-timeout 15 --max-time 60 \
--header "Authorization: token $GITEA_TOKEN" \
"$GITEA_API_URL/repos/$GITEA_REPOSITORY/raw/deploy/branch-flow.sh?ref=next" --output "$flow"
chmod +x "$flow"
bash "$flow" validate-version "$VERSION"
[[ "$VERSION" =~ ^[0-9]+\.[0-9]+$ ]] || { echo "freeze takes x.y; hotfixes are cut by hand as hotfix/x.y.z from main" >&2; exit 1; }
branch="release/$VERSION"
if [ -n "$(bash "$flow" tag-sha "v$VERSION")" ]; then
echo "v$VERSION is already released; choose a new version" >&2; exit 1
fi
if [ -n "$(bash "$flow" ref-sha "$branch")" ]; then
echo "$branch already exists" >&2; exit 1
fi
next_sha="$(bash "$flow" ref-sha next)"
[[ "$next_sha" =~ ^[0-9a-f]{40}$ ]] || { echo "branch next does not exist" >&2; exit 1; }
cd "$work"
mkdir repo && cd repo
bash "$flow" prepare-git
bash "$flow" fetch next
git checkout -q -b "$branch" "$next_sha"
version_file=frontend/src/lib/app-version.ts
current="$(sed -nE 's/^export const APP_VERSION = "([^"]+)";.*/\1/p' "$version_file")"
if [ "$current" != "$VERSION" ]; then
sed -i -E "s/^export const APP_VERSION = \"[^\"]+\";/export const APP_VERSION = \"$VERSION\";/" "$version_file"
grep -q "^export const APP_VERSION = \"$VERSION\";" "$version_file"
git add "$version_file"
git commit -q -m "chore(release): freeze $VERSION [release-bump]"
fi
git push origin "HEAD:refs/heads/$branch"
echo "froze $branch at $(git rev-parse HEAD) (next was $next_sha)"
+86
View File
@@ -0,0 +1,86 @@
name: Release branch to staging
# BUG-2415: a push to release/x.y or hotfix/x.y.z moves the `staging` branch to that head,
# using RELEASE_PUSH_TOKEN so the existing staging pipeline (quality gate → database
# migration → deploy → full release checks) runs unchanged for that exact SHA. Every new
# commit on a release or hotfix branch must name a BUG-NNNN. A release branch's fixes are
# then merged back into `next`.
on:
push:
branches:
- 'release/**'
- 'hotfix/**'
permissions:
contents: read
actions: read
concurrency:
group: release-flow
cancel-in-progress: false
jobs:
to-staging:
runs-on: xiaoxin
timeout-minutes: 20
env:
GITEA_API_URL: ${{ gitea.api_url }}
GITEA_REPOSITORY: ${{ gitea.repository }}
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
RELEASE_PUSH_TOKEN: ${{ secrets.RELEASE_PUSH_TOKEN }}
HEAD_SHA: ${{ gitea.sha }}
BEFORE_SHA: ${{ gitea.event.before }}
GITEA_REF: ${{ gitea.ref }}
steps:
- name: Move staging to the release head
run: |
set -euo pipefail
[[ "$HEAD_SHA" =~ ^[0-9a-f]{40}$ ]]
branch="${GITEA_REF#refs/heads/}"
[[ "$branch" =~ ^(release/[0-9]+\.[0-9]+|hotfix/[0-9]+\.[0-9]+\.[0-9]+)$ ]] || {
echo "branch $branch is not release/x.y or hotfix/x.y.z" >&2; exit 1; }
work="$(mktemp -d "${RUNNER_TEMP:-/tmp}/jyotisha-release.XXXXXX")"
trap 'rm -rf -- "$work"' EXIT
flow="$work/branch-flow.sh"
curl --fail --silent --show-error --connect-timeout 15 --max-time 60 \
--header "Authorization: token $GITEA_TOKEN" \
"$GITEA_API_URL/repos/$GITEA_REPOSITORY/raw/deploy/branch-flow.sh?ref=$HEAD_SHA" --output "$flow"
chmod +x "$flow"
main_sha="$(bash "$flow" ref-sha main)"
staging_sha="$(bash "$flow" ref-sha staging)"
# Every commit new to this branch names a BUG number (merges and the freeze bump excepted).
base="$BEFORE_SHA"
if [[ ! "$base" =~ ^[0-9a-f]{40}$ ]] || [[ "$base" =~ ^0+$ ]]; then base="$main_sha"; fi
bash "$flow" commit-messages "$base" "$HEAD_SHA" | bash "$flow" bug-ids-ok || {
echo "every commit on $branch must name a BUG-NNNN; staging was not moved" >&2; exit 1; }
cd "$work" && mkdir repo && cd repo
bash "$flow" prepare-git
bash "$flow" fetch main staging "$branch"
git cat-file -e "$HEAD_SHA^{commit}"
if git merge-base --is-ancestor "$staging_sha" "$HEAD_SHA"; then
git push origin "$HEAD_SHA:refs/heads/staging"
elif [ "$staging_sha" = "$main_sha" ] || [[ "$branch" == hotfix/* ]]; then
# staging still shows the last shipped version (or a hotfix takes over the test
# environment): staging is only a deploy pointer, so it may be reset.
git push --force-with-lease="refs/heads/staging:$staging_sha" origin "$HEAD_SHA:refs/heads/staging"
else
echo "staging ($staging_sha) holds another unshipped release; ship or abandon it first" >&2
exit 1
fi
echo "staging → $HEAD_SHA ($branch); the staging pipeline deploys it"
if [[ "$branch" == release/* ]]; then
bash "$flow" fetch next
git checkout -q -B next refs/remotes/origin/next
if git merge-base --is-ancestor "$HEAD_SHA" HEAD; then
echo "next already contains $HEAD_SHA"
elif git merge -q --no-edit -m "Merge $branch into next" "$HEAD_SHA"; then
git push origin HEAD:refs/heads/next
echo "merged $branch into next"
else
git merge --abort || true
echo "::warning::$branch could not be merged into next automatically (conflict); merge it by hand"
fi
fi
+112
View File
@@ -0,0 +1,112 @@
name: 发版 Ship release to production
# BUG-2415 (owner 2026-11-26): the owner's second decision. Ships release/x.y (or
# hotfix/x.y.z) after the owner tested it on staging:
# 1. the branch head must be what staging is running, carry APP_VERSION = the version,
# and have a successful full release check (release-quality-gate) for that exact SHA;
# 2. main fast-forwards to it (never a merge or a rewrite);
# 3. recovery point + production migration run only when migrations changed since the
# last release tag; then the existing exact-SHA production deploy (which tags v<version>);
# 4. main is merged back into next.
# The three production workflows keep every check they already make (main == staging,
# exact staging-gate images); this workflow only runs them in order.
on:
workflow_dispatch:
inputs:
version:
description: Version to ship, for example 1.6 (release/1.6) or 1.6.1 (hotfix/1.6.1)
required: true
type: string
permissions:
contents: read
actions: write
# Not production-mutation: the workflows it starts take that queue themselves.
concurrency:
group: release-flow
cancel-in-progress: false
jobs:
ship:
runs-on: xiaoxin
timeout-minutes: 150
env:
GITEA_API_URL: ${{ gitea.api_url }}
GITEA_REPOSITORY: ${{ gitea.repository }}
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
RELEASE_PUSH_TOKEN: ${{ secrets.RELEASE_PUSH_TOKEN }}
VERSION: ${{ inputs.version }}
STAGING_URL: ${{ vars.STAGING_URL }}
steps:
- name: Ship
run: |
set -euo pipefail
work="$(mktemp -d "${RUNNER_TEMP:-/tmp}/jyotisha-ship.XXXXXX")"
trap 'rm -rf -- "$work"' EXIT
flow="$work/branch-flow.sh"
curl --fail --silent --show-error --connect-timeout 15 --max-time 60 \
--header "Authorization: token $GITEA_TOKEN" \
"$GITEA_API_URL/repos/$GITEA_REPOSITORY/raw/deploy/branch-flow.sh?ref=staging" --output "$flow"
chmod +x "$flow"
bash "$flow" validate-version "$VERSION"
if [[ "$VERSION" =~ ^[0-9]+\.[0-9]+$ ]]; then branch="release/$VERSION"; else branch="hotfix/$VERSION"; fi
sha="$(bash "$flow" ref-sha "$branch")"
[[ "$sha" =~ ^[0-9a-f]{40}$ ]] || { echo "$branch does not exist" >&2; exit 1; }
[ -z "$(bash "$flow" tag-sha "v$VERSION")" ] || { echo "v$VERSION is already shipped" >&2; exit 1; }
staging_sha="$(bash "$flow" ref-sha staging)"
[ "$staging_sha" = "$sha" ] || { echo "staging runs $staging_sha, not $branch ($sha); wait for its deploy" >&2; exit 1; }
deployed="$(curl --fail --silent --show-error --connect-timeout 15 --max-time 60 "${STAGING_URL:-https://staging.jyotisha.chat}/api/health" |
jq -r '.deployment.gitCommit // ""')"
[ "$deployed" = "$sha" ] || { echo "staging is still deploying ($deployed); ship after it is live" >&2; exit 1; }
bash "$flow" release-gate-passed "$sha" || {
echo "no successful full release check for $sha yet; it runs after each staging deploy (or dispatch Jyotish Release Quality Gate)" >&2; exit 1; }
cd "$work" && mkdir repo && cd repo
bash "$flow" prepare-git
bash "$flow" fetch main next "$branch"
version_now="$(git show "$sha:frontend/src/lib/app-version.ts" | sed -nE 's/^export const APP_VERSION = "([^"]+)";.*/\1/p')"
[ "$version_now" = "$VERSION" ] || { echo "$branch says APP_VERSION $version_now, not $VERSION" >&2; exit 1; }
main_before="$(git rev-parse refs/remotes/origin/main)"
git merge-base --is-ancestor "$main_before" "$sha" || {
echo "main ($main_before) is not an ancestor of $sha; merge main into $branch first" >&2; exit 1; }
git push origin "$sha:refs/heads/main"
echo "main → $sha"
if bash "$flow" migrations-changed "$main_before" "$sha"; then
run="$(bash "$flow" dispatch create-production-recovery.yml refs/heads/main "$(jq -cn --arg s "$sha" '{deploy_sha:$s}')")"
echo "recovery point run $run"
bash "$flow" wait-run "$run" 45
job="$(curl --fail --silent --show-error --header "Authorization: token $GITEA_TOKEN" \
"$GITEA_API_URL/repos/$GITEA_REPOSITORY/actions/runs/$run/jobs" | jq -r '.jobs[0].id')"
line="$(curl --fail --silent --show-error --header "Authorization: token $GITEA_TOKEN" \
"$GITEA_API_URL/repos/$GITEA_REPOSITORY/actions/jobs/$job/logs" |
grep -oE 'Recovery (attested|restore-verified): reference=[^ ]+ created_at=[^ ]+' | tail -1)"
reference="$(sed -E 's/.*reference=([^ ]+).*/\1/' <<<"$line")"
created_at="$(sed -E 's/.*created_at=([^ ]+).*/\1/' <<<"$line")"
[ -n "$reference" ] && [ -n "$created_at" ] || { echo "recovery run $run did not report its reference" >&2; exit 1; }
run="$(bash "$flow" dispatch migrate-production-database.yml refs/heads/main "$(jq -cn --arg s "$sha" --arg r "$reference" --arg c "$created_at" \
'{deploy_sha:$s,recovery_reference:$r,recovery_created_at:$c,restore_verified:"true"}')")"
echo "production migration run $run"
bash "$flow" wait-run "$run" 45
else
echo "no migration changes since $main_before; skipping recovery point and migration"
fi
run="$(bash "$flow" dispatch deploy-production.yml refs/heads/main "$(jq -cn --arg s "$sha" \
'{deploy_sha:$s,allow_rollback:"false",verification_mode:"public"}')")"
echo "production deploy run $run"
bash "$flow" wait-run "$run" 45
echo "shipped v$VERSION ($sha)"
git checkout -q -B next refs/remotes/origin/next
if git merge-base --is-ancestor "$sha" HEAD; then
echo "next already contains v$VERSION"
elif git merge -q --no-edit -m "Merge v$VERSION (main) into next" "$sha"; then
git push origin HEAD:refs/heads/next
echo "merged main into next"
else
git merge --abort || true
echo "::warning::main could not be merged into next automatically (conflict); merge it by hand"
fi
+6 -6
View File
@@ -36,19 +36,19 @@
1. 打包前 `git status --short --branch`;不得覆盖无关的脏文件。
2. 部署后验证 `/login`、未登录 `/api/account` = `401`、内部 `/api/health` = `200` 且 `swisseph_available = true`;`deployment.gitCommit` 必须等于预期 SHA。
3. 不得暴露端口 `5200`、模型 key、数据库口令、用户 JWT、SSH 私钥。
4. 生产部署只走 Gitea 手动流程(先 `release-quality-gate`,再 dispatch `deploy-production`),复用 staging 已验收的镜像 digest;不改 DNS、不导入生产数据。
4. 生产部署只走 Gitea 手动「发版 Ship release」工作流(BUG-2415):它检查完整发布检查已通过,把 `main` 快进到 `release/x.y`(或 `hotfix/x.y.z`)的头,按需跑恢复点与迁移,再 dispatch `deploy-production`;复用 staging 已验收的同 SHA 镜像 digest;不改 DNS、不导入生产数据。
## 2. 分支与交付
分支模型:`staging` 是测试环境,`main` 是生产控制分支。所有改动先经 `staging` 验收,再提升到 `main`;不存在直接改 `main` 的路径。
分支模型(BUG-2415,2026-11-26 负责人批准,见 `docs/operations/branch-flow.md`):`next` 是下一版本的集成分支(只跑检查、不部署);`release/x.y` 是封板候选,推送后由 CI 把 `staging`(测试环境指针)移到它并部署;`hotfix/x.y.z` 从 `main` 拉;`main` 是生产控制分支,只由「发版」工作流快进。负责人只决定「封板」和「发版」。不存在直接改 `main` 的路径。
1. 动手前 `git fetch origin --prune`,以远端 **`origin/staging`** 为基线。本地 `staging` / `main` 经常落后远端上百个提交,不得作为基线。
1. 动手前 `git fetch origin --prune`,新功能以远端 **`origin/next`** 为基线;封板期修复以 **`origin/release/x.y`** 为基线。本地分支经常落后远端上百个提交,不得作为基线。
2. 在独立 worktree 开发:路径 `.worktrees/<主题>-<日期>`,分支 `codex/<主题>-<日期>`(见 §3)。
3. 交付到 staging 用快进推送 `git push origin HEAD:staging`。这会触发 Gitea `backend-quality-gate`;它的 `paths:` 过滤与 `deploy/gated-paths.txt` 逐行一致。改动**全部**落在清单之外的纯文档推送(`docs/**`、根目录 `BLOCKED.md` / `CHANGELOG*.md` / `CONTEXT.md` / `AGENTS.md` / `CLAUDE.md` / `README.md` 等)不触发门禁、不发布镜像、不部署。鼓励把文档与同批代码合并一次推送,避免 staging head 与已部署 SHA 分离。
3. 日常交付用快进推送 `git push origin HEAD:next`(只跑门禁检查,不部署);封板期的修复推 `release/x.y`,提交信息必须带 `BUG-NNNN`,CI 会把 `staging` 移过去并部署、再合回 `next`。直接 `git push origin HEAD:staging` 是过渡期旧做法,已弃用。推送 `staging` 会触发 Gitea `backend-quality-gate`;它的 `paths:` 过滤与 `deploy/gated-paths.txt` 逐行一致。改动**全部**落在清单之外的纯文档推送(`docs/**`、根目录 `BLOCKED.md` / `CHANGELOG*.md` / `CONTEXT.md` / `AGENTS.md` / `CLAUDE.md` / `README.md` 等)不触发门禁、不发布镜像、不部署。鼓励把文档与同批代码合并一次推送,避免 staging head 与已部署 SHA 分离。
4. 门禁构建 digest 固定镜像并 dispatch `deploy-staging`;随后在 staging 完成与风险相称的验收。`GET /api/health` 的 `.deployment.gitCommit` 必须等于**最近一次含门禁路径改动的 staging 提交**。记这个提交为发布修订 `R`,记当前 staging head 为 `H`。其后若只有纯文档提交,`deploy/is-docs-only-range.sh R H` 必须退出 0,否则视为未部署。生产四个手动工作流发布的是 `R`,不是纯文档的 `H`;公网 health 的 gitCommit 仍必须等于 `R`。该脚本退出 1 或 2 都拒绝发布。
5. 提升到 `main` **必须快进到 `H`,不得 merge**。`main` 与 `staging` 必须是同一 SHA。生产镜像和控制器产物取 `R` 的门禁结果,不取纯文档的 `H`。merge commit 会让生产部署失败。
5. 提升到 `main` 只由「发版」工作流做,**必须快进到 `H`,不得 merge**。`main` 与 `staging` 必须是同一 SHA。生产镜像和控制器产物取 `R` 的门禁结果,不取纯文档的 `H`。merge commit 会让生产部署失败。
6. 推送后必须核对远端 SHA;远端验证失败时不得声称已交付。
7. 不得自行提升 `main`、不动 DNS——这两件事只由产品负责人触发。不改 `.gitea/workflows/**`,除非任务书的决策记录点名了具体文件。2026-10-14 的授权只覆盖 `deploy-production.yml`、`create-production-recovery.yml`、`migrate-production-database.yml`、`release-quality-gate.yml` 的发布修订规则(`R` 加其后纯文档)。不改 staging 工作流,不改 `deploy/gated-paths.txt`。
7. 不得自行提升 `main`、不得自行封板、不动 DNS——封板、发版只由产品负责人决定(Gitea 手动工作流)。不改 `.gitea/workflows/**`,除非任务书的决策记录点名了具体文件。2026-10-14 的授权只覆盖 `deploy-production.yml`、`create-production-recovery.yml`、`migrate-production-database.yml`、`release-quality-gate.yml` 的发布修订规则(`R` 加其后纯文档)。不改 staging 工作流,不改 `deploy/gated-paths.txt`。2026-11-26 负责人授权 BUG-2415:`backend-quality-gate.yml` 的 push 分支加 `next`(只检查),新增 `freeze-release.yml`、`release-to-staging.yml`、`ship-release.yml` 与 `deploy/branch-flow.sh`。
## 3. 工作树与多会话
+53
View File
@@ -144,6 +144,10 @@ It fails while `frontend/src/lib/legal-entity.ts` still holds placeholder operat
## Manual production deployment with Gitea Actions
### Branch release flow (BUG-2415, owner 2026-11-26)
From 1.6 on, releases follow `docs/operations/branch-flow.md`: windows push to `next` (checks only, no deploy); the owner's **封板 Freeze release** workflow cuts `release/x.y` from `next`; a push to `release/*` or `hotfix/*` runs **Release branch to staging**, which requires `BUG-NNNN` on every new commit, moves `staging` to that head with `RELEASE_PUSH_TOKEN` (so the unchanged staging gate → migration → deploy → full release checks run for that exact SHA) and merges a release branch back into `next`. The owner's **发版 Ship release** workflow then fast-forwards `main` to that head only when staging is live on it, `APP_VERSION` equals the version and the full release checks passed for that SHA; it runs **Create Production Recovery Point** and **Migrate Production Database** only when `frontend/supabase/migrations/` changed since the previous `main` (the recovery run's restore verification is the attestation, and the owner's 「发版」 click is the human approval that the manual migrate step used to represent), then **Deploy Production** (which tags `v<APP_VERSION>`), and merges `main` back into `next`. The production workflows below keep every check they make; the ship workflow only runs them in order. Pushing directly to `staging` still deploys during the transition but is deprecated.
GitHub production deployment is retired. Production changes are released only by manually dispatching `.gitea/workflows/deploy-production.yml`. `main` must be a fast-forward to the current staging head `H`. The deployed SHA is `R`, the latest successful staging push of `backend-quality-gate`, and `deploy/is-docs-only-range.sh R H` must exit 0 (exit 1 or 2 both refuse). Controller artifacts and image digests come from `R`. Public staging health must report `R`. The full release gate (`release-quality-gate.yml`) must have succeeded for `R` or `H`. Since BUG-2390 (owner 2026-11-25) Deploy staging queues it automatically on `refs/heads/staging` after every successful staging deploy, so it normally exists before the owner approves a release and is not rerun from `main`; a newer staging deploy cancels an older queued run. If that run was cancelled or failed for an environment reason, dispatch the workflow manually from `main` (it may record `H` when `H` is docs-only ahead of `R`). Rollback still requires an explicit confirmation, a gate run, and ancestry inside reviewed `main` history. The workflow deploys immutable registry digests and never builds application images on the production host.
The `internal` verification mode is for pre-DNS checks on the new host. The `public` mode is for the same SHA after authoritative DNS and Caddy TLS converge. Neither mode imports data, applies pending migrations, or changes DNS.
@@ -563,6 +567,55 @@ deploy/find-request-log.sh <requestId> --since 24h
`<requestId>` 必须是 UUID。其它写法会拒绝,避免被当成命令。`--since` 只接受类似 `24h`、`30m` 的形式。容器日志行前面的服务名前缀会先去掉,再按时间排序。来自 web、api、caddy。
### 防入侵、防挖矿(BUG-2416 / #360)
**监控(随 `install-production-monitor.sh` 的 ops-check 每 5 分钟跑)**
- 主机 CPU 连续两次(约 10 分钟)超过 85%:`cpu_high`。
- 某个容器连续两次超过一个核的 90%:`container_cpu_high`(读 cgroup v2 的 `cpu.stat`)。
- 不在白名单里、CPU 占用超过 50% 的进程:`suspicious_process`。
- 命令行里出现常见挖矿程序名或 `stratum+tcp`:`miner_process`。
- 有进程连到常见矿池端口(3333、4444、5555、7777、9999、14444 等):`mining_pool_connection`。我们自己的 22/80/443/3000/5200/5432 入站连接不算。
- 告警只带进程名和进程号,不发命令行和环境变量。同一个进程只报一次。
- 阈值可用 `JYOTISHA_CPU_PERCENT_LIMIT`、`JYOTISHA_CONTAINER_CPU_LIMIT`、`JYOTISHA_PROCESS_CPU_LIMIT`、`JYOTISHA_CPU_SUSTAIN_RUNS` 调。
**容器(`docker-compose.server.yml`,测试和生产共用)**
- `api` 以 uid 10001、`web` 以 uid 1000 运行,不再是 root。
- 两者都是只读镜像(`read_only`),去掉全部 Linux 权限(`cap_drop: ALL`),不许提权(`no-new-privileges`),限制进程数和内存(api 2 GB,web 1 GB)。
- 可写的地方只有这些:
- api:`/app/scratch/local`(原来的命名卷:星盘缓存、任务记录)和 `/tmp`(内存盘 512 MB:报告产物、临时文件)。
- web:`/tmp`(内存盘 256 MB:在线技能的运行副本)和 `/app/frontend/.next/cache`(内存盘 256 MB:图片缓存)。
- `api-scratch-owner` 是一次性小容器:每次启动 api 前,把 scratch 卷里不属于 10001 的文件改给 10001。它没有网络,只有改文件属主的权限,跑完就退出。
- caddy 镜像按 digest 固定;caddy 只保留绑定 80/443 的权限。postgres 不动(它的启动脚本需要切换用户)。
- **回退**:容器设置只在 compose 文件里,镜像没变。出问题时把 `deploy/docker-compose.server.yml` 回到上一个版本再部署即可;回到 root 运行后,属于 10001 的 scratch 文件 root 照样能读写。
**主机只读核查**
```bash
sudo bash /opt/jyotisha-production/deploy/monitor/host-audit.sh
```
只读、只打印:自动安全更新、fail2ban、sshd 设置、CPU 最高的进程、临时目录里的可执行文件、各处 crontab、非软件包自带的 systemd 单元、对外连接、容器和镜像、最近登录。不改任何东西,不打印环境变量和密钥。
**可选:fail2ban(不会自动安装,需要负责人同意后手动执行)**
```bash
sudo apt-get install -y fail2ban
sudo tee /etc/fail2ban/jail.d/sshd.local >/dev/null <<'JAIL'
[sshd]
enabled = true
backend = systemd
maxretry = 5
findtime = 10m
bantime = 1h
JAIL
sudo systemctl enable --now fail2ban
sudo fail2ban-client status sshd
```
装之前先确认自己的 SSH 能登录(密钥登录不受影响,只封连续失败的地址)。
## Common operations
```bash
+166
View File
@@ -0,0 +1,166 @@
#!/usr/bin/env bash
# BUG-2415: helpers for the branch release flow (next / release/x.y / hotfix/x.y.z / main).
#
# branch-flow.sh validate-version <x.y|x.y.z> exit 1 unless the value is a version
# branch-flow.sh bug-ids-ok stdin: commit messages separated by NUL;
# exit 1 naming each message without BUG-NNNN
# (merge commits and [release-bump] are exempt)
# branch-flow.sh commit-messages <base> <head> NUL-separated messages of base..head (Gitea compare API)
# branch-flow.sh ref-sha <branch> the branch head SHA, or empty when it does not exist
# branch-flow.sh tag-sha <tag> the tagged commit SHA, or empty when the tag does not exist
# branch-flow.sh prepare-git init a work tree whose origin pushes with RELEASE_PUSH_TOKEN
# branch-flow.sh fetch <ref>... fetch refs (runner mirror first, then origin)
# branch-flow.sh dispatch <workflow> <ref> <json-inputs> prints the new run id
# branch-flow.sh wait-run <run-id> <minutes> exit 0 on success, 1 on failure/timeout
# branch-flow.sh release-gate-passed <sha> exit 0 when a release-quality-gate run for sha succeeded
# branch-flow.sh migrations-changed <base> <head> exit 0 when base..head touches frontend/supabase/migrations/
#
# Network calls use GITEA_API_URL / GITEA_REPOSITORY / GITEA_TOKEN. Pushes use
# RELEASE_PUSH_TOKEN (a personal access token), because pushes made with the
# workflow's own token do not start other workflows.
set -euo pipefail
api_url="${GITEA_API_URL:-https://git.copse.top/api/v1}"
repository="${GITEA_REPOSITORY:-root/Jyotisha}"
clone_url="${GITEA_CLONE_URL:-https://git.copse.top/root/Jyotisha.git}"
mirror="${JYOTISHA_MIRROR:-/root/.cache/jyotisha-mirror.git}"
api() {
curl --fail --silent --show-error --connect-timeout 15 --max-time 60 --retry 3 --retry-all-errors \
--header "Authorization: token ${GITEA_TOKEN:?GITEA_TOKEN is required}" "$@"
}
validate_version() {
[[ "${1:-}" =~ ^[1-9][0-9]*\.[0-9]+(\.[0-9]+)?$ ]] || { echo "not a version: ${1:-}" >&2; return 1; }
}
bug_ids_ok() {
local bad=0 message first
while IFS= read -r -d '' message || [ -n "$message" ]; do
[ -n "$message" ] || continue
first="${message%%$'\n'*}"
case "$first" in
"Merge "*) continue ;;
esac
if [[ "$message" == *"[release-bump]"* ]]; then continue; fi
if ! grep -Eq 'BUG-[0-9]{3,5}' <<<"$message"; then
echo "missing BUG number: $first" >&2
bad=1
fi
done
return "$bad"
}
commit_messages() {
local base="$1" head="$2"
local response
response="$(api "$api_url/repos/$repository/compare/$base...$head")"
jq -e '(.total_commits // 0) == ((.commits // []) | length)' <<<"$response" >/dev/null || {
echo "compare $base...$head returned a partial commit list; cannot check BUG numbers" >&2
return 2
}
jq -j '.commits[]? | .commit.message + "\u0000"' <<<"$response"
}
ref_sha() {
local branch="$1" out
out="$(curl --silent --connect-timeout 15 --max-time 60 --retry 3 \
--header "Authorization: token ${GITEA_TOKEN:?}" \
--write-out '\n%{http_code}' "$api_url/repos/$repository/branches/$branch")"
case "${out##*$'\n'}" in
200) jq -r '.commit.id' <<<"${out%$'\n'*}" ;;
404) printf '' ;;
*) echo "could not read branch $branch" >&2; return 2 ;;
esac
}
tag_sha() {
local tag="$1" out
out="$(curl --silent --connect-timeout 15 --max-time 60 --retry 3 \
--header "Authorization: token ${GITEA_TOKEN:?}" \
--write-out '\n%{http_code}' "$api_url/repos/$repository/tags/$tag")"
case "${out##*$'\n'}" in
200) jq -r '.commit.sha' <<<"${out%$'\n'*}" ;;
404) printf '' ;;
*) echo "could not read tag $tag" >&2; return 2 ;;
esac
}
prepare_git() {
: "${RELEASE_PUSH_TOKEN:?RELEASE_PUSH_TOKEN secret is missing: see docs/operations/branch-flow.md}"
git init -q .
git remote remove origin 2>/dev/null || true
git remote add origin "$clone_url"
git config user.name "Jyotisha release bot"
git config user.email "release-bot@jyotisha.invalid"
git config http.extraHeader "Authorization: Basic $(printf 'release-bot:%s' "$RELEASE_PUSH_TOKEN" | base64 -w0)"
}
fetch_refs() {
local ref
if [ -d "$mirror" ]; then
timeout 300 git fetch -q --no-tags "$mirror" '+refs/heads/*:refs/remotes/mirror/*' || true
fi
for ref in "$@"; do
timeout 300 git fetch -q --no-tags origin "+refs/heads/$ref:refs/remotes/origin/$ref"
done
}
dispatch() {
local workflow="$1" ref="$2" inputs="$3" response run_id
response="$(api --request POST --header "Content-Type: application/json" \
--data "$(jq -cn --arg ref "$ref" --argjson inputs "$inputs" '{ref:$ref,inputs:$inputs}')" \
"$api_url/repos/$repository/actions/workflows/$workflow/dispatches?return_run_details=true")"
run_id="$(jq -er '.workflow_run_id | select(type == "number" and . > 0)' <<<"$response")"
printf '%s\n' "$run_id"
}
wait_run() {
local run_id="$1" minutes="$2" deadline state
deadline=$(( $(date +%s) + minutes * 60 ))
while [ "$(date +%s)" -lt "$deadline" ]; do
state="$(api "$api_url/repos/$repository/actions/runs/$run_id" | jq -r '[.status, (.conclusion // "")] | join(" ")')"
case "$state" in
"completed success") return 0 ;;
completed*) echo "run $run_id ended: $state" >&2; return 1 ;;
esac
sleep 30
done
echo "run $run_id did not finish within $minutes minutes" >&2
return 1
}
release_gate_passed() {
local sha="$1"
api "$api_url/repos/$repository/actions/runs?head_sha=$sha&limit=50" |
jq -e --arg sha "$sha" '[.workflow_runs[]? | select(.head_sha == $sha)
| select((.path | split("@")[0]) | endswith("release-quality-gate.yml"))
| select(.status == "completed" and .conclusion == "success")] | length > 0' >/dev/null
}
migrations_changed() {
local base="$1" head="$2"
# Gitea lists changed files per commit; a truncated listing counts as "changed" so the
# release never skips a migration it could not see.
api "$api_url/repos/$repository/compare/$base...$head" |
jq -e '((.total_commits // 0) != ((.commits // []) | length))
or any(.commits[]?; (.files == null)
or any(.files[]?; ((.filename // "") + " " + (.previous_filename // "")) | test("frontend/supabase/migrations/")))' >/dev/null
}
command="${1:-}"
shift || true
case "$command" in
validate-version) validate_version "$@" ;;
bug-ids-ok) bug_ids_ok ;;
commit-messages) commit_messages "$@" ;;
ref-sha) ref_sha "$@" ;;
tag-sha) tag_sha "$@" ;;
prepare-git) prepare_git ;;
fetch) fetch_refs "$@" ;;
dispatch) dispatch "$@" ;;
wait-run) wait_run "$@" ;;
release-gate-passed) release_gate_passed "$@" ;;
migrations-changed) migrations_changed "$@" ;;
*) echo "usage: branch-flow.sh <command> …" >&2; exit 2 ;;
esac
+64 -1
View File
@@ -1,10 +1,45 @@
services:
# BUG-2416 (#360): api runs as uid 10001, so the existing scratch volume (written
# as root before) is handed over first. Root here only changes file owners on that
# one volume; it has no network and exits.
api-scratch-owner:
image: ${API_IMAGE:-jyotisha-api:local}
user: "0:0"
entrypoint: ["sh", "-c", "find /app/scratch/local ! -uid 10001 -exec chown -h 10001:10001 {} + && chmod 700 /app/scratch/local"]
network_mode: none
restart: "no"
security_opt:
- no-new-privileges:true
cap_drop:
- ALL
cap_add:
- CHOWN
- FOWNER
- DAC_OVERRIDE
- DAC_READ_SEARCH
volumes:
- api_scratch:/app/scratch/local
api:
image: ${API_IMAGE:-jyotisha-api:local}
build:
context: ..
dockerfile: deploy/railway-api.Dockerfile
restart: unless-stopped
# BUG-2416 (#360): no root, no extra privileges, read-only image. The only
# writable places are the scratch volume (chart cache, job records) and /tmp
# (report artifacts, tempfile). The image is unchanged, so rolling back the
# application image keeps these settings.
user: "10001:10001"
read_only: true
tmpfs:
- /tmp:size=512m,mode=1777
security_opt:
- no-new-privileges:true
cap_drop:
- ALL
pids_limit: 512
mem_limit: 2g
logging:
driver: json-file
options:
@@ -15,6 +50,8 @@ services:
environment:
PORT: 5200
GITHUB_SHA: ${GITHUB_SHA}
HOME: /tmp
PYTHONDONTWRITEBYTECODE: "1"
JYOTISH_ALLOWED_HOSTS: localhost,127.0.0.1,::1,api
expose:
- "5200"
@@ -30,6 +67,9 @@ services:
# files, and high-rigor job records live under scratch/local. Named volume
# is created on first use; previous overlay data was ephemeral.
- api_scratch:/app/scratch/local
depends_on:
api-scratch-owner:
condition: service_completed_successfully
web:
image: ${WEB_IMAGE:-jyotisha-web:local}
@@ -43,6 +83,20 @@ services:
# BUG-2352 (#347): on stop, the app hands running report jobs back before exiting
# (src/lib/graceful-shutdown.ts gives them up to 35 s); Docker waits 40 s before SIGKILL.
stop_grace_period: 40s
# BUG-2416 (#360): the node image's own unprivileged user (uid 1000), read-only
# image. Writable: /tmp (live skill runtime copies, tempfiles) and Next.js's
# runtime cache dir (image optimizer); both are memory-backed and start empty.
user: "1000:1000"
read_only: true
tmpfs:
- /tmp:size=256m,mode=1777
- /app/frontend/.next/cache:size=256m,uid=1000,gid=1000,mode=0755
security_opt:
- no-new-privileges:true
cap_drop:
- ALL
pids_limit: 512
mem_limit: 1g
logging:
driver: json-file
options:
@@ -69,8 +123,17 @@ services:
condition: service_healthy
caddy:
image: caddy:2-alpine
# BUG-2416 (#360): pinned by digest so a changed upstream tag never reaches production unreviewed.
image: caddy:2-alpine@sha256:003a97808e781aa9f7e75cc2f43d34d461099031faf5e20faefb9f61126836f0
restart: unless-stopped
security_opt:
- no-new-privileges:true
cap_drop:
- ALL
cap_add:
- NET_BIND_SERVICE
pids_limit: 256
mem_limit: 256m
logging:
driver: json-file
options:
+142
View File
@@ -0,0 +1,142 @@
#!/usr/bin/env bash
# BUG-2416 (#360): read-only security audit of the production host.
#
# sudo bash /opt/jyotisha-production/deploy/monitor/host-audit.sh
#
# It only reads and prints. It never installs, stops, deletes or edits anything,
# and it never prints environment variables, env files, keys or database URLs.
# Output is for the owner/coordinator to read; act on it separately.
set -uo pipefail
set +x
umask 077
export LC_ALL=C
section() {
printf '\n==== %s ====\n' "$1"
}
have() {
command -v "$1" >/dev/null 2>&1
}
# Command lines can carry tokens (e.g. --password=…). Show at most 160 characters
# and blank anything that looks like a key/value secret.
mask_args() {
sed -E 's/((pass(word)?|token|secret|key|apikey|api_key|authorization)[=: ]+)[^ ]+/\1***/Ig' | cut -c1-160
}
section "host"
uname -srm 2>/dev/null || true
uptime 2>/dev/null || true
section "unattended-upgrades"
if have systemctl; then
systemctl is-enabled unattended-upgrades 2>/dev/null || echo "unattended-upgrades: not installed or not enabled"
systemctl is-active unattended-upgrades 2>/dev/null || true
fi
if [ -r /etc/apt/apt.conf.d/20auto-upgrades ]; then
grep -E '^APT::Periodic' /etc/apt/apt.conf.d/20auto-upgrades || true
else
echo "/etc/apt/apt.conf.d/20auto-upgrades: missing"
fi
if [ -r /var/log/unattended-upgrades/unattended-upgrades.log ]; then
echo "last runs:"
grep -E 'Starting unattended upgrades|All upgrades installed|No packages found' /var/log/unattended-upgrades/unattended-upgrades.log | tail -5 || true
fi
if have apt; then
echo "pending security updates (count):"
apt list --upgradable 2>/dev/null | grep -c -- '-security' || true
fi
section "fail2ban"
if have fail2ban-client; then
fail2ban-client status 2>/dev/null || echo "fail2ban installed but not answering"
fail2ban-client status sshd 2>/dev/null | grep -E 'Currently|Total' || true
else
echo "fail2ban: not installed"
fi
section "sshd settings (effective)"
if have sshd; then
sshd -T 2>/dev/null | grep -Ei '^(port|permitrootlogin|passwordauthentication|pubkeyauthentication|kbdinteractiveauthentication|maxauthtries|allowusers) ' || true
else
grep -Ei '^\s*(Port|PermitRootLogin|PasswordAuthentication|PubkeyAuthentication)\b' /etc/ssh/sshd_config /etc/ssh/sshd_config.d/*.conf 2>/dev/null || true
fi
echo "authorized_keys entries (count, comment only):"
for file in /root/.ssh/authorized_keys /home/*/.ssh/authorized_keys; do
[ -r "$file" ] || continue
printf '%s: %s keys;' "$file" "$(grep -cvE '^\s*(#|$)' "$file")"
awk '!/^[[:space:]]*(#|$)/ {print " " $NF}' "$file" | tr '\n' ' '
printf '\n'
done
section "top CPU processes"
ps -eo pid,user,pcpu,pmem,etime,comm,args --sort=-pcpu 2>/dev/null | head -15 | mask_args
section "processes running from temp or hidden paths"
ps -eo pid,user,args 2>/dev/null | grep -E '(/tmp/|/var/tmp/|/dev/shm/|/\.[^/ ]+/)' | grep -v grep | mask_args || true
section "crontabs"
for file in /etc/crontab /etc/cron.d/*; do
[ -r "$file" ] || continue
echo "-- $file"
grep -vE '^\s*(#|$)' "$file" | cut -c1-200 || true
done
for dir in /etc/cron.hourly /etc/cron.daily /etc/cron.weekly /etc/cron.monthly; do
[ -d "$dir" ] && printf '%s: %s\n' "$dir" "$(ls -1 "$dir" 2>/dev/null | tr '\n' ' ')"
done
if [ -d /var/spool/cron/crontabs ]; then
for file in /var/spool/cron/crontabs/*; do
[ -r "$file" ] || continue
echo "-- user crontab $(basename "$file")"
grep -vE '^\s*(#|$)' "$file" | cut -c1-200 || true
done
fi
section "enabled systemd units not shipped by a package"
if have systemctl; then
systemctl list-unit-files --state=enabled --no-legend 2>/dev/null | awk '{print $1}' | while read -r unit; do
path="$(systemctl show -p FragmentPath --value "$unit" 2>/dev/null)"
[ -n "$path" ] || continue
if have dpkg && dpkg -S "$path" >/dev/null 2>&1; then
continue
fi
printf '%s %s\n' "$unit" "$path"
done
echo "timers:"
systemctl list-timers --all --no-legend 2>/dev/null | awk '{print $(NF-1), $NF}' | head -20
fi
section "executable files in /tmp /var/tmp /dev/shm"
for dir in /tmp /var/tmp /dev/shm; do
[ -d "$dir" ] || continue
find "$dir" -xdev -type f -perm /111 -printf '%TY-%Tm-%Td %u %s %p\n' 2>/dev/null | head -30
done
section "established outbound connections (not our inbound 22/80/443)"
if have ss; then
ss -Htnp state established 2>/dev/null | awk '{
split($3, l, ":"); lp = l[length(l)];
if (lp == "22" || lp == "80" || lp == "443" || lp == "3000" || lp == "5200" || lp == "5432") next;
print $3, "->", $4, $5
}' | head -40
fi
echo "listening ports:"
ss -Htlnp 2>/dev/null | awk '{print $4, $6}' | head -30 || true
section "docker"
if have docker; then
docker ps --format '{{.Names}} {{.Image}} {{.Status}}' 2>/dev/null || true
echo "images:"
docker images --format '{{.Repository}}:{{.Tag}} {{.ID}} {{.CreatedSince}}' 2>/dev/null | head -30 || true
echo "containers not from this project:"
docker ps -a --format '{{.Names}} {{.Label "com.docker.compose.project"}}' 2>/dev/null | awk '$2 != "jyotisha-production" {print $1}' || true
fi
section "recent logins"
last -n 15 -a 2>/dev/null || true
echo "failed ssh logins (last 24h, count):"
journalctl -u ssh -u sshd --since "24 hours ago" 2>/dev/null | grep -c 'Failed password\|Invalid user' || true
section "done"
echo "read-only audit finished; nothing was changed"
+5
View File
@@ -133,6 +133,11 @@ alert_label() {
memory_high) printf '服务器可用内存不足(数字是已用百分比)' ;;
report_queue_stuck) printf '报告排队太久没开始(数字是等待秒数)' ;;
feedback_new) printf '有新的用户反馈,去 /admin/feedback 看' ;;
cpu_high) printf '服务器 CPU 持续很高(约 10 分钟,数字是使用百分比),可能被挖矿' ;;
container_cpu_high) printf '某个容器 CPU 持续很高(约 10 分钟,数字是占一个核的百分比)' ;;
suspicious_process) printf '有不在白名单里的进程占用大量 CPU(数字是进程号,路径里是进程名)' ;;
miner_process) printf '发现疑似挖矿程序(数字是进程号,路径里是进程名)' ;;
mining_pool_connection) printf '有进程连到常见矿池端口(数字是进程号,路径里是进程名)' ;;
otp_send_failed) printf '验证码邮件发不出去' ;;
model_spend_alert) printf '今天的模型花费超过设定值' ;;
model_fallback_used) printf '默认模型失败,已切到备用模型' ;;
+235
View File
@@ -5,6 +5,11 @@
# - host available memory is low
# - the oldest report job has waited too long to start
# - new user feedback arrived (count only; no feedback text, no account)
# - BUG-2416: host CPU or one container's CPU stays high across two runs
# (about 10 minutes), a high-CPU process that is not on the allowlist, a
# known miner name or stratum URL in a command line, or an established
# connection to a common mining-pool port. Alerts carry the process name and
# pid only; command lines and environment are never sent.
set -euo pipefail
set +x
umask 077
@@ -32,6 +37,14 @@ queue_limit="${JYOTISHA_QUEUE_WAIT_LIMIT:-600}"
memory_limit="${JYOTISHA_MEMORY_PERCENT_LIMIT:-90}"
[[ "$queue_limit" =~ ^[1-9][0-9]{1,5}$ ]] || exit 2
[[ "$memory_limit" =~ ^[1-9][0-9]$ ]] || exit 2
cpu_limit="${JYOTISHA_CPU_PERCENT_LIMIT:-85}"
container_cpu_limit="${JYOTISHA_CONTAINER_CPU_LIMIT:-90}"
sustain_runs="${JYOTISHA_CPU_SUSTAIN_RUNS:-2}"
process_cpu_limit="${JYOTISHA_PROCESS_CPU_LIMIT:-50}"
[[ "$cpu_limit" =~ ^[1-9][0-9]$ ]] || exit 2
[[ "$container_cpu_limit" =~ ^[1-9][0-9]{1,2}$ ]] || exit 2
[[ "$sustain_runs" =~ ^[1-9]$ ]] || exit 2
[[ "$process_cpu_limit" =~ ^[1-9][0-9]{1,2}$ ]] || exit 2
# Tests replace docker and the memory file; production uses sudo -n docker
# because the monitor user is not in the docker group.
@@ -47,11 +60,32 @@ stamp() {
date -u +%Y-%m-%dT%H:%M:%SZ
}
now_epoch() {
if [[ "${JYOTISHA_NOW:-}" =~ ^[0-9]{9,11}$ ]]; then
printf '%s' "$JYOTISHA_NOW"
else
date +%s
fi
}
# Tests replace ps and ss with fixture scripts.
ps_cmd() {
if [ -n "${JYOTISHA_PS:-}" ]; then "$JYOTISHA_PS" "$@"; else ps "$@"; fi
}
ss_cmd() {
if [ -n "${JYOTISHA_SS:-}" ]; then "$JYOTISHA_SS" "$@"; else ss "$@"; fi
}
state_file="$state_dir/ops-check.state"
declare -A restarts=()
memory_open=0
queue_open=0
feedback_seen=""
cpu_prev=""
cpu_hot=0
cpu_open=0
declare -A ccpu_prev=() ccpu_hot=() ccpu_open=() suspects=() suspects_now=()
container_ids=""
read_state() {
local line key value
@@ -70,6 +104,26 @@ read_state() {
value="${line#feedback_seen=}"
[[ "$value" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\.[0-9]+)?Z$ ]] && feedback_seen="$value"
;;
cpu_prev=*)
value="${line#cpu_prev=}"
[[ "$value" =~ ^[0-9]+:[0-9]+$ ]] && cpu_prev="$value"
;;
cpu_hot=[0-9]) cpu_hot="${line#cpu_hot=}" ;;
cpu_open=[01]) cpu_open="${line#cpu_open=}" ;;
ccpu:*=*)
key="${line%%=*}"
key="${key#ccpu:}"
value="${line#*=}"
[[ "$key" =~ ^[0-9a-f]{64}$ ]] || continue
[[ "$value" =~ ^([0-9]+):([0-9]+):([0-9]):([01])$ ]] || continue
ccpu_prev["$key"]="${BASH_REMATCH[1]}:${BASH_REMATCH[2]}"
ccpu_hot["$key"]="${BASH_REMATCH[3]}"
ccpu_open["$key"]="${BASH_REMATCH[4]}"
;;
suspect:*)
key="${line#suspect:}"
[[ "$key" =~ ^[0-9]+/[A-Za-z0-9_.-]+$ ]] && suspects["$key"]=1
;;
esac
done <"$state_file"
}
@@ -79,9 +133,16 @@ write_state() {
tmp="$state_file.tmp.$$"
{
printf 'memory_open=%s\nqueue_open=%s\nfeedback_seen=%s\n' "$memory_open" "$queue_open" "$feedback_seen"
printf 'cpu_prev=%s\ncpu_hot=%s\ncpu_open=%s\n' "$cpu_prev" "$cpu_hot" "$cpu_open"
for key in "${!restarts[@]}"; do
printf 'restart:%s=%s\n' "$key" "${restarts[$key]}"
done
for key in "${!ccpu_prev[@]}"; do
printf 'ccpu:%s=%s:%s:%s\n' "$key" "${ccpu_prev[$key]}" "${ccpu_hot[$key]:-0}" "${ccpu_open[$key]:-0}"
done
for key in "${!suspects[@]}"; do
printf 'suspect:%s\n' "$key"
done
} >"$tmp"
if [ "$(uname -s)" = "Linux" ]; then
chmod 600 "$tmp"
@@ -108,6 +169,7 @@ check_containers() {
service="${service%-[0-9]*}"
[[ "$service" =~ ^[a-z0-9_-]+$ ]] || service="container"
current["$id"]="$count"
container_ids="${container_ids}${id}:${service}"$'\n'
if [ -n "${restarts[$id]:-}" ] && [ "$count" -gt "${restarts[$id]}" ]; then
if [ "$oom" = "true" ]; then
queue_alert "$service" - container_oom "$count"
@@ -187,9 +249,182 @@ check_feedback() {
fi
}
# Host CPU over the interval since the previous run, from /proc/stat. Two
# consecutive hot intervals (about 10 minutes at the 5-minute schedule) alert once.
check_host_cpu() {
local file line total idle prev_total prev_idle dt di used
file="${JYOTISHA_PROC_STAT:-/proc/stat}"
[ -r "$file" ] || return 0
line="$(awk '$1 == "cpu" {t = 0; for (i = 2; i <= 9 && i <= NF; i++) t += $i; print t ":" ($5 + $6); exit}' "$file")"
[[ "$line" =~ ^[0-9]+:[0-9]+$ ]] || return 0
total="${line%%:*}"
idle="${line#*:}"
if [ -n "$cpu_prev" ]; then
prev_total="${cpu_prev%%:*}"
prev_idle="${cpu_prev#*:}"
dt=$((total - prev_total))
di=$((idle - prev_idle))
if [ "$dt" -gt 0 ] && [ "$di" -ge 0 ]; then
used=$(( (dt - di) * 100 / dt ))
if [ "$used" -ge "$cpu_limit" ]; then
cpu_hot=$((cpu_hot < 9 ? cpu_hot + 1 : 9))
if [ "$cpu_hot" -ge "$sustain_runs" ] && [ "$cpu_open" -eq 0 ]; then
queue_alert host - cpu_high "$used"
cpu_open=1
fi
else
cpu_hot=0
if [ "$cpu_open" -eq 1 ]; then
queue_alert host - recovered 0
cpu_open=0
fi
fi
fi
fi
cpu_prev="$total:$idle"
}
# Per-container CPU from the cgroup v2 cpu.stat counter (percent of one core).
check_container_cpu() {
local root now entry id service file usage prev_usage prev_time dt pct
declare -A seen=()
root="${JYOTISHA_CGROUP_ROOT:-/sys/fs/cgroup}"
now="$(now_epoch)"
while IFS= read -r entry; do
[ -n "$entry" ] || continue
id="${entry%%:*}"
service="${entry#*:}"
[[ "$id" =~ ^[0-9a-f]{64}$ ]] || continue
file="$root/system.slice/docker-$id.scope/cpu.stat"
[ -r "$file" ] || continue
usage="$(awk '$1 == "usage_usec" {print $2; exit}' "$file")"
[[ "$usage" =~ ^[0-9]+$ ]] || continue
seen["$id"]=1
if [ -n "${ccpu_prev[$id]:-}" ]; then
prev_usage="${ccpu_prev[$id]%%:*}"
prev_time="${ccpu_prev[$id]#*:}"
dt=$((now - prev_time))
if [ "$dt" -gt 0 ] && [ "$usage" -ge "$prev_usage" ]; then
pct=$(( (usage - prev_usage) / (dt * 10000) ))
if [ "$pct" -ge "$container_cpu_limit" ]; then
ccpu_hot["$id"]=$(( ${ccpu_hot[$id]:-0} < 9 ? ${ccpu_hot[$id]:-0} + 1 : 9 ))
if [ "${ccpu_hot[$id]}" -ge "$sustain_runs" ] && [ "${ccpu_open[$id]:-0}" -eq 0 ]; then
queue_alert "$service" - container_cpu_high "$pct"
ccpu_open["$id"]=1
fi
else
ccpu_hot["$id"]=0
if [ "${ccpu_open[$id]:-0}" -eq 1 ]; then
queue_alert "$service" - recovered 0
ccpu_open["$id"]=0
fi
fi
fi
fi
ccpu_prev["$id"]="$usage:$now"
done <<<"$container_ids"
for id in "${!ccpu_prev[@]}"; do
if [ -z "${seen[$id]:-}" ]; then
unset "ccpu_prev[$id]" "ccpu_hot[$id]" "ccpu_open[$id]"
fi
done
}
# Process names that may legitimately use a lot of CPU on this host.
allowed_process() {
case "$1" in
node|python|python3|python3.*|uvicorn|gunicorn|postgres|postmaster|pg_dump|pg_restore|psql) return 0 ;;
caddy|dockerd|containerd|containerd-shim*|runc|docker|docker-proxy|docker-compose) return 0 ;;
sshd|cron|systemd|systemd-*|journald|rsyslogd|unattended-upgr*|apt|apt-get|dpkg|http|https|gpgv) return 0 ;;
bash|sh|awk|gzip|zstd|xz|tar|sort|ossutil*|kworker*|ksoftirqd*|kswapd*) return 0 ;;
esac
return 1
}
miner_text() {
case "$1" in
*stratum+tcp* | *stratum+ssl* | *stratum2+* | *xmrig* | *kdevtmpfsi* | *kinsing* | *minerd* | *cpuminer* | *nanominer* | *nbminer* | *lolminer* | *t-rex* | *--donate-level*) return 0 ;;
esac
return 1
}
report_suspect() {
local pid="$1" name="$2" code="$3"
[[ "$pid" =~ ^[0-9]+$ ]] || return 0
name="$(printf '%s' "$name" | tr -c 'A-Za-z0-9_.-' '_' | cut -c1-40)"
[ -n "$name" ] || name="unknown"
suspects_now["$pid/$name"]=1
# One alert per process: a miner that keeps running is not re-announced every 5 minutes.
[ -z "${suspects[$pid/$name]:-}" ] || return 0
suspects["$pid/$name"]=1
queue_alert host "/proc/$name" "$code" "$pid"
}
# Keep only processes still seen this run, so the state stays small.
prune_suspects() {
local key
suspects=()
for key in "${!suspects_now[@]}"; do
suspects["$key"]=1
done
}
check_processes() {
local pid pcpu comm args pct
while read -r pid pcpu comm args || [ -n "${pid:-}" ]; do
[[ "${pid:-}" =~ ^[0-9]+$ ]] || continue
if miner_text "$comm $args"; then
report_suspect "$pid" "$comm" miner_process
continue
fi
pct="${pcpu%%.*}"
[[ "$pct" =~ ^[0-9]+$ ]] || continue
if [ "$pct" -ge "$process_cpu_limit" ] && ! allowed_process "$comm"; then
report_suspect "$pid" "$comm" suspicious_process
fi
done < <(ps_cmd -eo pid=,pcpu=,comm=,args= 2>/dev/null || true)
}
# Established outbound connections to common mining-pool ports.
mining_port() {
case "$1" in
3333|4444|5555|6666|7777|8888|9999|14433|14444|45560|45700) return 0 ;;
esac
return 1
}
check_egress() {
local line local_addr local_port peer port proc pid name
while IFS= read -r line; do
[ -n "$line" ] || continue
local_addr="$(awk '{print $3}' <<<"$line")"
local_port="${local_addr##*:}"
# Inbound connections to our own services: the client's port can be anything.
case "$local_port" in
22|80|443|3000|5200|5432) continue ;;
esac
peer="$(awk '{print $4}' <<<"$line")"
port="${peer##*:}"
[[ "$port" =~ ^[0-9]+$ ]] || continue
mining_port "$port" || continue
proc="$(grep -oE 'users:\(\("[^"]+",pid=[0-9]+' <<<"$line" | head -1)"
name="$(sed -E 's/^users:\(\("([^"]+)".*/\1/' <<<"$proc")"
pid="$(sed -E 's/.*pid=([0-9]+)$/\1/' <<<"$proc")"
[[ "$pid" =~ ^[0-9]+$ ]] || pid=0
[ -n "$name" ] || name="unknown"
report_suspect "$pid" "$name" mining_pool_connection
done < <(ss_cmd -Htnp state established 2>/dev/null || true)
}
read_state
check_containers
check_memory
check_host_cpu
check_container_cpu
check_processes
check_egress
prune_suspects
check_report_queue
check_feedback
if [ -n "$alerts" ]; then
+29
View File
@@ -32879,3 +32879,32 @@
- **关联记录**:BUG-2392(王者格局结构满足即成立)、BUG-2412(成立的规则格局进星盘页)、BUG-2226(读者条件句)。
- **未处理**:报告附录的格局表仍用 `CUSTOM_CONDITION_UNLISTED_ZH`(报告窗口负责),这条规则现在有句子,不会再落到那里。
- **修复版本**:1.5。
## BUG-2415 | 发版流程改成分支:next / release/x.y / hotfix/x.y.z / main,由 CI 把关
- **状态**:resolved(代码已提交;需负责人在 Gitea 建 `RELEASE_PUSH_TOKEN`、`next` 分支并加分支保护后启用)
- **现象**:所有窗口都推 `staging`,`staging` 整体发正式。封板测试期间新功能无处可推;版本顺序靠协调窗口记忆,窗口重启后容易乱(2026-11-24~26 多次出现推送互相顶掉门禁、发版前等待)。
- **根因**:只有一条测试线 `staging` 同时承担「集成」「候选版本」「测试环境指针」三种角色,没有冻结分支,也没有机器检查的发版规则。
- **修复**:
- `backend-quality-gate.yml` 的 push 分支加 `next`(只跑检查;publish 仍只认 `refs/heads/staging`)。
- 新增 `freeze-release.yml`(封板:从 `next` 切 `release/x.y`,拒绝已发版本号和已存在分支,改 `APP_VERSION`)、`release-to-staging.yml`(`release/**`、`hotfix/**` 推送:新提交必须带 `BUG-NNNN`,用 `RELEASE_PUSH_TOKEN` 把 `staging` 快进到该头——仅在 `staging` 停在已发版本或热修时允许带租约重置——触发原有 staging 流水线,并把 release 合回 `next`)、`ship-release.yml`(发版:要求测试环境正在跑该 SHA、完整发布检查已通过、版本号一致,`main` 只快进;迁移有变化时才跑恢复点与生产迁移;再跑生产部署(自动打标签);最后 `main` 合回 `next`)。
- `deploy/branch-flow.sh` 放共用的检查与 API 调用;`docs/operations/branch-flow.md` 写日常流程和负责人要点的 Gitea 设置;`AGENTS.md` §1/§2、`deploy/README.md` 同步。
- 用 `RELEASE_PUSH_TOKEN`(个人令牌)推送的原因:CI 自带令牌的推送不会触发后续工作流。
- **验证**:新测试 `frontend/tests/branch-flow-2415.test.ts`(7 条:触发条件、BUG 号检查、只快进、迁移有变才跑、队列不占 production-mutation、版本号格式、文档里的设置);`staging-backend-workflows`、`health-deployment` 中钉 `branches: [staging]` 的三处按原值/新值/原因更新,其余失败与改动前相同(本机缺 yaml / rsync / docker);`test_resolve_release_revision`、`test_quality_gate_fragment_audit_once`、`test_beta_safety_net` 通过;三个新工作流 YAML 可解析。
- **防复发**:发版规则写在工作流里由 CI 执行;`release/*` 无 BUG 号的提交不会部署;生产只从快进后的 `main` 发。
- **关联记录**:BUG-2390/2391(完整检查只跑一次、正式部署加速)、BUG-2407(版本号与自动打标签)。
- **修复版本**:1.6 起生效(1.5 按旧流程发布)。
## BUG-2416 | 生产服务器防入侵、防挖矿:CPU/可疑进程/矿池连接告警,容器去 root 与只读,caddy 固定镜像
- **状态**:resolved(代码与文档;待随下一版部署到 staging 验证容器能正常启动、报告能生成)
- **现象/来源**:负责人问服务器被入侵挖矿有没有防御(Gitea #360)。协调窗口对生产做了一次只读核查:没有挖矿迹象;但 web/api 在容器里以 root 运行、caddy 用浮动的 `caddy:2-alpine`、fail2ban 没开(一天 1078 次 SSH 失败尝试,密码登录已关、root 只能用密钥)、没有 CPU 和可疑进程告警。
- **根因**:上线时只做了网络边界(ufw 只开 22/80/443、5200 不出网),没有做进程层的权限收紧和异常 CPU 监测。
- **修复**:
- `deploy/monitor/ops-check.sh`:主机 CPU 连续两次(约 10 分钟)≥85%、单个容器连续两次 ≥ 一个核的 90%、不在白名单的高 CPU 进程、命令行含挖矿程序名或 stratum、连常见矿池端口的出站连接,都走现有飞书+邮件告警;只发进程名和进程号,同一进程只报一次;入站 22/80/443 等不算。`notify-feishu.sh` 加对应中文标签。
- `deploy/docker-compose.server.yml`:api 以 uid 10001、web 以 uid 1000 运行;只读镜像、`cap_drop: ALL`、`no-new-privileges`、`pids_limit`、内存上限(api 2g、web 1g);可写处只留 api 的 scratch 卷和 /tmp、web 的 /tmp 和 `.next/cache`(内存盘);新增一次性 `api-scratch-owner` 把旧卷文件改给 10001(无网络、只有改属主权限)。caddy 固定 digest、只留 NET_BIND_SERVICE。postgres 不动。
- 新增只读核查脚本 `deploy/monitor/host-audit.sh`;README 写明可选的 fail2ban sshd 安装步骤(不自动执行)。
- **验证**:`tests/test_monitor_alerts_2348.py` 新增 CPU/挖矿/矿池连接与 compose 加固两条测试,并把主机 ps/ss//proc/stat/cgroup 全部换成测试夹具(不受跑测试的机器影响);`test_beta_safety_net`、`test_railway_deployment` 通过;`bash -n` 通过。本机没有 docker,容器实际启动要在 staging 部署时验证。
- **风险与回退**:只读和去 root 可能让某个没找全的写路径失败(已逐个查过 api 与 web 的运行时写入:scratch/local、/tmp、Next 图片缓存;PyJHora 设置文件随包自带不写入;Python 字节码关闭写入)。回退只需把 compose 文件改回上一版再部署,镜像不变。
- **关联记录**:BUG-2348(告警通道)、BUG-2352(web 停止宽限)、#360。
- **修复版本**:下一版(1.6)。
+45
View File
@@ -0,0 +1,45 @@
# 分支发版流程(BUG-2415,2026-11-26 负责人批准)
1.5 之后不再「所有窗口都推 staging、staging 整体发正式」。规则交给 CI,负责人只做两个决定:**封板**和**发版**。
## 分支
| 分支 | 放什么 | 谁推 | 推了以后 |
|---|---|---|---|
| `next` | 下一个版本的新功能和修复 | 各窗口随时推 | 只跑检查(backend-quality-gate 的 validate),不部署 |
| `release/x.y` | 封板的候选版本 | 「封板」工作流创建;之后只推你测出来的问题的修复,提交信息必须带 `BUG-NNNN` | 「Release branch to staging」把 `staging` 移到这个头 → 原有 staging 流水线(检查→迁移→部署→完整发布检查);修复自动合回 `next` |
| `hotfix/x.y.z` | 线上急修,从 `main` 拉 | 需要时手动建;提交带 `BUG-NNNN` | 同上,部署到测试环境(会暂时顶掉正在测的 release) |
| `main` | 正式环境当前版本 | 只有「发版」工作流快进 | 生产恢复点/迁移(有迁移时)→ 生产部署 → 自动打 `v<版本>` 标签 → 合回 `next` |
| `staging` | 测试环境指针(过渡期保留) | 只由 CI 移动;旧做法直接推 staging 仍可用,但已弃用 | 原有 staging 流水线 |
## 日常怎么做
1. 窗口开发:功能分支 → 本地检查 → 推 `next`(不再推 `staging`)。
2. 负责人说「封板 1.6」:Gitea → Actions →「封板 Freeze release」→ Run,`version` 填 `1.6`。它从 `next` 切出 `release/1.6`、把设置页版本改成 1.6,并部署到测试环境。
3. 测试中发现问题:修复提交(带 `BUG-NNNN`)推到 `release/1.6`;会重新部署测试环境,并自动合回 `next`。新功能照常推 `next`,不影响测试环境。
4. 负责人说「发 1.6」:Gitea → Actions →「发版 Ship release」→ Run,`version` 填 `1.6`。前提:测试环境正在跑 `release/1.6` 的最新提交,且这个提交的完整发布检查已经通过(每次测试环境部署后自动跑)。
5. 线上急修:从 `main` 建 `hotfix/1.6.1`,推修复 → 测试环境验证 → 「发版」填 `1.6.1`。若同时有未发的 `release/x.y`,发完后把 `main` 合进那个 release 分支。
## CI 自动把关
- 正式环境只从 `main` 部署;`main` 只能被「发版」快进到 `release/*` 或 `hotfix/*` 的头(必须是快进,不合并、不改写)。
- 发版前检查:版本号文件(`frontend/src/lib/app-version.ts`)= 输入的版本;`v<版本>` 标签不存在;测试环境正在跑这个 SHA;这个 SHA 的完整发布检查通过。
- `release/*`、`hotfix/*` 上每个新提交都要带 `BUG-NNNN`(合并提交和封板的版本号提交除外),否则不部署。
- 已有的生产保护全部保留:生产只用 staging 检查产出的同 SHA 镜像,`main` 与测试环境同一提交,迁移前必须有验证过的恢复点。
## 负责人需要在 Gitea 里点的设置(一次性)
1. **建一个发版用的令牌**:用有仓库写权限的账号(建议单独建一个 `release-bot` 账号并给仓库「写」权限),设置 → 应用 → 生成新令牌,勾选 `write:repository`。复制令牌。
2. **存成仓库密钥**:仓库 → 设置 → Actions → 密钥 → 添加,名字 `RELEASE_PUSH_TOKEN`,值是上一步的令牌。(用 CI 自带令牌推送不会触发后续流程,所以需要这个。)
3. **建 `next` 分支**:从当前 `main`(= v1.5)建 `next`(仓库 → 分支 → 新建分支,或让协调窗口推一次)。
4. **保护 `main`**:仓库 → 设置 → 分支 → 添加保护规则,分支名 `main`:
- 启用推送:只允许白名单用户 → 只勾 `release-bot`(第 1 步的账号)。
- 禁止强制推送。
- 不要求审批(发版由「发版」工作流把关)。
5. **保护 `release/*` 和 `hotfix/*`**:再加两条规则,分支名分别填 `release/*`、`hotfix/*`:禁止强制推送;允许推送(各窗口要推修复)。
6. **保护 `staging`**(可选,过渡期结束后):只允许 `release-bot` 推送,彻底禁止各窗口直推。
## 过渡
- 1.5 已按旧流程发布(main = staging = 87677ca96,标签 v1.5)。
- `staging` 分支直推仍然能部署(兼容旧窗口),但从现在起各窗口应推 `next`。第 6 步打开后直推会被拒绝。
+84
View File
@@ -0,0 +1,84 @@
import assert from "node:assert/strict";
import { spawnSync } from "node:child_process";
import { readFileSync } from "node:fs";
import { test } from "node:test";
import { fileURLToPath } from "node:url";
// BUG-2415 (owner 2026-11-26): next / release/x.y / hotfix/x.y.z / main, CI-enforced.
const root = new URL("../../", import.meta.url);
const read = (path: string) => readFileSync(new URL(path, root), "utf8");
const flowScript = fileURLToPath(new URL("deploy/branch-flow.sh", root));
const flow = (args: string[], input = "") =>
spawnSync("bash", [flowScript, ...args], { input, encoding: "utf8" });
test("next only runs the checks; only staging publishes and deploys", () => {
const gate = read(".gitea/workflows/backend-quality-gate.yml");
assert.match(gate, /push:\n(?:\s+#[^\n]*\n)*\s+branches: \[staging, next\]/);
assert.match(gate, /if: gitea\.event_name == 'push' && gitea\.ref == 'refs\/heads\/staging'/);
});
test("封板 cuts release/x.y from next, refuses a shipped version or an existing branch, and bumps the app version", () => {
const wf = read(".gitea/workflows/freeze-release.yml");
assert.match(wf, /^on:\n\s+workflow_dispatch:/m);
assert.doesNotMatch(wf, /^\s+push:/m);
assert.match(wf, /tag-sha "v\$VERSION"/);
assert.match(wf, /ref-sha "\$branch"/);
assert.match(wf, /ref-sha next/);
assert.match(wf, /APP_VERSION = \\"\$VERSION\\";/);
assert.match(wf, /\[release-bump\]/);
assert.match(wf, /RELEASE_PUSH_TOKEN: \$\{\{ secrets\.RELEASE_PUSH_TOKEN \}\}/);
assert.match(wf, /git push origin "HEAD:refs\/heads\/\$branch"/);
});
test("a release or hotfix push needs BUG numbers, moves staging only forward (or from the shipped head / for a hotfix) and merges back into next", () => {
const wf = read(".gitea/workflows/release-to-staging.yml");
assert.match(wf, /branches:\n\s+- 'release\/\*\*'\n\s+- 'hotfix\/\*\*'/);
assert.match(wf, /commit-messages "\$base" "\$HEAD_SHA" \| bash "\$flow" bug-ids-ok/);
assert.match(wf, /merge-base --is-ancestor "\$staging_sha" "\$HEAD_SHA"/);
assert.match(wf, /--force-with-lease="refs\/heads\/staging:\$staging_sha"/);
assert.match(wf, /holds another unshipped release/);
assert.match(wf, /Merge \$branch into next/);
assert.doesNotMatch(wf, /git push --force(?!-with-lease)/);
});
test("发版 ships only a tested head: staging live on it, release checks passed, version matches, main fast-forwards", () => {
const wf = read(".gitea/workflows/ship-release.yml");
assert.match(wf, /^on:\n\s+workflow_dispatch:/m);
assert.match(wf, /\[ "\$staging_sha" = "\$sha" \]/);
assert.match(wf, /\.deployment\.gitCommit/);
assert.match(wf, /release-gate-passed "\$sha"/);
assert.match(wf, /APP_VERSION \$version_now, not \$VERSION/);
assert.match(wf, /merge-base --is-ancestor "\$main_before" "\$sha"/);
assert.match(wf, /git push origin "\$sha:refs\/heads\/main"/);
assert.doesNotMatch(wf, /--force/);
// Recovery and migration only when migrations changed; the deploy always runs after them.
const recovery = wf.indexOf("create-production-recovery.yml");
const migrate = wf.indexOf("migrate-production-database.yml");
const deploy = wf.indexOf("deploy-production.yml");
assert.ok(recovery > 0 && recovery < migrate && migrate < deploy);
assert.match(wf, /if bash "\$flow" migrations-changed "\$main_before" "\$sha"; then/);
// Its own queue: the production workflows it starts hold production-mutation themselves.
assert.match(wf, /group: release-flow/);
assert.doesNotMatch(wf, /group: production-mutation/);
assert.match(wf, /Merge v\$VERSION \(main\) into next/);
});
test("branch-flow.sh accepts BUG-numbered, merge and release-bump commits and names the rest", () => {
const ok = flow(["bug-ids-ok"], "fix(chart): a (BUG-2415)\0Merge branch 'x' into next\0chore(release): freeze 1.6 [release-bump]\0");
assert.equal(ok.status, 0, ok.stderr);
const bad = flow(["bug-ids-ok"], "fix(chart): a (BUG-2415)\0fix: no number here\0");
assert.equal(bad.status, 1);
assert.match(bad.stderr, /missing BUG number: fix: no number here/);
});
test("branch-flow.sh only takes x.y or x.y.z versions", () => {
for (const good of ["1.6", "1.6.1", "2.0"]) assert.equal(flow(["validate-version", good]).status, 0, good);
for (const bad of ["v1.6", "1", "1.6-rc", "../x", ""]) assert.notEqual(flow(["validate-version", bad]).status, 0, bad);
});
test("the owner's one-time Gitea settings are documented", () => {
const doc = read("docs/operations/branch-flow.md");
for (const item of ["RELEASE_PUSH_TOKEN", "write:repository", "保护 `main`", "release/*", "hotfix/*", "禁止强制推送"]) {
assert.ok(doc.includes(item), item);
}
});
+2 -1
View File
@@ -193,7 +193,8 @@ test("staging deploy consumes only the isolated staging environment and tested r
"utf8",
);
assert.match(qualityGate, /push:\s*\n\s*branches: \[staging\]/);
// 原值:/push:\s*\n\s*branches: \[staging\]/ 新值:[staging, next] 原因:BUG-2415 next 只跑检查,部署仍只从 staging
assert.match(qualityGate, /push:\s*\n(?:\s*#[^\n]*\n)*\s*branches: \[staging, next\]/);
// 原值:/actions: read/ 新值:/actions: write/ 原因:BUG-2390 跟进,deploy-staging 要排队完整发布检查(dispatch 需要写权限)
assert.match(workflow, /actions: write/);
assert.match(workflow, /deploy_sha:/);
@@ -214,7 +214,9 @@ test("Gitea quality gate validates before publishing an immutable ACR manifest",
const workflow = read(giteaQualityWorkflow);
assert.match(workflow, /pull_request:\n\s+paths:/);
assert.match(workflow, /push:\n\s+branches: \[staging\]/);
// 原值:/push:\n\s+branches: \[staging\]/ 新值:push 分支是 [staging, next],publish 仍只认 staging 原因:BUG-2415 分支发版流程,next 只跑检查不部署
assert.match(workflow, /push:\n(?:\s+#[^\n]*\n)*\s+branches: \[staging, next\]/);
assert.match(workflow, /if: gitea\.event_name == 'push' && gitea\.ref == 'refs\/heads\/staging'/);
assert.match(workflow, /workflow_dispatch:/);
// 原值 → 新值见各行;原因:CI 提速,validate 拆成 validate-python 与 validate-frontend 两个并行 job(各自 checkout),venv 改为 deploy/ci-python-venv.sh 的主机缓存,npm 下载缓存持久化。
// 原值 2 个 runs-on;新值 3 个(两个 validate job + publish)。
@@ -1522,7 +1524,8 @@ function gatedGlobs(): string[] {
}
function triggerPaths(workflow: string, trigger: "pull_request" | "push"): string[] {
const block = workflow.match(new RegExp(`\\n ${trigger}:\\n(?: branches: \\[staging\\]\\n)? paths:\\n((?: - '[^'\\n]+'\\n)+)`));
// 原值:只认 `branches: [staging]` 新值:也认 `branches: [staging, next]` 原因:BUG-2415 next 只跑检查
const block = workflow.match(new RegExp(`\\n ${trigger}:\\n(?: branches: \\[staging(?:, next)?\\]\\n)? paths:\\n((?: - '[^'\\n]+'\\n)+)`));
assert.ok(block, `${trigger} trigger has no paths list`);
return [...block[1].matchAll(/ - '([^'\n]+)'\n/g)].map((match) => match[1]);
}
@@ -1560,7 +1563,8 @@ test("gated paths are one list shared by both quality-gate triggers", () => {
assert.ok(globs.length > 0, "deploy/gated-paths.txt must not be empty");
assert.deepEqual(triggerPaths(workflow, "pull_request"), globs);
assert.deepEqual(triggerPaths(workflow, "push"), globs);
assert.match(workflow, /push:\n\s+branches: \[staging\]\n\s+paths:\n/);
// 原值:/push:\n\s+branches: \[staging\]\n\s+paths:\n/ 新值:[staging, next] 原因:BUG-2415
assert.match(workflow, /push:\n(?:\s+#[^\n]*\n)*\s+branches: \[staging, next\]\n\s+paths:\n/);
assert.deepEqual(new Set(globs).size, globs.length, "gated globs must be unique");
});
+130 -1
View File
@@ -227,19 +227,41 @@ esac
"""
FAKE_PS = r"""#!/usr/bin/env bash
printf '%s\n' "${FAKE_PS_OUTPUT:-}"
"""
FAKE_SS = r"""#!/usr/bin/env bash
printf '%s\n' "${FAKE_SS_OUTPUT:-}"
"""
def run_ops(tmp_path: Path, state: Path, **fake: str) -> subprocess.CompletedProcess[str]:
docker = tmp_path / "fake-docker"
if not docker.exists():
write_text(docker, FAKE_DOCKER)
os.chmod(docker, 0o755)
# BUG-2416: the host process, socket, CPU and cgroup reads are fixtures too, so
# the real machine running the tests can never add an alert.
for name, body in (("fake-ps", FAKE_PS), ("fake-ss", FAKE_SS)):
path = tmp_path / name
if not path.exists():
write_text(path, body)
os.chmod(path, 0o755)
meminfo = tmp_path / "meminfo"
available = fake.pop("available_kb", "3000000")
write_text(meminfo, f"MemTotal: 4000000 kB\nMemAvailable: {available} kB\n")
proc_stat = tmp_path / "proc-stat"
write_text(proc_stat, fake.pop("proc_stat", "cpu 100 0 100 800 0 0 0 0 0 0\n"))
env = {
"JYOTISHA_MONITOR_STATE_DIR": bash_path(state),
"JYOTISHA_MONITOR_ENV": bash_path(tmp_path / "missing.env"),
"JYOTISHA_DOCKER": bash_path(docker),
"JYOTISHA_MEMINFO": bash_path(meminfo),
"JYOTISHA_PS": bash_path(tmp_path / "fake-ps"),
"JYOTISHA_SS": bash_path(tmp_path / "fake-ss"),
"JYOTISHA_PROC_STAT": bash_path(proc_stat),
"JYOTISHA_CGROUP_ROOT": bash_path(tmp_path / "cgroup"),
**{key.upper(): value for key, value in fake.items()},
}
return run_bash(OPS_SCRIPT, env)
@@ -352,6 +374,113 @@ def test_off_host_probe_workflow_runs_every_five_minutes_from_main() -> None:
def test_monitor_scripts_pass_bash_n() -> None:
for script in (OPS_SCRIPT, INSTALL_SCRIPT, MONITOR / "notify-feishu.sh"):
for script in (OPS_SCRIPT, INSTALL_SCRIPT, MONITOR / "notify-feishu.sh", MONITOR / "host-audit.sh"):
completed = subprocess.run([BASH, "-n", str(script)], capture_output=True, text=True)
assert completed.returncode == 0, completed.stderr
def test_ops_check_cpu_miners_and_pool_connections_2416(tmp_path: Path) -> None:
"""BUG-2416: sustained host/container CPU, miner names, unknown hot processes and pool ports."""
state = tmp_path / "state"
api = "c" * 64
base = {
"fake_ids": api[:12],
"fake_inspect": f"{api} /jyotisha-production-api-1 0 false",
}
cpu_stat = tmp_path / "cgroup" / "system.slice" / f"docker-{api}.scope" / "cpu.stat"
cpu_stat.parent.mkdir(parents=True)
def run(stat_total: int, stat_idle: int, usage_usec: int, now: int, **extra: str):
write_text(cpu_stat, f"usage_usec {usage_usec}\nuser_usec 0\n")
busy = stat_total - stat_idle
return run_ops(
tmp_path, state, **base, **extra,
proc_stat=f"cpu {busy} 0 0 {stat_idle} 0 0 0 0 0 0\n",
jyotisha_now=str(now),
)
t0 = 1_800_000_000
assert run(1000, 900, 0, t0).returncode == 0 # baselines only
assert alert_lines(state) == []
# One hot interval (95 % host, 100 % of a core in the container): not yet.
assert run(2000, 950, 300_000_000, t0 + 300).returncode == 0
assert [line for line in alert_lines(state) if "cpu_high" in line] == []
# Second hot interval in a row: one alert each, then no repeats.
assert run(3000, 1000, 600_000_000, t0 + 600).returncode == 0
lines = alert_lines(state)
assert any("service=host" in line and "errorCode=cpu_high" in line for line in lines)
assert any("service=api" in line and "errorCode=container_cpu_high" in line and "count=100" in line for line in lines)
before = len(alert_lines(state))
assert run(4000, 1050, 900_000_000, t0 + 900).returncode == 0
assert len(alert_lines(state)) == before
# Quiet interval: both recover.
assert run(5000, 1950, 901_000_000, t0 + 1200).returncode == 0
assert sum("errorCode=recovered" in line for line in alert_lines(state)[before:]) == 2
# Miner by name, an unknown hot process, a pool connection; allowlisted node stays quiet.
ps_out = "\n".join([
" 101 99.0 node node server.js",
" 202 80.0 kdevtmpfsi /tmp/kdevtmpfsi",
" 303 75.0 sysupdate /var/tmp/.x/sysupdate -o pool.example:443",
" 404 1.0 worker ./worker --url stratum+tcp://pool.example:3333 --user SECRETWALLET",
])
ss_out = "\n".join([
"0 0 10.0.0.5:51234 203.0.113.9:4444 users:((\"sysupdate\",pid=303,fd=7))",
"0 0 10.0.0.5:443 198.51.100.7:45700 users:((\"docker-proxy\",pid=55,fd=9))",
])
before = len(alert_lines(state))
assert run(6000, 2900, 902_000_000, t0 + 1500, fake_ps_output=ps_out, fake_ss_output=ss_out).returncode == 0
new = alert_lines(state)[before:]
joined = "\n".join(new)
assert "route=/proc/kdevtmpfsi errorCode=miner_process count=202" in joined
assert "route=/proc/worker errorCode=miner_process count=404" in joined
assert "route=/proc/sysupdate errorCode=suspicious_process count=303" in joined
assert "route=/proc/sysupdate errorCode=mining_pool_connection" not in joined # same pid already reported
assert "/proc/node" not in joined and "docker-proxy" not in joined # allowlisted / inbound
assert "SECRETWALLET" not in joined and "stratum" not in joined and "pool.example" not in joined
# Still running next time: not announced again.
before = len(alert_lines(state))
assert run(7000, 3800, 903_000_000, t0 + 1800, fake_ps_output=ps_out, fake_ss_output=ss_out).returncode == 0
assert len(alert_lines(state)) == before
# A new pool connection from a fresh pid is reported.
ss_new = "0 0 10.0.0.5:51300 203.0.113.9:14444 users:((\"xm\",pid=909,fd=3))"
assert run(8000, 4700, 904_000_000, t0 + 2100, fake_ss_output=ss_new).returncode == 0
assert "route=/proc/xm errorCode=mining_pool_connection count=909" in alert_lines(state)[-1]
def test_host_audit_script_is_read_only_and_masks_secrets_2416() -> None:
script = (MONITOR / "host-audit.sh").read_text(encoding="utf-8")
for forbidden in ("rm -", "systemctl stop", "systemctl disable", "apt-get install", "kill ", "chmod ", "chown ", "sed -i", "> /etc", "useradd", "passwd"):
assert forbidden not in script, forbidden
assert "docker inspect" not in script or "Config.Env" not in script # never prints container environments
for section in ("unattended-upgrades", "fail2ban", "PermitRootLogin", "PasswordAuthentication", "/tmp", "/dev/shm", "crontab", "ss -", "last"):
assert section in script, section
def test_server_compose_hardening_2416() -> None:
"""BUG-2416: api/web unprivileged + read-only with only the writable paths they need; caddy pinned."""
import yaml # noqa: PLC0415
compose = yaml.safe_load((ROOT / "deploy" / "docker-compose.server.yml").read_text(encoding="utf-8"))
services = compose["services"]
api, web, caddy, owner = services["api"], services["web"], services["caddy"], services["api-scratch-owner"]
for service in (api, web):
assert service["read_only"] is True
assert service["cap_drop"] == ["ALL"] and "cap_add" not in service
assert "no-new-privileges:true" in service["security_opt"]
assert service["pids_limit"] > 0 and service["mem_limit"]
assert service["user"] not in ("0", "0:0", "root")
assert api["user"] == "10001:10001"
assert any(entry.startswith("/tmp:") for entry in api["tmpfs"])
assert "api_scratch:/app/scratch/local" in api["volumes"]
assert api["depends_on"]["api-scratch-owner"]["condition"] == "service_completed_successfully"
assert api["environment"]["HOME"] == "/tmp"
assert web["user"] == "1000:1000"
assert any(entry.startswith("/tmp:") for entry in web["tmpfs"])
assert any(entry.startswith("/app/frontend/.next/cache:") and "uid=1000" in entry for entry in web["tmpfs"])
# The volume handover runs as root but only with file-owner capabilities and no network.
assert owner["network_mode"] == "none" and owner["restart"] == "no"
assert set(owner["cap_add"]) <= {"CHOWN", "FOWNER", "DAC_OVERRIDE", "DAC_READ_SEARCH"}
assert "10001:10001" in " ".join(owner["entrypoint"])
assert caddy["image"].startswith("caddy:2-alpine@sha256:") and len(caddy["image"].split("@sha256:")[1]) == 64
assert caddy["cap_add"] == ["NET_BIND_SERVICE"]