fix: restrict explicit force release to verified user document clients
This commit is contained in:
1 parent
e4266ae88c
commit
e53c5d0e92
18 files changed
+2090
-1623
No files matched your search
@@ -1,15 +1,17 @@
|
||||
# CBB 中心库上传后校验工具
|
||||
|
||||
当前临时分支的备份策略(2026-11-03):应用不再自动备份中心库或 CBB 工程。新增、替换、移除、校验、ICDB 维护和恢复在执行前提示手动备份;请自行保留可用副本。导入暂存、恢复用隔离验证库和轻量操作证据仍会生成,Mentor 原生 Repair 自身的备份行为保持不变。详见[自动备份检查与调整](docs/releases/2026-11-03-manual-backup.md)。此条优先于下方历史版本的备份说明。
|
||||
|
||||
当前补丁:**[v0.2.3-beta.1](docs/releases/v0.2.3-beta.1.md)(Beta 预发布,待现场验收)**,替代 0.2.2-beta.1。数据库所有权或关闭状态不确定时停止批次、保留现场;不自动移走地址文件、接管带锁设计或强杀 PCB 进程树。新增全库 ICDB 维护、同名 CBB 完整备份恢复弹窗及严格的原生复核流程。详见 [v0.2.3-beta.1 发布说明](docs/releases/v0.2.3-beta.1.md)。下方日期记录描述历史版本,以本补丁说明为准。
|
||||
当前临时分支的备份策略(2026-11-03):应用不再自动备份中心库或 CBB 工程。新增、替换、移除、校验、ICDB 维护和恢复在执行前提示手动备份;请自行保留可用副本。导入暂存、恢复用隔离验证库和轻量操作证据仍会生成,Mentor 原生 Repair 自身的备份行为保持不变。详见[自动备份检查与调整](docs/releases/2026-11-03-manual-backup.md)。此条优先于下方历史版本的备份说明。
|
||||
|
||||
当前开发版本:**[v0.2.4-beta.1](docs/releases/v0.2.4-beta.1.md)(待评审、待现场验收)**。ICDB 批量检查在后台逐项运行,普通校验、管理和恢复可排队;READY 工程在实际执行前再次排除。检查不自动 Repair、Restore 或选择历史版本,也不代表中心库 READY。
|
||||
|
||||
自动流程不强杀原生会话;释放入口默认正常关闭。另有单独确认的“强制结束客户端”操作,仅限属于当前 Windows 用户和会话、归属及进程身份已确认的 PCB、Library Manager、DxDesigner/viewdraw、iCDB Project Backup 客户端。**ICDB 数据库服务器、后台导入器和归属未知的进程不允许强制结束**,即使命令指向当前库也不例外。客户端中其他已打开工程可能一并退出、未保存更改可能丢失;必须先记录确认名单,结束后重新证明库已释放,不能宣称数据库已修复。详见 [操作规程](SOP.md) 与 [版本说明](docs/releases/v0.2.4-beta.1.md)。下方日期记录为历史行为,以本说明为准。
|
||||
|
||||
本目录是独立的 CBB 中心库上传后校验工具,不属于 Part Replacement,也不负责 CBB 工程复制或中心库上传。
|
||||
|
||||
针对 `The last server session ... lost the connection to the database`,修复分支增加
|
||||
`ICDB_REPAIR_REQUIRED` 专项识别、共享符号库路径诊断及停止批次处理。现场原生修复步骤及实现边界见
|
||||
[iCDB 旧服务器会话失联分析](docs/diagnostics/2026-10-27-icdb-lost-server-session.md)。
|
||||
当前分支会在目标明确、所有权释放和独占访问证据齐全时尝试一次同版本原生 Repair;操作前请手动备份,共享符号库没有 PRJ 入口时停止并要求人工处理。
|
||||
当前应用入口仅检查工程打开情况,不自动 Repair。需要修复或回退时由用户在原生版本与备份界面选择,操作前请手动备份;共享符号库故障不得通过修复无关的 CBB 工程替代。
|
||||
|
||||
## 功能边界
|
||||
|
||||
@@ -203,7 +205,7 @@ Mentor 桥耗时需在目标机器另行测量。
|
||||
- `save.log`:`LICENSE_OK / SAVE_OK / IS_SAVED / POST_SAVE_SYNCHRONIZED / CLOSE_OK / QUIT_OK`;
|
||||
- `result.json`:状态、中心库标志读取结果、阻断原因;
|
||||
- `image-status-map.json`:按中心库路径隔离的本机动态 `image_id` 校准快照(当前格式 `schema_version=2`);旧版本或无版本缓存会自动忽略并重新校准,日志会记录当前样本、缓存样本、Ready 主 ID、未映射 ID 和逐项决策原因;
|
||||
- `backup/`:历史版本的辅助文件副本;当前分支不再生成,所有路径记录 `backup_skipped / manual_backup_policy`。已有历史副本不由本轮改动清理。
|
||||
- `backup/`:历史版本的辅助文件副本;当前分支不再生成,所有路径记录 `backup_skipped / manual_backup_policy`。已有历史副本不由本轮改动清理。
|
||||
|
||||
超时采用无进展计时:界面和批量请求默认 600 秒无进展超时;它不是整个 CBB 的固定总时限,而是连续 600 秒没有可观察进展时才终止。PCB/COM 阶段切换、Project Integration 状态变化、保存标记变化和弹窗处理都会刷新计时器;重复的状态轮询不算进展。需要更快失败时仍可在界面将单项预算调低,但 30 秒只适合已确认 PCB 启动稳定的环境。
|
||||
|
||||
|
||||
@@ -1,4 +1,32 @@
|
||||
# CBB 中心库上传后校验操作规程
|
||||
# CBB 检查、校验、管理与残留释放操作规程
|
||||
|
||||
适用开发版本:0.2.4b1。未完成现场验收,不自动发布或关闭工单。以下为当前规程,下方旧上传校验检查表保留为历史参考。
|
||||
|
||||
## 当前操作与队列
|
||||
|
||||
选择中心库 `.lmc`,核对 CBB 名称、分区及完整 PRJ/PCB 工程。写操作和人工修复前由操作员保存可用一致备份;应用不自动备份整个中心库,隔离验证/暂存副本不代替人工备份。
|
||||
|
||||
普通校验完成原生打开、身份确认、Project Integration、保存和关闭后,必须由权威状态 READY/raw=1 确认成功。ICDB 检查仅尝试打开并检查本次错误,不自动 Repair、Restore 或选择版本,CHECKED 不等于 READY。排队期间变成 READY 的工程在执行前跳过。
|
||||
|
||||
原生任务串行排队,检查每项结束后让出机会;缓存筛选保持可用。失败项确认释放后继续独立项目;实际未释放时停止后续原生操作。“停止检查”只取消检查,“取消当前任务并停止队列”同时取消前台任务及后续后台检查,已进行的写入等待安全结束,不强杀代替取消。
|
||||
|
||||
新增拒绝同名冲突;更新先原生移除再导入,失败可能需要人工备份恢复;移除后重新读取目录确认。版本回退由操作员在原生界面选择,核对工程内容后单独校验。
|
||||
|
||||
## 默认释放与单独确认的强制客户端操作
|
||||
|
||||
1. 停止新任务,预览当前库的工程、程序、PID 和历史记录。默认“确认释放”仅正常关闭作用域及当前身份已确认的客户端。未保存更改由操作员选择保存、放弃或保留;未知提示保持现场。
|
||||
2. 数据库服务器可能服务同库其他用户。本工具不允许强制结束服务器,命令行指向本库也不构成独占授权;由库管理员核对用户和服务器状态。
|
||||
3. “强制结束客户端”是另行确认的异常处理,只允许属于当前 Windows 用户和会话、已确认作用域和精确进程身份的 Expedition PCB、Library Manager、viewdraw、iCDB Project Backup 客户端。后台导入器、脚本宿主和归属未知的进程同样不在强制名单。
|
||||
4. 警告明确告知客户端中其他已打开工程可能一并退出、未保存更改会丢失、写入中的工程可能需要恢复。执行前持久保存库外 `consent.json`,包含目标库、名单、创建身份和排除项;写入失败不执行。派发与最终进程句柄两处重新核对,PID 复用、用户/Windows 会话或范围变化时拒绝。
|
||||
5. 客户端退出仅证明进程结束,不表示修复成功或 READY。服务器仍活跃或库状态未知时保留 PARTIAL、检查点和映射。只有完整的独立释放证明才解除匹配的历史记录;空进程列表本身不是释放证明。
|
||||
|
||||
## 失败、证据和回退
|
||||
|
||||
保留原生错误、操作员、Mentor 版本、库/工程身份和证据目录;原生日志上传前脱敏。不得删除原生地址/锁文件或修改 LMC 伪造状态。强制客户端退出不可撤销;工程恢复依靠人工一致备份或原生历史版本,不自动回退共享库或重放写操作。
|
||||
|
||||
程序回退须先关闭当前客户端,再运行此前候选包;它不恢复丢失更改或被中断的原生事务。工程恢复另行在隔离副本验证,保留前后证据并重新校验。Windows 10、共享库跨机器并发和现场服务器失联恢复仍待验收,fake 测试和文件头损坏试验不代替现场验收。
|
||||
|
||||
## 历史上传校验检查表
|
||||
|
||||
## 1. 输入与证据
|
||||
|
||||
|
||||
@@ -8,6 +8,14 @@
|
||||
|
||||
操作前正常关闭使用相同库的 PCB、Library Manager、原理图/符号编辑客户端,核对原服务器会话已结束,保留包含数据库、原备份和日志的完整一致副本。以下写入先在副本上进行。
|
||||
|
||||
## 残留客户端与共享服务器
|
||||
|
||||
0.2.4b1 的默认检查、校验、取消和释放流程不会强杀原生会话。操作员可以在独立确认界面强制结束属于当前 Windows 用户和会话、名单中的受支持客户端;这会影响该客户端内其他已打开工程,未保存更改可能丢失,属于异常退出处理,不能替代 Repair。
|
||||
|
||||
ICDB 数据库服务器即使命令行指向当前中心库,也可能服务其他用户,**本工具不允许强制结束服务器**。归属未知的进程、后台导入器和脚本宿主同样不允许强制结束;由库管理员核对用户和服务器状态后处理。
|
||||
|
||||
强制客户端动作必须先在库外证据目录持久写入确认名单、库和进程创建身份,再核对当前进程句柄、用户 SID 和 Windows 会话;记录失败或身份变化时不执行。客户端结束后仍需独立证明库已释放,重新打开工程并核对版本,必要时从人工一致备份或原生历史版本恢复。不能把“进程已结束”解释为“ICDB 已修复”。具体步骤见 [操作规程](../SOP.md)。
|
||||
|
||||
## 原生工程数据库 Repair
|
||||
|
||||
1. 启动本机的 iCDB Project Backup,并打开实际报错工程对应的 `.prj`。本机可用 PowerShell 命令形式如下,工程路径需替换为自己的隔离副本:
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
{
|
||||
"review_comment": "https://git.simgreek.com/Skyworth_Digital_Hardware/cbb-refresh-verify-795/pulls/3#issuecomment-249",
|
||||
"version": "0.2.4b1",
|
||||
"base_main": "a56fd17b60d9f67997d7f48c862f3367d4502f84",
|
||||
"tests": {
|
||||
"infrastructure": {
|
||||
"tests": 491,
|
||||
"errors": 0,
|
||||
"failures": 0,
|
||||
"skipped": 0,
|
||||
"xml_sha256": "12c2cd40542cb01d4fa374e98908c8a77a8deb83f95d0833645b1666ea5574e9",
|
||||
"xml_file": "codex-review-infrastructure-pytest.xml",
|
||||
"seconds": 52.986
|
||||
},
|
||||
"native_backend": {
|
||||
"tests": 1376,
|
||||
"errors": 0,
|
||||
"failures": 0,
|
||||
"skipped": 0,
|
||||
"xml_sha256": "8db65d11dd918d2a1b141d72627654a990ea903b68e20511e982dfb927d6be58",
|
||||
"xml_file": "codex-review-native-backend-pytest.xml",
|
||||
"seconds": 275.957
|
||||
},
|
||||
"ui_integration": {
|
||||
"tests": 1545,
|
||||
"errors": 0,
|
||||
"failures": 0,
|
||||
"skipped": 0,
|
||||
"xml_sha256": "5a3e6d58d611240c6e34cc9bd2350a8bf605516ef453240333836c1f88233af6",
|
||||
"xml_file": "codex-review-ui-integration-pytest.xml",
|
||||
"seconds": 325.065
|
||||
},
|
||||
"final_stack": {
|
||||
"tests": 1601,
|
||||
"errors": 0,
|
||||
"failures": 0,
|
||||
"skipped": 0,
|
||||
"xml_sha256": "bab74328facfbf512416b62a074fb5cb65ea39b04f0039d42083f96b5349c351",
|
||||
"xml_file": "codex-review-residual-release-pytest.xml",
|
||||
"seconds": 246.75
|
||||
},
|
||||
"umbrella": {
|
||||
"tests": 1601,
|
||||
"errors": 0,
|
||||
"failures": 0,
|
||||
"skipped": 0,
|
||||
"xml_sha256": "566f50b4ba537d4e54939946a5b48cad9ed6dbd8fb69c5ffbabcc5da0fbaf507",
|
||||
"xml_file": "r10-pr-pytest.xml",
|
||||
"seconds": 313.479
|
||||
},
|
||||
"force_boundary": {
|
||||
"tests": 43,
|
||||
"errors": 0,
|
||||
"failures": 0,
|
||||
"skipped": 0,
|
||||
"xml_sha256": "832425306b5fea3a150cc2188e00c97a771bb6d953e54b69c091d36e8062dca9",
|
||||
"xml_file": "pr249-force-focused.xml",
|
||||
"seconds": 3.231
|
||||
}
|
||||
},
|
||||
"compileall": "passed",
|
||||
"git_diff_check": "passed",
|
||||
"final_content": {
|
||||
"file_count": 195,
|
||||
"sha256": "2784b81ff0ae4d47f85ac8ea4b217292bbd9a1e716667e729863bfd4a6a372cd",
|
||||
"umbrella_equals_stack": true
|
||||
},
|
||||
"post_test_formatting": "MainWindow line endings aligned with UI review base (AST equality asserted); unchanged README lines retain main line endings",
|
||||
"regression_red": {
|
||||
"baseline": "e4266ae",
|
||||
"selected_new_ownership_tests": 3,
|
||||
"expected_failures": 3,
|
||||
"method": "in-memory baseline module; no production files or native processes modified"
|
||||
},
|
||||
"force_contract": {
|
||||
"clients_only": true,
|
||||
"same_user_sid_and_windows_session": true,
|
||||
"servers_never_terminated": true,
|
||||
"durable_consent_before_action": true,
|
||||
"independent_library_release_proof_required": true
|
||||
},
|
||||
"not_validated": [
|
||||
"field server-session loss recovery",
|
||||
"Windows 10",
|
||||
"cross-machine shared-library concurrency",
|
||||
"actual Mentor force termination",
|
||||
"new frozen package"
|
||||
],
|
||||
"delivery_policy": "Draft review only; no merge, publish, automatic issue closure or native production-library operation"
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
# v0.2.4-beta.1(0.2.4b1)开发候选说明
|
||||
|
||||
状态:待评审、待现场验收。不是自动发布指令,工单保持开放。
|
||||
|
||||
## 用户可见变化
|
||||
|
||||
- 检验、ICDB 维护、中心库管理为独立入口。ICDB 检查在后台逐项运行,其他原生任务可排队,搜索/筛选保持可用。
|
||||
- 检查以当前 PCB 打开情况和本次原生错误为依据,只有明确 ICDB 错误才标记问题;不自动 Repair、Restore 或选择版本,CHECKED 不等于 READY。
|
||||
- 停止队列同时停止后续后台检查;执行前再次排除 READY,校验排队不隐藏检查进度;释放失败显示实际原因。
|
||||
- 原生新增、同名替换、移除和备份恢复继续要求确认及人工备份,失败结果和未完成任务逐项保留。
|
||||
- 默认残留释放为正常关闭。单独确认的强制结束仅允许属于当前 Windows 用户和会话、已确认作用域和精确身份的受支持文档客户端;服务器、后台导入器和未知进程不可强制结束。
|
||||
|
||||
## 强制客户端操作的契约
|
||||
|
||||
支持 Expedition PCB、Library Manager、viewdraw 和 iCDB Project Backup。操作员须知晓客户端中其他工程可能一并退出、未保存更改可能丢失、写入中的工程可能需要恢复。确认名单先持久记录为库外 `consent.json`,失败则不执行;派发与进程句柄两处复核,PID 复用、用户或 Windows 会话变化时拒绝。
|
||||
|
||||
数据库服务器可能服务同库其他用户,命令行归属不构成独占授权。本工具不会强制结束任何 ICDB 服务器;它仍活跃或库状态未知时保留 PARTIAL,不能通过结束客户端伪造释放或修复成功。
|
||||
|
||||
## 安全状态和回退
|
||||
|
||||
单项失败且本任务确已释放时可继续独立项;未释放时保留现场、检查点、映射和证据。客户端强制结束不可撤销,恢复使用人工一致备份或原生历史版本;不会自动重新导入、回退共享库或重放未完成写操作。
|
||||
|
||||
程序回退:先关闭正在使用的客户端,再使用此前候选包;程序回退不恢复原生事务或丢失更改。工程恢复:保留故障现场、选择确认过的备份,在隔离副本验证后恢复并重新校验。
|
||||
|
||||
## 验证与限制
|
||||
|
||||
PR #3 comment 249 的修复通过服务器排除、确认记录失败、PID 复用、客户端/服务器混合名单等 fake 边界回归;没有为了验证本功能终止真实 Mentor 客户端或服务器。
|
||||
|
||||
此前 r10 的原生隔离检查与界面排队证据只证明该候选包已记录的打开/释放行为,不能当成新强制客户端功能的现场验收。现场服务器失联恢复、ICDB 自动修复、Windows 10 和共享库跨机器并发仍未验收。
|
||||
|
||||
规范:[SOP](../../SOP.md)、[ICDB 手动修复手册](../ICDB-MANUAL-REPAIR-AND-UPDATE.md)。依赖和拆分顺序见 PR #3 的独立审查链。
|
||||
@@ -0,0 +1,13 @@
|
||||
# 独立审查 1:只读进程探测与原生任务准入队列
|
||||
|
||||
基于 main `a56fd17`,不叠加 PR #3 的历史提交。
|
||||
|
||||
**行为变化:** 增加有界、版本化、只读 owner-probe helper 和可取消的 FIFO 原生任务队列。应用仅新增隐藏的只读 helper 分派;现有 UI、验证和原生写操作保持原来的入口。
|
||||
|
||||
**失败安全:** 查询超时或协议/身份异常返回未确认;暂停或取消的队列票据不会运行其动作,也不阻止后面的可执行任务。不启动或终止 Mentor 进程。
|
||||
|
||||
**回滚方式:** 尚未合入下游时撤销本提交即可;下游接入后须按依赖从上层向下回退。
|
||||
|
||||
完整回归:491 passed,1 条既有 pywinauto STA 提示。编译和 diff 检查通过。
|
||||
|
||||
与原评论建议的差别:`management_transaction` 直接导入管理模型和库锁;`scoped_manifest` 的协调记录与独占快照依赖库锁协议。这两者在后端审查中一起交付,避免构造导入不完整的“纯工具”基线。
|
||||
@@ -0,0 +1,11 @@
|
||||
# Native backend review unit
|
||||
|
||||
Base: codex/review-infrastructure. This unit integrates ICDB open diagnostics, scoped content manifests, native CBB transactions and the library-release protocol; it does not expose the new UI or residual termination action. Verification and ICDB checks remain separate, READY items are excluded from maintenance, and a released single-item failure can continue independent targets.
|
||||
|
||||
Failure safety: no automatic Repair/version choice, no server termination, no direct LMC edits or native lock-file deletion. Native writes are serialized, uncertain ownership retains evidence and mappings, and unfinished writes are shown without replay.
|
||||
|
||||
Dependency rationale: library release imports native engineering identity and retained management workers; engineering identity imports management source models and scoped manifests. Separating these into nominally independent utilities would leave runtime imports unresolved. This PR therefore keeps the backend dependency closure together; UI and user-confirmed termination remain separate later PRs.
|
||||
|
||||
Rollback: before dependents are merged, revert this commit. After merging dependents, revert in reverse order or use the previous candidate package after closing the current app. Code rollback does not undo a native transaction; use a consistent manual backup or explicitly selected native history on an isolated copy.
|
||||
|
||||
Validation: full Python suite 1,376 passed (one existing pywinauto COM-threading warning); compileall and git diff --check passed. Native field recovery, Windows 10 and cross-machine shared-library acceptance remain pending.
|
||||
@@ -0,0 +1,9 @@
|
||||
# Residual release contract review unit
|
||||
|
||||
Base: codex/review-ui-integration. Behavior: expose the residual-session preview and cooperative close entry, plus a separately confirmed force action limited to recognized document clients of the current Windows user and session. Database servers, importers, unknown scope and unverified identities cannot be force ended. Version becomes 0.2.4b1, with README, SOP, manual and rollback notes aligned.
|
||||
|
||||
Failure safety: persist the exact allowed/excluded confirmation list before any native action, recheck scope/creation/executable/user/session at dispatch and the held handle, and require independent library-release proof after exit. Unreadable owner metadata disables force only. A terminated client is not a repaired/READY project; partial release retains evidence and mappings.
|
||||
|
||||
Rollback: reverse the dependent commits before reverting the backend, or close the current app and use the earlier candidate. Process termination cannot be undone, and code rollback does not restore native transactions or unsaved data. Use a consistent manual backup or an explicitly chosen native history version on a copy.
|
||||
|
||||
Validation: 1,601 passed for this final stack, 1,601 passed for the umbrella, and 43 focused release tests passed after the final UI wording change. Compileall, diff checks and byte-level final implementation equality passed. Detailed XML counts/hashes and content digest are recorded in ../releases/2026-11-05-pr249-review-validation.json. No real Mentor client/server was terminated for these checks. Field recovery, Windows 10, shared-library concurrency and the new frozen package remain unverified.
|
||||
@@ -0,0 +1,9 @@
|
||||
# Application integration review unit
|
||||
|
||||
Base: codex/review-native-backend. Behavior: verification, ICDB batch checking and CBB management have separate tabs; background checks yield between items, keep browsing responsive and let other native tasks queue. READY targets are excluded at execution, status refresh is scoped, and manual version/copy decisions remain explicit.
|
||||
|
||||
Failure safety: a released item failure can continue independent targets; uncertain native ownership retains evidence and mappings. There is no residual-session release backend in this review stage: its button and result actions are hidden, and its callback is inert. The next PR restores the complete release entry together with its tested backend, rather than exposing a button with a missing import. No automatic Repair or native version selection is added.
|
||||
|
||||
Rollback: revert this UI commit before its dependent release PR; after dependents, revert in reverse order or close the current program and use the prior candidate. This does not roll back library writes.
|
||||
|
||||
Validation: 1,545 passed (one existing pywinauto COM-threading warning), compileall and diff checks passed. Release-specific tests are introduced in the dependent PR, never discarded from the final tree. Windows 10, real shared-library concurrency and field ICDB recovery remain pending.
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
**Authorization:** The user requested implementation of comment 249. Earlier user decisions retain explicit user-confirmed residual release, manual backups and no release/issue closure before field acceptance. These decisions take precedence over changing Draft status merely to make a merge button available.
|
||||
|
||||
**Architecture:** Keep automatic verification and checking cooperative. A separate explicit force action can end supported document clients only after scope and exact process identity are checked. Native database servers and unknown processes remain observable and cannot be force terminated. Every force request must persist consent intent before any termination and still obtain independent library-release proof afterward.
|
||||
**Architecture:** Keep automatic verification and checking cooperative. A separate explicit force action can end supported document clients only after scope, exact process identity, current user SID and Windows session are checked. Native database servers and unknown processes remain observable and cannot be force terminated. Every force request must persist consent intent before any termination and still obtain independent library-release proof afterward.
|
||||
|
||||
**Review split:** Preserve #3 as an unmerged umbrella. Create a dependent review chain: (1) read-only owner probing and cooperative queue; (2) native backend, manifests, library coordination and transactions; (3) background checks and application UI integration; (4) residual-session release, its explicit contract, version and documentation. `management_transaction` imports management and lock APIs, and semantic manifests depend on recognized coordination checkpoints; they belong with the backend rather than pretending to be standalone read-only utilities. The existing #5 remains a prerequisite document review, not an automatically merged change.
|
||||
|
||||
@@ -20,25 +20,25 @@
|
||||
|
||||
Files: `residual_sessions.py`, `ui/residual_release_dialog.py`, `tests/test_residual_sessions.py`, `tests/test_residual_release_dialog.py`.
|
||||
|
||||
- [ ] Add failing tests: a scoped iCDB server cannot reach `_force_close`; direct force requests against server/unsupported names never obtain a terminate-capable handle; missing consent evidence causes zero termination calls; mixed client/server previews list only supported clients in the confirmation; rejected/reused process identities remain unchanged.
|
||||
- [ ] Define one shared force-eligibility function allowing only recognized document clients with confirmed scope and matching captured executable identity. Enforce it again at dispatch and at the exact handle boundary.
|
||||
- [ ] Persist `consent.json` with target library, exact preview identities and allowed/excluded targets before processing a force request. A write failure returns before native actions.
|
||||
- [ ] Keep excluded servers in the release result and require the existing independent release proof; process exit never means repaired/READY.
|
||||
- [ ] Run focused regressions and the complete suite with an isolated test mutex.
|
||||
- [x] Add failing tests: a scoped iCDB server cannot reach `_force_close`; direct force requests against server/unsupported names never obtain a terminate-capable handle; missing consent evidence causes zero termination calls; mixed client/server previews list only supported clients in the confirmation; rejected/reused process identities remain unchanged.
|
||||
- [x] Define one shared force-eligibility function allowing only recognized document clients with confirmed scope and matching captured executable identity. Enforce it again at dispatch and at the exact handle boundary.
|
||||
- [x] Persist `consent.json` with target library, exact preview identities and allowed/excluded targets before processing a force request. A write failure returns before native actions.
|
||||
- [x] Keep excluded servers in the release result and require the existing independent release proof; process exit never means repaired/READY.
|
||||
- [x] Run focused regressions and the complete suite with an isolated test mutex.
|
||||
|
||||
## Task 2: Version and operating contract
|
||||
|
||||
Files: `pyproject.toml`, `README.md`, `SOP-CBB-Refresh-After-Upload.md` (if present; otherwise the repository's actual SOP path), `docs/ICDB-MANUAL-REPAIR-AND-UPDATE.md`, `docs/releases/v0.2.4-beta.1.md`.
|
||||
Files: `pyproject.toml`, `README.md`, `SOP.md`, `docs/ICDB-MANUAL-REPAIR-AND-UPDATE.md`, `docs/releases/v0.2.4-beta.1.md`.
|
||||
|
||||
- [ ] Identify the actual tracked SOP before editing; update README, SOP and manual together.
|
||||
- [ ] Set `0.2.4b1` and document the user-confirmed client-only exception to the automatic no-force contract. Explain server handling, evidence, failure states, manual recovery and rollback.
|
||||
- [ ] Keep field ICDB recovery, Win10 and multiuser shared-library acceptance explicitly unverified.
|
||||
- [x] Identify the actual tracked SOP before editing; update README, SOP and manual together.
|
||||
- [x] Set `0.2.4b1` and document the user-confirmed client-only exception to the automatic no-force contract. Explain server handling, evidence, failure states, manual recovery and rollback.
|
||||
- [x] Keep field ICDB recovery, Win10 and multiuser shared-library acceptance explicitly unverified.
|
||||
|
||||
## Task 3: Review branches
|
||||
|
||||
- [ ] Inventory final files against main and assign each file to the smallest dependency-closed review stage. Keep UI/release hooks unavailable until their backend exists; do not publish branches with broken normal operation.
|
||||
- [ ] Create ordered branches with one concrete feature commit per review unit, no rewriting the existing umbrella history.
|
||||
- [ ] Test each review stage using appropriate unit/full checks; preserve all final regressions and verify the final source tree against the umbrella snapshot.
|
||||
- [x] Inventory final files against main and assign each file to the smallest dependency-closed review stage. Keep UI/release hooks unavailable until their backend exists; do not publish branches with broken normal operation.
|
||||
- [x] Create ordered branches with one concrete feature commit per review unit, no rewriting the existing umbrella history.
|
||||
- [x] Test each review stage using appropriate unit/full checks; preserve all final regressions and verify the final source tree against the umbrella snapshot.
|
||||
- [ ] Push branches without force and create draft PRs with explicit base dependencies. Link them from #3 and record the splitting rationale.
|
||||
|
||||
## Task 4: Delivery
|
||||
|
||||
+1
-1
@@ -3,7 +3,7 @@ requires = ["setuptools>=84.1.0"]
|
||||
build-backend = "setuptools.build_meta"
|
||||
[project]
|
||||
name = "cbb-refresh-verify"
|
||||
version = "0.2.3b1"
|
||||
version = "0.2.4b1"
|
||||
requires-python = ">=3.12,<3.13"
|
||||
dependencies = ["PySide6>=6.7,<7", "pywin32>=306", "pywinauto>=0.6.9,<0.7", "Pillow>=13.0.0,<14"]
|
||||
|
||||
|
||||
@@ -1 +1 @@
|
||||
__version__ = "0.2.3b1"
|
||||
__version__ = "0.2.4b1"
|
||||
@@ -15,6 +15,23 @@ _NAMES = {'expeditionpcb.exe', 'librarymanager.exe', 'icdbprojectbackup.exe',
|
||||
'reuseblockimporter.exe', 'cleanwglib.exe', 'cscript.exe', 'wscript.exe'} | _OWNER_NAMES
|
||||
_WORKER_NAMES = {'python.exe', 'pythonw.exe', 'cbbrefreshverify.exe'}
|
||||
_WORKER_FLAGS = ('--verify-worker', '--repair-worker', '--management-worker', '--native-backup-worker')
|
||||
_FORCE_CLIENT_NAMES = {'expeditionpcb.exe', 'librarymanager.exe', 'viewdraw.exe', 'icdbprojectbackup.exe'}
|
||||
|
||||
|
||||
def force_block_reason(row):
|
||||
"""A library path proves scope, never exclusive ownership of a server."""
|
||||
if row.get('scope_confirmed') is not True:
|
||||
return '进程归属未确认,不允许强制结束'
|
||||
name = str(row.get('name', '')).casefold()
|
||||
if name not in _FORCE_CLIENT_NAMES:
|
||||
return '服务器或其他受保护进程仅供观察,不允许强制结束'
|
||||
if (not row.get('created_handle') or not row.get('image')
|
||||
or Path(row['image']).name.casefold() != name):
|
||||
return '客户端身份未确认,不允许强制结束'
|
||||
if (row.get('force_user_confirmed') is not True or not row.get('owner_sid')
|
||||
or not isinstance(row.get('session_id'), int)):
|
||||
return '未确认属于当前用户和 Windows 会话,不允许强制结束'
|
||||
return ''
|
||||
|
||||
|
||||
@contextmanager
|
||||
@@ -45,7 +62,30 @@ def _handle_identity(handle):
|
||||
|
||||
def _process_identity(row):
|
||||
with _process_handle(row['pid']) as handle:
|
||||
return _handle_identity(handle)
|
||||
identity = _handle_identity(handle)
|
||||
try:
|
||||
identity.update(_force_ownership(handle, row['pid']))
|
||||
except Exception as error:
|
||||
identity.update(force_user_confirmed=False, owner_error=str(error))
|
||||
return identity
|
||||
|
||||
|
||||
def _force_ownership(handle, pid):
|
||||
import win32api, win32con, win32process, win32security, win32ts
|
||||
if win32process.GetProcessId(handle) != pid:
|
||||
raise ValueError('进程身份已变化')
|
||||
def owner(process):
|
||||
token = win32security.OpenProcessToken(process, win32con.TOKEN_QUERY)
|
||||
try:
|
||||
return win32security.ConvertSidToStringSid(
|
||||
win32security.GetTokenInformation(token, win32security.TokenUser)[0])
|
||||
finally:
|
||||
token.Close()
|
||||
sid = owner(handle)
|
||||
session = win32ts.ProcessIdToSessionId(pid)
|
||||
return {'owner_sid': sid, 'session_id': session, 'force_user_confirmed':
|
||||
sid == owner(win32api.GetCurrentProcess())
|
||||
and session == win32ts.ProcessIdToSessionId(os.getpid())}
|
||||
|
||||
|
||||
def _process_windows(pids):
|
||||
@@ -191,6 +231,10 @@ def inspect_residual_sessions(library, *, block_names=()):
|
||||
item.update(can_close=False, detail=f'进程已变化或暂时无法确认:{error}')
|
||||
item['project'] = _project_name(row, library) if row['scope_confirmed'] else '归属未确认'
|
||||
item['prompt'] = _save_question(windows.get(row['pid'], [])) if row['scope_confirmed'] else None
|
||||
item['force_block_reason'] = force_block_reason(item)
|
||||
item['force_allowed'] = not item['force_block_reason']
|
||||
if item['force_block_reason']:
|
||||
item['detail'] += ';'+item['force_block_reason']
|
||||
sessions.append(item)
|
||||
previous = []
|
||||
marker = blocker_path(library)
|
||||
@@ -253,15 +297,21 @@ def _force_close(row, *, stop=None):
|
||||
import win32api, win32con, win32event
|
||||
if stop is not None and stop.is_set():
|
||||
return {'release_status': 'CANCELLED', 'detail': '已停止释放'}
|
||||
if reason := force_block_reason(row):
|
||||
return {'release_status': 'WAITING', 'detail': reason}
|
||||
with _process_handle(row['pid'], terminate=True) as handle:
|
||||
if win32event.WaitForSingleObject(handle, 0) == win32con.WAIT_OBJECT_0:
|
||||
return {'release_status': 'RELEASED', 'detail': '已退出'}
|
||||
if _handle_identity(handle) != {k: row.get(k) for k in ('created_handle', 'image')}:
|
||||
return {'release_status': 'IDENTITY_CHANGED', 'detail': '进程身份已变化,未结束'}
|
||||
ownership = _force_ownership(handle, row['pid'])
|
||||
if (not ownership['force_user_confirmed'] or
|
||||
any(ownership[k] != row.get(k) for k in ('owner_sid', 'session_id'))):
|
||||
return {'release_status': 'IDENTITY_CHANGED', 'detail': '用户或 Windows 会话已变化,未结束'}
|
||||
win32api.TerminateProcess(handle, 1)
|
||||
exited = win32event.WaitForSingleObject(handle, 3000) == win32con.WAIT_OBJECT_0
|
||||
return {'release_status': 'RELEASED' if exited else 'WAITING',
|
||||
'detail': '已强制结束,工程需重新检查' if exited else '已请求结束,等待退出'}
|
||||
'detail': '已强制结束客户端,工程待检查,未执行修复' if exited else '已请求结束客户端,等待退出'}
|
||||
|
||||
|
||||
def _finish_library_release(library, evidence):
|
||||
@@ -277,6 +327,16 @@ def _release_residual_sessions(plan, evidence_dir, *, stop=None, force=False):
|
||||
root.mkdir(parents=True)
|
||||
result = {'status': 'PARTIAL', 'library': str(library), 'sessions': [], 'force': force,
|
||||
'evidence_path': str(root/'result.json'), 'previous_records': plan.get('previous_records', [])}
|
||||
if force:
|
||||
consent_path = root/'consent.json'
|
||||
consent = {'version': 1, 'mode': 'force_document_clients', 'library': str(library),
|
||||
'time_ns': time.time_ns(), 'sessions': [
|
||||
{**row, 'force_allowed': not force_block_reason(row),
|
||||
'force_block_reason': force_block_reason(row)} for row in plan['sessions']]}
|
||||
with consent_path.open('x', encoding='utf-8') as stream:
|
||||
json.dump(consent, stream, ensure_ascii=False, indent=2)
|
||||
stream.flush(); os.fsync(stream.fileno())
|
||||
result['consent_path'] = str(consent_path)
|
||||
fresh = {r['pid']: r for r in query_process_snapshot()}
|
||||
# Close native children first, so their supervisors can finish and drop leases.
|
||||
ordered = sorted(plan['sessions'], key=lambda r: r['name'].casefold() in _WORKER_NAMES)
|
||||
@@ -292,6 +352,8 @@ def _release_residual_sessions(plan, evidence_dir, *, stop=None, force=False):
|
||||
outcome = {'release_status': 'WAITING', 'detail': '未在确认名单中证明属于当前库,未关闭;请重新检查'}
|
||||
elif any(current.get(key) != original.get(key) for key in ('created', 'executable', 'command', 'name')):
|
||||
outcome = {'release_status': 'IDENTITY_CHANGED', 'detail': '确认后进程身份已变化,未关闭'}
|
||||
elif force and (reason := force_block_reason(original)):
|
||||
outcome = {'release_status': 'WAITING', 'detail': reason, 'force_allowed': False}
|
||||
else:
|
||||
try: outcome = (_force_close if force else _request_close)(original, stop=stop)
|
||||
except Exception as error:
|
||||
|
||||
+1584
-1584
File diff suppressed because it is too large.
Load diff
@@ -7,6 +7,7 @@ from PySide6.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout, QLabel, QPushB
|
||||
QTableWidget, QTableWidgetItem, QHeaderView, QMessageBox)
|
||||
|
||||
from .workers import ServiceWorker
|
||||
from ..residual_sessions import force_block_reason
|
||||
|
||||
|
||||
class ResidualReleaseDialog(QDialog):
|
||||
@@ -39,7 +40,7 @@ class ResidualReleaseDialog(QDialog):
|
||||
self.refresh_button = QPushButton('重新检查')
|
||||
self.confirm_button = QPushButton('确认释放')
|
||||
self.prompt_button = QPushButton('处理保存提示…')
|
||||
self.force_button = QPushButton('强制结束所列会话…')
|
||||
self.force_button = QPushButton('强制结束客户端…')
|
||||
self.force_button.setEnabled(False)
|
||||
self.prompt_button.setEnabled(False)
|
||||
self.close_button = QPushButton('关闭')
|
||||
@@ -71,7 +72,7 @@ class ResidualReleaseDialog(QDialog):
|
||||
self.refresh_button.setEnabled(True)
|
||||
self.confirm_button.setEnabled(self.plan is not None)
|
||||
self.force_button.setEnabled(bool(self.plan and any(
|
||||
r.get('scope_confirmed', True) for r in self.plan['sessions'])))
|
||||
not force_block_reason(r) for r in self.plan['sessions'])))
|
||||
self.close_button.setText('关闭')
|
||||
self._update_prompt()
|
||||
if self._refresh_after:
|
||||
@@ -132,11 +133,12 @@ class ResidualReleaseDialog(QDialog):
|
||||
|
||||
def force_release(self):
|
||||
if self.busy or not self.plan or not self.plan['sessions']: return
|
||||
targets = [r for r in self.plan['sessions'] if r.get('scope_confirmed', True)]
|
||||
targets = [r for r in self.plan['sessions'] if not force_block_reason(r)]
|
||||
if not targets: return
|
||||
names = '\n'.join(f'{r.get("project", "")} — {r["name"]} (PID {r["pid"]})' for r in targets)
|
||||
answer = QMessageBox.warning(self, '强制结束会话',
|
||||
'将强制结束以下进程,未保存的更改会丢失,正在写入的工程可能需要恢复。\n\n'+names+
|
||||
answer = QMessageBox.warning(self, '强制结束客户端',
|
||||
'仅强制结束以下客户端。客户端中其他已打开工程也会退出;未保存的更改会丢失,正在写入的工程可能需要恢复。'
|
||||
'\n数据库服务器和归属未知的进程不会被强制结束。\n\n'+names+
|
||||
'\n\n仍要结束这些进程吗?', QMessageBox.Yes | QMessageBox.Cancel, QMessageBox.Cancel)
|
||||
if answer == QMessageBox.Yes: self.confirm_release(force=True)
|
||||
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
from threading import Event, Thread
|
||||
|
||||
from cbb_refresh_verify.operation_queue import NativeQueue, QueueCancelled
|
||||
|
||||
|
||||
def test_paused_ticket_yields_to_a_ready_native_task():
|
||||
queue=NativeQueue()
|
||||
ready, waiting, complete=Event(),Event(),Event()
|
||||
order=[]
|
||||
thread=Thread(target=lambda:queue.run(lambda:(order.append('resumed'),complete.set()),
|
||||
ready=ready.is_set,waiting=waiting.set))
|
||||
thread.start()
|
||||
try:
|
||||
assert waiting.wait(2)
|
||||
queue.run(lambda:order.append('ready'))
|
||||
assert order==['ready']
|
||||
ready.set();queue.wake()
|
||||
assert complete.wait(2)
|
||||
assert order==['ready','resumed']
|
||||
finally:
|
||||
ready.set();queue.wake();thread.join(2)
|
||||
assert not thread.is_alive()
|
||||
|
||||
|
||||
def test_cancelled_paused_ticket_does_not_hold_later_work():
|
||||
queue=NativeQueue()
|
||||
waiting,stop=Event(),Event()
|
||||
outcome=[]
|
||||
def wait():
|
||||
try:
|
||||
queue.run(lambda:outcome.append('unexpected'),ready=lambda:False,
|
||||
waiting=waiting.set,stop=stop)
|
||||
except QueueCancelled:outcome.append('cancelled')
|
||||
thread=Thread(target=wait);thread.start()
|
||||
try:
|
||||
assert waiting.wait(2)
|
||||
stop.set();queue.wake();thread.join(2)
|
||||
assert not thread.is_alive()
|
||||
queue.run(lambda:outcome.append('next'))
|
||||
assert outcome==['cancelled','next']
|
||||
finally:
|
||||
stop.set();queue.wake();thread.join(2)
|
||||
@@ -81,7 +81,8 @@ def test_force_close_is_explicit_and_cancel_does_not_release(qtbot, tmp_path, mo
|
||||
from cbb_refresh_verify import library_lock
|
||||
from cbb_refresh_verify.ui.residual_release_dialog import ResidualReleaseDialog
|
||||
plan = {'library': str(tmp_path/'lib.lmc'), 'sessions': [
|
||||
{'project': 'A', 'name': 'ExpeditionPCB.exe', 'pid': 10, 'detail': '窗口无响应'}]}
|
||||
{'project': 'A', 'name': 'ExpeditionPCB.exe', 'pid': 10, 'detail': '窗口无响应',
|
||||
'scope_confirmed': True, 'owner_sid': 'S-1-current', 'session_id': 1, 'force_user_confirmed': True, 'image': 'C:/Mentor/ExpeditionPCB.exe', 'created_handle': 'creation'}]}
|
||||
monkeypatch.setattr(library_lock, 'inspect_residual_sessions', lambda *_: plan)
|
||||
calls = []
|
||||
def release(actual, *a, **kw):
|
||||
@@ -100,6 +101,31 @@ def test_force_close_is_explicit_and_cancel_does_not_release(qtbot, tmp_path, mo
|
||||
assert calls == [True]
|
||||
|
||||
|
||||
def test_force_confirmation_excludes_shared_servers(qtbot, tmp_path, monkeypatch):
|
||||
from PySide6.QtWidgets import QMessageBox
|
||||
from cbb_refresh_verify import library_lock
|
||||
from cbb_refresh_verify.ui.residual_release_dialog import ResidualReleaseDialog
|
||||
rows = [{'project': 'A', 'name': name, 'pid': pid, 'scope_confirmed': True, 'owner_sid': 'S-1-current', 'session_id': 1, 'force_user_confirmed': True,
|
||||
'image': 'C:/Mentor/'+name, 'created_handle': str(pid), 'detail': 'waiting'}
|
||||
for name, pid in [('icdbserver.exe', 10), ('ExpeditionPCB.exe', 20)]]
|
||||
monkeypatch.setattr(library_lock, 'inspect_residual_sessions', lambda *_: {
|
||||
'library': str(tmp_path/'lib.lmc'), 'sessions': rows})
|
||||
dialog = ResidualReleaseDialog(tmp_path/'lib.lmc', tmp_path/'evidence')
|
||||
qtbot.addWidget(dialog)
|
||||
qtbot.waitUntil(lambda: not dialog.busy)
|
||||
messages = []
|
||||
monkeypatch.setattr(QMessageBox, 'warning', lambda parent, title, text, *args:
|
||||
messages.append(text) or QMessageBox.Cancel)
|
||||
dialog.force_button.click()
|
||||
assert len(messages) == 1
|
||||
assert 'ExpeditionPCB.exe' in messages[0]
|
||||
assert 'icdbserver.exe' not in messages[0]
|
||||
assert '服务器' in messages[0]
|
||||
dialog.plan['sessions'] = [rows[0]]
|
||||
dialog._finished()
|
||||
assert not dialog.force_button.isEnabled()
|
||||
|
||||
|
||||
def test_released_batch_can_resume_only_its_unexecuted_items(qtbot, tmp_path, monkeypatch):
|
||||
from test_ui_filters import load_window
|
||||
from cbb_refresh_verify.verify_runner import VerifyResult
|
||||
|
||||
+144
-10
@@ -4,6 +4,9 @@ from types import SimpleNamespace
|
||||
import pytest
|
||||
|
||||
|
||||
OWNERSHIP = {"owner_sid": "S-1-current", "session_id": 1, "force_user_confirmed": True}
|
||||
|
||||
|
||||
def api():
|
||||
from cbb_refresh_verify import library_lock
|
||||
inspect = getattr(library_lock, 'inspect_residual_sessions', None)
|
||||
@@ -24,7 +27,7 @@ def test_preview_limits_to_selected_projects_and_keeps_process_identity(tmp_path
|
||||
a = library.parent/'ReusableBlocksLP/A/Work/A.prj'
|
||||
b = library.parent/'ReusableBlocksLP/B/Work/B.prj'
|
||||
monkeypatch.setattr(sessions, 'query_process_snapshot', lambda: [row(10, a), row(20, b)])
|
||||
monkeypatch.setattr(sessions, '_process_identity', lambda r: {'created_handle': r['created'], 'image': r['executable']})
|
||||
monkeypatch.setattr(sessions, '_process_identity', lambda r: {**OWNERSHIP, 'created_handle': r['created'], 'image': r['executable']})
|
||||
monkeypatch.setattr(sessions, '_process_windows', lambda pids: {p: [] for p in pids})
|
||||
result = inspect(library, block_names=('A',))
|
||||
assert [r['pid'] for r in result['sessions']] == [10]
|
||||
@@ -38,7 +41,7 @@ def test_unknown_scope_is_visible_but_never_closed_even_with_force(tmp_path, mon
|
||||
process['name'] = 'LibraryManager.exe'
|
||||
monkeypatch.setattr(sessions, 'query_process_snapshot', lambda: [process])
|
||||
monkeypatch.setattr(sessions, '_process_windows', lambda _: {})
|
||||
monkeypatch.setattr(sessions, '_process_identity', lambda r: {'created_handle': 'old', 'image': r['executable']})
|
||||
monkeypatch.setattr(sessions, '_process_identity', lambda r: {**OWNERSHIP, 'created_handle': 'old', 'image': r['executable']})
|
||||
plan = sessions.inspect_residual_sessions(library)
|
||||
assert plan['sessions'] and plan['sessions'][0]['scope_confirmed'] is False
|
||||
monkeypatch.setattr(sessions, '_request_close', lambda *a, **kw: pytest.fail('closed unknown scope'))
|
||||
@@ -74,7 +77,7 @@ def test_confirmation_rechecks_pid_reuse_and_never_posts_to_replacement(tmp_path
|
||||
library = tmp_path/'lib.lmc'; library.touch()
|
||||
process = row(10, tmp_path/'ReusableBlocksLP/A/Work/A.prj')
|
||||
monkeypatch.setattr(sessions, 'query_process_snapshot', lambda: [process.copy()])
|
||||
monkeypatch.setattr(sessions, '_process_identity', lambda r: {'created_handle': 'old', 'image': r['executable']})
|
||||
monkeypatch.setattr(sessions, '_process_identity', lambda r: {**OWNERSHIP, 'created_handle': 'old', 'image': r['executable']})
|
||||
monkeypatch.setattr(sessions, '_process_windows', lambda _: {10: []})
|
||||
plan = inspect(library)
|
||||
process['created'] = 'replacement'
|
||||
@@ -91,7 +94,7 @@ def test_close_requests_cover_whole_preview_and_failures_remain_per_item(tmp_pat
|
||||
library = tmp_path/'lib.lmc'; library.touch()
|
||||
rows = [row(p, tmp_path/f'ReusableBlocksLP/{p}/Work/{p}.prj') for p in (10, 20)]
|
||||
monkeypatch.setattr(sessions, 'query_process_snapshot', lambda: rows)
|
||||
monkeypatch.setattr(sessions, '_process_identity', lambda r: {'created_handle': r['created'], 'image': r['executable']})
|
||||
monkeypatch.setattr(sessions, '_process_identity', lambda r: {**OWNERSHIP, 'created_handle': r['created'], 'image': r['executable']})
|
||||
monkeypatch.setattr(sessions, '_process_windows', lambda _: {})
|
||||
calls = []
|
||||
monkeypatch.setattr(sessions, '_request_close', lambda r, *_, **kw: calls.append(r['pid']) or
|
||||
@@ -146,7 +149,7 @@ def test_force_requires_separate_explicit_argument_and_rechecks_identity(tmp_pat
|
||||
library = tmp_path/'lib.lmc'; library.touch()
|
||||
process = row(10, tmp_path/'ReusableBlocksLP/A/Work/A.prj')
|
||||
monkeypatch.setattr(sessions, 'query_process_snapshot', lambda: [process.copy()])
|
||||
monkeypatch.setattr(sessions, '_process_identity', lambda r: {'created_handle': 'old', 'image': r['executable']})
|
||||
monkeypatch.setattr(sessions, '_process_identity', lambda r: {**OWNERSHIP, 'created_handle': 'old', 'image': r['executable']})
|
||||
monkeypatch.setattr(sessions, '_process_windows', lambda _: {})
|
||||
monkeypatch.setattr(sessions, '_request_close', lambda *a, **k: {'release_status': 'WAITING', 'detail': 'hung'})
|
||||
forced = []
|
||||
@@ -163,14 +166,125 @@ def test_force_requires_separate_explicit_argument_and_rechecks_identity(tmp_pat
|
||||
assert forced == [10]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('name', ['icdbnetserver.exe', 'icdbserver.exe',
|
||||
'ReuseBlockImporter.exe', 'wscript.exe'])
|
||||
def test_force_preserves_servers_and_unsupported_processes_even_with_confirmed_scope(tmp_path, monkeypatch, name):
|
||||
from cbb_refresh_verify import residual_sessions as sessions
|
||||
library = tmp_path/'lib.lmc'; library.touch()
|
||||
process = row(10, tmp_path/'ReusableBlocksLP/A/Work/A.prj', name=name)
|
||||
monkeypatch.setattr(sessions, 'query_process_snapshot', lambda: [process.copy()])
|
||||
monkeypatch.setattr(sessions, '_process_identity', lambda r: {**OWNERSHIP, 'created_handle': 'old', 'image': r['executable']})
|
||||
monkeypatch.setattr(sessions, '_process_windows', lambda _: {})
|
||||
monkeypatch.setattr(sessions, '_force_close', lambda *a, **kw: pytest.fail('protected process was force terminated'))
|
||||
plan = sessions.inspect_residual_sessions(library)
|
||||
assert plan['sessions'][0]['scope_confirmed']
|
||||
result = sessions.release_residual_sessions(plan, tmp_path.parent/'release-evidence'/tmp_path.name, force=True)
|
||||
assert result['status'] == 'PARTIAL'
|
||||
assert result['sessions'][0]['release_status'] == 'WAITING'
|
||||
assert result['sessions'][0]['force_allowed'] is False
|
||||
|
||||
|
||||
@pytest.mark.parametrize('name', ['icdbserver.exe', 'cdbsvr.exe', 'python.exe'])
|
||||
def test_direct_force_cannot_request_a_terminate_handle_for_database_server(monkeypatch, name):
|
||||
from cbb_refresh_verify import residual_sessions as sessions
|
||||
process = {'pid': 10, 'name': name, 'scope_confirmed': True,
|
||||
'image': 'C:/Mentor/'+name, 'created_handle': 'creation'}
|
||||
monkeypatch.setattr(sessions, '_process_handle', lambda *a, **kw: pytest.fail('opened terminate-capable server handle'))
|
||||
assert sessions._force_close(process)['release_status'] == 'WAITING'
|
||||
|
||||
|
||||
def test_force_writes_exact_consent_before_any_native_action(tmp_path, monkeypatch):
|
||||
import json
|
||||
from cbb_refresh_verify import residual_sessions as sessions
|
||||
library = tmp_path/'lib.lmc'; library.touch()
|
||||
process = row(10, tmp_path/'ReusableBlocksLP/A/Work/A.prj', name='ExpeditionPCB.exe')
|
||||
monkeypatch.setattr(sessions, 'query_process_snapshot', lambda: [process.copy()])
|
||||
monkeypatch.setattr(sessions, '_process_identity', lambda r: {**OWNERSHIP, 'created_handle': 'old', 'image': r['executable']})
|
||||
monkeypatch.setattr(sessions, '_process_windows', lambda _: {})
|
||||
evidence = tmp_path.parent/'release-evidence'/tmp_path.name
|
||||
def force(actual, **kwargs):
|
||||
consent = json.loads(next(evidence.glob('sessions-*/consent.json')).read_text(encoding='utf-8'))
|
||||
assert consent['library'] == str(library.resolve())
|
||||
assert consent['mode'] == 'force_document_clients'
|
||||
assert consent['sessions'][0]['pid'] == actual['pid']
|
||||
assert consent['sessions'][0]['created_handle'] == actual['created_handle']
|
||||
return {'release_status': 'WAITING', 'detail': 'not exited'}
|
||||
monkeypatch.setattr(sessions, '_force_close', force)
|
||||
plan = sessions.inspect_residual_sessions(library)
|
||||
result = sessions.release_residual_sessions(plan, evidence, force=True)
|
||||
assert Path(result['consent_path']).is_file()
|
||||
assert result['status'] == 'PARTIAL'
|
||||
|
||||
|
||||
def test_unwritable_force_consent_prevents_all_native_actions(tmp_path, monkeypatch):
|
||||
from cbb_refresh_verify import residual_sessions as sessions
|
||||
library = tmp_path/'lib.lmc'; library.touch()
|
||||
process = row(10, tmp_path/'ReusableBlocksLP/A/Work/A.prj', name='ExpeditionPCB.exe')
|
||||
monkeypatch.setattr(sessions, 'query_process_snapshot', lambda: [process.copy()])
|
||||
monkeypatch.setattr(sessions, '_process_identity', lambda r: {**OWNERSHIP, 'created_handle': 'old', 'image': r['executable']})
|
||||
monkeypatch.setattr(sessions, '_process_windows', lambda _: {})
|
||||
plan = sessions.inspect_residual_sessions(library)
|
||||
original = Path.open
|
||||
def deny(path, *args, **kwargs):
|
||||
if path.name == 'consent.json': raise PermissionError('cannot record consent')
|
||||
return original(path, *args, **kwargs)
|
||||
monkeypatch.setattr(Path, 'open', deny)
|
||||
monkeypatch.setattr(sessions, '_force_close', lambda *a, **kw: pytest.fail('termination preceded durable consent'))
|
||||
with pytest.raises(PermissionError, match='cannot record consent'):
|
||||
sessions.release_residual_sessions(plan, tmp_path.parent/'release-evidence'/tmp_path.name, force=True)
|
||||
|
||||
|
||||
def test_current_process_handle_identity_uses_real_windows_api():
|
||||
import os
|
||||
from cbb_refresh_verify.residual_sessions import _process_identity
|
||||
identity = _process_identity({'pid': os.getpid()})
|
||||
assert identity['created_handle'] and Path(identity['image']).is_file()
|
||||
assert identity['owner_sid'].startswith('S-1-')
|
||||
assert isinstance(identity['session_id'], int)
|
||||
assert identity['force_user_confirmed'] is True
|
||||
|
||||
|
||||
def test_force_checks_exact_handle_before_ending_owned_test_helper():
|
||||
@pytest.mark.parametrize('ownership', [{}, {'owner_sid': 'S-1-other', 'session_id': 1,
|
||||
'force_user_confirmed': False}])
|
||||
def test_force_never_opens_terminate_handle_without_current_user_and_session(monkeypatch, ownership):
|
||||
from cbb_refresh_verify import residual_sessions as sessions
|
||||
process = {'pid': 10, 'name': 'ExpeditionPCB.exe', 'scope_confirmed': True,
|
||||
'created_handle': 'creation', 'image': 'C:/Mentor/ExpeditionPCB.exe', **ownership}
|
||||
monkeypatch.setattr(sessions, '_process_handle', lambda *a, **kw: pytest.fail('opened unowned process'))
|
||||
assert sessions._force_close(process)['release_status'] == 'WAITING'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('other_user,other_session', [(True, False), (False, True), (False, False)])
|
||||
def test_force_ownership_checks_user_sid_and_windows_session(monkeypatch, other_user, other_session):
|
||||
import os
|
||||
import win32api, win32process, win32security, win32ts
|
||||
from cbb_refresh_verify import residual_sessions as sessions
|
||||
closed = []
|
||||
monkeypatch.setattr(win32process, 'GetProcessId', lambda _: 10)
|
||||
monkeypatch.setattr(win32api, 'GetCurrentProcess', lambda: 999)
|
||||
monkeypatch.setattr(win32security, 'OpenProcessToken', lambda process, access:
|
||||
SimpleNamespace(process=process, Close=lambda: closed.append(process)))
|
||||
monkeypatch.setattr(win32security, 'GetTokenInformation', lambda token, kind:
|
||||
('other' if other_user and token.process == 123 else 'current', 0))
|
||||
monkeypatch.setattr(win32security, 'ConvertSidToStringSid', lambda sid: 'S-1-'+sid)
|
||||
monkeypatch.setattr(win32ts, 'ProcessIdToSessionId', lambda pid:
|
||||
2 if other_session and pid != os.getpid() else 1)
|
||||
assert sessions._force_ownership(123, 10)['force_user_confirmed'] is (not other_user and not other_session)
|
||||
assert closed == [123, 999]
|
||||
|
||||
|
||||
def test_unreadable_force_ownership_does_not_hide_cooperative_identity(monkeypatch):
|
||||
from contextlib import nullcontext
|
||||
from cbb_refresh_verify import residual_sessions as sessions
|
||||
monkeypatch.setattr(sessions, '_process_handle', lambda _: nullcontext(123))
|
||||
monkeypatch.setattr(sessions, '_handle_identity', lambda _: {'created_handle': 'creation', 'image': 'pcb.exe'})
|
||||
def denied(*args): raise PermissionError('token inaccessible')
|
||||
monkeypatch.setattr(sessions, '_force_ownership', denied)
|
||||
identity = sessions._process_identity({'pid': 10})
|
||||
assert identity['created_handle'] == 'creation' and identity['force_user_confirmed'] is False
|
||||
|
||||
|
||||
def test_force_refuses_actual_unsupported_test_helper():
|
||||
import subprocess
|
||||
import sys
|
||||
from cbb_refresh_verify.residual_sessions import _process_identity, _force_close
|
||||
@@ -178,16 +292,36 @@ def test_force_checks_exact_handle_before_ending_owned_test_helper():
|
||||
creationflags=subprocess.CREATE_NO_WINDOW)
|
||||
try:
|
||||
process = {'pid': child.pid, **_process_identity({'pid': child.pid})}
|
||||
changed = {**process, 'created_handle': 'different process'}
|
||||
assert _force_close(changed)['release_status'] == 'IDENTITY_CHANGED'
|
||||
assert _force_close(process)['release_status'] == 'WAITING'
|
||||
assert child.poll() is None
|
||||
assert _force_close(process)['release_status'] == 'RELEASED'
|
||||
assert child.wait(3) == 1
|
||||
finally:
|
||||
if child.poll() is None:
|
||||
child.terminate(); child.wait(3) # This test's sleep-only helper.
|
||||
|
||||
|
||||
def test_supported_force_revalidates_exact_handle_before_termination(monkeypatch):
|
||||
from contextlib import nullcontext
|
||||
import win32api, win32con, win32event
|
||||
from cbb_refresh_verify import residual_sessions as sessions
|
||||
process = {'pid': 10, 'name': 'ExpeditionPCB.exe', 'scope_confirmed': True,
|
||||
'created_handle': 'creation', 'image': 'C:/Mentor/ExpeditionPCB.exe', **OWNERSHIP}
|
||||
monkeypatch.setattr(sessions, '_process_handle', lambda *a, **kw: nullcontext(123))
|
||||
monkeypatch.setattr(sessions, '_handle_identity', lambda _: {
|
||||
'created_handle': 'creation', 'image': 'C:/Mentor/ExpeditionPCB.exe'})
|
||||
monkeypatch.setattr(win32event, 'WaitForSingleObject', lambda handle, timeout:
|
||||
win32con.WAIT_OBJECT_0 if timeout else win32con.WAIT_TIMEOUT)
|
||||
monkeypatch.setattr(sessions, '_force_ownership', lambda *args: dict(OWNERSHIP))
|
||||
calls = []
|
||||
monkeypatch.setattr(win32api, 'TerminateProcess', lambda handle, code: calls.append((handle, code)))
|
||||
assert sessions._force_close({**process, 'created_handle': 'reused'})['release_status'] == 'IDENTITY_CHANGED'
|
||||
assert not calls
|
||||
assert sessions._force_close({**process, 'session_id': 2})['release_status'] == 'IDENTITY_CHANGED'
|
||||
assert sessions._force_close({**process, 'owner_sid': 'S-1-other'})['release_status'] == 'IDENTITY_CHANGED'
|
||||
assert not calls
|
||||
assert sessions._force_close(process)['release_status'] == 'RELEASED'
|
||||
assert calls == [(123, 1)]
|
||||
|
||||
|
||||
def test_partial_desktop_enumeration_never_offers_normal_close(monkeypatch):
|
||||
import win32gui, win32service
|
||||
from cbb_refresh_verify.residual_sessions import _process_windows, close_target
|
||||
|
||||
Reference in new issue
Block a user