Compare commits
562 Commits
c42348eff5
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
| bf6f7658fd | |||
| cdcb178e34 | |||
| db12ae2dc0 | |||
| 39dfb52542 | |||
| 7fa73ddfb0 | |||
| 68b44ef447 | |||
| 420e72876d | |||
| 02682fcfcd | |||
| 08c3977da9 | |||
| 9b3e6c7d00 | |||
| 1ab2bca41d | |||
| a2c3a2157a | |||
| adc26fb158 | |||
| e472db67d5 | |||
| 76aa728312 | |||
| 96b1f86501 | |||
| 0a3c37ab8c | |||
| 5e7bbc9144 | |||
| 68710e5025 | |||
| 7ea31e160a | |||
| 9c77b6ce5c | |||
| b5eff81dbc | |||
| d88e820a1c | |||
| e17474c80d | |||
| cf447a8fe6 | |||
| bfc369062c | |||
| 7261b18539 | |||
| 8e415212fa | |||
| 9789b01acd | |||
| 386c999720 | |||
| 85915d8a57 | |||
| c80d5e79a5 | |||
| b7ead15108 | |||
| 91d35edb9c | |||
| b9d13e8856 | |||
| feb5463445 | |||
| 74db4db08b | |||
| b8cecf309d | |||
| 1d344a0c08 | |||
| 2ed9bb4892 | |||
| 489f6acb45 | |||
| 32f55e8def | |||
| e06c11e7b0 | |||
| 5a3f39b05b | |||
| 6ef591ce13 | |||
| 7013b6ce65 | |||
| 65fa9137b8 | |||
| 06a3811331 | |||
| 34fc3ce7a9 | |||
| 7db16e93ee | |||
| 4a8015d43a | |||
| a0d3b8a189 | |||
| a8b4c35be2 | |||
| 88de7050a0 | |||
| b4c24713b9 | |||
| 8aff5ece00 | |||
| 9796aa6b47 | |||
| 827b282001 | |||
| 738aa0b1c2 | |||
| 261e3b6c41 | |||
| 8c11c7fdf1 | |||
| 361226b24d | |||
| 75a1e6238e | |||
| 7ee65d9cd0 | |||
| fb40fec2d1 | |||
| 33993296b3 | |||
| 117398cfd9 | |||
| 6dc8b003ba | |||
| 3c1eada677 | |||
| e61af09c2e | |||
| bbc547e976 | |||
| 596ba86232 | |||
| aeb89047d8 | |||
| 6b371becd4 | |||
| bd257c6827 | |||
| 447f3c8bf0 | |||
| 46556dbb56 | |||
| 37cf0ff444 | |||
| f698f97889 | |||
| d8d633ddb2 | |||
| 075cf47fc2 | |||
| 5d2d9530ba | |||
| 7aeb9c6545 | |||
| 510d15d546 | |||
| cb424a0ce7 | |||
| b300784092 | |||
| 89e383a196 | |||
| e7b36a664b | |||
| f07bd3c776 | |||
| be1ce9ef3a | |||
| 73e69ef2b8 | |||
| 70c5aa2b4d | |||
| 3d61456d61 | |||
| f8469aa837 | |||
| 8969bee6a9 | |||
| cf432c00bd | |||
| 99f22b4148 | |||
| d36462ae7a | |||
| bb1c3ba97b | |||
| c1334df736 | |||
| 8232f3a9ee | |||
| f96104245e | |||
| 9bda64ec4b | |||
| 1118e0418e | |||
| ad7b37d200 | |||
| 9c3ab5fcb7 | |||
| 81c405292e | |||
| 9c0a7cca46 | |||
| 238050eebf | |||
| a274c3d824 | |||
| c398f36318 | |||
| 0914879915 | |||
| 2717d7c23b | |||
| 027eb354fd | |||
| 029f4aab50 | |||
| 65d8552584 | |||
| 276260ae3b | |||
| 0be9e2ab97 | |||
| 14c29f48bf | |||
| 3cb0104e88 | |||
| ee9b403c4f | |||
| d5cb6ba2c0 | |||
| 2fe0582d7e | |||
| 3ddb083b4c | |||
| fa68b0ea02 | |||
| 65197ca1a2 | |||
| 127f07e1ef | |||
| 53013eb2d8 | |||
| 178ef651f9 | |||
| 6d3fcaaa73 | |||
| 4909946104 | |||
| 2859d9ebfc | |||
| 41a5e4d187 | |||
| 71b8595742 | |||
| 85654d7b43 | |||
| d93ca7b8c2 | |||
| ca81dcbdd2 | |||
| f05ce80269 | |||
| 2011c8d6b9 | |||
| cfc7168ace | |||
| 616e913f3e | |||
| e6a724ba8e | |||
| e1a2df83f7 | |||
| f98ba08910 | |||
| f5ef0efedd | |||
| 3ca7e1936f | |||
| 6c4595e87f | |||
| f83c75678c | |||
| 610c40afa5 | |||
| cde1297c4a | |||
| e6beb9b4bf | |||
| e573ee40d5 | |||
| ccfcc7c3d2 | |||
| 470465dfbd | |||
| 30a12dd0fa | |||
| d5afd932e8 | |||
| a6d4d0d903 | |||
| da4cb92713 | |||
| d5de462f19 | |||
| 23693ef66c | |||
| 7c3d40ff19 | |||
| 2624b32b1c | |||
| 3180b09659 | |||
| 9f7d36e7dc | |||
| ef1b835910 | |||
| d25b73bacd | |||
| 24c2624ce5 | |||
| 1f23e8a965 | |||
| 2e2ce62665 | |||
| 4735913cdc | |||
| 2ff319197d | |||
| b322140b99 | |||
| 81d8901bf0 | |||
| 1c6fe5793b | |||
| 601f7ae0e6 | |||
| d042890d50 | |||
| d8147bd0fd | |||
| 2adcd75bdc | |||
| 71b077c41b | |||
| 4ca420302f | |||
| b500618a55 | |||
| 6cf69a00fb | |||
| 2dabb07a59 | |||
| ed122145ed | |||
| 16418e48a0 | |||
| 805e3aac67 | |||
| aaa669f536 | |||
| a33d8ecdfd | |||
| cbc7291f7b | |||
| 4c5a52d85f | |||
| 813ef65dbd | |||
| ccabcc68bc | |||
| 59bf74760c | |||
| 736158f2ad | |||
| bcbf1d006f | |||
| e1ad6becb0 | |||
| 9f986e16e8 | |||
| b3de2b7128 | |||
| fe5269208f | |||
| 92969c9c85 | |||
| 129d37f9e2 | |||
| b9bcf33834 | |||
| a5fd97b013 | |||
| d430684322 | |||
| 48af177dce | |||
| eab617f741 | |||
| ab1ad689df | |||
| be5e9fd436 | |||
| 3215d51154 | |||
| 5c207d1fe5 | |||
| 703461dab1 | |||
| 4382446ebd | |||
| 3df31d0c7a | |||
| 6123d03f92 | |||
| ebc493361e | |||
| 4a3c4e9b7e | |||
| fc81cbbd36 | |||
| db441d9d99 | |||
| fac3c5355c | |||
| 3aa7c728d5 | |||
| 649d4a0616 | |||
| a84c64e26f | |||
| fe94b32d42 | |||
| 849640f467 | |||
| 5e2d3dd1bc | |||
| 262e11feaf | |||
| 64efb49996 | |||
| 16fac72858 | |||
| eff8c6a00e | |||
| b64628de0b | |||
| b33f0f93c9 | |||
| c4366539ca | |||
| b8d3fa2ba1 | |||
| 9ec0da1b2c | |||
| b9a096c53a | |||
| b2adddbc8e | |||
| fd46999946 | |||
| 76e9c355b4 | |||
| c207573595 | |||
| 15a6c7c710 | |||
| 4af0ea8152 | |||
| 48813bba6f | |||
| d549a782fd | |||
| 5f5d684c44 | |||
| e1487fbf10 | |||
| 6112a9f447 | |||
| f60f641069 | |||
| c3b07d6766 | |||
| 015c556ced | |||
| 1786bab0a0 | |||
| 5bf2f2caf1 | |||
| ab3fa9ca83 | |||
| 3ef43ca926 | |||
| 362ba8d75f | |||
| 90b691af84 | |||
| 414050935e | |||
| 20cf3bfec7 | |||
| a2e2f4b463 | |||
| 6c81c0bc0a | |||
| c25acd6093 | |||
| 477245f5db | |||
| 91fb2b48dd | |||
| 726fbccf54 | |||
| 1baa384cbe | |||
| 2fea619da3 | |||
| 9cbe65c844 | |||
| f21f2e551d | |||
| 01c6dc1d02 | |||
| b4c38d0f0c | |||
| 1ab5ca026b | |||
| a05ce8c86d | |||
| 243c3fa619 | |||
| 8bb2679e43 | |||
| d0d3058651 | |||
| a16567b8bf | |||
| 66c3e060ae | |||
| 19d59915ea | |||
| 6b737b12b1 | |||
| 484d530e65 | |||
| fd180e576f | |||
| 967da5b43b | |||
| 6ad15fcf93 | |||
| 795af1da71 | |||
| 65c6b99cf2 | |||
| 420c2e0783 | |||
| 3cacdca861 | |||
| ade49c0935 | |||
| 02480d4fbc | |||
| 87bb647efb | |||
| a0cec479b6 | |||
| 91baba8fcc | |||
| 9688707d82 | |||
| 509114360d | |||
| cfd371ce18 | |||
| 51a956a878 | |||
| 2a3baae301 | |||
| 10fc22b87e | |||
| 8825cd966f | |||
| 69a7f8e1b5 | |||
| 01a6313fe7 | |||
| e7cfa21fda | |||
| 68f1b56acf | |||
| b4da0deacb | |||
| 180403cb17 | |||
| 67c182ce18 | |||
| 05042e5e36 | |||
| aed5fbf046 | |||
| 00ef22823f | |||
| c05a6d93b0 | |||
| ec2615a9d2 | |||
| 2a0b34e056 | |||
| 4555a3bdad | |||
| 681606dad0 | |||
| aa7093b53b | |||
| 17cb91a315 | |||
| 0adfb244b2 | |||
| c6e60cb6c4 | |||
| c713925ac7 | |||
| 0b056c6fee | |||
| 484b176cd6 | |||
| dd1eea2106 | |||
| 63cc772e8d | |||
| 3b4d81e630 | |||
| b6f5eb2535 | |||
| a8f5f66647 | |||
| df21d365ec | |||
| a2b40b7922 | |||
| 3c91f0f813 | |||
| a6c4161719 | |||
| 78ca2a6744 | |||
| 21a95c7f50 | |||
| c43d7ee1ad | |||
| d0b66bf105 | |||
| 44421dc5aa | |||
| 8fa7631ec4 | |||
| b62cfad48d | |||
| 625f207e08 | |||
| 29bfa8fbf9 | |||
| b0582eb66a | |||
| 9090b1b511 | |||
| e3d146aa21 | |||
| 177881c423 | |||
| 3c42069673 | |||
| 00ac436ae2 | |||
| 302d1245cd | |||
| fa0ca66a05 | |||
| 711e8beb2b | |||
| 9ac6ed51d3 | |||
| efd5d881dc | |||
| 0793159cbb | |||
| 51b6f1ab9f | |||
| 29d0c50f07 | |||
| adbf2eb182 | |||
| b392b84f21 | |||
| 5c73be486d | |||
| 308742b7a6 | |||
| 8cfe076012 | |||
| 646af887d1 | |||
| 1e0bfe03d4 | |||
| 9934bea05a | |||
| d0079ba1a1 | |||
| 4dda768801 | |||
| f6eef9d8eb | |||
| 16a84f9df4 | |||
| 3c92bf54b0 | |||
| fb33924473 | |||
| 46fa06a612 | |||
| 5ee31dbf7b | |||
| 98868a60d0 | |||
| 3903c9a196 | |||
| ef487957b2 | |||
| 895e881807 | |||
| 54f111e8b1 | |||
| 370a9eea96 | |||
| 4988c24618 | |||
| fe6216c533 | |||
| 10990a43c8 | |||
| e538ea36e3 | |||
| 63e6d3f867 | |||
| c72271aa8a | |||
| 2e545b50da | |||
| 6acc5c1908 | |||
| c54cd808f4 | |||
| de21669ad5 | |||
| dcee4199ab | |||
| b5da1c8c57 | |||
| c1e34c307e | |||
| 2969805e4e | |||
| 3f11704d10 | |||
| 300094e792 | |||
| 75c1897522 | |||
| 5e02c1c38f | |||
| 9663279594 | |||
| 122940c0e4 | |||
| e9dc13689a | |||
| f62b017cc7 | |||
| dbcbc5bd41 | |||
| 1145df682e | |||
| 3e5a5fde81 | |||
| b62981ff80 | |||
| 31a7c8a88a | |||
| 7757b9c6fc | |||
| 0038d46c9a | |||
| cea3930b94 | |||
| f627cee9c0 | |||
| 14cb283172 | |||
| 522cfbfda6 | |||
| 1ce0c5955f | |||
| 9377fa1678 | |||
| 92246c9734 | |||
| 1fee9755d7 | |||
| 205bddb3b8 | |||
| 206c588608 | |||
| bd929d98fc | |||
| 990f4c018d | |||
| 5da4ab3ebd | |||
| 3d2f3f59b2 | |||
| 58c2e14c38 | |||
| 58f605609d | |||
| f42aa14033 | |||
| 818775b311 | |||
| 4e01cbc2c3 | |||
| 1f8ab8e3b3 | |||
| 846b77f5b4 | |||
| da276ff15a | |||
| 81e0005628 | |||
| b850c3a47f | |||
| c5e894d9b3 | |||
| 74066bbe27 | |||
| 6084465e23 | |||
| d6fe3ae62a | |||
| 90b7cc6c48 | |||
| 9b6afe3efd | |||
| cbfe296279 | |||
| 105c230cb1 | |||
| 944595ad32 | |||
| f088cb81ba | |||
| 003783a593 | |||
| 4f97e72ac9 | |||
| c582508ae5 | |||
| 8f31184b7d | |||
| 8e99b3b4c0 | |||
| 7926e8bb46 | |||
| 76098ffcd4 | |||
| 1cc4ccd258 | |||
| 20e16c934c | |||
| ec4ad984c1 | |||
| 094307e18b | |||
| baaf0a183c | |||
| dc6410dfad | |||
| 3777e50564 | |||
| 40e07aa08e | |||
| 9dd288b3ad | |||
| f313c5e62e | |||
| f9d4e2f514 | |||
| d603a2f66e | |||
| 49fbbcfaeb | |||
| e7a126a9fc | |||
| 5fc75d93fd | |||
| 3b7dbfa082 | |||
| d131416673 | |||
| f0f607ea46 | |||
| 2a38b6ac76 | |||
| 75648ea28b | |||
| 84af475683 | |||
| 3ce9cc3657 | |||
| 1c675e9153 | |||
| 92ff6a0d8c | |||
| 174ad952dc | |||
| 0a8fe68d0a | |||
| 8997a46b74 | |||
| 5fbf53601c | |||
| 0c1702acbc | |||
| 2dc919e8a4 | |||
| 95865f0e9b | |||
| 2f96709341 | |||
| 46523db2bd | |||
| 31ca9407a6 | |||
| e62b4a5baf | |||
| 7a2980e2f1 | |||
| 0d4978953f | |||
| 7df05ccc27 | |||
| 294eb163cd | |||
| aada53b27a | |||
| 5198d3dc7f | |||
| c86cead5c2 | |||
| 321ab22111 | |||
| 5f81e65684 | |||
| 3e3748b985 | |||
| 55e0178d5c | |||
| 1c31e6bcb8 | |||
| 353af72265 | |||
| c5ea3a7b59 | |||
| 7fc77f2790 | |||
| cc95590196 | |||
| cf6d19d09d | |||
| 5fd7bf524a | |||
| ad7df925ae | |||
| 591307c13e | |||
| 537a4f524d | |||
| 1a7bff6a19 | |||
| c8c4c2bcde | |||
| 35f371ed74 | |||
| 63cf4c6f0c | |||
| 0e416cac0a | |||
| 7ed2c29842 | |||
| 2b45a59c5d | |||
| d30f54639f | |||
| 0bbe42eaa1 | |||
| 6d222ea491 | |||
| 7a6f997180 | |||
| 555d1b4afc | |||
| 883601a72b | |||
| 6b12a7b75e | |||
| 0121f55f1e | |||
| c07659c0e0 | |||
| ded7cf0d6d | |||
| f7f4554a36 | |||
| 850e23646a | |||
| ff073450dc | |||
| e96b5d49f9 | |||
| b0b57f8d54 | |||
| eedbf13712 | |||
| 035c5feeb8 | |||
| b02d7a92bb | |||
| 75f267c4c9 | |||
| 7dcd93c326 | |||
| 591eaac881 | |||
| 6ab50fed1f | |||
| a58d79b793 | |||
| bf75e265ab | |||
| 8698d1804b | |||
| 344bdc4da5 | |||
| 6a4fa220de | |||
| a61e041e58 | |||
| c81a6615ba | |||
| 280e57896b | |||
| af1e0a86b2 | |||
| c22b06deba | |||
| d95292c95d | |||
| 41013dcab3 | |||
| 92997b40dc | |||
| 5fe7135e2c | |||
| 61fc88c8a8 | |||
| d0110cf406 | |||
| 80668a07bd | |||
| 6721c8a224 | |||
| 3dbd6cd57c | |||
| 92015da4e0 | |||
| 1911de2c3c | |||
| b5e7bc8b3c | |||
| 4d93d2580b | |||
| 6dd7858619 | |||
| ff58ad4f60 | |||
| dbfd5e7a7e | |||
| 5919e29969 | |||
| ede5275d3a | |||
| 4f33eccfa7 | |||
| 7c8dd654ba | |||
| 3b7489a7b0 | |||
| 45d08929e7 | |||
| cad3bcb6bf |
@@ -0,0 +1,16 @@
|
||||
---
|
||||
name: sister-project-history
|
||||
description: Use when you need the detailed change history, live-gate records, redundancy/auth/ACL behaviour, or ScadaBridge consumer-impact notes for a sister project (OtOpcUa, HistorianGateway, BTDB) — the scadaproj root CLAUDE.md keeps only a short summary row per project; the full narrative lives in this directory.
|
||||
---
|
||||
|
||||
# Sister project history
|
||||
|
||||
The root `CLAUDE.md` index keeps one short row per sister project. The full narrative rows that used to live
|
||||
in that table were moved here **verbatim** on 2026-09-03 (they were ~57k characters loading into every session):
|
||||
|
||||
- `otopcua.md` — OtOpcUa: v3 dual-namespace address space, every driver, redundancy/mesh program, data-plane auth + ACL enforcement, deferment register, the authoring-vs-deploy-gate parity arc, and the per-issue consumer-impact record for ScadaBridge.
|
||||
- `historiangateway.md` — HistorianGateway: ArchReview cycles, pending.md items, session pools, datatype gaps, SQL-path workarounds, PR/commit history.
|
||||
- `btdb.md` — BTDB (Batch Tracking Database, added 2026-09-03): schema + sproc write contract, Historian/CLR coupling, Galaxy/MESAPI/ScadaBridge edges, the DARS `BatchTracker_DB` fork, and the gap analysis.
|
||||
|
||||
Read the file for the project you are working against. When a sister repo tells you to "update its entry in
|
||||
`scadaproj/CLAUDE.md`", append the detail to the file here and keep the index row to a few lines.
|
||||
@@ -0,0 +1,207 @@
|
||||
# BTDB (Batch Tracking Database) — index history + analysis
|
||||
|
||||
> Added 2026-09-03 as a sister project. **This file is the authoritative place for BTDB detail — append here and keep the root index row short.** Everything below was verified from source on 2026-09-03 unless marked _(inferred)_.
|
||||
|
||||
| Project | Location | Stack | Repo | Summary |
|
||||
|---|---|---|---|---|
|
||||
| **BTDB** (Batch Tracker) | `~/Desktop/btdb` (case-insensitive FS: also `BTDB`) | SQL Server 2016+ SSDT project + SQL CLR (net472) · manager: **Blazor Web App net10.0** on `feat/manager-blazor` (§8; `master` still carries the EOL net6.0 MVC app) | **`ZimmerBiomet/BTDB`** on the corporate Gitea `wonder-app-vd03.zmr.zimmer.com:3000` (`master` @ `d147c10e`, 2023-07-26). **Not** on `gitea.dohertylan.com`. | The `BT` SQL Server database that is the plant's **batch/cycle/work-order system of record for data collection**: Galaxy machine objects call its `StartMachineBatch`/`StartMachineCycle`/`End*`/`AddMachineBatchWorkOrder`/`AddOtherData*` sprocs; reports pull time-series per batch out of the AVEVA Historian through its CLR sprocs (`OPENQUERY(INSQL, … WideHistory …)` + `Runtime.dbo.*`); MESAPI and ScadaBridge's inbound API resolve `SAPID → Machine.Code` from `dbo.Machine`. `BTDBManager` is a small Windows-service MVC site for machine/group config, batch edits (audited) and cross-environment config import. |
|
||||
|
||||
## 1. What is on disk, and where the truth is
|
||||
|
||||
- `~/Desktop/btdb` is **not a git checkout** — no `.git`, no `CLAUDE.md`, no `README`. It is a file-for-file snapshot of `ZimmerBiomet/BTDB` `master` (the only branch) at its head commit `d147c10e` (2023-07-26, "Update notification system tables to add urgent flag"). Verified by comparing the Gitea tree with the local tree: 170 vs 168 files, the only difference being the remote's `.gitattributes`/`.gitignore`. The repo's `updated_at` of 2024-11-07 is not a commit (the branch head is still 2023-07-26).
|
||||
- `~/Desktop/DARS/WW_ARCH/BatchTracker_DB/` is a **fork of the `Database` project only** (no Manager), modified 2026-08-13, also not under git (DARS is not a repo). Substantive differences vs the snapshot, all matching the DARS sprint-1 spec `DARS/sprints/sprint1/bt_db_changes.md`:
|
||||
- new table `MachineBatchTransfer` (source/dest batch chain for mid-run reactor failure; `TransferType` CHECK `'mid_run_failure'`; three indexes) + sproc `AddMachineBatchTransfer` (linear-chain guard);
|
||||
- `MachineBatchWO` gains `ContainerID NVARCHAR(64) NULL` + `MoveOutTimestamp DATETIME2 NULL` with filtered indexes (Camstar container traceability; mirrors the `SAPID`/`ZTag` idiom);
|
||||
- new CLR sproc `GetLinkedBatchTSV` (+ `_Wrapper`) that walks the transfer chain and stitches TSVs, and `LinkedBatchAlarm_Wrapper`;
|
||||
- `StartMachineBatch.sql`, `MachineBatch.sql`, `AuditLogMachineBatch.sql` differ **only** in BOM/CRLF → LF normalization (no logic change).
|
||||
- Reference doc for the schema: `DARS/WW_ARCH/BatchTracker_Reference.md` (states 22 tables / 35 SQL sprocs / 4 CLR sprocs / 5 CLR UDFs / 6 table types / 1 aggregate).
|
||||
- **Resolved 2026-09-03 — the divergence is closed locally:** `~/Desktop/btdb` was turned into a real checkout (`git init` + fetch of `ZimmerBiomet/BTDB`, `master` tracking `origin/master`; the snapshot was tree-identical apart from exec bits copied from Windows, which were cleared). The DARS fork's transfer-chain work was migrated onto branch **`feat/machine-batch-transfer`** as one commit: the five new objects, the two `MachineBatchWO` columns, and the `.sqlproj` wiring **including the `Compile` entry for `GetLinkedBatchTSV.cs` that the fork had omitted** (without it the CLR sproc is never built and its wrapper fails at deploy). The BOM/CRLF re-saves were not carried over. The sprint-1 plan (`bt_db_changes.md`, overview, diagrams) and `BatchTracker_Reference.md` now live under `btdb/docs/`. **The branch is local only — not pushed to the corporate Gitea.** `DARS/WW_ARCH/BatchTracker_DB/` is now superseded and should be deleted or replaced by a pointer once the branch is pushed. A second commit on the same branch carried the two columns through the Manager's batch-edit path: `MachineBatchWOType` (appended last — the TVP binds by ordinal and `ToDataTable` emits properties in declaration order, so the view model's property order must keep matching), `AuditLogMachineBatchWO` (`Prev_`/current pairs), the DTOs and view model, `SaveBatchEdit.sql` (MERGE change-detection with `COALESCE` because both columns are NULL-able, OUTPUT and the three audit inserts), and the Kendo work-order grid in `Views/BatchEdit/Edit.cshtml` (masked timestamp editor like the cycle grid). `LookupBatchInfo.sql` is `SELECT *` so it needed nothing. Not touched: the Telerik `BatchEditAuditLogReport.trdp` (binary package; open it in the Telerik designer to add the audit columns) and the batch search grid (`SearchBatches.sql`), which still lists only work-order numbers. Nothing here was built or run: the Manager needs Telerik + Windows, and the SSDT project needs MSBuild; a throwaway compile of the Manager retargeted to .NET 10 on the Mac showed no errors in the touched files.
|
||||
|
||||
## 2. Solution shape
|
||||
|
||||
`BTDB.sln` (VS 2022) = two projects:
|
||||
|
||||
| Project | Kind | Notes |
|
||||
|---|---|---|
|
||||
| `Database/Database.sqlproj` | SSDT, `Sql130DatabaseSchemaProvider` (SQL Server 2016+), CLR assembly targets **net472**, C# namespace `BT` | 22 tables, 6 table types, ~35 T-SQL sprocs, 3 CLR sprocs (`GetTSV`, `GetMachineBatchTSV`, `GetCycleTSV`), 5 CLR UDFs (`GetAggregateValues`, `CheckTriggered`, `WhenTriggered`, `WhenCleared`, `StringCompare`), 1 CLR aggregate (`StringJoin`), 1 T-SQL TVF (`GenerateShifts`), 1 trigger (`TrgNotification` → `AuditLogNotification`). Requires `CLR enabled` on the instance. |
|
||||
| `Manager/BTDBManager.csproj` (**`master` only — deleted on `feat/manager-blazor`, see §8**) | ASP.NET Core MVC, **net6.0** (out of support since 2024-11), Dapper 2.0, `System.Data.SqlClient`, `System.DirectoryServices` (Windows-only LDAP), `Microsoft.Extensions.Hosting.WindowsServices`, Kendo UI + Bootstrap, **Telerik Reporting R2 2022** referenced by an absolute `HintPath` into `Program Files (x86)` | Kestrel `http://*:9876`; runs as a Windows service; 13 embedded `.sql` query resources; 3 `.trdp` Telerik audit reports. `Manager/install.bat`/`uninstall.bat` are **leftovers from a different service** (`WWNotificationSystem.exe`) and do not install the Manager. |
|
||||
|
||||
## 3. Database model (what the family writes and reads)
|
||||
|
||||
**Core hierarchy:** `Machine` (`Code` unique; optional unique `ZTag`, `SAPID`; `TimeZone`; `MultipleBatch`/`MultipleCycle` flags; `OtherData` JSON) → `MachineBatch` (start/end operator + UTC timestamps, `OtherData`) → `MachineCycle` (same shape) and `MachineBatchWO` (`WorkOrderNumber`, `ItemNumber`). `MachineGroup` + `MachineGroupMembership` give roll-ups (DARS models one `Machine` per reactor *side*, one `MachineGroup` per unit). `MachineAlarm` is a per-machine alarm catalog (`Severity` 0–999, `FlaggedForMES`).
|
||||
|
||||
**Lifecycle sprocs (the write contract):**
|
||||
|
||||
| Sproc | Behaviour |
|
||||
|---|---|
|
||||
| `StartMachineBatch(@Code, @OperatorID, @o_MachineBatchID OUT)` | Looks up machine by `Code`; unless `MultipleCycle`/`MultipleBatch`, **auto-closes** any open cycle/batch first; inserts with `GETUTCDATE()`. Throws 50000 if machine unknown. |
|
||||
| `EndMachineBatch(@MachineBatchID, @EndOperatorID)` | Closes the open cycle too; throws if not found / already closed. |
|
||||
| `StartMachineCycle(@MachineBatchID, @OperatorID, @o_MachineCycleID OUT)` / `EndMachineCycle` | Cycle must belong to an open batch. |
|
||||
| `AddMachineBatchWorkOrder(@MachineBatchID, @WorkOrderNumber, @ItemNumber, @o OUT)` | Only on open batches. |
|
||||
| `AddOtherDataMachineBatch` / `…MachineBatchWorkOrder` / `…MachineCycle (@ID, @DataKey, @DataValue)` | `JSON_MODIFY` into `OtherData` — via **dynamic SQL that concatenates `@DataKey`/`@DataValue`** into the statement (`sp_executesql` of a built string). Injection surface; callers today are trusted Galaxy scripts. |
|
||||
|
||||
All timestamps are `GETUTCDATE()`; `Machine.TimeZone` is used only at retrieval time (`wwTimeZone=` in report wrappers). This matches the family's all-UTC rule.
|
||||
|
||||
**Historian coupling (the read contract):** the CLR code resolves a machine-relative tag (`<Code>.<local>`; `*.<attr>` shorthand; `|literal|` static columns) to the Historian's global tagname via `Runtime.dbo.TagExtendedPropertyInfo` (`HierarchicalName`), then runs `SELECT … FROM OPENQUERY(INSQL, 'SELECT DateTime, [tag]… FROM WideHistory WHERE … wwTimeZone="UTC" AND <queryParams>')` (`wwRetrievalMode`, `wwResolution`, `wwTimeZone` are passed through **verbatim** from `@queryParams`). Discrete checks read `Runtime.dbo.DiscreteHistory`; alarm wrappers read `Runtime.dbo.Events` (`IsAlarm=1`, `Alarm_OriginationTime`, `Alarm_DurationMs`, `Alarm_UnAckDurationMs`). **Consequence: the `BT` database must live on (or three-part-name-reach) the Historian's SQL instance with the `INSQL` linked server** — it is co-tenant with `Runtime`, which is why it sits on the `wonder-sql-*` boxes.
|
||||
|
||||
**Report wrappers** are per machine family and are the consumers of the CLR layer: Crest (`CrestWide`/`CrestMinMax`/`CrestAlarm`/`CrestCleaner*`), Elma (`ElmaData`, `Elma_Bulk_Query_Nitric`), `ExtruderWide`, `PultrusionWide`, Haas (`HaasStatusReport`, `HaasAlarm`, `QV_Haas*` = QlikView), Solar (`SolarAlarms`/`SolarEvents`), DryHeat (`DryHeatCycleReport`/`Search`/`BulkReport`), PoncePolyPress, `Z002432Wide`/`Z002433Wide`. `GenerateShifts` builds a 3-shift calendar table for these.
|
||||
|
||||
**Auth tables that are not the Manager's:** `UserAuth`, `UserAuthDetails`, `UserAuthRole`, `ApiKey` are ServiceStack's schema — they belong to **MESAPI/WWSupport** (the Camstar-facing REST service, see `mes-delmia-integration-api.md` §1.1: `ApiKeyAuthProvider` + `LdapAuthProvider`, role `MESAPI`), which shares the `BT` database. The Manager authenticates via LDAP only.
|
||||
|
||||
**Notification tables** (`Notification`, `NotificationLog`, audited by trigger) back the separate `WWNotificationSystem` Windows service, which is **not in this repo**.
|
||||
|
||||
## 4. BTDBManager (the config/edit UI) — `master` state; the replacement is §8
|
||||
|
||||
- **Auth:** cookie scheme; `LdapAuthenticationService` binds `LDAP://nam.zimmer.com` with the user's own credentials via `System.DirectoryServices` (so it only runs on a domain-joined Windows host), reads `memberOf`, and keeps only the three configured group DNs. Policies `READONLY` / `MACHINECONFIG` / `BATCHEDIT` map to `ReadOnlySecurityGroup` / `MachineConfigSecurityGroup` / `BatchEditSecurityGroup`; the checked-in DEV config points all three at `UG_WW_APP_ADMIN_DEV`. A global `AuthorizeFilter` makes every controller (incl. `/Api/GetMachines`, `/Api/GetMachineGroups`) require login. This is exactly the AD-group→role problem the family's `ZB.MOM.WW.Auth` 0.3.0 + `ldap_mapping.md` already solve.
|
||||
- **Features:** Machine CRUD (with group memberships + alarm catalog via TVPs `MachineGroupMembershipType`/`MachineAlarmType`), MachineGroup CRUD, batch search/edit (`SaveBatchEdit` writes `AuditLogBatchEdit` + prev/new `AuditLogMachineBatch`/`…WO`/`…Cycle` rows), **MachineConfigImport** (copies machine/group config from another environment's `BT` — sources `QA` and `PROD` are hard-wired in `appsettings.json`), and Telerik `.trdp` audit reports.
|
||||
- **Secrets are checked in:** `appsettings.json` carries plaintext `wonderapp` SQL passwords for DEV/QA/PROD, and `install.bat` carries a domain service-account password. Treat all of them as compromised-by-repo; do not copy them into any other file or reply. This is the pattern `ZB.MOM.WW.Secrets` (`${secret:}`) exists to replace.
|
||||
- **Environment hosts as recorded in 2023:** DEV `wonder-sql-vd01/BT`, QA `wondersqlqa/BT` (`MultiSubnetFailover`), PROD `wondersqlpd/BT`. ScadaBridge's 2026-06-16 design says the DEV BTDB is on **`wonder-sql-vd03/BT`** (db-connection id 1). `mes-delmia-integration-api.md` also says `vd01`. **Host drift is unresolved** — do not assume either without probing.
|
||||
|
||||
## 5. How BTDB relates to the rest of the family
|
||||
|
||||
```
|
||||
Galaxy machine objects ──(script: EXEC StartMachineBatch / StartMachineCycle /
|
||||
($Reactor_Side etc.) AddMachineBatchWorkOrder / AddOtherData* …)──────────┐
|
||||
▼
|
||||
Camstar MES ──HTTPS──▶ MESAPI/WWSupport ──(SELECT Machine by SAPID; alarm catalog; ┌────────────────────┐
|
||||
(ServiceStack, own UserAuth/ApiKey tables) ────────────────▶ │ SQL Server "BT" │
|
||||
│ (BTDB) │
|
||||
ScadaBridge inbound API ──(Database helper, connection "BTDB": SELECT Code FROM │ co-tenant with │
|
||||
(IpsenMESMoveIn, MES alarm-status) ─────────────────────────────────────────────▶ │ Historian Runtime │
|
||||
ScadaBridge site scripts ──(Database.Connection / CachedWrite — customer scripts)─▶ │ + INSQL linked │
|
||||
└─────────┬──────────┘
|
||||
BTDBManager (config, batch edits, env import) ─────────────────────────────────────▶ │ CLR: OPENQUERY(INSQL) WideHistory,
|
||||
SSRS / QlikView / Telerik reports ──(EXEC *_Wrapper, GetMachineBatchTSV …)──────────▶ │ Runtime.dbo.{TagExtendedPropertyInfo,
|
||||
▼ DiscreteHistory, Events}
|
||||
AVEVA Historian (Runtime DB)
|
||||
```
|
||||
|
||||
- **Galaxy → BT** is the primary write path (batches/cycles/work orders/OtherData JSON). DARS `model_info.md` §: "Existing per-machine BT sprocs (`StartMachineBatch`, `StartMachineCycle`, `GetCycleTSV`, `Alarm_Wrapper`, …) work unchanged" — the sprocs are the contract Galaxy scripts bind to.
|
||||
- **ScadaBridge → BT (verified):** the inbound-API script context has a `Database` helper bound to named db-connections; production defines connection **`BTDB`** (id 1), and the `IpsenMESMoveIn` (design 2026-06-16) and MES alarm-status (2026-06-30) methods do `SELECT Code FROM dbo.Machine WHERE SAPID=@s` before `Route.To(instance)`. Template/site scripts expose `Database.Connection(name)` + `Database.CachedWrite(...)`, so site scripts **can** write batches into BT — but **no checked-in ScadaBridge script calls a BT sproc**; any batch logging is customer-site script configuration, not platform code, and the docker rig does **not** seed a `BT` database (`infra/mssql/setup.sql` creates only `ScadaBridgeConfig` + `ScadaBridgeMachineData`; the `InboundDatabaseHelperTests` use a stand-in). ScadaBridge's inbound API is the designated successor of MESAPI's move-in/move-out surface, which is why it needs the same `SAPID → Code` lookup.
|
||||
- **HistorianGateway ↔ BT:** no direct coupling, but both read `Runtime.dbo.Events` (HG's SQL-path `ReadEvents`) and both need the Historian SQL instance. BT's CLR `GetTSV`/`GetAggregateValues` is a bespoke, in-database equivalent of what HG's `ReadRaw`/aggregate retrieval modes do over gRPC — a candidate for consolidation if the report layer is ever re-platformed.
|
||||
- **OtOpcUa / mxaccessgw:** no coupling.
|
||||
- **Break surface:** the sproc signatures + `Machine.Code`/`SAPID`/`ZTag` semantics (Galaxy scripts, MESAPI, ScadaBridge inbound methods all bind to them), the `OtherData` JSON key conventions (DARS sprint 1 defines ~14 new keys with single writers), and the `INSQL`/`Runtime` co-location assumption.
|
||||
|
||||
## 6. Analysis — gaps and recommendations (2026-09-03)
|
||||
|
||||
1. **Push the branch.** ~~Put both copies under git~~ — done locally 2026-09-03 (`feat/machine-batch-transfer`). Remaining: push it to `ZimmerBiomet/BTDB`, review/merge, decide whether BTDB also gets a mirror on `gitea.dohertylan.com` like the other sisters, then delete the superseded `DARS/WW_ARCH/BatchTracker_DB/` copy.
|
||||
2. **Rotate and externalize the checked-in credentials** (three SQL passwords, one domain account). _Externalised on `feat/manager-blazor` (`${secret:btdb/...}` refs, store outside the content root); rotation is a cut-over step (§8)._ The family standard is `ZB.MOM.WW.Secrets` `${secret:}` with an absolute `Secrets:SqlitePath` outside the content root.
|
||||
3. **Manager re-platform** — _done on `feat/manager-blazor`, see §8_: net6.0 is EOL; Telerik is pinned by an absolute machine path; `System.DirectoryServices` binds the user's own credentials on a domain-joined box. A .NET 10 rewrite on the family libs is mostly assembly: Auth 0.3.0 (LDAP + `UG_WW_*` group→role mapping, `FallbackServers`), Theme 0.4.1, Health 0.3.0 (`MapZbHealth`, so Overview can watch it), Telemetry, Configuration, Audit (the batch-edit audit is a natural `ZB.MOM.WW.Audit` writer), Secrets. Keep Dapper + the embedded queries; replace Telerik `.trdp` with server-side rendering only if the three audit reports are still used.
|
||||
4. **Injection surfaces in the SQL layer:** `AddOtherData*` build dynamic SQL from `@DataKey`/`@DataValue`; `GetTSV`/`GetAggregateValues` interpolate tag names and append `@queryParams` raw into `OPENQUERY`. Trusted callers today, but ScadaBridge scripts and the inbound API widen the caller set. Fix `AddOtherData*` with parameterised `JSON_MODIFY` (no dynamic SQL needed), and whitelist `queryParams` to the three `ww*` keys.
|
||||
5. **ServiceStack auth tables** (`UserAuth*`, `ApiKey`) are MESAPI's, not BT's domain. Once ScadaBridge's inbound API fully replaces MESAPI (Ipsen MoveIn is the first slice; ScadaBridge keys already live in the `zbauth` schema via `Auth.ApiKeys.SqlServer` 0.3.0), those tables are dead weight in the schema and should be dropped from the sqlproj rather than carried forward.
|
||||
6. **Host inventory drift:** 2023 config says DEV BT is on `wonder-sql-vd01`; ScadaBridge's 2026 design says `wonder-sql-vd03`. Probe and record the answer in `deployment.md` §2.1 (which currently has no BT row at all).
|
||||
7. **`install.bat`/`uninstall.bat` are wrong for this project** (they install `WWNotificationSystem`). _Deleted on `feat/manager-blazor`; replaced by `deploy/install-service.bat` (NSSM, service `ZB.MOM.WW.BTDB.Manager`)._
|
||||
8. **CLR + Historian co-location is a hard deployment constraint** the index did not previously record: BT cannot be moved to the app-tier SQL (`wonder-app-vd03,1433`, where ScadaBridge's ConfigDb lives) without breaking every report wrapper. Any consolidation plan must keep BT on the Historian instance or replace the CLR with HistorianGateway calls.
|
||||
|
||||
## 7. Primary commands (Windows only)
|
||||
|
||||
```powershell
|
||||
# from ~/Desktop/btdb (master)
|
||||
dotnet build Manager\BTDBManager.csproj # net6.0; needs Telerik Reporting R2 2022 at the HintPath
|
||||
msbuild Database\Database.sqlproj /p:Configuration=Release # SSDT (VS 2022 + SSDT) → bin\Release\Database.dacpac
|
||||
SqlPackage /Action:Publish /SourceFile:Database\bin\Release\Database.dacpac /TargetServerName:<historian-sql> /TargetDatabaseName:BT
|
||||
# Instance prerequisites: CLR enabled, `INSQL` linked server, `Runtime` DB reachable by three-part name
|
||||
```
|
||||
|
||||
```bash
|
||||
# feat/manager-blazor (any OS for the app; SSDT still Windows-only)
|
||||
./build.sh # restore + build (Release, warnings-as-errors) + test BTDB.slnx
|
||||
dotnet run --project src/ZB.MOM.WW.BTDB.Manager # appsettings.Development.json → local glauth; needs a BT
|
||||
pwsh deploy/publish.ps1 # self-contained win-x64 → deploy/out/ (+ NSSM install scripts)
|
||||
```
|
||||
|
||||
```bash
|
||||
# Local Docker rig (2026-09-04, any OS) — see §9
|
||||
docker/deploy-db.sh # BT on scadabridge-mssql from Database/ (dacpac + SQL CLR); --recreate drops it first
|
||||
docker/deploy.sh # publish FDD on the host → zb-btdb-manager:local, up on :9877 (glauth login enabled)
|
||||
```
|
||||
|
||||
On `master` nothing builds on macOS (SSDT/CLR need Windows MSBuild, the MVC Manager needs Telerik + `System.DirectoryServices`). On the branch the app and its tests build and run on macOS; only `Database.sqlproj` (kept alone in `BTDB.sln`) still needs Windows — but §9's side projects build the same sources into a dacpac and a CLR assembly anywhere, for the local rig.
|
||||
|
||||
## 8. Blazor conversion — branch `feat/manager-blazor` (2026-09-04)
|
||||
|
||||
Plan: `btdb/docs/plans/manager_blazor_conversion.md` (+ `.tasks.json` tracker beside it; mockups `docs/mockups/manager_blazor_mockups.html`). Executed 2026-09-04 in worktree `~/.config/superpowers/worktrees/BTDB/feat-manager-blazor`; **uncommitted and unpushed at the time of writing** — phases 1–3 (scaffold, core, auth, widgets, queries, all pages) plus the local half of phase 4 are done; the DEV-box half of phase 4 (parity run, secrets seed + rotation, NSSM side-by-side, port swap) is written up as a runbook and not yet performed.
|
||||
|
||||
- **Shape on the branch:** `BTDB.slnx` = `src/ZB.MOM.WW.BTDB.Manager` (Blazor Web App, InteractiveServer, net10.0) + `src/ZB.MOM.WW.BTDB.Manager.Core` (Dapper data layer moved verbatim from the MVC app, hardened) + two xunit/bUnit test projects (334 tests, warnings-as-errors gate via root `Directory.Build.props`, `build.sh`/`build.ps1`). `BTDB.sln` keeps only `Database.sqlproj`. `Manager/` (MVC, Kendo, the three Telerik `.trdp` reports with embedded connection strings, the mis-named `install.bat`) is **deleted**; `/Api/GetMachines`+`GetMachineGroups` are gone (no external consumer — ScadaBridge/MESAPI read `dbo.Machine` by SQL).
|
||||
- **Family libs:** Theme 0.4.1, Health 0.3.0 (`MapZbHealth`; readiness = a `SELECT 1` against `BT` with a 3 s timeout, so `/health/ready` is 503 until the DB answers — register it in Overview), Telemetry + Serilog 0.1.0, Configuration 0.1.0 (`ConfigPreflight` requires `ConnectionStrings:BT` and `Btdb:Security:Ldap:Server`), Secrets 0.6.2 (`${secret:btdb/connectionstrings/{bt,qa,prod}}`, `${secret:btdb/ldap/serviceaccountpassword}`; SQLite store `C:\ProgramData\ZB.MOM.WW\btdb-manager\secrets.db`, KEK from `ZB_SECRETS_MASTER_KEY`), Auth.Ldap/AspNetCore 0.3.0 (service-account bind, `Btdb:Security:GroupToRole` → `CanonicalRole`; policies Viewer / BatchEdit (Operator+) / MachineConfig (Administrator); cookie `btdb.auth`, plain-HTTP cookie because the box has no certificate). `Microsoft.Data.SqlClient` 7.x with `Encrypt=False` forced by `BtConnectionStrings.Normalize` unless the string sets it.
|
||||
- **Behavioural deltas vs the MVC app worth knowing:** config import derives the group set from the selected machines' memberships (no separate group pick) and has a dry-run preview (`MachineConfigImportPreview.sql`: same MERGEs, `OUTPUT` into a table variable, always `ROLLBACK`); batch-edit timestamps are 7-fraction UTC strings validated on blur (no Kendo mask); the three audit reports are HTML tables with a print stylesheet instead of Telerik PDFs; `MachineAlarm` DTO property order/types were wrong in the MVC app (alarm import always threw) and are fixed against `MachineAlarmType`; every `Save*` runs in a transaction and `THROW 5001x` maps to `BtdbSaveException`.
|
||||
- **Cut-over material:** `docs/operations/cut-over.md` (parity checklist per route + THROW paths + audit-username check, secrets seed via the `secret` console + rotation, NSSM side-by-side on `:9877`, port swap to `:9876`, Overview registry entry), `deploy/` (`publish.ps1`, `install-service.bat` / `uninstall-service.bat` for NSSM service `ZB.MOM.WW.BTDB.Manager`), `tools/smoke-new-queries.sql` (runs the six never-executed queries read-only against DEV with sqlcmd). Still open after cut-over: Overview lacks the mockup's per-machine "open > 24 h" rows; Ldap `Server`/`SearchBase`/`ServiceAccountDn` are blank in `appsettings.json` by design (per-environment).
|
||||
|
||||
## 9. Local Docker rig — `docker/` (2026-09-04)
|
||||
|
||||
Mirrors the HistorianGateway / Overview pattern: publish framework-dependent on the host (Gitea feed creds), copy into `aspnet:10.0`, never restore in Docker. Compose project `zb-btdb`, container `zb-btdb-manager`, image `zb-btdb-manager:local`, port `:9877` (same as the DEV side-by-side port, so `appsettings.json`'s Kestrel section is the single binding authority; the Dockerfile clears `ASPNETCORE_URLS`/`ASPNETCORE_HTTP_PORTS`). `ASPNETCORE_ENVIRONMENT=Production`; all environment-specific values are compose env vars, dev-only and committed under the family's rig exception.
|
||||
|
||||
- **Database:** no MSSQL of its own — joins the external `scadabridge-net` and uses ScadaBridge's `scadabridge-mssql` (the instance that already carries `ScadaBridgeConfig` + `ZbSecretsHub`). `docker/deploy-db.sh`: (1) `docker/db/BT.Clr.csproj` compiles `Database/**/*.cs` to `Database.dll` (net472 via the auto-referenced reference assemblies — builds on macOS); (2) `docker/db/BT.Local.sqlproj` (SDK-style `Microsoft.Build.Sql/2.2.0`, `EnableDefaultSqlItems=false`, globs the four `Database/` folders, Sql130 model, suppresses the legacy build's own SQL71562/71558/71502) → `BT.Local.dacpac`; (3) `db/setup.sql` — `BT` + login `btdb_app` (db_owner); (4) `db/clr-objects.sql` — `clr enabled` on the instance, `sp_add_trusted_assembly` by SHA2-512 (strict security stays on), `CREATE ASSEMBLY [Database] … SAFE` from the bytes streamed as 2000-char `0x` chunks (a single 57 KB literal gets split by sqlcmd), then `StringJoin` aggregate, `StringCompare`/`CheckTriggered`/`WhenTriggered`/`WhenCleared`/`GetAggregateValues`, `GetTSV`/`GetMachineBatchTSV`/`GetCycleTSV`/`GetLinkedBatchTSV` with SSDT's type mapping; (5) `sqlpackage /Action:Publish` from a one-shot container (`db/Dockerfile.sqlpackage`, SDK image + the dotnet tool — the host's 10.0.5 runtime could not run the tool's 10.0.11 pin) with `DropObjectsNotInSource=false`, `BlockOnPossibleDataLoss=false`, `AllowIncompatiblePlatform=true`; (6) smoke. Result on the rig: 23 tables, 37 T-SQL procs + 1 TVF, 10 CLR objects, `Database` assembly `SAFE_ACCESS`. The script diffs the legacy `<Build Include>` list against the folders and warns on drift (found: `ElmaData_Nitric.sql` + `Elma_Bulk_Query_Nitric.sql` were on disk but not in `Database.sqlproj` — added). `ScadaBridge/infra/teardown.sh`/`reseed.sh` drop the volume and BT with it; re-run `deploy-db.sh`.
|
||||
- **Why not convert `Database.sqlproj` itself:** `Microsoft.Build.Sql` does not compile SQL CLR, and the Manager depends on `dbo.StringJoin` (batch search) and `dbo.StringCompare` (machine saves). The legacy SSDT project stays the artifact of record; the two side projects reference the same files, nothing is copied.
|
||||
- **Login:** enabled, `host.docker.internal:3893` + `FallbackServers` `:3894` (glauth-redundant), bind `cn=serviceaccount,dc=zb,dc=local`; `GroupToRole` `SCADA-Admins→Administrator`, `SCADA-Designers→Operator`, `SCADA-Viewers→Viewer`. Verified: `admin`/`designer` sign in, `gw-viewer` refused (fail closed). Literal `ConnectionStrings__BT` / LDAP password env vars override the `${secret:}` refs, so the `/data/btdb-secrets.db` store stays empty and no master key is set (confirmed to boot without one). The two config-import sources point at the local BT.
|
||||
- **Health / Overview:** `/healthz` 200, `/health/ready` 200 with the `sql` entry (503 when BT is down), `/health/active` 200, `/metrics`. Compose `healthcheck` = bash `/dev/tcp` GET of `/healthz` (liveness on purpose). Registered in `ZB.MOM.WW.Overview/src/…/appsettings.Docker.json` as application **BTDB Manager**, instance `manager`, `BaseUrl http://zb-btdb-manager:9877`, `HasActiveRole false`; the containerised Overview was republished and shows the tile Up with `sql` healthy (the dashboard already sits on `scadabridge-net`, so no extra network).
|
||||
|
||||
|
||||
## 10. State as of 2026-09-11 (supersedes §1, §4, §6.1, §6.3, §6.7, §8 where they differ)
|
||||
|
||||
- **Everything is on local `master`** (`78195b8`): the Blazor conversion (§8) was merged, the
|
||||
`feat/manager-blazor` worktree is gone, and the 2026-09-04 full review
|
||||
(`docs/reviews/2026-09-04-full-review.md`, reviewed at `c624d41`) was remediated in 12 work-package
|
||||
branches — `fix/save-batch-edit-null-compare`, `fix/db-lifecycle-sprocs`, `fix/clr-openquery-escaping`,
|
||||
`fix/config-import-parents-and-nulls`, `test/db-integration`, `fix/manager-robustness`,
|
||||
`fix/auth-hardening`, `ops/runbook-and-deploy`, `perf/indexes`, `db/schema-hygiene`,
|
||||
`fix/concurrency-and-async`, `chore/nits` — all merged; 60 findings fixed, 3 partial by decision
|
||||
(DB-15 `QV_*` impersonation, DB-16 alarm-CTE consolidation, DB-21 ServiceStack table drop), 0 open.
|
||||
`feat/machine-batch-transfer` (DARS sprint 1, §1 item 1) is merged too, and so is
|
||||
`feat/transfer-machine-batch` (merged `be976a6`, 2026-09-11): **`dbo.TransferMachineBatch`**, a tenth
|
||||
Galaxy-facing writer that ends the source batch if still open, starts the destination batch by machine
|
||||
`Code`, copies the `MachineBatchWO` rows still on the source (`MoveOutTimestamp IS NULL`, narrowed to
|
||||
`@ContainerID`; blank = whole batch; source rows never modified) and records the `MachineBatchTransfer`
|
||||
link — by composing `EndMachineBatch` / `StartMachineBatch` / `AddMachineBatchTransfer` in one owned
|
||||
transaction. Outputs `@o_DestMachineBatchID`, `@o_MachineBatchTransferID`. Documented in
|
||||
`docs/BatchTracker_Reference.md`; proven by `ValidateLifecycleSprocs.sql` §F (82 PASS on the rig).
|
||||
`fix/transfer-lot-walk` (merged `5f0da01`, 2026-09-11) **reopened review DB-6**: the 2026-09-04 loop guard
|
||||
in `AddMachineBatchTransfer` walked backward (toward the batches that fed the destination), which the
|
||||
already-transferred check makes unreachable for any source, so `A→B` then `B→A` was still accepted; it
|
||||
now walks forward along source→dest links with `HOLDLOCK`, and the destination row is held like the
|
||||
source. The chain walks in `GetLinkedBatchTSV.cs` and `LinkedBatchAlarm_Wrapper.sql` picked one root
|
||||
with `TOP 1` and dropped the other branch of a lot merge (`A→C, B→C`); both now resolve the whole lot
|
||||
(forward to the final batch, then every batch that fed it) with one CTE pair pinned equal by
|
||||
`SchemaHygieneTests`. Rig proofs: `ValidateLifecycleSprocs.sql` 87/0, `docker/db/validate-clr.sql`
|
||||
27/0 over a merged lot with a `Runtime.dbo.Events` stand-in.
|
||||
`feat/manager-transfers` (merged `695192d`, 2026-09-11) gave the **Manager** the transfer side it lacked: the
|
||||
batch edit page edits the batch's outgoing `MachineBatchTransfer` row as a fourth MERGEd collection in
|
||||
`SaveBatchEdit.sql` (guards `50015` self, `50016` destination missing, `50017` loop, `50018` more than one;
|
||||
destination row and chain walk held like `AddMachineBatchTransfer`), audited into the new
|
||||
`AuditLogMachineBatchTransfer` under the batch-edit header (new TVP `MachineBatchTransferType`); a read-only
|
||||
lot panel (`GetBatchLot.sql`, the same `Down`/`Lot` CTE as the CLR, pinned equal by a static test); a lineage
|
||||
column on Find Batch; a Transfers section on the batch-edit audit page and PDF. Rig proofs: 28 integration
|
||||
tests (three new: round trip with audit, loop refused, merged lot), smoke 17/17, lifecycle 87/0, transfer
|
||||
chains 4/0, validate-clr 27/0; gate 961 tests, 0 warnings. No branch is in flight.
|
||||
- **`master` is ~198 commits ahead of `origin/master` (`d147c10`) and unpushed.** Pushing is the user's
|
||||
call — the remote is the corporate `ZimmerBiomet/BTDB`.
|
||||
- **Solution shape now:** `BTDB.slnx` = `src/ZB.MOM.WW.BTDB.Manager` (Blazor host) +
|
||||
`src/ZB.MOM.WW.BTDB.Manager.Core` (Dapper data layer, embedded `Queries/*.sql`) + five test projects
|
||||
(`Manager.Core.Tests` static query invariants, `Manager.Tests` bUnit/boot, `Database.Tests` static SQL
|
||||
+ sqlproj invariants, `Clr.Tests` compiles the CLR sources into net10, `Manager.Core.IntegrationTests`
|
||||
opt-in on the rig behind `BTDB_TEST_CONNECTION`). `BTDB.sln` keeps `Database/Database.sqlproj`
|
||||
(Windows MSBuild only). `.gitea/workflows/build.yml` runs `./build.sh` (needs `GITEA_NUGET_TOKEN`).
|
||||
- **Invariants a future session must not break** (all test-enforced): TVPs bind by ordinal so model
|
||||
property order + lengths must equal `Database/Types/*.sql`; every write query is transaction-free and
|
||||
audited (the C# wrapper owns the transaction); `dbo.X` only, never `BT.dbo.X`; `SYSUTCDATETIME()` in
|
||||
Manager queries; every writer sproc follows the own-or-join `TRY/CATCH` template with locked lookups;
|
||||
every `.sql` on disk must be in `Database.sqlproj`'s `<Build Include>` list; optimistic concurrency via
|
||||
`ExpectedLastUpdate` → `THROW 50014`.
|
||||
- **Secrets/credentials (§6.2):** `${secret:btdb/connectionstrings/{bt,qa,prod}}` (the LDAP
|
||||
service-account secret is gone since 2026-10-01 — see below; only `dotnet run` against local glauth uses it), store at `C:\ProgramData\ZB.MOM.WW\btdb-manager\secrets.db`,
|
||||
master key only in `ZB_SECRETS_MASTER_KEY`. Rotation is cut-over step 4.2.
|
||||
- **Claude artifacts are gitignored + untracked in btdb** (2026-09-11): `CLAUDE.md`, `.claude/`,
|
||||
`docs/plans/`, `docs/reviews/`, `*.tasks.json` — they exist on disk (btdb's `CLAUDE.md` is the repo
|
||||
orientation and still loads) but never reach the corporate remote. `docs/operations/`,
|
||||
`docs/BatchTracker_Reference.md`, `docs/mockups/` stay tracked.
|
||||
- **Open step:** phase-4 cut-over on the DEV box (`docs/operations/cut-over.md`; 4.1 parity walk-through
|
||||
gates the rest) — **blocked by the 2026-09-11 remote-access hold** (no psbridge, no winrm; UNC copies and
|
||||
direct SQL logins still allowed). §6 item 6 (which SQL host carries DEV `BT`) is still unrecorded.
|
||||
- **2026-10-01 — LDAP sign-in by user bind** (merged `a81a480`): Auth 0.4.0/0.4.1 added opt-in
|
||||
`LdapOptions.BindMode=User`; BTDB ships it. Sign-in binds as `UserBindTemplate` (`<DOMAIN>\{0}` —
|
||||
down-level maps exactly to the sAMAccountName the group search uses), the same connection reads the
|
||||
user's own `memberOf`/`displayName`, and the username returned is the directory's spelling. No service
|
||||
account, no LDAP secret; the preflight requires the template and refuses `AllowInsecure`/`Transport=None`
|
||||
with user bind outside Development. Local dev + docker rig stay `BindMode=ServiceAccount` (GLAuth bind DNs
|
||||
embed the user's OU). Rollout to the three Manager nodes (vd03 first) and retiring the stored secret are
|
||||
the open steps (plan `docs/plans/2026-10-01-ldap-user-bind.md`, gitignored).
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,36 @@
|
||||
# ScadaBridge — index history
|
||||
|
||||
- **2026-10-13 existing fixes verified and issues closed.** Main `513fa1aa` already includes #35 fail-closed unavailable configured body/SQL redactors (`006202f3`) and #37 Flow Debugger structured/raw validated method inputs (`b5eb08f1`). Fresh full AuditLog project 407 passed/0 failed; FlowDebuggerPageTests 47 passed/0 failed; both terminal exit0. Remote ancestry confirmed; #35/#37 closed with evidence. No source changes/deployment/MES transactions. #36 runtime reset-echo overload is implemented, but QA/prod script port remains tracked; #30 per-site PSK deployment gate remains open.
|
||||
|
||||
- **2026-10-13 #36 runtime regression proof refreshed.** Rebuilt HandshakeResetEchoTests passed all three cases with local fakes, terminal exit0; an earlier no-build attempt matched no tests and is excluded from evidence. Tracker now distinguishes implemented runtime b623fdb0 from remaining QA/prod database-owned script rollout (deployment register row119, scripts13/14/36 and15/16/25/26/37/38). No database writes, deployments or fresh live rig claims.
|
||||
|
||||
- **2026-11-13 deployed `8e32f353` to wonder-app-vd03 (DEV) and enabled the audit hash chain** (was `424db155`; owner go on #107). 37 commits, no migration (64). Build: clean worktree, self-contained win-x64, zip SHA-256 `0cf06cf5…7fdebc`, LocalDb 0.3.8. WinRM swap 07:13–07:14 EST, site data path ~45 s, central API ~25 s; `sc failureflag 1` on both services (restart actions existed, but non-crash failures were FALSE, so a #132 exit 75 would have left the node stopped). Env block digest-identical before/after. **#131 applied** (`apply.sh apply 131`, SBTEST01/02 deployments 95/96; verify groups C+D 13/13 on the old binary and again after; C13 skipped because SAPID 103559 routes to Z28061) — #131 closed. Gates: health 200 ×4, MxGateway Connected 398/412 = baseline, Z28062 144 Good = baseline, AuditLog writing, Overview Up. **Hash chain:** backfill 843 → `unknown`, then `AuditLog__HashChain__Enabled=true` in the Central service env (ChainBacklog unset, head export off, single login), Central-only restart; one anchor (2026-11 `ChainSeq 0`, cutoff 2026-11-13T12:16:53.114Z), 0 pre-cutoff rows chained, `verify-chain 2026-11` Intact with 507 pre-cutoff rows, 2026-10 NotChained (667). Backup `ScadaBridge_pre-8e32f353_20261113T071302.bak`; rollback scripts in `E:\ApiInstall\_stage-sb-8e32f353\`. Record `docs/deployment/deployment-records/2026-11-13-wonder-app-vd03-8e32f353.md` (`581e25ca`). QA not deployed.
|
||||
|
||||
- **2026-11-11 deployed `424db155` to wonder-app-vd03 (DEV)** (was `0e540291`). Owner-approved WinRM deploy. Migrations 58→64 (`AddNativeAlarmSourceMesReportable`, `PrefixSearchIndexes`, `AddAuditLogHashChain`, `AddConfigGraphRowVersions`, `FlipAuditLogClusteredKey`, `AuditMaintenanceGrants`) applied by script with central + site stopped; #111 DEV sizing: 2,394 rows / 8 MB flip in ~1.5 s. **The plain `dotnet ef migrations script --idempotent` output fails (Msg 207 `ChainSeq`: column added and indexed in one batch)** — the deployed script adds `GO` per guarded block + `XACT_ABORT`; forward/rollback rehearsed on a restored copy of the vd03 DB. Downtime ~50 s; verify OK. Backup `ScadaBridge-backups\ScadaBridge_pre-424db155_20261111T164219.bak`. QA not deployed.
|
||||
|
||||
- **2026-11-12 #129 alarm Severity runs one direction (higher = more urgent), main `dd4f1c2a`.** MxGateway native alarms and computed `PriorityLevel` now band AVEVA-style priority onto `AlarmConditionState.Severity` with OtOpcUa's `GalaxyAlarmPriority` table (lmxopcua#887): 1–250→1000, 251–500→750, 501–750→500, 751–999→250, ≤0→1000, >999→250 (`AlarmPriorityBands`). OPC UA rows are unchanged. The raw number (= pre-#129 Severity) is kept on new `AlarmConditionState.Priority`, `ScriptAlarm.Priority` and `AlarmStateChanged.Priority`. There is no proto change: central derives Severity from the wire `priority` by kind, and pre-#129 `native_alarm_state` rows are upgraded on rehydrate. The native MES 900–999 band and the MES API `Severity`/`MinSeverity`/`MaxSeverity` key off `Priority`, so they select the same alarms as before. The rig seed scripts were switched; **deployed MES scripts (CvdReactor, vd03 SBTEST01/02) must switch `a.Severity`→`a.Priority` in the same deploy: deploy gate ScadaBridge#131.** **Visible flip:** Alarm Summary worst/filter/sort and the Sev column now rank AVEVA priority 1 highest. A computed raise logs `Error` at priority 1–500 (was raw ≥700). Tests (Release): Commons 977, DCL 549, Communication 834, SiteRuntime 1055, CentralUI 1545, all green; a mutation revert turned 62 red. Not deployed.
|
||||
|
||||
- **2026-11-12 OPC Foundation SDK 1.5.378.106 → 1.5.378.182 (`main` `e36cd605`, ScadaBridge#125 ask 2, owner option B; not deployed).**
|
||||
- Client (DCL) and the test-only Server move in lockstep. No source changes, no API breaks.
|
||||
- Release build has 0 warnings. DCL tests pass 536/536.
|
||||
- **Wire-compat re-run** with the bumped client, using the lmxopcua harness (`438484fd`, run at master `2e9cccbd`), ACL off:
|
||||
- The matrix passes 11/11 in None, Sign and SignAndEncrypt, against both the SDK 1.5 baseline `83ed880e` and the SDK **2.0.1** master `a28adba2`.
|
||||
- All 8 trust controls fail closed (0x80130000 and 0x801A0000).
|
||||
- Failover passes 8/8 legs, with the same timings as on the old client.
|
||||
- **Operational note:** since .156, a CA-issued OPC UA server cert that the DCL trusts needs an issuer with `keyCertSign`. SDK self-signed certs are unaffected.
|
||||
- **2.0.x is deferred** until lmxopcua#799 and #801 close. #125 stays open to track it.
|
||||
|
||||
- **2026-11-12 OPC Foundation SDK 1.5.378.182 → 2.0.1 (`main` `a2e9d718`, ScadaBridge#125 closed; not deployed).** Done once lmxopcua#782/#799/#801 had closed. Client (DCL) and the test-only Server move in lockstep; the transitive Core/Core.Types/Types/Configuration/Security.Certificates packages resolve to 2.0.1.
|
||||
- **API breaks fixed (DCL only):**
|
||||
- Immutable `Variant`/`DataValue`/`NodeId`/`StatusCode` and `ArrayOf<T>`. New `OpcUaValueBoundary` restores the SDK 1.5 CLR value shapes (`byte[]`, UTC `DateTime` with no-timestamp = `MinValue`, `Guid`, detached arrays) and keeps `new Variant(object)` write semantics.
|
||||
- `StatusCodes` are no longer constants, so code matches them by value.
|
||||
- `CertificateIdentifier.Certificate` and the `CertificateValidation` event are gone. The SDK-created `CertificateManager` owns the identity and trust lists and is disposed with the session; auto-accept and the verify probe use `AcceptError`.
|
||||
- X509 user identity now goes through `X509IdentityTokenHandler`.
|
||||
- **UserName = `LegacyRsaUserNameIdentityTokenHandler`** (ported from OtOpcUa `be28aa44`, lmxopcua#880). SDK 2's default handler sends a 65-char API key as an `RsaEncryptedSecret`, which SDK 1.5 servers reject (`BadIdentityTokenInvalid`) and SDK 2 servers clock-gate (#873). The DCL sends what it sent on 1.5, so it works against both server generations in a mixed rollout.
|
||||
- **Operational:** SDK 2 never accepts an incomplete chain or an empty subject/issuer DN, even with `AutoAcceptUntrustedCerts`. The `keyCertSign` rule from .156 still applies.
|
||||
- **Tests:** Release 0 warnings; DCL 570/570 incl. the #121 secure-connect tests and opc-plc live tests. The new handler tests are mutation-checked. Whole solution 11,345 passed / 188 failed (185 Playwright with no browser server, 3 load flakes that pass in isolation).
|
||||
- **Wire-compat re-run:** lmxopcua harness, its key now the 65-char production shape (`2705f166`). Against baseline `83ed880e` (SDK 1.5) and master `412da27c` (SDK 2.0.1):
|
||||
- Matrix 11/11 ×3 modes on both servers, ACL off and on; 8 trust controls fail closed.
|
||||
- Failover 8/8. Kill reaches the backup in about 20 s as before; freeze is detected in about 15 s (was about 20 s).
|
||||
- A mutation run with the SDK default UserName handler fails every SDK 1.5 leg with `BadIdentityTokenInvalid`, which is #880 reproduced from the consumer side.
|
||||
- Evidence: `~/validation-evidence/scadabridge-125/client-2.0.1/` (contains private PKI; not committed).
|
||||
+4
-2
@@ -7,8 +7,10 @@ obj/
|
||||
[Aa]rtifacts/
|
||||
*.user
|
||||
|
||||
# Claude Code tooling / agent worktrees (local-only)
|
||||
.claude/
|
||||
# Claude Code tooling / agent worktrees (local-only) — but .claude/skills/ IS tracked:
|
||||
# the sister-project-history skill holds the per-project narratives the root index points at.
|
||||
.claude/*
|
||||
!.claude/skills/
|
||||
|
||||
# Local ops/infra notes — internal access details, never publish
|
||||
zimmer-vpn-tunnel.md
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
# ZB.MOM.WW.Audit
|
||||
|
||||
Shared audit event model + writer seam for the **ZB.MOM.WW SCADA family** (single package; DEEP-adopted by all apps as the canonical record). Build/test from this directory: `dotnet test`. Component spec + gaps: `../components/audit/`.
|
||||
|
||||
## Index history (migrated from the scadaproj root CLAUDE.md)
|
||||
|
||||
> Moved verbatim out of the scadaproj root `CLAUDE.md` on 2026-09-03 so it loads only when needed. **This file is now the authoritative place for this history — append new entries here and keep the root index row short.**
|
||||
|
||||
### Narrative
|
||||
|
||||
The audit component is fully populated: a normalized [`spec`](components/audit/spec/SPEC.md), an
|
||||
[`event-model`](components/audit/spec/EVENT-MODEL.md) reference, a
|
||||
[`shared-contract`](components/audit/shared-contract/ZB.MOM.WW.Audit.md), three
|
||||
[`current-state`](components/audit/current-state/) docs, and an adoption [`GAPS`](components/audit/GAPS.md)
|
||||
backlog. Common ground = canonical `AuditEvent` record + `AuditOutcome` enum + `IAuditWriter` /
|
||||
`IAuditRedactor` seams + helpers (`NullAuditRedactor`, `TruncatingAuditRedactor`, `NoOpAuditWriter`,
|
||||
`CompositeAuditWriter`, `RedactingAuditWriter`) + `AddZbAudit` DI registration; left per-project =
|
||||
transport/storage and domain vocabulary. Closes the loop on Auth — audit's `Actor` field = the Auth
|
||||
principal. `IAuditRedactor` is aligned with Telemetry's `ILogRedactor` seam convention.
|
||||
|
||||
The shared library is **built and lives in this repo** at [`ZB.MOM.WW.Audit/`](ZB.MOM.WW.Audit/)
|
||||
(.NET 10; 1 package — `ZB.MOM.WW.Audit`; only non-BCL dependency `Microsoft.Extensions.DependencyInjection.Abstractions`;
|
||||
23 tests (verified 2026-07-18); `dotnet pack` → 1 nupkg @ 0.1.0). Repo: `https://gitea.dohertylan.com/dohertj2/zb-mom-ww-audit`.
|
||||
**Adopted across all three apps on 2026-06-02** (audit GAPS #1–#6) on each repo's `feat/adopt-zb-audit` branch
|
||||
(stacked on `feat/adopt-zb-auth`) — committed + reviewed, then **merged into the repo's local default (main/master)
|
||||
and PUSHED to origin (gitea) on 2026-06-03** (in sync). Depth =
|
||||
**DEEP adopt** (the canonical 9-field `AuditEvent` is the record everywhere; domain fields ride in `DetailsJson`).
|
||||
OtOpcUa: canonical record + `AuditWriterActor : IAuditWriter` + `Outcome` column/migration + `ClusterAudit` fix.
|
||||
MxGateway: new canonical SQLite `audit_event` store + `IAuditWriter` + `IApiKeyAuditStore`→canonical adapter.
|
||||
**ScadaBridge: a full audit-subsystem re-architecture** (the program's largest task) — canonical record everywhere via a
|
||||
deterministic codec; site SQLite split into `audit_event` + an `audit_forward_state` forwarding sidecar; central
|
||||
partitioned `dbo.AuditLog` collapsed to 10 canonical cols + persisted computed cols (`CollapseAuditLogToCanonical`
|
||||
migration, MSSQL-verified). Phase 3 wires `Actor` from the Auth principal at authenticated emit sites (per-app
|
||||
`IAuditActorAccessor`). Per-repo detail in [`components/audit/GAPS.md`](components/audit/GAPS.md) +
|
||||
`docs/plans/2026-06-02-auth-audit-normalization-phase2-deep.md` + `…-scadabridge-audit-rearch.md`.
|
||||
Build/test from `ZB.MOM.WW.Audit/`: `dotnet test`. Consumer matrix: all three apps consume the single
|
||||
`ZB.MOM.WW.Audit` package (OtOpcUa, MxAccessGateway, ScadaBridge — DEEP-adopted as the canonical record).
|
||||
@@ -16,11 +16,15 @@ Canonical audit event model, best-effort writer seam, and redactor seam for the
|
||||
|
||||
| Consumer | ZB.MOM.WW.Audit |
|
||||
|---|:---:|
|
||||
| **OtOpcUa** | yes (adoption deferred) |
|
||||
| **MxAccessGateway** | yes (adoption deferred) |
|
||||
| **ScadaBridge** | yes (adoption deferred — "align, don't replace") |
|
||||
| **OtOpcUa** | yes — DEEP-adopted 2026-06-02 (canonical record + `AuditWriterActor : IAuditWriter`), pins `0.1.0` |
|
||||
| **MxAccessGateway** | yes — DEEP-adopted 2026-06-02 (canonical SQLite `audit_event` store + `IAuditWriter`), pins `0.1.0` |
|
||||
| **ScadaBridge** | yes — DEEP-adopted 2026-06-02 (audit-subsystem re-architecture onto the canonical record), pins `0.1.0` |
|
||||
| **HistorianGateway** | yes — `AddZbAudit` + `IAuditWriter`, pins `0.1.0` |
|
||||
|
||||
Adoption is tracked in `components/audit/GAPS.md` in the outer `scadaproj` workspace. Each app brings its own transport (Akka broadcast / SQLite append / SQL ingest) and domain vocabulary (channels / kinds / event-types) — those stay per-project. The shared library provides the canonical record and the two seams that decouple "what to audit" from "how to store it".
|
||||
All four apps pin `0.1.0` (the only version on the Gitea feed), verified against each repo's origin default
|
||||
branch 2026-11-09. The 2026-06-02 adoption was merged and pushed on 2026-06-03.
|
||||
|
||||
Adoption history is in `components/audit/GAPS.md` in the outer `scadaproj` workspace. Each app brings its own transport (Akka broadcast / SQLite append / SQL ingest) and domain vocabulary (channels / kinds / event-types) — those stay per-project. The shared library provides the canonical record and the two seams that decouple "what to audit" from "how to store it".
|
||||
|
||||
---
|
||||
|
||||
@@ -53,7 +57,7 @@ dotnet test ZB.MOM.WW.Audit.slnx
|
||||
|
||||
Full design docs live in the `components/audit` folder of the SCADA project workspace:
|
||||
|
||||
- `~/Desktop/scadaproj-audit/components/audit/spec/SPEC.md` — overall audit specification
|
||||
- `~/Desktop/scadaproj-audit/components/audit/spec/EVENT-MODEL.md` — field-by-field event model + per-project mapping table
|
||||
- `~/Desktop/scadaproj-audit/components/audit/shared-contract/ZB.MOM.WW.Audit.md` — public API contract (on paper)
|
||||
- `~/Desktop/scadaproj-audit/components/audit/GAPS.md` — adoption backlog
|
||||
- `~/Desktop/scadaproj/components/audit/spec/SPEC.md` — overall audit specification
|
||||
- `~/Desktop/scadaproj/components/audit/spec/EVENT-MODEL.md` — field-by-field event model + per-project mapping table
|
||||
- `~/Desktop/scadaproj/components/audit/shared-contract/ZB.MOM.WW.Audit.md` — public API contract (on paper)
|
||||
- `~/Desktop/scadaproj/components/audit/GAPS.md` — adoption backlog
|
||||
|
||||
@@ -1,4 +1,10 @@
|
||||
#!/usr/bin/env bash
|
||||
# pack.sh — produce the ZB.MOM.WW.Audit NuGet package into ./artifacts.
|
||||
set -euo pipefail
|
||||
dotnet pack -c Release -o ./artifacts
|
||||
# cd to the repo root and name the solution + an absolute output path: `dotnet pack` with
|
||||
# neither a project argument nor a fixed working directory packs whatever solution happens
|
||||
# to sit in the CALLER's directory (the bug behind the LocalDb feed incident, 0038d46).
|
||||
REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
cd "$REPO_ROOT"
|
||||
|
||||
dotnet pack ZB.MOM.WW.Audit.slnx -c Release -o "$REPO_ROOT/artifacts"
|
||||
|
||||
@@ -16,9 +16,20 @@ set -euo pipefail
|
||||
: "${GITEA_NUGET_SOURCE:?set GITEA_NUGET_SOURCE to your Gitea NuGet feed URL}"
|
||||
: "${GITEA_NUGET_KEY:?set GITEA_NUGET_KEY to your Gitea access token}"
|
||||
|
||||
dotnet pack -c Release -o ./artifacts
|
||||
# Named solution, named output, and a cd to the repo root, all for one reason: `dotnet pack`
|
||||
# with neither a project argument nor a fixed working directory packs whatever solution
|
||||
# happens to sit in the CALLER's directory — and then pushes it to a live feed under this
|
||||
# script's name. Invoked by absolute path from another repo's checkout, the relative form
|
||||
# packed and published 25 unrelated packages (LocalDb's copy of this script, fixed in
|
||||
# 0038d46; recovered with `dotnet nuget delete`, but only because the token happened to
|
||||
# carry delete rights). A publish script must be unambiguous about WHAT it publishes no
|
||||
# matter where it is run.
|
||||
REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
cd "$REPO_ROOT"
|
||||
|
||||
dotnet nuget push "./artifacts/*.nupkg" \
|
||||
dotnet pack ZB.MOM.WW.Audit.slnx -c Release -o "$REPO_ROOT/artifacts"
|
||||
|
||||
dotnet nuget push "$REPO_ROOT/artifacts/*.nupkg" \
|
||||
--source "$GITEA_NUGET_SOURCE" \
|
||||
--api-key "$GITEA_NUGET_KEY" \
|
||||
--skip-duplicate
|
||||
|
||||
@@ -11,8 +11,8 @@
|
||||
<PackageId>ZB.MOM.WW.Audit</PackageId>
|
||||
<Authors>ZB.MOM.WW</Authors>
|
||||
<Description>Canonical audit event model + best-effort writer and redactor seams for the ZB.MOM.WW SCADA family.</Description>
|
||||
<PackageProjectUrl>https://gitea.dohertylan.com/dohertj2/zb-mom-ww-audit</PackageProjectUrl>
|
||||
<RepositoryUrl>https://gitea.dohertylan.com/dohertj2/zb-mom-ww-audit</RepositoryUrl>
|
||||
<PackageProjectUrl>https://gitea.dohertylan.com/dohertj2/scadaproj/src/branch/main/ZB.MOM.WW.Audit</PackageProjectUrl>
|
||||
<RepositoryUrl>https://gitea.dohertylan.com/dohertj2/scadaproj</RepositoryUrl>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" />
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
# ZB.MOM.WW.Auth
|
||||
|
||||
Shared login / identity / API-key library for the **ZB.MOM.WW SCADA family** (4 packages + `ApiKeys.SqlServer`; consumed by OtOpcUa, ScadaBridge, MxAccessGateway, HistorianGateway). Build/test from this directory: `dotnet test` (the `ApiKeys.SqlServer` live suite is gated on `AUTH_SQLSERVER_CONNSTR`). Component spec + gaps: `../components/auth/`.
|
||||
|
||||
**Backlog / open work:** lives in Gitea issues on `dohertj2/scadaproj` (`tea issues list --repo dohertj2/scadaproj`) — currently #5 (roll apps to `0.4.1`), #6 (VD03 NAM AD cutover), #18 (Secrets migrator jitter, ported from here). The history below is a record, not a status tracker; file new follow-ups as issues.
|
||||
|
||||
## Index history (migrated from the scadaproj root CLAUDE.md)
|
||||
|
||||
> Moved verbatim out of the scadaproj root `CLAUDE.md` on 2026-09-03 so it loads only when needed. **This file is now the authoritative place for this history — append new entries here and keep the root index row short.**
|
||||
|
||||
### Component-table row as it read in the index
|
||||
|
||||
| Component | Status | Goal | Design | Implementation |
|
||||
|---|---|---|---|---|
|
||||
| Auth (login / identity / authz) | Adopted (**feed carries `0.3.0` as of 2026-09-02 — five packages, the new one being `ZB.MOM.WW.Auth.ApiKeys.SqlServer`; ALL FOUR apps pin `0.3.0` as of 2026-09-03**: OtOpcUa `master @ b8b4c18f`, ScadaBridge `main @ e45c4af9` (the `inbound-api-key-shared-store` work, merged), MxAccessGateway `main @ 4f931e4`, HistorianGateway `main @ d8d890c` — each built + tested with no new failures versus its pre-bump baseline, all PUSHED to origin. The preceding `0.2.1` pins landed 2026-08-13 (OtOpcUa `08e33fc7`, ScadaBridge `d28824d9`, MxAccessGateway `1cb14d2`, HistorianGateway `e42ff31`). **`0.2.0` (2026-08-10) adds LDAP backup-DC sticky failover**, **`0.2.1` (2026-08-12) fixes a defect that broke AD logins outright** — an AD continuation referral escaped `NovellLdapConnection.Search`, so any `SearchBase` at a domain root failed every login as `ServiceAccountBindFailed` against a perfectly healthy directory. Live-proven against `DC=nam,DC=zimmer,DC=com`; the app-level exposure is closed by the pin bumps. **`FallbackServers` is live-gated** via the local redundant GLAuth pair ([`infra/glauth-redundant/`](infra/glauth-redundant/), primary :3893 + backup :3894 on the dev Mac): HistorianGateway dashboard drill PASS 2026-08-13 (failover, stickiness, walk-back). | Shared `ZB.MOM.WW.Auth` lib | [`components/auth/`](components/auth/) | [`ZB.MOM.WW.Auth/`](ZB.MOM.WW.Auth/) |
|
||||
|
||||
### Narrative
|
||||
|
||||
The auth component is fully populated: a normalized [`spec`](components/auth/spec/SPEC.md), a
|
||||
proposed [`shared-contract`](components/auth/shared-contract/ZB.MOM.WW.Auth.md), three
|
||||
[`current-state`](components/auth/current-state/) docs, and an adoption [`GAPS`](components/auth/GAPS.md)
|
||||
backlog. Common ground = LDAP/GLAuth identity + peppered-HMAC API keys; left per-project =
|
||||
the authz vocabularies (OPC-UA permissions / gRPC scopes / roles + site-scoping).
|
||||
|
||||
The shared library is **built and lives in this repo** at [`ZB.MOM.WW.Auth/`](ZB.MOM.WW.Auth/)
|
||||
(a plain directory of this repo — no nested `.git`, verified 2026-08-07; .NET 10; 4 packages — `Abstractions`, `Ldap`, `ApiKeys`, `AspNetCore`;
|
||||
250 tests passing + 2 skipped (verified 2026-08-10 at `0.2.0`; was 215+1 at `0.1.5`); feed carries `0.1.0`–`0.2.0`). The implementation plan is at
|
||||
[`docs/plans/2026-06-01-zb-mom-ww-auth-shared-library.md`](docs/plans/2026-06-01-zb-mom-ww-auth-shared-library.md).
|
||||
**Adopted across all three apps on 2026-06-02** (auth GAPS #1–#8) on each repo's `feat/adopt-zb-auth` branch —
|
||||
committed + reviewed, then **fast-forward-merged into the repo's local default (main/master) and PUSHED to origin
|
||||
(gitea) on 2026-06-03** (in sync; the `feat/*` branches kept locally as history). Cutover: shared `Auth.Ldap`,
|
||||
`Auth.ApiKeys` (ScadaBridge inbound fully re-architected to the keyId/Bearer model), `IGroupRoleMapper<TRole>` seam,
|
||||
`Transport`-enum config, canonical `ZbClaimTypes`/`ZbCookieDefaults`, unified dev base DN `dc=zb,dc=local`, and the
|
||||
canonical-six role vocabulary (with ScadaBridge's accepted auditor/admin SoD collapse). Consumer pins: **all four apps pin `0.3.0` as of 2026-09-03** (commits listed in the table row above, all pushed to origin); all four pinned `0.2.1` from 2026-08-13 before that. Prior history — all four pinned `0.1.5` (verified 2026-08-07): MxGateway via `e107019` 2026-07-18 (earlier bumped `0.1.2`→`0.1.4` 2026-07-09 for the G-2 API-key-expiry verifier enforcement — commit `197731a`; also required implementing the 0.1.3 `IApiKeyAdminStore.SetScopes/SetEnabled` members on a test fake), ScadaBridge `50d79ed1` + HistorianGateway `df211ee` 2026-07-18, OtOpcUa `1adaa2fc` 2026-07-20 (PR #484, family alignment from `0.1.1`). Per-repo detail in [`components/auth/GAPS.md`](components/auth/GAPS.md) +
|
||||
`docs/plans/2026-06-02-auth-audit-normalization*.md`.
|
||||
Build/test from `ZB.MOM.WW.Auth/`: `dotnet test` (the `ApiKeys.SqlServer` live suite is gated on `AUTH_SQLSERVER_CONNSTR`, skipped otherwise). Consumer matrix: OtOpcUa → Abstractions+Ldap+AspNetCore;
|
||||
MxAccessGateway & HistorianGateway → the original four; ScadaBridge → those four **plus `ApiKeys.SqlServer`** (ApiKeys not used by OtOpcUa).
|
||||
**`0.1.4` (2026-07-09, archreview G-2):** optional `ApiKeyRecord.ExpiresUtc` (nullable = never-expires), `ApiKeyFailure.KeyExpired`, `ApiKeyVerifier` expiry enforcement (inclusive, injected clock), a `CreateKeyAsync(expiresUtc)` overload, and a SQLite **schema v3** additive `expires_utc` column (idempotent `ALTER`; donor v2 DBs upgrade in place, no key invalidated). **All four Auth pkgs published to the Gitea feed at `0.1.4`** (2026-07-09). **HistorianGateway adopted the expiry surface at `0.1.4`** — `apikey create --expires` + dashboard Expires column (Task-10 done). **`0.1.5` (2026-07-18)** is `0.1.4` plus the `SQLitePCLRaw.lib.e_sqlite3 2.1.12` transitive security pin (GHSA-2m69-gcr7-jv3q), no API change; all four apps now pin it (see consumer pins above). **`0.2.0` (2026-08-10) — LDAP backup-DC sticky failover** (plan `docs/plans/2026-08-10-ldap-backup-dc-failover.md`, design `…-design.md`; **4 pkgs published to the feed, restore-verified**; family `Directory.Build.props` now `0.2.0`): one additive `LdapOptions.FallbackServers` list (`"host"` or `"host:port"`, empty default = failover off, single-endpoint behaviour byte-unchanged) makes `LdapAuthService` walk an ordered endpoint list (primary + fallbacks) on **system-side failures only** — connect/TLS, service-account bind, or search. A user-side answer from a healthy directory (`Success`/`UserNotFound`/`AmbiguousUser`/`BadCredentials`/`GroupLookupFailed`) is **final and never retried elsewhere** (re-asking a second DC about a rejected password would multiply one bad-password event into several against the account lockout policy). Endpoint preference is **sticky** — the last endpoint that gave *any* authoritative answer (success **or** a user-side failure) is tried first next time — so a primary outage costs its connect timeout once, not per login; an exhausted walk leaves the preference untouched. Fail-closed contract preserved per-endpoint; boot validation rejects a malformed `FallbackServers` entry naming the field; optional `ILogger<LdapAuthService>` emits a Warning per failed hop (endpoint + stage, no secrets) and an Information on sticky change; wired via `AddZbLdapAuth` (`GetService`, so logging is optional). Motivation: the ZB production directory is NAM AD with two DCs. Unit suite covers the walk/stickiness (14 tests) + env-gated live GLAuth failover test (`ZB_LDAP_IT=1`). **No `Abstractions` contract change beyond the new option; no `LdapAuthFailure` enum change.** App adoption (pin bump to `0.2.0` + authoring `FallbackServers`) is a follow-up.
|
||||
**`0.2.1` (2026-08-12) — AD continuation referrals no longer fail the search** (**4 pkgs published to the feed, restore-verified**; the assembly restored *from the feed* carries the fix and `0.2.0` does not — checked as a positive control, not by trusting the push). Active Directory answers **any search based at a domain root** with continuation references (to `CN=Configuration`, `DC=ForestDnsZones`, …). With referral following disabled — the default, and what we want, since chasing one would re-bind somewhere we never authenticated — Novell surfaces each by throwing `LdapReferralException` from `Next()`. That escaped `NovellLdapConnection.Search`, and `LdapAuthService` maps a failed search to `ServiceAccountBindFailed`, so **every login against `SearchBase = DC=nam,DC=zimmer,DC=com` failed system-side on both DCs while the directory, the credentials and the service account were all healthy** — ~546 ms, identical on each endpoint, so failover could not help either. Found by the new `tools/LdapProbe` (below) and live-proven fixed against the ZB NAM domain root. The search loop now skips referrals (`ReadEntries(ILdapSearchResults)`, extracted so it is unit-testable through the Novell seam without a live directory) and continues; a 1000-referral cap guards a client that throws without advancing, since that would spin forever inside a fail-closed auth path. **Non-referral faults still propagate** — swallowing those would turn "the directory is broken" into "no such user", which is the wrong answer to give about someone's credentials. 7 new tests (`NovellSearchReferralTests`), **6 verified red against the pre-fix code**, the seventh being the non-referral control that must stay green; suite 257 pass / 2 skip / 0 fail. **No `Abstractions` change; no config change.** **Consumer impact: an app on `0.1.5` cannot authenticate against an AD domain root at all**, so the pin bump is a functional fix, not housekeeping. **Closed 2026-08-13: all four apps adopted `0.2.1`** (see the table row for commits), and `FallbackServers` was live-gated the same day against the redundant local GLAuth pair (`infra/glauth-redundant/`).
|
||||
|
||||
**`0.3.0` (2026-09-02) — `ZB.MOM.WW.Auth.ApiKeys.SqlServer`, a SQL Server provider for the API-key store** (design `ScadaBridge/docs/plans/2026-09-02-inbound-api-key-shared-store-design.md`; **5 pkgs published to the feed**, `ApiKeys.SqlServer` search-verified from the ScadaBridge checkout; family `Directory.Build.props` now `0.3.0`). Motivation: `Auth.ApiKeys`' SQLite store is a per-node file, so on a two-node active/standby host (ScadaBridge central) a key minted on one node exists only there and a failover 401s every inbound caller (ScadaBridge deferred-work row 108). The new package implements `IApiKeyStore`/`IApiKeyAdminStore`/`IApiKeyAuditStore` over `Microsoft.Data.SqlClient` in a `zbauth` schema (v1: `schema_version`, `api_keys`, `api_key_audit`; all timestamps `DATETIMEOFFSET(7)`, tick-exact) with a concurrent-boot-safe migrator (Serializable tx, retry on 1205/2714/1913/2627 with **jittered** backoff — the Secrets replicator's flat `100*attempt` backoff exhausted five retries about once per sixty 8-way boots in the port's soak test, so the same latent defect is an open follow-up there → #18) and a `SqliteApiKeyStoreImporter` that copies an existing SQLite file into the schema insert-where-absent (idempotent, so both nodes of a pair can import their own file and the result is the union). Wiring: `services.AddZbApiKeyAuthSqlServer(config, apiKeySection, sqlServerSection)` registers the SQL Server stores + migrator **before** delegating to `AddZbApiKeyAuth`, whose `TryAdd*` registrations then yield (same displacement mechanism as Secrets 0.5.0). One `Abstractions` addition, additive: `IApiKeyStoreMigrator`, which `SqliteAuthStoreMigrator` now implements and `ApiKeyAdminCommands` accepts via a new ctor (old `SqliteAuthStoreMigrator` ctor retained — the three `0.2.1` consumers compile unchanged). Store semantics are pinned to the SQLite contract tests re-run live (mark-used skips revoked keys, delete only removes revoked keys, rotate clears last-used/revoked, list newest-first). 92 tests in the new project, 351 across the solution, 0 failed. A DBA-run copy of the DDL ships at `docs/sql/zbauth-schema.sql`.
|
||||
|
||||
**`tools/LdapProbe`** (`ldapprobe`, not packable, outside the Auth solution) is the diagnostic that found the above: it drives the **real** `LdapAuthService` so its verdict is what the four apps produce, then separately queries the directory for what the library cannot report — full group DNs, **nested** groups via `LDAP_MATCHING_RULE_IN_CHAIN`, the **primary group** (which AD omits from `memberOf`, so it can never be a role group), group type (security vs distribution), decoded `userAccountControl`, referral counts, and the TLS chain with key sizes. `--list-groups '<pat>'` enumerates every group in the directory matching a pattern, which a membership dump structurally cannot do. Findings recorded in [`ldap_setup.md`](ldap_setup.md), including the **`UG_WW_*` Wonderware group convention (39 groups)** that partly overturns that doc's earlier "no group→role convention exists" claim — it was true of Ignition, false of the domain.
|
||||
|
||||
**`0.5.0` (2026-11-12, ScadaBridge#46) — passwordless group lookup; first published version carrying 0.4.2–0.4.4.** New `Abstractions` contract `ILdapGroupLookup.GetUserGroupsAsync(username, ct)` → `LdapGroupLookupResult` / `LdapGroupLookupStatus` (`Found`, `UserNotFound`, `UserDisabled` (AD `userAccountControl` bit 2), `AmbiguousUser`, `DirectoryUnavailable`, `NotSupported` (`BindMode=User` / blank service DN / foreign `ILdapAuthService`), `ProviderDisabled`). Implemented by `LdapAuthService` (service-account bind + `UserNameAttribute` search; same extraction/canonicalisation as sign-in; the endpoint walk was factored into one generic `WalkEndpoints<T>` shared by both paths, so failover and the sticky preference are common). `AddZbLdapAuth` registers it as the same singleton. Tests: 30 unit (`LdapGroupLookupTests`, 6 mutations all killed) + 2 DI + 6 live GLAuth (`GLAuthGroupLookupTests`, run against the redundant local pair incl. two-live-endpoint failover; failover mutation killed live). **scadaproj#51 closed by a live NAM run (24/24)** — see README §0.5.0/§0.4.4 for what was proven; the identity check's non-vacuity was shown by mutating the `msDS-PrincipalName` comparison (user-bind sign-ins then fail). Consumers: ScadaBridge adopts 0.5.0 (#46); OtOpcUa / mxgw / HistorianGateway / BTDB stay on their pins.
|
||||
|
||||
**`0.4.4` (first published in 0.5.0, scadaproj#40, Auth-007):** `BindMode=User` now proves the entry whose groups it returns is the account that bound — RFC 4532 Who-am-I (`dn:` → DN match; AD `u:DOMAIN\name` → `sAMAccountName` match), falling back to the bind DN only for a DN template (GLAuth has no Who-am-I); otherwise `GroupLookupFailed`. `{0}` is RFC 4514-escaped in DN templates. Before the fix a user could sign in with another account's groups whenever the UPN/DN bind and the `UserNameAttribute` search named different accounts — reproduced live against a throwaway GLAuth (`tests/ZB.MOM.WW.Auth.Ldap.Tests/Integration/glauth-userbind/`, `ZB_LDAP_USERBIND_IT=1`, port 3897): pre-fix `mallory` signed in with `Admins`. **Consumer impact:** AD + down-level/UPN template unchanged for consistent accounts (BTDB Manager is the only user-bind consumer); non-AD user-bind needs a DN template that yields the entry's DN exactly as searched (GLAuth: `cn={0},ou=<group>,ou=users,<base>`). README §0.4.4.
|
||||
|
||||
**`0.4.4`, continued (first published in 0.5.0, scadaproj#46 + #50):** still `0.4.4`.
|
||||
- **Auth-008 (`ApiKeys.SqlServer`):** over-length key records are refused with `ArgumentException`; an over-64 key-id lookup answers not-found without querying; every `key_id` predicate adds an exact `VARBINARY` match, so lookups are case- and trailing-space-exact like SQLite. No schema change. `ApiKeyImportResult` gains the `init` lists `KeyIdCollisions` and `KeysRejected`, and `KeysSkipped` now counts exact duplicates only. Audit text is still truncated to 64 characters, deliberately (documented).
|
||||
- **Auth-009:** the canonical username is the `UserNameAttribute` value matching the typed name, ignoring case, not `values[0]`.
|
||||
- **Auth-010:** the new `ApiKeyFailure.StoreUnavailable` (appended) is returned when `FindByKeyIdAsync` throws; only cancellation still throws.
|
||||
- **#50 (user bind, AD forests):** for a `u:DOMAIN\name` Who-am-I answer, the entry must be that domain's account. Where AD offers `msDS-PrincipalName` (a base read through the new internal `ILdapConnection.Read`), it must equal the answer. Otherwise the name must have exactly one holder under `SearchBase`. Live-verified against the NAM AD 2026-11-12 (scadaproj#51, see 0.5.0).
|
||||
- **Consumer-facing:** a new enum value; SQL Server key ids now match exactly; over-length creates throw; the importer reports collisions and rejections.
|
||||
- Suites: 363 passed / 81 skipped offline; 440 passed / 4 skipped (LDAP live) with `AUTH_SQLSERVER_CONNSTR`, against a throwaway SQL Server 2022.
|
||||
|
||||
**`0.4.3` (unpublished, scadaproj#26):** `Microsoft.Data.Sqlite` 10.0.7 -> 10.0.13 (efcore#39009 pool fault); `SQLitePCLRaw.lib.e_sqlite3` transitive pin 2.1.12 -> 2.1.13 (10.0.13 floors 2.1.13). No API change.
|
||||
|
||||
**`0.4.2` (unpublished, scadaproj#23 + #22):** `ZB.MOM.WW.Auth.ApiKeys.ApiKeyPepperUnavailableException : InvalidOperationException` (message still `"pepper unavailable"`) is now thrown by `ApiKeyAdminCommands` create/rotate when the pepper is missing, so consumers can catch it by type; existing `catch (InvalidOperationException)` blocks keep working (only exact-type assertions like xunit `ThrowsAsync<InvalidOperationException>` need updating). **Release note: consumers can drop their own `IApiKeyPepperProvider` pre-checks** — mxaccessgw's `DashboardApiKeyManagementService` and any similar code. Also pins `System.Security.Cryptography.Pkcs 9.0.21` (transitive, via SqlClient 6.0.2) to clear NuGetAudit NU1902/NU1903. Not yet published to the feed.
|
||||
@@ -5,7 +5,16 @@
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<LangVersion>latest</LangVersion>
|
||||
<Version>0.1.5</Version>
|
||||
<!-- 0.4.0: opt-in LdapOptions.BindMode = User — authenticate by binding as the signing-in user
|
||||
(UserBindTemplate) and read their own groups on the same connection; no service account.
|
||||
ServiceAccount stays the default, so existing consumers need no change. -->
|
||||
<!-- 0.4.1: Username canonicalised from the entry's UserNameAttribute; empty passwords refused
|
||||
in both bind modes (ServiceAccount-mode behaviour change); template docs prefer EXAMPLE\{0}. -->
|
||||
<!-- 0.4.2: typed ApiKeyPepperUnavailableException (: InvalidOperationException) for a missing pepper on
|
||||
create/rotate; patched System.Security.Cryptography.Pkcs transitive pin (SqlServer package). -->
|
||||
<!-- 0.5.0: passwordless group lookup — ILdapGroupLookup.GetUserGroupsAsync (service account; shares the
|
||||
endpoint walk / sticky preference / TLS policy with AuthenticateAsync). Includes the unpublished 0.4.2–0.4.4. -->
|
||||
<Version>0.5.0</Version>
|
||||
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
|
||||
</PropertyGroup>
|
||||
|
||||
|
||||
@@ -11,10 +11,23 @@
|
||||
<PackageVersion Include="Novell.Directory.Ldap.NETStandard" Version="3.6.0" />
|
||||
|
||||
<!-- Data -->
|
||||
<PackageVersion Include="Microsoft.Data.Sqlite" Version="10.0.7" />
|
||||
<!-- Transitive security pin: Microsoft.Data.Sqlite 10.0.7 pulls SQLitePCLRaw.lib.e_sqlite3 2.1.11,
|
||||
which carries advisory GHSA-2m69-gcr7-jv3q (NU1903). Pin the patched 2.1.12 native lib. -->
|
||||
<PackageVersion Include="SQLitePCLRaw.lib.e_sqlite3" Version="2.1.12" />
|
||||
<PackageVersion Include="Microsoft.Data.Sqlite" Version="10.0.13" />
|
||||
<!-- Transitive security pin: Microsoft.Data.Sqlite pulled SQLitePCLRaw.lib.e_sqlite3 2.1.11 (10.0.7); 10.0.13 floors 2.1.13 (scadaproj#26),
|
||||
which carries advisory GHSA-2m69-gcr7-jv3q (NU1903). Pin the patched 2.1.13 native lib. -->
|
||||
<PackageVersion Include="SQLitePCLRaw.lib.e_sqlite3" Version="2.1.13" />
|
||||
<!-- Shared SQL-Server API-key store (ZB.MOM.WW.Auth.ApiKeys.SqlServer). 6.0.2 matches the
|
||||
family pin used by ZB.MOM.WW.Secrets' SQL-Server store, so a consumer taking both gets one
|
||||
SqlClient rather than a downgrade warning. -->
|
||||
<PackageVersion Include="Microsoft.Data.SqlClient" Version="6.0.2" />
|
||||
<!-- 9.0.4, not 9.0.0: Microsoft.Data.SqlClient 6.0.2 pulls System.Configuration.ConfigurationManager
|
||||
9.0.4, which requires ProtectedData >= 9.0.4. With transitive pinning on, the lower central
|
||||
version is a hard NU1109 downgrade error rather than a silent resolve. -->
|
||||
<PackageVersion Include="System.Security.Cryptography.ProtectedData" Version="9.0.4" />
|
||||
<!-- Transitive security pin (scadaproj#22): Microsoft.Data.SqlClient 6.0.2 pulls
|
||||
System.Security.Cryptography.Pkcs 9.0.4, which carries GHSA-846f-f764-76mx (high) and
|
||||
GHSA-2fmv-rv2c-59x7 (moderate) and fails restore under warnings-as-errors (NU1902/NU1903).
|
||||
Pin the patched 9.0.21 (first fixed in the 9.0 line; 9.0.0-9.0.20 and 10.0.0-10.0.12 are all affected). -->
|
||||
<PackageVersion Include="System.Security.Cryptography.Pkcs" Version="9.0.21" />
|
||||
|
||||
<!-- Extensions -->
|
||||
<PackageVersion Include="Microsoft.Extensions.Options" Version="10.0.7" />
|
||||
@@ -24,6 +37,7 @@
|
||||
<PackageVersion Include="Microsoft.Extensions.Configuration.Abstractions" Version="10.0.7" />
|
||||
<PackageVersion Include="Microsoft.Extensions.Configuration" Version="10.0.7" />
|
||||
<PackageVersion Include="Microsoft.Extensions.Hosting.Abstractions" Version="10.0.7" />
|
||||
<PackageVersion Include="Microsoft.Extensions.Logging.Abstractions" Version="10.0.7" />
|
||||
|
||||
<!-- ASP.NET Core Authentication / Authorization -->
|
||||
<PackageVersion Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.7" />
|
||||
|
||||
@@ -11,17 +11,18 @@ Authentication and authorisation libraries for the **ZB.MOM.WW SCADA family** (O
|
||||
| `ZB.MOM.WW.Auth.Abstractions` | Auth contracts, canonical role constants, and shared types (`LdapOptions`, `LdapAuthResult`, `ILdapAuthService`, `IApiKeyStore`). No runtime dependencies beyond the BCL. | — |
|
||||
| `ZB.MOM.WW.Auth.Ldap` | LDAP authentication service: bind-then-search-then-bind against GLAuth or Active Directory; RFC 4514-aware group extraction; fail-closed. | `Abstractions`, `Novell.Directory.Ldap.NETStandard` |
|
||||
| `ZB.MOM.WW.Auth.ApiKeys` | SQLite-backed API-key store with **pepper-keyed HMAC-SHA256** secret hashing, rotation, and audit log. DI wiring is `AddZbApiKeyAuth`; an opt-in `MigrationHostedService` runs schema migrations on startup. | `Abstractions`, `Microsoft.Data.Sqlite` |
|
||||
| `ZB.MOM.WW.Auth.ApiKeys.SqlServer` | SQL Server-backed API-key store sharing **one row set** across clustered hosts (e.g. a central pair), instead of each node keeping its own SQLite file. DI wiring is `AddZbApiKeyAuthSqlServer(config, apiKeySection, sqlServerSection)`, called **instead of** `AddZbApiKeyAuth` (it calls that internally). Also ships `SqliteApiKeyStoreImporter` — a one-shot per-node SQLite → shared store copy a host runs once at boot. | `Abstractions`, `ApiKeys`, `Microsoft.Data.SqlClient` |
|
||||
| `ZB.MOM.WW.Auth.AspNetCore` | ASP.NET Core wiring for the **LDAP** provider only: `AddZbLdapAuth` (binds + start-time-validates `LdapOptions`, registers `ILdapAuthService`), plus `ZbCookieDefaults.Apply` (hardened cookie helper the consumer calls itself) and `ZbClaimTypes` constants. It does **not** wire API keys or cookie middleware — API-key DI is `AddZbApiKeyAuth` in the `ApiKeys` package. | `Abstractions`, `Ldap`, `Microsoft.AspNetCore.App` |
|
||||
|
||||
---
|
||||
|
||||
## Consumer Matrix
|
||||
|
||||
| Consumer | Abstractions | Ldap | ApiKeys | AspNetCore |
|
||||
|---|:---:|:---:|:---:|:---:|
|
||||
| **OtOpcUa** | yes | yes | — | yes |
|
||||
| **MxAccessGateway** | yes | yes | yes | yes |
|
||||
| **ScadaBridge** | yes | yes | yes | yes |
|
||||
| Consumer | Abstractions | Ldap | ApiKeys | ApiKeys.SqlServer | AspNetCore |
|
||||
|---|:---:|:---:|:---:|:---:|:---:|
|
||||
| **OtOpcUa** | yes | yes | — | — | yes |
|
||||
| **MxAccessGateway** | yes | yes | yes | — | yes |
|
||||
| **ScadaBridge** | yes | yes | yes | yes (central pair, 2026-09-02) | yes |
|
||||
|
||||
`ApiKeys` is NOT used by OtOpcUa (that app authenticates human operators via LDAP + cookies only; machine-to-machine access is out of scope).
|
||||
|
||||
@@ -29,7 +30,73 @@ Authentication and authorisation libraries for the **ZB.MOM.WW SCADA family** (O
|
||||
|
||||
## Versioning
|
||||
|
||||
All four packages are versioned **lockstep** from `Directory.Build.props`. The current release is **0.1.4**. A single version bump in `Directory.Build.props` bumps all four packages simultaneously — consumers should reference the same version for all ZB.MOM.WW.Auth packages.
|
||||
All five packages are versioned **lockstep** from `Directory.Build.props`. The current release is **0.5.0**. A single version bump in `Directory.Build.props` bumps all five packages simultaneously — consumers should reference the same version for all ZB.MOM.WW.Auth packages.
|
||||
|
||||
### 0.5.0 — passwordless group lookup (`ILdapGroupLookup`, ScadaBridge#46)
|
||||
|
||||
Includes every unpublished 0.4.2–0.4.4 change below; **0.5.0 is the first published version carrying them** (scadaproj#51 live-verified them against the NAM AD before publishing).
|
||||
|
||||
- **New `Abstractions` contract:** `ILdapGroupLookup.GetUserGroupsAsync(string username, CancellationToken ct)` → `LdapGroupLookupResult(Status, Username, DisplayName, Groups)`, with `LdapGroupLookupStatus` = `Found` | `UserNotFound` | `UserDisabled` | `AmbiguousUser` | `DirectoryUnavailable` | `NotSupported` | `ProviderDisabled`. It re-reads a known user's groups **without their password** — e.g. to refresh an active session when directory membership changes.
|
||||
- **`LdapAuthService` implements it** (`AddZbLdapAuth` registers `ILdapGroupLookup` as the *same* singleton, so sign-in and lookup share one sticky endpoint preference). It binds as the **service account**, searches `UserNameAttribute` under `SearchBase`, and returns the same group set, canonical username and display name `AuthenticateAsync` would — through the same group extraction, canonicalisation, endpoint walk (`FallbackServers`, system-side failures only), timeouts and TLS policy. The name is normalised as `AuthenticateAsync` normalises it in `ServiceAccount` mode (trimmed).
|
||||
- **Outcomes:** connect/TLS, service-account bind or search failing on every endpoint → `DirectoryUnavailable` (a statement about the directory, never about the user). `UserDisabled` comes from AD's `userAccountControl` ACCOUNTDISABLE bit (requested automatically; directories without the attribute never report it). `Found` may carry **zero** groups — sign-in refuses such a user, the caller decides. `BindMode = User` (no service account) and a blank `ServiceAccountDn` answer `NotSupported` without touching the network; `Enabled = false` answers `ProviderDisabled`. Never throws (cancellation at entry only); credentials are never logged.
|
||||
- A host that registers its own `ILdapAuthService` (a dev stub, a decorator) gets a lookup that answers `NotSupported`.
|
||||
- **Consumer impact:** additive. No existing signature or enum value changed in 0.5.0 itself; the 0.4.2–0.4.4 notes below still apply to anyone coming from 0.4.1.
|
||||
- **Live-verified 2026-11-12 against the NAM AD** (both DCs, LDAPS 636, StartTLS 389, the Global Catalog 3269 with a forest-wide base): lookup groups == sign-in groups (176), a real disabled account → `UserDisabled`, unknown → `UserNotFound`, failover to either DC, all-dead / wrong service password → `DirectoryUnavailable`, `User` mode → `NotSupported`. Plus GLAuth (redundant local pair) integration tests `GLAuthGroupLookupTests`.
|
||||
|
||||
### 0.4.4 — user bind proves the bound account is the one whose groups it returns (first published in 0.5.0, scadaproj#40)
|
||||
|
||||
- **Security fix (Auth-007), `BindMode = User` only.** The bind name (`UserBindTemplate`) and the group search (`UserNameAttribute`) are two separate directory lookups and could name two accounts — e.g. AD resolves `jsmith@corp.com` to the account with that explicit UPN while `(sAMAccountName=jsmith)` finds a different one, so a user could sign in with another account's groups. The service now only accepts the entry it found when it is provably the account that bound:
|
||||
- it asks the directory with RFC 4532 **Who-am-I** after the bind; a `dn:<dn>` answer must equal the entry's DN (`distinguishedNameMatch`), and AD's `u:DOMAIN\name` answer must equal the entry's `sAMAccountName` (requested automatically);
|
||||
- a server without Who-am-I (GLAuth answers protocol error 2) is supported only with a **DN template** (contains `=`), whose bind DN must equal the entry's DN;
|
||||
- anything else — a mismatch, an unanswered Who-am-I with a UPN or down-level template — is `GroupLookupFailed`, logged at Warning, and never retried on a fallback endpoint.
|
||||
- **`{0}` is now RFC 4514-escaped in a DN template**, so a typed name such as `x,ou=Admins` cannot rewrite the bind DN.
|
||||
- **Behaviour change for consumers:** AD with a down-level or UPN template is unaffected for accounts whose bound identity and searched entry agree (AD has supported Who-am-I since Windows Server 2003). A UPN template now refuses accounts whose UPN prefix differs from `sAMAccountName` instead of risking the wrong account. A **non-AD directory** in `User` mode needs either Who-am-I support or a DN template that yields the entry's DN *exactly as the search returns it* — for GLAuth that is `cn={0},ou=<group>,ou=users,<base>`, not `cn={0},ou=<group>,<base>`. ServiceAccount mode is unchanged.
|
||||
- The validator's `UserBindTemplate` message now leads with `EXAMPLE\{0}`. No `Abstractions` contract change (XML docs only).
|
||||
- **AD forests (scadaproj#50).** `sAMAccountName` is unique per *domain*, so with a search base that spans a forest (a Global Catalog) a matching `sAMAccountName` alone could be another domain's account of the same name. For AD's `u:DOMAIN\name` answer the entry must now also be proven to be that domain's account:
|
||||
- where the directory computes `msDS-PrincipalName` for the entry (a base read; AD's `DOMAIN\name`, derived from `objectSid`), it must equal the Who-am-I answer, domain included;
|
||||
- otherwise the name must have exactly one holder under `SearchBase`, and it must be the entry found — no extra search is made when `UserNameAttribute` is `sAMAccountName` and the user typed the bound name, because the user search already proved that. Two holders → `GroupLookupFailed`.
|
||||
- A single-domain AD (BTDB Manager) is unaffected. **Live-verified against the NAM AD 2026-11-12 (scadaproj#51):** `User` mode with `NAM\{0}` and the UPN template both sign in with the same groups as `ServiceAccount` mode; AD answers Who-am-I as `u:NAM\<sAMAccountName>` and serves `msDS-PrincipalName` on a base read (DC and Global Catalog); a forest-wide Global Catalog base (`DC=zimmer,DC=com`) signs in correctly; and mutating the `msDS-PrincipalName` comparison makes every user-bind sign-in fail `GroupLookupFailed`, so that check is what decides against real AD.
|
||||
- **`ApiKeyFailure.StoreUnavailable` (Auth-010, `Abstractions` addition).** `ApiKeyVerifier.VerifyAsync` no longer lets a key-store fault escape: a `FindByKeyIdAsync` that throws (shared SQL Server unreachable, a SQLite I/O fault) returns `Succeeded = false` with the new `StoreUnavailable` failure, so it takes the host's normal — audited — auth-failure path instead of an unhandled 500 / gRPC `Unknown`. Cancellation still throws. The value is appended, so existing numeric values are unchanged; a host may answer it with 503 rather than 401. A misconfigured `SqlServerApiKeyOptions` still throws when the store is first resolved (outside `VerifyAsync`).
|
||||
- **SQL Server store: no truncation, exact key ids (Auth-008).** The `ApiKeys.SqlServer` stores now behave like the SQLite store they port:
|
||||
- `CreateAsync` throws `ArgumentException` for a key id over 64, prefix over 16 or display name over 256 characters (it used to store them silently truncated), and every lookup of an over-64-character key id answers "not found" without querying (a truncated parameter could match a different key sharing its first 64 characters).
|
||||
- Key-id matching is **exact** — case- and trailing-space-sensitive — via a binary comparison added to every `key_id` predicate; the primary-key seek is unchanged and there is **no schema change**. A token presented with a case-altered key id (`LINE1` for `line1`) now fails `KeyNotFound` instead of resolving.
|
||||
- `SqliteApiKeyStoreImporter` reports instead of hiding: `ApiKeyImportResult.KeyIdCollisions` lists source keys whose id differs only in case from one already in SQL Server (the primary key follows the database collation and cannot hold both — re-mint those keys), and `KeysRejected` lists over-length keys; neither is counted in `KeysSkipped` any more. Both are new `init` properties, so existing code is unaffected.
|
||||
- Audit text (`key_id`, `event_type`, `remote_address`) is still truncated to 64 characters — deliberately, and now documented: an audit append runs after the action it records and must not fail it.
|
||||
- **Canonical username from a multi-valued attribute (Auth-009).** `LdapAuthResult.Username` is now the `UserNameAttribute` value that equals the typed name ignoring case — `cn: [John Smith, jsmith]` signs `jsmith` in as `jsmith`, not whichever value the server lists first. The first value is used only when none matches. Both bind modes.
|
||||
|
||||
### 0.4.1 — LDAP review fixes
|
||||
|
||||
- **Canonical username (both modes):** the search now also requests `UserNameAttribute`, and `LdapAuthResult.Username` is the entry's first value of it (the directory's spelling), so `JDoe` and `jdoe` sign in as one identity in consumers' audit columns. Falls back to the normalised typed name when the entry has no such value.
|
||||
- **Behaviour change for `ServiceAccount`-mode consumers:** an empty (or null) password is now refused by the library as `BadCredentials` before any network call, in both bind modes. Previously only `User` mode refused it; in `ServiceAccount` mode the re-bind as the user's DN with an empty password is an unauthenticated bind that AD reports as success, so a consumer without its own edge check admitted anyone.
|
||||
- **Template guidance:** prefer the down-level `UserBindTemplate` `EXAMPLE\{0}` — it maps exactly to the `sAMAccountName` the group search uses. A UPN template (`{0}@example.com`) is only correct where every account's UPN prefix equals its `sAMAccountName`; AD resolves UPN binds against the explicit `userPrincipalName`, so a mismatch can fail sign-in or bind a different account than the one whose groups are read.
|
||||
- No `Abstractions` contract change.
|
||||
|
||||
### 0.4.0 — LDAP sign-in by user bind (opt-in)
|
||||
|
||||
- **`LdapOptions.BindMode`** (`ServiceAccount` default | `User`), **`UserBindTemplate`** (`{0}` = the login name, e.g. `EXAMPLE\{0}` — preferred, see 0.4.1 — or `{0}@example.com`) and **`AcceptDomainQualifiedNames`** (default `true`).
|
||||
- In `User` mode `LdapAuthService` binds as the user; success authenticates them and the same connection reads their entry (`UserNameAttribute`, `DisplayNameAttribute`, `GroupAttribute`). No `ServiceAccountDn` / `ServiceAccountPassword` is needed or validated.
|
||||
- Failure mapping: empty password or an unusable name → `BadCredentials` with no network call (AD treats an empty-password simple bind as an unauthenticated success). Bind result 49 → `BadCredentials`, final — never retried on a fallback DC, so one wrong password is one lockout strike. Any other bind error, a connect failure or a search failure → the system-side bucket (`ServiceAccountBindFailed`) and the next endpoint. Zero/several entries or no groups after a good bind → `GroupLookupFailed`.
|
||||
- `DOMAIN\name` / `name@suffix` are reduced to `name` (or refused when `AcceptDomainQualifiedNames` is `false`), so the result's `Username` has one spelling (0.4.1 also canonicalises its case from the entry).
|
||||
- No `Abstractions` contract change beyond the new enum and option properties; `ServiceAccount` mode is unchanged.
|
||||
- `UserBindTemplate` output is used verbatim as the bind name, so use a down-level (`EXAMPLE\{0}`, preferred) or UPN (`{0}@example.com`, only where every UPN prefix equals the `sAMAccountName`) template; a DN template is not escaped.
|
||||
|
||||
### 0.3.0 — SQL Server API-key store (ScadaBridge central pair)
|
||||
|
||||
- **`IApiKeyStoreMigrator`** added to `Abstractions`: creates or upgrades an API-key store's schema; idempotent and safe to run concurrently from several nodes. `SqliteAuthStoreMigrator` implements it unchanged. `AddZbApiKeyAuth` registers the SQLite implementation via `TryAdd`, so a provider that registers its own migrator first (see below) wins — that ordering is the whole mechanism by which a different backend is swapped in.
|
||||
- **New package `ZB.MOM.WW.Auth.ApiKeys.SqlServer`** + `AddZbApiKeyAuthSqlServer(config, apiKeySection, sqlServerSection)`, called instead of `AddZbApiKeyAuth` (it calls it internally after registering the SQL Server stores and migrator first).
|
||||
- **`zbauth` schema v1** (three tables: `schema_version`, `api_keys`, `api_key_audit`; `DATETIMEOFFSET(7)` timestamps). `SqlServerApiKeyStoreMigrator` is concurrent-boot safe — a central pair's two nodes both migrate at every boot — with retry on SQL error numbers 1205/2714/1913/2627 and jittered backoff (measured: the flat backoff it replaced exhausted its retries roughly 1 in 60 eight-way boots). DBA-facing DDL: `docs/sql/zbauth-schema.sql`.
|
||||
- **`SqliteApiKeyStoreImporter`** — idempotent insert-where-not-exists copy of an existing node's per-node SQLite keys and audit rows into the shared store; a row already present in SQL Server is never modified, so running it from both nodes of a pair converges on the union of their files.
|
||||
- **`ApiKeyAdminCommands`** gained a ctor taking `IApiKeyStoreMigrator`; the existing ctor taking the concrete `SqliteAuthStoreMigrator` is retained (MxAccessGateway, HistorianGateway and ScadaBridge all construct it that way).
|
||||
- SQLite remains the default store; **existing consumers need no code change to move to 0.3.0**.
|
||||
- Live tests for the SQL Server package are gated on `AUTH_SQLSERVER_CONNSTR` and skip (not fail) when it is unset.
|
||||
|
||||
### 0.2.1 — LDAP AD continuation-referral fix
|
||||
|
||||
- `NovellLdapConnection.Search` now skips Active Directory continuation referrals (`LdapReferralException` from `Next()`) instead of letting one fail the whole search — a `SearchBase` at a domain root made every login fail as `ServiceAccountBindFailed` against a healthy directory. Non-referral faults still propagate untouched.
|
||||
|
||||
### 0.2.0 — version bump only
|
||||
|
||||
- No functional change; bumped the lockstep family version ahead of the 0.2.1 LDAP fix.
|
||||
|
||||
### 0.1.4 — API-key expiry (archreview G-2)
|
||||
|
||||
@@ -63,6 +130,8 @@ The GLAuth integration test (`GLAuthIntegrationTests`) is **skipped by default**
|
||||
--filter "FullyQualifiedName~GLAuthIntegrationTests"
|
||||
```
|
||||
|
||||
The 0.5.0 group-lookup tests (`GLAuthGroupLookupTests`) use the same variables plus an optional `ZB_LDAP_FALLBACK=host:port` for a second live directory (e.g. the redundant pair in `infra/glauth-redundant`, `:3893` + `:3894`, service account `cn=serviceaccount,dc=zb,dc=local`).
|
||||
|
||||
All other variables (`ZB_LDAP_SERVER`, `ZB_LDAP_PORT`, `ZB_LDAP_BASE`, `ZB_LDAP_USERATTR`) default to sensible GLAuth values and are optional. The test also probes TCP reachability before attempting auth and skips if the server is not contactable.
|
||||
|
||||
---
|
||||
|
||||
@@ -2,11 +2,13 @@
|
||||
<Folder Name="/src/">
|
||||
<Project Path="src/ZB.MOM.WW.Auth.Abstractions/ZB.MOM.WW.Auth.Abstractions.csproj" />
|
||||
<Project Path="src/ZB.MOM.WW.Auth.ApiKeys/ZB.MOM.WW.Auth.ApiKeys.csproj" />
|
||||
<Project Path="src/ZB.MOM.WW.Auth.ApiKeys.SqlServer/ZB.MOM.WW.Auth.ApiKeys.SqlServer.csproj" />
|
||||
<Project Path="src/ZB.MOM.WW.Auth.AspNetCore/ZB.MOM.WW.Auth.AspNetCore.csproj" />
|
||||
<Project Path="src/ZB.MOM.WW.Auth.Ldap/ZB.MOM.WW.Auth.Ldap.csproj" />
|
||||
</Folder>
|
||||
<Folder Name="/tests/">
|
||||
<Project Path="tests/ZB.MOM.WW.Auth.ApiKeys.Tests/ZB.MOM.WW.Auth.ApiKeys.Tests.csproj" />
|
||||
<Project Path="tests/ZB.MOM.WW.Auth.ApiKeys.SqlServer.Tests/ZB.MOM.WW.Auth.ApiKeys.SqlServer.Tests.csproj" />
|
||||
<Project Path="tests/ZB.MOM.WW.Auth.AspNetCore.Tests/ZB.MOM.WW.Auth.AspNetCore.Tests.csproj" />
|
||||
<Project Path="tests/ZB.MOM.WW.Auth.Ldap.Tests/ZB.MOM.WW.Auth.Ldap.Tests.csproj" />
|
||||
</Folder>
|
||||
|
||||
@@ -6,4 +6,10 @@
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
dotnet pack -c Release -o ./artifacts
|
||||
# cd to the repo root and name the solution + an absolute output path: `dotnet pack` with
|
||||
# neither a project argument nor a fixed working directory packs whatever solution happens
|
||||
# to sit in the CALLER's directory (the bug behind the LocalDb feed incident, 0038d46).
|
||||
REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
cd "$REPO_ROOT"
|
||||
|
||||
dotnet pack ZB.MOM.WW.Auth.slnx -c Release -o "$REPO_ROOT/artifacts"
|
||||
|
||||
@@ -16,9 +16,20 @@ set -euo pipefail
|
||||
: "${GITEA_NUGET_SOURCE:?set GITEA_NUGET_SOURCE to your Gitea NuGet feed URL}"
|
||||
: "${GITEA_NUGET_KEY:?set GITEA_NUGET_KEY to your Gitea access token}"
|
||||
|
||||
dotnet pack -c Release -o ./artifacts
|
||||
# Named solution, named output, and a cd to the repo root, all for one reason: `dotnet pack`
|
||||
# with neither a project argument nor a fixed working directory packs whatever solution
|
||||
# happens to sit in the CALLER's directory — and then pushes it to a live feed under this
|
||||
# script's name. Invoked by absolute path from another repo's checkout, the relative form
|
||||
# packed and published 25 unrelated packages (LocalDb's copy of this script, fixed in
|
||||
# 0038d46; recovered with `dotnet nuget delete`, but only because the token happened to
|
||||
# carry delete rights). A publish script must be unambiguous about WHAT it publishes no
|
||||
# matter where it is run.
|
||||
REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
cd "$REPO_ROOT"
|
||||
|
||||
dotnet nuget push "./artifacts/*.nupkg" \
|
||||
dotnet pack ZB.MOM.WW.Auth.slnx -c Release -o "$REPO_ROOT/artifacts"
|
||||
|
||||
dotnet nuget push "$REPO_ROOT/artifacts/*.nupkg" \
|
||||
--source "$GITEA_NUGET_SOURCE" \
|
||||
--api-key "$GITEA_NUGET_KEY" \
|
||||
--skip-duplicate
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
-- ZB.MOM.WW.Auth.ApiKeys.SqlServer — shared API-key schema, version 1.
|
||||
--
|
||||
-- For DBAs whose application login lacks DDL rights. The host normally provisions this itself at
|
||||
-- startup (SqlServerApiKeyStoreMigrator, which runs the identical statements and is safe to run
|
||||
-- concurrently from every node); where the app login may only read and write rows, run this script
|
||||
-- once against the target database instead. The migrator then finds the version row already at the
|
||||
-- version it supports and does nothing further beyond re-stamping applied_utc.
|
||||
--
|
||||
-- The schema name is hard-coded to zbauth here — the default of SqlServerApiKeyOptions.Schema. If a
|
||||
-- deployment overrides that option, substitute the name in every bracketed identifier below.
|
||||
--
|
||||
-- Kept byte-for-byte consistent with SqlServerAuthSchema.CreateSchemaDdl apart from that
|
||||
-- substitution and the literal version row at the end; change both together.
|
||||
|
||||
IF NOT EXISTS (SELECT 1 FROM sys.schemas WHERE name = N'zbauth')
|
||||
EXEC(N'CREATE SCHEMA [zbauth]');
|
||||
|
||||
IF OBJECT_ID(N'[zbauth].[schema_version]', N'U') IS NULL
|
||||
CREATE TABLE [zbauth].[schema_version] (
|
||||
id INT NOT NULL CONSTRAINT PK_zbauth_schema_version PRIMARY KEY CHECK (id = 1),
|
||||
version INT NOT NULL,
|
||||
applied_utc DATETIMEOFFSET(7) NOT NULL
|
||||
);
|
||||
|
||||
IF OBJECT_ID(N'[zbauth].[api_keys]', N'U') IS NULL
|
||||
CREATE TABLE [zbauth].[api_keys] (
|
||||
key_id NVARCHAR(64) NOT NULL CONSTRAINT PK_zbauth_api_keys PRIMARY KEY,
|
||||
key_prefix NVARCHAR(16) NOT NULL,
|
||||
secret_hash VARBINARY(64) NOT NULL,
|
||||
display_name NVARCHAR(256) NOT NULL,
|
||||
scopes NVARCHAR(MAX) NOT NULL,
|
||||
constraints NVARCHAR(MAX) NULL,
|
||||
created_utc DATETIMEOFFSET(7) NOT NULL,
|
||||
last_used_utc DATETIMEOFFSET(7) NULL,
|
||||
revoked_utc DATETIMEOFFSET(7) NULL,
|
||||
expires_utc DATETIMEOFFSET(7) NULL
|
||||
);
|
||||
|
||||
IF OBJECT_ID(N'[zbauth].[api_key_audit]', N'U') IS NULL
|
||||
CREATE TABLE [zbauth].[api_key_audit] (
|
||||
audit_id BIGINT IDENTITY(1,1) NOT NULL CONSTRAINT PK_zbauth_api_key_audit PRIMARY KEY,
|
||||
key_id NVARCHAR(64) NULL,
|
||||
event_type NVARCHAR(64) NOT NULL,
|
||||
remote_address NVARCHAR(64) NULL,
|
||||
created_utc DATETIMEOFFSET(7) NOT NULL,
|
||||
details NVARCHAR(MAX) NULL
|
||||
);
|
||||
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM sys.indexes
|
||||
WHERE name = N'ix_api_keys_revoked_utc'
|
||||
AND object_id = OBJECT_ID(N'[zbauth].[api_keys]'))
|
||||
CREATE INDEX ix_api_keys_revoked_utc
|
||||
ON [zbauth].[api_keys] (revoked_utc);
|
||||
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM sys.indexes
|
||||
WHERE name = N'ix_api_key_audit_key_id_created_utc'
|
||||
AND object_id = OBJECT_ID(N'[zbauth].[api_key_audit]'))
|
||||
CREATE INDEX ix_api_key_audit_key_id_created_utc
|
||||
ON [zbauth].[api_key_audit] (key_id, created_utc);
|
||||
|
||||
MERGE [zbauth].[schema_version] AS target
|
||||
USING (SELECT 1 AS id, 1 AS version, SYSDATETIMEOFFSET() AS applied_utc) AS source
|
||||
ON target.id = source.id
|
||||
WHEN MATCHED THEN
|
||||
UPDATE SET version = source.version, applied_utc = source.applied_utc
|
||||
WHEN NOT MATCHED THEN
|
||||
INSERT (id, version, applied_utc) VALUES (1, source.version, source.applied_utc);
|
||||
@@ -8,7 +8,35 @@ public sealed record ApiKeyOptions
|
||||
public bool RunMigrationsOnStartup { get; init; } = true;
|
||||
}
|
||||
|
||||
public enum ApiKeyFailure { MissingOrMalformed, KeyNotFound, KeyRevoked, PepperUnavailable, SecretMismatch, KeyExpired }
|
||||
/// <summary>Why an API-key verification failed. New values are only ever appended, so stored or logged numeric values keep their meaning.</summary>
|
||||
public enum ApiKeyFailure
|
||||
{
|
||||
/// <summary>No credential, or one that does not parse as <c><prefix>_<keyId>_<secret></c>.</summary>
|
||||
MissingOrMalformed,
|
||||
|
||||
/// <summary>No key with the presented key id exists.</summary>
|
||||
KeyNotFound,
|
||||
|
||||
/// <summary>The key exists but has been revoked.</summary>
|
||||
KeyRevoked,
|
||||
|
||||
/// <summary>The pepper could not be resolved, so no key can be verified.</summary>
|
||||
PepperUnavailable,
|
||||
|
||||
/// <summary>The presented secret does not match the stored hash.</summary>
|
||||
SecretMismatch,
|
||||
|
||||
/// <summary>The key exists but its absolute expiry has passed.</summary>
|
||||
KeyExpired,
|
||||
|
||||
/// <summary>
|
||||
/// The key store could not be queried (database unreachable, misconfigured, I/O fault), so the
|
||||
/// credential could be neither accepted nor rejected on its merits. Added in 0.4.4 (Auth-010);
|
||||
/// before it, the store's exception escaped <c>VerifyAsync</c>. A host may answer it with 503
|
||||
/// rather than 401, since the caller did nothing wrong.
|
||||
/// </summary>
|
||||
StoreUnavailable,
|
||||
}
|
||||
|
||||
public sealed record ApiKeyIdentity(string KeyId, string DisplayName, IReadOnlySet<string> Scopes, object? Constraints);
|
||||
|
||||
@@ -78,3 +106,16 @@ public interface IApiKeyAuditStore
|
||||
Task AppendAsync(ApiKeyAuditEntry entry, CancellationToken ct);
|
||||
Task<IReadOnlyList<ApiKeyAuditEntry>> ListRecentAsync(int limit, CancellationToken ct);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates or upgrades the API-key store schema to the version this build supports. Each store
|
||||
/// provider (SQLite, SQL Server) supplies one; hosts run it at startup and before admin commands.
|
||||
/// Implementations must be idempotent and safe to run concurrently from several nodes.
|
||||
/// </summary>
|
||||
public interface IApiKeyStoreMigrator
|
||||
{
|
||||
/// <summary>Migrates the store schema.</summary>
|
||||
/// <param name="ct">A token to cancel the operation.</param>
|
||||
/// <returns>A task that completes when the schema is current.</returns>
|
||||
Task MigrateAsync(CancellationToken ct);
|
||||
}
|
||||
|
||||
@@ -4,6 +4,20 @@ namespace ZB.MOM.WW.Auth.Abstractions.Ldap;
|
||||
|
||||
public enum LdapTransport { Ldaps, StartTls, None }
|
||||
|
||||
/// <summary>How <see cref="LdapOptions"/> authenticates a sign-in.</summary>
|
||||
public enum LdapBindMode
|
||||
{
|
||||
/// <summary>Bind as the service account, search for the user, re-bind as the user (0.3.0 behaviour).</summary>
|
||||
ServiceAccount,
|
||||
|
||||
/// <summary>
|
||||
/// Bind as the signing-in user (identity built from <see cref="LdapOptions.UserBindTemplate"/>);
|
||||
/// a successful bind authenticates them, and the same connection reads their own entry for groups.
|
||||
/// No service account is used.
|
||||
/// </summary>
|
||||
User,
|
||||
}
|
||||
|
||||
public sealed record LdapOptions
|
||||
{
|
||||
public bool Enabled { get; init; } = true;
|
||||
@@ -19,6 +33,51 @@ public sealed record LdapOptions
|
||||
public string GroupAttribute { get; init; } = "memberOf";
|
||||
public int ConnectionTimeoutMs { get; init; } = 10_000;
|
||||
|
||||
/// <summary>
|
||||
/// Selects the authentication flow. <see cref="LdapBindMode.ServiceAccount"/> (the default) is the
|
||||
/// 0.3.0 bind-then-search-then-bind flow; <see cref="LdapBindMode.User"/> binds as the user and needs
|
||||
/// no <see cref="ServiceAccountDn"/> / <see cref="ServiceAccountPassword"/>.
|
||||
/// </summary>
|
||||
public LdapBindMode BindMode { get; init; } = LdapBindMode.ServiceAccount;
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="LdapBindMode.User"/> only: the simple-bind identity, with <c>{0}</c> replaced by the
|
||||
/// normalised login name. Must contain <c>{0}</c> exactly once.
|
||||
/// <para>
|
||||
/// Prefer the down-level form <c>EXAMPLE\{0}</c>: it maps exactly to the <c>sAMAccountName</c> the
|
||||
/// group search uses. A UPN template (<c>{0}@example.com</c>) only signs in accounts whose UPN
|
||||
/// prefix equals their <c>sAMAccountName</c> — AD resolves a UPN bind against the explicit
|
||||
/// <c>userPrincipalName</c>, so it can bind a different account than the one the search finds.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// Since 0.4.4 the service proves the entry it reads is the account that bound, and refuses the
|
||||
/// sign-in (<see cref="LdapAuthFailure.GroupLookupFailed"/>) otherwise. It asks the directory
|
||||
/// (RFC 4532 "Who am I?") and compares the answer with the entry's DN or, for AD's
|
||||
/// <c>u:DOMAIN\name</c> answer, its <c>sAMAccountName</c>. A server without Who-am-I (e.g. GLAuth)
|
||||
/// is only supported with a DN template (containing <c>=</c>), which must produce the entry's DN
|
||||
/// exactly as the search reports it; <c>{0}</c> is RFC 4514-escaped in a DN template.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public string UserBindTemplate { get; init; } = "";
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="LdapBindMode.User"/> only: when <see langword="true"/> (default) a login typed as
|
||||
/// <c>DOMAIN\name</c> or <c>name@suffix</c> is reduced to <c>name</c>; when <see langword="false"/>
|
||||
/// such input is refused as bad credentials without contacting the directory.
|
||||
/// </summary>
|
||||
public bool AcceptDomainQualifiedNames { get; init; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// Ordered fallback LDAP endpoints tried when the primary (and any earlier fallback)
|
||||
/// fails with a system-side error (connect/TLS, service-account bind, or search).
|
||||
/// Each entry is <c>"host"</c> (adopts <see cref="Port"/>) or <c>"host:port"</c>.
|
||||
/// Empty (the default) disables failover entirely — single-endpoint behavior is
|
||||
/// unchanged. The TLS validation policy (<see cref="ServerCertificateValidationCallback"/>
|
||||
/// / <see cref="AllowInsecure"/>) applies to every endpoint. Endpoint preference is
|
||||
/// sticky: the service keeps using the last endpoint that answered until it fails.
|
||||
/// </summary>
|
||||
public IReadOnlyList<string> FallbackServers { get; init; } = Array.Empty<string>();
|
||||
|
||||
/// <summary>
|
||||
/// Optional hook to harden (or, in dev, relax) TLS server-certificate validation for the
|
||||
/// <see cref="LdapTransport.Ldaps"/> / <see cref="LdapTransport.StartTls"/> transports. When
|
||||
@@ -57,3 +116,80 @@ public interface ILdapAuthService
|
||||
/// </remarks>
|
||||
Task<LdapAuthResult> AuthenticateAsync(string username, string password, CancellationToken ct);
|
||||
}
|
||||
|
||||
/// <summary>Outcome of a passwordless <see cref="ILdapGroupLookup.GetUserGroupsAsync"/> call.</summary>
|
||||
public enum LdapGroupLookupStatus
|
||||
{
|
||||
/// <summary>Exactly one entry matched; <see cref="LdapGroupLookupResult.Groups"/> is its group set (may be empty).</summary>
|
||||
Found,
|
||||
|
||||
/// <summary>A healthy directory answered and no entry matched the name — the account was deleted or renamed.</summary>
|
||||
UserNotFound,
|
||||
|
||||
/// <summary>Exactly one entry matched but the directory marks it disabled (AD <c>userAccountControl</c> ACCOUNTDISABLE).</summary>
|
||||
UserDisabled,
|
||||
|
||||
/// <summary>Two or more entries matched; no group set can be attributed to the name.</summary>
|
||||
AmbiguousUser,
|
||||
|
||||
/// <summary>
|
||||
/// No endpoint gave an answer: connect/TLS, the service-account bind or the search failed on every
|
||||
/// endpoint (primary and <see cref="LdapOptions.FallbackServers"/>). Says nothing about the user.
|
||||
/// </summary>
|
||||
DirectoryUnavailable,
|
||||
|
||||
/// <summary>
|
||||
/// The configuration cannot search without the user's password: <see cref="LdapOptions.BindMode"/> is
|
||||
/// <see cref="LdapBindMode.User"/> (there is no service account), no
|
||||
/// <see cref="LdapOptions.ServiceAccountDn"/> is configured, or the registered provider does not implement lookup.
|
||||
/// </summary>
|
||||
NotSupported,
|
||||
|
||||
/// <summary><see cref="LdapOptions.Enabled"/> is <see langword="false"/>; the network was not touched.</summary>
|
||||
ProviderDisabled,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Result of a passwordless group lookup. <see cref="Username"/>, <see cref="DisplayName"/> and
|
||||
/// <see cref="Groups"/> are populated only for <see cref="LdapGroupLookupStatus.Found"/>; for every other
|
||||
/// status they are empty.
|
||||
/// </summary>
|
||||
public sealed record LdapGroupLookupResult(
|
||||
LdapGroupLookupStatus Status,
|
||||
string Username,
|
||||
string DisplayName,
|
||||
IReadOnlyList<string> Groups)
|
||||
{
|
||||
/// <summary><see langword="true"/> when <see cref="Status"/> is <see cref="LdapGroupLookupStatus.Found"/>.</summary>
|
||||
public bool IsFound => Status == LdapGroupLookupStatus.Found;
|
||||
|
||||
public static LdapGroupLookupResult Found(string username, string displayName, IReadOnlyList<string> groups)
|
||||
=> new(LdapGroupLookupStatus.Found, username, displayName, groups);
|
||||
|
||||
/// <summary>Any non-<see cref="LdapGroupLookupStatus.Found"/> outcome, with empty identity fields.</summary>
|
||||
public static LdapGroupLookupResult Of(LdapGroupLookupStatus status)
|
||||
=> status == LdapGroupLookupStatus.Found
|
||||
? throw new ArgumentException("Use Found(...) for a successful lookup.", nameof(status))
|
||||
: new(status, "", "", Array.Empty<string>());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Passwordless directory group lookup (since 0.5.0): re-reads a known user's group membership without
|
||||
/// their credentials, e.g. to refresh an active session's roles when the directory changes.
|
||||
/// </summary>
|
||||
public interface ILdapGroupLookup
|
||||
{
|
||||
/// <summary>
|
||||
/// Binds as the configured service account, finds <paramref name="username"/> by
|
||||
/// <see cref="LdapOptions.UserNameAttribute"/> under <see cref="LdapOptions.SearchBase"/>, and returns the
|
||||
/// same group set (and canonical username / display name) <see cref="ILdapAuthService.AuthenticateAsync"/>
|
||||
/// would return for that user in <see cref="LdapBindMode.ServiceAccount"/> mode.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Never throws except for cancellation observed at entry; every fault maps to a
|
||||
/// <see cref="LdapGroupLookupStatus"/>. Endpoint failover, timeouts and TLS policy are the same as
|
||||
/// <see cref="ILdapAuthService.AuthenticateAsync"/>. Unlike authentication, a <see cref="LdapGroupLookupStatus.Found"/>
|
||||
/// result may carry zero groups (sign-in would refuse such a user); the caller decides what that means.
|
||||
/// </remarks>
|
||||
Task<LdapGroupLookupResult> GetUserGroupsAsync(string username, CancellationToken ct);
|
||||
}
|
||||
|
||||
@@ -11,8 +11,8 @@
|
||||
<PackageId>ZB.MOM.WW.Auth.Abstractions</PackageId>
|
||||
<Authors>ZB.MOM.WW</Authors>
|
||||
<Description>Auth contracts and canonical roles for the ZB.MOM.WW SCADA family.</Description>
|
||||
<PackageProjectUrl>https://gitea.dohertylan.com/dohertj2/zb-mom-ww-auth</PackageProjectUrl>
|
||||
<RepositoryUrl>https://gitea.dohertylan.com/dohertj2/zb-mom-ww-auth</RepositoryUrl>
|
||||
<PackageProjectUrl>https://gitea.dohertylan.com/dohertj2/scadaproj/src/branch/main/ZB.MOM.WW.Auth</PackageProjectUrl>
|
||||
<RepositoryUrl>https://gitea.dohertylan.com/dohertj2/scadaproj</RepositoryUrl>
|
||||
</PropertyGroup>
|
||||
|
||||
</Project>
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
using Microsoft.Data.SqlClient;
|
||||
|
||||
namespace ZB.MOM.WW.Auth.ApiKeys.SqlServer;
|
||||
|
||||
/// <summary>
|
||||
/// Opens connections to the shared SQL Server API-key database and carries the settings every
|
||||
/// command needs (schema name, command timeout).
|
||||
/// </summary>
|
||||
/// <param name="options">The SQL Server API-key store options; validated in the constructor.</param>
|
||||
/// <exception cref="InvalidOperationException"><paramref name="options"/> is not usable.</exception>
|
||||
public sealed class AuthSqlServerConnectionFactory(SqlServerApiKeyOptions options)
|
||||
{
|
||||
private readonly SqlServerApiKeyOptions _options = Validate(options);
|
||||
|
||||
private static SqlServerApiKeyOptions Validate(SqlServerApiKeyOptions options)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(options);
|
||||
options.Validate();
|
||||
return options;
|
||||
}
|
||||
|
||||
/// <summary>The schema that owns the three API-key tables.</summary>
|
||||
public string Schema => _options.Schema;
|
||||
|
||||
/// <summary>Command timeout, in whole seconds, for every command issued against this store.</summary>
|
||||
public int CommandTimeoutSeconds => Math.Max(1, (int)_options.CommandTimeout.TotalSeconds);
|
||||
|
||||
/// <summary>Opens a connection to the shared API-key database.</summary>
|
||||
/// <param name="cancellationToken">A token to cancel the connect.</param>
|
||||
/// <returns>An opened connection. The caller owns disposal.</returns>
|
||||
public async Task<SqlConnection> OpenConnectionAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var connection = new SqlConnection(_options.ConnectionString);
|
||||
try
|
||||
{
|
||||
await connection.OpenAsync(cancellationToken).ConfigureAwait(false);
|
||||
return connection;
|
||||
}
|
||||
catch
|
||||
{
|
||||
await connection.DisposeAsync().ConfigureAwait(false);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a command on <paramref name="connection"/> with the configured timeout applied.
|
||||
/// </summary>
|
||||
/// <param name="connection">The open connection.</param>
|
||||
/// <param name="commandText">The command text.</param>
|
||||
/// <param name="transaction">The ambient transaction, if any.</param>
|
||||
/// <returns>The configured command. The caller owns disposal.</returns>
|
||||
public SqlCommand CreateCommand(
|
||||
SqlConnection connection, string commandText, SqlTransaction? transaction = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(connection);
|
||||
|
||||
SqlCommand command = connection.CreateCommand();
|
||||
command.CommandText = commandText;
|
||||
command.CommandTimeout = CommandTimeoutSeconds;
|
||||
command.Transaction = transaction;
|
||||
return command;
|
||||
}
|
||||
}
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.DependencyInjection.Extensions;
|
||||
using Microsoft.Extensions.Options;
|
||||
using ZB.MOM.WW.Auth.Abstractions.ApiKeys;
|
||||
using ZB.MOM.WW.Auth.ApiKeys.DependencyInjection;
|
||||
|
||||
namespace ZB.MOM.WW.Auth.ApiKeys.SqlServer.DependencyInjection;
|
||||
|
||||
/// <summary>
|
||||
/// Dependency-injection entry point that swaps the API-key store backend from the SQLite default
|
||||
/// to a shared SQL Server database — one row set read and written by every node of a cluster (e.g.
|
||||
/// a ScadaBridge central pair), instead of the per-node file <see cref="AddZbApiKeyAuth"/> alone
|
||||
/// would give each node.
|
||||
/// </summary>
|
||||
public static class SqlServerApiKeyServiceCollectionExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Registers the SQL Server-backed <see cref="IApiKeyStore"/>, <see cref="IApiKeyAdminStore"/>,
|
||||
/// <see cref="IApiKeyAuditStore"/> and <see cref="IApiKeyStoreMigrator"/>, then calls
|
||||
/// <see cref="ApiKeyServiceCollectionExtensions.AddZbApiKeyAuth"/> to complete the registration
|
||||
/// (verifier, pepper provider, migration hosted service).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// <b>Call this INSTEAD of <see cref="ApiKeyServiceCollectionExtensions.AddZbApiKeyAuth"/></b>,
|
||||
/// never both — this method calls it internally. The SQL Server stores and migrator are
|
||||
/// registered here, BEFORE that inner call, precisely because
|
||||
/// <see cref="ApiKeyServiceCollectionExtensions.AddZbApiKeyAuth"/> registers everything with
|
||||
/// <c>TryAdd*</c>: whichever implementation of <see cref="IApiKeyStore"/> (etc.) is registered
|
||||
/// first wins, and a later <c>TryAdd</c> for the same service is a no-op. That ordering is the
|
||||
/// entire mechanism by which this method displaces the SQLite default.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <see cref="ApiKeyServiceCollectionExtensions.AddZbApiKeyAuth"/> still registers a SQLite
|
||||
/// connection factory from <c>ApiKeyOptions.SqlitePath</c> even when SQL Server wins every
|
||||
/// store slot. That is harmless — the SQLite factory is lazy and the connection it would open
|
||||
/// is never opened when nothing resolves it — and it is actually useful: it keeps the one path
|
||||
/// a node's pre-existing per-node SQLite file lives at in a single option, which is exactly the
|
||||
/// source path <see cref="SqliteApiKeyStoreImporter"/> needs for the one-shot copy into the
|
||||
/// shared store.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <see cref="SqliteApiKeyStoreImporter"/> is registered here so a host can resolve it and run
|
||||
/// it once at boot (e.g. from a startup task or its own hosted service) to copy an existing
|
||||
/// node's per-node keys and audit rows into the now-shared store; it performs no work by being
|
||||
/// merely registered.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <b>The connection string must be a literal value or an environment-variable override — never
|
||||
/// a <c>${secret:}</c> reference</b> on a host whose secret store is itself SQL-backed: resolving
|
||||
/// that reference would require a working secret store, which on such a host requires this very
|
||||
/// database to already be reachable, an unbreakable circular dependency at boot.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
/// <param name="services">The service collection to add to.</param>
|
||||
/// <param name="config">The application configuration.</param>
|
||||
/// <param name="apiKeySectionPath">Path of the configuration section holding the core API-key options.</param>
|
||||
/// <param name="sqlServerSectionPath">Path of the configuration section holding <see cref="SqlServerApiKeyOptions"/>.</param>
|
||||
/// <returns>The same <paramref name="services"/> instance, for chaining.</returns>
|
||||
public static IServiceCollection AddZbApiKeyAuthSqlServer(
|
||||
this IServiceCollection services,
|
||||
IConfiguration config,
|
||||
string apiKeySectionPath,
|
||||
string sqlServerSectionPath)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(services);
|
||||
ArgumentNullException.ThrowIfNull(config);
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(apiKeySectionPath);
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(sqlServerSectionPath);
|
||||
|
||||
services.Configure<SqlServerApiKeyOptions>(config.GetSection(sqlServerSectionPath));
|
||||
|
||||
services.TryAddSingleton(sp =>
|
||||
new AuthSqlServerConnectionFactory(sp.GetRequiredService<IOptions<SqlServerApiKeyOptions>>().Value));
|
||||
|
||||
// Registered BEFORE AddZbApiKeyAuth so its TryAdd calls find these already present and
|
||||
// leave them alone — that is the whole mechanism by which the SQL Server store displaces
|
||||
// SQLite (see the class remarks).
|
||||
services.TryAddSingleton<IApiKeyStore>(sp =>
|
||||
new SqlServerApiKeyStore(sp.GetRequiredService<AuthSqlServerConnectionFactory>()));
|
||||
services.TryAddSingleton<IApiKeyAdminStore>(sp =>
|
||||
new SqlServerApiKeyAdminStore(sp.GetRequiredService<AuthSqlServerConnectionFactory>()));
|
||||
services.TryAddSingleton<IApiKeyAuditStore>(sp =>
|
||||
new SqlServerApiKeyAuditStore(sp.GetRequiredService<AuthSqlServerConnectionFactory>()));
|
||||
|
||||
services.TryAddSingleton<SqlServerApiKeyStoreMigrator>();
|
||||
services.TryAddSingleton<IApiKeyStoreMigrator>(sp => sp.GetRequiredService<SqlServerApiKeyStoreMigrator>());
|
||||
|
||||
// Registered so a host can resolve it and run the one-shot per-node SQLite -> shared store
|
||||
// copy at boot; registering it here does no work on its own.
|
||||
services.TryAddSingleton<SqliteApiKeyStoreImporter>();
|
||||
|
||||
return services.AddZbApiKeyAuth(config, apiKeySectionPath);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,263 @@
|
||||
using System.Data;
|
||||
using Microsoft.Data.SqlClient;
|
||||
using ZB.MOM.WW.Auth.Abstractions.ApiKeys;
|
||||
using ZB.MOM.WW.Auth.ApiKeys.Sqlite;
|
||||
|
||||
namespace ZB.MOM.WW.Auth.ApiKeys.SqlServer;
|
||||
|
||||
/// <summary>
|
||||
/// SQL Server-backed administration store for API keys (create, revoke, rotate, delete,
|
||||
/// set-scopes, enable/disable, list).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Semantics are a deliberate one-for-one port of <c>SqliteApiKeyAdminStore</c> — same WHERE and SET
|
||||
/// clauses, same rows-affected return contract — so an admin command behaves identically whichever
|
||||
/// provider a host composed. The point of this provider is only WHERE the rows live: one shared row
|
||||
/// set for a clustered pair instead of a file per node, so a revoke on either node is a revoke
|
||||
/// everywhere.
|
||||
/// </remarks>
|
||||
/// <param name="connectionFactory">Factory for connections to the shared API-key database.</param>
|
||||
public sealed class SqlServerApiKeyAdminStore(AuthSqlServerConnectionFactory connectionFactory) : IApiKeyAdminStore
|
||||
{
|
||||
/// <inheritdoc />
|
||||
/// <remarks>
|
||||
/// A plain INSERT: a duplicate <c>key_id</c> surfaces as a primary-key
|
||||
/// <see cref="SqlException"/> rather than silently overwriting an existing key (the SQLite store
|
||||
/// raises its own <c>SqliteException</c> in the same situation). Unlike SQLite, the primary key
|
||||
/// follows the database collation, so on a case-insensitive database <c>Line1</c> cannot be
|
||||
/// created beside <c>line1</c> either. A key id over 64, prefix over 16 or display name over 256
|
||||
/// characters throws <see cref="ArgumentException"/> before anything is sent (since 0.4.4; it
|
||||
/// was silently truncated before).
|
||||
/// </remarks>
|
||||
/// <exception cref="ArgumentException">A field is longer than its column.</exception>
|
||||
public async Task CreateAsync(ApiKeyRecord record, CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(record);
|
||||
SqlServerColumnLimits.EnsureFits(record);
|
||||
|
||||
string schema = connectionFactory.Schema;
|
||||
|
||||
await using SqlConnection connection =
|
||||
await connectionFactory.OpenConnectionAsync(ct).ConfigureAwait(false);
|
||||
|
||||
await using SqlCommand command = connectionFactory.CreateCommand(connection, $"""
|
||||
INSERT INTO [{schema}].[{SqlServerAuthSchema.ApiKeysTable}] (
|
||||
key_id, key_prefix, secret_hash, display_name, scopes,
|
||||
constraints, created_utc, last_used_utc, revoked_utc, expires_utc)
|
||||
VALUES (
|
||||
@key_id, @key_prefix, @secret_hash, @display_name, @scopes,
|
||||
@constraints, @created_utc, @last_used_utc, @revoked_utc, @expires_utc);
|
||||
""");
|
||||
command.Parameters.Add("@key_id", SqlDbType.NVarChar, 64).Value = record.KeyId;
|
||||
command.Parameters.Add("@key_prefix", SqlDbType.NVarChar, 16).Value = record.KeyPrefix;
|
||||
command.Parameters.Add("@secret_hash", SqlDbType.VarBinary, 64).Value = record.SecretHash;
|
||||
command.Parameters.Add("@display_name", SqlDbType.NVarChar, 256).Value = record.DisplayName;
|
||||
command.Parameters.Add("@scopes", SqlDbType.NVarChar, -1).Value = ScopeSerializer.Serialize(record.Scopes);
|
||||
command.Parameters.Add("@constraints", SqlDbType.NVarChar, -1).Value = (object?)record.ConstraintsJson ?? DBNull.Value;
|
||||
command.Parameters.Add("@created_utc", SqlDbType.DateTimeOffset).Value = record.CreatedUtc;
|
||||
command.Parameters.Add("@last_used_utc", SqlDbType.DateTimeOffset).Value = (object?)record.LastUsedUtc ?? DBNull.Value;
|
||||
command.Parameters.Add("@revoked_utc", SqlDbType.DateTimeOffset).Value = (object?)record.RevokedUtc ?? DBNull.Value;
|
||||
command.Parameters.Add("@expires_utc", SqlDbType.DateTimeOffset).Value = (object?)record.ExpiresUtc ?? DBNull.Value;
|
||||
|
||||
await command.ExecuteNonQueryAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
/// <remarks>
|
||||
/// Guarded on <c>revoked_utc IS NULL</c>, so the returned flag means "this call revoked it" —
|
||||
/// a second revoke of the same key returns <see langword="false"/> and preserves the original
|
||||
/// revocation instant.
|
||||
/// </remarks>
|
||||
public async Task<bool> RevokeAsync(string keyId, DateTimeOffset whenUtc, CancellationToken ct)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(keyId);
|
||||
if (!SqlServerColumnLimits.CanExist(keyId))
|
||||
return false;
|
||||
|
||||
string schema = connectionFactory.Schema;
|
||||
|
||||
await using SqlConnection connection =
|
||||
await connectionFactory.OpenConnectionAsync(ct).ConfigureAwait(false);
|
||||
|
||||
await using SqlCommand command = connectionFactory.CreateCommand(connection, $"""
|
||||
UPDATE [{schema}].[{SqlServerAuthSchema.ApiKeysTable}]
|
||||
SET revoked_utc = @revoked_utc
|
||||
WHERE key_id = @key_id AND {SqlServerColumnLimits.ExactKeyIdMatch} AND revoked_utc IS NULL;
|
||||
""");
|
||||
command.Parameters.Add("@key_id", SqlDbType.NVarChar, 64).Value = keyId;
|
||||
command.Parameters.Add("@revoked_utc", SqlDbType.DateTimeOffset).Value = whenUtc;
|
||||
|
||||
int rows = await command.ExecuteNonQueryAsync(ct).ConfigureAwait(false);
|
||||
|
||||
return rows > 0;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
/// <remarks>
|
||||
/// Rotating also clears <c>last_used_utc</c> and <c>revoked_utc</c> — a rotated key is a fresh,
|
||||
/// active credential — while leaving <c>expires_utc</c> alone, so an absolute expiry survives a
|
||||
/// rotation.
|
||||
/// </remarks>
|
||||
public async Task<bool> RotateAsync(string keyId, byte[] newSecretHash, CancellationToken ct)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(keyId);
|
||||
if (!SqlServerColumnLimits.CanExist(keyId))
|
||||
return false;
|
||||
ArgumentNullException.ThrowIfNull(newSecretHash);
|
||||
|
||||
string schema = connectionFactory.Schema;
|
||||
|
||||
await using SqlConnection connection =
|
||||
await connectionFactory.OpenConnectionAsync(ct).ConfigureAwait(false);
|
||||
|
||||
await using SqlCommand command = connectionFactory.CreateCommand(connection, $"""
|
||||
UPDATE [{schema}].[{SqlServerAuthSchema.ApiKeysTable}]
|
||||
SET secret_hash = @secret_hash,
|
||||
last_used_utc = NULL,
|
||||
revoked_utc = NULL
|
||||
WHERE key_id = @key_id AND {SqlServerColumnLimits.ExactKeyIdMatch};
|
||||
""");
|
||||
command.Parameters.Add("@key_id", SqlDbType.NVarChar, 64).Value = keyId;
|
||||
command.Parameters.Add("@secret_hash", SqlDbType.VarBinary, 64).Value = newSecretHash;
|
||||
|
||||
int rows = await command.ExecuteNonQueryAsync(ct).ConfigureAwait(false);
|
||||
|
||||
return rows > 0;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<bool> SetScopesAsync(string keyId, IReadOnlySet<string> scopes, CancellationToken ct)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(keyId);
|
||||
if (!SqlServerColumnLimits.CanExist(keyId))
|
||||
return false;
|
||||
ArgumentNullException.ThrowIfNull(scopes);
|
||||
|
||||
string schema = connectionFactory.Schema;
|
||||
|
||||
await using SqlConnection connection =
|
||||
await connectionFactory.OpenConnectionAsync(ct).ConfigureAwait(false);
|
||||
|
||||
await using SqlCommand command = connectionFactory.CreateCommand(connection, $"""
|
||||
UPDATE [{schema}].[{SqlServerAuthSchema.ApiKeysTable}]
|
||||
SET scopes = @scopes
|
||||
WHERE key_id = @key_id AND {SqlServerColumnLimits.ExactKeyIdMatch};
|
||||
""");
|
||||
command.Parameters.Add("@key_id", SqlDbType.NVarChar, 64).Value = keyId;
|
||||
command.Parameters.Add("@scopes", SqlDbType.NVarChar, -1).Value = ScopeSerializer.Serialize(scopes);
|
||||
|
||||
int rows = await command.ExecuteNonQueryAsync(ct).ConfigureAwait(false);
|
||||
|
||||
return rows > 0;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<bool> SetEnabledAsync(string keyId, bool enabled, DateTimeOffset whenUtc, CancellationToken ct)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(keyId);
|
||||
if (!SqlServerColumnLimits.CanExist(keyId))
|
||||
return false;
|
||||
|
||||
string schema = connectionFactory.Schema;
|
||||
|
||||
await using SqlConnection connection =
|
||||
await connectionFactory.OpenConnectionAsync(ct).ConfigureAwait(false);
|
||||
|
||||
// Reversible toggle: NO `revoked_utc IS NULL` guard (unlike RevokeAsync), so it works
|
||||
// regardless of current state. Deliberately leaves secret_hash and last_used_utc untouched
|
||||
// — that is what distinguishes re-enable from RotateAsync.
|
||||
SqlCommand command;
|
||||
|
||||
if (enabled)
|
||||
{
|
||||
command = connectionFactory.CreateCommand(connection, $"""
|
||||
UPDATE [{schema}].[{SqlServerAuthSchema.ApiKeysTable}]
|
||||
SET revoked_utc = NULL
|
||||
WHERE key_id = @key_id AND {SqlServerColumnLimits.ExactKeyIdMatch};
|
||||
""");
|
||||
command.Parameters.Add("@key_id", SqlDbType.NVarChar, 64).Value = keyId;
|
||||
}
|
||||
else
|
||||
{
|
||||
command = connectionFactory.CreateCommand(connection, $"""
|
||||
UPDATE [{schema}].[{SqlServerAuthSchema.ApiKeysTable}]
|
||||
SET revoked_utc = @revoked_utc
|
||||
WHERE key_id = @key_id AND {SqlServerColumnLimits.ExactKeyIdMatch};
|
||||
""");
|
||||
command.Parameters.Add("@key_id", SqlDbType.NVarChar, 64).Value = keyId;
|
||||
command.Parameters.Add("@revoked_utc", SqlDbType.DateTimeOffset).Value = whenUtc;
|
||||
}
|
||||
|
||||
await using (command)
|
||||
{
|
||||
int rows = await command.ExecuteNonQueryAsync(ct).ConfigureAwait(false);
|
||||
|
||||
return rows > 0;
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
/// <remarks>
|
||||
/// Only a REVOKED key can be deleted (<c>revoked_utc IS NOT NULL</c>), so an active credential
|
||||
/// cannot vanish in one step — revoke first, and the revocation stands on its own until then.
|
||||
/// </remarks>
|
||||
public async Task<bool> DeleteAsync(string keyId, CancellationToken ct)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(keyId);
|
||||
if (!SqlServerColumnLimits.CanExist(keyId))
|
||||
return false;
|
||||
|
||||
string schema = connectionFactory.Schema;
|
||||
|
||||
await using SqlConnection connection =
|
||||
await connectionFactory.OpenConnectionAsync(ct).ConfigureAwait(false);
|
||||
|
||||
await using SqlCommand command = connectionFactory.CreateCommand(connection, $"""
|
||||
DELETE FROM [{schema}].[{SqlServerAuthSchema.ApiKeysTable}]
|
||||
WHERE key_id = @key_id AND {SqlServerColumnLimits.ExactKeyIdMatch} AND revoked_utc IS NOT NULL;
|
||||
""");
|
||||
command.Parameters.Add("@key_id", SqlDbType.NVarChar, 64).Value = keyId;
|
||||
|
||||
int rows = await command.ExecuteNonQueryAsync(ct).ConfigureAwait(false);
|
||||
|
||||
return rows > 0;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<IReadOnlyList<ApiKeyListItem>> ListAsync(CancellationToken ct)
|
||||
{
|
||||
string schema = connectionFactory.Schema;
|
||||
|
||||
await using SqlConnection connection =
|
||||
await connectionFactory.OpenConnectionAsync(ct).ConfigureAwait(false);
|
||||
|
||||
// Deliberately omits secret_hash so listing can never leak secret material. key_id is the
|
||||
// tie-break so keys minted in the same instant still list in a stable order.
|
||||
await using SqlCommand command = connectionFactory.CreateCommand(connection, $"""
|
||||
SELECT key_id, key_prefix, display_name, scopes, constraints,
|
||||
created_utc, last_used_utc, revoked_utc, expires_utc
|
||||
FROM [{schema}].[{SqlServerAuthSchema.ApiKeysTable}]
|
||||
ORDER BY created_utc DESC, key_id DESC;
|
||||
""");
|
||||
|
||||
List<ApiKeyListItem> items = [];
|
||||
|
||||
await using SqlDataReader reader = await command.ExecuteReaderAsync(ct).ConfigureAwait(false);
|
||||
|
||||
while (await reader.ReadAsync(ct).ConfigureAwait(false))
|
||||
{
|
||||
items.Add(new ApiKeyListItem(
|
||||
KeyId: reader.GetString(0),
|
||||
KeyPrefix: reader.GetString(1),
|
||||
DisplayName: reader.GetString(2),
|
||||
Scopes: ScopeSerializer.Deserialize(reader.GetString(3)),
|
||||
ConstraintsJson: reader.IsDBNull(4) ? null : reader.GetString(4),
|
||||
CreatedUtc: reader.GetDateTimeOffset(5),
|
||||
LastUsedUtc: reader.IsDBNull(6) ? null : reader.GetDateTimeOffset(6),
|
||||
RevokedUtc: reader.IsDBNull(7) ? null : reader.GetDateTimeOffset(7),
|
||||
ExpiresUtc: reader.IsDBNull(8) ? null : reader.GetDateTimeOffset(8)));
|
||||
}
|
||||
|
||||
return items;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
using System.Data;
|
||||
using Microsoft.Data.SqlClient;
|
||||
using ZB.MOM.WW.Auth.Abstractions.ApiKeys;
|
||||
|
||||
namespace ZB.MOM.WW.Auth.ApiKeys.SqlServer;
|
||||
|
||||
/// <summary>
|
||||
/// SQL Server-backed, append-only audit store for API-key events. A one-for-one port of
|
||||
/// <c>SqliteApiKeyAuditStore</c>; on a clustered host the rows from every node land in one table,
|
||||
/// so the audit trail no longer has to be stitched together per node.
|
||||
/// </summary>
|
||||
/// <param name="connectionFactory">Factory for connections to the shared API-key database.</param>
|
||||
public sealed class SqlServerApiKeyAuditStore(AuthSqlServerConnectionFactory connectionFactory) : IApiKeyAuditStore
|
||||
{
|
||||
/// <inheritdoc />
|
||||
/// <remarks>
|
||||
/// <b>Over-length text is truncated, deliberately.</b> <c>key_id</c>, <c>event_type</c> and
|
||||
/// <c>remote_address</c> are 64-character columns; a longer value is stored as its first 64
|
||||
/// characters (the SQLite store keeps it whole). Unlike a key record (refused when over-length,
|
||||
/// see <see cref="SqlServerApiKeyAdminStore.CreateAsync"/>), an audit append is not refused: it
|
||||
/// runs after the action it records, and failing it would lose the record of a change that has
|
||||
/// already happened. <c>details</c> is unbounded.
|
||||
/// </remarks>
|
||||
public async Task AppendAsync(ApiKeyAuditEntry entry, CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(entry);
|
||||
|
||||
string schema = connectionFactory.Schema;
|
||||
|
||||
await using SqlConnection connection =
|
||||
await connectionFactory.OpenConnectionAsync(ct).ConfigureAwait(false);
|
||||
|
||||
await using SqlCommand command = connectionFactory.CreateCommand(connection, $"""
|
||||
INSERT INTO [{schema}].[{SqlServerAuthSchema.ApiKeyAuditTable}] (
|
||||
key_id, event_type, remote_address, created_utc, details)
|
||||
VALUES (@key_id, @event_type, @remote_address, @created_utc, @details);
|
||||
""");
|
||||
command.Parameters.Add("@key_id", SqlDbType.NVarChar, 64).Value = (object?)entry.KeyId ?? DBNull.Value;
|
||||
command.Parameters.Add("@event_type", SqlDbType.NVarChar, 64).Value = entry.EventType;
|
||||
command.Parameters.Add("@remote_address", SqlDbType.NVarChar, 64).Value = (object?)entry.RemoteAddress ?? DBNull.Value;
|
||||
command.Parameters.Add("@created_utc", SqlDbType.DateTimeOffset).Value = entry.CreatedUtc;
|
||||
command.Parameters.Add("@details", SqlDbType.NVarChar, -1).Value = (object?)entry.Details ?? DBNull.Value;
|
||||
|
||||
await command.ExecuteNonQueryAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
/// <remarks>
|
||||
/// Ordered by the IDENTITY <c>audit_id</c>, not by <c>created_utc</c>: two events stamped in the
|
||||
/// same instant still come back in insertion order. A non-positive limit short-circuits without
|
||||
/// opening a connection — <c>SELECT TOP (-1)</c> is not even legal T-SQL.
|
||||
/// </remarks>
|
||||
public async Task<IReadOnlyList<ApiKeyAuditEntry>> ListRecentAsync(int limit, CancellationToken ct)
|
||||
{
|
||||
if (limit <= 0)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
string schema = connectionFactory.Schema;
|
||||
|
||||
await using SqlConnection connection =
|
||||
await connectionFactory.OpenConnectionAsync(ct).ConfigureAwait(false);
|
||||
|
||||
await using SqlCommand command = connectionFactory.CreateCommand(connection, $"""
|
||||
SELECT TOP (@limit) key_id, event_type, remote_address, created_utc, details
|
||||
FROM [{schema}].[{SqlServerAuthSchema.ApiKeyAuditTable}]
|
||||
ORDER BY audit_id DESC;
|
||||
""");
|
||||
command.Parameters.Add("@limit", SqlDbType.Int).Value = limit;
|
||||
|
||||
List<ApiKeyAuditEntry> entries = [];
|
||||
|
||||
await using SqlDataReader reader = await command.ExecuteReaderAsync(ct).ConfigureAwait(false);
|
||||
|
||||
while (await reader.ReadAsync(ct).ConfigureAwait(false))
|
||||
{
|
||||
entries.Add(new ApiKeyAuditEntry(
|
||||
KeyId: reader.IsDBNull(0) ? null : reader.GetString(0),
|
||||
EventType: reader.GetString(1),
|
||||
RemoteAddress: reader.IsDBNull(2) ? null : reader.GetString(2),
|
||||
CreatedUtc: reader.GetDateTimeOffset(3),
|
||||
Details: reader.IsDBNull(4) ? null : reader.GetString(4)));
|
||||
}
|
||||
|
||||
return entries;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
namespace ZB.MOM.WW.Auth.ApiKeys.SqlServer;
|
||||
|
||||
/// <summary>
|
||||
/// Options for the shared SQL Server API-key store (section supplied by the host, e.g.
|
||||
/// <c>ScadaBridge:InboundApi:ApiKeyStore:SqlServer</c>).
|
||||
/// </summary>
|
||||
public sealed class SqlServerApiKeyOptions
|
||||
{
|
||||
/// <summary>
|
||||
/// Full SQL Server connection string. Required. Never a <c>${secret:}</c> reference on hosts
|
||||
/// whose secret store is itself SQL-backed.
|
||||
/// </summary>
|
||||
public string ConnectionString { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>Schema that owns the three tables. Letters, digits and underscore only (it is interpolated into DDL).</summary>
|
||||
public string Schema { get; set; } = "zbauth";
|
||||
|
||||
/// <summary>
|
||||
/// Command timeout applied to every store operation. Defaults to 30 seconds — long enough for
|
||||
/// a contended shared database, short enough that a hung server surfaces as an error rather
|
||||
/// than stalling a resolve indefinitely.
|
||||
/// </summary>
|
||||
public TimeSpan CommandTimeout { get; set; } = TimeSpan.FromSeconds(30);
|
||||
|
||||
/// <summary>Fails fast on a blank connection string, an unsafe schema identifier, or a non-positive command timeout.</summary>
|
||||
/// <exception cref="InvalidOperationException">The options are not usable.</exception>
|
||||
public void Validate()
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(ConnectionString))
|
||||
throw new InvalidOperationException("SQL Server API-key store requires a ConnectionString.");
|
||||
|
||||
ValidateIdentifier(Schema);
|
||||
|
||||
if (CommandTimeout <= TimeSpan.Zero)
|
||||
throw new InvalidOperationException($"SQL Server API-key store CommandTimeout must be positive (was {CommandTimeout}).");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Strict allow-list for a SQL identifier that will be interpolated into DDL or query text.
|
||||
/// Rejects everything that is not <c>[A-Za-z_][A-Za-z0-9_]{0,63}</c> — no brackets, quotes, dots
|
||||
/// or spaces — so no bracket-escape (<c>]]</c>) trick can break out of the quoting applied at the
|
||||
/// use site. Uses the ASCII-only character tests deliberately, so homoglyph and full-width
|
||||
/// look-alikes are rejected rather than accepted as "letters".
|
||||
/// </summary>
|
||||
/// <param name="schemaName">The candidate identifier.</param>
|
||||
/// <returns>The same value, once validated.</returns>
|
||||
/// <exception cref="InvalidOperationException">The value is not a plain identifier.</exception>
|
||||
/// <remarks>
|
||||
/// Public because <see cref="SqlServerAuthSchema.CreateSchemaDdl(string)"/> is public and must
|
||||
/// defend itself rather than trust that every caller routed through <see cref="Validate"/>.
|
||||
/// </remarks>
|
||||
public static string ValidateIdentifier(string schemaName)
|
||||
{
|
||||
if (string.IsNullOrEmpty(schemaName)
|
||||
|| schemaName.Length > 64
|
||||
|| (!char.IsAsciiLetter(schemaName[0]) && schemaName[0] != '_')
|
||||
|| !schemaName.All(c => char.IsAsciiLetterOrDigit(c) || c == '_'))
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
$"SQL Server API-key store schema name '{schemaName}' is not a safe identifier.");
|
||||
}
|
||||
|
||||
return schemaName;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
using System.Data;
|
||||
using Microsoft.Data.SqlClient;
|
||||
using ZB.MOM.WW.Auth.Abstractions.ApiKeys;
|
||||
using ZB.MOM.WW.Auth.ApiKeys.Sqlite;
|
||||
|
||||
namespace ZB.MOM.WW.Auth.ApiKeys.SqlServer;
|
||||
|
||||
/// <summary>
|
||||
/// SQL Server-backed read store for API-key records — the verification hot path.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Semantics are a deliberate one-for-one port of <c>SqliteApiKeyStore</c>, down to the WHERE
|
||||
/// clauses, so a host can switch providers without any behaviour changing. One connection per
|
||||
/// operation: the shared store is reached over the network and pooling, not a held connection, is
|
||||
/// what keeps a central pair's concurrent verifies cheap.
|
||||
/// </remarks>
|
||||
/// <param name="connectionFactory">Factory for connections to the shared API-key database.</param>
|
||||
public sealed class SqlServerApiKeyStore(AuthSqlServerConnectionFactory connectionFactory) : IApiKeyStore
|
||||
{
|
||||
private const string SelectColumns =
|
||||
"key_id, key_prefix, secret_hash, display_name, scopes, constraints, created_utc, last_used_utc, revoked_utc, expires_utc";
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<ApiKeyRecord?> FindByKeyIdAsync(string keyId, CancellationToken ct)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(keyId);
|
||||
return FindAsync(keyId, requireActive: false, ct);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<ApiKeyRecord?> FindActiveByKeyIdAsync(string keyId, CancellationToken ct)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(keyId);
|
||||
return FindAsync(keyId, requireActive: true, ct);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
/// <remarks>
|
||||
/// Guarded on <c>revoked_utc IS NULL</c>: a revoked key's last-used stamp is frozen at its last
|
||||
/// legitimate use, so it never records the rejected attempts that follow.
|
||||
/// </remarks>
|
||||
public async Task MarkUsedAsync(string keyId, DateTimeOffset whenUtc, CancellationToken ct)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(keyId);
|
||||
if (!SqlServerColumnLimits.CanExist(keyId))
|
||||
return;
|
||||
|
||||
string schema = connectionFactory.Schema;
|
||||
|
||||
await using SqlConnection connection =
|
||||
await connectionFactory.OpenConnectionAsync(ct).ConfigureAwait(false);
|
||||
|
||||
await using SqlCommand command = connectionFactory.CreateCommand(connection, $"""
|
||||
UPDATE [{schema}].[{SqlServerAuthSchema.ApiKeysTable}]
|
||||
SET last_used_utc = @last_used_utc
|
||||
WHERE key_id = @key_id AND {SqlServerColumnLimits.ExactKeyIdMatch} AND revoked_utc IS NULL;
|
||||
""");
|
||||
command.Parameters.Add("@key_id", SqlDbType.NVarChar, 64).Value = keyId;
|
||||
command.Parameters.Add("@last_used_utc", SqlDbType.DateTimeOffset).Value = whenUtc;
|
||||
|
||||
await command.ExecuteNonQueryAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task<ApiKeyRecord?> FindAsync(string keyId, bool requireActive, CancellationToken ct)
|
||||
{
|
||||
// An id longer than the column cannot be stored; querying would truncate it and could match
|
||||
// another key sharing its first 64 characters (Auth-008).
|
||||
if (!SqlServerColumnLimits.CanExist(keyId))
|
||||
return null;
|
||||
|
||||
string schema = connectionFactory.Schema;
|
||||
string table = $"[{schema}].[{SqlServerAuthSchema.ApiKeysTable}]";
|
||||
|
||||
await using SqlConnection connection =
|
||||
await connectionFactory.OpenConnectionAsync(ct).ConfigureAwait(false);
|
||||
|
||||
// Active means NOT REVOKED only. Expiry is deliberately not filtered here — the verifier
|
||||
// owns it, so it can tell an expired key from an unknown one (ApiKeyFailure.KeyExpired).
|
||||
await using SqlCommand command = connectionFactory.CreateCommand(
|
||||
connection,
|
||||
requireActive
|
||||
? $"SELECT {SelectColumns} FROM {table} WHERE key_id = @key_id AND {SqlServerColumnLimits.ExactKeyIdMatch} AND revoked_utc IS NULL;"
|
||||
: $"SELECT {SelectColumns} FROM {table} WHERE key_id = @key_id AND {SqlServerColumnLimits.ExactKeyIdMatch};");
|
||||
command.Parameters.Add("@key_id", SqlDbType.NVarChar, 64).Value = keyId;
|
||||
|
||||
await using SqlDataReader reader = await command.ExecuteReaderAsync(ct).ConfigureAwait(false);
|
||||
|
||||
if (!await reader.ReadAsync(ct).ConfigureAwait(false))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return ReadRecord(reader);
|
||||
}
|
||||
|
||||
internal static ApiKeyRecord ReadRecord(SqlDataReader reader) => new(
|
||||
KeyId: reader.GetString(0),
|
||||
KeyPrefix: reader.GetString(1),
|
||||
SecretHash: reader.GetFieldValue<byte[]>(2),
|
||||
DisplayName: reader.GetString(3),
|
||||
Scopes: ScopeSerializer.Deserialize(reader.GetString(4)),
|
||||
ConstraintsJson: reader.IsDBNull(5) ? null : reader.GetString(5),
|
||||
CreatedUtc: reader.GetDateTimeOffset(6),
|
||||
LastUsedUtc: reader.IsDBNull(7) ? null : reader.GetDateTimeOffset(7),
|
||||
RevokedUtc: reader.IsDBNull(8) ? null : reader.GetDateTimeOffset(8),
|
||||
ExpiresUtc: reader.IsDBNull(9) ? null : reader.GetDateTimeOffset(9));
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
using System.Data;
|
||||
using System.Globalization;
|
||||
using Microsoft.Data.SqlClient;
|
||||
using ZB.MOM.WW.Auth.Abstractions.ApiKeys;
|
||||
using ZB.MOM.WW.Auth.ApiKeys.Sqlite;
|
||||
|
||||
namespace ZB.MOM.WW.Auth.ApiKeys.SqlServer;
|
||||
|
||||
/// <summary>
|
||||
/// Creates the shared SQL Server API-key schema and records the applied version. Idempotent: safe
|
||||
/// to run on every node at every startup, including concurrently — lost provisioning races surface
|
||||
/// as retryable <see cref="SqlException"/>s (see <see cref="IsRetryableMigrationErrorNumber"/>) and
|
||||
/// the retry re-runs the <c>IF NOT EXISTS</c> path against the objects the winner just created.
|
||||
/// Refuses to run against a database whose recorded version is newer than this build supports.
|
||||
/// </summary>
|
||||
/// <param name="connectionFactory">Factory for connections to the shared API-key database.</param>
|
||||
public sealed class SqlServerApiKeyStoreMigrator(AuthSqlServerConnectionFactory connectionFactory)
|
||||
: IApiKeyStoreMigrator
|
||||
{
|
||||
// Every node runs this at every startup, so a virgin database being provisioned by N nodes at
|
||||
// once is the NORMAL case, not a rare race — and an unretried failure aborts that node's whole
|
||||
// host at startup. Two failure shapes come out of that race, and retrying is correct for both
|
||||
// precisely because the migration is idempotent:
|
||||
//
|
||||
// - Deadlock victim (1205): concurrent Serializable DDL against the system catalogs can pick
|
||||
// a victim even though the IF NOT EXISTS guards make the logic itself safe.
|
||||
// - Lost CREATE / lost INSERT (2714, 1913, 2627): Serializable range locks do NOT serialize
|
||||
// the metadata existence checks against another session's in-flight CREATE — observed live
|
||||
// on the sibling shared secret store (ScadaBridge central-pair first boot, 2026-08-07):
|
||||
// both nodes passed the sys.schemas IF NOT EXISTS probe, the loser's CREATE SCHEMA then
|
||||
// died with 2714 "There is already an object named 'zbsecrets'". The object the loser tried
|
||||
// to create now exists, which is the desired end state — the retry's IF NOT EXISTS pass
|
||||
// skips it and proceeds.
|
||||
//
|
||||
// The retry cap keeps this from masking a GENUINE conflict (e.g. an unrelated pre-existing
|
||||
// object colliding with the schema name): that reproduces on every attempt, so after
|
||||
// MaxMigrationRetries the real SqlException propagates and the node fails closed.
|
||||
private const int MaxMigrationRetries = 5;
|
||||
|
||||
/// <summary>Deadlock victim.</summary>
|
||||
private const int SqlDeadlockVictimErrorNumber = 1205;
|
||||
|
||||
/// <summary>"There is already an object named '%ls'" — lost CREATE SCHEMA / CREATE TABLE race.</summary>
|
||||
private const int SqlObjectAlreadyExistsErrorNumber = 2714;
|
||||
|
||||
/// <summary>"An index or statistics with name '%ls' already exists" — lost CREATE INDEX race.</summary>
|
||||
private const int SqlIndexAlreadyExistsErrorNumber = 1913;
|
||||
|
||||
/// <summary>Primary-key violation — lost version-row MERGE-insert race.</summary>
|
||||
private const int SqlPrimaryKeyViolationErrorNumber = 2627;
|
||||
|
||||
/// <inheritdoc />
|
||||
/// <exception cref="AuthStoreMigrationException">
|
||||
/// The recorded schema version is newer than <see cref="SqlServerAuthSchema.CurrentVersion"/>.
|
||||
/// </exception>
|
||||
public async Task MigrateAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
for (int attempt = 1; ; attempt++)
|
||||
{
|
||||
try
|
||||
{
|
||||
await MigrateOnceAsync(cancellationToken).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
catch (SqlException ex)
|
||||
when (IsRetryableMigrationError(ex) && attempt < MaxMigrationRetries)
|
||||
{
|
||||
await Task.Delay(BackoffFor(attempt), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Back-off before retry attempt <paramref name="attempt"/> + 1: a growing base plus RANDOM
|
||||
/// jitter. The jitter is the load-bearing half. The sibling secret-store migrator this is ported
|
||||
/// from delays a flat <c>100 * attempt</c>, which is the SAME value for every victim of the same
|
||||
/// round — so N deadlock victims wake together and re-collide, exactly the lockstep its comment
|
||||
/// claims to prevent. Measured here against a live SQL Server with eight concurrent migrators on
|
||||
/// a virgin schema, the unjittered form exhausted the five-attempt budget on repeated 1205s in
|
||||
/// roughly 1 run in 60; with jitter it did not.
|
||||
/// </summary>
|
||||
/// <param name="attempt">The 1-based attempt that just failed.</param>
|
||||
/// <returns>How long to wait before the next attempt.</returns>
|
||||
private static TimeSpan BackoffFor(int attempt) =>
|
||||
TimeSpan.FromMilliseconds((100 * attempt) + Random.Shared.Next(0, 100 * attempt));
|
||||
|
||||
/// <summary>
|
||||
/// Whether any error carried by <paramref name="exception"/> is a retryable provisioning-race
|
||||
/// outcome. Scans the whole <see cref="SqlException.Errors"/> collection rather than only
|
||||
/// <see cref="SqlException.Number"/> because a failed DDL batch stacks follow-on errors (e.g.
|
||||
/// 2714 arrives with 2759 "CREATE SCHEMA failed due to previous errors") and the retryable one
|
||||
/// is not guaranteed to be first.
|
||||
/// </summary>
|
||||
/// <param name="exception">The exception the migration attempt failed with.</param>
|
||||
/// <returns><see langword="true"/> when a retry may succeed.</returns>
|
||||
internal static bool IsRetryableMigrationError(SqlException exception)
|
||||
{
|
||||
foreach (SqlError error in exception.Errors)
|
||||
{
|
||||
if (IsRetryableMigrationErrorNumber(error.Number))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return IsRetryableMigrationErrorNumber(exception.Number);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Classifies a SQL Server error number as a retryable outcome of N nodes provisioning the same
|
||||
/// (possibly virgin) database at once. Everything here is a race whose retry re-runs the
|
||||
/// idempotent <c>IF NOT EXISTS</c> path; anything else (login failures, missing database,
|
||||
/// permissions, syntax) reproduces identically on retry and must propagate. 2705 (duplicate
|
||||
/// column) is deliberately absent: every column lives inside a single <c>CREATE TABLE</c>
|
||||
/// statement, so no cross-session race can produce it.
|
||||
/// </summary>
|
||||
/// <param name="errorNumber">The <see cref="SqlError.Number"/> to classify.</param>
|
||||
/// <returns><see langword="true"/> when the number is a known provisioning-race outcome.</returns>
|
||||
internal static bool IsRetryableMigrationErrorNumber(int errorNumber) => errorNumber
|
||||
is SqlDeadlockVictimErrorNumber
|
||||
or SqlObjectAlreadyExistsErrorNumber
|
||||
or SqlIndexAlreadyExistsErrorNumber
|
||||
or SqlPrimaryKeyViolationErrorNumber;
|
||||
|
||||
private async Task MigrateOnceAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
string schema = connectionFactory.Schema;
|
||||
|
||||
await using SqlConnection connection =
|
||||
await connectionFactory.OpenConnectionAsync(cancellationToken).ConfigureAwait(false);
|
||||
|
||||
// Serializable: unlike the single-writer SQLite store, EVERY node in the cluster runs this
|
||||
// migration at startup, so concurrent first-boots are the normal case rather than a rare
|
||||
// race. The isolation level narrows the race window but does NOT close it — the IF NOT
|
||||
// EXISTS metadata probes are not serialized against another session's in-flight CREATE, so
|
||||
// a loser can still fail with "object exists" (2714/1913) or a deadlock (1205). The retry
|
||||
// filter in MigrateAsync is what makes simultaneous provision converge: by the time the
|
||||
// loser retries, the winner's objects exist and every guard here skips them.
|
||||
await using SqlTransaction transaction = (SqlTransaction)
|
||||
await connection.BeginTransactionAsync(IsolationLevel.Serializable, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
int existingVersion =
|
||||
await ReadExistingSchemaVersionAsync(connection, transaction, schema, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
if (existingVersion > SqlServerAuthSchema.CurrentVersion)
|
||||
{
|
||||
throw new AuthStoreMigrationException(
|
||||
$"Shared API-key database schema version {existingVersion} is newer than supported version " +
|
||||
$"{SqlServerAuthSchema.CurrentVersion}. Upgrade this node before it writes to the shared store.");
|
||||
}
|
||||
|
||||
await using (SqlCommand ddl = connectionFactory.CreateCommand(
|
||||
connection, SqlServerAuthSchema.CreateSchemaDdl(schema), transaction))
|
||||
{
|
||||
await ddl.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// MERGE rather than insert-if-missing: WHEN MATCHED re-stamps the row, so a future schema
|
||||
// version actually lands in the table instead of leaving the first-ever value behind.
|
||||
await using (SqlCommand version = connectionFactory.CreateCommand(
|
||||
connection,
|
||||
$"""
|
||||
MERGE [{schema}].[{SqlServerAuthSchema.SchemaVersionTable}] AS target
|
||||
USING (SELECT 1 AS id, @version AS version, @applied_utc AS applied_utc) AS source
|
||||
ON target.id = source.id
|
||||
WHEN MATCHED THEN
|
||||
UPDATE SET version = source.version, applied_utc = source.applied_utc
|
||||
WHEN NOT MATCHED THEN
|
||||
INSERT (id, version, applied_utc) VALUES (1, source.version, source.applied_utc);
|
||||
""",
|
||||
transaction))
|
||||
{
|
||||
version.Parameters.Add("@version", SqlDbType.Int).Value = SqlServerAuthSchema.CurrentVersion;
|
||||
version.Parameters.Add("@applied_utc", SqlDbType.DateTimeOffset).Value = DateTimeOffset.UtcNow;
|
||||
await version.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await transaction.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task<int> ReadExistingSchemaVersionAsync(
|
||||
SqlConnection connection,
|
||||
SqlTransaction transaction,
|
||||
string schema,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
// OBJECT_ID returns NULL for an absent table, so this reads 0 on a virgin database without
|
||||
// needing the table to exist first.
|
||||
await using SqlCommand command = connectionFactory.CreateCommand(
|
||||
connection,
|
||||
$"""
|
||||
IF OBJECT_ID(N'[{schema}].[{SqlServerAuthSchema.SchemaVersionTable}]', N'U') IS NULL
|
||||
SELECT 0;
|
||||
ELSE
|
||||
SELECT ISNULL((SELECT version FROM [{schema}].[{SqlServerAuthSchema.SchemaVersionTable}] WHERE id = 1), 0);
|
||||
""",
|
||||
transaction);
|
||||
|
||||
object? version = await command.ExecuteScalarAsync(cancellationToken).ConfigureAwait(false);
|
||||
|
||||
return version is null || version == DBNull.Value
|
||||
? 0
|
||||
: Convert.ToInt32(version, CultureInfo.InvariantCulture);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
namespace ZB.MOM.WW.Auth.ApiKeys.SqlServer;
|
||||
|
||||
/// <summary>
|
||||
/// Schema constants and DDL for the shared SQL Server API-key store. Mirrors
|
||||
/// <c>ZB.MOM.WW.Auth.ApiKeys.Sqlite.SqliteAuthSchema</c> column-for-column so a row means exactly
|
||||
/// the same thing in either store.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// <b>Timestamps are <c>DATETIMEOFFSET(7)</c>, not ISO-8601 text.</b> The sibling
|
||||
/// <c>ZB.MOM.WW.Secrets</c> SQL Server store deliberately stores its timestamps as
|
||||
/// <c>nvarchar</c> because its rows <em>replicate</em> with a SQLite store and last-writer-wins
|
||||
/// compares those timestamps for equality, where a sub-tick round-trip difference would turn a tie
|
||||
/// into a spurious "newer". No such rationale applies here: this store never replicates with the
|
||||
/// SQLite one — a host picks exactly one provider, and the one-shot SQLite import is a copy, not an
|
||||
/// ongoing sync — so the native type is used, which sorts and range-scans correctly and keeps the
|
||||
/// tables readable to a DBA.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <c>SqliteAuthSchema.CurrentVersion</c> is 3 only because that store carries the donor
|
||||
/// MxAccessGateway's version history (v1/v2 were byte-identical; v3 added <c>expires_utc</c>). This
|
||||
/// schema is created whole, with <c>expires_utc</c> present from the start, so its own version line
|
||||
/// starts at 1.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public static class SqlServerAuthSchema
|
||||
{
|
||||
/// <summary>
|
||||
/// The schema version this build creates and supports. The migrator refuses a database whose
|
||||
/// recorded version is <em>newer</em> than this.
|
||||
/// </summary>
|
||||
public const int CurrentVersion = 1;
|
||||
|
||||
/// <summary>Default schema the API-key tables live in.</summary>
|
||||
public const string DefaultSchemaName = "zbauth";
|
||||
|
||||
/// <summary>Name of the single-row table tracking the applied schema version.</summary>
|
||||
public const string SchemaVersionTable = "schema_version";
|
||||
|
||||
/// <summary>Name of the table storing API-key records.</summary>
|
||||
public const string ApiKeysTable = "api_keys";
|
||||
|
||||
/// <summary>Name of the append-only audit table.</summary>
|
||||
public const string ApiKeyAuditTable = "api_key_audit";
|
||||
|
||||
/// <summary>
|
||||
/// Returns the idempotent DDL that provisions the schema, the three tables and the two
|
||||
/// supporting indexes in <paramref name="schemaName"/>.
|
||||
/// </summary>
|
||||
/// <param name="schemaName">The SQL schema name to create the objects in.</param>
|
||||
/// <returns>The DDL batch.</returns>
|
||||
/// <remarks>
|
||||
/// <paramref name="schemaName"/> is interpolated, not parameterized — T-SQL has no parameter
|
||||
/// form for an object name. It is re-validated here against the same strict identifier
|
||||
/// allow-list <see cref="SqlServerApiKeyOptions.Validate"/> enforces, and bracket-quoted below.
|
||||
/// The duplicate check is deliberate: this method is <c>public</c>, so it must defend itself
|
||||
/// rather than trust that every caller routed through the options type. The version row is NOT
|
||||
/// written here — <see cref="SqlServerApiKeyStoreMigrator"/> writes it with a MERGE that also
|
||||
/// updates on match, so a future upgrade re-stamps the stored version.
|
||||
/// </remarks>
|
||||
/// <exception cref="InvalidOperationException"><paramref name="schemaName"/> is not a plain identifier.</exception>
|
||||
public static string CreateSchemaDdl(string schemaName)
|
||||
{
|
||||
SqlServerApiKeyOptions.ValidateIdentifier(schemaName);
|
||||
|
||||
return $"""
|
||||
IF NOT EXISTS (SELECT 1 FROM sys.schemas WHERE name = N'{schemaName}')
|
||||
EXEC(N'CREATE SCHEMA [{schemaName}]');
|
||||
|
||||
IF OBJECT_ID(N'[{schemaName}].[{SchemaVersionTable}]', N'U') IS NULL
|
||||
CREATE TABLE [{schemaName}].[{SchemaVersionTable}] (
|
||||
id INT NOT NULL CONSTRAINT PK_{schemaName}_{SchemaVersionTable} PRIMARY KEY CHECK (id = 1),
|
||||
version INT NOT NULL,
|
||||
applied_utc DATETIMEOFFSET(7) NOT NULL
|
||||
);
|
||||
|
||||
IF OBJECT_ID(N'[{schemaName}].[{ApiKeysTable}]', N'U') IS NULL
|
||||
CREATE TABLE [{schemaName}].[{ApiKeysTable}] (
|
||||
key_id NVARCHAR(64) NOT NULL CONSTRAINT PK_{schemaName}_{ApiKeysTable} PRIMARY KEY,
|
||||
key_prefix NVARCHAR(16) NOT NULL,
|
||||
secret_hash VARBINARY(64) NOT NULL,
|
||||
display_name NVARCHAR(256) NOT NULL,
|
||||
scopes NVARCHAR(MAX) NOT NULL,
|
||||
constraints NVARCHAR(MAX) NULL,
|
||||
created_utc DATETIMEOFFSET(7) NOT NULL,
|
||||
last_used_utc DATETIMEOFFSET(7) NULL,
|
||||
revoked_utc DATETIMEOFFSET(7) NULL,
|
||||
expires_utc DATETIMEOFFSET(7) NULL
|
||||
);
|
||||
|
||||
IF OBJECT_ID(N'[{schemaName}].[{ApiKeyAuditTable}]', N'U') IS NULL
|
||||
CREATE TABLE [{schemaName}].[{ApiKeyAuditTable}] (
|
||||
audit_id BIGINT IDENTITY(1,1) NOT NULL CONSTRAINT PK_{schemaName}_{ApiKeyAuditTable} PRIMARY KEY,
|
||||
key_id NVARCHAR(64) NULL,
|
||||
event_type NVARCHAR(64) NOT NULL,
|
||||
remote_address NVARCHAR(64) NULL,
|
||||
created_utc DATETIMEOFFSET(7) NOT NULL,
|
||||
details NVARCHAR(MAX) NULL
|
||||
);
|
||||
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM sys.indexes
|
||||
WHERE name = N'ix_api_keys_revoked_utc'
|
||||
AND object_id = OBJECT_ID(N'[{schemaName}].[{ApiKeysTable}]'))
|
||||
CREATE INDEX ix_api_keys_revoked_utc
|
||||
ON [{schemaName}].[{ApiKeysTable}] (revoked_utc);
|
||||
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM sys.indexes
|
||||
WHERE name = N'ix_api_key_audit_key_id_created_utc'
|
||||
AND object_id = OBJECT_ID(N'[{schemaName}].[{ApiKeyAuditTable}]'))
|
||||
CREATE INDEX ix_api_key_audit_key_id_created_utc
|
||||
ON [{schemaName}].[{ApiKeyAuditTable}] (key_id, created_utc);
|
||||
""";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
using ZB.MOM.WW.Auth.Abstractions.ApiKeys;
|
||||
|
||||
namespace ZB.MOM.WW.Auth.ApiKeys.SqlServer;
|
||||
|
||||
/// <summary>
|
||||
/// Keeps the SQL Server stores' key-id handling identical to the SQLite store they port (Auth-008):
|
||||
/// no silent truncation and exact key-id matching.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// <b>Lengths.</b> Every parameter carries an explicit size, and SqlClient truncates an over-length
|
||||
/// value to that size without an error. So an over-length key record is refused up front, and a
|
||||
/// lookup of an over-length key id answers "not found" without querying — such a key cannot exist,
|
||||
/// and the truncated parameter would otherwise match a different key that shares its first 64
|
||||
/// characters.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <b>Case.</b> The <c>key_id</c> column uses the database's collation, case-insensitive on a stock
|
||||
/// SQL Server, whereas SQLite compares key ids byte-for-byte. Changing the column's collation would
|
||||
/// need a schema migration of a primary key on a live shared store, so every <c>key_id</c> predicate
|
||||
/// instead adds <see cref="ExactKeyIdMatch"/>: the collation-aware <c>=</c> still drives the primary-key
|
||||
/// seek, and the binary comparison then rejects a row that differs in case or trailing spaces.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
internal static class SqlServerColumnLimits
|
||||
{
|
||||
/// <summary>Width of <c>api_keys.key_id</c> (and <c>api_key_audit.key_id</c>).</summary>
|
||||
public const int KeyId = 64;
|
||||
|
||||
/// <summary>Width of <c>api_keys.key_prefix</c>.</summary>
|
||||
public const int KeyPrefix = 16;
|
||||
|
||||
/// <summary>Width of <c>api_keys.display_name</c>.</summary>
|
||||
public const int DisplayName = 256;
|
||||
|
||||
/// <summary>
|
||||
/// Appended to every <c>key_id = @key_id</c>. <c>NVARCHAR</c> → <c>VARBINARY</c> yields the UTF-16
|
||||
/// bytes, so the comparison is exact (case, accents and trailing spaces all significant).
|
||||
/// </summary>
|
||||
public const string ExactKeyIdMatch = "CAST(key_id AS VARBINARY(128)) = CAST(@key_id AS VARBINARY(128))";
|
||||
|
||||
/// <summary>Whether a key with this id could be stored at all.</summary>
|
||||
public static bool CanExist(string keyId) => keyId.Length <= KeyId;
|
||||
|
||||
/// <summary>The first over-length field of <paramref name="record"/>, described, or <see langword="null"/> when every field fits.</summary>
|
||||
public static string? OverLengthField(ApiKeyRecord record) =>
|
||||
record.KeyId.Length > KeyId ? Describe(nameof(ApiKeyRecord.KeyId), record.KeyId.Length, KeyId)
|
||||
: record.KeyPrefix.Length > KeyPrefix ? Describe(nameof(ApiKeyRecord.KeyPrefix), record.KeyPrefix.Length, KeyPrefix)
|
||||
: record.DisplayName.Length > DisplayName ? Describe(nameof(ApiKeyRecord.DisplayName), record.DisplayName.Length, DisplayName)
|
||||
: null;
|
||||
|
||||
/// <summary>Throws <see cref="ArgumentException"/> when a field of <paramref name="record"/> exceeds its column.</summary>
|
||||
public static void EnsureFits(ApiKeyRecord record)
|
||||
{
|
||||
if (OverLengthField(record) is { } problem)
|
||||
throw new ArgumentException($"API key record cannot be stored in SQL Server: {problem}.", nameof(record));
|
||||
}
|
||||
|
||||
private static string Describe(string field, int length, int max) =>
|
||||
$"{field} is {length} characters, more than the column's {max}";
|
||||
}
|
||||
@@ -0,0 +1,361 @@
|
||||
using System.Data;
|
||||
using Microsoft.Data.SqlClient;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using ZB.MOM.WW.Auth.Abstractions.ApiKeys;
|
||||
using ZB.MOM.WW.Auth.ApiKeys.Sqlite;
|
||||
|
||||
namespace ZB.MOM.WW.Auth.ApiKeys.SqlServer;
|
||||
|
||||
/// <summary>Result of a one-shot import.</summary>
|
||||
/// <param name="KeysInserted">Keys copied into SQL Server by this run.</param>
|
||||
/// <param name="KeysSkipped">Keys whose <c>key_id</c> already existed in SQL Server.</param>
|
||||
/// <param name="AuditInserted">Audit rows copied into SQL Server by this run.</param>
|
||||
/// <param name="AuditSkipped">Audit rows that already existed in SQL Server.</param>
|
||||
/// <param name="SourceFound">Whether the SQLite file existed at all.</param>
|
||||
public sealed record ApiKeyImportResult(
|
||||
int KeysInserted, int KeysSkipped, int AuditInserted, int AuditSkipped, bool SourceFound)
|
||||
{
|
||||
/// <summary>
|
||||
/// Source key ids that were NOT imported because SQL Server already holds a key whose id differs
|
||||
/// only in case (since 0.4.4, Auth-008). SQLite compares key ids exactly, so <c>Line1</c> and
|
||||
/// <c>line1</c> can both exist there; the SQL Server <c>key_id</c> primary key uses the database's
|
||||
/// collation (case-insensitive by default) and cannot hold both. Such a key's token will not
|
||||
/// verify against the shared store — re-mint it under a distinct id. Not counted in
|
||||
/// <see cref="KeysSkipped"/>, which counts only exact duplicates.
|
||||
/// </summary>
|
||||
public IReadOnlyList<string> KeyIdCollisions { get; init; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Source key ids that were NOT imported because a value exceeds its SQL Server column
|
||||
/// (<c>key_id</c> 64, <c>key_prefix</c> 16, <c>display_name</c> 256 characters) (since 0.4.4,
|
||||
/// Auth-008). Up to 0.4.3 such a row was imported silently truncated. Not counted in
|
||||
/// <see cref="KeysSkipped"/>.
|
||||
/// </summary>
|
||||
public IReadOnlyList<string> KeysRejected { get; init; } = [];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Copies every key and audit row from a per-node SQLite store into the shared SQL Server store,
|
||||
/// insert-where-not-exists (keys by key_id; audit rows by key_id + event_type + created_utc), so it is
|
||||
/// idempotent and every node of a pair may run it: the result is the UNION of the nodes' files. A row
|
||||
/// that already exists in SQL Server is never modified — a revoke recorded on one node but not the
|
||||
/// other therefore survives only if the revoked copy is imported first; operators reconcile by listing.
|
||||
/// </summary>
|
||||
/// <param name="sql">Factory for connections to the shared SQL Server API-key database.</param>
|
||||
public sealed class SqliteApiKeyStoreImporter(AuthSqlServerConnectionFactory sql)
|
||||
{
|
||||
/// <summary>
|
||||
/// Imports the keys and audit rows held in the SQLite store at <paramref name="sqlitePath"/>.
|
||||
/// </summary>
|
||||
/// <param name="sqlitePath">Path of the per-node SQLite API-key file.</param>
|
||||
/// <param name="ct">A token to cancel the import.</param>
|
||||
/// <returns>
|
||||
/// The per-category insert/skip counts. When the file does not exist the result is all zeroes
|
||||
/// with <see cref="ApiKeyImportResult.SourceFound"/> <see langword="false"/> and nothing is
|
||||
/// opened — a host that has already imported (and renamed the file) pays nothing.
|
||||
/// </returns>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// The SQLite file is opened READ-ONLY and the schema migrator is deliberately NOT run against
|
||||
/// it: the source is evidence, not something to upgrade. A file with no <c>api_keys</c> table is
|
||||
/// treated as an empty source rather than an error, and a pre-v3 file (no <c>expires_utc</c>
|
||||
/// column) reads its expiry as NULL = never expires, which is exactly what those keys meant.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// Every row is read and the SQLite connection closed BEFORE any SQL Server write, and all the
|
||||
/// writes then run inside ONE transaction. So the import is all-or-nothing: a failure part way
|
||||
/// through rolls the transaction back and the exception propagates to the caller, leaving the
|
||||
/// shared store exactly as it was. The host decides what that means — for a boot-time import,
|
||||
/// logging and carrying on is usually right, because keys already in SQL Server keep working.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
/// <exception cref="SqlException">A SQL Server write failed; nothing was committed.</exception>
|
||||
/// <exception cref="SqliteException">The source file could not be read.</exception>
|
||||
public async Task<ApiKeyImportResult> ImportAsync(string sqlitePath, CancellationToken ct)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(sqlitePath);
|
||||
|
||||
if (!File.Exists(sqlitePath))
|
||||
{
|
||||
return new ApiKeyImportResult(0, 0, 0, 0, SourceFound: false);
|
||||
}
|
||||
|
||||
(IReadOnlyList<ApiKeyRecord> keys, IReadOnlyList<ApiKeyAuditEntry> auditEntries) =
|
||||
await ReadSourceAsync(sqlitePath, ct).ConfigureAwait(false);
|
||||
|
||||
return await WriteAsync(keys, auditEntries, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// --- read side (SQLite) ---
|
||||
|
||||
private static async Task<(IReadOnlyList<ApiKeyRecord> Keys, IReadOnlyList<ApiKeyAuditEntry> Audit)>
|
||||
ReadSourceAsync(string sqlitePath, CancellationToken ct)
|
||||
{
|
||||
SqliteConnectionStringBuilder builder = new()
|
||||
{
|
||||
DataSource = sqlitePath,
|
||||
Mode = SqliteOpenMode.ReadOnly,
|
||||
};
|
||||
|
||||
await using var connection = new SqliteConnection(builder.ToString());
|
||||
await connection.OpenAsync(ct).ConfigureAwait(false);
|
||||
|
||||
IReadOnlyList<ApiKeyRecord> keys =
|
||||
await TableExistsAsync(connection, SqliteAuthSchema.ApiKeysTable, ct).ConfigureAwait(false)
|
||||
? await ReadKeysAsync(connection, ct).ConfigureAwait(false)
|
||||
: [];
|
||||
|
||||
IReadOnlyList<ApiKeyAuditEntry> audit =
|
||||
await TableExistsAsync(connection, SqliteAuthSchema.ApiKeyAuditTable, ct).ConfigureAwait(false)
|
||||
? await ReadAuditAsync(connection, ct).ConfigureAwait(false)
|
||||
: [];
|
||||
|
||||
return (keys, audit);
|
||||
}
|
||||
|
||||
private static async Task<bool> TableExistsAsync(
|
||||
SqliteConnection connection, string tableName, CancellationToken ct)
|
||||
{
|
||||
await using SqliteCommand command = connection.CreateCommand();
|
||||
command.CommandText = """
|
||||
SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = $table_name;
|
||||
""";
|
||||
command.Parameters.AddWithValue("$table_name", tableName);
|
||||
|
||||
return (long)(await command.ExecuteScalarAsync(ct).ConfigureAwait(false) ?? 0L) > 0;
|
||||
}
|
||||
|
||||
private static async Task<IReadOnlyList<ApiKeyRecord>> ReadKeysAsync(
|
||||
SqliteConnection connection, CancellationToken ct)
|
||||
{
|
||||
// A pre-v3 file has no expires_utc column, so select a literal NULL in its place rather than
|
||||
// failing the import: NULL is precisely what those keys mean (never expires).
|
||||
bool hasExpires = await ColumnExistsAsync(
|
||||
connection, SqliteAuthSchema.ApiKeysTable, SqliteAuthSchema.ExpiresUtcColumn, ct).ConfigureAwait(false);
|
||||
|
||||
string expiresColumn = hasExpires ? SqliteAuthSchema.ExpiresUtcColumn : "NULL";
|
||||
|
||||
await using SqliteCommand command = connection.CreateCommand();
|
||||
command.CommandText =
|
||||
"SELECT key_id, key_prefix, secret_hash, display_name, scopes, constraints, " +
|
||||
$"created_utc, last_used_utc, revoked_utc, {expiresColumn} FROM api_keys;";
|
||||
|
||||
List<ApiKeyRecord> keys = [];
|
||||
|
||||
await using SqliteDataReader reader = await command.ExecuteReaderAsync(ct).ConfigureAwait(false);
|
||||
|
||||
while (await reader.ReadAsync(ct).ConfigureAwait(false))
|
||||
{
|
||||
keys.Add(new ApiKeyRecord(
|
||||
KeyId: reader.GetString(0),
|
||||
KeyPrefix: reader.GetString(1),
|
||||
SecretHash: reader.GetFieldValue<byte[]>(2),
|
||||
DisplayName: reader.GetString(3),
|
||||
Scopes: ScopeSerializer.Deserialize(reader.GetString(4)),
|
||||
ConstraintsJson: reader.IsDBNull(5) ? null : reader.GetString(5),
|
||||
CreatedUtc: SqliteValueParsing.ParseUtc(reader.GetString(6)),
|
||||
LastUsedUtc: SqliteValueParsing.ReadNullableUtc(reader, 7),
|
||||
RevokedUtc: SqliteValueParsing.ReadNullableUtc(reader, 8),
|
||||
ExpiresUtc: SqliteValueParsing.ReadNullableUtc(reader, 9)));
|
||||
}
|
||||
|
||||
return keys;
|
||||
}
|
||||
|
||||
// SQLite has no information_schema; PRAGMA table_info is the column probe (the same one
|
||||
// SqliteAuthStoreMigrator uses to decide whether its v3 ALTER TABLE is needed).
|
||||
private static async Task<bool> ColumnExistsAsync(
|
||||
SqliteConnection connection, string tableName, string columnName, CancellationToken ct)
|
||||
{
|
||||
await using SqliteCommand command = connection.CreateCommand();
|
||||
// table_info takes an identifier, not a bindable parameter; the name is an internal constant.
|
||||
command.CommandText = $"PRAGMA table_info({tableName});";
|
||||
|
||||
await using SqliteDataReader reader = await command.ExecuteReaderAsync(ct).ConfigureAwait(false);
|
||||
|
||||
while (await reader.ReadAsync(ct).ConfigureAwait(false))
|
||||
{
|
||||
// PRAGMA table_info columns: cid(0), name(1), type(2), ...
|
||||
if (string.Equals(reader.GetString(1), columnName, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static async Task<IReadOnlyList<ApiKeyAuditEntry>> ReadAuditAsync(
|
||||
SqliteConnection connection, CancellationToken ct)
|
||||
{
|
||||
await using SqliteCommand command = connection.CreateCommand();
|
||||
// Insertion order, so the shared table's IDENTITY re-creates the source's ordering.
|
||||
command.CommandText = """
|
||||
SELECT key_id, event_type, remote_address, created_utc, details
|
||||
FROM api_key_audit
|
||||
ORDER BY audit_id;
|
||||
""";
|
||||
|
||||
List<ApiKeyAuditEntry> entries = [];
|
||||
|
||||
await using SqliteDataReader reader = await command.ExecuteReaderAsync(ct).ConfigureAwait(false);
|
||||
|
||||
while (await reader.ReadAsync(ct).ConfigureAwait(false))
|
||||
{
|
||||
entries.Add(new ApiKeyAuditEntry(
|
||||
KeyId: reader.IsDBNull(0) ? null : reader.GetString(0),
|
||||
EventType: reader.GetString(1),
|
||||
RemoteAddress: reader.IsDBNull(2) ? null : reader.GetString(2),
|
||||
CreatedUtc: SqliteValueParsing.ParseUtc(reader.GetString(3)),
|
||||
Details: reader.IsDBNull(4) ? null : reader.GetString(4)));
|
||||
}
|
||||
|
||||
return entries;
|
||||
}
|
||||
|
||||
// --- write side (SQL Server) ---
|
||||
|
||||
private async Task<ApiKeyImportResult> WriteAsync(
|
||||
IReadOnlyList<ApiKeyRecord> keys,
|
||||
IReadOnlyList<ApiKeyAuditEntry> auditEntries,
|
||||
CancellationToken ct)
|
||||
{
|
||||
string schema = sql.Schema;
|
||||
|
||||
await using SqlConnection connection = await sql.OpenConnectionAsync(ct).ConfigureAwait(false);
|
||||
await using SqlTransaction transaction =
|
||||
(SqlTransaction)await connection.BeginTransactionAsync(ct).ConfigureAwait(false);
|
||||
|
||||
int keysInserted = 0;
|
||||
int keysSkipped = 0;
|
||||
int auditInserted = 0;
|
||||
List<string> collisions = [];
|
||||
List<string> rejected = [];
|
||||
|
||||
foreach (ApiKeyRecord key in keys)
|
||||
{
|
||||
// Refused rather than written truncated: a truncated key_id would verify only through an
|
||||
// equally truncated lookup and authenticate as an id nobody assigned (Auth-008).
|
||||
if (SqlServerColumnLimits.OverLengthField(key) is not null)
|
||||
{
|
||||
rejected.Add(key.KeyId);
|
||||
continue;
|
||||
}
|
||||
|
||||
switch (await InsertKeyIfAbsentAsync(connection, transaction, schema, key, ct).ConfigureAwait(false))
|
||||
{
|
||||
case KeyInsertOutcome.Inserted:
|
||||
keysInserted++;
|
||||
break;
|
||||
case KeyInsertOutcome.AlreadyPresent:
|
||||
keysSkipped++;
|
||||
break;
|
||||
default:
|
||||
collisions.Add(key.KeyId);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
foreach (ApiKeyAuditEntry entry in auditEntries)
|
||||
{
|
||||
if (await InsertAuditIfAbsentAsync(connection, transaction, schema, entry, ct).ConfigureAwait(false))
|
||||
{
|
||||
auditInserted++;
|
||||
}
|
||||
}
|
||||
|
||||
await transaction.CommitAsync(ct).ConfigureAwait(false);
|
||||
|
||||
return new ApiKeyImportResult(
|
||||
KeysInserted: keysInserted,
|
||||
KeysSkipped: keysSkipped,
|
||||
AuditInserted: auditInserted,
|
||||
AuditSkipped: auditEntries.Count - auditInserted,
|
||||
SourceFound: true)
|
||||
{
|
||||
KeyIdCollisions = collisions,
|
||||
KeysRejected = rejected,
|
||||
};
|
||||
}
|
||||
|
||||
private enum KeyInsertOutcome
|
||||
{
|
||||
Inserted = 1,
|
||||
AlreadyPresent = 0,
|
||||
CaseVariantPresent = 2,
|
||||
}
|
||||
|
||||
// The guard is inside the statement rather than a separate SELECT so the check and the insert
|
||||
// cannot straddle a concurrent writer. The collation-aware `key_id = @key_id` finds a row whose
|
||||
// id differs only in case — the primary key would refuse to hold both — and the exact match tells
|
||||
// that collision apart from a genuine duplicate.
|
||||
private async Task<KeyInsertOutcome> InsertKeyIfAbsentAsync(
|
||||
SqlConnection connection,
|
||||
SqlTransaction transaction,
|
||||
string schema,
|
||||
ApiKeyRecord key,
|
||||
CancellationToken ct)
|
||||
{
|
||||
await using SqlCommand command = sql.CreateCommand(connection, $"""
|
||||
IF EXISTS (
|
||||
SELECT 1 FROM [{schema}].[{SqlServerAuthSchema.ApiKeysTable}]
|
||||
WHERE key_id = @key_id AND {SqlServerColumnLimits.ExactKeyIdMatch})
|
||||
SELECT 0;
|
||||
ELSE IF EXISTS (
|
||||
SELECT 1 FROM [{schema}].[{SqlServerAuthSchema.ApiKeysTable}] WHERE key_id = @key_id)
|
||||
SELECT 2;
|
||||
ELSE
|
||||
BEGIN
|
||||
INSERT INTO [{schema}].[{SqlServerAuthSchema.ApiKeysTable}] (
|
||||
key_id, key_prefix, secret_hash, display_name, scopes,
|
||||
constraints, created_utc, last_used_utc, revoked_utc, expires_utc)
|
||||
VALUES (
|
||||
@key_id, @key_prefix, @secret_hash, @display_name, @scopes,
|
||||
@constraints, @created_utc, @last_used_utc, @revoked_utc, @expires_utc);
|
||||
SELECT 1;
|
||||
END
|
||||
""", transaction);
|
||||
command.Parameters.Add("@key_id", SqlDbType.NVarChar, 64).Value = key.KeyId;
|
||||
command.Parameters.Add("@key_prefix", SqlDbType.NVarChar, 16).Value = key.KeyPrefix;
|
||||
command.Parameters.Add("@secret_hash", SqlDbType.VarBinary, 64).Value = key.SecretHash;
|
||||
command.Parameters.Add("@display_name", SqlDbType.NVarChar, 256).Value = key.DisplayName;
|
||||
command.Parameters.Add("@scopes", SqlDbType.NVarChar, -1).Value = ScopeSerializer.Serialize(key.Scopes);
|
||||
command.Parameters.Add("@constraints", SqlDbType.NVarChar, -1).Value = (object?)key.ConstraintsJson ?? DBNull.Value;
|
||||
command.Parameters.Add("@created_utc", SqlDbType.DateTimeOffset).Value = key.CreatedUtc;
|
||||
command.Parameters.Add("@last_used_utc", SqlDbType.DateTimeOffset).Value = (object?)key.LastUsedUtc ?? DBNull.Value;
|
||||
command.Parameters.Add("@revoked_utc", SqlDbType.DateTimeOffset).Value = (object?)key.RevokedUtc ?? DBNull.Value;
|
||||
command.Parameters.Add("@expires_utc", SqlDbType.DateTimeOffset).Value = (object?)key.ExpiresUtc ?? DBNull.Value;
|
||||
|
||||
object? outcome = await command.ExecuteScalarAsync(ct).ConfigureAwait(false);
|
||||
return (KeyInsertOutcome)Convert.ToInt32(outcome, System.Globalization.CultureInfo.InvariantCulture);
|
||||
}
|
||||
|
||||
// Audit rows carry no natural key (audit_id is per-file IDENTITY), so identity is the triple
|
||||
// key_id + event_type + created_utc. key_id is nullable, hence the explicit NULL-safe arm: a
|
||||
// plain `key_id = @key_id` is UNKNOWN, never true, when both sides are NULL.
|
||||
private async Task<bool> InsertAuditIfAbsentAsync(
|
||||
SqlConnection connection,
|
||||
SqlTransaction transaction,
|
||||
string schema,
|
||||
ApiKeyAuditEntry entry,
|
||||
CancellationToken ct)
|
||||
{
|
||||
await using SqlCommand command = sql.CreateCommand(connection, $"""
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM [{schema}].[{SqlServerAuthSchema.ApiKeyAuditTable}]
|
||||
WHERE ((key_id = @key_id) OR (key_id IS NULL AND @key_id IS NULL))
|
||||
AND event_type = @event_type
|
||||
AND created_utc = @created_utc)
|
||||
INSERT INTO [{schema}].[{SqlServerAuthSchema.ApiKeyAuditTable}] (
|
||||
key_id, event_type, remote_address, created_utc, details)
|
||||
VALUES (@key_id, @event_type, @remote_address, @created_utc, @details);
|
||||
""", transaction);
|
||||
command.Parameters.Add("@key_id", SqlDbType.NVarChar, 64).Value = (object?)entry.KeyId ?? DBNull.Value;
|
||||
command.Parameters.Add("@event_type", SqlDbType.NVarChar, 64).Value = entry.EventType;
|
||||
command.Parameters.Add("@remote_address", SqlDbType.NVarChar, 64).Value = (object?)entry.RemoteAddress ?? DBNull.Value;
|
||||
command.Parameters.Add("@created_utc", SqlDbType.DateTimeOffset).Value = entry.CreatedUtc;
|
||||
command.Parameters.Add("@details", SqlDbType.NVarChar, -1).Value = (object?)entry.Details ?? DBNull.Value;
|
||||
|
||||
return await command.ExecuteNonQueryAsync(ct).ConfigureAwait(false) > 0;
|
||||
}
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\ZB.MOM.WW.Auth.ApiKeys\ZB.MOM.WW.Auth.ApiKeys.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Data.SqlClient" />
|
||||
<!--
|
||||
Lightweight Microsoft.Extensions.* abstractions back the DI extension
|
||||
(AddZbApiKeyAuthSqlServer, shipped by Task 6): IServiceCollection / TryAdd* / Configure
|
||||
(DependencyInjection.Abstractions), IOptions (Options), IConfiguration
|
||||
(Configuration.Abstractions), and IHostedService / AddHostedService (Hosting.Abstractions).
|
||||
-->
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" />
|
||||
<PackageReference Include="Microsoft.Extensions.Options" />
|
||||
<!-- Supplies the Configure<TOptions>(IConfiguration) binding overload used by the DI extension. -->
|
||||
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" />
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" />
|
||||
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" />
|
||||
</ItemGroup>
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup>
|
||||
<IsPackable>true</IsPackable>
|
||||
<PackageId>ZB.MOM.WW.Auth.ApiKeys.SqlServer</PackageId>
|
||||
<Authors>ZB.MOM.WW</Authors>
|
||||
<Description>SQL Server API-key store for the ZB.MOM.WW SCADA family — one shared row set for clustered hosts (central pairs).</Description>
|
||||
<PackageProjectUrl>https://gitea.dohertylan.com/dohertj2/scadaproj/src/branch/main/ZB.MOM.WW.Auth</PackageProjectUrl>
|
||||
<RepositoryUrl>https://gitea.dohertylan.com/dohertj2/scadaproj</RepositoryUrl>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<InternalsVisibleTo Include="ZB.MOM.WW.Auth.ApiKeys.SqlServer.Tests" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -33,10 +33,15 @@ public sealed class ApiKeyAdminCommands
|
||||
private readonly IApiKeyAdminStore _adminStore;
|
||||
private readonly IApiKeyAuditStore _auditStore;
|
||||
private readonly IApiKeyPepperProvider _pepperProvider;
|
||||
private readonly SqliteAuthStoreMigrator _migrator;
|
||||
private readonly IApiKeyStoreMigrator _migrator;
|
||||
private readonly TimeProvider _clock;
|
||||
|
||||
/// <summary>Creates the command set over the supplied stores and options.</summary>
|
||||
/// <summary>
|
||||
/// Creates the command set over the supplied stores and options.
|
||||
/// Retained for existing consumers (MxAccessGateway, HistorianGateway, ScadaBridge) that
|
||||
/// construct this type against the concrete SQLite migrator; forwards to the
|
||||
/// <see cref="IApiKeyStoreMigrator"/> overload.
|
||||
/// </summary>
|
||||
/// <param name="options">API-key options (token prefix, store path, ...).</param>
|
||||
/// <param name="adminStore">Mutating store (create / revoke / rotate / delete / list).</param>
|
||||
/// <param name="auditStore">Append-only audit store wired into every mutating verb.</param>
|
||||
@@ -50,6 +55,25 @@ public sealed class ApiKeyAdminCommands
|
||||
IApiKeyPepperProvider pepperProvider,
|
||||
SqliteAuthStoreMigrator migrator,
|
||||
TimeProvider? clock = null)
|
||||
: this(options, adminStore, auditStore, pepperProvider, (IApiKeyStoreMigrator)migrator, clock)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>Creates the command set over the supplied stores and options.</summary>
|
||||
/// <param name="options">API-key options (token prefix, store path, ...).</param>
|
||||
/// <param name="adminStore">Mutating store (create / revoke / rotate / delete / list).</param>
|
||||
/// <param name="auditStore">Append-only audit store wired into every mutating verb.</param>
|
||||
/// <param name="pepperProvider">Resolves the pepper used to hash secrets.</param>
|
||||
/// <param name="migrator">Schema migrator used by <see cref="InitDbAsync"/> — whichever store
|
||||
/// provider's implementation (SQLite, SQL Server, ...) DI has registered.</param>
|
||||
/// <param name="clock">Optional clock; defaults to <see cref="TimeProvider.System"/>.</param>
|
||||
public ApiKeyAdminCommands(
|
||||
ApiKeyOptions options,
|
||||
IApiKeyAdminStore adminStore,
|
||||
IApiKeyAuditStore auditStore,
|
||||
IApiKeyPepperProvider pepperProvider,
|
||||
IApiKeyStoreMigrator migrator,
|
||||
TimeProvider? clock = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(options);
|
||||
ArgumentNullException.ThrowIfNull(adminStore);
|
||||
@@ -261,7 +285,7 @@ public sealed class ApiKeyAdminCommands
|
||||
string? pepper = _pepperProvider.GetPepper();
|
||||
if (string.IsNullOrWhiteSpace(pepper))
|
||||
{
|
||||
throw new InvalidOperationException("pepper unavailable");
|
||||
throw new ApiKeyPepperUnavailableException();
|
||||
}
|
||||
|
||||
return pepper;
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
namespace ZB.MOM.WW.Auth.ApiKeys;
|
||||
|
||||
/// <summary>
|
||||
/// Thrown when an API-key operation needs the secret pepper but
|
||||
/// <see cref="IApiKeyPepperProvider.GetPepper"/> returned <c>null</c>, empty or whitespace
|
||||
/// (create and rotate in <c>ApiKeyAdminCommands</c>).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Derives from <see cref="InvalidOperationException"/>, which is what these paths threw before
|
||||
/// this type existed, so existing <c>catch (InvalidOperationException)</c> blocks keep working.
|
||||
/// The message stays <c>"pepper unavailable"</c>. Consumers can catch this type instead of
|
||||
/// pre-checking <see cref="IApiKeyPepperProvider"/> themselves or matching the message. The verifier
|
||||
/// does not throw it: a missing pepper surfaces there as <c>ApiKeyFailure.PepperUnavailable</c>.
|
||||
/// </remarks>
|
||||
public sealed class ApiKeyPepperUnavailableException : InvalidOperationException
|
||||
{
|
||||
/// <summary>Creates the exception with the default <c>"pepper unavailable"</c> message.</summary>
|
||||
public ApiKeyPepperUnavailableException()
|
||||
: base("pepper unavailable")
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>Creates the exception with a custom message.</summary>
|
||||
public ApiKeyPepperUnavailableException(string message)
|
||||
: base(message)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>Creates the exception with a custom message and inner exception.</summary>
|
||||
public ApiKeyPepperUnavailableException(string message, Exception innerException)
|
||||
: base(message, innerException)
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,8 @@ namespace ZB.MOM.WW.Auth.ApiKeys;
|
||||
/// <remarks>
|
||||
/// The failure reason is discriminated for the caller/audit pipeline, but the verifier returns a
|
||||
/// structured result rather than throwing (the caller decides the opaque client-facing message).
|
||||
/// The only exception path is cancellation. A successful identity carries the key's scopes and the
|
||||
/// The only exception path is cancellation: a key-store lookup that faults is reported as
|
||||
/// <see cref="ApiKeyFailure.StoreUnavailable"/> (since 0.4.4), and a failed last-used write is ignored. A successful identity carries the key's scopes and the
|
||||
/// opaque <c>ConstraintsJson</c> blob (which the verifier does not interpret); it never carries the
|
||||
/// presented secret, the pepper, or the stored secret hash.
|
||||
/// </remarks>
|
||||
@@ -44,7 +45,24 @@ public sealed class ApiKeyVerifier(
|
||||
}
|
||||
|
||||
// 3. Look up the record (including revoked ones) so we can discriminate not-found vs revoked.
|
||||
ApiKeyRecord? record = await store.FindByKeyIdAsync(parsed.KeyId, ct).ConfigureAwait(false);
|
||||
// A store fault is a structured StoreUnavailable failure, not an exception (Auth-010): the
|
||||
// store may be a shared network database, so "unreachable" is an operating condition, and
|
||||
// consumers map Succeeded == false to their auth-failure path (and audit it) — an escaping
|
||||
// SqlException became an unaudited 500 / gRPC Unknown instead. Cancellation still throws.
|
||||
ApiKeyRecord? record;
|
||||
try
|
||||
{
|
||||
record = await store.FindByKeyIdAsync(parsed.KeyId, ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return Fail(ApiKeyFailure.StoreUnavailable);
|
||||
}
|
||||
|
||||
if (record is null)
|
||||
{
|
||||
return Fail(ApiKeyFailure.KeyNotFound);
|
||||
|
||||
+6
-5
@@ -1,17 +1,18 @@
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Options;
|
||||
using ZB.MOM.WW.Auth.Abstractions.ApiKeys;
|
||||
using ZB.MOM.WW.Auth.ApiKeys.Sqlite;
|
||||
|
||||
namespace ZB.MOM.WW.Auth.ApiKeys.DependencyInjection;
|
||||
|
||||
/// <summary>
|
||||
/// Runs the API-key SQLite schema migration at application startup when
|
||||
/// <see cref="ApiKeyOptions.RunMigrationsOnStartup"/> is <see langword="true"/>.
|
||||
/// The migration is idempotent, so repeated restarts are safe.
|
||||
/// Runs the registered <see cref="IApiKeyStoreMigrator"/> at application startup when
|
||||
/// <see cref="ApiKeyOptions.RunMigrationsOnStartup"/> is <see langword="true"/>. The migrator
|
||||
/// registered in DI is whichever store provider's implementation won the <c>TryAdd</c> race —
|
||||
/// SQLite by default, or a provider package (e.g. SQL Server) registered before
|
||||
/// <c>AddZbApiKeyAuth</c>. The migration is idempotent, so repeated restarts are safe.
|
||||
/// </summary>
|
||||
internal sealed class ApiKeyMigrationHostedService(
|
||||
SqliteAuthStoreMigrator migrator,
|
||||
IApiKeyStoreMigrator migrator,
|
||||
IOptions<ApiKeyOptions> options) : IHostedService
|
||||
{
|
||||
/// <inheritdoc />
|
||||
|
||||
+4
-2
@@ -61,10 +61,12 @@ public static class ApiKeyServiceCollectionExtensions
|
||||
sp.GetRequiredService<IApiKeyStore>(),
|
||||
sp.GetRequiredService<IApiKeyPepperProvider>()));
|
||||
|
||||
// Migrator: singleton, constructed from the already-registered connection factory.
|
||||
// Needed before any store operations so the schema exists.
|
||||
// Migrator: the SQLite implementation is the default; a provider package that registers
|
||||
// IApiKeyStoreMigrator (and the three stores) BEFORE this call displaces it — that is the
|
||||
// whole mechanism by which AddZbApiKeyAuthSqlServer swaps the backend.
|
||||
services.TryAddSingleton(sp =>
|
||||
new SqliteAuthStoreMigrator(sp.GetRequiredService<AuthSqliteConnectionFactory>()));
|
||||
services.TryAddSingleton<IApiKeyStoreMigrator>(sp => sp.GetRequiredService<SqliteAuthStoreMigrator>());
|
||||
|
||||
// Hosted service that runs migrations on startup when ApiKeyOptions.RunMigrationsOnStartup.
|
||||
services.AddHostedService<ApiKeyMigrationHostedService>();
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using System.Globalization;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using ZB.MOM.WW.Auth.Abstractions.ApiKeys;
|
||||
|
||||
namespace ZB.MOM.WW.Auth.ApiKeys.Sqlite;
|
||||
|
||||
@@ -11,7 +12,7 @@ public sealed class AuthStoreMigrationException(string message) : InvalidOperati
|
||||
/// is safe to run repeatedly. Refuses to run against a database whose on-disk version
|
||||
/// is newer than this build supports.
|
||||
/// </summary>
|
||||
public sealed class SqliteAuthStoreMigrator(AuthSqliteConnectionFactory connectionFactory)
|
||||
public sealed class SqliteAuthStoreMigrator(AuthSqliteConnectionFactory connectionFactory) : IApiKeyStoreMigrator
|
||||
{
|
||||
/// <summary>Applies the schema migration to the auth store.</summary>
|
||||
/// <param name="cancellationToken">Cancellation token.</param>
|
||||
|
||||
@@ -32,12 +32,15 @@
|
||||
<PackageId>ZB.MOM.WW.Auth.ApiKeys</PackageId>
|
||||
<Authors>ZB.MOM.WW</Authors>
|
||||
<Description>SQLite-backed API-key store with pepper-based hashing for the ZB.MOM.WW SCADA family.</Description>
|
||||
<PackageProjectUrl>https://gitea.dohertylan.com/dohertj2/zb-mom-ww-auth</PackageProjectUrl>
|
||||
<RepositoryUrl>https://gitea.dohertylan.com/dohertj2/zb-mom-ww-auth</RepositoryUrl>
|
||||
<PackageProjectUrl>https://gitea.dohertylan.com/dohertj2/scadaproj/src/branch/main/ZB.MOM.WW.Auth</PackageProjectUrl>
|
||||
<RepositoryUrl>https://gitea.dohertylan.com/dohertj2/scadaproj</RepositoryUrl>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<InternalsVisibleTo Include="ZB.MOM.WW.Auth.ApiKeys.Tests" />
|
||||
<!-- Task 5's SqliteApiKeyStoreImporter parses SQLite values with SqliteValueParsing (internal)
|
||||
rather than duplicating the parser. -->
|
||||
<InternalsVisibleTo Include="ZB.MOM.WW.Auth.ApiKeys.SqlServer" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
||||
@@ -22,7 +22,8 @@ public static class ServiceCollectionExtensions
|
||||
/// <summary>
|
||||
/// Registers LDAP authentication: binds and validates <see cref="LdapOptions"/> from the
|
||||
/// configuration section at <paramref name="sectionPath"/>, and registers
|
||||
/// <see cref="ILdapAuthService"/>.
|
||||
/// <see cref="ILdapAuthService"/> and (0.5.0) <see cref="ILdapGroupLookup"/> — both resolve to the
|
||||
/// same <see cref="LdapAuthService"/> instance.
|
||||
/// </summary>
|
||||
/// <param name="services">The service collection to add to.</param>
|
||||
/// <param name="config">The application configuration.</param>
|
||||
@@ -49,12 +50,35 @@ public static class ServiceCollectionExtensions
|
||||
// Fail fast at startup on a misconfigured directory rather than on first login.
|
||||
services.AddSingleton<IValidateOptions<LdapOptions>, LdapOptionsValidator>();
|
||||
|
||||
// LdapAuthService is stateless: it holds only a snapshot of LdapOptions and a stateless
|
||||
// connection factory, and opens/disposes a connection per call. It is not IDisposable.
|
||||
// Singleton is correct; TryAdd mirrors the pattern in AddZbApiKeyAuth (idempotency).
|
||||
// LdapAuthService opens/disposes a connection per call and is not IDisposable. Its only
|
||||
// mutable state is the sticky endpoint preference used by FallbackServers failover —
|
||||
// which is precisely why the instance must be shared, so a primary-DC outage is paid
|
||||
// for once rather than on every login. Singleton is correct; TryAdd mirrors the pattern
|
||||
// in AddZbApiKeyAuth (idempotency). The logger is resolved with GetService, not
|
||||
// GetRequiredService, so a host without logging configured still resolves the service.
|
||||
services.TryAddSingleton<ILdapAuthService>(sp =>
|
||||
new LdapAuthService(sp.GetRequiredService<IOptions<LdapOptions>>().Value));
|
||||
new LdapAuthService(
|
||||
sp.GetRequiredService<IOptions<LdapOptions>>().Value,
|
||||
sp.GetService<Microsoft.Extensions.Logging.ILogger<LdapAuthService>>()));
|
||||
|
||||
// 0.5.0: the passwordless group lookup is the SAME instance as the auth service, so both share
|
||||
// one sticky endpoint preference. A host that registered its own ILdapAuthService (a dev stub,
|
||||
// a decorator) gets a lookup that answers NotSupported rather than a second, divergent client.
|
||||
services.TryAddSingleton<ILdapGroupLookup>(sp =>
|
||||
sp.GetRequiredService<ILdapAuthService>() as ILdapGroupLookup ?? UnsupportedLdapGroupLookup.Instance);
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
/// <summary>Answers every lookup with <see cref="LdapGroupLookupStatus.NotSupported"/>.</summary>
|
||||
private sealed class UnsupportedLdapGroupLookup : ILdapGroupLookup
|
||||
{
|
||||
public static readonly UnsupportedLdapGroupLookup Instance = new();
|
||||
|
||||
public Task<LdapGroupLookupResult> GetUserGroupsAsync(string username, CancellationToken ct)
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
return Task.FromResult(LdapGroupLookupResult.Of(LdapGroupLookupStatus.NotSupported));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,8 +11,8 @@
|
||||
<PackageId>ZB.MOM.WW.Auth.AspNetCore</PackageId>
|
||||
<Authors>ZB.MOM.WW</Authors>
|
||||
<Description>ASP.NET Core DI helpers, cookie defaults, and claim mappings for the ZB.MOM.WW SCADA family.</Description>
|
||||
<PackageProjectUrl>https://gitea.dohertylan.com/dohertj2/zb-mom-ww-auth</PackageProjectUrl>
|
||||
<RepositoryUrl>https://gitea.dohertylan.com/dohertj2/zb-mom-ww-auth</RepositoryUrl>
|
||||
<PackageProjectUrl>https://gitea.dohertylan.com/dohertj2/scadaproj/src/branch/main/ZB.MOM.WW.Auth</PackageProjectUrl>
|
||||
<RepositoryUrl>https://gitea.dohertylan.com/dohertj2/scadaproj</RepositoryUrl>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
@@ -45,6 +45,22 @@ internal interface ILdapConnection : IDisposable
|
||||
|
||||
/// <summary>Executes a subtree search and returns all matching entries.</summary>
|
||||
IReadOnlyList<LdapSearchEntry> Search(string searchBase, string filter, IReadOnlyList<string> attributes);
|
||||
|
||||
/// <summary>
|
||||
/// Reads one entry by DN (a base-scope search) and returns the requested attributes the server
|
||||
/// sent, or <see langword="null"/> when the entry does not exist. Throws <c>LdapException</c> on
|
||||
/// any other failure. Used for constructed attributes such as AD's <c>msDS-PrincipalName</c>,
|
||||
/// which a server may compute for a base read but not for a subtree search.
|
||||
/// </summary>
|
||||
LdapSearchEntry? Read(string dn, IReadOnlyList<string> attributes);
|
||||
|
||||
/// <summary>
|
||||
/// RFC 4532 "Who am I?": the authorization identity the directory associates with the current
|
||||
/// bind, as the server sends it (<c>dn:<dn></c>, <c>u:DOMAIN\name</c>, or empty for an
|
||||
/// anonymous bind). Throws <c>LdapException</c> when the server does not support the operation
|
||||
/// (GLAuth answers protocol error 2).
|
||||
/// </summary>
|
||||
string WhoAmI();
|
||||
}
|
||||
|
||||
/// <summary>Factory that produces <see cref="ILdapConnection"/> instances.</summary>
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
namespace ZB.MOM.WW.Auth.Ldap.Internal;
|
||||
|
||||
/// <summary>A single LDAP server endpoint resolved from configuration.</summary>
|
||||
internal sealed record LdapEndpoint(string Host, int Port)
|
||||
{
|
||||
/// <summary>Renders the endpoint as <c>host:port</c> — the form used in failover log messages.</summary>
|
||||
public override string ToString() => $"{Host}:{Port}";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Parses <c>FallbackServers</c> entries: <c>"host"</c> (adopts the caller's default port)
|
||||
/// or <c>"host:port"</c>. IPv6 literals are not supported — use a DNS name.
|
||||
/// </summary>
|
||||
internal static class LdapEndpointParser
|
||||
{
|
||||
/// <summary>
|
||||
/// Attempts to parse a single <c>FallbackServers</c> entry.
|
||||
/// </summary>
|
||||
/// <param name="entry">The configured entry, <c>"host"</c> or <c>"host:port"</c>. Surrounding whitespace is tolerated.</param>
|
||||
/// <param name="defaultPort">Port adopted when the entry carries no explicit one.</param>
|
||||
/// <param name="endpoint">The parsed endpoint on success; undefined otherwise.</param>
|
||||
/// <param name="error">A human-readable reason on failure; empty on success.</param>
|
||||
/// <returns><see langword="true"/> when the entry parsed.</returns>
|
||||
public static bool TryParse(string entry, int defaultPort, out LdapEndpoint endpoint, out string error)
|
||||
{
|
||||
endpoint = null!;
|
||||
error = "";
|
||||
|
||||
if (string.IsNullOrWhiteSpace(entry))
|
||||
{
|
||||
error = "entry is empty or whitespace";
|
||||
return false;
|
||||
}
|
||||
|
||||
var parts = entry.Trim().Split(':');
|
||||
if (parts.Length > 2)
|
||||
{
|
||||
error = $"entry \"{entry.Trim()}\" contains more than one ':' " +
|
||||
"(IPv6 literals are not supported — use a DNS name)";
|
||||
return false;
|
||||
}
|
||||
|
||||
var host = parts[0].Trim();
|
||||
if (host.Length == 0)
|
||||
{
|
||||
error = $"entry \"{entry.Trim()}\" has an empty host";
|
||||
return false;
|
||||
}
|
||||
|
||||
var port = defaultPort;
|
||||
if (parts.Length == 2 && (!int.TryParse(parts[1].Trim(), out port) || port is < 1 or > 65535))
|
||||
{
|
||||
error = $"entry \"{entry.Trim()}\" has an invalid port (must be 1–65535)";
|
||||
return false;
|
||||
}
|
||||
|
||||
endpoint = new LdapEndpoint(host, port);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
namespace ZB.MOM.WW.Auth.Ldap.Internal;
|
||||
|
||||
/// <summary>
|
||||
/// Reduces a typed login to the bare account name used by <see cref="Abstractions.Ldap.LdapBindMode.User"/>:
|
||||
/// the qualifier is stripped before the name reaches the bind template and the search filter, so audit
|
||||
/// rows never carry <c>DOMAIN\jdoe</c> for one sign-in and <c>jdoe</c> for the next. Case is NOT
|
||||
/// normalised here: the returned username is canonicalised from the directory entry's
|
||||
/// <c>UserNameAttribute</c> value, so <c>JDoe</c> and <c>jdoe</c> also yield one identity; this name is
|
||||
/// only the fallback when the entry has no such value.
|
||||
/// </summary>
|
||||
internal static class LdapUserName
|
||||
{
|
||||
/// <summary>
|
||||
/// Trims <paramref name="input"/> and, when <paramref name="acceptDomainQualified"/>, strips one
|
||||
/// leading <c>DOMAIN\</c> or one trailing <c>@suffix</c>. Returns <see langword="false"/> (with
|
||||
/// <paramref name="name"/> empty) for blank input, for both forms at once, for a repeated
|
||||
/// separator, for an empty side, or for any qualified form when <paramref name="acceptDomainQualified"/>
|
||||
/// is <see langword="false"/>.
|
||||
/// </summary>
|
||||
public static bool TryNormalize(string? input, bool acceptDomainQualified, out string name)
|
||||
{
|
||||
name = "";
|
||||
if (string.IsNullOrWhiteSpace(input))
|
||||
return false;
|
||||
|
||||
var s = input.Trim();
|
||||
var slash = s.IndexOf('\\');
|
||||
var at = s.IndexOf('@');
|
||||
|
||||
if (slash >= 0 || at >= 0)
|
||||
{
|
||||
if (!acceptDomainQualified || (slash >= 0 && at >= 0))
|
||||
return false;
|
||||
|
||||
if (slash >= 0)
|
||||
{
|
||||
if (slash == 0 || s.IndexOf('\\', slash + 1) >= 0)
|
||||
return false;
|
||||
s = s[(slash + 1)..];
|
||||
}
|
||||
else
|
||||
{
|
||||
// Unlike the slash branch (whose extracted suffix is checked for emptiness by the
|
||||
// final length check below), the extracted piece here is the *prefix* — so an empty
|
||||
// domain part (a trailing "@", e.g. "jdoe@") must be rejected explicitly.
|
||||
if (at == s.Length - 1 || s.IndexOf('@', at + 1) >= 0)
|
||||
return false;
|
||||
s = s[..at];
|
||||
}
|
||||
|
||||
s = s.Trim();
|
||||
}
|
||||
|
||||
if (s.Length == 0)
|
||||
return false;
|
||||
|
||||
name = s;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -99,23 +99,107 @@ internal sealed class NovellLdapConnection : ILdapConnection
|
||||
attributes.ToArray(),
|
||||
typesOnly: false);
|
||||
|
||||
var entries = new List<LdapSearchEntry>();
|
||||
while (results.HasMore())
|
||||
return ReadEntries(results);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public LdapSearchEntry? Read(string dn, IReadOnlyList<string> attributes)
|
||||
{
|
||||
var results = _conn.Search(
|
||||
dn,
|
||||
LdapConnection.ScopeBase,
|
||||
"(objectClass=*)",
|
||||
attributes.ToArray(),
|
||||
typesOnly: false);
|
||||
|
||||
try
|
||||
{
|
||||
var entry = results.Next();
|
||||
var attrs = new Dictionary<string, IReadOnlyList<string>>(StringComparer.OrdinalIgnoreCase);
|
||||
var entries = ReadEntries(results);
|
||||
return entries.Count == 0 ? null : entries[0];
|
||||
}
|
||||
catch (LdapException ex) when (ex.ResultCode == LdapException.NoSuchObject)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
foreach (LdapAttribute attr in entry.GetAttributeSet())
|
||||
/// <inheritdoc/>
|
||||
public string WhoAmI()
|
||||
{
|
||||
// ExtendedOperation throws LdapException on a non-success result (e.g. protocol error 2
|
||||
// from a server without RFC 4532 support), which the caller treats as "no answer".
|
||||
var response = _conn.ExtendedOperation(new LdapWhoAmIOperation());
|
||||
if (response is LdapWhoAmIResponse whoAmI)
|
||||
return whoAmI.AuthzId ?? "";
|
||||
|
||||
var value = response.Value;
|
||||
return value is null ? "" : System.Text.Encoding.UTF8.GetString(value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Drains a result set into entries, <b>skipping continuation referrals</b>.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// Active Directory answers any search based at a domain root with one or more
|
||||
/// continuation references (to <c>CN=Configuration</c>, <c>DC=ForestDnsZones</c> and
|
||||
/// friends). With referral following disabled — the default, and what we want, since
|
||||
/// chasing a referral would re-bind somewhere we did not authenticate — Novell surfaces
|
||||
/// each one by throwing <see cref="LdapReferralException"/> from <see cref="ILdapSearchResults.Next"/>.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// A continuation reference is a <em>pointer to another naming context</em>, not an error:
|
||||
/// it says "there may be more results over there", never that this search failed. Letting
|
||||
/// it escape made the whole search stage fail, which <c>LdapAuthService</c> maps to
|
||||
/// <see cref="Abstractions.Ldap.LdapAuthFailure.ServiceAccountBindFailed"/> — so against a
|
||||
/// real AD domain root, every login failed with a system-side error while the directory,
|
||||
/// the credentials and both DCs were perfectly healthy. Verified against
|
||||
/// <c>DC=nam,DC=zimmer,DC=com</c> on 2026-08-12.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// Skipping is the correct behaviour rather than a workaround: the entries we can see are
|
||||
/// exactly the ones in the naming context we bound to, which is the set the caller asked
|
||||
/// about. Internal so the referral handling can be unit-tested through the
|
||||
/// <see cref="ILdapSearchResults"/> seam without a live directory.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
internal static List<LdapSearchEntry> ReadEntries(ILdapSearchResults results)
|
||||
{
|
||||
var entries = new List<LdapSearchEntry>();
|
||||
var referrals = 0;
|
||||
|
||||
while (true)
|
||||
{
|
||||
try
|
||||
{
|
||||
attrs[attr.Name] = attr.StringValueArray.ToList();
|
||||
}
|
||||
if (!results.HasMore()) break;
|
||||
|
||||
entries.Add(new LdapSearchEntry(entry.Dn, attrs));
|
||||
var entry = results.Next();
|
||||
var attrs = new Dictionary<string, IReadOnlyList<string>>(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
foreach (LdapAttribute attr in entry.GetAttributeSet())
|
||||
{
|
||||
attrs[attr.Name] = attr.StringValueArray.ToList();
|
||||
}
|
||||
|
||||
entries.Add(new LdapSearchEntry(entry.Dn, attrs));
|
||||
}
|
||||
catch (LdapException ex) when (ex is LdapReferralException || ex.ResultCode == LdapException.Referral)
|
||||
{
|
||||
// Novell dequeues the reference before throwing, so the enumeration advances and
|
||||
// this terminates. The cap is a belt-and-braces guard: a client that threw without
|
||||
// advancing would otherwise spin forever inside a fail-closed auth path, which is a
|
||||
// far worse failure than under-reporting an implausible number of referrals.
|
||||
if (++referrals > MaxReferrals) break;
|
||||
}
|
||||
}
|
||||
|
||||
return entries;
|
||||
}
|
||||
|
||||
/// <summary>Upper bound on continuation references tolerated in one search — see <see cref="ReadEntries"/>.</summary>
|
||||
private const int MaxReferrals = 1_000;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public void Dispose()
|
||||
{
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Novell.Directory.Ldap;
|
||||
using ZB.MOM.WW.Auth.Abstractions.Ldap;
|
||||
using ZB.MOM.WW.Auth.Ldap.Internal;
|
||||
@@ -11,6 +12,7 @@ namespace ZB.MOM.WW.Auth.Ldap;
|
||||
/// <see cref="ILdapConnection"/> so the logic is unit-testable without a live server.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// Fully fail-closed: authentication never throws to the caller — every error, expected
|
||||
/// or unexpected, is mapped to a structured <see cref="LdapAuthResult.Fail(LdapAuthFailure)"/>.
|
||||
/// A success is only returned for a user that resolved to exactly one entry, whose password
|
||||
@@ -18,11 +20,42 @@ namespace ZB.MOM.WW.Auth.Ldap;
|
||||
/// Service-account bind failures (<see cref="LdapAuthFailure.ServiceAccountBindFailed"/>) are
|
||||
/// kept distinct from end-user bind failures (<see cref="LdapAuthFailure.BadCredentials"/>) so
|
||||
/// a system misconfiguration is not mistaken for bad user input.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// When <see cref="LdapOptions.FallbackServers"/> is non-empty the flow above runs against
|
||||
/// an ordered endpoint list (primary first, then fallbacks in declared order) and moves on
|
||||
/// to the next endpoint ONLY on a system-side failure — connect/TLS, service-account bind,
|
||||
/// or search — i.e. when the endpoint gave no authoritative answer. Any answer from a healthy
|
||||
/// directory (success, or a user-side failure such as
|
||||
/// <see cref="LdapAuthFailure.BadCredentials"/> / <see cref="LdapAuthFailure.UserNotFound"/>)
|
||||
/// is final and is never retried elsewhere: retrying a rejected password against a second DC
|
||||
/// would turn one bad-password event into several, tripping account lockouts. Endpoint
|
||||
/// preference is sticky — the last endpoint that answered is tried first next time — so a
|
||||
/// primary outage costs its connect timeout once, not once per login.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// The service is safe to share (it is registered as a singleton). The sticky index is the
|
||||
/// only mutable state; concurrent logins may race on it, which is benign — the worst outcome
|
||||
/// is one login starting at a stale endpoint and walking on.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// With <c>BindMode = User</c> the service-account bind and the user re-bind are replaced by a
|
||||
/// single bind as the user (<see cref="LdapOptions.UserBindTemplate"/>); see <see cref="CompleteAsUser"/>.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public sealed class LdapAuthService : ILdapAuthService
|
||||
public sealed class LdapAuthService : ILdapAuthService, ILdapGroupLookup
|
||||
{
|
||||
private readonly LdapOptions _options;
|
||||
private readonly ILdapConnectionFactory _connectionFactory;
|
||||
private readonly IReadOnlyList<LdapEndpoint> _endpoints;
|
||||
private readonly ILogger<LdapAuthService>? _logger;
|
||||
|
||||
/// <summary>
|
||||
/// Index into <see cref="_endpoints"/> of the endpoint tried first. Written on any
|
||||
/// authoritative answer from a non-preferred endpoint. Accessed via
|
||||
/// <see cref="Volatile"/> only; benign races are accepted (see the type remarks).
|
||||
/// </summary>
|
||||
private int _preferredIndex;
|
||||
|
||||
/// <summary>
|
||||
/// Production constructor: binds against a live directory via the real
|
||||
@@ -31,9 +64,15 @@ public sealed class LdapAuthService : ILdapAuthService
|
||||
/// <see cref="LdapOptions.AllowInsecure"/> bypass) is carried into the factory so each
|
||||
/// connection is built with it.
|
||||
/// </summary>
|
||||
public LdapAuthService(LdapOptions options)
|
||||
/// <param name="options">The directory connection and search settings.</param>
|
||||
/// <param name="logger">
|
||||
/// Optional. When supplied, endpoint failover is made visible: a Warning per failed
|
||||
/// endpoint hop and an Information line when the sticky preference moves. Omitting it
|
||||
/// (the default) leaves the service silent — hosts without logging still work.
|
||||
/// </param>
|
||||
public LdapAuthService(LdapOptions options, ILogger<LdapAuthService>? logger = null)
|
||||
: this(options, new NovellLdapConnectionFactory(
|
||||
options.AllowInsecure, options.ServerCertificateValidationCallback))
|
||||
options.AllowInsecure, options.ServerCertificateValidationCallback), logger)
|
||||
{
|
||||
}
|
||||
|
||||
@@ -42,10 +81,33 @@ public sealed class LdapAuthService : ILdapAuthService
|
||||
/// so the bind/search logic can be exercised without a live directory. Internal
|
||||
/// because the connection seam is an implementation detail.
|
||||
/// </summary>
|
||||
internal LdapAuthService(LdapOptions options, ILdapConnectionFactory connectionFactory)
|
||||
internal LdapAuthService(
|
||||
LdapOptions options,
|
||||
ILdapConnectionFactory connectionFactory,
|
||||
ILogger<LdapAuthService>? logger = null)
|
||||
{
|
||||
_options = options;
|
||||
_connectionFactory = connectionFactory;
|
||||
_logger = logger;
|
||||
_endpoints = BuildEndpoints(options);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Primary first, then fallbacks in declared order. The validator rejects malformed
|
||||
/// entries at boot; unparseable entries are skipped defensively here so a service
|
||||
/// constructed without options validation degrades to the parseable subset rather
|
||||
/// than throwing from a constructor.
|
||||
/// </summary>
|
||||
private static IReadOnlyList<LdapEndpoint> BuildEndpoints(LdapOptions options)
|
||||
{
|
||||
var endpoints = new List<LdapEndpoint> { new(options.Server, options.Port) };
|
||||
foreach (var entry in options.FallbackServers)
|
||||
{
|
||||
if (LdapEndpointParser.TryParse(entry, options.Port, out var endpoint, out _))
|
||||
endpoints.Add(endpoint);
|
||||
}
|
||||
|
||||
return endpoints;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
@@ -54,7 +116,10 @@ public sealed class LdapAuthService : ILdapAuthService
|
||||
/// bind-then-search-then-bind flow is wrapped so that any error — expected or unexpected —
|
||||
/// is mapped to a structured <see cref="LdapAuthResult.Fail(LdapAuthFailure)"/>. A
|
||||
/// <c>Succeeded == true</c> result is only ever returned when the user resolved to exactly
|
||||
/// one entry, their password verified, AND at least one group was extracted.
|
||||
/// one entry, their password verified, AND at least one group was extracted. With
|
||||
/// <see cref="LdapOptions.FallbackServers"/> configured the flow may run against more than
|
||||
/// one endpoint before answering — see the type-level remarks for the walk and its
|
||||
/// system-side-only failover rule.
|
||||
/// </remarks>
|
||||
public Task<LdapAuthResult> AuthenticateAsync(string username, string password, CancellationToken ct)
|
||||
{
|
||||
@@ -80,112 +145,583 @@ public sealed class LdapAuthService : ILdapAuthService
|
||||
// filter and the returned result (avoids two identities for one person).
|
||||
username = username.Trim();
|
||||
|
||||
// 3b. An empty password must never reach the directory, in EITHER bind mode: AD answers a
|
||||
// simple bind with an empty password as an UNAUTHENTICATED bind and reports success —
|
||||
// the user bind (or the ServiceAccount-mode re-bind as the user's DN) would admit anyone.
|
||||
// Refused here, before any network call, so no consumer depends on its own edge check.
|
||||
if (string.IsNullOrEmpty(password))
|
||||
return LdapAuthResult.Fail(LdapAuthFailure.BadCredentials);
|
||||
|
||||
// 3c. User-bind mode: reduce the name to the bare account name the bind template and the
|
||||
// search filter share. (The returned username is canonicalised from the entry later.)
|
||||
if (_options.BindMode == LdapBindMode.User
|
||||
&& !LdapUserName.TryNormalize(username, _options.AcceptDomainQualifiedNames, out username))
|
||||
{
|
||||
return LdapAuthResult.Fail(LdapAuthFailure.BadCredentials);
|
||||
}
|
||||
|
||||
// 4. Walk the endpoint list, preferred one first. A single-endpoint configuration
|
||||
// (no FallbackServers) collapses to exactly one attempt — unchanged behaviour.
|
||||
// ServiceAccountBindFailed is the (sole) system-side bucket: that endpoint gave no
|
||||
// authoritative answer, so try the next one. Every other outcome — success, or a
|
||||
// user-side failure like UserNotFound/BadCredentials — came from a healthy directory
|
||||
// and is FINAL: re-asking a second DC about a rejected password would multiply one
|
||||
// bad-password event into several against the account lockout policy.
|
||||
// Seeded so an exhausted walk still returns the conservative system-side bucket
|
||||
// even in the impossible case of an empty endpoint list.
|
||||
return WalkEndpoints(
|
||||
endpoint => AuthenticateAgainst(endpoint, username, password),
|
||||
result => result.Failure == LdapAuthFailure.ServiceAccountBindFailed,
|
||||
LdapAuthResult.Fail(LdapAuthFailure.ServiceAccountBindFailed));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Runs <paramref name="attempt"/> against the endpoints, preferred one first, moving on only
|
||||
/// while <paramref name="isSystemSide"/> says the endpoint gave no authoritative answer. The
|
||||
/// first authoritative answer is returned and, if it came from a non-preferred endpoint, makes
|
||||
/// that endpoint the sticky preference. An exhausted walk returns the last system-side result
|
||||
/// (or <paramref name="exhausted"/>) and leaves the preference untouched: a total outage says
|
||||
/// nothing about which endpoint to prefer once one recovers.
|
||||
/// </summary>
|
||||
private T WalkEndpoints<T>(Func<LdapEndpoint, T> attempt, Func<T, bool> isSystemSide, T exhausted)
|
||||
{
|
||||
var preferred = Volatile.Read(ref _preferredIndex);
|
||||
if ((uint)preferred >= (uint)_endpoints.Count)
|
||||
preferred = 0; // defensive: the list is immutable, but never index out of it
|
||||
|
||||
var last = exhausted;
|
||||
foreach (var index in WalkOrder(_endpoints.Count, preferred))
|
||||
{
|
||||
var result = attempt(_endpoints[index]);
|
||||
if (isSystemSide(result))
|
||||
{
|
||||
last = result;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Sticky preference: any authoritative answer proves this endpoint healthy.
|
||||
// Updating only on success would re-pay the dead primary's connect timeout on
|
||||
// every mistyped password (or every refresh of a deleted user) for the whole outage.
|
||||
if (index != preferred)
|
||||
{
|
||||
Volatile.Write(ref _preferredIndex, index);
|
||||
_logger?.LogInformation("LDAP sticky preference moved to {Endpoint}.", _endpoints[index]);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
return last;
|
||||
}
|
||||
|
||||
/// <summary>Preferred endpoint first, then every other endpoint in declared order.</summary>
|
||||
private static IEnumerable<int> WalkOrder(int count, int preferred)
|
||||
{
|
||||
yield return preferred;
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
if (i != preferred)
|
||||
yield return i;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Runs one full bind-then-search-then-bind attempt against a single endpoint on a fresh
|
||||
/// connection. The fail-closed contract holds per attempt: this never throws, and it
|
||||
/// returns <see cref="LdapAuthFailure.ServiceAccountBindFailed"/> for — and only for —
|
||||
/// system-side faults, which is what the caller reads as "no authoritative answer, try
|
||||
/// the next endpoint".
|
||||
/// </summary>
|
||||
private LdapAuthResult AuthenticateAgainst(LdapEndpoint endpoint, string username, string password)
|
||||
{
|
||||
// The whole flow runs inside an outer fail-closed guard: a StageFailure carries an
|
||||
// already-mapped failure out of a stage, and any OTHER unexpected exception defaults to
|
||||
// the most conservative system-side bucket. Either way the caller gets a structured result.
|
||||
try
|
||||
{
|
||||
// A fresh connection per attempt: a Novell connection that has failed to connect
|
||||
// or bind is not safely reusable against another host.
|
||||
using var conn = _connectionFactory.Create();
|
||||
|
||||
// 4. Open the connection (transport/TLS handling lives in the adapter). The
|
||||
// 5. Open the connection (transport/TLS handling lives in the adapter). The
|
||||
// per-operation timeout (ConnectionTimeoutMs) is applied by the adapter here.
|
||||
// A failure to connect/upgrade means the directory is unreachable — a
|
||||
// system-side fault, not the user's, so map it to ServiceAccountBindFailed.
|
||||
// A failure to connect/upgrade means this endpoint is unreachable — a
|
||||
// system-side fault, not the user's, so map it to ServiceAccountBindFailed
|
||||
// and let the caller try the next endpoint.
|
||||
// NOTE: the LdapAuthFailure enum has no dedicated DirectoryUnavailable value;
|
||||
// ServiceAccountBindFailed is the closest system-side bucket. A future
|
||||
// Abstractions change could add DirectoryUnavailable to disambiguate.
|
||||
try
|
||||
{
|
||||
conn.Connect(
|
||||
_options.Server,
|
||||
_options.Port,
|
||||
_options.Transport,
|
||||
_options.AllowInsecure,
|
||||
_options.ConnectionTimeoutMs,
|
||||
_options.ServerCertificateValidationCallback);
|
||||
}
|
||||
catch (LdapException)
|
||||
{
|
||||
throw new StageFailure(LdapAuthFailure.ServiceAccountBindFailed);
|
||||
}
|
||||
ConnectTo(conn, endpoint);
|
||||
|
||||
return _options.BindMode == LdapBindMode.User
|
||||
? CompleteAsUser(conn, username, password)
|
||||
: CompleteWithServiceAccount(conn, username, password);
|
||||
}
|
||||
catch (StageFailure stage)
|
||||
{
|
||||
// A stage mapped its own failure; surface it as a structured result. Log at Warning
|
||||
// so a silent failover — the failure mode this feature exists to survive — is
|
||||
// visible in the host's log rather than only in a latency graph.
|
||||
_logger?.LogWarning(
|
||||
"LDAP endpoint {Endpoint} failed system-side at {Stage}; treating as no answer.",
|
||||
endpoint, stage.Stage);
|
||||
return LdapAuthResult.Fail(stage.Failure);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// Belt-and-braces: ANY unexpected exception fails closed to the most conservative
|
||||
// system-side bucket rather than propagating to the caller.
|
||||
_logger?.LogWarning(ex, "LDAP endpoint {Endpoint} failed system-side with an unexpected error.", endpoint);
|
||||
return LdapAuthResult.Fail(LdapAuthFailure.ServiceAccountBindFailed);
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
/// <remarks>
|
||||
/// Fail-closed like <see cref="AuthenticateAsync"/>: never throws to the caller (cancellation is
|
||||
/// observed at entry only). Uses the service account in every case, so it is
|
||||
/// <see cref="LdapGroupLookupStatus.NotSupported"/> in <see cref="LdapBindMode.User"/> mode. The
|
||||
/// name is normalised exactly as <see cref="AuthenticateAsync"/> normalises it in
|
||||
/// <see cref="LdapBindMode.ServiceAccount"/> mode (trimmed, otherwise verbatim), so a name a session
|
||||
/// was issued for resolves to the same entry. The endpoint walk, sticky preference, timeouts and
|
||||
/// TLS policy are shared with authentication; only a system-side failure moves to the next
|
||||
/// endpoint. Credentials are never logged.
|
||||
/// </remarks>
|
||||
public Task<LdapGroupLookupResult> GetUserGroupsAsync(string username, CancellationToken ct)
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
return Task.FromResult(LookupGroups(username));
|
||||
}
|
||||
|
||||
private LdapGroupLookupResult LookupGroups(string username)
|
||||
{
|
||||
if (!_options.Enabled)
|
||||
return LdapGroupLookupResult.Of(LdapGroupLookupStatus.ProviderDisabled);
|
||||
|
||||
// User mode has no service account to search with, and a blank service-account DN would bind
|
||||
// anonymously — the validator refuses that at boot; refuse it here too for unvalidated hosts.
|
||||
if (_options.BindMode == LdapBindMode.User || string.IsNullOrWhiteSpace(_options.ServiceAccountDn))
|
||||
return LdapGroupLookupResult.Of(LdapGroupLookupStatus.NotSupported);
|
||||
|
||||
if (string.IsNullOrWhiteSpace(username))
|
||||
return LdapGroupLookupResult.Of(LdapGroupLookupStatus.UserNotFound);
|
||||
|
||||
username = username.Trim();
|
||||
|
||||
return WalkEndpoints(
|
||||
endpoint => LookupAgainst(endpoint, username),
|
||||
result => result.Status == LdapGroupLookupStatus.DirectoryUnavailable,
|
||||
LdapGroupLookupResult.Of(LdapGroupLookupStatus.DirectoryUnavailable));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One lookup attempt against one endpoint on a fresh connection: connect, service-account bind,
|
||||
/// search. A fault in any of those is <see cref="LdapGroupLookupStatus.DirectoryUnavailable"/> (try
|
||||
/// the next endpoint); every other status is the directory's answer.
|
||||
/// </summary>
|
||||
private LdapGroupLookupResult LookupAgainst(LdapEndpoint endpoint, string username)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var conn = _connectionFactory.Create();
|
||||
ConnectTo(conn, endpoint);
|
||||
|
||||
// 5. Service-account bind so we can search for the user's DN. A bind failure
|
||||
// here is a service-account misconfiguration — DISTINCT from a user-credential
|
||||
// failure — so it maps to ServiceAccountBindFailed.
|
||||
try
|
||||
{
|
||||
conn.Bind(_options.ServiceAccountDn, _options.ServiceAccountPassword);
|
||||
}
|
||||
catch (LdapException)
|
||||
{
|
||||
throw new StageFailure(LdapAuthFailure.ServiceAccountBindFailed);
|
||||
throw new StageFailure(LdapAuthFailure.ServiceAccountBindFailed, "service-bind");
|
||||
}
|
||||
|
||||
// 6. Search for the user entry by the configured username attribute. A search
|
||||
// failure is infrastructure (directory unreachable / unhealthy) — system-side.
|
||||
// NOTE: same enum limitation as Connect above; ServiceAccountBindFailed is the
|
||||
// closest system-side bucket until a DirectoryUnavailable value exists.
|
||||
IReadOnlyList<LdapSearchEntry> entries;
|
||||
try
|
||||
{
|
||||
var filter = $"({_options.UserNameAttribute}={LdapEscaping.Filter(username)})";
|
||||
entries = conn.Search(_options.SearchBase, filter, BuildSearchAttributes());
|
||||
}
|
||||
catch (LdapException)
|
||||
{
|
||||
throw new StageFailure(LdapAuthFailure.ServiceAccountBindFailed);
|
||||
}
|
||||
|
||||
// 7. Require exactly one match. Zero -> UserNotFound; two or more -> AmbiguousUser.
|
||||
// We never attempt a user bind against an ambiguous DN.
|
||||
var entries = SearchUser(conn, username, UserAccountControlAttribute);
|
||||
if (entries.Count == 0)
|
||||
return LdapAuthResult.Fail(LdapAuthFailure.UserNotFound);
|
||||
return LdapGroupLookupResult.Of(LdapGroupLookupStatus.UserNotFound);
|
||||
if (entries.Count >= 2)
|
||||
return LdapAuthResult.Fail(LdapAuthFailure.AmbiguousUser);
|
||||
return LdapGroupLookupResult.Of(LdapGroupLookupStatus.AmbiguousUser);
|
||||
|
||||
var entry = entries[0];
|
||||
if (IsAccountDisabled(entry))
|
||||
return LdapGroupLookupResult.Of(LdapGroupLookupStatus.UserDisabled);
|
||||
|
||||
// 8. User bind: re-bind as the resolved DN to verify the password. A bind failure
|
||||
// here is the end user's bad credentials.
|
||||
try
|
||||
{
|
||||
conn.Bind(entry.Dn, password);
|
||||
}
|
||||
catch (LdapException)
|
||||
{
|
||||
throw new StageFailure(LdapAuthFailure.BadCredentials);
|
||||
}
|
||||
|
||||
// 9. Group extraction. Fail closed: an empty/missing group set, or any error while
|
||||
// extracting groups, is a GroupLookupFailed — never a zero-group success.
|
||||
IReadOnlyList<string> groups;
|
||||
try
|
||||
{
|
||||
groups = ExtractGroups(entry);
|
||||
}
|
||||
catch
|
||||
{
|
||||
throw new StageFailure(LdapAuthFailure.GroupLookupFailed);
|
||||
}
|
||||
|
||||
if (groups.Count == 0)
|
||||
return LdapAuthResult.Fail(LdapAuthFailure.GroupLookupFailed);
|
||||
|
||||
// 10. Success — and only here, with a verified password and >= 1 group.
|
||||
var displayName = ExtractDisplayName(entry, username);
|
||||
return LdapAuthResult.Success(username, displayName, groups);
|
||||
var canonical = ExtractUserName(entry, username);
|
||||
return LdapGroupLookupResult.Found(canonical, ExtractDisplayName(entry, canonical), ExtractGroups(entry));
|
||||
}
|
||||
catch (StageFailure stage)
|
||||
{
|
||||
// A stage mapped its own failure; surface it as a structured result.
|
||||
return LdapAuthResult.Fail(stage.Failure);
|
||||
_logger?.LogWarning(
|
||||
"LDAP endpoint {Endpoint} failed system-side at {Stage} during a group lookup; treating as no answer.",
|
||||
endpoint, stage.Stage);
|
||||
return LdapGroupLookupResult.Of(LdapGroupLookupStatus.DirectoryUnavailable);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger?.LogWarning(ex, "LDAP endpoint {Endpoint} failed system-side with an unexpected error during a group lookup.", endpoint);
|
||||
return LdapGroupLookupResult.Of(LdapGroupLookupStatus.DirectoryUnavailable);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>AD's account-flags attribute; absent on directories that do not model it (GLAuth, OpenLDAP).</summary>
|
||||
private const string UserAccountControlAttribute = "userAccountControl";
|
||||
|
||||
/// <summary>AD <c>userAccountControl</c> ACCOUNTDISABLE flag.</summary>
|
||||
private const int AccountDisableFlag = 0x2;
|
||||
|
||||
/// <summary>
|
||||
/// <see langword="true"/> when the entry carries AD's <c>userAccountControl</c> with ACCOUNTDISABLE set.
|
||||
/// An absent or unparseable value is "not disabled": directories without the attribute have no such
|
||||
/// state, and a password bind is what refuses a disabled account at sign-in anyway.
|
||||
/// </summary>
|
||||
private static bool IsAccountDisabled(LdapSearchEntry entry)
|
||||
=> entry.Attributes.TryGetValue(UserAccountControlAttribute, out var values)
|
||||
&& values.Count > 0
|
||||
&& int.TryParse(values[0], System.Globalization.NumberStyles.Integer,
|
||||
System.Globalization.CultureInfo.InvariantCulture, out var flags)
|
||||
&& (flags & AccountDisableFlag) != 0;
|
||||
|
||||
/// <summary>Opens the connection; a connect/TLS fault means this endpoint is unreachable (system-side).</summary>
|
||||
private void ConnectTo(ZB.MOM.WW.Auth.Ldap.Internal.ILdapConnection conn, LdapEndpoint endpoint)
|
||||
{
|
||||
try
|
||||
{
|
||||
conn.Connect(
|
||||
endpoint.Host,
|
||||
endpoint.Port,
|
||||
_options.Transport,
|
||||
_options.AllowInsecure,
|
||||
_options.ConnectionTimeoutMs,
|
||||
_options.ServerCertificateValidationCallback);
|
||||
}
|
||||
catch (LdapException)
|
||||
{
|
||||
throw new StageFailure(LdapAuthFailure.ServiceAccountBindFailed, "connect");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Steps 6–11 of the 0.3.0 flow: service-account bind, search, user re-bind, groups.</summary>
|
||||
private LdapAuthResult CompleteWithServiceAccount(ZB.MOM.WW.Auth.Ldap.Internal.ILdapConnection conn, string username, string password)
|
||||
{
|
||||
// 6. Service-account bind so we can search for the user's DN. A bind failure here is a
|
||||
// service-account misconfiguration — DISTINCT from a user-credential failure — so it
|
||||
// maps to ServiceAccountBindFailed.
|
||||
try
|
||||
{
|
||||
conn.Bind(_options.ServiceAccountDn, _options.ServiceAccountPassword);
|
||||
}
|
||||
catch (LdapException)
|
||||
{
|
||||
throw new StageFailure(LdapAuthFailure.ServiceAccountBindFailed, "service-bind");
|
||||
}
|
||||
|
||||
// 7–8. Require exactly one match. Zero -> UserNotFound; two or more -> AmbiguousUser.
|
||||
// Both are authoritative answers from a healthy directory, so they end the walk.
|
||||
// We never attempt a user bind against an ambiguous DN.
|
||||
var entries = SearchUser(conn, username);
|
||||
if (entries.Count == 0)
|
||||
return LdapAuthResult.Fail(LdapAuthFailure.UserNotFound);
|
||||
if (entries.Count >= 2)
|
||||
return LdapAuthResult.Fail(LdapAuthFailure.AmbiguousUser);
|
||||
|
||||
var entry = entries[0];
|
||||
|
||||
// 9. User bind: re-bind as the resolved DN to verify the password. A bind failure here is
|
||||
// the end user's bad credentials — the directory answered, so this is returned directly
|
||||
// and never retried against another endpoint.
|
||||
try
|
||||
{
|
||||
conn.Bind(entry.Dn, password);
|
||||
}
|
||||
catch (LdapException)
|
||||
{
|
||||
return LdapAuthResult.Fail(LdapAuthFailure.BadCredentials);
|
||||
}
|
||||
|
||||
return SucceedFromEntry(entry, username);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="LdapBindMode.User"/>: the user's own bind is the authentication; the same
|
||||
/// connection then reads their entry. Only result 49 (invalid credentials — AD's answer for a
|
||||
/// wrong password AND for unknown, locked, disabled or expired accounts) is the user's failure
|
||||
/// and final; any other bind error means this endpoint gave no answer, so the walk moves on.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The bind name (from <see cref="LdapOptions.UserBindTemplate"/>) and the search filter
|
||||
/// (<see cref="LdapOptions.UserNameAttribute"/>) are resolved by two different directory
|
||||
/// lookups, so they can name two different accounts — e.g. a UPN bind that AD resolves to the
|
||||
/// account whose explicit <c>userPrincipalName</c> is <c>jsmith@corp</c> while the search finds
|
||||
/// the account whose <c>sAMAccountName</c> is <c>jsmith</c> (Auth-007). The entry is therefore
|
||||
/// only accepted when it is provably the account that bound: see <see cref="ResolveBoundIdentity"/>
|
||||
/// and <see cref="IsBoundAccount"/>. Anything else is <see cref="LdapAuthFailure.GroupLookupFailed"/>.
|
||||
/// </remarks>
|
||||
private LdapAuthResult CompleteAsUser(ZB.MOM.WW.Auth.Ldap.Internal.ILdapConnection conn, string username, string password)
|
||||
{
|
||||
var dnTemplate = IsDnTemplate(_options.UserBindTemplate);
|
||||
|
||||
// A DN template splices the name into a DN, so the name is RFC 4514-escaped: unescaped, a
|
||||
// name like "x,ou=other" would bind a DN of the caller's choosing.
|
||||
var bindName = _options.UserBindTemplate.Replace(
|
||||
"{0}", dnTemplate ? LdapEscaping.Dn(username) : username, StringComparison.Ordinal);
|
||||
try
|
||||
{
|
||||
conn.Bind(bindName, password);
|
||||
}
|
||||
catch (LdapException ex) when (ex.ResultCode == LdapException.InvalidCredentials)
|
||||
{
|
||||
return LdapAuthResult.Fail(LdapAuthFailure.BadCredentials);
|
||||
}
|
||||
catch (LdapException)
|
||||
{
|
||||
throw new StageFailure(LdapAuthFailure.ServiceAccountBindFailed, "user-bind");
|
||||
}
|
||||
|
||||
var bound = ResolveBoundIdentity(conn, bindName, dnTemplate);
|
||||
if (bound is null)
|
||||
{
|
||||
_logger?.LogWarning(
|
||||
"LDAP user bind succeeded but the bound identity could not be established (no RFC 4532 " +
|
||||
"Who-am-I answer and UserBindTemplate is not a DN); refusing the sign-in.");
|
||||
return LdapAuthResult.Fail(LdapAuthFailure.GroupLookupFailed);
|
||||
}
|
||||
|
||||
// After a good bind, anything but exactly one readable entry is a failure to establish the
|
||||
// user's groups — never a success, and never UserNotFound (the directory just accepted them).
|
||||
var entries = SearchUser(conn, username, bound.AccountName is null ? null : SamAccountNameAttribute);
|
||||
if (entries.Count != 1)
|
||||
return LdapAuthResult.Fail(LdapAuthFailure.GroupLookupFailed);
|
||||
|
||||
if (!IsBoundAccount(conn, entries[0], bound, username))
|
||||
{
|
||||
_logger?.LogWarning(
|
||||
"LDAP user bind authenticated {BoundIdentity} but the entry found for the typed name is " +
|
||||
"{EntryDn}; refusing the sign-in rather than returning another account's groups.",
|
||||
bound, entries[0].Dn);
|
||||
return LdapAuthResult.Fail(LdapAuthFailure.GroupLookupFailed);
|
||||
}
|
||||
|
||||
return SucceedFromEntry(entries[0], username);
|
||||
}
|
||||
|
||||
/// <summary>The AD attribute that an RFC 4532 <c>u:DOMAIN\name</c> authorization identity names.</summary>
|
||||
private const string SamAccountNameAttribute = "sAMAccountName";
|
||||
|
||||
/// <summary>AD's constructed attribute holding a principal's <c>DOMAIN\name</c>, derived from its <c>objectSid</c>.</summary>
|
||||
private const string PrincipalNameAttribute = "msDS-PrincipalName";
|
||||
|
||||
/// <summary>
|
||||
/// The account a user bind authenticated: either its DN, or (AD's Who-am-I form) its
|
||||
/// <c>sAMAccountName</c> plus, when the answer carried one, its NetBIOS <see cref="Domain"/>.
|
||||
/// Exactly one of <see cref="Dn"/> / <see cref="AccountName"/> is set.
|
||||
/// </summary>
|
||||
private sealed record BoundIdentity(string? Dn, string? AccountName, string? Domain = null)
|
||||
{
|
||||
public override string ToString() =>
|
||||
Dn is not null ? $"dn:{Dn}" : Domain is null ? $"u:{AccountName}" : $@"u:{Domain}\{AccountName}";
|
||||
}
|
||||
|
||||
/// <summary>A template is a DN template when it contains an attribute assertion (<c>=</c>); UPN and down-level forms never do.</summary>
|
||||
private static bool IsDnTemplate(string template) => template.Contains('=', StringComparison.Ordinal);
|
||||
|
||||
/// <summary>
|
||||
/// Establishes which account the bind authenticated. The directory's own answer wins: RFC 4532
|
||||
/// Who-am-I (<c>dn:<dn></c>, or AD's <c>u:DOMAIN\name</c>). Without one — the server does
|
||||
/// not support the operation (GLAuth), or answers empty — a DN template is still provable,
|
||||
/// because the directory accepted exactly that DN; a UPN or down-level template is not, so the
|
||||
/// result is <see langword="null"/> and the sign-in fails closed.
|
||||
/// </summary>
|
||||
private static BoundIdentity? ResolveBoundIdentity(
|
||||
ZB.MOM.WW.Auth.Ldap.Internal.ILdapConnection conn, string bindName, bool dnTemplate)
|
||||
{
|
||||
string authzId;
|
||||
try
|
||||
{
|
||||
authzId = conn.WhoAmI()?.Trim() ?? "";
|
||||
}
|
||||
catch (LdapException)
|
||||
{
|
||||
// Unsupported (protocol error / unwilling) or a transport fault. Either way there is no
|
||||
// answer; a dead connection will fail the following search, which is system-side.
|
||||
authzId = "";
|
||||
}
|
||||
|
||||
if (authzId.StartsWith("dn:", StringComparison.OrdinalIgnoreCase) && authzId.Length > 3)
|
||||
return new BoundIdentity(authzId[3..].Trim(), null);
|
||||
|
||||
if (authzId.StartsWith("u:", StringComparison.OrdinalIgnoreCase) && authzId.Length > 2)
|
||||
{
|
||||
var account = authzId[2..].Trim();
|
||||
string? domain = null;
|
||||
var slash = account.LastIndexOf('\\');
|
||||
if (slash >= 0)
|
||||
{
|
||||
domain = account[..slash].Trim();
|
||||
account = account[(slash + 1)..];
|
||||
}
|
||||
if (account.Length > 0)
|
||||
return new BoundIdentity(null, account, string.IsNullOrEmpty(domain) ? null : domain);
|
||||
}
|
||||
|
||||
return dnTemplate ? new BoundIdentity(bindName, null) : null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <see langword="true"/> only when <paramref name="entry"/> is the account that bound: its DN
|
||||
/// equals the bound DN (RFC 4514 <c>distinguishedNameMatch</c>, case- and space-insensitive), or
|
||||
/// — for AD's <c>u:DOMAIN\name</c> answer — it is provably that domain's account of that name
|
||||
/// (see <see cref="IsBoundAdAccount"/>).
|
||||
/// </summary>
|
||||
private bool IsBoundAccount(
|
||||
ZB.MOM.WW.Auth.Ldap.Internal.ILdapConnection conn, LdapSearchEntry entry, BoundIdentity bound, string username)
|
||||
{
|
||||
if (bound.Dn is not null)
|
||||
{
|
||||
try
|
||||
{
|
||||
return LdapDn.Equals(entry.Dn, bound.Dn);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
// An unparseable DN on either side cannot be proven equal.
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return IsBoundAdAccount(conn, entry, bound, username);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The <c>u:DOMAIN\name</c> case. A matching <c>sAMAccountName</c> is necessary but not enough:
|
||||
/// <c>sAMAccountName</c> is unique per DOMAIN, so a search base that spans a forest (a Global
|
||||
/// Catalog) can find another domain's account of the same name and hand back its groups
|
||||
/// (scadaproj#50). In order of strength:
|
||||
/// <list type="number">
|
||||
/// <item>Where the directory offers AD's constructed <c>msDS-PrincipalName</c> for the entry —
|
||||
/// its <c>DOMAIN\name</c>, computed from the entry's <c>objectSid</c> — it must equal the
|
||||
/// Who-am-I answer, domain included. That is the decisive, SID-anchored check. (The bound
|
||||
/// account's own <c>objectSid</c> cannot be compared directly: Who-am-I does not return it.)</item>
|
||||
/// <item>Otherwise the name must have exactly ONE holder under <see cref="LdapOptions.SearchBase"/>,
|
||||
/// and that holder's DN must be the entry's: two holders mean which one bound cannot be proven,
|
||||
/// so the sign-in fails closed. The user search already proves this when it was itself
|
||||
/// <c>(sAMAccountName=<the bound name>)</c> and found one entry, so no second search is
|
||||
/// made then. Residual: a search base that covers another domain's holder but NOT the bound
|
||||
/// account's own domain is not detectable without <c>msDS-PrincipalName</c>.</item>
|
||||
/// </list>
|
||||
/// </summary>
|
||||
private bool IsBoundAdAccount(
|
||||
ZB.MOM.WW.Auth.Ldap.Internal.ILdapConnection conn, LdapSearchEntry entry, BoundIdentity bound, string username)
|
||||
{
|
||||
if (!entry.Attributes.TryGetValue(SamAccountNameAttribute, out var values)
|
||||
|| values.Count != 1
|
||||
|| !string.Equals(values[0], bound.AccountName, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (bound.Domain is not null && ReadPrincipalName(conn, entry.Dn) is { } principal)
|
||||
return string.Equals(principal, $@"{bound.Domain}\{bound.AccountName}", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
var searchedOnTheBoundName =
|
||||
string.Equals(_options.UserNameAttribute, SamAccountNameAttribute, StringComparison.OrdinalIgnoreCase)
|
||||
&& string.Equals(username, bound.AccountName, StringComparison.OrdinalIgnoreCase);
|
||||
if (searchedOnTheBoundName)
|
||||
return true;
|
||||
|
||||
IReadOnlyList<LdapSearchEntry> holders;
|
||||
try
|
||||
{
|
||||
holders = conn.Search(
|
||||
_options.SearchBase,
|
||||
$"({SamAccountNameAttribute}={LdapEscaping.Filter(bound.AccountName!)})",
|
||||
new[] { SamAccountNameAttribute });
|
||||
}
|
||||
catch (LdapException)
|
||||
{
|
||||
// Same bucket as the user search: the directory could not answer, which is system-side.
|
||||
throw new StageFailure(LdapAuthFailure.ServiceAccountBindFailed, "search");
|
||||
}
|
||||
|
||||
if (holders.Count != 1)
|
||||
return false;
|
||||
|
||||
try
|
||||
{
|
||||
return LdapDn.Equals(holders[0].Dn, entry.Dn);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The entry's <c>msDS-PrincipalName</c> when the directory computes one in <c>DOMAIN\name</c>
|
||||
/// form; <see langword="null"/> when it is absent, unreadable, or a SID string (AD's form for a
|
||||
/// principal it cannot name) — all of which mean "not available", never "mismatch".
|
||||
/// </summary>
|
||||
private static string? ReadPrincipalName(ZB.MOM.WW.Auth.Ldap.Internal.ILdapConnection conn, string dn)
|
||||
{
|
||||
try
|
||||
{
|
||||
var read = conn.Read(dn, new[] { PrincipalNameAttribute });
|
||||
if (read is not null
|
||||
&& read.Attributes.TryGetValue(PrincipalNameAttribute, out var values)
|
||||
&& values.Count == 1
|
||||
&& values[0].Contains('\\', StringComparison.Ordinal))
|
||||
{
|
||||
return values[0].Trim();
|
||||
}
|
||||
}
|
||||
catch (LdapException)
|
||||
{
|
||||
// Not offered, or not readable by this account: fall back to the uniqueness check.
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>Step 7: search for the user entry; a search fault is system-side.</summary>
|
||||
private IReadOnlyList<LdapSearchEntry> SearchUser(
|
||||
ZB.MOM.WW.Auth.Ldap.Internal.ILdapConnection conn, string username, string? extraAttribute = null)
|
||||
{
|
||||
// A search failure is infrastructure (directory unreachable / unhealthy) — system-side.
|
||||
// NOTE: the LdapAuthFailure enum has no DirectoryUnavailable value, so a failed search maps
|
||||
// to ServiceAccountBindFailed, the closest system-side bucket (same limitation as
|
||||
// Connect), until a DirectoryUnavailable value exists.
|
||||
try
|
||||
{
|
||||
var filter = $"({_options.UserNameAttribute}={LdapEscaping.Filter(username)})";
|
||||
return conn.Search(_options.SearchBase, filter, BuildSearchAttributes(extraAttribute));
|
||||
}
|
||||
catch (LdapException)
|
||||
{
|
||||
throw new StageFailure(LdapAuthFailure.ServiceAccountBindFailed, "search");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Steps 10–11: fail-closed group extraction, then success. The returned username is the
|
||||
/// entry's own <see cref="LdapOptions.UserNameAttribute"/> value (the directory's spelling), so
|
||||
/// <c>JDoe</c> and <c>jdoe</c> sign in as one identity; the typed (normalised) name is the
|
||||
/// fallback when the entry carries no such value.
|
||||
/// </summary>
|
||||
private LdapAuthResult SucceedFromEntry(LdapSearchEntry entry, string username)
|
||||
{
|
||||
IReadOnlyList<string> groups;
|
||||
try
|
||||
{
|
||||
groups = ExtractGroups(entry);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Belt-and-braces: ANY unexpected exception fails closed to the most conservative
|
||||
// system-side bucket rather than propagating to the caller.
|
||||
return LdapAuthResult.Fail(LdapAuthFailure.ServiceAccountBindFailed);
|
||||
return LdapAuthResult.Fail(LdapAuthFailure.GroupLookupFailed);
|
||||
}
|
||||
|
||||
if (groups.Count == 0)
|
||||
return LdapAuthResult.Fail(LdapAuthFailure.GroupLookupFailed);
|
||||
|
||||
var canonical = ExtractUserName(entry, username);
|
||||
return LdapAuthResult.Success(canonical, ExtractDisplayName(entry, canonical), groups);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -194,22 +730,61 @@ public sealed class LdapAuthService : ILdapAuthService
|
||||
/// </summary>
|
||||
private sealed class StageFailure : Exception
|
||||
{
|
||||
public StageFailure(LdapAuthFailure failure) => Failure = failure;
|
||||
public StageFailure(LdapAuthFailure failure, string stage)
|
||||
{
|
||||
Failure = failure;
|
||||
Stage = stage;
|
||||
}
|
||||
|
||||
public LdapAuthFailure Failure { get; }
|
||||
|
||||
/// <summary>Which stage faulted (<c>connect</c> / <c>service-bind</c> / <c>user-bind</c> / <c>search</c>), for diagnostics.</summary>
|
||||
public string Stage { get; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the distinct attribute list requested from the directory. The display-name
|
||||
/// and group attributes are de-duplicated so we never request the same attribute twice
|
||||
/// when an operator configures them to the same value.
|
||||
/// Builds the distinct attribute list requested from the directory: display name, groups,
|
||||
/// the username attribute (read back as the canonical username) and, when the user-bind
|
||||
/// identity check needs it, <paramref name="extraAttribute"/>. They are de-duplicated,
|
||||
/// case-insensitively, so we never request the same attribute twice when an operator
|
||||
/// configures two of them to the same value.
|
||||
/// </summary>
|
||||
private IReadOnlyList<string> BuildSearchAttributes()
|
||||
private IReadOnlyList<string> BuildSearchAttributes(string? extraAttribute = null)
|
||||
{
|
||||
if (string.Equals(_options.DisplayNameAttribute, _options.GroupAttribute, StringComparison.OrdinalIgnoreCase))
|
||||
return new[] { _options.DisplayNameAttribute };
|
||||
var attributes = new List<string>(4);
|
||||
foreach (var name in new[] { _options.DisplayNameAttribute, _options.GroupAttribute, _options.UserNameAttribute, extraAttribute })
|
||||
{
|
||||
if (name is not null && !attributes.Contains(name, StringComparer.OrdinalIgnoreCase))
|
||||
attributes.Add(name);
|
||||
}
|
||||
|
||||
return new[] { _options.DisplayNameAttribute, _options.GroupAttribute };
|
||||
return attributes;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the directory's spelling of the name the user matched on: the value of the configured
|
||||
/// username attribute that equals the typed (already normalised) name ignoring case. Only when no
|
||||
/// value does is the first non-blank value used, and only when there is none the typed name.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The attribute can be multi-valued — the default <c>cn</c> is, and OpenLDAP / 389-DS entries
|
||||
/// routinely carry both <c>cn: John Smith</c> and <c>cn: jsmith</c>. 0.4.1 returned whichever
|
||||
/// value the server listed first, so <c>jsmith</c> could sign in as <c>John Smith</c> depending on
|
||||
/// attribute ordering (Auth-009). Matching ordinal-ignore-case still canonicalises case
|
||||
/// (<c>JSMITH</c> → <c>jsmith</c>), which is what 0.4.1 set out to do.
|
||||
/// </remarks>
|
||||
private string ExtractUserName(LdapSearchEntry entry, string username)
|
||||
{
|
||||
if (!entry.Attributes.TryGetValue(_options.UserNameAttribute, out var values) || values.Count == 0)
|
||||
return username;
|
||||
|
||||
foreach (var value in values)
|
||||
{
|
||||
if (string.Equals(value, username, StringComparison.OrdinalIgnoreCase))
|
||||
return value;
|
||||
}
|
||||
|
||||
return string.IsNullOrWhiteSpace(values[0]) ? username : values[0];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -10,7 +10,7 @@ namespace ZB.MOM.WW.Auth.Ldap;
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Validation is skipped entirely when <see cref="LdapOptions.Enabled"/> is <c>false</c>
|
||||
/// (a disabled provider's connection fields are inert). When enabled, four conditions
|
||||
/// (a disabled provider's connection fields are inert). When enabled, five conditions
|
||||
/// are enforced:
|
||||
/// <list type="bullet">
|
||||
/// <item>plaintext transport (<see cref="LdapTransport.None"/>) is rejected unless
|
||||
@@ -18,8 +18,13 @@ namespace ZB.MOM.WW.Auth.Ldap;
|
||||
/// <item><see cref="LdapOptions.Server"/> must be specified (no sane default host);</item>
|
||||
/// <item><see cref="LdapOptions.SearchBase"/> must be specified (the DN root every
|
||||
/// search runs against);</item>
|
||||
/// <item><see cref="LdapOptions.ServiceAccountDn"/> must be specified — an empty value
|
||||
/// would bind anonymously, defeating the search-then-bind authentication flow.</item>
|
||||
/// <item>in <see cref="LdapBindMode.ServiceAccount"/> mode <see cref="LdapOptions.ServiceAccountDn"/>
|
||||
/// must be specified — an empty value would bind anonymously, defeating the search-then-bind
|
||||
/// authentication flow; in <see cref="LdapBindMode.User"/> mode <see cref="LdapOptions.UserBindTemplate"/>
|
||||
/// must contain <c>{0}</c> exactly once instead;</item>
|
||||
/// <item>every <see cref="LdapOptions.FallbackServers"/> entry must parse as
|
||||
/// <c>"host"</c> or <c>"host:port"</c> — a typo'd backup DC must not lie dormant
|
||||
/// until the primary outage it exists to survive.</item>
|
||||
/// </list>
|
||||
/// </remarks>
|
||||
public sealed class LdapOptionsValidator : IValidateOptions<LdapOptions>
|
||||
@@ -60,7 +65,20 @@ public sealed class LdapOptionsValidator : IValidateOptions<LdapOptions>
|
||||
"set it to the search-base DN (e.g. \"dc=example,dc=com\").");
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(options.ServiceAccountDn))
|
||||
if (options.BindMode == LdapBindMode.User)
|
||||
{
|
||||
// User mode binds as the signing-in user, so there is no service account to require.
|
||||
// The template is the bind identity: without exactly one {0} every login would bind as
|
||||
// the same fixed name (or as a name with the user spliced in twice).
|
||||
if (CountPlaceholders(options.UserBindTemplate) != 1)
|
||||
{
|
||||
return ValidateOptionsResult.Fail(
|
||||
$"{nameof(LdapOptions.UserBindTemplate)} must contain {{0}} exactly once when " +
|
||||
$"{nameof(LdapOptions.BindMode)} is {nameof(LdapBindMode.User)} — e.g. \"EXAMPLE\\{{0}}\" " +
|
||||
"(preferred) or \"{0}@example.com\".");
|
||||
}
|
||||
}
|
||||
else if (string.IsNullOrWhiteSpace(options.ServiceAccountDn))
|
||||
{
|
||||
return ValidateOptionsResult.Fail(
|
||||
$"{nameof(LdapOptions.ServiceAccountDn)} is required but was empty or whitespace — " +
|
||||
@@ -68,6 +86,33 @@ public sealed class LdapOptionsValidator : IValidateOptions<LdapOptions>
|
||||
"(e.g. \"cn=svc,dc=example,dc=com\").");
|
||||
}
|
||||
|
||||
// Fallback endpoints are walked by LdapAuthService on system-side failures. A
|
||||
// malformed entry would be silently skipped there (the walk degrades to the
|
||||
// parseable subset rather than throwing), so it must be caught at boot instead —
|
||||
// otherwise an operator's typo'd backup DC would only surface as a failed
|
||||
// failover during the primary outage it was meant to survive.
|
||||
foreach (var entry in options.FallbackServers)
|
||||
{
|
||||
if (!Internal.LdapEndpointParser.TryParse(entry, options.Port, out _, out var error))
|
||||
{
|
||||
return ValidateOptionsResult.Fail(
|
||||
$"{nameof(LdapOptions.FallbackServers)} contains an invalid entry — {error}. " +
|
||||
"Each entry must be \"host\" or \"host:port\" (port 1–65535).");
|
||||
}
|
||||
}
|
||||
|
||||
return ValidateOptionsResult.Success;
|
||||
}
|
||||
|
||||
private static int CountPlaceholders(string? template)
|
||||
{
|
||||
if (string.IsNullOrEmpty(template))
|
||||
return 0;
|
||||
|
||||
var count = 0;
|
||||
for (var i = template.IndexOf("{0}", StringComparison.Ordinal); i >= 0;
|
||||
i = template.IndexOf("{0}", i + 3, StringComparison.Ordinal))
|
||||
count++;
|
||||
return count;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,8 +11,8 @@
|
||||
<PackageId>ZB.MOM.WW.Auth.Ldap</PackageId>
|
||||
<Authors>ZB.MOM.WW</Authors>
|
||||
<Description>LDAP authentication service (GLAuth / Active Directory) for the ZB.MOM.WW SCADA family.</Description>
|
||||
<PackageProjectUrl>https://gitea.dohertylan.com/dohertj2/zb-mom-ww-auth</PackageProjectUrl>
|
||||
<RepositoryUrl>https://gitea.dohertylan.com/dohertj2/zb-mom-ww-auth</RepositoryUrl>
|
||||
<PackageProjectUrl>https://gitea.dohertylan.com/dohertj2/scadaproj/src/branch/main/ZB.MOM.WW.Auth</PackageProjectUrl>
|
||||
<RepositoryUrl>https://gitea.dohertylan.com/dohertj2/scadaproj</RepositoryUrl>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
@@ -22,6 +22,7 @@
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Novell.Directory.Ldap.NETStandard" />
|
||||
<PackageReference Include="Microsoft.Extensions.Options" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
using Microsoft.Data.Sqlite;
|
||||
using ZB.MOM.WW.Auth.Abstractions.ApiKeys;
|
||||
using ZB.MOM.WW.Auth.ApiKeys.Sqlite;
|
||||
|
||||
namespace ZB.MOM.WW.Auth.ApiKeys.SqlServer.Tests.Live;
|
||||
|
||||
/// <summary>
|
||||
/// Auth-008 (scadaproj#46), the live half: key ids match exactly, as they do in the SQLite store
|
||||
/// this one ports. The <c>key_id</c> column uses the database's default collation — case-insensitive
|
||||
/// on a stock SQL Server — so <c>LINE1</c> found the row stored as <c>line1</c>, and the importer
|
||||
/// counted a SQLite <c>Line1</c> beside <c>line1</c> as an ordinary "skipped" duplicate.
|
||||
/// </summary>
|
||||
[Collection("live-sqlserver")]
|
||||
public sealed class KeyIdFidelityLiveTests : IAsyncLifetime
|
||||
{
|
||||
private readonly string _schema = LiveSqlServer.NewSchemaName();
|
||||
private readonly string _sqlitePath =
|
||||
Path.Combine(Path.GetTempPath(), $"zbauth-keyid-{Guid.NewGuid():N}.db");
|
||||
|
||||
private AuthSqlServerConnectionFactory _factory = null!;
|
||||
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
if (!LiveSqlServer.IsEnabled)
|
||||
return;
|
||||
|
||||
_factory = new AuthSqlServerConnectionFactory(LiveSqlServer.OptionsFor(_schema));
|
||||
await new SqlServerApiKeyStoreMigrator(_factory).MigrateAsync(CancellationToken.None);
|
||||
}
|
||||
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
SqliteConnection.ClearAllPools();
|
||||
foreach (string path in new[] { _sqlitePath, _sqlitePath + "-wal", _sqlitePath + "-shm" })
|
||||
{
|
||||
if (File.Exists(path))
|
||||
File.Delete(path);
|
||||
}
|
||||
|
||||
await LiveSqlServer.DropSchemaAsync(_schema);
|
||||
}
|
||||
|
||||
private static ApiKeyRecord Record(string keyId) => new(
|
||||
KeyId: keyId,
|
||||
KeyPrefix: "sbk",
|
||||
SecretHash: [1, 2, 3, 4],
|
||||
DisplayName: "Key " + keyId,
|
||||
Scopes: new HashSet<string>(["read"], StringComparer.Ordinal),
|
||||
ConstraintsJson: null,
|
||||
CreatedUtc: new DateTimeOffset(2026, 5, 1, 8, 30, 0, TimeSpan.Zero),
|
||||
LastUsedUtc: null,
|
||||
RevokedUtc: null);
|
||||
|
||||
[SkippableFact]
|
||||
public async Task Lookups_AreCaseSensitive_LikeTheSqliteStore()
|
||||
{
|
||||
Skip.IfNot(LiveSqlServer.IsEnabled, LiveSqlServer.SkipReason);
|
||||
|
||||
var admin = new SqlServerApiKeyAdminStore(_factory);
|
||||
var read = new SqlServerApiKeyStore(_factory);
|
||||
await admin.CreateAsync(Record("line1"), CancellationToken.None);
|
||||
|
||||
Assert.NotNull(await read.FindByKeyIdAsync("line1", CancellationToken.None));
|
||||
Assert.Null(await read.FindByKeyIdAsync("LINE1", CancellationToken.None));
|
||||
Assert.Null(await read.FindActiveByKeyIdAsync("Line1", CancellationToken.None));
|
||||
// Trailing spaces are significant too (SQL Server's '=' pads them away).
|
||||
Assert.Null(await read.FindByKeyIdAsync("line1 ", CancellationToken.None));
|
||||
Assert.False(await admin.RevokeAsync("LINE1", DateTimeOffset.UtcNow, CancellationToken.None));
|
||||
Assert.Null((await read.FindByKeyIdAsync("line1", CancellationToken.None))!.RevokedUtc);
|
||||
}
|
||||
|
||||
[SkippableFact]
|
||||
public async Task Import_CaseVariantKeyIds_AreReportedAsCollisions_NotSkipped()
|
||||
{
|
||||
Skip.IfNot(LiveSqlServer.IsEnabled, LiveSqlServer.SkipReason);
|
||||
|
||||
var sqliteFactory = new AuthSqliteConnectionFactory(_sqlitePath);
|
||||
await new SqliteAuthStoreMigrator(sqliteFactory).MigrateAsync(CancellationToken.None);
|
||||
var sqliteAdmin = new SqliteApiKeyAdminStore(sqliteFactory);
|
||||
await sqliteAdmin.CreateAsync(Record("line1"), CancellationToken.None);
|
||||
await sqliteAdmin.CreateAsync(Record("Line1"), CancellationToken.None);
|
||||
|
||||
ApiKeyImportResult result = await new SqliteApiKeyStoreImporter(_factory).ImportAsync(_sqlitePath, CancellationToken.None);
|
||||
|
||||
Assert.Equal(1, result.KeysInserted);
|
||||
Assert.Equal(0, result.KeysSkipped);
|
||||
Assert.Single(result.KeyIdCollisions);
|
||||
|
||||
// Re-running: the inserted one is now an ordinary skip, the other still a collision.
|
||||
ApiKeyImportResult again = await new SqliteApiKeyStoreImporter(_factory).ImportAsync(_sqlitePath, CancellationToken.None);
|
||||
Assert.Equal(0, again.KeysInserted);
|
||||
Assert.Equal(1, again.KeysSkipped);
|
||||
Assert.Single(again.KeyIdCollisions);
|
||||
}
|
||||
|
||||
[SkippableFact]
|
||||
public async Task Import_OverLengthKey_IsRejected_NotTruncated()
|
||||
{
|
||||
Skip.IfNot(LiveSqlServer.IsEnabled, LiveSqlServer.SkipReason);
|
||||
|
||||
string longId = new('k', 70);
|
||||
var sqliteFactory = new AuthSqliteConnectionFactory(_sqlitePath);
|
||||
await new SqliteAuthStoreMigrator(sqliteFactory).MigrateAsync(CancellationToken.None);
|
||||
var sqliteAdmin = new SqliteApiKeyAdminStore(sqliteFactory);
|
||||
await sqliteAdmin.CreateAsync(Record(longId), CancellationToken.None);
|
||||
await sqliteAdmin.CreateAsync(Record("ok-key"), CancellationToken.None);
|
||||
|
||||
ApiKeyImportResult result = await new SqliteApiKeyStoreImporter(_factory).ImportAsync(_sqlitePath, CancellationToken.None);
|
||||
|
||||
Assert.Equal(1, result.KeysInserted);
|
||||
Assert.Equal(longId, Assert.Single(result.KeysRejected));
|
||||
Assert.Equal(1L, Convert.ToInt64(await LiveSqlServer.ScalarAsync($"SELECT COUNT(*) FROM [{_schema}].[api_keys]")));
|
||||
}
|
||||
}
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
using Microsoft.Data.SqlClient;
|
||||
|
||||
namespace ZB.MOM.WW.Auth.ApiKeys.SqlServer.Tests.Live;
|
||||
|
||||
/// <summary>
|
||||
/// Shared connection details for the env-gated live SQL Server suite.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Gated on <c>AUTH_SQLSERVER_CONNSTR</c> and skips cleanly when it is unset, matching the family
|
||||
/// live-test idiom (see <c>ZB.MOM.WW.Secrets.Replicator.SqlServer</c>) — the offline suite must stay
|
||||
/// runnable on any machine. Set it to a database the test is allowed to create and drop a schema in,
|
||||
/// for example <c>Server=localhost,1433;Database=ZbAuthTest;User Id=sa;Password=...;TrustServerCertificate=true</c>.
|
||||
/// Each test class works in a throwaway <em>schema</em> rather than a throwaway database: it needs no
|
||||
/// CREATE DATABASE right, and a virgin schema still reproduces the CREATE SCHEMA race the migrator's
|
||||
/// retry loop exists for.
|
||||
/// </remarks>
|
||||
public static class LiveSqlServer
|
||||
{
|
||||
/// <summary>Environment variable holding the live connection string.</summary>
|
||||
public const string ConnectionStringVariable = "AUTH_SQLSERVER_CONNSTR";
|
||||
|
||||
/// <summary>The configured connection string, or <see langword="null"/> when the suite is not enabled.</summary>
|
||||
public static string? ConnectionString =>
|
||||
Environment.GetEnvironmentVariable(ConnectionStringVariable);
|
||||
|
||||
/// <summary>Whether the live suite should run.</summary>
|
||||
public static bool IsEnabled => !string.IsNullOrWhiteSpace(ConnectionString);
|
||||
|
||||
/// <summary>Skip reason shown when the suite is not enabled.</summary>
|
||||
public const string SkipReason =
|
||||
"Live SQL Server suite disabled; set AUTH_SQLSERVER_CONNSTR to enable.";
|
||||
|
||||
/// <summary>
|
||||
/// Builds options against a throwaway schema so parallel runs and repeat runs cannot collide,
|
||||
/// and so a failed run leaves no trace in a shared database.
|
||||
/// </summary>
|
||||
/// <param name="schemaName">The unique schema name for this test.</param>
|
||||
/// <returns>Options targeting that schema.</returns>
|
||||
public static SqlServerApiKeyOptions OptionsFor(string schemaName) => new()
|
||||
{
|
||||
ConnectionString = ConnectionString!,
|
||||
Schema = schemaName,
|
||||
};
|
||||
|
||||
/// <summary>Generates a unique, allow-list-legal schema name for one test.</summary>
|
||||
/// <returns>A fresh schema name.</returns>
|
||||
public static string NewSchemaName() => $"zbauth_test_{Guid.NewGuid():N}"[..32];
|
||||
|
||||
/// <summary>Drops the throwaway schema and its three tables.</summary>
|
||||
/// <param name="schemaName">The schema to drop.</param>
|
||||
/// <returns>A task that completes when the schema is gone.</returns>
|
||||
public static async Task DropSchemaAsync(string schemaName)
|
||||
{
|
||||
if (!IsEnabled)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await using var connection = new SqlConnection(ConnectionString);
|
||||
await connection.OpenAsync();
|
||||
|
||||
await using SqlCommand command = connection.CreateCommand();
|
||||
command.CommandText = $"""
|
||||
IF OBJECT_ID(N'[{schemaName}].[api_key_audit]', N'U') IS NOT NULL DROP TABLE [{schemaName}].[api_key_audit];
|
||||
IF OBJECT_ID(N'[{schemaName}].[api_keys]', N'U') IS NOT NULL DROP TABLE [{schemaName}].[api_keys];
|
||||
IF OBJECT_ID(N'[{schemaName}].[schema_version]', N'U') IS NOT NULL DROP TABLE [{schemaName}].[schema_version];
|
||||
IF EXISTS (SELECT 1 FROM sys.schemas WHERE name = N'{schemaName}') EXEC(N'DROP SCHEMA [{schemaName}]');
|
||||
""";
|
||||
|
||||
await command.ExecuteNonQueryAsync();
|
||||
}
|
||||
|
||||
/// <summary>Runs a scalar query against the live database.</summary>
|
||||
/// <param name="commandText">The query text.</param>
|
||||
/// <returns>The first column of the first row, or <see langword="null"/>.</returns>
|
||||
public static async Task<object?> ScalarAsync(string commandText)
|
||||
{
|
||||
await using var connection = new SqlConnection(ConnectionString);
|
||||
await connection.OpenAsync();
|
||||
|
||||
await using SqlCommand command = connection.CreateCommand();
|
||||
command.CommandText = commandText;
|
||||
|
||||
object? value = await command.ExecuteScalarAsync();
|
||||
return value == DBNull.Value ? null : value;
|
||||
}
|
||||
|
||||
/// <summary>Runs a non-query statement against the live database.</summary>
|
||||
/// <param name="commandText">The statement text.</param>
|
||||
/// <returns>A task that completes when the statement has run.</returns>
|
||||
public static async Task ExecuteAsync(string commandText)
|
||||
{
|
||||
await using var connection = new SqlConnection(ConnectionString);
|
||||
await connection.OpenAsync();
|
||||
|
||||
await using SqlCommand command = connection.CreateCommand();
|
||||
command.CommandText = commandText;
|
||||
|
||||
await command.ExecuteNonQueryAsync();
|
||||
}
|
||||
}
|
||||
+499
@@ -0,0 +1,499 @@
|
||||
using ZB.MOM.WW.Auth.Abstractions.ApiKeys;
|
||||
|
||||
namespace ZB.MOM.WW.Auth.ApiKeys.SqlServer.Tests.Live;
|
||||
|
||||
/// <summary>
|
||||
/// Live contract tests for <see cref="SqlServerApiKeyAdminStore"/> (and the audit store it is
|
||||
/// exercised alongside).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// A one-for-one port of <c>SqliteApiKeyAdminStoreTests</c> — same test names, same assertions — so
|
||||
/// the create/revoke/rotate/scope/enable/delete semantics are pinned identically across the two
|
||||
/// providers. xUnit constructs a new test-class instance per test, so each test provisions and drops
|
||||
/// its own throwaway schema.
|
||||
/// </remarks>
|
||||
[Collection("live-sqlserver")]
|
||||
public sealed class SqlServerApiKeyAdminStoreLiveTests : IAsyncLifetime
|
||||
{
|
||||
private readonly string _schema = LiveSqlServer.NewSchemaName();
|
||||
|
||||
private AuthSqlServerConnectionFactory _factory = null!;
|
||||
private SqlServerApiKeyAdminStore _admin = null!;
|
||||
private SqlServerApiKeyStore _read = null!;
|
||||
private SqlServerApiKeyAuditStore _audit = null!;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
if (!LiveSqlServer.IsEnabled)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_factory = new AuthSqlServerConnectionFactory(LiveSqlServer.OptionsFor(_schema));
|
||||
await new SqlServerApiKeyStoreMigrator(_factory).MigrateAsync(CancellationToken.None);
|
||||
_admin = new SqlServerApiKeyAdminStore(_factory);
|
||||
_read = new SqlServerApiKeyStore(_factory);
|
||||
_audit = new SqlServerApiKeyAuditStore(_factory);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task DisposeAsync() => LiveSqlServer.DropSchemaAsync(_schema);
|
||||
|
||||
// --- Create ---
|
||||
|
||||
[SkippableFact]
|
||||
public async Task Create_ThenFindByKeyId_ReturnsRecord()
|
||||
{
|
||||
Skip.IfNot(LiveSqlServer.IsEnabled, LiveSqlServer.SkipReason);
|
||||
|
||||
ApiKeyRecord record = SampleRecord("key-1");
|
||||
|
||||
await _admin.CreateAsync(record, CancellationToken.None);
|
||||
|
||||
ApiKeyRecord? found = await _read.FindByKeyIdAsync("key-1", CancellationToken.None);
|
||||
Assert.NotNull(found);
|
||||
Assert.Equal(record.SecretHash, found!.SecretHash);
|
||||
Assert.True(record.Scopes.SetEquals(found.Scopes));
|
||||
Assert.Equal(record.ConstraintsJson, found.ConstraintsJson);
|
||||
Assert.Null(found.LastUsedUtc);
|
||||
Assert.Null(found.RevokedUtc);
|
||||
}
|
||||
|
||||
[SkippableFact]
|
||||
public async Task Create_WithExpiresUtc_RoundTripsThroughFindAndList()
|
||||
{
|
||||
Skip.IfNot(LiveSqlServer.IsEnabled, LiveSqlServer.SkipReason);
|
||||
|
||||
var expiry = new DateTimeOffset(2026, 12, 31, 23, 59, 59, TimeSpan.Zero);
|
||||
ApiKeyRecord record = SampleRecord("key-exp") with { ExpiresUtc = expiry };
|
||||
|
||||
await _admin.CreateAsync(record, CancellationToken.None);
|
||||
|
||||
ApiKeyRecord? found = await _read.FindByKeyIdAsync("key-exp", CancellationToken.None);
|
||||
Assert.Equal(expiry, found!.ExpiresUtc);
|
||||
|
||||
IReadOnlyList<ApiKeyListItem> listed = await _admin.ListAsync(CancellationToken.None);
|
||||
ApiKeyListItem item = Assert.Single(listed, k => k.KeyId == "key-exp");
|
||||
Assert.Equal(expiry, item.ExpiresUtc);
|
||||
}
|
||||
|
||||
[SkippableFact]
|
||||
public async Task Create_WithoutExpiresUtc_ReadsBackAsNull()
|
||||
{
|
||||
Skip.IfNot(LiveSqlServer.IsEnabled, LiveSqlServer.SkipReason);
|
||||
|
||||
await _admin.CreateAsync(SampleRecord("key-1"), CancellationToken.None);
|
||||
|
||||
ApiKeyRecord? found = await _read.FindByKeyIdAsync("key-1", CancellationToken.None);
|
||||
Assert.Null(found!.ExpiresUtc);
|
||||
|
||||
IReadOnlyList<ApiKeyListItem> listed = await _admin.ListAsync(CancellationToken.None);
|
||||
Assert.Null(Assert.Single(listed, k => k.KeyId == "key-1").ExpiresUtc);
|
||||
}
|
||||
|
||||
// --- Revoke ---
|
||||
|
||||
[SkippableFact]
|
||||
public async Task Revoke_ActiveKey_SetsRevokedAndFindActiveReturnsNull()
|
||||
{
|
||||
Skip.IfNot(LiveSqlServer.IsEnabled, LiveSqlServer.SkipReason);
|
||||
|
||||
await _admin.CreateAsync(SampleRecord("key-1"), CancellationToken.None);
|
||||
var when = new DateTimeOffset(2026, 5, 31, 9, 0, 0, TimeSpan.Zero);
|
||||
|
||||
bool result = await _admin.RevokeAsync("key-1", when, CancellationToken.None);
|
||||
|
||||
Assert.True(result);
|
||||
Assert.Null(await _read.FindActiveByKeyIdAsync("key-1", CancellationToken.None));
|
||||
ApiKeyRecord? found = await _read.FindByKeyIdAsync("key-1", CancellationToken.None);
|
||||
Assert.Equal(when, found!.RevokedUtc);
|
||||
}
|
||||
|
||||
[SkippableFact]
|
||||
public async Task Revoke_UnknownKey_ReturnsFalse()
|
||||
{
|
||||
Skip.IfNot(LiveSqlServer.IsEnabled, LiveSqlServer.SkipReason);
|
||||
|
||||
bool result = await _admin.RevokeAsync("missing", DateTimeOffset.UtcNow, CancellationToken.None);
|
||||
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
[SkippableFact]
|
||||
public async Task Revoke_AlreadyRevoked_ReturnsFalse()
|
||||
{
|
||||
Skip.IfNot(LiveSqlServer.IsEnabled, LiveSqlServer.SkipReason);
|
||||
|
||||
await _admin.CreateAsync(SampleRecord("key-1"), CancellationToken.None);
|
||||
await _admin.RevokeAsync("key-1", DateTimeOffset.UtcNow, CancellationToken.None);
|
||||
|
||||
bool result = await _admin.RevokeAsync("key-1", DateTimeOffset.UtcNow, CancellationToken.None);
|
||||
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
// --- Rotate ---
|
||||
|
||||
[SkippableFact]
|
||||
public async Task Rotate_ChangesHashAndReactivates()
|
||||
{
|
||||
Skip.IfNot(LiveSqlServer.IsEnabled, LiveSqlServer.SkipReason);
|
||||
|
||||
await _admin.CreateAsync(SampleRecord("key-1"), CancellationToken.None);
|
||||
await _admin.RevokeAsync("key-1", DateTimeOffset.UtcNow, CancellationToken.None);
|
||||
await _read.MarkUsedAsync("key-1", DateTimeOffset.UtcNow, CancellationToken.None);
|
||||
byte[] newHash = [9, 9, 9, 9];
|
||||
|
||||
bool result = await _admin.RotateAsync("key-1", newHash, CancellationToken.None);
|
||||
|
||||
Assert.True(result);
|
||||
ApiKeyRecord? found = await _read.FindByKeyIdAsync("key-1", CancellationToken.None);
|
||||
Assert.Equal(newHash, found!.SecretHash);
|
||||
Assert.Null(found.RevokedUtc);
|
||||
Assert.Null(found.LastUsedUtc);
|
||||
// Reactivated: now visible as active.
|
||||
Assert.NotNull(await _read.FindActiveByKeyIdAsync("key-1", CancellationToken.None));
|
||||
}
|
||||
|
||||
[SkippableFact]
|
||||
public async Task Rotate_UnknownKey_ReturnsFalse()
|
||||
{
|
||||
Skip.IfNot(LiveSqlServer.IsEnabled, LiveSqlServer.SkipReason);
|
||||
|
||||
bool result = await _admin.RotateAsync("missing", [1], CancellationToken.None);
|
||||
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
// --- SetScopes ---
|
||||
|
||||
[SkippableFact]
|
||||
public async Task SetScopesAsync_ReplacesScopes_AndReturnsTrue()
|
||||
{
|
||||
Skip.IfNot(LiveSqlServer.IsEnabled, LiveSqlServer.SkipReason);
|
||||
|
||||
await _admin.CreateAsync(
|
||||
SampleRecord("key-1") with { Scopes = new HashSet<string>(["a"], StringComparer.Ordinal) },
|
||||
CancellationToken.None);
|
||||
|
||||
bool result = await _admin.SetScopesAsync(
|
||||
"key-1",
|
||||
new HashSet<string>(["b", "c"], StringComparer.Ordinal),
|
||||
CancellationToken.None);
|
||||
|
||||
Assert.True(result);
|
||||
IReadOnlyList<ApiKeyListItem> listed = await _admin.ListAsync(CancellationToken.None);
|
||||
ApiKeyListItem item = Assert.Single(listed, k => k.KeyId == "key-1");
|
||||
Assert.True(item.Scopes.SetEquals(new HashSet<string>(["b", "c"], StringComparer.Ordinal)));
|
||||
}
|
||||
|
||||
[SkippableFact]
|
||||
public async Task SetScopesAsync_UnknownKey_ReturnsFalse()
|
||||
{
|
||||
Skip.IfNot(LiveSqlServer.IsEnabled, LiveSqlServer.SkipReason);
|
||||
|
||||
bool result = await _admin.SetScopesAsync(
|
||||
"missing",
|
||||
new HashSet<string>(["b"], StringComparer.Ordinal),
|
||||
CancellationToken.None);
|
||||
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
// --- SetEnabled ---
|
||||
|
||||
[SkippableFact]
|
||||
public async Task SetEnabledAsync_False_DisablesKey()
|
||||
{
|
||||
Skip.IfNot(LiveSqlServer.IsEnabled, LiveSqlServer.SkipReason);
|
||||
|
||||
await _admin.CreateAsync(SampleRecord("key-1"), CancellationToken.None);
|
||||
var when = new DateTimeOffset(2026, 5, 31, 9, 0, 0, TimeSpan.Zero);
|
||||
|
||||
bool result = await _admin.SetEnabledAsync("key-1", enabled: false, when, CancellationToken.None);
|
||||
|
||||
Assert.True(result);
|
||||
Assert.Null(await _read.FindActiveByKeyIdAsync("key-1", CancellationToken.None));
|
||||
ApiKeyRecord? found = await _read.FindByKeyIdAsync("key-1", CancellationToken.None);
|
||||
Assert.Equal(when, found!.RevokedUtc);
|
||||
}
|
||||
|
||||
[SkippableFact]
|
||||
public async Task SetEnabledAsync_True_ReenablesKey_WithoutChangingSecret()
|
||||
{
|
||||
Skip.IfNot(LiveSqlServer.IsEnabled, LiveSqlServer.SkipReason);
|
||||
|
||||
ApiKeyRecord original = SampleRecord("key-1");
|
||||
await _admin.CreateAsync(original, CancellationToken.None);
|
||||
// Record some usage so we can prove last_used_utc is left untouched on re-enable.
|
||||
var used = new DateTimeOffset(2026, 5, 20, 12, 0, 0, TimeSpan.Zero);
|
||||
await _read.MarkUsedAsync("key-1", used, CancellationToken.None);
|
||||
|
||||
// Disable, then re-enable.
|
||||
await _admin.SetEnabledAsync(
|
||||
"key-1", enabled: false, new DateTimeOffset(2026, 5, 31, 9, 0, 0, TimeSpan.Zero), CancellationToken.None);
|
||||
bool result = await _admin.SetEnabledAsync(
|
||||
"key-1", enabled: true, new DateTimeOffset(2026, 6, 1, 9, 0, 0, TimeSpan.Zero), CancellationToken.None);
|
||||
|
||||
Assert.True(result);
|
||||
|
||||
// Active again, and the secret hash + last-used timestamp are unchanged.
|
||||
ApiKeyRecord? active = await _read.FindActiveByKeyIdAsync("key-1", CancellationToken.None);
|
||||
Assert.NotNull(active);
|
||||
Assert.True(active!.SecretHash.SequenceEqual(original.SecretHash));
|
||||
Assert.Null(active.RevokedUtc);
|
||||
Assert.Equal(used, active.LastUsedUtc);
|
||||
}
|
||||
|
||||
[SkippableFact]
|
||||
public async Task SetEnabledAsync_UnknownKey_ReturnsFalse()
|
||||
{
|
||||
Skip.IfNot(LiveSqlServer.IsEnabled, LiveSqlServer.SkipReason);
|
||||
|
||||
bool result = await _admin.SetEnabledAsync(
|
||||
"missing", enabled: false, DateTimeOffset.UtcNow, CancellationToken.None);
|
||||
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
// --- Delete ---
|
||||
|
||||
[SkippableFact]
|
||||
public async Task Delete_ActiveKey_ReturnsFalseAndKeyStillPresent()
|
||||
{
|
||||
Skip.IfNot(LiveSqlServer.IsEnabled, LiveSqlServer.SkipReason);
|
||||
|
||||
await _admin.CreateAsync(SampleRecord("key-1"), CancellationToken.None);
|
||||
|
||||
bool result = await _admin.DeleteAsync("key-1", CancellationToken.None);
|
||||
|
||||
Assert.False(result);
|
||||
Assert.NotNull(await _read.FindByKeyIdAsync("key-1", CancellationToken.None));
|
||||
}
|
||||
|
||||
[SkippableFact]
|
||||
public async Task Delete_RevokedKey_ReturnsTrueAndKeyGone()
|
||||
{
|
||||
Skip.IfNot(LiveSqlServer.IsEnabled, LiveSqlServer.SkipReason);
|
||||
|
||||
await _admin.CreateAsync(SampleRecord("key-1"), CancellationToken.None);
|
||||
await _admin.RevokeAsync("key-1", DateTimeOffset.UtcNow, CancellationToken.None);
|
||||
|
||||
bool result = await _admin.DeleteAsync("key-1", CancellationToken.None);
|
||||
|
||||
Assert.True(result);
|
||||
Assert.Null(await _read.FindByKeyIdAsync("key-1", CancellationToken.None));
|
||||
}
|
||||
|
||||
[SkippableFact]
|
||||
public async Task Delete_UnknownKey_ReturnsFalse()
|
||||
{
|
||||
Skip.IfNot(LiveSqlServer.IsEnabled, LiveSqlServer.SkipReason);
|
||||
|
||||
bool result = await _admin.DeleteAsync("missing", CancellationToken.None);
|
||||
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
// --- keyId guard tests ---
|
||||
|
||||
[SkippableTheory]
|
||||
[InlineData(null)]
|
||||
[InlineData("")]
|
||||
[InlineData(" ")]
|
||||
public async Task Revoke_NullOrWhitespaceKeyId_ThrowsArgumentException(string? keyId)
|
||||
{
|
||||
Skip.IfNot(LiveSqlServer.IsEnabled, LiveSqlServer.SkipReason);
|
||||
|
||||
// ArgumentNullException (null) and ArgumentException (empty/whitespace) are both acceptable;
|
||||
// ThrowIfNullOrWhiteSpace throws ArgumentNullException for null, ArgumentException for whitespace.
|
||||
await Assert.ThrowsAnyAsync<ArgumentException>(
|
||||
() => _admin.RevokeAsync(keyId!, DateTimeOffset.UtcNow, CancellationToken.None));
|
||||
}
|
||||
|
||||
[SkippableTheory]
|
||||
[InlineData(null)]
|
||||
[InlineData("")]
|
||||
[InlineData(" ")]
|
||||
public async Task Rotate_NullOrWhitespaceKeyId_ThrowsArgumentException(string? keyId)
|
||||
{
|
||||
Skip.IfNot(LiveSqlServer.IsEnabled, LiveSqlServer.SkipReason);
|
||||
|
||||
await Assert.ThrowsAnyAsync<ArgumentException>(
|
||||
() => _admin.RotateAsync(keyId!, [1, 2, 3], CancellationToken.None));
|
||||
}
|
||||
|
||||
[SkippableTheory]
|
||||
[InlineData(null)]
|
||||
[InlineData("")]
|
||||
[InlineData(" ")]
|
||||
public async Task Delete_NullOrWhitespaceKeyId_ThrowsArgumentException(string? keyId)
|
||||
{
|
||||
Skip.IfNot(LiveSqlServer.IsEnabled, LiveSqlServer.SkipReason);
|
||||
|
||||
await Assert.ThrowsAnyAsync<ArgumentException>(
|
||||
() => _admin.DeleteAsync(keyId!, CancellationToken.None));
|
||||
}
|
||||
|
||||
[SkippableTheory]
|
||||
[InlineData(null)]
|
||||
[InlineData("")]
|
||||
[InlineData(" ")]
|
||||
public async Task SetScopesAsync_NullOrWhitespaceKeyId_ThrowsArgumentException(string? keyId)
|
||||
{
|
||||
Skip.IfNot(LiveSqlServer.IsEnabled, LiveSqlServer.SkipReason);
|
||||
|
||||
await Assert.ThrowsAnyAsync<ArgumentException>(
|
||||
() => _admin.SetScopesAsync(
|
||||
keyId!,
|
||||
new HashSet<string>(["read"], StringComparer.Ordinal),
|
||||
CancellationToken.None));
|
||||
}
|
||||
|
||||
[SkippableTheory]
|
||||
[InlineData(null)]
|
||||
[InlineData("")]
|
||||
[InlineData(" ")]
|
||||
public async Task SetEnabledAsync_NullOrWhitespaceKeyId_ThrowsArgumentException(string? keyId)
|
||||
{
|
||||
Skip.IfNot(LiveSqlServer.IsEnabled, LiveSqlServer.SkipReason);
|
||||
|
||||
await Assert.ThrowsAnyAsync<ArgumentException>(
|
||||
() => _admin.SetEnabledAsync(keyId!, enabled: false, DateTimeOffset.UtcNow, CancellationToken.None));
|
||||
}
|
||||
|
||||
[SkippableFact]
|
||||
public async Task SetScopesAsync_NullScopes_ThrowsArgumentNullException()
|
||||
{
|
||||
Skip.IfNot(LiveSqlServer.IsEnabled, LiveSqlServer.SkipReason);
|
||||
|
||||
await _admin.CreateAsync(SampleRecord("key-1"), CancellationToken.None);
|
||||
|
||||
await Assert.ThrowsAsync<ArgumentNullException>(
|
||||
() => _admin.SetScopesAsync("key-1", null!, CancellationToken.None));
|
||||
}
|
||||
|
||||
// --- SetEnabled idempotence ---
|
||||
|
||||
[SkippableFact]
|
||||
public async Task SetEnabledAsync_OnAlreadyActiveKey_ReturnsTrue()
|
||||
{
|
||||
Skip.IfNot(LiveSqlServer.IsEnabled, LiveSqlServer.SkipReason);
|
||||
|
||||
await _admin.CreateAsync(SampleRecord("key-1"), CancellationToken.None);
|
||||
|
||||
bool result = await _admin.SetEnabledAsync(
|
||||
"key-1", enabled: true, DateTimeOffset.UtcNow, CancellationToken.None);
|
||||
|
||||
Assert.True(result);
|
||||
ApiKeyRecord? active = await _read.FindActiveByKeyIdAsync("key-1", CancellationToken.None);
|
||||
Assert.NotNull(active);
|
||||
Assert.Null(active!.RevokedUtc);
|
||||
}
|
||||
|
||||
[SkippableFact]
|
||||
public async Task SetEnabledAsync_OnAlreadyDisabledKey_OverwritesTimestamp_ReturnsTrue()
|
||||
{
|
||||
Skip.IfNot(LiveSqlServer.IsEnabled, LiveSqlServer.SkipReason);
|
||||
|
||||
await _admin.CreateAsync(SampleRecord("key-1"), CancellationToken.None);
|
||||
var t1 = new DateTimeOffset(2026, 5, 1, 10, 0, 0, TimeSpan.Zero);
|
||||
var t2 = new DateTimeOffset(2026, 5, 15, 10, 0, 0, TimeSpan.Zero);
|
||||
|
||||
// Disable at t1.
|
||||
await _admin.SetEnabledAsync("key-1", enabled: false, t1, CancellationToken.None);
|
||||
|
||||
// Disable again at a later t2 (idempotent overwrite — no guard on revoked_utc).
|
||||
bool result = await _admin.SetEnabledAsync("key-1", enabled: false, t2, CancellationToken.None);
|
||||
|
||||
Assert.True(result);
|
||||
IReadOnlyList<ApiKeyListItem> listed = await _admin.ListAsync(CancellationToken.None);
|
||||
ApiKeyListItem item = Assert.Single(listed, k => k.KeyId == "key-1");
|
||||
Assert.Equal(t2, item.RevokedUtc);
|
||||
}
|
||||
|
||||
// --- Audit ---
|
||||
|
||||
[SkippableFact]
|
||||
public async Task Audit_AppendThenListRecent_ReturnsEntry()
|
||||
{
|
||||
Skip.IfNot(LiveSqlServer.IsEnabled, LiveSqlServer.SkipReason);
|
||||
|
||||
var entry = new ApiKeyAuditEntry(
|
||||
KeyId: "key-1",
|
||||
EventType: "created",
|
||||
RemoteAddress: "10.0.0.1",
|
||||
CreatedUtc: new DateTimeOffset(2026, 5, 31, 10, 0, 0, TimeSpan.Zero),
|
||||
Details: "by admin");
|
||||
|
||||
await _audit.AppendAsync(entry, CancellationToken.None);
|
||||
|
||||
IReadOnlyList<ApiKeyAuditEntry> recent = await _audit.ListRecentAsync(10, CancellationToken.None);
|
||||
Assert.Single(recent);
|
||||
Assert.Equal("key-1", recent[0].KeyId);
|
||||
Assert.Equal("created", recent[0].EventType);
|
||||
Assert.Equal("10.0.0.1", recent[0].RemoteAddress);
|
||||
Assert.Equal("by admin", recent[0].Details);
|
||||
}
|
||||
|
||||
[SkippableFact]
|
||||
public async Task Audit_ListRecent_ReturnsNewestFirst()
|
||||
{
|
||||
Skip.IfNot(LiveSqlServer.IsEnabled, LiveSqlServer.SkipReason);
|
||||
|
||||
await _audit.AppendAsync(
|
||||
new ApiKeyAuditEntry("k", "first", null, DateTimeOffset.UtcNow, null), CancellationToken.None);
|
||||
await _audit.AppendAsync(
|
||||
new ApiKeyAuditEntry("k", "second", null, DateTimeOffset.UtcNow, null), CancellationToken.None);
|
||||
await _audit.AppendAsync(
|
||||
new ApiKeyAuditEntry("k", "third", null, DateTimeOffset.UtcNow, null), CancellationToken.None);
|
||||
|
||||
IReadOnlyList<ApiKeyAuditEntry> recent = await _audit.ListRecentAsync(10, CancellationToken.None);
|
||||
|
||||
Assert.Equal(["third", "second", "first"], recent.Select(e => e.EventType));
|
||||
}
|
||||
|
||||
[SkippableFact]
|
||||
public async Task Audit_ListRecent_RespectsLimit()
|
||||
{
|
||||
Skip.IfNot(LiveSqlServer.IsEnabled, LiveSqlServer.SkipReason);
|
||||
|
||||
for (int i = 0; i < 5; i++)
|
||||
{
|
||||
await _audit.AppendAsync(
|
||||
new ApiKeyAuditEntry("k", $"e{i}", null, DateTimeOffset.UtcNow, null), CancellationToken.None);
|
||||
}
|
||||
|
||||
IReadOnlyList<ApiKeyAuditEntry> recent = await _audit.ListRecentAsync(2, CancellationToken.None);
|
||||
|
||||
Assert.Equal(2, recent.Count);
|
||||
Assert.Equal(["e4", "e3"], recent.Select(e => e.EventType));
|
||||
}
|
||||
|
||||
[SkippableFact]
|
||||
public async Task Audit_NullableFields_RoundTripAsNull()
|
||||
{
|
||||
Skip.IfNot(LiveSqlServer.IsEnabled, LiveSqlServer.SkipReason);
|
||||
|
||||
await _audit.AppendAsync(
|
||||
new ApiKeyAuditEntry(null, "anon", null, DateTimeOffset.UtcNow, null), CancellationToken.None);
|
||||
|
||||
IReadOnlyList<ApiKeyAuditEntry> recent = await _audit.ListRecentAsync(10, CancellationToken.None);
|
||||
Assert.Single(recent);
|
||||
Assert.Null(recent[0].KeyId);
|
||||
Assert.Null(recent[0].RemoteAddress);
|
||||
Assert.Null(recent[0].Details);
|
||||
}
|
||||
|
||||
private static ApiKeyRecord SampleRecord(string keyId) => new(
|
||||
KeyId: keyId,
|
||||
KeyPrefix: "mxgw_ab12",
|
||||
SecretHash: [1, 2, 3, 4, 5, 6, 7, 8],
|
||||
DisplayName: "Test Key " + keyId,
|
||||
Scopes: new HashSet<string>(["read", "write"], StringComparer.Ordinal),
|
||||
ConstraintsJson: """{"ipAllow":["10.0.0.0/8"]}""",
|
||||
CreatedUtc: new DateTimeOffset(2026, 5, 1, 8, 30, 0, TimeSpan.Zero),
|
||||
LastUsedUtc: null,
|
||||
RevokedUtc: null);
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
using ZB.MOM.WW.Auth.Abstractions.ApiKeys;
|
||||
|
||||
namespace ZB.MOM.WW.Auth.ApiKeys.SqlServer.Tests.Live;
|
||||
|
||||
/// <summary>
|
||||
/// Live tests for <see cref="SqlServerApiKeyAuditStore"/> that the ported SQLite suite does not
|
||||
/// already cover: newest-first ordering under a limit, and the non-positive-limit short circuit.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// xUnit constructs a new test-class instance per test, so each test provisions and drops its own
|
||||
/// throwaway schema.
|
||||
/// </remarks>
|
||||
[Collection("live-sqlserver")]
|
||||
public sealed class SqlServerApiKeyAuditStoreLiveTests : IAsyncLifetime
|
||||
{
|
||||
private readonly string _schema = LiveSqlServer.NewSchemaName();
|
||||
|
||||
private SqlServerApiKeyAuditStore _audit = null!;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
if (!LiveSqlServer.IsEnabled)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var factory = new AuthSqlServerConnectionFactory(LiveSqlServer.OptionsFor(_schema));
|
||||
await new SqlServerApiKeyStoreMigrator(factory).MigrateAsync(CancellationToken.None);
|
||||
_audit = new SqlServerApiKeyAuditStore(factory);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task DisposeAsync() => LiveSqlServer.DropSchemaAsync(_schema);
|
||||
|
||||
[SkippableFact]
|
||||
public async Task Append_ThenListRecent_ReturnsNewestFirstWithinLimit()
|
||||
{
|
||||
Skip.IfNot(LiveSqlServer.IsEnabled, LiveSqlServer.SkipReason);
|
||||
|
||||
// Every row carries the SAME created_utc, so the newest-first order can only come from the
|
||||
// IDENTITY audit_id the ORDER BY names — the timestamp cannot accidentally supply it.
|
||||
var when = new DateTimeOffset(2026, 7, 1, 0, 0, 0, TimeSpan.Zero);
|
||||
for (int i = 0; i < 6; i++)
|
||||
{
|
||||
await _audit.AppendAsync(
|
||||
new ApiKeyAuditEntry("k", $"e{i}", "10.0.0.1", when, $"detail {i}"),
|
||||
CancellationToken.None);
|
||||
}
|
||||
|
||||
IReadOnlyList<ApiKeyAuditEntry> recent = await _audit.ListRecentAsync(3, CancellationToken.None);
|
||||
|
||||
Assert.Equal(3, recent.Count);
|
||||
Assert.Equal(["e5", "e4", "e3"], recent.Select(e => e.EventType));
|
||||
Assert.Equal("detail 5", recent[0].Details);
|
||||
Assert.Equal(when, recent[0].CreatedUtc);
|
||||
}
|
||||
|
||||
[SkippableFact]
|
||||
public async Task ListRecent_NonPositiveLimit_ReturnsEmpty()
|
||||
{
|
||||
Skip.IfNot(LiveSqlServer.IsEnabled, LiveSqlServer.SkipReason);
|
||||
|
||||
await _audit.AppendAsync(
|
||||
new ApiKeyAuditEntry("k", "created", null, DateTimeOffset.UtcNow, null),
|
||||
CancellationToken.None);
|
||||
|
||||
// A non-positive limit short circuits WITHOUT touching the database — SELECT TOP (0) would
|
||||
// be legal but SELECT TOP (-1) is a syntax error, so the guard is load-bearing here in a way
|
||||
// it is not for SQLite's LIMIT.
|
||||
Assert.Empty(await _audit.ListRecentAsync(0, CancellationToken.None));
|
||||
Assert.Empty(await _audit.ListRecentAsync(-5, CancellationToken.None));
|
||||
}
|
||||
}
|
||||
+340
@@ -0,0 +1,340 @@
|
||||
using System.Data;
|
||||
using Microsoft.Data.SqlClient;
|
||||
using ZB.MOM.WW.Auth.Abstractions.ApiKeys;
|
||||
using ZB.MOM.WW.Auth.ApiKeys.Sqlite;
|
||||
|
||||
namespace ZB.MOM.WW.Auth.ApiKeys.SqlServer.Tests.Live;
|
||||
|
||||
/// <summary>
|
||||
/// Live contract tests for <see cref="SqlServerApiKeyStore"/>.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// A one-for-one port of <c>SqliteApiKeyStoreTests</c> (same test names, same assertions) so the two
|
||||
/// providers are pinned to identical semantics: whichever store a host composes, a row means the
|
||||
/// same thing. xUnit constructs a new test-class instance per test, so each test provisions and
|
||||
/// drops its own throwaway schema — the isolation the SQLite suite gets from a per-test temp file.
|
||||
/// </remarks>
|
||||
[Collection("live-sqlserver")]
|
||||
public sealed class SqlServerApiKeyStoreLiveTests : IAsyncLifetime
|
||||
{
|
||||
private readonly string _schema = LiveSqlServer.NewSchemaName();
|
||||
|
||||
private AuthSqlServerConnectionFactory _factory = null!;
|
||||
private SqlServerApiKeyStore _store = null!;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
if (!LiveSqlServer.IsEnabled)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_factory = new AuthSqlServerConnectionFactory(LiveSqlServer.OptionsFor(_schema));
|
||||
await new SqlServerApiKeyStoreMigrator(_factory).MigrateAsync(CancellationToken.None);
|
||||
_store = new SqlServerApiKeyStore(_factory);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task DisposeAsync() => LiveSqlServer.DropSchemaAsync(_schema);
|
||||
|
||||
[SkippableFact]
|
||||
public async Task FindByKeyId_AfterInsert_ReturnsEqualRecord()
|
||||
{
|
||||
Skip.IfNot(LiveSqlServer.IsEnabled, LiveSqlServer.SkipReason);
|
||||
|
||||
ApiKeyRecord record = SampleRecord("key-1");
|
||||
await InsertAsync(record);
|
||||
|
||||
ApiKeyRecord? found = await _store.FindByKeyIdAsync("key-1", CancellationToken.None);
|
||||
|
||||
Assert.NotNull(found);
|
||||
AssertRecordEqual(record, found!);
|
||||
}
|
||||
|
||||
[SkippableFact]
|
||||
public async Task FindByKeyId_ReturnsRevokedRecord()
|
||||
{
|
||||
Skip.IfNot(LiveSqlServer.IsEnabled, LiveSqlServer.SkipReason);
|
||||
|
||||
ApiKeyRecord record = SampleRecord("key-revoked") with
|
||||
{
|
||||
RevokedUtc = new DateTimeOffset(2026, 1, 2, 3, 4, 5, TimeSpan.Zero),
|
||||
};
|
||||
await InsertAsync(record);
|
||||
|
||||
ApiKeyRecord? found = await _store.FindByKeyIdAsync("key-revoked", CancellationToken.None);
|
||||
|
||||
Assert.NotNull(found);
|
||||
Assert.NotNull(found!.RevokedUtc);
|
||||
}
|
||||
|
||||
[SkippableFact]
|
||||
public async Task FindActiveByKeyId_RevokedKey_ReturnsNull()
|
||||
{
|
||||
Skip.IfNot(LiveSqlServer.IsEnabled, LiveSqlServer.SkipReason);
|
||||
|
||||
ApiKeyRecord record = SampleRecord("key-revoked") with
|
||||
{
|
||||
RevokedUtc = new DateTimeOffset(2026, 1, 2, 3, 4, 5, TimeSpan.Zero),
|
||||
};
|
||||
await InsertAsync(record);
|
||||
|
||||
ApiKeyRecord? found = await _store.FindActiveByKeyIdAsync("key-revoked", CancellationToken.None);
|
||||
|
||||
Assert.Null(found);
|
||||
}
|
||||
|
||||
[SkippableFact]
|
||||
public async Task FindActiveByKeyId_ActiveKey_ReturnsRecord()
|
||||
{
|
||||
Skip.IfNot(LiveSqlServer.IsEnabled, LiveSqlServer.SkipReason);
|
||||
|
||||
await InsertAsync(SampleRecord("key-active"));
|
||||
|
||||
ApiKeyRecord? found = await _store.FindActiveByKeyIdAsync("key-active", CancellationToken.None);
|
||||
|
||||
Assert.NotNull(found);
|
||||
}
|
||||
|
||||
[SkippableFact]
|
||||
public async Task FindByKeyId_UnknownKey_ReturnsNull()
|
||||
{
|
||||
Skip.IfNot(LiveSqlServer.IsEnabled, LiveSqlServer.SkipReason);
|
||||
|
||||
ApiKeyRecord? found = await _store.FindByKeyIdAsync("missing", CancellationToken.None);
|
||||
|
||||
Assert.Null(found);
|
||||
}
|
||||
|
||||
[SkippableFact]
|
||||
public async Task MarkUsed_ActiveKey_UpdatesLastUsed()
|
||||
{
|
||||
Skip.IfNot(LiveSqlServer.IsEnabled, LiveSqlServer.SkipReason);
|
||||
|
||||
await InsertAsync(SampleRecord("key-active"));
|
||||
var when = new DateTimeOffset(2026, 5, 31, 12, 0, 0, TimeSpan.Zero);
|
||||
|
||||
await _store.MarkUsedAsync("key-active", when, CancellationToken.None);
|
||||
|
||||
ApiKeyRecord? found = await _store.FindByKeyIdAsync("key-active", CancellationToken.None);
|
||||
Assert.Equal(when, found!.LastUsedUtc);
|
||||
}
|
||||
|
||||
[SkippableFact]
|
||||
public async Task MarkUsed_RevokedKey_DoesNotUpdateLastUsed()
|
||||
{
|
||||
Skip.IfNot(LiveSqlServer.IsEnabled, LiveSqlServer.SkipReason);
|
||||
|
||||
ApiKeyRecord record = SampleRecord("key-revoked") with
|
||||
{
|
||||
RevokedUtc = new DateTimeOffset(2026, 1, 2, 3, 4, 5, TimeSpan.Zero),
|
||||
};
|
||||
await InsertAsync(record);
|
||||
var when = new DateTimeOffset(2026, 5, 31, 12, 0, 0, TimeSpan.Zero);
|
||||
|
||||
await _store.MarkUsedAsync("key-revoked", when, CancellationToken.None);
|
||||
|
||||
ApiKeyRecord? found = await _store.FindByKeyIdAsync("key-revoked", CancellationToken.None);
|
||||
Assert.Null(found!.LastUsedUtc);
|
||||
}
|
||||
|
||||
// --- SQL-Server-specific: DATETIMEOFFSET(7) must not truncate to milliseconds ---
|
||||
|
||||
[SkippableFact]
|
||||
public async Task FindByKeyId_RoundTripsDateTimeOffsetToTheTick()
|
||||
{
|
||||
Skip.IfNot(LiveSqlServer.IsEnabled, LiveSqlServer.SkipReason);
|
||||
|
||||
// Sub-millisecond ticks: SQLite persists round-trip ("O") text and keeps them for free,
|
||||
// whereas SQL Server keeps them only because the columns are DATETIMEOFFSET(7) and the
|
||||
// parameters are bound as SqlDbType.DateTimeOffset. A DATETIME/DATETIME2(3) column or an
|
||||
// untyped parameter would silently round here.
|
||||
var created = new DateTimeOffset(2026, 3, 4, 5, 6, 7, TimeSpan.Zero).AddTicks(1234567);
|
||||
var expires = new DateTimeOffset(2027, 3, 4, 5, 6, 7, TimeSpan.Zero).AddTicks(7654321);
|
||||
ApiKeyRecord record = SampleRecord("key-ticks") with { CreatedUtc = created, ExpiresUtc = expires };
|
||||
await InsertAsync(record);
|
||||
|
||||
ApiKeyRecord? found = await _store.FindByKeyIdAsync("key-ticks", CancellationToken.None);
|
||||
|
||||
Assert.NotNull(found);
|
||||
Assert.Equal(created, found!.CreatedUtc);
|
||||
Assert.Equal(created.Ticks, found.CreatedUtc.Ticks);
|
||||
Assert.Equal(expires, found.ExpiresUtc);
|
||||
Assert.Equal(expires.Ticks, found.ExpiresUtc!.Value.Ticks);
|
||||
}
|
||||
|
||||
// --- keyId guard tests ---
|
||||
|
||||
[SkippableTheory]
|
||||
[InlineData(null)]
|
||||
[InlineData("")]
|
||||
[InlineData(" ")]
|
||||
public async Task FindByKeyId_NullOrWhitespaceKeyId_ThrowsArgumentException(string? keyId)
|
||||
{
|
||||
Skip.IfNot(LiveSqlServer.IsEnabled, LiveSqlServer.SkipReason);
|
||||
|
||||
// ArgumentNullException (null) and ArgumentException (empty/whitespace) are both acceptable;
|
||||
// ThrowIfNullOrWhiteSpace throws ArgumentNullException for null, ArgumentException for whitespace.
|
||||
await Assert.ThrowsAnyAsync<ArgumentException>(
|
||||
() => _store.FindByKeyIdAsync(keyId!, CancellationToken.None));
|
||||
}
|
||||
|
||||
[SkippableTheory]
|
||||
[InlineData(null)]
|
||||
[InlineData("")]
|
||||
[InlineData(" ")]
|
||||
public async Task FindActiveByKeyId_NullOrWhitespaceKeyId_ThrowsArgumentException(string? keyId)
|
||||
{
|
||||
Skip.IfNot(LiveSqlServer.IsEnabled, LiveSqlServer.SkipReason);
|
||||
|
||||
await Assert.ThrowsAnyAsync<ArgumentException>(
|
||||
() => _store.FindActiveByKeyIdAsync(keyId!, CancellationToken.None));
|
||||
}
|
||||
|
||||
[SkippableTheory]
|
||||
[InlineData(null)]
|
||||
[InlineData("")]
|
||||
[InlineData(" ")]
|
||||
public async Task MarkUsed_NullOrWhitespaceKeyId_ThrowsArgumentException(string? keyId)
|
||||
{
|
||||
Skip.IfNot(LiveSqlServer.IsEnabled, LiveSqlServer.SkipReason);
|
||||
|
||||
await Assert.ThrowsAnyAsync<ArgumentException>(
|
||||
() => _store.MarkUsedAsync(keyId!, DateTimeOffset.UtcNow, CancellationToken.None));
|
||||
}
|
||||
|
||||
[SkippableFact]
|
||||
public void ScopeSerializer_RoundTripsAndSortsOrdinally()
|
||||
{
|
||||
Skip.IfNot(LiveSqlServer.IsEnabled, LiveSqlServer.SkipReason);
|
||||
|
||||
var unsorted = new HashSet<string>(["zeta", "alpha", "mike"], StringComparer.Ordinal);
|
||||
var differentOrder = new HashSet<string>(["mike", "zeta", "alpha"], StringComparer.Ordinal);
|
||||
|
||||
string a = ScopeSerializer.Serialize(unsorted);
|
||||
string b = ScopeSerializer.Serialize(differentOrder);
|
||||
|
||||
// Equal sets must produce identical column text regardless of insertion order.
|
||||
Assert.Equal(a, b);
|
||||
Assert.Equal("""["alpha","mike","zeta"]""", a);
|
||||
|
||||
IReadOnlySet<string> roundTripped = ScopeSerializer.Deserialize(a);
|
||||
Assert.True(roundTripped.SetEquals(unsorted));
|
||||
}
|
||||
|
||||
[SkippableFact]
|
||||
public void ScopeSerializer_DeserializeNullOrEmpty_ReturnsEmptySet()
|
||||
{
|
||||
Skip.IfNot(LiveSqlServer.IsEnabled, LiveSqlServer.SkipReason);
|
||||
|
||||
Assert.Empty(ScopeSerializer.Deserialize(null));
|
||||
Assert.Empty(ScopeSerializer.Deserialize(""));
|
||||
}
|
||||
|
||||
// --- Auth-003: corrupt scopes JSON must fail closed (empty set), never throw JsonException ---
|
||||
|
||||
[SkippableTheory]
|
||||
[InlineData("not json at all")]
|
||||
[InlineData("{")]
|
||||
[InlineData("{\"a\":1}")] // valid JSON, but an object, not a string[]
|
||||
[InlineData("42")] // valid JSON, but a number
|
||||
[InlineData("[\"read\",")] // truncated/partial write
|
||||
public void ScopeSerializer_DeserializeMalformed_ReturnsEmptySet_DoesNotThrow(string value)
|
||||
{
|
||||
Skip.IfNot(LiveSqlServer.IsEnabled, LiveSqlServer.SkipReason);
|
||||
|
||||
// A poisoned scopes column (tampering, partial write, format change, buggy writer) must
|
||||
// degrade to a zero-scope set rather than throwing on the verification hot path.
|
||||
IReadOnlySet<string> scopes = ScopeSerializer.Deserialize(value);
|
||||
Assert.Empty(scopes);
|
||||
}
|
||||
|
||||
[SkippableFact]
|
||||
public async Task FindByKeyId_CorruptScopesColumn_ReturnsRecordWithEmptyScopes_DoesNotThrow()
|
||||
{
|
||||
Skip.IfNot(LiveSqlServer.IsEnabled, LiveSqlServer.SkipReason);
|
||||
|
||||
// Insert a row whose scopes column holds malformed (non-array) JSON, then read it through
|
||||
// the store. The store must NOT propagate a JsonException out of FindByKeyIdAsync (which the
|
||||
// verifier relies on for its "only exception path is cancellation" contract).
|
||||
await InsertWithRawScopesAsync("key-corrupt", scopesJson: "{ this is not valid json");
|
||||
|
||||
ApiKeyRecord? found = await _store.FindByKeyIdAsync("key-corrupt", CancellationToken.None);
|
||||
|
||||
Assert.NotNull(found);
|
||||
Assert.Empty(found!.Scopes);
|
||||
}
|
||||
|
||||
private static ApiKeyRecord SampleRecord(string keyId) => new(
|
||||
KeyId: keyId,
|
||||
KeyPrefix: "mxgw_ab12",
|
||||
SecretHash: [1, 2, 3, 4, 5, 6, 7, 8],
|
||||
DisplayName: "Test Key " + keyId,
|
||||
Scopes: new HashSet<string>(["read", "write"], StringComparer.Ordinal),
|
||||
ConstraintsJson: """{"ipAllow":["10.0.0.0/8"]}""",
|
||||
CreatedUtc: new DateTimeOffset(2026, 5, 1, 8, 30, 0, TimeSpan.Zero),
|
||||
LastUsedUtc: null,
|
||||
RevokedUtc: null);
|
||||
|
||||
private static void AssertRecordEqual(ApiKeyRecord expected, ApiKeyRecord actual)
|
||||
{
|
||||
Assert.Equal(expected.KeyId, actual.KeyId);
|
||||
Assert.Equal(expected.KeyPrefix, actual.KeyPrefix);
|
||||
Assert.Equal(expected.SecretHash, actual.SecretHash);
|
||||
Assert.Equal(expected.DisplayName, actual.DisplayName);
|
||||
Assert.True(expected.Scopes.SetEquals(actual.Scopes));
|
||||
Assert.Equal(expected.ConstraintsJson, actual.ConstraintsJson);
|
||||
Assert.Equal(expected.CreatedUtc, actual.CreatedUtc);
|
||||
Assert.Equal(expected.LastUsedUtc, actual.LastUsedUtc);
|
||||
Assert.Equal(expected.RevokedUtc, actual.RevokedUtc);
|
||||
}
|
||||
|
||||
private async Task InsertAsync(ApiKeyRecord record)
|
||||
{
|
||||
await using SqlConnection connection =
|
||||
await _factory.OpenConnectionAsync(CancellationToken.None);
|
||||
await using SqlCommand command = _factory.CreateCommand(connection, $"""
|
||||
INSERT INTO [{_schema}].[{SqlServerAuthSchema.ApiKeysTable}] (
|
||||
key_id, key_prefix, secret_hash, display_name, scopes,
|
||||
constraints, created_utc, last_used_utc, revoked_utc, expires_utc)
|
||||
VALUES (
|
||||
@key_id, @key_prefix, @secret_hash, @display_name, @scopes,
|
||||
@constraints, @created_utc, @last_used_utc, @revoked_utc, @expires_utc);
|
||||
""");
|
||||
command.Parameters.Add("@key_id", SqlDbType.NVarChar, 64).Value = record.KeyId;
|
||||
command.Parameters.Add("@key_prefix", SqlDbType.NVarChar, 16).Value = record.KeyPrefix;
|
||||
command.Parameters.Add("@secret_hash", SqlDbType.VarBinary, 64).Value = record.SecretHash;
|
||||
command.Parameters.Add("@display_name", SqlDbType.NVarChar, 256).Value = record.DisplayName;
|
||||
command.Parameters.Add("@scopes", SqlDbType.NVarChar, -1).Value = ScopeSerializer.Serialize(record.Scopes);
|
||||
command.Parameters.Add("@constraints", SqlDbType.NVarChar, -1).Value = (object?)record.ConstraintsJson ?? DBNull.Value;
|
||||
command.Parameters.Add("@created_utc", SqlDbType.DateTimeOffset).Value = record.CreatedUtc;
|
||||
command.Parameters.Add("@last_used_utc", SqlDbType.DateTimeOffset).Value = (object?)record.LastUsedUtc ?? DBNull.Value;
|
||||
command.Parameters.Add("@revoked_utc", SqlDbType.DateTimeOffset).Value = (object?)record.RevokedUtc ?? DBNull.Value;
|
||||
command.Parameters.Add("@expires_utc", SqlDbType.DateTimeOffset).Value = (object?)record.ExpiresUtc ?? DBNull.Value;
|
||||
await command.ExecuteNonQueryAsync(CancellationToken.None);
|
||||
}
|
||||
|
||||
private async Task InsertWithRawScopesAsync(string keyId, string scopesJson)
|
||||
{
|
||||
// Writes the scopes column verbatim (NOT via ScopeSerializer.Serialize) so a malformed
|
||||
// value can be persisted to simulate tampering / a partial or buggy write.
|
||||
await using SqlConnection connection =
|
||||
await _factory.OpenConnectionAsync(CancellationToken.None);
|
||||
await using SqlCommand command = _factory.CreateCommand(connection, $"""
|
||||
INSERT INTO [{_schema}].[{SqlServerAuthSchema.ApiKeysTable}] (
|
||||
key_id, key_prefix, secret_hash, display_name, scopes,
|
||||
constraints, created_utc, last_used_utc, revoked_utc, expires_utc)
|
||||
VALUES (
|
||||
@key_id, @key_prefix, @secret_hash, @display_name, @scopes,
|
||||
NULL, @created_utc, NULL, NULL, NULL);
|
||||
""");
|
||||
command.Parameters.Add("@key_id", SqlDbType.NVarChar, 64).Value = keyId;
|
||||
command.Parameters.Add("@key_prefix", SqlDbType.NVarChar, 16).Value = "mxgw";
|
||||
command.Parameters.Add("@secret_hash", SqlDbType.VarBinary, 64).Value = new byte[] { 1, 2, 3 };
|
||||
command.Parameters.Add("@display_name", SqlDbType.NVarChar, 256).Value = "Corrupt Key";
|
||||
command.Parameters.Add("@scopes", SqlDbType.NVarChar, -1).Value = scopesJson;
|
||||
command.Parameters.Add("@created_utc", SqlDbType.DateTimeOffset).Value = DateTimeOffset.UnixEpoch;
|
||||
await command.ExecuteNonQueryAsync(CancellationToken.None);
|
||||
}
|
||||
}
|
||||
+145
@@ -0,0 +1,145 @@
|
||||
using System.Globalization;
|
||||
using ZB.MOM.WW.Auth.ApiKeys.Sqlite;
|
||||
|
||||
namespace ZB.MOM.WW.Auth.ApiKeys.SqlServer.Tests.Live;
|
||||
|
||||
/// <summary>
|
||||
/// Live provisioning tests for <see cref="SqlServerApiKeyStoreMigrator"/>.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Every test provisions its own throwaway schema — the concurrency case in particular needs a
|
||||
/// virgin one, because the race the retry loop exists for only happens while the schema and tables
|
||||
/// do not yet exist. All schemas created by the class are dropped in <see cref="DisposeAsync"/>.
|
||||
/// </remarks>
|
||||
[Collection("live-sqlserver")]
|
||||
public sealed class SqlServerApiKeyStoreMigratorLiveTests : IAsyncLifetime
|
||||
{
|
||||
private readonly List<string> _schemas = [];
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task InitializeAsync() => Task.CompletedTask;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
foreach (string schema in _schemas)
|
||||
{
|
||||
await LiveSqlServer.DropSchemaAsync(schema);
|
||||
}
|
||||
}
|
||||
|
||||
private string NewSchema()
|
||||
{
|
||||
string schema = LiveSqlServer.NewSchemaName();
|
||||
_schemas.Add(schema);
|
||||
return schema;
|
||||
}
|
||||
|
||||
private static SqlServerApiKeyStoreMigrator MigratorFor(string schema) =>
|
||||
new(new AuthSqlServerConnectionFactory(LiveSqlServer.OptionsFor(schema)));
|
||||
|
||||
[SkippableFact]
|
||||
public async Task Migrate_OnEmptyDatabase_CreatesSchemaTablesAndVersionRow()
|
||||
{
|
||||
Skip.IfNot(LiveSqlServer.IsEnabled, LiveSqlServer.SkipReason);
|
||||
|
||||
string schema = NewSchema();
|
||||
|
||||
await MigratorFor(schema).MigrateAsync(CancellationToken.None);
|
||||
|
||||
Assert.Equal(
|
||||
1,
|
||||
Convert.ToInt32(
|
||||
await LiveSqlServer.ScalarAsync(
|
||||
$"SELECT COUNT(*) FROM sys.schemas WHERE name = N'{schema}'"),
|
||||
CultureInfo.InvariantCulture));
|
||||
|
||||
foreach (string table in new[]
|
||||
{
|
||||
SqlServerAuthSchema.SchemaVersionTable,
|
||||
SqlServerAuthSchema.ApiKeysTable,
|
||||
SqlServerAuthSchema.ApiKeyAuditTable,
|
||||
})
|
||||
{
|
||||
Assert.NotNull(
|
||||
await LiveSqlServer.ScalarAsync($"SELECT OBJECT_ID(N'[{schema}].[{table}]', N'U')"));
|
||||
}
|
||||
|
||||
Assert.Equal(
|
||||
SqlServerAuthSchema.CurrentVersion,
|
||||
Convert.ToInt32(
|
||||
await LiveSqlServer.ScalarAsync(
|
||||
$"SELECT version FROM [{schema}].[{SqlServerAuthSchema.SchemaVersionTable}] WHERE id = 1"),
|
||||
CultureInfo.InvariantCulture));
|
||||
}
|
||||
|
||||
[SkippableFact]
|
||||
public async Task Migrate_Twice_IsIdempotent()
|
||||
{
|
||||
Skip.IfNot(LiveSqlServer.IsEnabled, LiveSqlServer.SkipReason);
|
||||
|
||||
string schema = NewSchema();
|
||||
SqlServerApiKeyStoreMigrator migrator = MigratorFor(schema);
|
||||
|
||||
await migrator.MigrateAsync(CancellationToken.None);
|
||||
await migrator.MigrateAsync(CancellationToken.None);
|
||||
|
||||
Assert.Equal(
|
||||
1,
|
||||
Convert.ToInt32(
|
||||
await LiveSqlServer.ScalarAsync(
|
||||
$"SELECT COUNT(*) FROM [{schema}].[{SqlServerAuthSchema.SchemaVersionTable}]"),
|
||||
CultureInfo.InvariantCulture));
|
||||
Assert.Equal(
|
||||
SqlServerAuthSchema.CurrentVersion,
|
||||
Convert.ToInt32(
|
||||
await LiveSqlServer.ScalarAsync(
|
||||
$"SELECT version FROM [{schema}].[{SqlServerAuthSchema.SchemaVersionTable}] WHERE id = 1"),
|
||||
CultureInfo.InvariantCulture));
|
||||
}
|
||||
|
||||
[SkippableFact]
|
||||
public async Task Migrate_Concurrently_FromEightTasks_AllSucceed()
|
||||
{
|
||||
Skip.IfNot(LiveSqlServer.IsEnabled, LiveSqlServer.SkipReason);
|
||||
|
||||
// A virgin schema provisioned by eight nodes at once — the central-pair first boot, scaled
|
||||
// up. Each task gets its own factory (and therefore its own connection) so the DDL really
|
||||
// does run on eight sessions.
|
||||
string schema = NewSchema();
|
||||
|
||||
await Task.WhenAll(Enumerable.Range(0, 8).Select(_ =>
|
||||
Task.Run(() => MigratorFor(schema).MigrateAsync(CancellationToken.None))));
|
||||
|
||||
Assert.Equal(
|
||||
1,
|
||||
Convert.ToInt32(
|
||||
await LiveSqlServer.ScalarAsync(
|
||||
$"SELECT COUNT(*) FROM [{schema}].[{SqlServerAuthSchema.SchemaVersionTable}]"),
|
||||
CultureInfo.InvariantCulture));
|
||||
Assert.Equal(
|
||||
SqlServerAuthSchema.CurrentVersion,
|
||||
Convert.ToInt32(
|
||||
await LiveSqlServer.ScalarAsync(
|
||||
$"SELECT version FROM [{schema}].[{SqlServerAuthSchema.SchemaVersionTable}] WHERE id = 1"),
|
||||
CultureInfo.InvariantCulture));
|
||||
}
|
||||
|
||||
[SkippableFact]
|
||||
public async Task Migrate_WhenStoredVersionIsNewer_Throws()
|
||||
{
|
||||
Skip.IfNot(LiveSqlServer.IsEnabled, LiveSqlServer.SkipReason);
|
||||
|
||||
string schema = NewSchema();
|
||||
SqlServerApiKeyStoreMigrator migrator = MigratorFor(schema);
|
||||
|
||||
await migrator.MigrateAsync(CancellationToken.None);
|
||||
await LiveSqlServer.ExecuteAsync(
|
||||
$"UPDATE [{schema}].[{SqlServerAuthSchema.SchemaVersionTable}] SET version = 99 WHERE id = 1");
|
||||
|
||||
AuthStoreMigrationException exception = await Assert.ThrowsAsync<AuthStoreMigrationException>(
|
||||
() => migrator.MigrateAsync(CancellationToken.None));
|
||||
|
||||
Assert.Contains("99", exception.Message, StringComparison.Ordinal);
|
||||
}
|
||||
}
|
||||
+283
@@ -0,0 +1,283 @@
|
||||
using Microsoft.Data.Sqlite;
|
||||
using ZB.MOM.WW.Auth.Abstractions.ApiKeys;
|
||||
using ZB.MOM.WW.Auth.ApiKeys.Sqlite;
|
||||
|
||||
namespace ZB.MOM.WW.Auth.ApiKeys.SqlServer.Tests.Live;
|
||||
|
||||
/// <summary>
|
||||
/// Live tests for <see cref="SqliteApiKeyStoreImporter"/> — the one-shot per-node SQLite to shared
|
||||
/// SQL Server copy.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Each test owns a throwaway SQL Server schema AND a throwaway SQLite file under the temp
|
||||
/// directory; both are torn down in <see cref="DisposeAsync"/>, so a failed run leaves nothing
|
||||
/// behind on a shared database or the developer's disk.
|
||||
/// </remarks>
|
||||
[Collection("live-sqlserver")]
|
||||
public sealed class SqliteApiKeyStoreImporterLiveTests : IAsyncLifetime
|
||||
{
|
||||
private readonly string _schema = LiveSqlServer.NewSchemaName();
|
||||
private readonly string _sqlitePath =
|
||||
Path.Combine(Path.GetTempPath(), $"zbauth-import-{Guid.NewGuid():N}.db");
|
||||
|
||||
private AuthSqlServerConnectionFactory _factory = null!;
|
||||
private SqlServerApiKeyAdminStore _sqlAdmin = null!;
|
||||
private SqlServerApiKeyStore _sqlRead = null!;
|
||||
private SqlServerApiKeyAuditStore _sqlAudit = null!;
|
||||
private SqliteApiKeyStoreImporter _importer = null!;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
if (!LiveSqlServer.IsEnabled)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_factory = new AuthSqlServerConnectionFactory(LiveSqlServer.OptionsFor(_schema));
|
||||
await new SqlServerApiKeyStoreMigrator(_factory).MigrateAsync(CancellationToken.None);
|
||||
_sqlAdmin = new SqlServerApiKeyAdminStore(_factory);
|
||||
_sqlRead = new SqlServerApiKeyStore(_factory);
|
||||
_sqlAudit = new SqlServerApiKeyAuditStore(_factory);
|
||||
_importer = new SqliteApiKeyStoreImporter(_factory);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
// SQLite pools connections by connection string; the handle must be released before the
|
||||
// file can be removed cleanly.
|
||||
SqliteConnection.ClearAllPools();
|
||||
|
||||
foreach (string path in new[] { _sqlitePath, _sqlitePath + "-wal", _sqlitePath + "-shm" })
|
||||
{
|
||||
if (File.Exists(path))
|
||||
{
|
||||
File.Delete(path);
|
||||
}
|
||||
}
|
||||
|
||||
await LiveSqlServer.DropSchemaAsync(_schema);
|
||||
}
|
||||
|
||||
[SkippableFact]
|
||||
public async Task Import_CopiesKeysAndAuditRows_AndReturnsCounts()
|
||||
{
|
||||
Skip.IfNot(LiveSqlServer.IsEnabled, LiveSqlServer.SkipReason);
|
||||
|
||||
(ApiKeyRecord keyA, ApiKeyRecord keyB) = await SeedSqliteAsync();
|
||||
|
||||
ApiKeyImportResult result = await _importer.ImportAsync(_sqlitePath, CancellationToken.None);
|
||||
|
||||
Assert.True(result.SourceFound);
|
||||
Assert.Equal(2, result.KeysInserted);
|
||||
Assert.Equal(0, result.KeysSkipped);
|
||||
Assert.Equal(3, result.AuditInserted);
|
||||
Assert.Equal(0, result.AuditSkipped);
|
||||
|
||||
await AssertRecordMatchesAsync(keyA);
|
||||
await AssertRecordMatchesAsync(keyB);
|
||||
|
||||
IReadOnlyList<ApiKeyAuditEntry> audit = await _sqlAudit.ListRecentAsync(10, CancellationToken.None);
|
||||
Assert.Equal(3, audit.Count);
|
||||
Assert.Contains(audit, e => e.KeyId is null && e.EventType == "auth_failed");
|
||||
Assert.Contains(audit, e => e.KeyId == "key-a" && e.EventType == "created");
|
||||
Assert.Contains(audit, e => e.KeyId == "key-b" && e.EventType == "created");
|
||||
}
|
||||
|
||||
[SkippableFact]
|
||||
public async Task Import_Twice_IsIdempotent()
|
||||
{
|
||||
Skip.IfNot(LiveSqlServer.IsEnabled, LiveSqlServer.SkipReason);
|
||||
|
||||
await SeedSqliteAsync();
|
||||
|
||||
await _importer.ImportAsync(_sqlitePath, CancellationToken.None);
|
||||
ApiKeyImportResult second = await _importer.ImportAsync(_sqlitePath, CancellationToken.None);
|
||||
|
||||
Assert.True(second.SourceFound);
|
||||
Assert.Equal(0, second.KeysInserted);
|
||||
Assert.Equal(2, second.KeysSkipped);
|
||||
Assert.Equal(0, second.AuditInserted);
|
||||
Assert.Equal(3, second.AuditSkipped);
|
||||
|
||||
Assert.Equal(2, (await _sqlAdmin.ListAsync(CancellationToken.None)).Count);
|
||||
Assert.Equal(3, (await _sqlAudit.ListRecentAsync(10, CancellationToken.None)).Count);
|
||||
}
|
||||
|
||||
[SkippableFact]
|
||||
public async Task Import_UnionsWithExistingRows()
|
||||
{
|
||||
Skip.IfNot(LiveSqlServer.IsEnabled, LiveSqlServer.SkipReason);
|
||||
|
||||
var lastUsed = new DateTimeOffset(2026, 7, 4, 12, 0, 0, TimeSpan.Zero);
|
||||
ApiKeyRecord keyC = SampleRecord("key-c") with { LastUsedUtc = lastUsed };
|
||||
await _sqlAdmin.CreateAsync(keyC, CancellationToken.None);
|
||||
|
||||
await SeedSqliteAsync();
|
||||
|
||||
ApiKeyImportResult result = await _importer.ImportAsync(_sqlitePath, CancellationToken.None);
|
||||
|
||||
Assert.Equal(2, result.KeysInserted);
|
||||
Assert.Equal(0, result.KeysSkipped);
|
||||
|
||||
IReadOnlyList<ApiKeyListItem> listed = await _sqlAdmin.ListAsync(CancellationToken.None);
|
||||
Assert.Equal(
|
||||
["key-a", "key-b", "key-c"],
|
||||
listed.Select(k => k.KeyId).OrderBy(k => k, StringComparer.Ordinal));
|
||||
|
||||
// The pre-existing row is untouched — the importer only ever inserts.
|
||||
Assert.Equal(lastUsed, Assert.Single(listed, k => k.KeyId == "key-c").LastUsedUtc);
|
||||
}
|
||||
|
||||
[SkippableFact]
|
||||
public async Task Import_MissingFile_ReturnsZeroWithoutThrowing()
|
||||
{
|
||||
Skip.IfNot(LiveSqlServer.IsEnabled, LiveSqlServer.SkipReason);
|
||||
|
||||
ApiKeyImportResult result = await _importer.ImportAsync(
|
||||
Path.Combine(Path.GetTempPath(), $"zbauth-absent-{Guid.NewGuid():N}.db"),
|
||||
CancellationToken.None);
|
||||
|
||||
Assert.False(result.SourceFound);
|
||||
Assert.Equal(0, result.KeysInserted);
|
||||
Assert.Equal(0, result.KeysSkipped);
|
||||
Assert.Equal(0, result.AuditInserted);
|
||||
Assert.Equal(0, result.AuditSkipped);
|
||||
}
|
||||
|
||||
[SkippableFact]
|
||||
public async Task Import_PreV3FileWithoutExpiresColumn_ReadsExpiryAsNull()
|
||||
{
|
||||
Skip.IfNot(LiveSqlServer.IsEnabled, LiveSqlServer.SkipReason);
|
||||
|
||||
await CreatePreV3SqliteFileAsync();
|
||||
|
||||
ApiKeyImportResult result = await _importer.ImportAsync(_sqlitePath, CancellationToken.None);
|
||||
|
||||
Assert.True(result.SourceFound);
|
||||
Assert.Equal(1, result.KeysInserted);
|
||||
|
||||
ApiKeyRecord? found = await _sqlRead.FindByKeyIdAsync("key-old", CancellationToken.None);
|
||||
Assert.NotNull(found);
|
||||
Assert.Null(found!.ExpiresUtc);
|
||||
Assert.Equal("legacy key", found.DisplayName);
|
||||
Assert.Equal(new DateTimeOffset(2026, 1, 2, 3, 4, 5, TimeSpan.Zero), found.CreatedUtc);
|
||||
}
|
||||
|
||||
// --- helpers ---
|
||||
|
||||
/// <summary>
|
||||
/// Seeds the throwaway SQLite file with two keys (one revoked, one with an expiry) and three
|
||||
/// audit rows (one of them key-less), then returns the two key records as SQLite holds them.
|
||||
/// </summary>
|
||||
private async Task<(ApiKeyRecord KeyA, ApiKeyRecord KeyB)> SeedSqliteAsync()
|
||||
{
|
||||
var sqliteFactory = new AuthSqliteConnectionFactory(_sqlitePath);
|
||||
await new SqliteAuthStoreMigrator(sqliteFactory).MigrateAsync(CancellationToken.None);
|
||||
|
||||
var admin = new SqliteApiKeyAdminStore(sqliteFactory);
|
||||
var audit = new SqliteApiKeyAuditStore(sqliteFactory);
|
||||
var read = new SqliteApiKeyStore(sqliteFactory);
|
||||
|
||||
ApiKeyRecord keyA = SampleRecord("key-a");
|
||||
ApiKeyRecord keyB = SampleRecord("key-b") with
|
||||
{
|
||||
ExpiresUtc = new DateTimeOffset(2027, 3, 1, 0, 0, 0, TimeSpan.Zero),
|
||||
};
|
||||
|
||||
await admin.CreateAsync(keyA, CancellationToken.None);
|
||||
await admin.CreateAsync(keyB, CancellationToken.None);
|
||||
await admin.RevokeAsync("key-a", new DateTimeOffset(2026, 6, 1, 7, 8, 9, TimeSpan.Zero), CancellationToken.None);
|
||||
|
||||
await audit.AppendAsync(
|
||||
new ApiKeyAuditEntry("key-a", "created", "10.0.0.1", new DateTimeOffset(2026, 5, 1, 8, 30, 0, TimeSpan.Zero), "by admin"),
|
||||
CancellationToken.None);
|
||||
await audit.AppendAsync(
|
||||
new ApiKeyAuditEntry("key-b", "created", null, new DateTimeOffset(2026, 5, 1, 8, 31, 0, TimeSpan.Zero), null),
|
||||
CancellationToken.None);
|
||||
await audit.AppendAsync(
|
||||
new ApiKeyAuditEntry(null, "auth_failed", "10.0.0.9", new DateTimeOffset(2026, 5, 2, 9, 0, 0, TimeSpan.Zero), "unknown key"),
|
||||
CancellationToken.None);
|
||||
|
||||
// Re-read so the assertions compare against exactly what SQLite holds, revocation included.
|
||||
ApiKeyRecord storedA = (await read.FindByKeyIdAsync("key-a", CancellationToken.None))!;
|
||||
ApiKeyRecord storedB = (await read.FindByKeyIdAsync("key-b", CancellationToken.None))!;
|
||||
|
||||
return (storedA, storedB);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes a v2-shaped SQLite file by hand — <c>api_keys</c> WITHOUT <c>expires_utc</c> — and
|
||||
/// inserts one key row, reproducing a store created before schema v3.
|
||||
/// </summary>
|
||||
private async Task CreatePreV3SqliteFileAsync()
|
||||
{
|
||||
await using var connection = new SqliteConnection(
|
||||
new SqliteConnectionStringBuilder { DataSource = _sqlitePath }.ToString());
|
||||
await connection.OpenAsync();
|
||||
|
||||
await using SqliteCommand ddl = connection.CreateCommand();
|
||||
ddl.CommandText = """
|
||||
CREATE TABLE api_keys (
|
||||
key_id TEXT PRIMARY KEY,
|
||||
key_prefix TEXT NOT NULL,
|
||||
secret_hash BLOB NOT NULL,
|
||||
display_name TEXT NOT NULL,
|
||||
scopes TEXT NOT NULL,
|
||||
constraints TEXT NULL,
|
||||
created_utc TEXT NOT NULL,
|
||||
last_used_utc TEXT NULL,
|
||||
revoked_utc TEXT NULL
|
||||
);
|
||||
CREATE TABLE api_key_audit (
|
||||
audit_id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
key_id TEXT NULL,
|
||||
event_type TEXT NOT NULL,
|
||||
remote_address TEXT NULL,
|
||||
created_utc TEXT NOT NULL,
|
||||
details TEXT NULL
|
||||
);
|
||||
""";
|
||||
await ddl.ExecuteNonQueryAsync();
|
||||
|
||||
await using SqliteCommand insert = connection.CreateCommand();
|
||||
insert.CommandText = """
|
||||
INSERT INTO api_keys (
|
||||
key_id, key_prefix, secret_hash, display_name, scopes,
|
||||
constraints, created_utc, last_used_utc, revoked_utc)
|
||||
VALUES ('key-old', 'sbk_old1', $hash, 'legacy key', 'read', NULL, $created, NULL, NULL);
|
||||
""";
|
||||
insert.Parameters.Add("$hash", SqliteType.Blob).Value = new byte[] { 4, 5, 6 };
|
||||
insert.Parameters.AddWithValue(
|
||||
"$created", new DateTimeOffset(2026, 1, 2, 3, 4, 5, TimeSpan.Zero).ToString("O"));
|
||||
await insert.ExecuteNonQueryAsync();
|
||||
}
|
||||
|
||||
private async Task AssertRecordMatchesAsync(ApiKeyRecord expected)
|
||||
{
|
||||
ApiKeyRecord? actual = await _sqlRead.FindByKeyIdAsync(expected.KeyId, CancellationToken.None);
|
||||
|
||||
Assert.NotNull(actual);
|
||||
Assert.Equal(expected.KeyPrefix, actual!.KeyPrefix);
|
||||
Assert.True(expected.SecretHash.SequenceEqual(actual.SecretHash));
|
||||
Assert.Equal(expected.DisplayName, actual.DisplayName);
|
||||
Assert.True(expected.Scopes.SetEquals(actual.Scopes));
|
||||
Assert.Equal(expected.ConstraintsJson, actual.ConstraintsJson);
|
||||
Assert.Equal(expected.CreatedUtc, actual.CreatedUtc);
|
||||
Assert.Equal(expected.LastUsedUtc, actual.LastUsedUtc);
|
||||
Assert.Equal(expected.RevokedUtc, actual.RevokedUtc);
|
||||
Assert.Equal(expected.ExpiresUtc, actual.ExpiresUtc);
|
||||
}
|
||||
|
||||
private static ApiKeyRecord SampleRecord(string keyId) => new(
|
||||
KeyId: keyId,
|
||||
KeyPrefix: "sbk_ab12",
|
||||
SecretHash: [1, 2, 3, 4, 5, 6, 7, 8],
|
||||
DisplayName: "Test Key " + keyId,
|
||||
Scopes: new HashSet<string>(["read", "write"], StringComparer.Ordinal),
|
||||
ConstraintsJson: """{"ipAllow":["10.0.0.0/8"]}""",
|
||||
CreatedUtc: new DateTimeOffset(2026, 5, 1, 8, 30, 0, TimeSpan.Zero),
|
||||
LastUsedUtc: null,
|
||||
RevokedUtc: null);
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
namespace ZB.MOM.WW.Auth.ApiKeys.SqlServer.Tests;
|
||||
|
||||
public sealed class SqlServerApiKeyOptionsTests
|
||||
{
|
||||
[Fact]
|
||||
public void Validate_RejectsMissingConnectionString() =>
|
||||
Assert.Throws<InvalidOperationException>(() => new SqlServerApiKeyOptions { ConnectionString = " " }.Validate());
|
||||
|
||||
[Fact]
|
||||
public void Validate_RejectsUnsafeSchemaName() =>
|
||||
Assert.Throws<InvalidOperationException>(() => new SqlServerApiKeyOptions { ConnectionString = "Server=x", Schema = "zb;auth" }.Validate());
|
||||
|
||||
[Fact]
|
||||
public void Schema_DefaultsToZbauth() =>
|
||||
Assert.Equal("zbauth", new SqlServerApiKeyOptions().Schema);
|
||||
}
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Options;
|
||||
using ZB.MOM.WW.Auth.Abstractions.ApiKeys;
|
||||
using ZB.MOM.WW.Auth.ApiKeys.SqlServer.DependencyInjection;
|
||||
|
||||
namespace ZB.MOM.WW.Auth.ApiKeys.SqlServer.Tests;
|
||||
|
||||
public sealed class SqlServerApiKeyServiceCollectionExtensionsTests
|
||||
{
|
||||
private static IConfiguration MinimalConfig() =>
|
||||
new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string?>
|
||||
{
|
||||
["ApiKeys:TokenPrefix"] = "sbk",
|
||||
["ApiKeys:PepperSecretName"] = "Pepper",
|
||||
["Pepper"] = "0123456789abcdef",
|
||||
["ApiKeys:SqlServer:ConnectionString"] = "Server=unused;TrustServerCertificate=true",
|
||||
}).Build();
|
||||
|
||||
[Fact]
|
||||
public void AddZbApiKeyAuthSqlServer_DisplacesSqliteStoresAndMigrator()
|
||||
{
|
||||
var services = new ServiceCollection();
|
||||
services.AddZbApiKeyAuthSqlServer(MinimalConfig(), "ApiKeys", "ApiKeys:SqlServer");
|
||||
using ServiceProvider sp = services.BuildServiceProvider();
|
||||
|
||||
Assert.IsType<SqlServerApiKeyStore>(sp.GetRequiredService<IApiKeyStore>());
|
||||
Assert.IsType<SqlServerApiKeyAdminStore>(sp.GetRequiredService<IApiKeyAdminStore>());
|
||||
Assert.IsType<SqlServerApiKeyAuditStore>(sp.GetRequiredService<IApiKeyAuditStore>());
|
||||
Assert.IsType<SqlServerApiKeyStoreMigrator>(sp.GetRequiredService<IApiKeyStoreMigrator>());
|
||||
Assert.NotNull(sp.GetRequiredService<SqliteApiKeyStoreImporter>());
|
||||
Assert.NotNull(sp.GetRequiredService<IApiKeyVerifier>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AddZbApiKeyAuthSqlServer_BindsSqlServerOptionsFromSection()
|
||||
{
|
||||
var config = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string?>
|
||||
{
|
||||
["ApiKeys:TokenPrefix"] = "sbk",
|
||||
["ApiKeys:PepperSecretName"] = "Pepper",
|
||||
["Pepper"] = "0123456789abcdef",
|
||||
["ApiKeys:SqlServer:ConnectionString"] = "Server=my-shared-sql;TrustServerCertificate=true",
|
||||
["ApiKeys:SqlServer:Schema"] = "zbauth_custom",
|
||||
}).Build();
|
||||
var services = new ServiceCollection();
|
||||
services.AddZbApiKeyAuthSqlServer(config, "ApiKeys", "ApiKeys:SqlServer");
|
||||
using ServiceProvider sp = services.BuildServiceProvider();
|
||||
|
||||
SqlServerApiKeyOptions options = sp.GetRequiredService<IOptions<SqlServerApiKeyOptions>>().Value;
|
||||
Assert.Equal("Server=my-shared-sql;TrustServerCertificate=true", options.ConnectionString);
|
||||
Assert.Equal("zbauth_custom", options.Schema);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AddZbApiKeyAuthSqlServer_RegistersMigrationHostedService()
|
||||
{
|
||||
var services = new ServiceCollection();
|
||||
services.AddZbApiKeyAuthSqlServer(MinimalConfig(), "ApiKeys", "ApiKeys:SqlServer");
|
||||
using ServiceProvider sp = services.BuildServiceProvider();
|
||||
|
||||
IEnumerable<IHostedService> hostedServices = sp.GetServices<IHostedService>();
|
||||
Assert.Contains(hostedServices, s => s.GetType().Name == "ApiKeyMigrationHostedService");
|
||||
}
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
namespace ZB.MOM.WW.Auth.ApiKeys.SqlServer.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Offline pins for the migrator's retry classification. A <see cref="Microsoft.Data.SqlClient.SqlException"/>
|
||||
/// cannot be constructed normally, so the error-number predicate is extracted as an internal static
|
||||
/// and pinned here by number; the concurrent-provision behaviour itself is exercised by the
|
||||
/// env-gated live suite. These run on any machine, so the retry filter stays pinned even when the
|
||||
/// live suite skips.
|
||||
/// </summary>
|
||||
public sealed class SqlServerApiKeyStoreMigratorTests
|
||||
{
|
||||
/// <summary>
|
||||
/// The provisioning-race outcomes the ScadaBridge central shared-store live gate (2026-08-07)
|
||||
/// proved reachable — or that the multi-statement DDL makes reachable — when N nodes provision
|
||||
/// one virgin database at once. Losing such a race means the object now exists, which is the
|
||||
/// desired end state, so a retry of the idempotent IF NOT EXISTS path must be taken.
|
||||
/// </summary>
|
||||
/// <param name="errorNumber">The SQL Server error number under test.</param>
|
||||
[Theory]
|
||||
[InlineData(1205)] // deadlock victim
|
||||
[InlineData(2714)] // "There is already an object named ..." — lost CREATE SCHEMA/TABLE (the live-gate defect)
|
||||
[InlineData(1913)] // "index ... already exists" — lost CREATE INDEX
|
||||
[InlineData(2627)] // PK violation — lost schema_version MERGE-insert
|
||||
public void Provisioning_race_error_numbers_are_retryable(int errorNumber)
|
||||
=> Assert.True(SqlServerApiKeyStoreMigrator.IsRetryableMigrationErrorNumber(errorNumber));
|
||||
|
||||
/// <summary>
|
||||
/// Errors that reproduce identically on retry must propagate so the node fails closed instead
|
||||
/// of spinning through the retry budget against a genuine misconfiguration.
|
||||
/// </summary>
|
||||
/// <param name="errorNumber">The SQL Server error number under test.</param>
|
||||
[Theory]
|
||||
[InlineData(2705)] // duplicate column — unreachable from the race (single CREATE TABLE statement)
|
||||
[InlineData(208)] // invalid object name
|
||||
[InlineData(229)] // permission denied
|
||||
[InlineData(2759)] // "CREATE SCHEMA failed due to previous errors" — retryable only via its companion 2714
|
||||
[InlineData(4060)] // cannot open database
|
||||
[InlineData(18456)] // login failed
|
||||
[InlineData(0)]
|
||||
[InlineData(-2)] // client-side timeout
|
||||
public void Non_race_error_numbers_are_not_retryable(int errorNumber)
|
||||
=> Assert.False(SqlServerApiKeyStoreMigrator.IsRetryableMigrationErrorNumber(errorNumber));
|
||||
}
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
using ZB.MOM.WW.Auth.Abstractions.ApiKeys;
|
||||
|
||||
namespace ZB.MOM.WW.Auth.ApiKeys.SqlServer.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Auth-008 (scadaproj#46), the offline half: a value longer than its column is rejected or treated
|
||||
/// as absent BEFORE any connection is opened. Every <c>SqlParameter</c> carries an explicit size, and
|
||||
/// SqlClient truncates an over-length value to that size silently — so a 70-character key id was
|
||||
/// stored as its first 64 characters, and a different 70-character id sharing that prefix then
|
||||
/// "found" it. These tests point at a refused loopback port: pre-fix they reach the network and throw
|
||||
/// <c>SqlException</c>; post-fix nothing is sent.
|
||||
/// </summary>
|
||||
public sealed class SqlServerColumnLimitTests
|
||||
{
|
||||
private static readonly AuthSqlServerConnectionFactory Unreachable = new(new SqlServerApiKeyOptions
|
||||
{
|
||||
ConnectionString = "Server=tcp:127.0.0.1,1;Connect Timeout=3;ConnectRetryCount=0;TrustServerCertificate=true",
|
||||
});
|
||||
|
||||
private static readonly string LongKeyId = new('k', 65);
|
||||
|
||||
private static ApiKeyRecord Record(string keyId = "key-1", string prefix = "sbk", string displayName = "Key") => new(
|
||||
KeyId: keyId,
|
||||
KeyPrefix: prefix,
|
||||
SecretHash: [1, 2, 3],
|
||||
DisplayName: displayName,
|
||||
Scopes: new HashSet<string>(StringComparer.Ordinal),
|
||||
ConstraintsJson: null,
|
||||
CreatedUtc: DateTimeOffset.UnixEpoch,
|
||||
LastUsedUtc: null,
|
||||
RevokedUtc: null);
|
||||
|
||||
public static TheoryData<ApiKeyRecord, string> OverLength() => new()
|
||||
{
|
||||
{ Record(keyId: LongKeyId), "KeyId" },
|
||||
{ Record(prefix: new string('p', 17)), "KeyPrefix" },
|
||||
{ Record(displayName: new string('d', 257)), "DisplayName" },
|
||||
};
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(OverLength))]
|
||||
public async Task Create_OverLengthValue_IsRejected_NotTruncated(ApiKeyRecord record, string field)
|
||||
{
|
||||
var store = new SqlServerApiKeyAdminStore(Unreachable);
|
||||
|
||||
var ex = await Assert.ThrowsAsync<ArgumentException>(() => store.CreateAsync(record, CancellationToken.None));
|
||||
Assert.Contains(field, ex.Message, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Create_AtTheColumnLimits_ReachesTheDatabase()
|
||||
{
|
||||
// Positive control: values exactly at the limits are not rejected — the call gets as far as
|
||||
// the (unreachable) server.
|
||||
var store = new SqlServerApiKeyAdminStore(Unreachable);
|
||||
var record = Record(keyId: new string('k', 64), prefix: new string('p', 16), displayName: new string('d', 256));
|
||||
|
||||
await Assert.ThrowsAsync<Microsoft.Data.SqlClient.SqlException>(() => store.CreateAsync(record, CancellationToken.None));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Lookups_OfAnOverLengthKeyId_FindNothing_WithoutQuerying()
|
||||
{
|
||||
var read = new SqlServerApiKeyStore(Unreachable);
|
||||
var admin = new SqlServerApiKeyAdminStore(Unreachable);
|
||||
var now = DateTimeOffset.UnixEpoch;
|
||||
|
||||
Assert.Null(await read.FindByKeyIdAsync(LongKeyId, CancellationToken.None));
|
||||
Assert.Null(await read.FindActiveByKeyIdAsync(LongKeyId, CancellationToken.None));
|
||||
await read.MarkUsedAsync(LongKeyId, now, CancellationToken.None);
|
||||
Assert.False(await admin.RevokeAsync(LongKeyId, now, CancellationToken.None));
|
||||
Assert.False(await admin.RotateAsync(LongKeyId, [1], CancellationToken.None));
|
||||
Assert.False(await admin.SetScopesAsync(LongKeyId, new HashSet<string>(), CancellationToken.None));
|
||||
Assert.False(await admin.SetEnabledAsync(LongKeyId, true, now, CancellationToken.None));
|
||||
Assert.False(await admin.DeleteAsync(LongKeyId, CancellationToken.None));
|
||||
}
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
using ZB.MOM.WW.Auth.Abstractions.ApiKeys;
|
||||
|
||||
namespace ZB.MOM.WW.Auth.ApiKeys.SqlServer.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Auth-010 (scadaproj#46), end to end through the real SQL Server store with no server: the shared
|
||||
/// store being unreachable (failover, lost route) must come back from <c>VerifyAsync</c> as a
|
||||
/// structured <see cref="ApiKeyFailure.StoreUnavailable"/>, not as a <c>SqlException</c> that
|
||||
/// surfaces as an unaudited 500. Offline: it dials a refused local port.
|
||||
/// </summary>
|
||||
public sealed class SqlServerUnreachableVerifierTests
|
||||
{
|
||||
private sealed class Pepper : IApiKeyPepperProvider
|
||||
{
|
||||
public string? GetPepper() => "0123456789abcdef";
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task VerifyAsync_AgainstAnUnreachableSqlServer_ReturnsStoreUnavailable()
|
||||
{
|
||||
var factory = new AuthSqlServerConnectionFactory(new SqlServerApiKeyOptions
|
||||
{
|
||||
// Port 1 on loopback refuses immediately; no retries, so the test stays fast.
|
||||
ConnectionString = "Server=tcp:127.0.0.1,1;Connect Timeout=3;ConnectRetryCount=0;TrustServerCertificate=true",
|
||||
});
|
||||
var verifier = new ApiKeyVerifier(
|
||||
new ApiKeyOptions { TokenPrefix = "sbk" }, new SqlServerApiKeyStore(factory), new Pepper());
|
||||
|
||||
var result = await verifier.VerifyAsync("sbk_line1_supersecretvalue", CancellationToken.None);
|
||||
|
||||
Assert.False(result.Succeeded);
|
||||
Assert.Equal(ApiKeyFailure.StoreUnavailable, result.Failure);
|
||||
}
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<IsPackable>false</IsPackable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="coverlet.collector" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" />
|
||||
<PackageReference Include="xunit" />
|
||||
<PackageReference Include="xunit.runner.visualstudio" />
|
||||
<!-- Live tests (Task 3+) skip rather than fail when AUTH_SQLSERVER_CONNSTR is unset. -->
|
||||
<PackageReference Include="Xunit.SkippableFact" />
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection" />
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration" />
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" />
|
||||
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Using Include="Xunit" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\src\ZB.MOM.WW.Auth.ApiKeys.SqlServer\ZB.MOM.WW.Auth.ApiKeys.SqlServer.csproj" />
|
||||
<ProjectReference Include="..\..\src\ZB.MOM.WW.Auth.ApiKeys\ZB.MOM.WW.Auth.ApiKeys.csproj" />
|
||||
<ProjectReference Include="..\..\src\ZB.MOM.WW.Auth.Abstractions\ZB.MOM.WW.Auth.Abstractions.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -163,7 +163,7 @@ public sealed class ApiKeyAdminCommandsTests : IAsyncLifetime
|
||||
|
||||
int auditCountBefore = (await _audit.ListRecentAsync(50, CancellationToken.None)).Count;
|
||||
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(() => commands.CreateKeyAsync(
|
||||
await Assert.ThrowsAsync<ApiKeyPepperUnavailableException>(() => commands.CreateKeyAsync(
|
||||
"key-x",
|
||||
"No Pepper",
|
||||
new HashSet<string>(StringComparer.Ordinal),
|
||||
@@ -297,6 +297,52 @@ public sealed class ApiKeyAdminCommandsTests : IAsyncLifetime
|
||||
Assert.Equal("not-found", auditRow.Details);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task PepperUnavailable_IsStillCatchableAsInvalidOperationException_WithOriginalMessage()
|
||||
{
|
||||
// Back-compat: consumers that caught InvalidOperationException before the typed exception
|
||||
// existed must keep working, for both create and rotate.
|
||||
ApiKeyAdminCommands setup = BuildCommands(pepper: Pepper);
|
||||
await setup.InitDbAsync(null, CancellationToken.None);
|
||||
await setup.CreateKeyAsync("key-bc", "BC", new HashSet<string>(StringComparer.Ordinal), null, null, CancellationToken.None);
|
||||
ApiKeyAdminCommands nopepper = BuildCommands(pepper: null);
|
||||
|
||||
InvalidOperationException create = await Assert.ThrowsAnyAsync<InvalidOperationException>(() =>
|
||||
nopepper.CreateKeyAsync("key-bc2", "BC2", new HashSet<string>(StringComparer.Ordinal), null, null, CancellationToken.None));
|
||||
InvalidOperationException rotate = await Assert.ThrowsAnyAsync<InvalidOperationException>(() =>
|
||||
nopepper.RotateKeyAsync("key-bc", null, CancellationToken.None));
|
||||
|
||||
Assert.IsType<ApiKeyPepperUnavailableException>(create);
|
||||
Assert.IsType<ApiKeyPepperUnavailableException>(rotate);
|
||||
Assert.Equal("pepper unavailable", create.Message);
|
||||
Assert.Equal("pepper unavailable", rotate.Message);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)]
|
||||
[InlineData("")]
|
||||
[InlineData(" ")]
|
||||
public async Task CreateKey_NullEmptyOrWhitespacePepper_ThrowsTypedException(string? pepper)
|
||||
{
|
||||
ApiKeyAdminCommands commands = BuildCommands(pepper);
|
||||
await new ApiKeyAdminCommands(_options, _admin, _audit, new FakePepperProvider(Pepper), _migrator)
|
||||
.InitDbAsync(null, CancellationToken.None);
|
||||
|
||||
await Assert.ThrowsAsync<ApiKeyPepperUnavailableException>(() => commands.CreateKeyAsync(
|
||||
"key-w", "W", new HashSet<string>(StringComparer.Ordinal), null, null, CancellationToken.None));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PepperUnavailableException_ConstructorOverloads_AreInvalidOperationExceptions()
|
||||
{
|
||||
var inner = new Exception("inner");
|
||||
Assert.Equal("pepper unavailable", new ApiKeyPepperUnavailableException().Message);
|
||||
Assert.Equal("custom", new ApiKeyPepperUnavailableException("custom").Message);
|
||||
var withInner = new ApiKeyPepperUnavailableException("m", inner);
|
||||
Assert.Same(inner, withInner.InnerException);
|
||||
Assert.IsAssignableFrom<InvalidOperationException>(withInner);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RotateKey_PepperUnavailable_Throws_HashUnchanged_AndAppendsNoAudit()
|
||||
{
|
||||
@@ -319,7 +365,7 @@ public sealed class ApiKeyAdminCommandsTests : IAsyncLifetime
|
||||
|
||||
// Act: rotate with no pepper available.
|
||||
ApiKeyAdminCommands nopepper = BuildCommands(pepper: null);
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(() =>
|
||||
await Assert.ThrowsAsync<ApiKeyPepperUnavailableException>(() =>
|
||||
nopepper.RotateKeyAsync("key-1", null, CancellationToken.None));
|
||||
|
||||
// Assert: stored hash is unchanged.
|
||||
|
||||
+34
@@ -5,6 +5,7 @@ using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Options;
|
||||
using ZB.MOM.WW.Auth.Abstractions.ApiKeys;
|
||||
using ZB.MOM.WW.Auth.ApiKeys.DependencyInjection;
|
||||
using ZB.MOM.WW.Auth.ApiKeys.Sqlite;
|
||||
|
||||
namespace ZB.MOM.WW.Auth.ApiKeys.Tests;
|
||||
|
||||
@@ -197,4 +198,37 @@ public class ApiKeyServiceCollectionExtensionsTests
|
||||
File.Delete(sqlitePath);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AddZbApiKeyAuth_RegistersSqliteMigratorAsIApiKeyStoreMigrator()
|
||||
{
|
||||
IConfiguration config = BuildConfiguration(TempSqlitePath());
|
||||
var services = new ServiceCollection();
|
||||
|
||||
services.AddZbApiKeyAuth(config, ApiKeySection);
|
||||
|
||||
using ServiceProvider sp = services.BuildServiceProvider();
|
||||
|
||||
Assert.IsType<SqliteAuthStoreMigrator>(sp.GetRequiredService<IApiKeyStoreMigrator>());
|
||||
Assert.Same(sp.GetRequiredService<SqliteAuthStoreMigrator>(), sp.GetRequiredService<IApiKeyStoreMigrator>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AddZbApiKeyAuth_LeavesPreRegisteredMigratorInPlace()
|
||||
{
|
||||
var services = new ServiceCollection();
|
||||
var fake = new FakeMigrator();
|
||||
services.AddSingleton<IApiKeyStoreMigrator>(fake);
|
||||
|
||||
services.AddZbApiKeyAuth(BuildConfiguration(TempSqlitePath()), ApiKeySection);
|
||||
|
||||
using ServiceProvider sp = services.BuildServiceProvider();
|
||||
|
||||
Assert.Same(fake, sp.GetRequiredService<IApiKeyStoreMigrator>());
|
||||
}
|
||||
|
||||
private sealed class FakeMigrator : IApiKeyStoreMigrator
|
||||
{
|
||||
public Task MigrateAsync(CancellationToken ct) => Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -356,6 +356,45 @@ public class ApiKeyVerifierTests
|
||||
|
||||
// --- Cancellation ---
|
||||
|
||||
// --- StoreUnavailable (Auth-010, scadaproj#46) ---
|
||||
|
||||
public static TheoryData<Exception> StoreFaults() => new()
|
||||
{
|
||||
// Stand-ins for what real stores throw: a database fault (SqlClient's SqlException on a
|
||||
// closed port or failover), an InvalidOperationException (e.g. a pooled connection in a bad
|
||||
// state), and an I/O fault from a local SQLite file.
|
||||
new System.Data.DataException("store unreachable"),
|
||||
new InvalidOperationException("The connection is in a broken state."),
|
||||
new IOException("disk I/O error"),
|
||||
};
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(StoreFaults))]
|
||||
public async Task VerifyAsync_StoreLookupThrows_ReturnsStoreUnavailable_InsteadOfThrowing(Exception fault)
|
||||
{
|
||||
var store = new FakeApiKeyStore { FindException = fault };
|
||||
var verifier = BuildVerifier(store, new FakePepperProvider(Pepper));
|
||||
|
||||
ApiKeyVerification result = await verifier.VerifyAsync(Header(KeyId, Secret), CancellationToken.None);
|
||||
|
||||
Assert.False(result.Succeeded);
|
||||
Assert.Equal(ApiKeyFailure.StoreUnavailable, result.Failure);
|
||||
Assert.Null(result.Identity);
|
||||
Assert.True(store.FindByKeyIdCalled);
|
||||
Assert.False(store.MarkUsedCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task VerifyAsync_StoreLookupCancelled_Propagates()
|
||||
{
|
||||
// Cancellation stays the one exception path.
|
||||
var store = new FakeApiKeyStore { FindException = new OperationCanceledException() };
|
||||
var verifier = BuildVerifier(store, new FakePepperProvider(Pepper));
|
||||
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(
|
||||
() => verifier.VerifyAsync(Header(KeyId, Secret), CancellationToken.None));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task VerifyAsync_AlreadyCancelled_Throws()
|
||||
{
|
||||
@@ -398,10 +437,13 @@ public class ApiKeyVerifierTests
|
||||
/// <summary>When set, <see cref="MarkUsedAsync"/> throws this exception (after recording the call).</summary>
|
||||
public Exception? MarkUsedException { get; set; }
|
||||
|
||||
/// <summary>When set, <see cref="FindByKeyIdAsync"/> throws this exception (after recording the call).</summary>
|
||||
public Exception? FindException { get; set; }
|
||||
|
||||
public Task<ApiKeyRecord?> FindByKeyIdAsync(string keyId, CancellationToken ct)
|
||||
{
|
||||
FindByKeyIdCalled = true;
|
||||
return Task.FromResult(Record);
|
||||
return FindException is not null ? Task.FromException<ApiKeyRecord?>(FindException) : Task.FromResult(Record);
|
||||
}
|
||||
|
||||
public Task<ApiKeyRecord?> FindActiveByKeyIdAsync(string keyId, CancellationToken ct) =>
|
||||
|
||||
+70
@@ -134,4 +134,74 @@ public class ServiceCollectionExtensionsTests
|
||||
await host.StartAsync();
|
||||
await host.StopAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AddZbLdapAuth_BindsUserBindModeKeys()
|
||||
{
|
||||
IConfiguration config = new ConfigurationBuilder()
|
||||
.AddInMemoryCollection(new Dictionary<string, string?>
|
||||
{
|
||||
[$"{LdapSection}:Server"] = LdapServer,
|
||||
[$"{LdapSection}:SearchBase"] = "dc=example,dc=com",
|
||||
[$"{LdapSection}:Transport"] = nameof(LdapTransport.Ldaps),
|
||||
[$"{LdapSection}:BindMode"] = "User",
|
||||
[$"{LdapSection}:UserBindTemplate"] = "{0}@corp.test",
|
||||
[$"{LdapSection}:AcceptDomainQualifiedNames"] = "false",
|
||||
})
|
||||
.Build();
|
||||
var services = new ServiceCollection();
|
||||
|
||||
services.AddZbLdapAuth(config, LdapSection);
|
||||
|
||||
using ServiceProvider provider = services.BuildServiceProvider();
|
||||
var options = provider.GetRequiredService<IOptions<LdapOptions>>().Value;
|
||||
|
||||
Assert.Equal(LdapBindMode.User, options.BindMode);
|
||||
Assert.Equal("{0}@corp.test", options.UserBindTemplate);
|
||||
Assert.False(options.AcceptDomainQualifiedNames);
|
||||
}
|
||||
}
|
||||
|
||||
public class LdapGroupLookupRegistrationTests
|
||||
{
|
||||
private static IConfiguration Config() =>
|
||||
new ConfigurationBuilder()
|
||||
.AddInMemoryCollection(new Dictionary<string, string?>
|
||||
{
|
||||
["Auth:Ldap:Server"] = "ldap.example.com",
|
||||
["Auth:Ldap:SearchBase"] = "dc=example,dc=com",
|
||||
["Auth:Ldap:ServiceAccountDn"] = "cn=svc,dc=example,dc=com",
|
||||
})
|
||||
.Build();
|
||||
|
||||
[Fact]
|
||||
public void AddZbLdapAuth_ResolvesGroupLookup_AsTheSameInstanceAsTheAuthService()
|
||||
{
|
||||
var services = new ServiceCollection().AddZbLdapAuth(Config(), "Auth:Ldap");
|
||||
using var provider = services.BuildServiceProvider();
|
||||
|
||||
var lookup = provider.GetRequiredService<ILdapGroupLookup>();
|
||||
|
||||
Assert.IsType<LdapAuthService>(lookup);
|
||||
Assert.Same(provider.GetRequiredService<ILdapAuthService>(), lookup);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddZbLdapAuth_WithAForeignAuthService_ResolvesANotSupportedLookup()
|
||||
{
|
||||
var services = new ServiceCollection();
|
||||
services.AddSingleton<ILdapAuthService, StubAuth>();
|
||||
services.AddZbLdapAuth(Config(), "Auth:Ldap");
|
||||
using var provider = services.BuildServiceProvider();
|
||||
|
||||
var result = await provider.GetRequiredService<ILdapGroupLookup>().GetUserGroupsAsync("alice", CancellationToken.None);
|
||||
|
||||
Assert.Equal(LdapGroupLookupStatus.NotSupported, result.Status);
|
||||
}
|
||||
|
||||
private sealed class StubAuth : ILdapAuthService
|
||||
{
|
||||
public Task<LdapAuthResult> AuthenticateAsync(string username, string password, CancellationToken ct)
|
||||
=> Task.FromResult(LdapAuthResult.Fail(LdapAuthFailure.Disabled));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,6 +16,12 @@ internal sealed class FakeLdapConnection : ILdapConnection
|
||||
private bool _throwOnConnect;
|
||||
private bool _throwOnServiceBind;
|
||||
private bool _throwOnUserBind;
|
||||
private int? _firstBindResultCode;
|
||||
private bool _throwOnSearch;
|
||||
private string? _whoAmI;
|
||||
private string? _principalName;
|
||||
private bool _throwOnRead;
|
||||
private readonly Dictionary<string, List<LdapSearchEntry>> _filterResults = new(StringComparer.Ordinal);
|
||||
|
||||
// ---- observation -----
|
||||
|
||||
@@ -32,13 +38,24 @@ internal sealed class FakeLdapConnection : ILdapConnection
|
||||
/// </summary>
|
||||
public int BindAttempts { get; private set; }
|
||||
|
||||
/// <summary>The attribute list passed to the most recent <see cref="Search"/> call (the fake still returns every scripted attribute).</summary>
|
||||
public IReadOnlyList<string>? SearchAttributes { get; private set; }
|
||||
|
||||
/// <summary>Every call in order: <c>connect</c>, <c>bind:<dn></c>, <c>search:<filter></c>.</summary>
|
||||
public List<string> Calls { get; } = new();
|
||||
|
||||
// ---- builder methods -----
|
||||
|
||||
/// <summary>
|
||||
/// Scripts a user entry that will be returned by the next <see cref="Search"/> call.
|
||||
/// Builds a minimal attribute bag with <c>memberOf</c> and optional <c>displayName</c>.
|
||||
/// Builds a minimal attribute bag with <c>memberOf</c>, optional <c>displayName</c> and any
|
||||
/// <paramref name="extraAttributes"/> (e.g. <c>sAMAccountName</c>) the test needs.
|
||||
/// </summary>
|
||||
public FakeLdapConnection WithUserEntry(string dn, string[] memberOf, string? displayName = null)
|
||||
public FakeLdapConnection WithUserEntry(
|
||||
string dn,
|
||||
string[] memberOf,
|
||||
string? displayName = null,
|
||||
IReadOnlyDictionary<string, string[]>? extraAttributes = null)
|
||||
{
|
||||
var attrs = new Dictionary<string, IReadOnlyList<string>>(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
@@ -46,6 +63,11 @@ internal sealed class FakeLdapConnection : ILdapConnection
|
||||
};
|
||||
if (displayName is not null)
|
||||
attrs["displayName"] = new[] { displayName };
|
||||
if (extraAttributes is not null)
|
||||
{
|
||||
foreach (var (name, values) in extraAttributes)
|
||||
attrs[name] = values;
|
||||
}
|
||||
|
||||
_scriptedEntries.Add(new LdapSearchEntry(dn, attrs));
|
||||
return this;
|
||||
@@ -83,6 +105,67 @@ internal sealed class FakeLdapConnection : ILdapConnection
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Throw <see cref="Novell.Directory.Ldap.LdapException"/> with <paramref name="resultCode"/> on the
|
||||
/// FIRST bind. In user-bind mode the first bind is the user's own, so 49 simulates a wrong
|
||||
/// password and e.g. 52 (Unavailable) a domain controller that cannot answer.
|
||||
/// </summary>
|
||||
public FakeLdapConnection ThrowOnFirstBind(int resultCode)
|
||||
{
|
||||
_firstBindResultCode = resultCode;
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Scripts the RFC 4532 Who-am-I answer (e.g. <c>dn:CN=Jane,DC=x</c> or <c>u:CORP\jane</c>).
|
||||
/// Unscripted, <see cref="WhoAmI"/> throws protocol error 2 — what GLAuth answers.
|
||||
/// </summary>
|
||||
public FakeLdapConnection WithWhoAmI(string authzId)
|
||||
{
|
||||
_whoAmI = authzId;
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Scripts AD's constructed <c>msDS-PrincipalName</c> (<c>DOMAIN\name</c>) that a base
|
||||
/// <see cref="Read"/> of any DN returns. Unscripted, <see cref="Read"/> returns the entry without it.
|
||||
/// </summary>
|
||||
public FakeLdapConnection WithPrincipalName(string value)
|
||||
{
|
||||
_principalName = value;
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>Throw <see cref="Novell.Directory.Ldap.LdapException"/> from <see cref="Read"/>.</summary>
|
||||
public FakeLdapConnection ThrowOnRead()
|
||||
{
|
||||
_throwOnRead = true;
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Scripts the entries a <see cref="Search"/> with exactly <paramref name="filter"/> returns, each
|
||||
/// carrying the given <c>sAMAccountName</c>. Other filters still return the
|
||||
/// <see cref="WithUserEntry"/> entries.
|
||||
/// </summary>
|
||||
public FakeLdapConnection WithSearchResult(string filter, params (string Dn, string Sam)[] entries)
|
||||
{
|
||||
_filterResults[filter] = entries
|
||||
.Select(e => new LdapSearchEntry(e.Dn, new Dictionary<string, IReadOnlyList<string>>(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
["sAMAccountName"] = new[] { e.Sam },
|
||||
}))
|
||||
.ToList();
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>Throw <see cref="Novell.Directory.Ldap.LdapException"/> from <see cref="Search"/> (unhealthy directory).</summary>
|
||||
public FakeLdapConnection ThrowOnSearch()
|
||||
{
|
||||
_throwOnSearch = true;
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Throw <see cref="Novell.Directory.Ldap.LdapException"/> from <see cref="Connect"/> to
|
||||
/// simulate an unreachable directory (infrastructure failure).
|
||||
@@ -120,6 +203,7 @@ internal sealed class FakeLdapConnection : ILdapConnection
|
||||
int timeoutMs,
|
||||
RemoteCertificateValidationCallback? serverCertificateValidationCallback = null)
|
||||
{
|
||||
Calls.Add("connect");
|
||||
ConnectArgs = (host, port, transport, allowInsecure, timeoutMs);
|
||||
ConnectCertCallback = serverCertificateValidationCallback;
|
||||
if (_throwOnConnect)
|
||||
@@ -130,8 +214,12 @@ internal sealed class FakeLdapConnection : ILdapConnection
|
||||
public void Bind(string dn, string password)
|
||||
{
|
||||
BindAttempts++;
|
||||
Calls.Add($"bind:{dn}");
|
||||
var isServiceBind = BindAttempts == 1;
|
||||
|
||||
if (isServiceBind && _firstBindResultCode is { } code)
|
||||
throw new Novell.Directory.Ldap.LdapException("Bind refused", code, dn);
|
||||
|
||||
if ((_throwOnServiceBind && isServiceBind)
|
||||
|| (_throwOnUserBind && !isServiceBind)
|
||||
|| _throwBindDns.Contains(dn))
|
||||
@@ -147,7 +235,33 @@ internal sealed class FakeLdapConnection : ILdapConnection
|
||||
string searchBase,
|
||||
string filter,
|
||||
IReadOnlyList<string> attributes)
|
||||
=> _scriptedEntries.AsReadOnly();
|
||||
{
|
||||
Calls.Add($"search:{filter}");
|
||||
SearchAttributes = attributes;
|
||||
if (_throwOnSearch)
|
||||
throw new Novell.Directory.Ldap.LdapException(
|
||||
"Search failed", Novell.Directory.Ldap.LdapException.Unavailable, searchBase);
|
||||
return _filterResults.TryGetValue(filter, out var scripted) ? scripted : _scriptedEntries.AsReadOnly();
|
||||
}
|
||||
|
||||
public LdapSearchEntry? Read(string dn, IReadOnlyList<string> attributes)
|
||||
{
|
||||
Calls.Add($"read:{dn}");
|
||||
if (_throwOnRead)
|
||||
throw new Novell.Directory.Ldap.LdapException(
|
||||
"Read failed", Novell.Directory.Ldap.LdapException.InsufficientAccessRights, dn);
|
||||
var attrs = new Dictionary<string, IReadOnlyList<string>>(StringComparer.OrdinalIgnoreCase);
|
||||
if (_principalName is not null)
|
||||
attrs["msDS-PrincipalName"] = new[] { _principalName };
|
||||
return new LdapSearchEntry(dn, attrs);
|
||||
}
|
||||
|
||||
public string WhoAmI()
|
||||
{
|
||||
Calls.Add("whoami");
|
||||
return _whoAmI ?? throw new Novell.Directory.Ldap.LdapException(
|
||||
"Protocol Error", Novell.Directory.Ldap.LdapException.ProtocolError, null);
|
||||
}
|
||||
|
||||
public void Dispose() { /* nothing to clean up */ }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
// GLAuth integration tests for the 0.5.0 passwordless group lookup — opt-in only.
|
||||
//
|
||||
// Same gate and variables as GLAuthIntegrationTests (ZB_LDAP_IT=1, ZB_LDAP_SERVER/PORT/BASE,
|
||||
// ZB_LDAP_SVC_DN/PW, ZB_LDAP_USER/PW, ZB_LDAP_USERATTR). ZB_LDAP_FALLBACK (optional, "host:port")
|
||||
// names a second live directory for the two-live-endpoint failover case — e.g. the redundant local
|
||||
// pair in scadaproj/infra/glauth-redundant (primary :3893, backup :3894):
|
||||
//
|
||||
// ZB_LDAP_IT=1 ZB_LDAP_SERVER=localhost ZB_LDAP_PORT=3893 ZB_LDAP_FALLBACK=localhost:3894 \
|
||||
// ZB_LDAP_BASE=dc=zb,dc=local ZB_LDAP_SVC_DN=cn=serviceaccount,dc=zb,dc=local ZB_LDAP_SVC_PW=... \
|
||||
// ZB_LDAP_USER=multi-role ZB_LDAP_PW=... \
|
||||
// dotnet test tests/ZB.MOM.WW.Auth.Ldap.Tests --filter "FullyQualifiedName~GLAuthGroupLookupTests"
|
||||
|
||||
using System.Net.Sockets;
|
||||
using ZB.MOM.WW.Auth.Abstractions.Ldap;
|
||||
|
||||
namespace ZB.MOM.WW.Auth.Ldap.Tests.Integration;
|
||||
|
||||
public sealed class GLAuthGroupLookupTests
|
||||
{
|
||||
private sealed record Env(string Server, int Port, string BaseDn, string SvcDn, string SvcPw,
|
||||
string User, string Pw, string UserAttr, string? Fallback);
|
||||
|
||||
private static Env Require()
|
||||
{
|
||||
Skip.IfNot(Environment.GetEnvironmentVariable("ZB_LDAP_IT") == "1", "Set ZB_LDAP_IT=1 and a reachable GLAuth to run.");
|
||||
var env = new Env(
|
||||
Environment.GetEnvironmentVariable("ZB_LDAP_SERVER") ?? "localhost",
|
||||
int.TryParse(Environment.GetEnvironmentVariable("ZB_LDAP_PORT"), out var p) ? p : 3893,
|
||||
Environment.GetEnvironmentVariable("ZB_LDAP_BASE") ?? "dc=lmxopcua,dc=local",
|
||||
Environment.GetEnvironmentVariable("ZB_LDAP_SVC_DN") ?? "",
|
||||
Environment.GetEnvironmentVariable("ZB_LDAP_SVC_PW") ?? "",
|
||||
Environment.GetEnvironmentVariable("ZB_LDAP_USER") ?? "",
|
||||
Environment.GetEnvironmentVariable("ZB_LDAP_PW") ?? "",
|
||||
Environment.GetEnvironmentVariable("ZB_LDAP_USERATTR") ?? "cn",
|
||||
Environment.GetEnvironmentVariable("ZB_LDAP_FALLBACK"));
|
||||
try
|
||||
{
|
||||
using var tcp = new TcpClient();
|
||||
if (!tcp.ConnectAsync(env.Server, env.Port).Wait(TimeSpan.FromSeconds(3)))
|
||||
Skip.If(true, $"GLAuth not reachable at {env.Server}:{env.Port} (connect timed out).");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Skip.If(true, $"GLAuth not reachable at {env.Server}:{env.Port}: {ex.Message}");
|
||||
}
|
||||
|
||||
return env;
|
||||
}
|
||||
|
||||
private static LdapOptions Options(Env env) => new()
|
||||
{
|
||||
Enabled = true,
|
||||
Server = env.Server,
|
||||
Port = env.Port,
|
||||
Transport = LdapTransport.None,
|
||||
AllowInsecure = true,
|
||||
SearchBase = env.BaseDn,
|
||||
ServiceAccountDn = env.SvcDn,
|
||||
ServiceAccountPassword = env.SvcPw,
|
||||
UserNameAttribute = env.UserAttr,
|
||||
GroupAttribute = "memberOf",
|
||||
ConnectionTimeoutMs = 3000,
|
||||
};
|
||||
|
||||
/// <summary>The lookup returns exactly the group set, username and display name a real sign-in does.</summary>
|
||||
[SkippableFact]
|
||||
public async Task Lookup_ReturnsTheSameGroupsAsSignIn()
|
||||
{
|
||||
var env = Require();
|
||||
var svc = new LdapAuthService(Options(env));
|
||||
|
||||
var login = await svc.AuthenticateAsync(env.User, env.Pw, CancellationToken.None);
|
||||
var lookup = await svc.GetUserGroupsAsync(env.User, CancellationToken.None);
|
||||
|
||||
Assert.True(login.Succeeded, $"sign-in failed: {login.Failure}");
|
||||
Assert.Equal(LdapGroupLookupStatus.Found, lookup.Status);
|
||||
Assert.NotEmpty(lookup.Groups);
|
||||
Assert.Equal(login.Groups.OrderBy(g => g, StringComparer.Ordinal), lookup.Groups.OrderBy(g => g, StringComparer.Ordinal));
|
||||
Assert.Equal(login.Username, lookup.Username);
|
||||
Assert.Equal(login.DisplayName, lookup.DisplayName);
|
||||
}
|
||||
|
||||
[SkippableFact]
|
||||
public async Task Lookup_OfAnUnknownName_IsUserNotFound()
|
||||
{
|
||||
var env = Require();
|
||||
var svc = new LdapAuthService(Options(env));
|
||||
|
||||
var lookup = await svc.GetUserGroupsAsync("no-such-user-" + Guid.NewGuid().ToString("N")[..8], CancellationToken.None);
|
||||
|
||||
Assert.Equal(LdapGroupLookupStatus.UserNotFound, lookup.Status);
|
||||
}
|
||||
|
||||
/// <summary>A wrong service-account password is the directory refusing US, not the user: DirectoryUnavailable.</summary>
|
||||
[SkippableFact]
|
||||
public async Task Lookup_WithAWrongServiceAccountPassword_IsDirectoryUnavailable()
|
||||
{
|
||||
var env = Require();
|
||||
var svc = new LdapAuthService(Options(env) with { ServiceAccountPassword = "definitely-wrong" });
|
||||
|
||||
var lookup = await svc.GetUserGroupsAsync(env.User, CancellationToken.None);
|
||||
|
||||
Assert.Equal(LdapGroupLookupStatus.DirectoryUnavailable, lookup.Status);
|
||||
}
|
||||
|
||||
/// <summary>Dead primary (closed local port) fails over to the live directory, twice (sticky).</summary>
|
||||
[SkippableFact]
|
||||
public async Task Lookup_FailsOverFromADeadPrimary()
|
||||
{
|
||||
var env = Require();
|
||||
var svc = new LdapAuthService(Options(env) with
|
||||
{
|
||||
Server = "127.0.0.1",
|
||||
Port = 39999,
|
||||
FallbackServers = new[] { $"{env.Server}:{env.Port}" },
|
||||
});
|
||||
|
||||
var first = await svc.GetUserGroupsAsync(env.User, CancellationToken.None);
|
||||
var second = await svc.GetUserGroupsAsync(env.User, CancellationToken.None);
|
||||
|
||||
Assert.Equal(LdapGroupLookupStatus.Found, first.Status);
|
||||
Assert.Equal(LdapGroupLookupStatus.Found, second.Status);
|
||||
}
|
||||
|
||||
/// <summary>Every endpoint dead: DirectoryUnavailable, never UserNotFound (which would revoke a session).</summary>
|
||||
[SkippableFact]
|
||||
public async Task Lookup_WithEveryEndpointDead_IsDirectoryUnavailable()
|
||||
{
|
||||
var env = Require();
|
||||
var svc = new LdapAuthService(Options(env) with
|
||||
{
|
||||
Server = "127.0.0.1",
|
||||
Port = 39999,
|
||||
FallbackServers = new[] { "127.0.0.1:39998" },
|
||||
});
|
||||
|
||||
var lookup = await svc.GetUserGroupsAsync(env.User, CancellationToken.None);
|
||||
|
||||
Assert.Equal(LdapGroupLookupStatus.DirectoryUnavailable, lookup.Status);
|
||||
}
|
||||
|
||||
/// <summary>Two LIVE directories (ZB_LDAP_FALLBACK): primary answers first; a dead primary port walks to the backup.</summary>
|
||||
[SkippableFact]
|
||||
public async Task Lookup_AcrossTwoLiveDirectories_AnswersFromEither()
|
||||
{
|
||||
var env = Require();
|
||||
Skip.If(string.IsNullOrWhiteSpace(env.Fallback), "Set ZB_LDAP_FALLBACK=host:port to a second live directory.");
|
||||
|
||||
var both = new LdapAuthService(Options(env) with { FallbackServers = new[] { env.Fallback! } });
|
||||
var backupOnly = new LdapAuthService(Options(env) with { Port = 39999, Server = "127.0.0.1", FallbackServers = new[] { env.Fallback! } });
|
||||
|
||||
var viaPrimary = await both.GetUserGroupsAsync(env.User, CancellationToken.None);
|
||||
var viaBackup = await backupOnly.GetUserGroupsAsync(env.User, CancellationToken.None);
|
||||
|
||||
Assert.Equal(LdapGroupLookupStatus.Found, viaPrimary.Status);
|
||||
Assert.Equal(LdapGroupLookupStatus.Found, viaBackup.Status);
|
||||
Assert.Equal(viaPrimary.Groups.OrderBy(g => g), viaBackup.Groups.OrderBy(g => g));
|
||||
}
|
||||
}
|
||||
@@ -99,4 +99,70 @@ public sealed class GLAuthIntegrationTests
|
||||
$"Authentication failed: {result.Failure} (server={server}:{port}, user={user})");
|
||||
Assert.NotEmpty(result.Groups);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Failover: primary endpoint points at a closed local port (refused immediately),
|
||||
/// fallback at the real GLAuth. The login must succeed via the fallback, and a second
|
||||
/// login must also succeed (sticky preference — no re-walk through the dead primary).
|
||||
/// Skipped unless <c>ZB_LDAP_IT=1</c> is set; skipped again if the server is unreachable.
|
||||
/// </summary>
|
||||
[SkippableFact]
|
||||
public async Task Authenticate_FailsOverFromDeadPrimary_ToRealGLAuth()
|
||||
{
|
||||
// ------------------------------------------------------------------ opt-in gate
|
||||
Skip.IfNot(
|
||||
Environment.GetEnvironmentVariable("ZB_LDAP_IT") == "1",
|
||||
"Set ZB_LDAP_IT=1 and a reachable GLAuth to run.");
|
||||
|
||||
// ------------------------------------------------------------------ read config
|
||||
var server = Environment.GetEnvironmentVariable("ZB_LDAP_SERVER") ?? "localhost";
|
||||
var port = int.TryParse(Environment.GetEnvironmentVariable("ZB_LDAP_PORT"), out var p) ? p : 3893;
|
||||
var baseDn = Environment.GetEnvironmentVariable("ZB_LDAP_BASE") ?? "dc=lmxopcua,dc=local";
|
||||
var svcDn = Environment.GetEnvironmentVariable("ZB_LDAP_SVC_DN") ?? "";
|
||||
var svcPw = Environment.GetEnvironmentVariable("ZB_LDAP_SVC_PW") ?? "";
|
||||
var user = Environment.GetEnvironmentVariable("ZB_LDAP_USER") ?? "";
|
||||
var pw = Environment.GetEnvironmentVariable("ZB_LDAP_PW") ?? "";
|
||||
var userAttr = Environment.GetEnvironmentVariable("ZB_LDAP_USERATTR") ?? "cn";
|
||||
|
||||
// ------------------------------------------------------------------ reachability probe
|
||||
try
|
||||
{
|
||||
using var tcp = new TcpClient();
|
||||
// 3-second connect timeout to keep the test suite snappy when the server is absent
|
||||
var connectTask = tcp.ConnectAsync(server, port);
|
||||
if (!connectTask.Wait(TimeSpan.FromSeconds(3)))
|
||||
Skip.If(true, $"GLAuth not reachable at {server}:{port} (connect timed out).");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Skip.If(true, $"GLAuth not reachable at {server}:{port}: {ex.Message}");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ build options
|
||||
var options = new LdapOptions
|
||||
{
|
||||
Enabled = true,
|
||||
Server = "127.0.0.1",
|
||||
Port = 39999, // closed port -> immediate refusal
|
||||
Transport = LdapTransport.None,
|
||||
AllowInsecure = true,
|
||||
SearchBase = baseDn,
|
||||
ServiceAccountDn = svcDn,
|
||||
ServiceAccountPassword = svcPw,
|
||||
UserNameAttribute = userAttr,
|
||||
GroupAttribute = "memberOf",
|
||||
ConnectionTimeoutMs = 3000,
|
||||
FallbackServers = new[] { $"{server}:{port}" },
|
||||
};
|
||||
|
||||
// ------------------------------------------------------------------ exercise the real service
|
||||
var svc = new LdapAuthService(options);
|
||||
|
||||
var first = await svc.AuthenticateAsync(user, pw, CancellationToken.None);
|
||||
Assert.True(first.Succeeded, $"first login failed: {first.Failure}");
|
||||
|
||||
// Second login exercises the sticky preference: it must not re-walk the dead primary.
|
||||
var second = await svc.AuthenticateAsync(user, pw, CancellationToken.None);
|
||||
Assert.True(second.Succeeded, $"second login failed: {second.Failure}");
|
||||
}
|
||||
}
|
||||
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
// Live user-bind identity test (Auth-007, scadaproj#40) — opt-in only.
|
||||
//
|
||||
// Start the throwaway fixture (NOT the shared rig — it needs users that can search):
|
||||
// cd tests/ZB.MOM.WW.Auth.Ldap.Tests/Integration/glauth-userbind && docker compose up -d
|
||||
// Run:
|
||||
// ZB_LDAP_USERBIND_IT=1 dotnet test tests/ZB.MOM.WW.Auth.Ldap.Tests \
|
||||
// --filter "FullyQualifiedName~GLAuthUserBindIdentityTests"
|
||||
// Optional: ZB_LDAP_USERBIND_SERVER (default localhost), ZB_LDAP_USERBIND_PORT (default 3897).
|
||||
//
|
||||
// GLAuth does not implement RFC 4532 Who-am-I (it answers protocol error 2), so these tests also
|
||||
// prove the DN-template fallback path against a real directory.
|
||||
|
||||
using System.Net.Sockets;
|
||||
using ZB.MOM.WW.Auth.Abstractions.Ldap;
|
||||
|
||||
namespace ZB.MOM.WW.Auth.Ldap.Tests.Integration;
|
||||
|
||||
public sealed class GLAuthUserBindIdentityTests
|
||||
{
|
||||
private static LdapOptions Options(string template, string userNameAttribute)
|
||||
{
|
||||
var server = Environment.GetEnvironmentVariable("ZB_LDAP_USERBIND_SERVER") ?? "localhost";
|
||||
var port = int.TryParse(Environment.GetEnvironmentVariable("ZB_LDAP_USERBIND_PORT"), out var p) ? p : 3897;
|
||||
|
||||
try
|
||||
{
|
||||
using var tcp = new TcpClient();
|
||||
if (!tcp.ConnectAsync(server, port).Wait(TimeSpan.FromSeconds(3)))
|
||||
Skip.If(true, $"GLAuth fixture not reachable at {server}:{port}.");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Skip.If(true, $"GLAuth fixture not reachable at {server}:{port}: {ex.Message}");
|
||||
}
|
||||
|
||||
return new LdapOptions
|
||||
{
|
||||
Server = server,
|
||||
Port = port,
|
||||
Transport = LdapTransport.None,
|
||||
AllowInsecure = true,
|
||||
SearchBase = "dc=zb,dc=local",
|
||||
BindMode = LdapBindMode.User,
|
||||
UserBindTemplate = template,
|
||||
UserNameAttribute = userNameAttribute,
|
||||
GroupAttribute = "memberOf",
|
||||
ConnectionTimeoutMs = 3000,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// mallory binds with her own password; <c>(mail=mallory)</c> finds the <c>boss</c> entry, which
|
||||
/// is in Admins. Before the fix this signed mallory in with boss's groups.
|
||||
/// </summary>
|
||||
[SkippableFact]
|
||||
public async Task BoundAccount_DifferentFromTheSearchedEntry_IsRefused()
|
||||
{
|
||||
Skip.IfNot(Environment.GetEnvironmentVariable("ZB_LDAP_USERBIND_IT") == "1",
|
||||
"Set ZB_LDAP_USERBIND_IT=1 and start Integration/glauth-userbind to run.");
|
||||
|
||||
var svc = new LdapAuthService(Options("cn={0},ou=Users,dc=zb,dc=local", "mail"));
|
||||
var result = await svc.AuthenticateAsync("mallory", "password", CancellationToken.None);
|
||||
|
||||
Assert.False(result.Succeeded, $"signed in as {result.Username} with [{string.Join(",", result.Groups)}]");
|
||||
Assert.Equal(LdapAuthFailure.GroupLookupFailed, result.Failure);
|
||||
Assert.DoesNotContain("Admins", result.Groups);
|
||||
}
|
||||
|
||||
/// <summary>Positive control: the same mechanism admits a user whose bind DN is the entry's DN.</summary>
|
||||
[SkippableFact]
|
||||
public async Task BoundAccount_SameAsTheSearchedEntry_Succeeds()
|
||||
{
|
||||
Skip.IfNot(Environment.GetEnvironmentVariable("ZB_LDAP_USERBIND_IT") == "1",
|
||||
"Set ZB_LDAP_USERBIND_IT=1 and start Integration/glauth-userbind to run.");
|
||||
|
||||
// GLAuth reports search DNs as cn=<user>,ou=<group>,ou=users,<base>; it also accepts that
|
||||
// form as a bind DN, so this template binds the exact DN the search returns.
|
||||
var svc = new LdapAuthService(Options("cn={0},ou=Users,ou=users,dc=zb,dc=local", "cn"));
|
||||
var result = await svc.AuthenticateAsync("boss", "password", CancellationToken.None);
|
||||
|
||||
Assert.True(result.Succeeded, $"failed: {result.Failure}");
|
||||
Assert.Equal("boss", result.Username);
|
||||
Assert.Contains("Admins", result.Groups);
|
||||
}
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
# GLAuth fixture for the user-bind identity test (Auth-007, scadaproj#40).
|
||||
# Start: docker compose up -d (listens on localhost:3897)
|
||||
# All passwords are "password" (sha256 below).
|
||||
#
|
||||
# mallory binds as herself (cn=mallory,ou=Users,...). The admin entry carries mail=mallory,
|
||||
# so with UserNameAttribute=mail a search for the typed name "mallory" finds the ADMIN — the
|
||||
# account that bound and the account searched for differ. The library must refuse.
|
||||
|
||||
[ldap]
|
||||
enabled = true
|
||||
listen = "0.0.0.0:3893"
|
||||
|
||||
[ldaps]
|
||||
enabled = false
|
||||
|
||||
[backend]
|
||||
datastore = "config"
|
||||
baseDN = "dc=zb,dc=local"
|
||||
|
||||
[behaviors]
|
||||
LimitFailedBinds = false
|
||||
|
||||
[[groups]]
|
||||
name = "Users"
|
||||
gidnumber = 6001
|
||||
[[groups]]
|
||||
name = "Admins"
|
||||
gidnumber = 6002
|
||||
|
||||
[[users]]
|
||||
name = "mallory"
|
||||
mail = "mallory-real@zb.local"
|
||||
uidnumber = 6101
|
||||
primarygroup = 6001
|
||||
passsha256 = "5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8"
|
||||
[[users.capabilities]]
|
||||
action = "search"
|
||||
object = "*"
|
||||
|
||||
[[users]]
|
||||
name = "boss"
|
||||
mail = "mallory"
|
||||
uidnumber = 6102
|
||||
primarygroup = 6001
|
||||
othergroups = [6002]
|
||||
passsha256 = "5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8"
|
||||
[[users.capabilities]]
|
||||
action = "search"
|
||||
object = "*"
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
# Throwaway GLAuth for GLAuthUserBindIdentityTests (Auth-007). Not the shared rig.
|
||||
name: zb-auth-userbind-it
|
||||
services:
|
||||
glauth:
|
||||
image: glauth/glauth:latest
|
||||
container_name: zb-auth-userbind-it
|
||||
ports:
|
||||
- "3897:3893"
|
||||
volumes:
|
||||
- ./config.toml:/app/config/config.cfg:ro
|
||||
@@ -0,0 +1,297 @@
|
||||
using ZB.MOM.WW.Auth.Abstractions.Ldap;
|
||||
|
||||
namespace ZB.MOM.WW.Auth.Ldap.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Covers the multi-endpoint failover walk: which failures fail over (system-side only),
|
||||
/// which are final (any authoritative answer from a healthy directory), how the sticky
|
||||
/// endpoint preference moves, and that single-endpoint behaviour is unchanged.
|
||||
/// </summary>
|
||||
public class LdapAuthServiceFailoverTests
|
||||
{
|
||||
private static LdapOptions Opts(params string[] fallbacks) => new()
|
||||
{
|
||||
Enabled = true,
|
||||
Server = "dc1",
|
||||
Port = 636,
|
||||
Transport = LdapTransport.Ldaps,
|
||||
SearchBase = "dc=x",
|
||||
ServiceAccountDn = "cn=svc,dc=x",
|
||||
ServiceAccountPassword = "svcpw",
|
||||
FallbackServers = fallbacks,
|
||||
};
|
||||
|
||||
private static FakeLdapConnection HealthyWithUser() =>
|
||||
new FakeLdapConnection().WithUserEntry("cn=alice,dc=x", new[] { "cn=ops,dc=x" });
|
||||
|
||||
// ---- failover triggers (system-side) ----
|
||||
|
||||
[Fact]
|
||||
public async Task ConnectFailure_FailsOverToFallback_AndSucceeds()
|
||||
{
|
||||
var factory = new SequenceLdapConnectionFactory(
|
||||
new FakeLdapConnection().ThrowOnConnect(), HealthyWithUser());
|
||||
var svc = new LdapAuthService(Opts("dc2:3894"), factory);
|
||||
|
||||
var result = await svc.AuthenticateAsync("alice", "pw", CancellationToken.None);
|
||||
|
||||
Assert.True(result.Succeeded);
|
||||
Assert.Equal(2, factory.Created.Count);
|
||||
Assert.Equal("dc1", factory.Created[0].ConnectArgs!.Value.Host);
|
||||
Assert.Equal("dc2", factory.Created[1].ConnectArgs!.Value.Host);
|
||||
Assert.Equal(3894, factory.Created[1].ConnectArgs!.Value.Port);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ServiceBindFailure_FailsOverToFallback()
|
||||
{
|
||||
var factory = new SequenceLdapConnectionFactory(
|
||||
new FakeLdapConnection().ThrowOnServiceBind(), HealthyWithUser());
|
||||
var svc = new LdapAuthService(Opts("dc2"), factory);
|
||||
|
||||
var result = await svc.AuthenticateAsync("alice", "pw", CancellationToken.None);
|
||||
|
||||
Assert.True(result.Succeeded);
|
||||
Assert.Equal(636, factory.Created[1].ConnectArgs!.Value.Port); // bare host adopts Port
|
||||
}
|
||||
|
||||
// ---- user-side results NEVER fail over ----
|
||||
|
||||
[Fact]
|
||||
public async Task BadUserCredentials_DoesNotFailOver()
|
||||
{
|
||||
var factory = new SequenceLdapConnectionFactory(
|
||||
HealthyWithUser().ThrowOnUserBind());
|
||||
var svc = new LdapAuthService(Opts("dc2"), factory);
|
||||
|
||||
var result = await svc.AuthenticateAsync("alice", "wrong", CancellationToken.None);
|
||||
|
||||
Assert.Equal(LdapAuthFailure.BadCredentials, result.Failure);
|
||||
Assert.Single(factory.Created);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UserNotFound_DoesNotFailOver()
|
||||
{
|
||||
var factory = new SequenceLdapConnectionFactory(new FakeLdapConnection());
|
||||
var svc = new LdapAuthService(Opts("dc2"), factory);
|
||||
|
||||
var result = await svc.AuthenticateAsync("ghost", "pw", CancellationToken.None);
|
||||
|
||||
Assert.Equal(LdapAuthFailure.UserNotFound, result.Failure);
|
||||
Assert.Single(factory.Created);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GroupLookupFailed_DoesNotFailOver()
|
||||
{
|
||||
var factory = new SequenceLdapConnectionFactory(
|
||||
new FakeLdapConnection().WithUserEntry("cn=alice,dc=x", Array.Empty<string>()));
|
||||
var svc = new LdapAuthService(Opts("dc2"), factory);
|
||||
|
||||
var result = await svc.AuthenticateAsync("alice", "pw", CancellationToken.None);
|
||||
|
||||
Assert.Equal(LdapAuthFailure.GroupLookupFailed, result.Failure);
|
||||
Assert.Single(factory.Created);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AmbiguousUser_DoesNotFailOver()
|
||||
{
|
||||
var factory = new SequenceLdapConnectionFactory(
|
||||
new FakeLdapConnection().WithDuplicateMatch());
|
||||
var svc = new LdapAuthService(Opts("dc2"), factory);
|
||||
|
||||
var result = await svc.AuthenticateAsync("alice", "pw", CancellationToken.None);
|
||||
|
||||
Assert.Equal(LdapAuthFailure.AmbiguousUser, result.Failure);
|
||||
Assert.Single(factory.Created);
|
||||
}
|
||||
|
||||
// ---- exhaustion ----
|
||||
|
||||
[Fact]
|
||||
public async Task AllEndpointsDown_ReturnsServiceAccountBindFailed()
|
||||
{
|
||||
var factory = new SequenceLdapConnectionFactory(
|
||||
new FakeLdapConnection().ThrowOnConnect(),
|
||||
new FakeLdapConnection().ThrowOnConnect());
|
||||
var svc = new LdapAuthService(Opts("dc2"), factory);
|
||||
|
||||
var result = await svc.AuthenticateAsync("alice", "pw", CancellationToken.None);
|
||||
|
||||
Assert.Equal(LdapAuthFailure.ServiceAccountBindFailed, result.Failure);
|
||||
Assert.Equal(2, factory.Created.Count);
|
||||
}
|
||||
|
||||
// ---- stickiness ----
|
||||
|
||||
[Fact]
|
||||
public async Task StickyPreference_SecondLoginStartsAtLastGoodEndpoint()
|
||||
{
|
||||
var factory = new SequenceLdapConnectionFactory(
|
||||
new FakeLdapConnection().ThrowOnConnect(), // login 1 @ dc1: dead
|
||||
HealthyWithUser(), // login 1 @ dc2: answers
|
||||
HealthyWithUser()); // login 2: should go straight to dc2
|
||||
var svc = new LdapAuthService(Opts("dc2"), factory);
|
||||
|
||||
Assert.True((await svc.AuthenticateAsync("alice", "pw", CancellationToken.None)).Succeeded);
|
||||
Assert.True((await svc.AuthenticateAsync("alice", "pw", CancellationToken.None)).Succeeded);
|
||||
|
||||
Assert.Equal(3, factory.Created.Count);
|
||||
Assert.Equal("dc2", factory.Created[2].ConnectArgs!.Value.Host);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StickyPreference_DriftsBackToPrimary_WhenPreferredFails()
|
||||
{
|
||||
var factory = new SequenceLdapConnectionFactory(
|
||||
new FakeLdapConnection().ThrowOnConnect(), // login 1 @ dc1: dead
|
||||
HealthyWithUser(), // login 1 @ dc2: answers -> preferred
|
||||
new FakeLdapConnection().ThrowOnConnect(), // login 2 @ dc2: now dead
|
||||
HealthyWithUser(), // login 2 @ dc1 (declared order): recovered
|
||||
HealthyWithUser()); // login 3: should start at dc1 again
|
||||
var svc = new LdapAuthService(Opts("dc2"), factory);
|
||||
|
||||
Assert.True((await svc.AuthenticateAsync("alice", "pw", CancellationToken.None)).Succeeded);
|
||||
Assert.True((await svc.AuthenticateAsync("alice", "pw", CancellationToken.None)).Succeeded);
|
||||
Assert.True((await svc.AuthenticateAsync("alice", "pw", CancellationToken.None)).Succeeded);
|
||||
|
||||
Assert.Equal(5, factory.Created.Count);
|
||||
Assert.Equal("dc1", factory.Created[3].ConnectArgs!.Value.Host);
|
||||
Assert.Equal("dc1", factory.Created[4].ConnectArgs!.Value.Host);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StickyPreference_UpdatesOnUserSideAnswer_NotOnlySuccess()
|
||||
{
|
||||
var factory = new SequenceLdapConnectionFactory(
|
||||
new FakeLdapConnection().ThrowOnConnect(), // login 1 @ dc1: dead
|
||||
new FakeLdapConnection(), // login 1 @ dc2: answers UserNotFound
|
||||
HealthyWithUser()); // login 2: should start at dc2
|
||||
var svc = new LdapAuthService(Opts("dc2"), factory);
|
||||
|
||||
var first = await svc.AuthenticateAsync("ghost", "pw", CancellationToken.None);
|
||||
Assert.Equal(LdapAuthFailure.UserNotFound, first.Failure);
|
||||
|
||||
Assert.True((await svc.AuthenticateAsync("alice", "pw", CancellationToken.None)).Succeeded);
|
||||
Assert.Equal("dc2", factory.Created[2].ConnectArgs!.Value.Host);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AllEndpointsDown_LeavesPreferenceUnchanged()
|
||||
{
|
||||
// A total outage teaches nothing about which endpoint is healthy, so the walk
|
||||
// must not move the preference — the next login still starts at the primary.
|
||||
var factory = new SequenceLdapConnectionFactory(
|
||||
new FakeLdapConnection().ThrowOnConnect(), // login 1 @ dc1
|
||||
new FakeLdapConnection().ThrowOnConnect(), // login 1 @ dc2
|
||||
HealthyWithUser()); // login 2: must start at dc1 again
|
||||
var svc = new LdapAuthService(Opts("dc2"), factory);
|
||||
|
||||
Assert.Equal(LdapAuthFailure.ServiceAccountBindFailed,
|
||||
(await svc.AuthenticateAsync("alice", "pw", CancellationToken.None)).Failure);
|
||||
Assert.True((await svc.AuthenticateAsync("alice", "pw", CancellationToken.None)).Succeeded);
|
||||
|
||||
Assert.Equal("dc1", factory.Created[2].ConnectArgs!.Value.Host);
|
||||
}
|
||||
|
||||
// ---- back-compat ----
|
||||
|
||||
[Fact]
|
||||
public async Task NoFallbacks_SingleAttempt_UnchangedBehavior()
|
||||
{
|
||||
var factory = new SequenceLdapConnectionFactory(
|
||||
new FakeLdapConnection().ThrowOnConnect());
|
||||
var svc = new LdapAuthService(Opts(/* no fallbacks */), factory);
|
||||
|
||||
var result = await svc.AuthenticateAsync("alice", "pw", CancellationToken.None);
|
||||
|
||||
Assert.Equal(LdapAuthFailure.ServiceAccountBindFailed, result.Failure);
|
||||
Assert.Single(factory.Created);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Disabled_NeverOpensAConnection_EvenWithFallbacks()
|
||||
{
|
||||
var factory = new SequenceLdapConnectionFactory(HealthyWithUser());
|
||||
var svc = new LdapAuthService(Opts("dc2") with { Enabled = false }, factory);
|
||||
|
||||
var result = await svc.AuthenticateAsync("alice", "pw", CancellationToken.None);
|
||||
|
||||
Assert.Equal(LdapAuthFailure.Disabled, result.Failure);
|
||||
Assert.Empty(factory.Created);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task MalformedFallbackEntry_IsSkippedDefensively()
|
||||
{
|
||||
// The validator rejects this at boot; a service constructed without validation
|
||||
// must degrade to the parseable subset, not throw.
|
||||
var factory = new SequenceLdapConnectionFactory(HealthyWithUser());
|
||||
var svc = new LdapAuthService(Opts(":::"), factory);
|
||||
|
||||
Assert.True((await svc.AuthenticateAsync("alice", "pw", CancellationToken.None)).Succeeded);
|
||||
Assert.Single(factory.Created);
|
||||
}
|
||||
|
||||
// ---- observability ----
|
||||
|
||||
/// <summary>Captures emitted log entries so failover visibility can be asserted.</summary>
|
||||
private sealed class RecordingLogger : Microsoft.Extensions.Logging.ILogger<LdapAuthService>
|
||||
{
|
||||
public List<(Microsoft.Extensions.Logging.LogLevel Level, string Message)> Entries { get; } = new();
|
||||
public IDisposable? BeginScope<TState>(TState state) where TState : notnull => null;
|
||||
public bool IsEnabled(Microsoft.Extensions.Logging.LogLevel logLevel) => true;
|
||||
public void Log<TState>(Microsoft.Extensions.Logging.LogLevel logLevel, Microsoft.Extensions.Logging.EventId eventId,
|
||||
TState state, Exception? exception, Func<TState, Exception?, string> formatter)
|
||||
=> Entries.Add((logLevel, formatter(state, exception)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Failover_LogsWarningWithEndpointAndStage_AndInfoOnStickyChange()
|
||||
{
|
||||
var logger = new RecordingLogger();
|
||||
var factory = new SequenceLdapConnectionFactory(
|
||||
new FakeLdapConnection().ThrowOnConnect(), HealthyWithUser());
|
||||
var svc = new LdapAuthService(Opts("dc2:3894"), factory, logger);
|
||||
|
||||
await svc.AuthenticateAsync("alice", "pw", CancellationToken.None);
|
||||
|
||||
Assert.Contains(logger.Entries, e =>
|
||||
e.Level == Microsoft.Extensions.Logging.LogLevel.Warning
|
||||
&& e.Message.Contains("dc1:636") && e.Message.Contains("connect"));
|
||||
Assert.Contains(logger.Entries, e =>
|
||||
e.Level == Microsoft.Extensions.Logging.LogLevel.Information
|
||||
&& e.Message.Contains("dc2:3894"));
|
||||
// Never log secrets:
|
||||
Assert.DoesNotContain(logger.Entries, e => e.Message.Contains("svcpw") || e.Message.Contains("pw\""));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HappyPath_LogsNothing()
|
||||
{
|
||||
var logger = new RecordingLogger();
|
||||
var factory = new SequenceLdapConnectionFactory(HealthyWithUser());
|
||||
var svc = new LdapAuthService(Opts("dc2"), factory, logger);
|
||||
|
||||
await svc.AuthenticateAsync("alice", "pw", CancellationToken.None);
|
||||
|
||||
Assert.Empty(logger.Entries);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ServiceBindFailure_LogsTheServiceBindStage_NotConnect()
|
||||
{
|
||||
var logger = new RecordingLogger();
|
||||
var factory = new SequenceLdapConnectionFactory(
|
||||
new FakeLdapConnection().ThrowOnServiceBind(), HealthyWithUser());
|
||||
var svc = new LdapAuthService(Opts("dc2"), factory, logger);
|
||||
|
||||
await svc.AuthenticateAsync("alice", "pw", CancellationToken.None);
|
||||
|
||||
Assert.Contains(logger.Entries, e =>
|
||||
e.Level == Microsoft.Extensions.Logging.LogLevel.Warning
|
||||
&& e.Message.Contains("dc1:636") && e.Message.Contains("service-bind"));
|
||||
}
|
||||
}
|
||||
@@ -147,4 +147,93 @@ public class LdapAuthServiceTests
|
||||
Assert.True(r.Succeeded);
|
||||
Assert.Equal(new[] { "Eng,ineers", "A,B" }, r.Groups);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Username_IsCanonicalisedFromTheEntry_InServiceAccountMode()
|
||||
{
|
||||
var fake = new FakeLdapConnection().WithUserEntry(
|
||||
"cn=alice,dc=x", new[] { "cn=g,dc=x" }, "Alice",
|
||||
new Dictionary<string, string[]> { ["cn"] = new[] { "alice" } });
|
||||
var svc = new LdapAuthService(Opts(), new FakeLdapConnectionFactory(fake));
|
||||
|
||||
var r = await svc.AuthenticateAsync("ALICE", "pw", default);
|
||||
|
||||
Assert.True(r.Succeeded);
|
||||
Assert.Equal("alice", r.Username);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Username_FallsBackToTheTypedName_InServiceAccountMode_WhenAttributeAbsent()
|
||||
{
|
||||
var fake = new FakeLdapConnection().WithUserEntry("cn=alice,dc=x", new[] { "cn=g,dc=x" }, "Alice");
|
||||
var svc = new LdapAuthService(Opts(), new FakeLdapConnectionFactory(fake));
|
||||
|
||||
var r = await svc.AuthenticateAsync("ALICE", "pw", default);
|
||||
|
||||
Assert.True(r.Succeeded);
|
||||
Assert.Equal("ALICE", r.Username);
|
||||
}
|
||||
|
||||
// ---- Auth-009 (scadaproj#46): a multi-valued UserNameAttribute ----------------------------
|
||||
|
||||
[Fact]
|
||||
public async Task Username_FromAMultiValuedAttribute_IsTheValueTheUserMatched()
|
||||
{
|
||||
// OpenLDAP / 389-DS entries routinely carry both cn values; the server's ordering decides
|
||||
// which comes first. The search matched "jsmith", so that is the identity, not "John Smith".
|
||||
var fake = new FakeLdapConnection().WithUserEntry(
|
||||
"cn=jsmith,dc=x", new[] { "cn=g,dc=x" }, "John",
|
||||
new Dictionary<string, string[]> { ["cn"] = new[] { "John Smith", "jsmith" } });
|
||||
var svc = new LdapAuthService(Opts(), new FakeLdapConnectionFactory(fake));
|
||||
|
||||
var r = await svc.AuthenticateAsync("jsmith", "pw", default);
|
||||
|
||||
Assert.True(r.Succeeded);
|
||||
Assert.Equal("jsmith", r.Username);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Username_FromAMultiValuedAttribute_StillTakesTheDirectorysCase()
|
||||
{
|
||||
var fake = new FakeLdapConnection().WithUserEntry(
|
||||
"cn=jsmith,dc=x", new[] { "cn=g,dc=x" }, "John",
|
||||
new Dictionary<string, string[]> { ["cn"] = new[] { "John Smith", "JSmith" } });
|
||||
var svc = new LdapAuthService(Opts(), new FakeLdapConnectionFactory(fake));
|
||||
|
||||
var r = await svc.AuthenticateAsync("jsmith", "pw", default);
|
||||
|
||||
Assert.True(r.Succeeded);
|
||||
Assert.Equal("JSmith", r.Username);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Username_FallsBackToTheFirstValue_WhenNoValueMatchesTheTypedName()
|
||||
{
|
||||
// The directory matched on something the attribute values do not spell the same way
|
||||
// (a matching rule beyond case, say): keep 0.4.1's first-value behaviour.
|
||||
var fake = new FakeLdapConnection().WithUserEntry(
|
||||
"cn=jsmith,dc=x", new[] { "cn=g,dc=x" }, "John",
|
||||
new Dictionary<string, string[]> { ["cn"] = new[] { "J. Smith", "John Smith" } });
|
||||
var svc = new LdapAuthService(Opts(), new FakeLdapConnectionFactory(fake));
|
||||
|
||||
var r = await svc.AuthenticateAsync("jsmith", "pw", default);
|
||||
|
||||
Assert.True(r.Succeeded);
|
||||
Assert.Equal("J. Smith", r.Username);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("")]
|
||||
[InlineData(null)]
|
||||
public async Task EmptyPassword_IsRefused_InServiceAccountMode_WithoutContactingTheDirectory(string? password)
|
||||
{
|
||||
var factory = new SequenceLdapConnectionFactory(
|
||||
new FakeLdapConnection().WithUserEntry("cn=alice,dc=x", new[] { "cn=g,dc=x" }, "Alice"));
|
||||
var svc = new LdapAuthService(Opts(), factory);
|
||||
|
||||
var r = await svc.AuthenticateAsync("alice", password!, default);
|
||||
|
||||
Assert.Equal(LdapAuthFailure.BadCredentials, r.Failure);
|
||||
Assert.Empty(factory.Created);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,478 @@
|
||||
using Novell.Directory.Ldap;
|
||||
using ZB.MOM.WW.Auth.Abstractions.Ldap;
|
||||
|
||||
namespace ZB.MOM.WW.Auth.Ldap.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="LdapBindMode.User"/>: bind as the signing-in user, then read their own entry on the
|
||||
/// same connection. The service account in <see cref="Opts"/> is deliberately populated so the
|
||||
/// tests prove it is never used.
|
||||
/// </summary>
|
||||
public class LdapAuthServiceUserBindTests
|
||||
{
|
||||
private static LdapOptions Opts(params string[] fallbacks) => new()
|
||||
{
|
||||
Enabled = true,
|
||||
Server = "dc1",
|
||||
Port = 636,
|
||||
Transport = LdapTransport.Ldaps,
|
||||
SearchBase = "dc=x",
|
||||
UserNameAttribute = "sAMAccountName",
|
||||
DisplayNameAttribute = "displayName",
|
||||
GroupAttribute = "memberOf",
|
||||
BindMode = LdapBindMode.User,
|
||||
UserBindTemplate = "{0}@corp.test",
|
||||
ServiceAccountDn = "cn=svc,dc=x",
|
||||
ServiceAccountPassword = "svcpw",
|
||||
FallbackServers = fallbacks,
|
||||
};
|
||||
|
||||
private const string JaneDn = "CN=Jane Doe,OU=u,DC=x";
|
||||
|
||||
private static FakeLdapConnection Jane() => new FakeLdapConnection()
|
||||
.WithWhoAmI("dn:" + JaneDn)
|
||||
.WithUserEntry(JaneDn, new[] { "CN=UG_A,OU=g,DC=x", "CN=UG_B,OU=g,DC=x" }, "Jane Doe");
|
||||
|
||||
private static Task<LdapAuthResult> Login(LdapAuthService svc, string user, string pw = "pw") =>
|
||||
svc.AuthenticateAsync(user, pw, CancellationToken.None);
|
||||
|
||||
[Fact]
|
||||
public async Task Success_BindsAsUser_ThenSearchesOnTheSameConnection()
|
||||
{
|
||||
var factory = new SequenceLdapConnectionFactory(Jane());
|
||||
var result = await Login(new LdapAuthService(Opts(), factory), "jdoe");
|
||||
|
||||
Assert.True(result.Succeeded);
|
||||
Assert.Equal("jdoe", result.Username);
|
||||
Assert.Equal("Jane Doe", result.DisplayName);
|
||||
Assert.Equal(new[] { "UG_A", "UG_B" }, result.Groups);
|
||||
var conn = Assert.Single(factory.Created);
|
||||
Assert.Equal(new[] { "connect", "bind:jdoe@corp.test", "whoami", "search:(sAMAccountName=jdoe)" }, conn.Calls);
|
||||
Assert.Equal(new[] { "jdoe@corp.test" }, conn.BoundDns);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(@"NAM\jdoe")]
|
||||
[InlineData("jdoe@corp.test")]
|
||||
[InlineData(" jdoe ")]
|
||||
public async Task QualifiedNames_BindAsTheTemplate_AndReturnTheBareName(string typed)
|
||||
{
|
||||
var factory = new SequenceLdapConnectionFactory(Jane());
|
||||
var result = await Login(new LdapAuthService(Opts(), factory), typed);
|
||||
|
||||
Assert.True(result.Succeeded);
|
||||
Assert.Equal("jdoe", result.Username);
|
||||
Assert.Equal(new[] { "jdoe@corp.test" }, factory.Created[0].BoundDns);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EmptyPassword_IsRefused_WithoutContactingTheDirectory()
|
||||
{
|
||||
var factory = new SequenceLdapConnectionFactory(Jane());
|
||||
var result = await Login(new LdapAuthService(Opts(), factory), "jdoe", "");
|
||||
|
||||
Assert.Equal(LdapAuthFailure.BadCredentials, result.Failure);
|
||||
Assert.Empty(factory.Created);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("@x")]
|
||||
[InlineData(@"a\b\c")]
|
||||
[InlineData("a@b@c")]
|
||||
public async Task UnusableNames_AreRefused_WithoutContactingTheDirectory(string typed)
|
||||
{
|
||||
var factory = new SequenceLdapConnectionFactory(Jane());
|
||||
var result = await Login(new LdapAuthService(Opts(), factory), typed);
|
||||
|
||||
Assert.Equal(LdapAuthFailure.BadCredentials, result.Failure);
|
||||
Assert.Empty(factory.Created);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StrictMode_RefusesQualifiedNames_WithoutContactingTheDirectory()
|
||||
{
|
||||
var factory = new SequenceLdapConnectionFactory(Jane());
|
||||
var svc = new LdapAuthService(Opts() with { AcceptDomainQualifiedNames = false }, factory);
|
||||
|
||||
var result = await Login(svc, @"NAM\jdoe");
|
||||
|
||||
Assert.Equal(LdapAuthFailure.BadCredentials, result.Failure);
|
||||
Assert.Empty(factory.Created);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task WrongPassword_IsFinal_AndNeverAsksTheFallback()
|
||||
{
|
||||
var factory = new SequenceLdapConnectionFactory(
|
||||
Jane().ThrowOnFirstBind(LdapException.InvalidCredentials), Jane());
|
||||
var result = await Login(new LdapAuthService(Opts("dc2"), factory), "jdoe", "wrong");
|
||||
|
||||
Assert.Equal(LdapAuthFailure.BadCredentials, result.Failure);
|
||||
Assert.Single(factory.Created);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task NonCredentialBindError_FailsOver()
|
||||
{
|
||||
var factory = new SequenceLdapConnectionFactory(
|
||||
Jane().ThrowOnFirstBind(LdapException.Unavailable), Jane());
|
||||
var result = await Login(new LdapAuthService(Opts("dc2"), factory), "jdoe");
|
||||
|
||||
Assert.True(result.Succeeded);
|
||||
Assert.Equal(2, factory.Created.Count);
|
||||
Assert.Equal("dc2", factory.Created[1].ConnectArgs!.Value.Host);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ConnectFailure_FailsOver()
|
||||
{
|
||||
var factory = new SequenceLdapConnectionFactory(new FakeLdapConnection().ThrowOnConnect(), Jane());
|
||||
var result = await Login(new LdapAuthService(Opts("dc2"), factory), "jdoe");
|
||||
|
||||
Assert.True(result.Succeeded);
|
||||
Assert.Equal(2, factory.Created.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SearchFailure_FailsOver()
|
||||
{
|
||||
var factory = new SequenceLdapConnectionFactory(Jane().ThrowOnSearch(), Jane());
|
||||
var result = await Login(new LdapAuthService(Opts("dc2"), factory), "jdoe");
|
||||
|
||||
Assert.True(result.Succeeded);
|
||||
Assert.Equal(2, factory.Created.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EveryEndpointDown_IsSystemSide()
|
||||
{
|
||||
var factory = new SequenceLdapConnectionFactory(
|
||||
new FakeLdapConnection().ThrowOnConnect(), new FakeLdapConnection().ThrowOnConnect());
|
||||
var result = await Login(new LdapAuthService(Opts("dc2"), factory), "jdoe");
|
||||
|
||||
Assert.Equal(LdapAuthFailure.ServiceAccountBindFailed, result.Failure);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task NoEntryAfterAGoodBind_IsGroupLookupFailed()
|
||||
{
|
||||
var factory = new SequenceLdapConnectionFactory(new FakeLdapConnection().WithWhoAmI("dn:" + JaneDn).WithNoMatch());
|
||||
var result = await Login(new LdapAuthService(Opts("dc2"), factory), "jdoe");
|
||||
|
||||
Assert.Equal(LdapAuthFailure.GroupLookupFailed, result.Failure);
|
||||
Assert.Single(factory.Created);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TwoEntriesAfterAGoodBind_IsGroupLookupFailed()
|
||||
{
|
||||
var factory = new SequenceLdapConnectionFactory(new FakeLdapConnection().WithWhoAmI("dn:cn=dup1,dc=x").WithDuplicateMatch());
|
||||
var result = await Login(new LdapAuthService(Opts(), factory), "jdoe");
|
||||
|
||||
Assert.Equal(LdapAuthFailure.GroupLookupFailed, result.Failure);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task NoGroups_IsGroupLookupFailed()
|
||||
{
|
||||
var factory = new SequenceLdapConnectionFactory(
|
||||
new FakeLdapConnection().WithWhoAmI("dn:CN=Jane,DC=x").WithUserEntry("CN=Jane,DC=x", Array.Empty<string>(), "Jane"));
|
||||
var result = await Login(new LdapAuthService(Opts(), factory), "jdoe");
|
||||
|
||||
Assert.Equal(LdapAuthFailure.GroupLookupFailed, result.Failure);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Username_IsCanonicalisedFromTheEntry_NotTheTypedCase()
|
||||
{
|
||||
var factory = new SequenceLdapConnectionFactory(new FakeLdapConnection().WithWhoAmI(@"u:NAM\jdoe").WithUserEntry(
|
||||
"CN=Jane Doe,OU=u,DC=x", new[] { "CN=UG_A,OU=g,DC=x" }, "Jane Doe",
|
||||
new Dictionary<string, string[]> { ["sAMAccountName"] = new[] { "jdoe" } }));
|
||||
var result = await Login(new LdapAuthService(Opts(), factory), @"NAM\JDOE");
|
||||
|
||||
Assert.True(result.Succeeded);
|
||||
Assert.Equal("jdoe", result.Username);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Username_FallsBackToTheTypedName_WhenTheEntryLacksTheAttribute()
|
||||
{
|
||||
var factory = new SequenceLdapConnectionFactory(Jane());
|
||||
var result = await Login(new LdapAuthService(Opts(), factory), "JDOE");
|
||||
|
||||
Assert.True(result.Succeeded);
|
||||
Assert.Equal("JDOE", result.Username);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Search_RequestsTheUserNameAttribute()
|
||||
{
|
||||
var factory = new SequenceLdapConnectionFactory(Jane());
|
||||
await Login(new LdapAuthService(Opts(), factory), "jdoe");
|
||||
|
||||
Assert.Equal(new[] { "displayName", "memberOf", "sAMAccountName" }, factory.Created[0].SearchAttributes);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Search_DeDuplicatesTheUserNameAttribute_CaseInsensitively()
|
||||
{
|
||||
var factory = new SequenceLdapConnectionFactory(Jane());
|
||||
var svc = new LdapAuthService(Opts() with { DisplayNameAttribute = "SAMACCOUNTNAME" }, factory);
|
||||
await Login(svc, "jdoe");
|
||||
|
||||
Assert.Equal(new[] { "SAMACCOUNTNAME", "memberOf" }, factory.Created[0].SearchAttributes);
|
||||
}
|
||||
|
||||
// ---- Auth-007 (scadaproj#40): the entry whose groups are returned must be the account that bound ----
|
||||
|
||||
/// <summary>
|
||||
/// The review's scenario: a UPN bind for <c>jsmith</c> is resolved by AD to Mallory (explicit UPN
|
||||
/// <c>jsmith@corp.test</c>, sAMAccountName <c>jsmith2</c>), while <c>(sAMAccountName=jsmith)</c>
|
||||
/// finds the admin. Before the fix this returned the admin's groups to Mallory.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task UpnBind_ResolvedToAnotherAccount_DoesNotReturnTheSearchedEntrysGroups()
|
||||
{
|
||||
var fake = new FakeLdapConnection()
|
||||
.WithWhoAmI(@"u:CORP\jsmith2")
|
||||
.WithUserEntry("CN=Admin Smith,OU=u,DC=x", new[] { "CN=UG_Admins,OU=g,DC=x" }, "Admin Smith",
|
||||
new Dictionary<string, string[]> { ["sAMAccountName"] = new[] { "jsmith" } });
|
||||
var factory = new SequenceLdapConnectionFactory(fake);
|
||||
|
||||
var result = await Login(new LdapAuthService(Opts(), factory), "jsmith", "mallorys-own-password");
|
||||
|
||||
Assert.False(result.Succeeded);
|
||||
Assert.Equal(LdapAuthFailure.GroupLookupFailed, result.Failure);
|
||||
Assert.Empty(result.Groups);
|
||||
Assert.Equal(new[] { "jsmith@corp.test" }, fake.BoundDns);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task WhoAmIAccountName_MatchingTheEntry_Succeeds_AndRequestsSamAccountName()
|
||||
{
|
||||
var fake = new FakeLdapConnection()
|
||||
.WithWhoAmI(@"u:CORP\JSmith")
|
||||
.WithUserEntry("CN=John Smith,OU=u,DC=x", new[] { "CN=UG_A,OU=g,DC=x" }, "John Smith",
|
||||
new Dictionary<string, string[]> { ["sAMAccountName"] = new[] { "jsmith" } });
|
||||
var factory = new SequenceLdapConnectionFactory(fake);
|
||||
var svc = new LdapAuthService(Opts() with { UserNameAttribute = "cn" }, factory);
|
||||
|
||||
var result = await Login(svc, "John Smith");
|
||||
|
||||
Assert.True(result.Succeeded);
|
||||
Assert.Contains("sAMAccountName", fake.SearchAttributes!);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task WhoAmIAccountName_WithoutDomain_IsAccepted()
|
||||
{
|
||||
var fake = new FakeLdapConnection()
|
||||
.WithWhoAmI("u:jdoe")
|
||||
.WithUserEntry(JaneDn, new[] { "CN=UG_A,OU=g,DC=x" }, "Jane Doe",
|
||||
new Dictionary<string, string[]> { ["sAMAccountName"] = new[] { "jdoe" } });
|
||||
|
||||
var result = await Login(new LdapAuthService(Opts(), new SequenceLdapConnectionFactory(fake)), "jdoe");
|
||||
|
||||
Assert.True(result.Succeeded);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task WhoAmIAccountName_EntryWithoutSamAccountName_FailsClosed()
|
||||
{
|
||||
var fake = new FakeLdapConnection()
|
||||
.WithWhoAmI(@"u:CORP\jdoe")
|
||||
.WithUserEntry(JaneDn, new[] { "CN=UG_A,OU=g,DC=x" }, "Jane Doe");
|
||||
|
||||
var result = await Login(new LdapAuthService(Opts(), new SequenceLdapConnectionFactory(fake)), "jdoe");
|
||||
|
||||
Assert.Equal(LdapAuthFailure.GroupLookupFailed, result.Failure);
|
||||
}
|
||||
|
||||
// ---- scadaproj#50: an AD forest — the same sAMAccountName in two domains ----------------------
|
||||
|
||||
// A Global Catalog search base spans every domain in the forest. CORP\jsmith binds; the search
|
||||
// (here on mail, so the filter is not sAMAccountName) finds OTHER\jsmith, whose sAMAccountName is
|
||||
// also "jsmith". 0.4.4 compared sAMAccountName alone and returned OTHER\jsmith's groups.
|
||||
private const string OtherDn = "CN=J Smith,OU=u,DC=other,DC=forest";
|
||||
private const string CorpDn = "CN=John Smith,OU=u,DC=corp,DC=forest";
|
||||
|
||||
private static FakeLdapConnection ForestSearchFinding(string dn) => new FakeLdapConnection()
|
||||
.WithWhoAmI(@"u:CORP\jsmith")
|
||||
.WithUserEntry(dn, new[] { "CN=UG_Admins,OU=g,DC=other,DC=forest" }, "J Smith",
|
||||
new Dictionary<string, string[]> { ["sAMAccountName"] = new[] { "jsmith" }, ["mail"] = new[] { "jsmith" } });
|
||||
|
||||
private static LdapOptions ForestOpts() => Opts() with { UserNameAttribute = "mail", SearchBase = "DC=forest" };
|
||||
|
||||
[Fact]
|
||||
public async Task Forest_PrincipalNameInAnotherDomain_FailsClosed()
|
||||
{
|
||||
var fake = ForestSearchFinding(OtherDn).WithPrincipalName(@"OTHER\jsmith");
|
||||
|
||||
var result = await Login(new LdapAuthService(ForestOpts(), new SequenceLdapConnectionFactory(fake)), "jsmith");
|
||||
|
||||
Assert.Equal(LdapAuthFailure.GroupLookupFailed, result.Failure);
|
||||
Assert.Empty(result.Groups);
|
||||
Assert.Contains("read:" + OtherDn, fake.Calls);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Forest_PrincipalNameInTheBoundDomain_Succeeds()
|
||||
{
|
||||
var fake = ForestSearchFinding(CorpDn).WithPrincipalName(@"corp\JSMITH");
|
||||
|
||||
var result = await Login(new LdapAuthService(ForestOpts(), new SequenceLdapConnectionFactory(fake)), "jsmith");
|
||||
|
||||
Assert.True(result.Succeeded);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Forest_NoPrincipalName_AndTheNameIsHeldInTwoDomains_FailsClosed()
|
||||
{
|
||||
// The directory offers no msDS-PrincipalName, so which jsmith bound cannot be proven; with two
|
||||
// holders of the name in scope the sign-in is refused rather than guessed.
|
||||
var fake = ForestSearchFinding(OtherDn)
|
||||
.WithSearchResult("(sAMAccountName=jsmith)", (CorpDn, "jsmith"), (OtherDn, "jsmith"));
|
||||
|
||||
var result = await Login(new LdapAuthService(ForestOpts(), new SequenceLdapConnectionFactory(fake)), "jsmith");
|
||||
|
||||
Assert.Equal(LdapAuthFailure.GroupLookupFailed, result.Failure);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Forest_NoPrincipalName_AndTheReadFails_StillFallsBackToTheUniquenessCheck()
|
||||
{
|
||||
var fake = ForestSearchFinding(OtherDn).ThrowOnRead()
|
||||
.WithSearchResult("(sAMAccountName=jsmith)", (CorpDn, "jsmith"), (OtherDn, "jsmith"));
|
||||
|
||||
var result = await Login(new LdapAuthService(ForestOpts(), new SequenceLdapConnectionFactory(fake)), "jsmith");
|
||||
|
||||
Assert.Equal(LdapAuthFailure.GroupLookupFailed, result.Failure);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SingleDomain_NoPrincipalName_UniqueName_Succeeds()
|
||||
{
|
||||
// Compatibility: a single-domain directory without msDS-PrincipalName still signs in — the
|
||||
// name has exactly one holder in scope, and it is the entry found.
|
||||
var fake = ForestSearchFinding(CorpDn).WithSearchResult("(sAMAccountName=jsmith)", (CorpDn, "jsmith"));
|
||||
|
||||
var result = await Login(new LdapAuthService(ForestOpts(), new SequenceLdapConnectionFactory(fake)), "jsmith");
|
||||
|
||||
Assert.True(result.Succeeded);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SamAccountNameSearch_ForTheBoundName_NeedsNoSecondSearch()
|
||||
{
|
||||
// When the user search itself was (sAMAccountName=<the bound name>) and found exactly one
|
||||
// entry, the name is already proven unique in scope.
|
||||
var fake = new FakeLdapConnection()
|
||||
.WithWhoAmI(@"u:CORP\jdoe")
|
||||
.WithUserEntry(JaneDn, new[] { "CN=UG_A,OU=g,DC=x" }, "Jane Doe",
|
||||
new Dictionary<string, string[]> { ["sAMAccountName"] = new[] { "jdoe" } });
|
||||
|
||||
var result = await Login(new LdapAuthService(Opts(), new SequenceLdapConnectionFactory(fake)), "jdoe");
|
||||
|
||||
Assert.True(result.Succeeded);
|
||||
Assert.Single(fake.Calls, c => c.StartsWith("search:", StringComparison.Ordinal));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task WhoAmIDn_NamingAnotherEntry_FailsClosed()
|
||||
{
|
||||
var fake = new FakeLdapConnection()
|
||||
.WithWhoAmI("dn:CN=Mallory,OU=u,DC=x")
|
||||
.WithUserEntry("CN=Admin Smith,OU=u,DC=x", new[] { "CN=UG_Admins,OU=g,DC=x" }, "Admin Smith");
|
||||
|
||||
var result = await Login(new LdapAuthService(Opts(), new SequenceLdapConnectionFactory(fake)), "jsmith");
|
||||
|
||||
Assert.Equal(LdapAuthFailure.GroupLookupFailed, result.Failure);
|
||||
Assert.Empty(result.Groups);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task WhoAmIDn_IsComparedAsADn_NotAsAString()
|
||||
{
|
||||
var fake = new FakeLdapConnection()
|
||||
.WithWhoAmI("dn:cn=jane doe, ou=U, dc=X")
|
||||
.WithUserEntry(JaneDn, new[] { "CN=UG_A,OU=g,DC=x" }, "Jane Doe");
|
||||
|
||||
var result = await Login(new LdapAuthService(Opts(), new SequenceLdapConnectionFactory(fake)), "jdoe");
|
||||
|
||||
Assert.True(result.Succeeded);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)] // server does not support Who-am-I (GLAuth: protocol error 2)
|
||||
[InlineData("")] // anonymous / empty answer
|
||||
[InlineData("x:garbage")]
|
||||
public async Task UpnTemplate_WithoutAWhoAmIAnswer_FailsClosed_WithoutSearching(string? whoAmI)
|
||||
{
|
||||
var fake = new FakeLdapConnection()
|
||||
.WithUserEntry(JaneDn, new[] { "CN=UG_A,OU=g,DC=x" }, "Jane Doe");
|
||||
if (whoAmI is not null)
|
||||
fake.WithWhoAmI(whoAmI);
|
||||
|
||||
var result = await Login(new LdapAuthService(Opts(), new SequenceLdapConnectionFactory(fake)), "jdoe");
|
||||
|
||||
Assert.Equal(LdapAuthFailure.GroupLookupFailed, result.Failure);
|
||||
Assert.DoesNotContain(fake.Calls, c => c.StartsWith("search:", StringComparison.Ordinal));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DownLevelTemplate_WithoutAWhoAmIAnswer_FailsClosed()
|
||||
{
|
||||
var fake = new FakeLdapConnection()
|
||||
.WithUserEntry(JaneDn, new[] { "CN=UG_A,OU=g,DC=x" }, "Jane Doe");
|
||||
var svc = new LdapAuthService(Opts() with { UserBindTemplate = @"CORP\{0}" }, new SequenceLdapConnectionFactory(fake));
|
||||
|
||||
var result = await Login(svc, "jdoe");
|
||||
|
||||
Assert.Equal(LdapAuthFailure.GroupLookupFailed, result.Failure);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DnTemplate_WithoutWhoAmI_AcceptsTheEntryAtTheBoundDn()
|
||||
{
|
||||
var fake = new FakeLdapConnection()
|
||||
.WithUserEntry("cn=jdoe,ou=Users,dc=x", new[] { "cn=UG_A,ou=g,dc=x" }, "Jane Doe");
|
||||
var svc = new LdapAuthService(
|
||||
Opts() with { UserBindTemplate = "cn={0},ou=users,dc=x", UserNameAttribute = "cn" },
|
||||
new SequenceLdapConnectionFactory(fake));
|
||||
|
||||
var result = await Login(svc, "jdoe");
|
||||
|
||||
Assert.True(result.Succeeded);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DnTemplate_WithoutWhoAmI_RefusesAnEntryAtAnotherDn()
|
||||
{
|
||||
// Mallory binds as cn=mallory with her own password; (mail=mallory) finds the admin.
|
||||
var fake = new FakeLdapConnection()
|
||||
.WithUserEntry("cn=admin,ou=Users,dc=x", new[] { "cn=UG_Admins,ou=g,dc=x" }, "Admin");
|
||||
var svc = new LdapAuthService(
|
||||
Opts() with { UserBindTemplate = "cn={0},ou=users,dc=x", UserNameAttribute = "mail" },
|
||||
new SequenceLdapConnectionFactory(fake));
|
||||
|
||||
var result = await Login(svc, "mallory");
|
||||
|
||||
Assert.Equal(LdapAuthFailure.GroupLookupFailed, result.Failure);
|
||||
Assert.Equal(new[] { "cn=mallory,ou=users,dc=x" }, fake.BoundDns);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DnTemplate_EscapesTheName_SoItCannotRewriteTheBindDn()
|
||||
{
|
||||
var fake = new FakeLdapConnection()
|
||||
.WithUserEntry("cn=admin,ou=Admins,dc=x", new[] { "cn=UG_Admins,ou=g,dc=x" }, "Admin");
|
||||
var svc = new LdapAuthService(
|
||||
Opts() with { UserBindTemplate = "cn={0},ou=users,dc=x", UserNameAttribute = "cn" },
|
||||
new SequenceLdapConnectionFactory(fake));
|
||||
|
||||
var result = await Login(svc, "admin,ou=Admins");
|
||||
|
||||
Assert.Equal(new[] { @"cn=admin\,ou=Admins,ou=users,dc=x" }, fake.BoundDns);
|
||||
Assert.False(result.Succeeded);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
using ZB.MOM.WW.Auth.Ldap.Internal;
|
||||
|
||||
namespace ZB.MOM.WW.Auth.Ldap.Tests;
|
||||
|
||||
public class LdapEndpointParserTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData("dc2.example.com", 636, "dc2.example.com", 636)] // bare host -> default port
|
||||
[InlineData("dc2.example.com:3894", 636, "dc2.example.com", 3894)] // explicit port wins
|
||||
[InlineData(" dc2.example.com : 3894 ", 636, "dc2.example.com", 3894)] // whitespace tolerated
|
||||
public void TryParse_ValidEntry_Succeeds(string entry, int defaultPort, string host, int port)
|
||||
{
|
||||
Assert.True(LdapEndpointParser.TryParse(entry, defaultPort, out var ep, out _));
|
||||
Assert.Equal(host, ep.Host);
|
||||
Assert.Equal(port, ep.Port);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("")] // empty
|
||||
[InlineData(" ")] // whitespace
|
||||
[InlineData(":636")] // empty host
|
||||
[InlineData("dc2:0")] // port below range
|
||||
[InlineData("dc2:65536")] // port above range
|
||||
[InlineData("dc2:abc")] // non-numeric port
|
||||
[InlineData("2001:db8::1:636")] // IPv6 literal (unsupported, >1 colon)
|
||||
public void TryParse_InvalidEntry_Fails(string entry)
|
||||
{
|
||||
Assert.False(LdapEndpointParser.TryParse(entry, 636, out _, out var error));
|
||||
Assert.NotEmpty(error);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Endpoint_ToString_IsHostColonPort() =>
|
||||
Assert.Equal("dc2:3894", new LdapEndpoint("dc2", 3894).ToString());
|
||||
}
|
||||
@@ -0,0 +1,342 @@
|
||||
using ZB.MOM.WW.Auth.Abstractions.Ldap;
|
||||
|
||||
namespace ZB.MOM.WW.Auth.Ldap.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// 0.5.0 passwordless group lookup (<see cref="ILdapGroupLookup"/>): statuses, parity with
|
||||
/// <see cref="LdapAuthService.AuthenticateAsync"/>'s group set, the shared failover walk, and the
|
||||
/// configurations that cannot search without a password.
|
||||
/// </summary>
|
||||
public class LdapGroupLookupTests
|
||||
{
|
||||
private static LdapOptions Opts(params string[] fallbacks) => new()
|
||||
{
|
||||
Enabled = true,
|
||||
Server = "dc1",
|
||||
Port = 636,
|
||||
Transport = LdapTransport.Ldaps,
|
||||
SearchBase = "dc=x",
|
||||
ServiceAccountDn = "cn=svc,dc=x",
|
||||
ServiceAccountPassword = "svcpw",
|
||||
UserNameAttribute = "sAMAccountName",
|
||||
DisplayNameAttribute = "displayName",
|
||||
FallbackServers = fallbacks,
|
||||
};
|
||||
|
||||
private static FakeLdapConnection Alice(string? userAccountControl = null)
|
||||
{
|
||||
var extra = new Dictionary<string, string[]> { ["sAMAccountName"] = new[] { "Alice" } };
|
||||
if (userAccountControl is not null)
|
||||
extra["userAccountControl"] = new[] { userAccountControl };
|
||||
return new FakeLdapConnection().WithUserEntry(
|
||||
"cn=Alice,ou=people,dc=x",
|
||||
new[] { "cn=Operators,ou=g,dc=x", @"cn=Eng\,ineers,ou=g,dc=x" },
|
||||
displayName: "Alice Smith",
|
||||
extraAttributes: extra);
|
||||
}
|
||||
|
||||
// ---- the happy path and parity with AuthenticateAsync ----
|
||||
|
||||
[Fact]
|
||||
public async Task Found_ReturnsCanonicalNameDisplayNameAndGroups_WithServiceAccountOnly()
|
||||
{
|
||||
var fake = Alice();
|
||||
var svc = new LdapAuthService(Opts(), new FakeLdapConnectionFactory(fake));
|
||||
|
||||
var result = await svc.GetUserGroupsAsync(" alice ", CancellationToken.None);
|
||||
|
||||
Assert.Equal(LdapGroupLookupStatus.Found, result.Status);
|
||||
Assert.True(result.IsFound);
|
||||
Assert.Equal("Alice", result.Username); // directory spelling, not the typed one
|
||||
Assert.Equal("Alice Smith", result.DisplayName);
|
||||
Assert.Equal(new[] { "Operators", "Eng,ineers" }, result.Groups);
|
||||
// Exactly one bind, as the service account — never a bind as the user.
|
||||
Assert.Equal(new[] { "cn=svc,dc=x" }, fake.BoundDns);
|
||||
Assert.Equal(1, fake.BindAttempts);
|
||||
Assert.Contains("search:(sAMAccountName=alice)", fake.Calls);
|
||||
Assert.Contains("userAccountControl", fake.SearchAttributes!);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Found_MatchesTheGroupSetAuthenticateAsyncReturns()
|
||||
{
|
||||
var lookup = await new LdapAuthService(Opts(), new FakeLdapConnectionFactory(Alice()))
|
||||
.GetUserGroupsAsync("alice", CancellationToken.None);
|
||||
var login = await new LdapAuthService(Opts(), new FakeLdapConnectionFactory(Alice()))
|
||||
.AuthenticateAsync("alice", "pw", CancellationToken.None);
|
||||
|
||||
Assert.True(login.Succeeded);
|
||||
Assert.Equal(login.Groups, lookup.Groups);
|
||||
Assert.Equal(login.Username, lookup.Username);
|
||||
Assert.Equal(login.DisplayName, lookup.DisplayName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Found_WithZeroGroups_IsFoundWithAnEmptySet()
|
||||
{
|
||||
var fake = new FakeLdapConnection().WithUserEntry("cn=bob,dc=x", Array.Empty<string>());
|
||||
var svc = new LdapAuthService(Opts(), new FakeLdapConnectionFactory(fake));
|
||||
|
||||
var result = await svc.GetUserGroupsAsync("bob", CancellationToken.None);
|
||||
|
||||
Assert.Equal(LdapGroupLookupStatus.Found, result.Status);
|
||||
Assert.Empty(result.Groups);
|
||||
}
|
||||
|
||||
// ---- directory answers ----
|
||||
|
||||
[Fact]
|
||||
public async Task NoEntry_IsUserNotFound()
|
||||
{
|
||||
var svc = new LdapAuthService(Opts(), new FakeLdapConnectionFactory(new FakeLdapConnection().WithNoMatch()));
|
||||
|
||||
var result = await svc.GetUserGroupsAsync("ghost", CancellationToken.None);
|
||||
|
||||
Assert.Equal(LdapGroupLookupStatus.UserNotFound, result.Status);
|
||||
Assert.Empty(result.Groups);
|
||||
Assert.Equal("", result.Username);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TwoEntries_IsAmbiguousUser()
|
||||
{
|
||||
var svc = new LdapAuthService(Opts(), new FakeLdapConnectionFactory(new FakeLdapConnection().WithDuplicateMatch()));
|
||||
|
||||
var result = await svc.GetUserGroupsAsync("dup", CancellationToken.None);
|
||||
|
||||
Assert.Equal(LdapGroupLookupStatus.AmbiguousUser, result.Status);
|
||||
Assert.Empty(result.Groups);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("514")] // NORMAL_ACCOUNT | ACCOUNTDISABLE
|
||||
[InlineData("66050")] // + DONT_EXPIRE_PASSWORD
|
||||
[InlineData("2")]
|
||||
public async Task AccountDisableFlag_IsUserDisabled_AndReturnsNoGroups(string uac)
|
||||
{
|
||||
var svc = new LdapAuthService(Opts(), new FakeLdapConnectionFactory(Alice(uac)));
|
||||
|
||||
var result = await svc.GetUserGroupsAsync("alice", CancellationToken.None);
|
||||
|
||||
Assert.Equal(LdapGroupLookupStatus.UserDisabled, result.Status);
|
||||
Assert.Empty(result.Groups);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("512")] // NORMAL_ACCOUNT
|
||||
[InlineData("66048")] // + DONT_EXPIRE_PASSWORD
|
||||
[InlineData("garbage")] // unparseable is "not disabled", never a fault
|
||||
public async Task EnabledOrUnparseableAccountControl_IsFound(string uac)
|
||||
{
|
||||
var svc = new LdapAuthService(Opts(), new FakeLdapConnectionFactory(Alice(uac)));
|
||||
|
||||
var result = await svc.GetUserGroupsAsync("alice", CancellationToken.None);
|
||||
|
||||
Assert.Equal(LdapGroupLookupStatus.Found, result.Status);
|
||||
}
|
||||
|
||||
// ---- system-side faults and failover ----
|
||||
|
||||
[Fact]
|
||||
public async Task ConnectFailure_OnOnlyEndpoint_IsDirectoryUnavailable()
|
||||
{
|
||||
var svc = new LdapAuthService(Opts(), new FakeLdapConnectionFactory(new FakeLdapConnection().ThrowOnConnect()));
|
||||
|
||||
var result = await svc.GetUserGroupsAsync("alice", CancellationToken.None);
|
||||
|
||||
Assert.Equal(LdapGroupLookupStatus.DirectoryUnavailable, result.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ServiceBindFailure_IsDirectoryUnavailable_NotUserNotFound()
|
||||
{
|
||||
var svc = new LdapAuthService(Opts(), new FakeLdapConnectionFactory(Alice().ThrowOnServiceBind()));
|
||||
|
||||
var result = await svc.GetUserGroupsAsync("alice", CancellationToken.None);
|
||||
|
||||
Assert.Equal(LdapGroupLookupStatus.DirectoryUnavailable, result.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SearchFailure_IsDirectoryUnavailable()
|
||||
{
|
||||
var svc = new LdapAuthService(Opts(), new FakeLdapConnectionFactory(Alice().ThrowOnSearch()));
|
||||
|
||||
var result = await svc.GetUserGroupsAsync("alice", CancellationToken.None);
|
||||
|
||||
Assert.Equal(LdapGroupLookupStatus.DirectoryUnavailable, result.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ConnectFailure_FailsOverToFallback_AndFindsTheUser()
|
||||
{
|
||||
var factory = new SequenceLdapConnectionFactory(new FakeLdapConnection().ThrowOnConnect(), Alice());
|
||||
var svc = new LdapAuthService(Opts("dc2:3894"), factory);
|
||||
|
||||
var result = await svc.GetUserGroupsAsync("alice", CancellationToken.None);
|
||||
|
||||
Assert.Equal(LdapGroupLookupStatus.Found, result.Status);
|
||||
Assert.Equal(2, factory.Created.Count);
|
||||
Assert.Equal(("dc2", 3894), (factory.Created[1].ConnectArgs!.Value.Host, factory.Created[1].ConnectArgs!.Value.Port));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SearchFailure_FailsOverToFallback()
|
||||
{
|
||||
var factory = new SequenceLdapConnectionFactory(Alice().ThrowOnSearch(), Alice());
|
||||
var svc = new LdapAuthService(Opts("dc2"), factory);
|
||||
|
||||
var result = await svc.GetUserGroupsAsync("alice", CancellationToken.None);
|
||||
|
||||
Assert.Equal(LdapGroupLookupStatus.Found, result.Status);
|
||||
Assert.Equal(2, factory.Created.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UserNotFound_IsFinal_AndDoesNotFailOver()
|
||||
{
|
||||
var factory = new SequenceLdapConnectionFactory(new FakeLdapConnection(), Alice());
|
||||
var svc = new LdapAuthService(Opts("dc2"), factory);
|
||||
|
||||
var result = await svc.GetUserGroupsAsync("alice", CancellationToken.None);
|
||||
|
||||
Assert.Equal(LdapGroupLookupStatus.UserNotFound, result.Status);
|
||||
Assert.Single(factory.Created);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AllEndpointsDown_IsDirectoryUnavailable_AfterTryingEach()
|
||||
{
|
||||
var factory = new SequenceLdapConnectionFactory(
|
||||
new FakeLdapConnection().ThrowOnConnect(), new FakeLdapConnection().ThrowOnServiceBind());
|
||||
var svc = new LdapAuthService(Opts("dc2"), factory);
|
||||
|
||||
var result = await svc.GetUserGroupsAsync("alice", CancellationToken.None);
|
||||
|
||||
Assert.Equal(LdapGroupLookupStatus.DirectoryUnavailable, result.Status);
|
||||
Assert.Equal(2, factory.Created.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StickyPreference_IsSharedWithAuthentication()
|
||||
{
|
||||
// A lookup that fails over to dc2 makes dc2 preferred for the next sign-in too.
|
||||
var factory = new SequenceLdapConnectionFactory(
|
||||
new FakeLdapConnection().ThrowOnConnect(), Alice(), Alice());
|
||||
var svc = new LdapAuthService(Opts("dc2"), factory);
|
||||
|
||||
await svc.GetUserGroupsAsync("alice", CancellationToken.None);
|
||||
var login = await svc.AuthenticateAsync("alice", "pw", CancellationToken.None);
|
||||
|
||||
Assert.True(login.Succeeded);
|
||||
Assert.Equal(3, factory.Created.Count);
|
||||
Assert.Equal("dc2", factory.Created[2].ConnectArgs!.Value.Host);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UsesConfiguredTransportTimeoutAndCertificatePolicy()
|
||||
{
|
||||
System.Net.Security.RemoteCertificateValidationCallback callback = (_, _, _, _) => true;
|
||||
var fake = Alice();
|
||||
var options = Opts() with { Transport = LdapTransport.StartTls, ConnectionTimeoutMs = 1234, ServerCertificateValidationCallback = callback };
|
||||
var svc = new LdapAuthService(options, new FakeLdapConnectionFactory(fake));
|
||||
|
||||
await svc.GetUserGroupsAsync("alice", CancellationToken.None);
|
||||
|
||||
Assert.Equal(LdapTransport.StartTls, fake.ConnectArgs!.Value.Transport);
|
||||
Assert.Equal(1234, fake.ConnectArgs!.Value.TimeoutMs);
|
||||
Assert.Same(callback, fake.ConnectCertCallback);
|
||||
}
|
||||
|
||||
// ---- configurations that cannot look up ----
|
||||
|
||||
[Fact]
|
||||
public async Task UserBindMode_IsNotSupported_WithoutTouchingTheNetwork()
|
||||
{
|
||||
var fake = Alice();
|
||||
var options = Opts() with { BindMode = LdapBindMode.User, UserBindTemplate = @"X\{0}", ServiceAccountDn = "" };
|
||||
var svc = new LdapAuthService(options, new FakeLdapConnectionFactory(fake));
|
||||
|
||||
var result = await svc.GetUserGroupsAsync("alice", CancellationToken.None);
|
||||
|
||||
Assert.Equal(LdapGroupLookupStatus.NotSupported, result.Status);
|
||||
Assert.Empty(fake.Calls);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UserBindMode_IsNotSupported_EvenWithAServiceAccountConfigured()
|
||||
{
|
||||
var fake = Alice();
|
||||
var options = Opts() with { BindMode = LdapBindMode.User, UserBindTemplate = @"X\{0}" };
|
||||
var svc = new LdapAuthService(options, new FakeLdapConnectionFactory(fake));
|
||||
|
||||
var result = await svc.GetUserGroupsAsync("alice", CancellationToken.None);
|
||||
|
||||
Assert.Equal(LdapGroupLookupStatus.NotSupported, result.Status);
|
||||
Assert.Empty(fake.Calls);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task BlankServiceAccount_IsNotSupported_NeverAnAnonymousBind()
|
||||
{
|
||||
var fake = Alice();
|
||||
var svc = new LdapAuthService(Opts() with { ServiceAccountDn = " " }, new FakeLdapConnectionFactory(fake));
|
||||
|
||||
var result = await svc.GetUserGroupsAsync("alice", CancellationToken.None);
|
||||
|
||||
Assert.Equal(LdapGroupLookupStatus.NotSupported, result.Status);
|
||||
Assert.Empty(fake.Calls);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DisabledProvider_IsProviderDisabled_WithoutTouchingTheNetwork()
|
||||
{
|
||||
var fake = Alice();
|
||||
var svc = new LdapAuthService(Opts() with { Enabled = false }, new FakeLdapConnectionFactory(fake));
|
||||
|
||||
var result = await svc.GetUserGroupsAsync("alice", CancellationToken.None);
|
||||
|
||||
Assert.Equal(LdapGroupLookupStatus.ProviderDisabled, result.Status);
|
||||
Assert.Empty(fake.Calls);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)]
|
||||
[InlineData("")]
|
||||
[InlineData(" ")]
|
||||
public async Task BlankUsername_IsUserNotFound_WithoutTouchingTheNetwork(string? username)
|
||||
{
|
||||
var fake = Alice();
|
||||
var svc = new LdapAuthService(Opts(), new FakeLdapConnectionFactory(fake));
|
||||
|
||||
var result = await svc.GetUserGroupsAsync(username!, CancellationToken.None);
|
||||
|
||||
Assert.Equal(LdapGroupLookupStatus.UserNotFound, result.Status);
|
||||
Assert.Empty(fake.Calls);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task FilterMetacharacters_AreEscaped()
|
||||
{
|
||||
var fake = new FakeLdapConnection();
|
||||
var svc = new LdapAuthService(Opts(), new FakeLdapConnectionFactory(fake));
|
||||
|
||||
await svc.GetUserGroupsAsync("*)(cn=*", CancellationToken.None);
|
||||
|
||||
Assert.Contains(@"search:(sAMAccountName=\2a\29\28cn=\2a)", fake.Calls);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CancelledToken_Throws()
|
||||
{
|
||||
var svc = new LdapAuthService(Opts(), new FakeLdapConnectionFactory(Alice()));
|
||||
using var cts = new CancellationTokenSource();
|
||||
cts.Cancel();
|
||||
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => svc.GetUserGroupsAsync("alice", cts.Token));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Of_RefusesFound()
|
||||
=> Assert.Throws<ArgumentException>(() => LdapGroupLookupResult.Of(LdapGroupLookupStatus.Found));
|
||||
}
|
||||
@@ -88,4 +88,66 @@ public class LdapOptionsValidatorTests
|
||||
ServiceAccountDn = "",
|
||||
})
|
||||
.Failed);
|
||||
|
||||
[Fact]
|
||||
public void Validator_Succeeds_WithValidFallbackServers() =>
|
||||
Assert.False(new LdapOptionsValidator()
|
||||
.Validate(null, Opts() with { FallbackServers = new[] { "dc2", "dc3:3894" } })
|
||||
.Failed);
|
||||
|
||||
[Theory]
|
||||
[InlineData("")]
|
||||
[InlineData(":636")]
|
||||
[InlineData("dc2:0")]
|
||||
[InlineData("dc2:notaport")]
|
||||
public void Validator_Fails_OnMalformedFallbackServer(string entry)
|
||||
{
|
||||
var result = new LdapOptionsValidator()
|
||||
.Validate(null, Opts() with { FallbackServers = new[] { entry } });
|
||||
|
||||
Assert.True(result.Failed);
|
||||
Assert.Contains(nameof(LdapOptions.FallbackServers), result.FailureMessage);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validator_Skips_FallbackServers_WhenDisabled() =>
|
||||
// Same inert-when-disabled rule as every other connection field: a disabled
|
||||
// provider never opens a connection, so its fallback list is never walked.
|
||||
Assert.False(new LdapOptionsValidator()
|
||||
.Validate(null, Opts() with { Enabled = false, FallbackServers = new[] { ":::" } })
|
||||
.Failed);
|
||||
|
||||
private static LdapOptions UserOpts() => Opts() with
|
||||
{
|
||||
BindMode = LdapBindMode.User,
|
||||
UserBindTemplate = "{0}@corp.test",
|
||||
ServiceAccountDn = "",
|
||||
ServiceAccountPassword = "",
|
||||
};
|
||||
|
||||
[Fact]
|
||||
public void Defaults_KeepServiceAccountMode()
|
||||
{
|
||||
var o = new LdapOptions();
|
||||
Assert.Equal(LdapBindMode.ServiceAccount, o.BindMode);
|
||||
Assert.Equal("", o.UserBindTemplate);
|
||||
Assert.True(o.AcceptDomainQualifiedNames);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validator_UserMode_DoesNotRequireServiceAccount() =>
|
||||
Assert.True(new LdapOptionsValidator().Validate(null, UserOpts()).Succeeded);
|
||||
|
||||
[Theory]
|
||||
[InlineData("")]
|
||||
[InlineData(" ")]
|
||||
[InlineData("jdoe@corp.test")]
|
||||
[InlineData("{0}{0}@corp.test")]
|
||||
public void Validator_UserMode_RequiresExactlyOnePlaceholder(string template)
|
||||
{
|
||||
var result = new LdapOptionsValidator().Validate(null, UserOpts() with { UserBindTemplate = template });
|
||||
|
||||
Assert.True(result.Failed);
|
||||
Assert.Contains(nameof(LdapOptions.UserBindTemplate), result.FailureMessage, StringComparison.Ordinal);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
using ZB.MOM.WW.Auth.Ldap.Internal;
|
||||
|
||||
namespace ZB.MOM.WW.Auth.Ldap.Tests;
|
||||
|
||||
public class LdapUserNameTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData("jdoe")]
|
||||
[InlineData(" jdoe ")]
|
||||
[InlineData(@"NAM\jdoe")]
|
||||
[InlineData("jdoe@corp.test")]
|
||||
public void Accepting_ReducesToBareName(string input)
|
||||
{
|
||||
Assert.True(LdapUserName.TryNormalize(input, acceptDomainQualified: true, out var name));
|
||||
Assert.Equal("jdoe", name);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(@"NAM\jdoe")]
|
||||
[InlineData("jdoe@corp.test")]
|
||||
public void Strict_RefusesQualifiedNames(string input) =>
|
||||
Assert.False(LdapUserName.TryNormalize(input, acceptDomainQualified: false, out _));
|
||||
|
||||
[Fact]
|
||||
public void Strict_AcceptsBareName()
|
||||
{
|
||||
Assert.True(LdapUserName.TryNormalize(" jdoe ", acceptDomainQualified: false, out var name));
|
||||
Assert.Equal("jdoe", name);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)]
|
||||
[InlineData("")]
|
||||
[InlineData(" ")]
|
||||
[InlineData("@x")]
|
||||
[InlineData(@"\jdoe")]
|
||||
[InlineData("jdoe@")]
|
||||
[InlineData(@"NAM\")]
|
||||
[InlineData(@"a\b\c")]
|
||||
[InlineData("a@b@c")]
|
||||
[InlineData(@"NAM\jdoe@corp.test")]
|
||||
public void Unusable_IsRefused(string? input)
|
||||
{
|
||||
Assert.False(LdapUserName.TryNormalize(input, acceptDomainQualified: true, out var name));
|
||||
Assert.Equal("", name);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
using Novell.Directory.Ldap;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.Auth.Ldap.Internal;
|
||||
|
||||
namespace ZB.MOM.WW.Auth.Ldap.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Covers <see cref="NovellLdapConnection.ReadEntries"/>' handling of AD continuation
|
||||
/// referrals. Active Directory returns one for any search based at a domain root, and
|
||||
/// Novell surfaces it by throwing from <c>Next()</c>. Before this was handled, the
|
||||
/// exception escaped the search stage and every login against
|
||||
/// <c>DC=nam,DC=zimmer,DC=com</c> failed as <c>ServiceAccountBindFailed</c> while the
|
||||
/// directory and credentials were healthy.
|
||||
/// </summary>
|
||||
public sealed class NovellSearchReferralTests
|
||||
{
|
||||
[Fact]
|
||||
public void Referral_before_the_only_entry_does_not_lose_it()
|
||||
{
|
||||
var results = new ScriptedResults(
|
||||
Step.Referral(),
|
||||
Step.Entry("CN=dohertj2,OU=Office Users,OU=Warsaw,DC=nam,DC=zimmer,DC=com"));
|
||||
|
||||
var entries = NovellLdapConnection.ReadEntries(results);
|
||||
|
||||
var entry = Assert.Single(entries);
|
||||
Assert.Equal("CN=dohertj2,OU=Office Users,OU=Warsaw,DC=nam,DC=zimmer,DC=com", entry.Dn);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Referral_after_the_entry_does_not_discard_what_was_already_read()
|
||||
{
|
||||
var results = new ScriptedResults(
|
||||
Step.Entry("CN=a,DC=nam,DC=zimmer,DC=com"),
|
||||
Step.Referral());
|
||||
|
||||
var entries = NovellLdapConnection.ReadEntries(results);
|
||||
|
||||
Assert.Equal("CN=a,DC=nam,DC=zimmer,DC=com", Assert.Single(entries).Dn);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The real shape observed against the NAM domain root: several references interleaved
|
||||
/// with the one user entry. All three of AD's usual continuation points are present.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void Multiple_interleaved_referrals_still_yield_every_entry()
|
||||
{
|
||||
var results = new ScriptedResults(
|
||||
Step.Referral(),
|
||||
Step.Entry("CN=a,DC=nam,DC=zimmer,DC=com"),
|
||||
Step.Referral(),
|
||||
Step.Referral(),
|
||||
Step.Entry("CN=b,DC=nam,DC=zimmer,DC=com"));
|
||||
|
||||
var entries = NovellLdapConnection.ReadEntries(results);
|
||||
|
||||
Assert.Equal(["CN=a,DC=nam,DC=zimmer,DC=com", "CN=b,DC=nam,DC=zimmer,DC=com"],
|
||||
entries.Select(e => e.Dn));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A referral-only result set is a legitimate "nothing here" answer, and must come back
|
||||
/// empty rather than throwing — <c>LdapAuthService</c> reads empty as <c>UserNotFound</c>,
|
||||
/// which is the honest verdict, where an exception would become a system-side failure.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void Referrals_only_returns_empty_rather_than_throwing()
|
||||
{
|
||||
var results = new ScriptedResults(Step.Referral(), Step.Referral());
|
||||
|
||||
Assert.Empty(NovellLdapConnection.ReadEntries(results));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A base <see cref="LdapException"/> carrying the Referral result code is treated the
|
||||
/// same as the derived type — the catch filter must not depend on the exact class.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void Referral_result_code_on_a_base_exception_is_also_skipped()
|
||||
{
|
||||
var results = new ScriptedResults(
|
||||
Step.Throwing(new LdapException("referral", LdapException.Referral, null)),
|
||||
Step.Entry("CN=a,DC=nam,DC=zimmer,DC=com"));
|
||||
|
||||
Assert.Single(NovellLdapConnection.ReadEntries(results));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Only referrals are swallowed. A genuine directory fault must still propagate so the
|
||||
/// caller maps it to a system-side failure — silently returning a short result set would
|
||||
/// turn "the directory is broken" into "no such user", which is the wrong answer to give
|
||||
/// about someone's credentials.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void A_non_referral_fault_still_propagates()
|
||||
{
|
||||
var results = new ScriptedResults(
|
||||
Step.Throwing(new LdapException("busy", LdapException.Busy, null)),
|
||||
Step.Entry("CN=a,DC=nam,DC=zimmer,DC=com"));
|
||||
|
||||
var ex = Assert.Throws<LdapException>(() => NovellLdapConnection.ReadEntries(results));
|
||||
Assert.Equal(LdapException.Busy, ex.ResultCode);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A pathological client that throws a referral without advancing must not spin forever
|
||||
/// inside a fail-closed authentication path.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void An_endless_referral_stream_terminates()
|
||||
{
|
||||
var results = new EndlessReferrals();
|
||||
|
||||
var entries = NovellLdapConnection.ReadEntries(results);
|
||||
|
||||
Assert.Empty(entries);
|
||||
Assert.InRange(results.Calls, 1, 2_000);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
|
||||
private sealed record Step(LdapEntry? Value, Exception? Throw)
|
||||
{
|
||||
public static Step Entry(string dn) => new(new LdapEntry(dn, new LdapAttributeSet()), null);
|
||||
public static Step Referral() => new(null, new LdapReferralException("continuation reference"));
|
||||
public static Step Throwing(Exception ex) => new(null, ex);
|
||||
}
|
||||
|
||||
/// <summary>Replays a fixed script of entries and faults through the Novell result seam.</summary>
|
||||
private sealed class ScriptedResults : ILdapSearchResults
|
||||
{
|
||||
private readonly Step[] _steps;
|
||||
private int _index;
|
||||
|
||||
public ScriptedResults(params Step[] steps) => _steps = steps;
|
||||
|
||||
public int Count => _steps.Length;
|
||||
|
||||
public LdapControl[] ResponseControls => [];
|
||||
|
||||
public bool HasMore() => _index < _steps.Length;
|
||||
|
||||
public LdapEntry Next()
|
||||
{
|
||||
var step = _steps[_index++];
|
||||
if (step.Throw is not null) throw step.Throw;
|
||||
return step.Value!;
|
||||
}
|
||||
|
||||
// The production reader drives HasMore()/Next() directly; enumeration is part of the
|
||||
// interface but not part of the path under test.
|
||||
public IEnumerator<LdapEntry> GetEnumerator() => throw new NotSupportedException();
|
||||
|
||||
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator();
|
||||
}
|
||||
|
||||
/// <summary>Always claims more results and always throws a referral, never advancing.</summary>
|
||||
private sealed class EndlessReferrals : ILdapSearchResults
|
||||
{
|
||||
public int Calls { get; private set; }
|
||||
|
||||
public int Count => int.MaxValue;
|
||||
|
||||
public LdapControl[] ResponseControls => [];
|
||||
|
||||
public bool HasMore() => true;
|
||||
|
||||
public LdapEntry Next()
|
||||
{
|
||||
Calls++;
|
||||
throw new LdapReferralException("continuation reference");
|
||||
}
|
||||
|
||||
public IEnumerator<LdapEntry> GetEnumerator() => throw new NotSupportedException();
|
||||
|
||||
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
using ZB.MOM.WW.Auth.Ldap.Internal;
|
||||
|
||||
namespace ZB.MOM.WW.Auth.Ldap.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Test double for <see cref="ILdapConnectionFactory"/> that hands out pre-scripted
|
||||
/// <see cref="FakeLdapConnection"/> instances in order, one per <see cref="Create"/> call —
|
||||
/// exactly matching the failover walk, which opens a fresh connection per endpoint attempt.
|
||||
/// Records every created connection for inspection. When the script runs out, returns a
|
||||
/// bare unscripted fake (which yields user-not-found) so a miscounted test fails loudly
|
||||
/// rather than reusing a stale fake.
|
||||
/// </summary>
|
||||
internal sealed class SequenceLdapConnectionFactory : ILdapConnectionFactory
|
||||
{
|
||||
private readonly Queue<FakeLdapConnection> _script;
|
||||
|
||||
/// <summary>Scripts the connections handed out, in the order the walk will request them.</summary>
|
||||
public SequenceLdapConnectionFactory(params FakeLdapConnection[] fakes)
|
||||
=> _script = new Queue<FakeLdapConnection>(fakes);
|
||||
|
||||
/// <summary>Every connection handed out, in creation order (scripted or overflow).</summary>
|
||||
public List<FakeLdapConnection> Created { get; } = new();
|
||||
|
||||
/// <inheritdoc />
|
||||
public ILdapConnection Create()
|
||||
{
|
||||
var fake = _script.Count > 0 ? _script.Dequeue() : new FakeLdapConnection();
|
||||
Created.Add(fake);
|
||||
return fake;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Smoke test: verifies the sequencing and overflow behaviour the failover tests rely on.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
public class SequenceLdapConnectionFactorySmokeTests
|
||||
{
|
||||
[Fact]
|
||||
public void Create_ReturnsScriptedFakesInOrder_ThenOverflows()
|
||||
{
|
||||
var first = new FakeLdapConnection().ThrowOnConnect();
|
||||
var second = new FakeLdapConnection();
|
||||
var factory = new SequenceLdapConnectionFactory(first, second);
|
||||
|
||||
Assert.Same(first, factory.Create());
|
||||
Assert.Same(second, factory.Create());
|
||||
Assert.NotSame(second, factory.Create()); // overflow: fresh bare fake
|
||||
Assert.Equal(3, factory.Created.Count);
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,7 @@ Startup configuration-validation library for the **ZB.MOM.WW SCADA family** (OtO
|
||||
|
||||
The library normalizes the three-project configuration-validation surface: a failure-accumulating `IValidateOptions` base, reusable rule primitives, a bind+validate+`ValidateOnStart` DI extension, and a pre-host `ConfigPreflight` aggregator for raw `IConfiguration` — so the plumbing is written once and domain rules stay per-project.
|
||||
|
||||
**Built at 0.1.0. Adopted by OtOpcUa, MxAccessGateway, and ScadaBridge on 2026-06-01** (local default branches; not yet pushed to remotes). Adoption tracked in `~/Desktop/scadaproj/components/configuration/GAPS.md`.
|
||||
**Built at 0.1.0. Adopted by OtOpcUa, MxAccessGateway, and ScadaBridge on 2026-06-01, and by HistorianGateway since;** all four pin `0.1.0` (the only feed version) on their pushed origin default branches (verified 2026-11-09). Adoption tracked in `~/Desktop/scadaproj/components/configuration/GAPS.md`.
|
||||
|
||||
---
|
||||
|
||||
@@ -66,7 +66,7 @@ ZB.MOM.WW.Configuration/
|
||||
|
||||
## Status
|
||||
|
||||
Part of the **scadaproj component-normalization family** — this is the configuration + validation component. Built at **0.1.0**. **Adopted by OtOpcUa, MxAccessGateway, and ScadaBridge on 2026-06-01** (local default branches; not yet pushed to remotes) — per-app result is tracked in:
|
||||
Part of the **scadaproj component-normalization family** — this is the configuration + validation component. Built at **0.1.0**. **Adopted by OtOpcUa, MxAccessGateway, and ScadaBridge on 2026-06-01** (since pushed; HistorianGateway also pins `0.1.0` — all four verified on their origin default branches 2026-11-09) — per-app result is tracked in:
|
||||
|
||||
- `~/Desktop/scadaproj/components/configuration/GAPS.md`
|
||||
|
||||
@@ -75,3 +75,34 @@ Design documentation:
|
||||
- `~/Desktop/scadaproj/components/configuration/spec/SPEC.md` — normalized validation target
|
||||
- `~/Desktop/scadaproj/components/configuration/shared-contract/ZB.MOM.WW.Configuration.md` — proposed shared-library API
|
||||
- `~/Desktop/scadaproj/components/configuration/current-state/` — per-project current state (code-verified)
|
||||
|
||||
## Index history (migrated from the scadaproj root CLAUDE.md)
|
||||
|
||||
> Moved verbatim out of the scadaproj root `CLAUDE.md` on 2026-09-03 so it loads only when needed. **This file is now the authoritative place for this history — append new entries here and keep the root index row short.**
|
||||
|
||||
### Narrative
|
||||
|
||||
The configuration component is fully populated: a normalized [`spec`](components/configuration/spec/SPEC.md), a
|
||||
[`shared-contract`](components/configuration/shared-contract/ZB.MOM.WW.Configuration.md), three
|
||||
[`current-state`](components/configuration/current-state/) docs, and an adoption [`GAPS`](components/configuration/GAPS.md)
|
||||
backlog. Shared = the `IValidateOptions<T>` failure-accumulation base (`OptionsValidatorBase<T>`) +
|
||||
reusable rule primitives (`ValidationBuilder`: port / host:port / required / positive-duration / one-of /
|
||||
min-count) + `AddValidatedOptions<TOptions,TValidator>()` (bind + validate + `ValidateOnStart`) + the
|
||||
pre-host `ConfigPreflight` aggregator (generalizes ScadaBridge's `StartupValidator`, byte-compatible
|
||||
message); left per-project = each app's options classes + domain rules, and OtOpcUa's
|
||||
draft/generation-content validation (DB-side `sp_ValidateDraft`; its C# `DraftValidator` is dormant).
|
||||
|
||||
The shared library is **built and lives in this repo** at [`ZB.MOM.WW.Configuration/`](ZB.MOM.WW.Configuration/)
|
||||
(.NET 10; single package `ZB.MOM.WW.Configuration`; 42 tests (verified 2026-07-18); `dotnet pack` → 1 nupkg @ 0.1.0).
|
||||
The implementation plan is at
|
||||
[`docs/plans/2026-06-01-zb-mom-ww-configuration-shared-library.md`](docs/plans/2026-06-01-zb-mom-ww-configuration-shared-library.md).
|
||||
**Adopted across all three apps on 2026-06-01** (OtOpcUa, MxAccessGateway, ScadaBridge) on each repo's
|
||||
local default branch (`main`/`master`) — merged, and since pushed to origin (the "not yet pushed" caveat this
|
||||
record carried is stale; all four apps, HistorianGateway included, pin `0.1.0` on their origin default branches as of 2026-11-09); the package was first
|
||||
published to the Gitea feed. Behaviour-preserving onto `OptionsValidatorBase`/`AddValidatedOptions`
|
||||
for MxGateway + ScadaBridge (validator messages byte-identical), `StartupValidator` → `ConfigPreflight`
|
||||
for ScadaBridge, and net-new `Ldap`/`OpcUa` validators for OtOpcUa. Per-app result tracked in
|
||||
[`components/configuration/GAPS.md`](components/configuration/GAPS.md).
|
||||
Build/test from `ZB.MOM.WW.Configuration/`: `dotnet test`. Consumer matrix: all three apps consume the
|
||||
single package; ScadaBridge is the heaviest adopter (per-module validators + `StartupValidator` →
|
||||
`ConfigPreflight`); OtOpcUa adoption is additive (it has no `IValidateOptions` usage today).
|
||||
|
||||
@@ -5,8 +5,8 @@
|
||||
<Authors>ZB.MOM.WW</Authors>
|
||||
<Description>Startup configuration-validation toolkit for the ZB.MOM.WW SCADA family: a failure-accumulating IValidateOptions base, reusable rule primitives (port, host:port, required, positive-duration, one-of, min-count), a bind+validate+ValidateOnStart DI helper, and a pre-host ConfigPreflight aggregator for raw IConfiguration. Extracts the validation plumbing the apps share; domain rules stay per-project.</Description>
|
||||
<PackageTags>configuration;options;validation;ivalidateoptions;validateonstart;startup;scada;wonderware;zb-mom-ww</PackageTags>
|
||||
<PackageProjectUrl>https://gitea.dohertylan.com/dohertj2/zb-mom-ww-configuration</PackageProjectUrl>
|
||||
<RepositoryUrl>https://gitea.dohertylan.com/dohertj2/zb-mom-ww-configuration</RepositoryUrl>
|
||||
<PackageProjectUrl>https://gitea.dohertylan.com/dohertj2/scadaproj/src/branch/main/ZB.MOM.WW.Configuration</PackageProjectUrl>
|
||||
<RepositoryUrl>https://gitea.dohertylan.com/dohertj2/scadaproj</RepositoryUrl>
|
||||
<PackageReadmeFile>README.md</PackageReadmeFile>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
# ZB.MOM.WW.GalaxyRepository
|
||||
|
||||
Shared Galaxy object-hierarchy SQL browse + `galaxy_repository.v1` gRPC service for the **ZB.MOM.WW SCADA family** (consumed by HistorianGateway and mxaccessgw). Build/test from this directory: `dotnet test`.
|
||||
|
||||
## 0.2.2 (2026-11-09, UNPUBLISHED)
|
||||
|
||||
Version bumped in `Directory.Build.props`, not packed or pushed. P3 review fixes (scadaproj#47):
|
||||
- 003: parent cycles are broken at the lowest gobject id so their members stay browsable.
|
||||
- 004: Stale threshold is `max(5 min, 3 x DashboardRefreshIntervalSeconds)` (new optional `IOptions` ctor
|
||||
parameter on `GalaxyHierarchyCache`); the projected-Stale entry is memoized per source entry.
|
||||
- 005: `WatchDeployEvents` subscribers never see a non-increasing `Sequence`.
|
||||
- 006: container-building tests for `AddZbGalaxyRepository`.
|
||||
- 007: `System.Security.Cryptography.Pkcs` pinned at 9.0.21 (clears NU1902/NU1903 for consumers).
|
||||
- 008: empty `SnapshotCachePath` disables persistence (documented + logged once).
|
||||
|
||||
## 0.2.1 (2026-11-09, UNPUBLISHED)
|
||||
|
||||
Version bumped in `Directory.Build.props`, not packed or pushed; consumers stay on `0.2.0`.
|
||||
- GalaxyRepository-001 (scadaproj#41): the per-cache-entry filter memos of both projectors are now
|
||||
`ProjectionMemo<T>`, capped at 64 signatures (FIFO; an evicted signature is recomputed, same answer).
|
||||
- GalaxyRepository-002 (scadaproj#42): a browse-subtree scope (`Plant/LineA/*`) no longer hides the
|
||||
allowed subtree's ancestors. `BrowseChildren` and `DiscoverHierarchy` return them as
|
||||
**navigation-only** nodes — attributes stripped, only the path to an allowed object listed, siblings
|
||||
still hidden. **Behaviour change for consumers:** a scoped `DiscoverHierarchy` now includes those
|
||||
ancestors (`GalaxyHierarchyQueryResult.NavigationAncestorCount` says how many); `WatchDeployEvents`
|
||||
still counts allowed objects only. Semantics documented on `IGalaxyBrowseScopeProvider`.
|
||||
|
||||
## Index history (migrated from the scadaproj root CLAUDE.md)
|
||||
|
||||
> Moved verbatim out of the scadaproj root `CLAUDE.md` on 2026-09-03 so it loads only when needed. **This file is now the authoritative place for this history — append new entries here and keep the root index row short.**
|
||||
|
||||
### Narrative
|
||||
|
||||
The Galaxy Repository component normalizes the **Galaxy object-hierarchy SQL browse + reusable gRPC service**
|
||||
that was previously embedded in `mxaccessgw`. Shared = canonical `galaxy_repository.v1` proto (wire-compatible
|
||||
with `mxaccessgw`'s existing contract so OtOpcUa's `GalaxyRepositoryClient` is unaffected), the SQL browse
|
||||
provider (`HierarchySql` / `AttributesSql` validated reverse-engineered queries), in-memory hierarchy cache +
|
||||
snapshot + deploy-poll refresh `BackgroundService`, `GalaxyHierarchyProjector`, and `AddZbGalaxyRepository` /
|
||||
`MapZbGalaxyRepository` DI extension. Left per-consumer = section path, subtree auth filtering, and any
|
||||
app-specific paging defaults.
|
||||
|
||||
The shared library is **built and lives in this repo** at [`ZB.MOM.WW.GalaxyRepository/`](ZB.MOM.WW.GalaxyRepository/)
|
||||
(.NET 10; single package `ZB.MOM.WW.GalaxyRepository`; `dotnet pack` → 1 nupkg @ 0.1.0, **published to
|
||||
the Gitea NuGet feed** `gitea.dohertylan.com/api/packages/dohertj2/nuget`). The design doc is at
|
||||
[`docs/plans/2026-06-23-historian-gateway-design.md`](docs/plans/2026-06-23-historian-gateway-design.md) (§10, component 1).
|
||||
**Consumed by HistorianGateway** as a `PackageReference` from that Gitea feed, pinned at `0.2.0` (originally a
|
||||
cross-repo `ProjectReference` to this scadaproj tree; switched to the feed package 2026-06-24; bumped `0.1.0` → `0.2.0` 2026-06-25).
|
||||
**mxaccessgw has adopted it** (its Server calls `AddZbGalaxyRepository` / `MapZbGalaxyRepository`; the
|
||||
`galaxy_repository.v1` wire contract is identical, so OtOpcUa and ScadaBridge clients are unaffected). Build/test from `ZB.MOM.WW.GalaxyRepository/`: `dotnet test`.
|
||||
Consumer matrix: HistorianGateway (initial); mxaccessgw (adopted, 0.2.0).
|
||||
@@ -4,7 +4,7 @@
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<LangVersion>latest</LangVersion>
|
||||
<Version>0.2.0</Version>
|
||||
<Version>0.2.2</Version>
|
||||
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
|
||||
<GenerateDocumentationFile>true</GenerateDocumentationFile>
|
||||
</PropertyGroup>
|
||||
|
||||
@@ -7,6 +7,11 @@
|
||||
<ItemGroup>
|
||||
<!-- Library -->
|
||||
<PackageVersion Include="Microsoft.Data.SqlClient" Version="6.0.2" />
|
||||
<!-- Transitive security pin (scadaproj#22/#47): Microsoft.Data.SqlClient 6.0.2 pulls
|
||||
System.Security.Cryptography.Pkcs 9.0.4, which carries GHSA-846f-f764-76mx (high) and
|
||||
GHSA-2fmv-rv2c-59x7 (moderate) and fails restore under warnings-as-errors (NU1902/NU1903).
|
||||
Pin the patched 9.0.21 (first fixed in the 9.0 line). -->
|
||||
<PackageVersion Include="System.Security.Cryptography.Pkcs" Version="9.0.21" />
|
||||
<PackageVersion Include="Grpc.AspNetCore" Version="2.76.0" />
|
||||
<!-- Google.Protobuf and Grpc.Tools must be >= the minimums Grpc.AspNetCore 2.76.0 requires -->
|
||||
<PackageVersion Include="Google.Protobuf" Version="3.31.1" />
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
@@ -13,13 +12,19 @@ namespace ZB.MOM.WW.GalaxyRepository;
|
||||
/// filtered child list per cache-entry instance so repeated paging is an O(pageSize)
|
||||
/// slice rather than an O(siblings) filter scan per page. The memo is keyed on the
|
||||
/// immutable cache entry, so when the cache publishes a new entry the stale memo
|
||||
/// becomes unreachable and is reclaimed with it.
|
||||
/// becomes unreachable and is reclaimed with it. Each entry's memo is capped at
|
||||
/// <see cref="ProjectionMemo{TValue}.Capacity"/> signatures, because the signature is
|
||||
/// client-controlled (GalaxyRepository-001).
|
||||
/// </summary>
|
||||
public static class GalaxyBrowseProjector
|
||||
{
|
||||
private static readonly ConditionalWeakTable<
|
||||
GalaxyHierarchyCacheEntry,
|
||||
ConcurrentDictionary<string, FilteredChildren>> FilteredChildrenCache = new();
|
||||
ProjectionMemo<FilteredChildren>> FilteredChildrenCache = new();
|
||||
|
||||
/// <summary>Number of filter signatures currently memoized for <paramref name="entry"/> (tests).</summary>
|
||||
internal static int MemoCount(GalaxyHierarchyCacheEntry entry) =>
|
||||
FilteredChildrenCache.TryGetValue(entry, out var memo) ? memo.Count : 0;
|
||||
|
||||
/// <summary>Projects one page of direct children of the resolved parent.</summary>
|
||||
/// <param name="entry">The Galaxy hierarchy cache entry to query.</param>
|
||||
@@ -55,7 +60,9 @@ public static class GalaxyBrowseProjector
|
||||
List<bool> hasChildren = new(Math.Max(0, end - offset));
|
||||
for (int index = offset; index < end; index++)
|
||||
{
|
||||
page.Add(CloneObject(filtered.Children[index].Object, includeAttributes));
|
||||
// A navigation-only ancestor of the browse scope never carries attributes: it is in
|
||||
// the reply only so the caller can reach the allowed subtree (GalaxyRepository-002).
|
||||
page.Add(CloneObject(filtered.Children[index].Object, includeAttributes && !filtered.NavigationOnly[index]));
|
||||
hasChildren.Add(filtered.HasMatchingDescendant[index]);
|
||||
}
|
||||
|
||||
@@ -115,8 +122,8 @@ public static class GalaxyBrowseProjector
|
||||
int parentId,
|
||||
string filterSignature)
|
||||
{
|
||||
ConcurrentDictionary<string, FilteredChildren> memo =
|
||||
FilteredChildrenCache.GetValue(entry, static _ => new ConcurrentDictionary<string, FilteredChildren>(StringComparer.Ordinal));
|
||||
ProjectionMemo<FilteredChildren> memo =
|
||||
FilteredChildrenCache.GetValue(entry, static _ => new ProjectionMemo<FilteredChildren>());
|
||||
|
||||
return memo.GetOrAdd(
|
||||
filterSignature,
|
||||
@@ -129,10 +136,22 @@ public static class GalaxyBrowseProjector
|
||||
|
||||
List<GalaxyObjectView> matched = [];
|
||||
List<bool> hasMatching = [];
|
||||
List<bool> navigationOnly = [];
|
||||
foreach (GalaxyObjectView view in directChildren)
|
||||
{
|
||||
if (!MatchesBrowseSubtrees(view, state.BrowseSubtreeGlobs))
|
||||
{
|
||||
// Out of scope itself, but an ancestor of an allowed object (scope
|
||||
// `Plant/LineA/*` → `Plant`, `Plant/LineA`): surface it as a navigation-
|
||||
// only container, or scoped lazy browse from the root is empty
|
||||
// (GalaxyRepository-002). Its other children stay hidden because the same
|
||||
// rule applies one level down when the caller expands it.
|
||||
if (HasMatchingDescendant(view, state.Entry.Index, state.Request, state.BrowseSubtreeGlobs))
|
||||
{
|
||||
matched.Add(view);
|
||||
hasMatching.Add(true);
|
||||
navigationOnly.Add(true);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (!MatchesFilters(view.Object, state.Request))
|
||||
@@ -145,14 +164,16 @@ public static class GalaxyBrowseProjector
|
||||
{
|
||||
matched.Add(view);
|
||||
hasMatching.Add(true);
|
||||
navigationOnly.Add(false);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
matched.Add(view);
|
||||
hasMatching.Add(HasMatchingDescendant(view, state.Entry.Index, state.Request, state.BrowseSubtreeGlobs));
|
||||
navigationOnly.Add(false);
|
||||
}
|
||||
|
||||
return new FilteredChildren(matched, hasMatching);
|
||||
return new FilteredChildren(matched, hasMatching, navigationOnly);
|
||||
},
|
||||
(Entry: entry, ParentId: parentId, Request: request, BrowseSubtreeGlobs: browseSubtreeGlobs));
|
||||
}
|
||||
@@ -277,5 +298,6 @@ public static class GalaxyBrowseProjector
|
||||
|
||||
private sealed record FilteredChildren(
|
||||
IReadOnlyList<GalaxyObjectView> Children,
|
||||
IReadOnlyList<bool> HasMatchingDescendant);
|
||||
IReadOnlyList<bool> HasMatchingDescendant,
|
||||
IReadOnlyList<bool> NavigationOnly);
|
||||
}
|
||||
|
||||
@@ -60,12 +60,21 @@ public sealed class GalaxyDeployNotifier : IGalaxyDeployNotifier
|
||||
channel.Writer.TryWrite(bootstrap);
|
||||
}
|
||||
|
||||
long lastSequence = long.MinValue;
|
||||
try
|
||||
{
|
||||
while (await channel.Reader.WaitToReadAsync(cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
while (channel.Reader.TryRead(out GalaxyDeployEventInfo? next))
|
||||
{
|
||||
// The bootstrap write can race a concurrent Publish and land behind a
|
||||
// newer event; never yield an event that is not newer than the last one.
|
||||
if (next.Sequence <= lastSequence)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
lastSequence = next.Sequence;
|
||||
yield return next;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,17 +16,22 @@ namespace ZB.MOM.WW.GalaxyRepository;
|
||||
/// </summary>
|
||||
public sealed class GalaxyHierarchyCache : IGalaxyHierarchyCache, IDisposable
|
||||
{
|
||||
private static readonly TimeSpan StaleThreshold = TimeSpan.FromMinutes(5);
|
||||
private static readonly TimeSpan MinimumStaleThreshold = TimeSpan.FromMinutes(5);
|
||||
|
||||
private readonly IGalaxyRepository _repository;
|
||||
private readonly IGalaxyDeployNotifier _notifier;
|
||||
private readonly IGalaxyHierarchySnapshotStore? _snapshotStore;
|
||||
private readonly TimeProvider _timeProvider;
|
||||
private readonly TimeSpan _staleThreshold;
|
||||
private readonly ILogger<GalaxyHierarchyCache>? _logger;
|
||||
private readonly TaskCompletionSource _firstLoad = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
private readonly SemaphoreSlim _refreshGate = new(1, 1);
|
||||
private GalaxyHierarchyCacheEntry _current = GalaxyHierarchyCacheEntry.Empty;
|
||||
private bool _restoreAttempted;
|
||||
private ProjectedStale? _projectedStale;
|
||||
|
||||
/// <summary>Memoized status-only projection so repeated reads return the same instance (keeps projector memos warm).</summary>
|
||||
private sealed record ProjectedStale(GalaxyHierarchyCacheEntry Source, GalaxyHierarchyCacheEntry Projected);
|
||||
|
||||
/// <summary>Initializes a new instance of the <see cref="GalaxyHierarchyCache"/> class.</summary>
|
||||
/// <param name="repository">Galaxy Repository client for SQL queries.</param>
|
||||
@@ -37,13 +42,21 @@ public sealed class GalaxyHierarchyCache : IGalaxyHierarchyCache, IDisposable
|
||||
/// Optional on-disk snapshot store. When supplied, the cache persists each
|
||||
/// successful refresh and restores the last snapshot on first load.
|
||||
/// </param>
|
||||
/// <param name="options">
|
||||
/// Optional options; the staleness threshold is <c>max(5 min, 3 x DashboardRefreshIntervalSeconds)</c>
|
||||
/// so a healthy cache on a slow refresh interval is not reported Stale.
|
||||
/// </param>
|
||||
public GalaxyHierarchyCache(
|
||||
IGalaxyRepository repository,
|
||||
IGalaxyDeployNotifier notifier,
|
||||
TimeProvider? timeProvider = null,
|
||||
ILogger<GalaxyHierarchyCache>? logger = null,
|
||||
IGalaxyHierarchySnapshotStore? snapshotStore = null)
|
||||
IGalaxyHierarchySnapshotStore? snapshotStore = null,
|
||||
Microsoft.Extensions.Options.IOptions<GalaxyRepositoryOptions>? options = null)
|
||||
{
|
||||
int refreshSeconds = options?.Value.DashboardRefreshIntervalSeconds ?? 0;
|
||||
TimeSpan derived = TimeSpan.FromSeconds(Math.Max(0, refreshSeconds) * 3.0);
|
||||
_staleThreshold = derived > MinimumStaleThreshold ? derived : MinimumStaleThreshold;
|
||||
_repository = repository;
|
||||
_notifier = notifier;
|
||||
_timeProvider = timeProvider ?? TimeProvider.System;
|
||||
@@ -58,9 +71,22 @@ public sealed class GalaxyHierarchyCache : IGalaxyHierarchyCache, IDisposable
|
||||
{
|
||||
GalaxyHierarchyCacheEntry snapshot = Volatile.Read(ref _current);
|
||||
GalaxyCacheStatus projected = ProjectStatus(snapshot);
|
||||
return projected == snapshot.Status
|
||||
? snapshot
|
||||
: snapshot with { Status = projected };
|
||||
if (projected == snapshot.Status)
|
||||
{
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
// Reuse the projected record while the source entry is unchanged: the projectors
|
||||
// memoize per entry instance, so a fresh record per read defeats the memo.
|
||||
ProjectedStale? memo = Volatile.Read(ref _projectedStale);
|
||||
if (memo is not null && ReferenceEquals(memo.Source, snapshot) && memo.Projected.Status == projected)
|
||||
{
|
||||
return memo.Projected;
|
||||
}
|
||||
|
||||
GalaxyHierarchyCacheEntry created = snapshot with { Status = projected };
|
||||
Volatile.Write(ref _projectedStale, new ProjectedStale(snapshot, created));
|
||||
return created;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -355,7 +381,7 @@ public sealed class GalaxyHierarchyCache : IGalaxyHierarchyCache, IDisposable
|
||||
}
|
||||
|
||||
if (snapshot.LastSuccessAt is { } success
|
||||
&& _timeProvider.GetUtcNow() - success > StaleThreshold)
|
||||
&& _timeProvider.GetUtcNow() - success > _staleThreshold)
|
||||
{
|
||||
return GalaxyCacheStatus.Stale;
|
||||
}
|
||||
|
||||
@@ -127,6 +127,8 @@ public sealed class GalaxyHierarchyIndex
|
||||
bucket.Add(view);
|
||||
}
|
||||
|
||||
ReRootUnreachable(views, childrenByParent);
|
||||
|
||||
foreach (List<GalaxyObjectView> bucket in childrenByParent.Values)
|
||||
{
|
||||
bucket.Sort(CompareByAreaThenDisplayName);
|
||||
@@ -147,6 +149,109 @@ public sealed class GalaxyHierarchyIndex
|
||||
viewsByContainedPath);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Re-roots objects that are not reachable from key 0 — members of a multi-node parent
|
||||
/// cycle (A→B→C→A, every parent present) and anything hanging off one — so they do not
|
||||
/// vanish from browse. Each cycle is broken at its lowest gobject id.
|
||||
/// </summary>
|
||||
private static void ReRootUnreachable(
|
||||
List<GalaxyObjectView> views,
|
||||
Dictionary<int, List<GalaxyObjectView>> childrenByParent)
|
||||
{
|
||||
HashSet<int> reached = [];
|
||||
MarkReachable(0, childrenByParent, reached);
|
||||
if (reached.Count >= views.Count)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Ascending id: a cycle member with the lowest id is re-rooted before any other
|
||||
// member; a descendant hanging off a cycle is reached once its cycle is re-rooted.
|
||||
foreach (GalaxyObjectView view in views.OrderBy(v => v.Object.GobjectId))
|
||||
{
|
||||
int id = view.Object.GobjectId;
|
||||
if (reached.Contains(id))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
// Only break at a node that is itself on a cycle (walking parents returns to it);
|
||||
// a plain descendant of a cycle waits for its ancestor cycle to be broken.
|
||||
if (!IsOnCycle(view, childrenByParent))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
childrenByParent[view.Object.ParentGobjectId].Remove(view);
|
||||
if (!childrenByParent.TryGetValue(0, out List<GalaxyObjectView>? roots))
|
||||
{
|
||||
roots = [];
|
||||
childrenByParent[0] = roots;
|
||||
}
|
||||
|
||||
roots.Add(view);
|
||||
MarkReachable(0, childrenByParent, reached);
|
||||
}
|
||||
}
|
||||
|
||||
private static bool IsOnCycle(
|
||||
GalaxyObjectView start,
|
||||
Dictionary<int, List<GalaxyObjectView>> childrenByParent)
|
||||
{
|
||||
// Descend from start through children; on a cycle we come back to start.
|
||||
HashSet<int> seen = [];
|
||||
Stack<int> stack = new();
|
||||
stack.Push(start.Object.GobjectId);
|
||||
while (stack.Count > 0)
|
||||
{
|
||||
int key = stack.Pop();
|
||||
if (!childrenByParent.TryGetValue(key, out List<GalaxyObjectView>? kids))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach (GalaxyObjectView kid in kids)
|
||||
{
|
||||
int kidId = kid.Object.GobjectId;
|
||||
if (kidId == start.Object.GobjectId)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
if (seen.Add(kidId))
|
||||
{
|
||||
stack.Push(kidId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static void MarkReachable(
|
||||
int rootKey,
|
||||
Dictionary<int, List<GalaxyObjectView>> childrenByParent,
|
||||
HashSet<int> reached)
|
||||
{
|
||||
Stack<int> stack = new();
|
||||
stack.Push(rootKey);
|
||||
while (stack.Count > 0)
|
||||
{
|
||||
if (!childrenByParent.TryGetValue(stack.Pop(), out List<GalaxyObjectView>? kids))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach (GalaxyObjectView kid in kids)
|
||||
{
|
||||
if (reached.Add(kid.Object.GobjectId))
|
||||
{
|
||||
stack.Push(kid.Object.GobjectId);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static string BuildContainedPath(
|
||||
GalaxyObject obj,
|
||||
IReadOnlyDictionary<int, GalaxyObject> objectsById)
|
||||
|
||||
+80
-13
@@ -1,4 +1,3 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
@@ -23,9 +22,15 @@ public static class GalaxyHierarchyProjector
|
||||
/// With it, the first page builds the filtered list and each subsequent page is an
|
||||
/// O(pageSize) slice. The table is keyed on the immutable cache-entry instance, so
|
||||
/// when the cache publishes a new entry the stale memo becomes unreachable and is
|
||||
/// reclaimed with it — no explicit invalidation needed.
|
||||
/// reclaimed with it — no explicit invalidation needed. Each entry's memo is capped at
|
||||
/// <see cref="ProjectionMemo{TValue}.Capacity"/> signatures, because the signature is
|
||||
/// client-controlled (GalaxyRepository-001).
|
||||
/// </summary>
|
||||
private static readonly ConditionalWeakTable<GalaxyHierarchyCacheEntry, ConcurrentDictionary<string, IReadOnlyList<GalaxyObjectView>>> FilteredViewCache = new();
|
||||
private static readonly ConditionalWeakTable<GalaxyHierarchyCacheEntry, ProjectionMemo<FilteredViews>> FilteredViewCache = new();
|
||||
|
||||
/// <summary>Number of filter signatures currently memoized for <paramref name="entry"/> (tests).</summary>
|
||||
internal static int MemoCount(GalaxyHierarchyCacheEntry entry) =>
|
||||
FilteredViewCache.TryGetValue(entry, out var memo) ? memo.Count : 0;
|
||||
|
||||
/// <summary>Projects a discovery request against a cache entry and returns all matching objects.</summary>
|
||||
/// <param name="entry">The Galaxy hierarchy cache entry.</param>
|
||||
@@ -78,28 +83,33 @@ public static class GalaxyHierarchyProjector
|
||||
}
|
||||
|
||||
string filterSignature = ComputeFilterSignature(request, browseSubtreeGlobs);
|
||||
IReadOnlyList<GalaxyObjectView> matchedViews = GetFilteredViews(
|
||||
FilteredViews filtered = GetFilteredViews(
|
||||
entry,
|
||||
request,
|
||||
browseSubtreeGlobs,
|
||||
maxDepth,
|
||||
filterSignature);
|
||||
IReadOnlyList<GalaxyObjectView> matchedViews = filtered.Views;
|
||||
|
||||
bool includeAttributes = IncludeAttributes(request);
|
||||
List<GalaxyObject> page = new(Math.Min(pageSize, Math.Max(0, matchedViews.Count - offset)));
|
||||
int end = (int)Math.Min((long)offset + pageSize, matchedViews.Count);
|
||||
for (int index = offset; index < end; index++)
|
||||
{
|
||||
page.Add(CloneObject(matchedViews[index].Object, includeAttributes));
|
||||
// Navigation-only scope ancestors never carry attributes (GalaxyRepository-002).
|
||||
page.Add(CloneObject(matchedViews[index].Object, includeAttributes && !filtered.NavigationOnly[index]));
|
||||
}
|
||||
|
||||
return new GalaxyHierarchyQueryResult(
|
||||
page,
|
||||
matchedViews.Count,
|
||||
filterSignature);
|
||||
filterSignature)
|
||||
{
|
||||
NavigationAncestorCount = filtered.NavigationAncestorCount,
|
||||
};
|
||||
}
|
||||
|
||||
private static IReadOnlyList<GalaxyObjectView> GetFilteredViews(
|
||||
private static FilteredViews GetFilteredViews(
|
||||
GalaxyHierarchyCacheEntry entry,
|
||||
DiscoverHierarchyRequest request,
|
||||
IReadOnlyList<string>? browseSubtreeGlobs,
|
||||
@@ -111,29 +121,86 @@ public static class GalaxyHierarchyProjector
|
||||
IReadOnlyList<GalaxyObjectView> views = entry.Index.ObjectViews;
|
||||
GalaxyObjectView? root = ResolveRoot(request, entry.Index);
|
||||
|
||||
ConcurrentDictionary<string, IReadOnlyList<GalaxyObjectView>> memo =
|
||||
FilteredViewCache.GetValue(entry, static _ => new ConcurrentDictionary<string, IReadOnlyList<GalaxyObjectView>>(StringComparer.Ordinal));
|
||||
ProjectionMemo<FilteredViews> memo =
|
||||
FilteredViewCache.GetValue(entry, static _ => new ProjectionMemo<FilteredViews>());
|
||||
|
||||
return memo.GetOrAdd(
|
||||
filterSignature,
|
||||
static (_, state) =>
|
||||
{
|
||||
List<GalaxyObjectView> matched = [];
|
||||
HashSet<int> inScope = [];
|
||||
foreach (GalaxyObjectView view in state.Views)
|
||||
{
|
||||
if (MatchesRoot(view, state.Root, state.MaxDepth)
|
||||
&& MatchesBrowseSubtrees(view, state.BrowseSubtreeGlobs)
|
||||
&& MatchesFilters(view.Object, state.Request))
|
||||
{
|
||||
matched.Add(view);
|
||||
inScope.Add(view.Object.GobjectId);
|
||||
}
|
||||
}
|
||||
|
||||
return matched;
|
||||
// A scope such as `Plant/LineA/*` excludes `Plant` and `Plant/LineA` themselves,
|
||||
// leaving the allowed objects with no parent in the reply (GalaxyRepository-002).
|
||||
// Ancestors of an allowed object are returned as navigation-only nodes —
|
||||
// attribute-stripped — when the request would otherwise have returned them
|
||||
// (inside root/depth, passing the request filters).
|
||||
HashSet<int> ancestors = state.BrowseSubtreeGlobs is { Count: > 0 }
|
||||
? CollectAncestors(inScope, state.Index)
|
||||
: [];
|
||||
|
||||
List<GalaxyObjectView> matched = [];
|
||||
List<bool> navigationOnly = [];
|
||||
int navigationCount = 0;
|
||||
foreach (GalaxyObjectView view in state.Views)
|
||||
{
|
||||
int id = view.Object.GobjectId;
|
||||
if (inScope.Contains(id))
|
||||
{
|
||||
matched.Add(view);
|
||||
navigationOnly.Add(false);
|
||||
}
|
||||
else if (ancestors.Contains(id)
|
||||
&& MatchesRoot(view, state.Root, state.MaxDepth)
|
||||
&& MatchesFilters(view.Object, state.Request))
|
||||
{
|
||||
matched.Add(view);
|
||||
navigationOnly.Add(true);
|
||||
navigationCount++;
|
||||
}
|
||||
}
|
||||
|
||||
return new FilteredViews(matched, navigationOnly, navigationCount);
|
||||
},
|
||||
(Views: views, Root: root, MaxDepth: maxDepth, BrowseSubtreeGlobs: browseSubtreeGlobs, Request: request));
|
||||
(Views: views, Index: entry.Index, Root: root, MaxDepth: maxDepth, BrowseSubtreeGlobs: browseSubtreeGlobs, Request: request));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The out-of-scope ancestors of every in-scope object. Cycle-safe: a walk stops at any id
|
||||
/// already seen, which also stops it re-walking a chain another object already covered.
|
||||
/// </summary>
|
||||
private static HashSet<int> CollectAncestors(HashSet<int> inScope, GalaxyHierarchyIndex index)
|
||||
{
|
||||
HashSet<int> ancestors = [];
|
||||
foreach (int id in inScope)
|
||||
{
|
||||
int parentId = index.ObjectViewsById.TryGetValue(id, out GalaxyObjectView? view) ? view.Object.ParentGobjectId : 0;
|
||||
while (parentId != 0
|
||||
&& !inScope.Contains(parentId)
|
||||
&& ancestors.Add(parentId)
|
||||
&& index.ObjectViewsById.TryGetValue(parentId, out GalaxyObjectView? parent))
|
||||
{
|
||||
parentId = parent.Object.ParentGobjectId;
|
||||
}
|
||||
}
|
||||
|
||||
return ancestors;
|
||||
}
|
||||
|
||||
private sealed record FilteredViews(
|
||||
IReadOnlyList<GalaxyObjectView> Views,
|
||||
IReadOnlyList<bool> NavigationOnly,
|
||||
int NavigationAncestorCount);
|
||||
|
||||
/// <summary>Finds an object in the hierarchy by its tag address.</summary>
|
||||
/// <param name="entry">The Galaxy hierarchy cache entry.</param>
|
||||
/// <param name="tagAddress">The tag address to search for.</param>
|
||||
|
||||
+9
-1
@@ -13,4 +13,12 @@ namespace ZB.MOM.WW.GalaxyRepository;
|
||||
public sealed record GalaxyHierarchyQueryResult(
|
||||
IReadOnlyList<GalaxyObject> Objects,
|
||||
int TotalObjectCount,
|
||||
string FilterSignature);
|
||||
string FilterSignature)
|
||||
{
|
||||
/// <summary>
|
||||
/// How many of the <see cref="TotalObjectCount"/> objects are navigation-only ancestors
|
||||
/// of a browse-subtree scope: returned (attribute-stripped) only so a client can attach the
|
||||
/// allowed objects to a tree, not because they are themselves in scope. Always 0 unscoped.
|
||||
/// </summary>
|
||||
public int NavigationAncestorCount { get; init; }
|
||||
}
|
||||
|
||||
+7
@@ -46,6 +46,13 @@ public sealed class GalaxyHierarchySnapshotStore : IGalaxyHierarchySnapshotStore
|
||||
: null;
|
||||
_writeTimeout = TimeSpan.FromSeconds(Math.Max(1, value.CommandTimeoutSeconds));
|
||||
_logger = logger;
|
||||
|
||||
if (value.PersistSnapshot && _path is null)
|
||||
{
|
||||
_logger?.LogInformation(
|
||||
"Galaxy hierarchy snapshot persistence is disabled: PersistSnapshot is true but SnapshotCachePath is empty. "
|
||||
+ "Last-known browse data will not survive a restart while the Galaxy database is unreachable.");
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
|
||||
+3
-2
@@ -48,8 +48,9 @@ public sealed class GalaxyRepositoryOptions
|
||||
/// File path for the persisted Galaxy browse snapshot. Ignored when
|
||||
/// <see cref="PersistSnapshot"/> is <see langword="false"/>. There is no built-in
|
||||
/// default path — the consumer supplies a cross-platform-friendly path appropriate to
|
||||
/// its host. When left empty and <see cref="PersistSnapshot"/> is enabled, the
|
||||
/// snapshot store (a later task) decides where to write.
|
||||
/// its host. When left empty, snapshot persistence is <b>disabled</b> even if
|
||||
/// <see cref="PersistSnapshot"/> is <see langword="true"/> (the store logs this once at
|
||||
/// Information), so the cold-start last-known-data guarantee does not apply.
|
||||
/// </summary>
|
||||
public string SnapshotCachePath { get; init; } = string.Empty;
|
||||
}
|
||||
|
||||
+3
-1
@@ -246,7 +246,9 @@ public sealed class GalaxyRepositoryGrpcService(
|
||||
cache.Current,
|
||||
new DiscoverHierarchyRequest(),
|
||||
browseSubtrees);
|
||||
objectCount = scoped.TotalObjectCount;
|
||||
// Count the objects the scope allows, not the navigation-only ancestors that the
|
||||
// projection adds so a tree can be built (GalaxyRepository-002).
|
||||
objectCount = scoped.TotalObjectCount - scoped.NavigationAncestorCount;
|
||||
attributeCount = scoped.Objects.Sum(obj => obj.Attributes.Count);
|
||||
}
|
||||
|
||||
|
||||
+17
@@ -8,6 +8,23 @@ namespace ZB.MOM.WW.GalaxyRepository.Grpc;
|
||||
/// identity without the library knowing the host's authorization model. The default
|
||||
/// <see cref="NullGalaxyBrowseScopeProvider"/> applies no scoping (full hierarchy).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// Each glob is matched (anchored, case-insensitive, <c>*</c>/<c>?</c>) against an
|
||||
/// object's slash-separated contained path. An object whose path matches any glob is
|
||||
/// <b>allowed</b> and is returned in full.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <b>Ancestors of an allowed object are navigation-only.</b> With <c>Plant/LineA/*</c>,
|
||||
/// neither <c>Plant</c> nor <c>Plant/LineA</c> matches, but both are returned so a client
|
||||
/// can reach the allowed subtree: by <c>BrowseChildren</c> (with
|
||||
/// <c>child_has_children = true</c>) and by <c>DiscoverHierarchy</c>. They are returned
|
||||
/// with their attributes stripped, and only their children on the path to an allowed
|
||||
/// object are listed — siblings such as <c>Plant/LineB</c> stay hidden. An ancestor is
|
||||
/// surfaced only when an allowed descendant also passes the request's own filters.
|
||||
/// <c>WatchDeployEvents</c> counts allowed objects only.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public interface IGalaxyBrowseScopeProvider
|
||||
{
|
||||
/// <summary>
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
namespace ZB.MOM.WW.GalaxyRepository;
|
||||
|
||||
/// <summary>
|
||||
/// A small, bounded, thread-safe memo of filter-signature → projected result, held per
|
||||
/// immutable <see cref="GalaxyHierarchyCacheEntry"/>.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Bounded because the signature is client-controlled: <c>tag_name_glob</c> values such as
|
||||
/// <c>*</c>, <c>**</c>, <c>***</c> are all distinct signatures that each retain a full result
|
||||
/// list, and the per-entry memo is otherwise released only when a new Galaxy deploy publishes
|
||||
/// a new entry (GalaxyRepository-001). Eviction is FIFO: the memo exists to make paging through
|
||||
/// ONE filter O(pageSize), and an evicted signature is simply recomputed — the projection is a
|
||||
/// pure function of the entry and the request, so the answer and its page tokens are unchanged.
|
||||
/// The factory runs outside the lock; two racing first callers may both compute, and the first
|
||||
/// to publish wins (same contract as <c>ConcurrentDictionary.GetOrAdd</c>).
|
||||
/// </remarks>
|
||||
/// <typeparam name="TValue">The memoized projection.</typeparam>
|
||||
internal sealed class ProjectionMemo<TValue>
|
||||
where TValue : class
|
||||
{
|
||||
/// <summary>Maximum number of distinct filter signatures retained per cache entry.</summary>
|
||||
public const int Capacity = 64;
|
||||
|
||||
private readonly object _gate = new();
|
||||
private readonly Dictionary<string, TValue> _items = new(StringComparer.Ordinal);
|
||||
private readonly Queue<string> _insertionOrder = new();
|
||||
|
||||
/// <summary>Number of signatures currently retained.</summary>
|
||||
public int Count
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
return _items.Count;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Returns the memoized value for <paramref name="key"/>, computing it when absent.</summary>
|
||||
/// <typeparam name="TState">State passed to <paramref name="factory"/>.</typeparam>
|
||||
/// <param name="key">The filter signature.</param>
|
||||
/// <param name="factory">Computes the value; must be pure.</param>
|
||||
/// <param name="state">State for <paramref name="factory"/>.</param>
|
||||
public TValue GetOrAdd<TState>(string key, Func<string, TState, TValue> factory, TState state)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_items.TryGetValue(key, out TValue? existing))
|
||||
{
|
||||
return existing;
|
||||
}
|
||||
}
|
||||
|
||||
TValue created = factory(key, state);
|
||||
|
||||
lock (_gate)
|
||||
{
|
||||
if (_items.TryGetValue(key, out TValue? raced))
|
||||
{
|
||||
return raced;
|
||||
}
|
||||
|
||||
_items[key] = created;
|
||||
_insertionOrder.Enqueue(key);
|
||||
while (_items.Count > Capacity)
|
||||
{
|
||||
_items.Remove(_insertionOrder.Dequeue());
|
||||
}
|
||||
|
||||
return created;
|
||||
}
|
||||
}
|
||||
}
|
||||
+4
-3
@@ -6,12 +6,14 @@
|
||||
<Authors>ZB.MOM.WW</Authors>
|
||||
<Description>Read-only Galaxy object-hierarchy browse library for the ZB.MOM.WW SCADA family. Provides a SQL provider for the Galaxy Repository database and a canonical gRPC service for exposing the hierarchy to modern .NET 10 clients — extracted from MxAccessGateway so any consumer can browse the Galaxy without loading 32-bit COM.</Description>
|
||||
<PackageTags>galaxy;repository;browse;aveva;wonderware;system-platform;scada;grpc;sql;zb-mom-ww</PackageTags>
|
||||
<PackageProjectUrl>https://gitea.dohertylan.com/dohertj2/zb-mom-ww-galaxyrepository</PackageProjectUrl>
|
||||
<RepositoryUrl>https://gitea.dohertylan.com/dohertj2/zb-mom-ww-galaxyrepository</RepositoryUrl>
|
||||
<PackageProjectUrl>https://gitea.dohertylan.com/dohertj2/scadaproj/src/branch/main/ZB.MOM.WW.GalaxyRepository</PackageProjectUrl>
|
||||
<RepositoryUrl>https://gitea.dohertylan.com/dohertj2/scadaproj</RepositoryUrl>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Data.SqlClient" />
|
||||
<!-- Direct reference so the centrally pinned, patched version flows to consumers (GalaxyRepository-007). -->
|
||||
<PackageReference Include="System.Security.Cryptography.Pkcs" />
|
||||
<PackageReference Include="Grpc.AspNetCore" />
|
||||
<PackageReference Include="Google.Protobuf" />
|
||||
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" />
|
||||
@@ -22,7 +24,6 @@
|
||||
</PackageReference>
|
||||
</ItemGroup>
|
||||
|
||||
<!-- Proto files are added in Task 2; the empty glob is intentional and builds cleanly. -->
|
||||
<ItemGroup>
|
||||
<Protobuf Include="Protos\*.proto" GrpcServices="Server" />
|
||||
</ItemGroup>
|
||||
|
||||
+8
-5
@@ -80,14 +80,17 @@ public sealed class GalaxyRepositoryGrpcServiceScopeTests
|
||||
Assert.Equal(6, full.TotalObjectCount);
|
||||
Assert.Equal(4, full.Objects.Sum(obj => obj.Attributes.Count));
|
||||
|
||||
// The glob selects only LineA's two leaf objects (Pump01, Valve01), each with one
|
||||
// attribute. That scoped projection (2 objects / 2 attributes) is a non-empty subset
|
||||
// distinct from both the full count and the raw notifier values below.
|
||||
// The glob allows only LineA's two leaf objects (Pump01, Valve01), each with one
|
||||
// attribute. The projection also returns their two ancestors (PlantArea, LineA) as
|
||||
// attribute-stripped navigation nodes (GalaxyRepository-002); the deploy event must count
|
||||
// only the 2 allowed objects / 2 attributes — a non-empty subset distinct from both the
|
||||
// full count and the raw notifier values below.
|
||||
GalaxyHierarchyQueryResult scopedProjection = GalaxyHierarchyProjector.Project(
|
||||
entry,
|
||||
new DiscoverHierarchyRequest(),
|
||||
browseSubtreeGlobs: ["PlantArea/LineA/*"]);
|
||||
Assert.Equal(2, scopedProjection.TotalObjectCount);
|
||||
Assert.Equal(4, scopedProjection.TotalObjectCount);
|
||||
Assert.Equal(2, scopedProjection.NavigationAncestorCount);
|
||||
Assert.Equal(2, scopedProjection.Objects.Sum(obj => obj.Attributes.Count));
|
||||
|
||||
// Publish a deploy event whose RAW counts differ from both full and scoped, so an
|
||||
@@ -114,7 +117,7 @@ public sealed class GalaxyRepositoryGrpcServiceScopeTests
|
||||
new TestServerCallContext());
|
||||
|
||||
DeployEvent emitted = Assert.Single(responseStream.Written);
|
||||
Assert.Equal(scopedProjection.TotalObjectCount, emitted.ObjectCount);
|
||||
Assert.Equal(2, emitted.ObjectCount);
|
||||
Assert.Equal(2, emitted.AttributeCount);
|
||||
// The raw notifier values were overridden by the scoped re-projection.
|
||||
Assert.NotEqual(999, emitted.ObjectCount);
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user