diff --git a/docs/CANDIDATE_RELEASE_RUNBOOK.md b/docs/CANDIDATE_RELEASE_RUNBOOK.md index 88be283..fe81c78 100644 --- a/docs/CANDIDATE_RELEASE_RUNBOOK.md +++ b/docs/CANDIDATE_RELEASE_RUNBOOK.md @@ -34,11 +34,11 @@ - 版本管理机使用 Python 3.11 及以上、Docker Compose、HiFox CLI 和已有 Gitea 凭据。候选执行器通过 `candidate_worker.py <仓库工作树> <访问文件>` 绑定 `127.0.0.1:38984`,仓库工作树允许读取 `origin/main`。执行器通过现有 Gitea 凭据读取作业与日志。运行账户需能以 `weknora-test` 执行只读版本检查。 - 为候选执行器单独配置 `kg-candidate` Runner。作业使用同机回环网络,通过仓库 Secrets 的 `KG_CANDIDATE_ACCESS` 访问执行器。访问文件由执行器用户持有,内容为独立 64 位十六进制随机凭据。候选作业使用的容器须无宿主 Docker socket 和生产密钥挂载。 -- 业务验收使用 `~/.config/knowledge-governance/{qa.json,qa.pgpass,rds-ca.pem}`。复用 `qa_env.py` 的专用 `kg_qa_` RDS 库和角色校验。验收使用专用账号与测试数据。需要验证外部系统的用例须先准备各自的隔离资源。 +- 业务验收使用 `~/.config/knowledge-governance/{qa.json,qa.pgpass,rds-ca.pem}`。复用 `qa_env.py` 的专用 `kg_qa_` RDS 库和角色校验。`qa.pgpass` 可包含同一端点的应用库和集成测试库条目,候选只读取 `qa.json` 指定的库和角色。验收使用专用账号与测试数据。需要验证外部系统的用例须先准备各自的隔离资源。 - 候选执行器采用单验收槽。新批次启动前由运维确认前一批验收结束,按上一批 `ready.json` 中的容器身份停止其 Compose 项目,归档原有配置和回执后释放槽位。保留已验收的归档及审批记录。 ## 演练和当前环境 `prepare-candidate.yml` 的 `verify` 模式校验 Gitea 范围与 CI。可在评审分支验证。`prepare` 模式只接受 `main` 的调度。`candidate_release.py build` 和 `candidate_runtime.py ` 可在隔离开发机演练打包及冒烟。后者使用临时 Docker 数据库,退出后停止演练容器。 -主站当前运行的提交必须在候选的 `main` 主干历史内。若现有主站来自分叉的现场分支,先评审并同步运行基线,再以新提交打包。现有临时候选所用的 RDS 库需要先核验身份,主站数据库不用于候选业务验收。 +候选提交必须位于 `main` 的第一父链,并包含主站实际运行的提交。若现场版本从独立分支发布,先通过保留提交历史的合并将现场基线纳入 `main`。现场提交本身可以位于第二父链。候选计划须覆盖 `git rev-list --first-parent <现场 SHA>..<候选 SHA>` 的每一项,包括基线合并提交和已确认随批发布的工程提交。主站数据库仅用于正式应用,业务候选使用专用 QA 库。 diff --git a/scripts/candidate_release.py b/scripts/candidate_release.py index 3c3afb0..4865af4 100644 --- a/scripts/candidate_release.py +++ b/scripts/candidate_release.py @@ -86,18 +86,23 @@ def check_qa(plan, receipt, reports, authors): f'{task}: required QA cases have not passed') -def git(*args, cwd=None): +def git(*args, cwd=None, allowed=(0,)): env = dict(os.environ, GIT_TERMINAL_PROMPT='0') - return cd.run(['git', *args], 'read candidate source', cwd=cwd, env=env, timeout=120).decode().strip() + return cd.run(['git', *args], 'read candidate source', cwd=cwd, env=env, allowed=allowed, + timeout=120).decode().strip() def verify_source(plan, repo): + check_plan(plan) main_line = git('rev-list', '--first-parent', 'origin/main', cwd=repo).splitlines() sha, base = plan['sha'], plan['base'] - cd.require(sha in main_line and base in main_line and main_line.index(sha) < main_line.index(base), - 'candidate and baseline must be ordered commits on main first-parent history') - check_scope(plan, lambda n: read_forge(API + f'/pulls/{n}'), - main_line[main_line.index(sha):main_line.index(base)]) + cd.require(sha in main_line, 'candidate must be on main first-parent history') + cd.require(git('merge-base', sha, base, cwd=repo, allowed=(0, 1)) == base, + 'running baseline must be an ancestor of the candidate') + # A previously deployed branch may enter main as a second parent. Its reachable + # commits are already represented by the baseline, but the integration itself is in scope. + added = git('rev-list', '--first-parent', f'{base}..{sha}', cwd=repo).splitlines() + check_scope(plan, lambda n: read_forge(API + f'/pulls/{n}'), added) contexts = {line.split('#', 1)[0].strip() for line in CONTEXTS.read_text().splitlines()} - {''} cd.verify_contexts(read_forge(API + f'/commits/{sha}/status'), contexts) diff --git a/scripts/candidate_runtime.py b/scripts/candidate_runtime.py index 2fc4787..34e2c9c 100644 --- a/scripts/candidate_runtime.py +++ b/scripts/candidate_runtime.py @@ -35,10 +35,14 @@ def qa_database(path): passfile, cert = [path.parent / name for name in ('qa.pgpass', 'rds-ca.pem')] qa_env.private_file(passfile) qa_env.private_file(cert) - expected = f"{db['host']}:{db['port']}:{db['database']}:{db['user']}:" + endpoint = f"{db['host']}:{db['port']}:" + expected = f"{endpoint}{db['database']}:{db['user']}:" entries = [line for line in passfile.read_text().splitlines() if line and not line.startswith('#')] - cd.require(len(entries) == 1 and entries[0].startswith(expected), 'pgpass must authorize exactly the dedicated QA database') - password = re.sub(r'\\(.)', r'\1', entries[0][len(expected):]) + qa_entry = re.compile(re.escape(endpoint) + r'kg_qa_[a-z0-9_]{1,56}:kg_qa_[a-z0-9_]{1,56}:(?:[^:\\]|\\.)+') + cd.require(all(qa_entry.fullmatch(line) for line in entries), 'pgpass must contain only exact QA entries at the configured endpoint') + matching = [line for line in entries if line.startswith(expected)] + cd.require(len(matching) == 1, 'pgpass must contain exactly one entry for the configured QA database and role') + password = re.sub(r'\\(.)', r'\1', matching[0][len(expected):]) cd.require(bool(password), 'dedicated QA database password missing') url = (f"postgresql://{db['user']}:{quote(password, safe='')}@{db['host']}:{db['port']}/{db['database']}" '?sslmode=verify-full&sslrootcert=/run/qa/rds-ca.pem') diff --git a/scripts/test_candidate_release.py b/scripts/test_candidate_release.py index 8134603..342daee 100644 --- a/scripts/test_candidate_release.py +++ b/scripts/test_candidate_release.py @@ -1,7 +1,12 @@ +from pathlib import Path +import subprocess +import tempfile import unittest from types import SimpleNamespace +from unittest.mock import patch import candidate_release as candidate +import candidate_runtime as runtime import production_cd as cd BASE, A, B, OTHER = [c * 40 for c in 'abcd'] @@ -28,6 +33,61 @@ class CandidateReleaseTest(unittest.TestCase): with self.assertRaisesRegex(cd.CDError, 'merged into main'): candidate.check_scope(self.plan, self.prs.__getitem__, [A, B]) + def test_merged_runtime_baseline_requires_full_main_scope(self): + with tempfile.TemporaryDirectory() as tmp: + repo = Path(tmp) + + def git(*args): + return subprocess.check_output(['git', *args], cwd=repo, text=True).strip() + + git('init', '-q') + git('config', 'user.name', 'Test') + git('config', 'user.email', 'test@example.invalid') + tree = git('hash-object', '-w', '-t', 'tree', '/dev/null') + + def commit(message, *parents): + return git('commit-tree', tree, '-m', message, *(part for p in parents for part in ('-p', p))) + + root = commit('root') + live = commit('running baseline', root) + control = commit('control plane', root) + integration = commit('bring the running version into main', control, live) + landed = commit('land business PR', integration) + git('update-ref', 'refs/remotes/origin/main', landed) + plan = dict(self.plan, base=live, sha=landed, items=[{'task': QA1, 'pr': 20}], + extra=[control, integration]) + pr = dict(self.prs[20], merge_commit_sha=landed) + with patch.object(candidate, 'read_forge', return_value=pr), patch.object(cd, 'verify_contexts'): + candidate.verify_source(plan, repo) + with self.assertRaisesRegex(cd.CDError, 'outside the release scope'): + candidate.verify_source(dict(plan, extra=[integration]), repo) + unrelated = commit('unmerged branch', root) + with self.assertRaisesRegex(cd.CDError, 'baseline must be an ancestor'): + candidate.verify_source(dict(plan, base=unrelated), repo) + with self.assertRaisesRegex(cd.CDError, 'candidate must be on main'): + candidate.verify_source(dict(plan, base=root, sha=live), repo) + + def test_candidate_selects_only_the_configured_qa_password(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + config = root / 'qa.json' + pgpass = root / 'qa.pgpass' + cert = root / 'rds-ca.pem' + for path in (config, pgpass, cert): + path.touch(mode=0o600) + config.write_text('{"host":"kg-qa-rds.test","port":15483,"database":"kg_qa_app","user":"kg_qa_app"}') + application = 'kg-qa-rds.test:15483:kg_qa_app:kg_qa_app:app\\:example' + integration = 'kg-qa-rds.test:15483:kg_qa_it:kg_qa_it:it-example' + pgpass.write_text(f'{integration}\n{application}\n') + url, ca = runtime.qa_database(config) + self.assertEqual(ca, cert) + self.assertIn('app%3Aexample@kg-qa-rds.test:15483/kg_qa_app', url) + for rows in ((integration,), (application, application), (application, '*:15483:*:*:example'), + (application, 'kg-qa-rds.test:15483:governance:governance:example')): + pgpass.write_text('\n'.join(rows)) + with self.subTest(rows=rows), self.assertRaises(cd.CDError): + runtime.qa_database(config) + def test_require_all_qa_reports_and_shared_regression(self): sources = {QA1: (self.report, self.result()), QA2: (self.report, self.result())} with self.assertRaisesRegex(cd.CDError, 'every requirement and the release task'):