diff --git a/CHANGELOG.md b/CHANGELOG.md index c485d317..16be4e1d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,61 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Live evidence preparation follow-up + +- Prepare ordered masking variants only when discovered material grows; + reset them for every run. Preserve discovery, exact replacement behavior, + original HTTP values and normal authentication lifetimes. +- Enumerate actual dictionary keys with `PSBase.Keys` so a public JWKS + `keys` member cannot corrupt serialization or nested material discovery. +- Retain 213 prior redaction assertions and add 42 reuse/invalidation, + dictionary/discovery, ordered-plan, culture and array-shape controls: + 255 PASS. + Ownership: 206 to 224 PASS. Actual nested-script + wiring: one Jest suite, nine tests PASS. +- A bounded 100-field/30-material probe reduces redundant JSON preparation + from 3,000 calls to zero, 1,330.49 ms to 416.16 ms. This is not an API + latency claim. The previous full live attempt aborted on token expiry + after 633 partial PASS lines. A second attempt was explicitly stopped after + 1,255 partial PASS lines and one JWKS serialization FAIL, without a final + summary; exact disposable cleanup passed. Those failed receipts remain. +- A separate process-CPU experiment measured 546.875 ms before and 46.875 ms + after combining necessary-signal discovery guards and a small in-process + .NET ordered replacement loop. Either partial optimization missed the + local experimental goal. No CI timing gate or API latency claim is added. +- Preserve the existing regex culture semantics in the authorization fast + guard; a Turkish dotted-I RED/GREEN regression prevents an ordinal precheck + from skipping an otherwise matching authorization string. +- Preserve empty/singleton arrays by assigning dictionary/property values + inside branches rather than enumerating them through conditional-expression + output. Treat PowerShell-wrapped arrays as enumerables before custom-object + properties in both copying and material discovery, avoiding false cycles + through collection metadata. Both defects have focused RED/GREEN controls. +- Decode only the ownership admission copy of a byte HTTP response using + strict UTF-8. Preserve the actual response identity/body and existing UUID + guards; cover malformed JSON, unsupported types and invalid UTF-8. +- Clear the PATCH-profile endpoint reference only after successful early + deletion. Its `finally` block no longer issues a duplicate DELETE, while + the failure path retains retry and sticky failure evidence. The existing + 9z.36 assertion now checks actual success rather than unconditional true. +- Four actual JWKS, two downloaded log-array checks, the actual early/finally + profile lifecycle and four nested correctness contracts pass before full + live execution. Complete PostgreSQL live exits zero: 169 sections, + 1,845/1,845 assertions, zero failures, 2,060 flow steps, 450.6 seconds. + Fresh InMemory also completes: 169 sections, 1,845/1,845 assertions, + zero failures, 2,060 flow steps, 421.5 seconds, outer/child exit zero. + Exact owned cleanup and listener closure pass for both. The PostgreSQL + private outer verifier's redacted-timestamp parsing failure + is retained and independently reconciled using exact-target file freshness + and source hashes; it is not hidden as a successful original outer exit. +- This script-only follow-up changes no application version or dependency + lock. See [RCA and qualification limits](docs/LIVE_EVIDENCE_REDACTION.md#preparation-reuse-and-live-run-expiry). +- Original harness tip `a1f00397`: all 29 normal Fast gates and six exact-tip + PR checks PASS, API219/6272, reduced HTTP2519/45 known skips and web126/1664. + Integration preserves normally merged tooling PR284 and both documentation + histories. The combined tip requires its own normal checks before merge; + no shipping or deployment acceptance is inferred. + ### Root documentation tooling security recovery - Raise the root-only `markdown-it` floor from `^14.3.0` to `^14.3.3`, @@ -19,8 +74,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 Mermaid parser relocation. Fresh npm ci preserves imported bytes. - Root audit moves from one High/one Moderate/two Low to zero High/one Moderate/two Low. Normal bootstrap Fast: 220 API suites/6,273 tests and - reduced HTTP 120 suites/2,519 tests, 45 known skips. Final exact-tip gates, - CI and review remain pending; bootstrap is not final shipping acceptance. + reduced HTTP 120 suites/2,519 tests, 45 known skips. Final normal Fast: + all 29 gates, API220/6274 and reduced HTTP2519/45 known skips. All six + exact-tip PR checks PASS, web126/1664, test image/smoke and gated Trivy. + Normal PR284 merged at `36d07884` after recorded source self-review; no + independent approval or final shipping acceptance is claimed. - Document rejected unseeded dependency drift, semantic parser-hoist verification and unchanged tracked locks in the [supply-chain RCA](docs/strategy/NPM_SUPPLY_CHAIN_QUARANTINE_POLICY.md#2026-11-23-root-markdown-tooling-recovery). diff --git a/Session_starter.md b/Session_starter.md index 6506012d..da7a52e3 100644 --- a/Session_starter.md +++ b/Session_starter.md @@ -1,5 +1,61 @@ ## SCIMServer - Condensed Session Memory +### Live evidence preparation follow-up, 2026-11-23 + +Isolated harness-only work reduces repeated material preparation without +changing application source, version 0.55.70, token lifetime or assertions. +The unchanged full live attempt stopped on token expiry after 633 partial +PASS lines; no final success is claimed. Exact owned fixtures were removed. +Redaction contracts increased from 213 to 255 passing assertions, ownership +now has 224 passing assertions, and actual nested-script Jest wiring remains +nine passing tests. A 100-field/30-material probe drops repeated JSON encoding +from 3,000 calls to zero, 1,330.49 ms to 416.16 ms. A second full attempt was +explicitly stopped after 1,255 partial PASS lines and one JWKS serialization +FAIL, without a final summary. Both dictionary traversal sites now use +`PSBase.Keys` to avoid a payload member named `keys` shadowing the collection. +Focused RED/GREEN controls cover public JWKS shape and nested discovery. +All owned fixtures were removed, originals retained and listener absent. +A separate CPU experiment measured 546.875 ms before discovery guards plus a +small in-process ordered replacement loop, and 46.875 ms after. Either partial +optimization missed the local experimental goal; this is not a CI timing gate +or API improvement claim. Real-JWKS admission exposed array-shape loss; the +next early run exposed wrapped-array misclassification as a cyclic custom +object. Both have focused RED/GREEN controls, including secret discovery. +Fresh admission now passes four real JWKS plus two actual log-array evidence +checks. The repaired complete PostgreSQL live runner exited zero with +1,845/1,845 passing assertions, 169 sections, 2,060 flow steps and no cleanup +failures in 450.6 seconds. Exact fixture cleanup and listener closure passed. +The private outer verifier initially rejected an intentionally redacted ISO +timestamp; a separate receipt reconciles the complete result using its exact +target, file-write interval and executed source hashes, retaining the failed +outer receipt. Four wrong-target/stale/future/unchanged-file controls pass. +The corresponding fresh InMemory run also completed: 1,845/1,845 assertions, +169 sections and 2,060 flow steps in 421.5 seconds, outer/child exit zero. +Its exact container/client-directory cleanup, original identity retention +and listener closure pass. Both run-specific sanitized results are retained. +Strict UTF-8 web-response admission preserves original byte responses; +profile cleanup now clears a successfully deleted local handle rather than +issuing a duplicate DELETE in `finally`. Actual failure-path controls retain +the UUID for retry and preserve sticky cleanup failure evidence. +The initial root tooling audit separately reported a Markdown-it High. Separate +#284 normally merged at `36d07884` after its CI-authenticated patched lock, +zero High/Critical root audit, 29 normal Fast gates, six exact-tip checks and +recorded source self-review. No independent approval is claimed. Repository +protection requires strict CI checks, not an external approval; unavailable +Copilot review quota is not an extra merge gate. The original harness tip +`a1f00397` also passed all 29 normal Fast gates and six exact-tip checks. +This harness rollback unit changes no dependencies; the integration imports +the already-merged root lock and preserves both documentation histories. +Direct consolidation review found no new high-confidence production defect. +The combined tip still requires its own normal hook and exact-tip CI before +merge. No shipping or all-security-green claim. +See +[the current evidence boundary](docs/LIVE_EVIDENCE_REDACTION.md#preparation-reuse-and-live-run-expiry). + +| Date | Summary | +|---|---| +| 2026-11-23 | Redaction 255 PASS, nested wiring nine PASS, ownership 224 PASS. Complete PostgreSQL and InMemory live each 1,845/1,845 PASS with exact cleanup; original PostgreSQL outer failure separately reconciled. Harness a1f00397 passes 29 normal Fast/six PR checks. Integrating normally merged tooling #284 at 36d07884; combined-tip gates remain required. No shipping or cloud acceptance. | + ### Root Markdown tooling security recovery, 2026-11-23 Separate c52-based tooling-only rollback unit. Root `markdown-it` floor moves @@ -16,14 +72,18 @@ complete package-map review admits only Markdown and exact parser relocation. Fresh locked root installation preserves SHA-256 80a519be2009bd87db82fcdd5f6cff09dcb0bd9ceec2eb9fd8f178a674f75bc4. Two Markdown unit tests pass; root audit now has zero High/Critical, -one Moderate and two Low. Final normal gates/CI/review remain pending. +one Moderate and two Low. Final normal Fast passes all 29 gates, API +220 suites/6,274 tests and reduced HTTP 2,519 passes/45 known skips. All six +exact-tip PR checks pass, including web 126 files/1,664 tests, image smoke and +gated Trivy. Recorded source self-review found no unresolved defect; normal +PR #284 merged at `36d07884`. No independent approval is claimed. Application version/source, API/web locks, runtime fixtures, Docker Desktop and other worktrees unchanged. See [root tooling recovery and RCA](docs/strategy/NPM_SUPPLY_CHAIN_QUARANTINE_POLICY.md#2026-11-23-root-markdown-tooling-recovery). | Date | Summary | |---|---| -| 2026-11-23 | Root Markdown manifest/lock RED/GREEN, 23 artifact/installed-tree contracts and authenticated CI root lock accepted locally. Fresh npm ci preserves bytes; zero High/Critical root audit. Bootstrap normal Fast passed; final exact-tip gates/review pending, not shipping acceptance. | +| 2026-11-23 | Root Markdown manifest/lock RED/GREEN, 23 tooling contracts and authenticated CI lock. Final Fast 29/29 and exact-tip PR six/six PASS; normal reviewed-source merge #284 at 36d07884. Zero High/Critical root audit, with Moderate/Low retained. Not shipping acceptance. | ### POST User correction in qualification, 2026-11-23 diff --git a/docs/CONTEXT_INSTRUCTIONS.md b/docs/CONTEXT_INSTRUCTIONS.md index 6aa06b99..d357eda8 100644 --- a/docs/CONTEXT_INSTRUCTIONS.md +++ b/docs/CONTEXT_INSTRUCTIONS.md @@ -9,12 +9,43 @@ ## Active Delivery Process -**Unreleased root-tooling security recovery:** `markdown-it` manifest floor +**Unreleased live-harness recovery:** The isolated follow-up retains all prior +redaction controls and now passes 255 assertions, with nine nested-script +wiring tests and 224 ownership checks. It caches material preparation, +reduces measured text-loop cost, traverses actual dictionary keys and +preserves empty/singleton and PowerShell-wrapped arrays. Real JWKS and +downloaded log-array admission, byte-response registration and actual profile +early/finally cleanup controls precede full execution. The PostgreSQL runner +completed 1,845/1,845 assertions with exit zero and exact cleanup. A private +outer timestamp parse failed on redacted evidence; separate exact-target, +file-write-window and source-hash reconciliation retains that failed receipt. +Fresh InMemory also completes 1,845/1,845 assertions with outer/child exit zero +and exact cleanup. No parent fixture remains; shipping and deployment remain +blocked by separate acceptance requirements. +The initial root tooling graph separately reported a Markdown-it High. +Separate #284 normally merged at `36d07884`, with an authenticated CI lock, +zero High/Critical root audit, 29 final normal Fast gates, all six exact-tip +checks and a recorded source self-review. Original harness tip `a1f00397` +also passes 29 normal Fast gates and all six PR checks. The integration +preserves both changes and must pass normal gates and exact new-tip CI before +its own merge. The harness changes no dependencies; the merged root repair +supplies its own authenticated lock. Direct review found no unresolved defect. +No independent approval or all-security-green claim is made. The actual +repository policy/protection requires green exact-tip CI and resolved review +findings, not an external approval or a specific review service. Copilot +quota exhaustion is retained as a service limitation, not an extra merge gate. +Application version 0.55.70, token lifetimes, HTTP values and assertions remain +unchanged. See [RCA and qualification limits](LIVE_EVIDENCE_REDACTION.md#preparation-reuse-and-live-run-expiry). + +**Merged root-tooling security recovery:** `markdown-it` manifest floor is `^14.3.3` after observed manifest/lock RED/GREEN. Authenticated root-only CI run45275004952 artifact is imported unchanged; fresh npm ci preserves its bytes. Two focused units and 23 artifact/installed-tree controls pass; root -audit now has zero High/Critical, one Moderate and two Low. Normal bootstrap -Fast passed all29 gates; final gates/CI/review remain pending. +audit now has zero High/Critical, one Moderate and two Low. Final normal Fast +passes all29 gates, API220/6274 and reduced HTTP2519/45 known skips. All six +exact-tip checks pass, including web126/1664, test image/smoke and gated Trivy. +Source self-review is recorded as COMMENTED, not independent approval. +Normal PR284 merged at `36d07884`; shipping and deployment remain separate. API/web dependencies and application version 0.55.70 remain unchanged. See [root-tooling RCA](strategy/NPM_SUPPLY_CHAIN_QUARANTINE_POLICY.md#2026-11-23-root-markdown-tooling-recovery). diff --git a/docs/LIVE_EVIDENCE_REDACTION.md b/docs/LIVE_EVIDENCE_REDACTION.md index c822a8bd..349092bd 100644 --- a/docs/LIVE_EVIDENCE_REDACTION.md +++ b/docs/LIVE_EVIDENCE_REDACTION.md @@ -1,22 +1,269 @@ # Live integration evidence redaction -**Last verified:** 2026-11-21 +**Last verified:** 2026-11-23 ## Executive summary -This is a source-only, unreleased correction to the live integration runner. +The original redaction correction was merged in #280, and the separate +ownership correction was merged in #281. A source-only evidence-preparation +performance follow-up is now under qualification. It does not change the +application image, package versions, authentication lifetime or assertions. Authentication and credential material must reach real HTTP requests and positive administrator assertions, but must not reach console output or the -run-specific and latest evidence JSON files. No complete live runner was -started for this fix. Runtime qualification and deployment remain separate -review obligations. +run-specific and latest evidence JSON files. The historical implementation +evidence below remains useful; the new qualification result is recorded next. -**Separate ownership blocker:** Do not execute this live runner against a dev -estate containing original data. The existing name-based cleanup sweep can -select unowned original endpoints, and inventory-difference reconciliation -can select endpoints created concurrently by another owner. Redaction does -not prove cleanup ownership. That existing issue needs its own coherent fix -before original-data dev live execution; it is not redesigned in this change. +**Shared-estate boundary:** Endpoint ownership is now guarded, but the complete +suite also mutates global settings and logs. Qualify on a separately owned +disposable instance/database rather than assuming endpoint ownership makes +shared dev execution preservation-safe. + +## Preparation reuse and live-run expiry + +The unchanged complete Windows live run against exact merged `c52de06f` +emitted 633 PASS lines and no assertion FAIL lines, then aborted with +`bearer_oauth_expired` after approximately one hour. Its trap attempted cleanup +with the expired token; 15 cleanup failures were retained. No final summary +exists, and this is not a completed-suite pass. The run used separately owned +API/PostgreSQL containers, an actual tmpfs database and all 30 fresh migrations. +Exact container/network cleanup and retention of original identities were +verified afterward. Original data, the deployment owner's database/bridge and +Docker Desktop were not modified. + +The observed PowerShell child consumed nearly one CPU-second per elapsed +second. A bounded synthetic probe established one concrete cost: for 30 +registered materials and 100 nonsecret text fields after warmup, the helper +performed 3,000 redundant material JSON encodings in 1,330.49 ms. It also +re-sorted materials and rebuilt percent-escape regexes for every text field, +in both evidence-copy passes. + +The follow-up prepares the same ordered replacements once per material-set +generation. Discovery still runs before replacement. New material grows the +run-owned set and triggers preparation on the same call; duplicate material +does not. Run initialization clears all preparation even if the new set has +the same count. Replacement order, duplicate variants, case handling, +two-pass sibling discovery and original HTTP values are unchanged. Prepared +material remains process-local and is never exported. + +The same bounded probe now performs zero repeated material JSON encodings +and takes 416.16 ms, about 3.2 times faster for this synthetic case. This does +not prove sole causality for the hour-long run or an application latency +improvement. Complete live recovery remains a separate required result. + +| Validation | Result | +|---|---| +| Existing redaction contract | All 213 prior assertions retained | +| Preparation regression | Observed RED for repeated encoding, then GREEN | +| Strengthened redaction contract | 255 passing assertions, including exact public JWKS, wrapped-array discovery and empty/singleton array-shape controls | +| Actual nested-script wiring | One Jest suite, nine passing tests | +| Endpoint ownership contract | 224 passing assertions, including unchanged HTTP response identity, text/byte admission and actual profile cleanup lifecycle | +| Full live recovery | Fresh PostgreSQL and InMemory each pass 1,845/1,845 with exact cleanup. The PostgreSQL private outer timestamp-verifier failure is separately reconciled; original failed attempts remain below. | + +### JWKS dictionary collision and remaining text cost + +The second complete candidate attempt reached 1,255 PASS lines and one FAIL +line before it was explicitly stopped. Section 9z-AM failed while serializing +the public JWKS response: `OrderedDictionary` keys must be strings. A JSON +member named `keys` shadowed PowerShell's adapted dictionary `Keys` property. +The redactor enumerated the payload value instead of the dictionary's keys. +This also affected discovery inside secret-valued dictionaries. Both sites now +use `PSBase.Keys`; focused hashtable and ordered-dictionary controls reproduced +the exact serialization failure before the fix and pass afterward. Original +responses remain unchanged, and earlier-sibling secret masking is verified. +The stopped run is not a completed-suite result. Its exact API, database, +network and private client directory were removed, original identities were +retained, and the Windows listener was absent. + +A separate warm, 100-field/30-material experiment measured process CPU rather +than application latency. The prepared PowerShell path used 546.875 ms. +Moving only the ordered loop into a small in-process .NET helper still used +406.25 ms; guarding only impossible discovery matches used 218.75 ms. The +combined implementation used 46.875 ms, about 11.7 times less CPU than the +prepared PowerShell path in this case. The experiment's local 100 ms goal +failed for either partial change and passed for the combination. It is not a +new CI timing threshold, a full-run duration guarantee or an API benchmark. +These CPU measurements are distinct from the earlier elapsed-time probe. + +The guards skip URI discovery only without `://`, assignments only without +either `=` or `:`, and authorization discovery only without either scheme +name, compared case-insensitively using the current culture to match the +existing regex behavior. The original matching expressions remain +authoritative when those necessary signals exist. The .NET helper applies +the same ordered string/regex entries, including duplicates; its type stores +no static material, and each run owns its prepared plan. Permanent controls +verify overlap order, mixed regex/string entries and duplicate preservation. +No token lifetime, HTTP value, assertion or application threshold changed. + +| Issue | Type / severity | Root cause and correction | Detection / earliest possible | +|---|---|---|---| +| Public JWKS serialization and nested material discovery | Test correctness / High | An arbitrary dictionary member shadowed `Keys`. Use `PSBase.Keys` in both recursive traversal paths; preserve public shape, original values and sibling masking. | Late live section / focused arbitrary-JSON dictionary contract | +| Remaining interpreted text work | Tooling performance / Medium | Preparation reuse did not remove per-entry interpreted loops or unnecessary discovery regex calls. A measured combination of necessary-signal guards and the existing ordered plan in .NET removes those costs without changing matching semantics. Either partial experiment missed the local goal. | Bounded CPU experiment / hot-path experiment before another complete live attempt | +| Fast guard initially used a different case culture | Test correctness / Medium | An ordinal scheme-name precheck skipped an authorization string accepted by the existing current-culture regex. A Turkish dotted-I control observed RED, then GREEN after aligning the guard with `CurrentCultureIgnoreCase`. | Focused pre-commit parity probe / culture-equivalence contract when adding the fast guard | + +After the culture correction, all 242 redaction controls pass. A fresh +process-CPU recheck used 15.625 ms for the same bounded input. The CPU timer +has coarse increments and these isolated values are not a stable capacity +benchmark; no CI timing requirement was introduced. + +The subsequent real-JWKS wrapper probe rejected admission before starting +another complete suite: serialization no longer threw, but singleton `keys` +was an object rather than an array. A conditional expression assigned its +value through PowerShell's pipeline, which enumerated singleton arrays and +turned empty arrays into null. Assigning inside each branch preserves the +original collection. The exact shape regression observed RED, then GREEN. +All 250 redaction assertions now pass, including dictionary and custom-object +JWKS inputs and empty/singleton scalar arrays. The probe's exact API/database/ +network/client directory were removed, original identities retained and +Windows listener absent. Complete live recovery is still pending. + +| Additional issue | Type / severity | Root cause and correction | Detection / earliest possible | +|---|---|---|---| +| Empty and singleton evidence arrays lost their shape | Test correctness / Medium | Assignment from an `if` expression enumerated property values through the pipeline. Assign inside the selected branch. Existing count/value assertions also accepted singleton objects; new assertions require actual arrays. | Real JWKS wrapper preflight, before full suite / exact output-shape contract | + +The next fresh fixture passed all four real JWKS wrapper checks, then its +complete live attempt aborted early during JSON log download with a false +cycle error. PowerShell can wrap an array so it satisfies both +`[pscustomobject]` and `IEnumerable`; treating it as a property bag traversed +collection metadata, including `SyncRoot` pointing to itself. Preserving +arrays exposed this previously hidden classification problem. Both copy +and discovery now prefer enumerable semantics over custom-object property +enumeration while retaining dictionary handling first. A synthetic +PowerShell-wrapped array reproduced the same cycle error before the fix. +All 255 controls pass afterward, including empty/single/multiple wrapped +arrays, nested material discovery and original preservation. The failed +attempt's exact fixture cleanup passed. The private admission now also +requires actual downloaded log-array evidence to retain its array shape +before another complete suite starts. + +| Additional issue | Type / severity | Root cause and correction | Detection / earliest possible | +|---|---|---|---| +| Wrapped HTTP arrays falsely reported as cycles | Harness / Medium | A PowerShell-wrapped array also matched `pscustomobject`; property traversal reached its self-referencing collection metadata. Prefer `IEnumerable` before custom-object traversal in copy and discovery, retaining dictionary precedence. | Early live log download / wrapped-array representation contract before complete retry | + +The subsequent unchanged live attempt reached 1,763 partial PASS lines and +four late correctness FAIL lines in approximately seven minutes, without +token expiry. It still has no final summary. All four nested PowerShell +contracts created endpoints through the real web wrapper, whose ownership +admission piped `byte[]` HTTP content directly to `ConvertFrom-Json`. That +pipeline parsed byte values rather than the JSON document, so registration +rejected a missing UUID. Exact container-level cleanup passed; the live +orphan-cleanup failure remains in its original receipt. + +The wrapper now decodes only its local admission copy with strict UTF-8 before +JSON parsing. Strings remain accepted; invalid UTF-8, malformed JSON and other +body types fail closed. It still returns the original HTTP response and byte/ +string representation, and original/unowned UUID rejection is unchanged. +The actual wrapper projection reproduced the same UUID error before the fix. +All 218 ownership assertions, 255 redaction controls and nine nested-wiring +tests now pass. Fresh admission additionally exercises the four real nested +contracts before another complete suite starts. + +| Additional issue | Type / severity | Root cause and correction | Detection / earliest possible | +|---|---|---|---| +| Web-wrapper create admission did not decode bytes | Harness / Medium | The ownership wrapper parsed individual byte values, not the complete JSON document. Decode a local byte copy using strict UTF-8; preserve original response identity/body and require the same UUID ownership checks. | Late nested correctness contracts / real-wrapper text/byte admission contract | + +With byte admission repaired, the next full attempt reached 1,845 partial +PASS lines and zero assertion FAIL lines but still aborted before the final +summary: orphan reconciliation retained one cleanup failure. The actual +profile section deleted its PATCH endpoint successfully, then its `finally` +block deliberately attempted the same DELETE again and swallowed the 404. +That historical call-site behavior conflicts with the correctly sticky +ownership guard. The guard was not relaxed. Successful early cleanup now +clears only that local reference; failure retains the UUID for `finally`, +reports the real failure and leaves sticky evidence intact. The existing +9z.36 assertion now checks actual success rather than unconditional true. + +A contract executing the actual early and `finally` AST blocks observed RED +for two DELETE calls, then GREEN after the fix. Its failure control confirms +the later retry still runs and cannot erase the earlier failure. Ownership +now passes 224 assertions; redaction remains 255. Fresh real admission also +executes this actual profile lifecycle before another complete run. + +| Additional issue | Type / severity | Root cause and correction | Detection / earliest possible | +|---|---|---|---| +| Successful profile cleanup attempted twice | Harness / Medium | A historical `finally` block swallowed the second DELETE's 404, but the newer ownership guard correctly retained that failure. Clear the local reference only after verified successful early deletion; preserve failed handles and sticky failures. | Final full-run reconciliation / actual call-site early/finally lifecycle contract | + +Confirmed RCA: encoding, sorting and regex construction were coupled to every +text conversion rather than changes in discovered material. The executable +preparation-count assertion detects the mechanism without a flaky elapsed-time +threshold. The real live expiry was detected late; a stable-registry +work-count contract could have caught this redundant work before runtime. +Missing test discovery in VS Code and missing local Jest dependencies were +tooling preconditions: the targeted CLI run exposed the missing executable, +then locked `npm ci` restored 660 API packages without changing lock bytes. +The existing audit reported 22 Moderate findings; no dependency was upgraded. + +Test/gate self-improvement: applied. Reuse, duplicate registration, +same-count fresh-run invalidation and late-sibling discovery are in the +existing default-running contract, together with the JWKS collision and +ordered-plan equivalence controls. Design/architecture disposition: applied. +The small in-process loop remains inside the cohesive evidence helper and is +justified by measured interpreter cost; another service, strategy interface +or dependency would be speculative. Normal review/integration and the +remaining qualification lanes are still required. + +### Complete PostgreSQL recovery and private verification correction + +The next unchanged full PostgreSQL invocation completed: child exit zero, +169 sections, 1,845/1,845 assertions, zero failures, 2,060 flow steps and +450.6 seconds. Ownership reported no cleanup failures. Exact parent-owned +API/database/network/client-directory removal, original identity retention +and Windows listener closure passed. + +Its private outer verifier still exited one because it attempted to parse +the evidence payload's redacted timestamp. Exact material masking can also +mask short strings that occur in metadata; the redactor must not exempt +metadata or discard short material to make a verifier pass. The original +failed outer receipt is retained separately from the reconciled acceptance. +The replacement private check proves exact target, a result-file write +within the recorded owned child invocation and a changed hash when an older +file exists. Actual-result negative controls reject wrong target, stale +write, future write and unchanged hash. Both executed source hashes are +independently unchanged. The recovered result is copied to a run-specific +private artifact before another backend can overwrite the latest file. + +| Issue | Type / severity | Resolution and why | Detection / earliest possible | +|---|---|---|---| +| Private verifier parsed redacted metadata as raw ISO | Tooling / Low | Preserve redaction and the failed receipt; verify freshness using the owned invocation/file interval and exact target, with source hashes and negative controls. | After complete live execution / private verifier contract with redacted metadata | +| Missing local documentation/typecheck dependencies | Environment / Low | Actual missing-tool failures preceded normal locked root/web `npm ci`; all three tracked lock hashes remained unchanged. | Chosen validation commands / dependency availability at validation startup | +| Root documentation graph audit findings | Dependency / High | Initial root tooling audit reported `markdown-it` High, one Moderate and two Low. Separate #284 now has a CI-authenticated Markdown 14.3.3 lock and zero High/Critical locally; all 29 final normal Fast gates and all six exact-tip PR checks pass. Independent review remains pending because Copilot review quota is exhausted. This harness unit changes no dependencies. | Actual root restore/audit / root dependency audit before release | + +The root audit is distinct from unchanged API runtime dependencies and from +the successful live result. The public +[markdown-it advisory](https://github.com/advisories/GHSA-vfgh-jcmw-g37q) +describes repeated unterminated inline HTML constructs causing quadratic +parsing with HTML enabled. Remediation and approved-feed publication-age +qualification belong to the separate tooling-only +[repair #284](https://github.com/pranems/SCIMServer/pull/284), not this harness +rollback unit. Its local locked audit retains one Moderate and two Low +findings. Accepted master still has the earlier graph until normal reviewed +integration; no all-security-green or release acceptance is claimed. +Owner: repository maintainer; target: before release acceptance. + +Fresh InMemory qualification subsequently completed with outer/child exit +zero: 169 sections, 1,845/1,845 assertions, zero failures, 2,060 flow steps +and 421.5 seconds. Exact container/client-directory cleanup, original identity +retention and listener closure pass. Both run-specific sanitized results +remain private. No parent fixture remains. These local complete results +do not establish application-latency, shipping, Azure or Desktop-removal +acceptance. + +**RCA provenance:** the entire parent JSONL stream was scanned incrementally. +The previously reviewed 20:45:06.146 to 21:25:04.676 UTC interval covered 846 +later events, 85 signal candidates and 23 explicitly classified execution +results. The next interval, through **2026-11-23T22:13:59.179Z**, covers 1,037 +later events, 52 candidates and 20 explicitly classified execution results, +including the successful InMemory outcome and separate root-tooling work. +Both reviews have zero undisposed candidates. Error/signal and +diagnosis-narration passes, followed by execution-purpose and causal-marker +review, distinguished actual failures from source/read/search echoes and +expected negative controls. Prior reviewed receipts remain intact. +Missing-tool failures, real byte/profile REDs, cleanup outcomes and the private +timestamp failure have entries above; dependency-bootstrap issues belong to +the separate tooling repair's supply-chain RCA. Successful read/status +commands, expected trap output and already-diagnosed source echoes were not +counted as new incidents. No raw transcript or credential material was +exported. Later normal push/PR events are separate evidence and do not extend +this bounded transcript-review cutoff. ## Evidence boundary @@ -156,9 +403,9 @@ processes were only owned pure PowerShell contract processes. - Review the exact key policy against any new authentication response shapes. - Run the default evidence contract and required consolidation gates during normal review, without claiming the parent's older runtime proves this tip. -- The runtime owner may qualify this tip only on an isolated disposable target - with no original or concurrently owned endpoints until the separate cleanup - ownership fix is reviewed. After that fix, run on proven owned fixtures, +- The runtime owner must qualify this tip on an isolated disposable target + because complete-suite global mutations remain separate from endpoint + ownership. Run on proven owned fixtures, inspect both JSON exports and console output, and independently verify that real authentication and positive admin sentinel assertions still pass. - Original HTTP exceptions remain available to caught negative tests. @@ -184,8 +431,8 @@ Architecture disposition: accepted. One small cohesive helper owns copying, material discovery and evidence formatting. The large runner only invokes that boundary; another strategy/interface layer would be speculative. The follow-up applies one authoritative lifecycle trap rather than competing -error owners. Accepted scope boundary: cleanup ownership selection remains -a separate blocker, not an additional redesign inside this redaction fix. +error owners. Historical scope boundary: cleanup ownership selection was +repaired separately in #281, not redesigned inside the redaction fix. Userinfo discovery extends the existing text/material boundary; no transport dependency or scheme-specific strategy was introduced. Applied: URI and decoded Basic credentials share one small credential-pair diff --git a/docs/strategy/ENGINEERING_LESSONS_AND_PATTERNS.md b/docs/strategy/ENGINEERING_LESSONS_AND_PATTERNS.md index 4a714614..1f0eb13a 100644 --- a/docs/strategy/ENGINEERING_LESSONS_AND_PATTERNS.md +++ b/docs/strategy/ENGINEERING_LESSONS_AND_PATTERNS.md @@ -1,5 +1,114 @@ # Engineering lessons and patterns - the self-improving ledger +## Prepare evidence transforms when material changes (2026-11-23) + +A complete disposable-fixture live run consumed approximately an hour before +its normal OAuth token expired. The PowerShell child was CPU-active; a focused +probe established that 100 ordinary text fields re-encoded 30 unchanged +materials 3,000 times, in addition to repeated sorting and regex preparation. +Passing leak-prevention tests did not bound this work. + +Keep dynamic discovery and exact masking behavior, but prepare ordered +replacement transforms per run-owned material generation. Initialization must +invalidate preparation even when the new set has the same size; newly learned +material must protect the same call and earlier siblings in the second copy. +Test preparation work directly, not just wall-clock time or output absence. +The strengthened default contract retains every previous sentinel and adds +reuse, duplicate-registration, run-reset and late-discovery controls. +See [measurements and remaining live recovery](../LIVE_EVIDENCE_REDACTION.md#preparation-reuse-and-live-run-expiry). +This correction proves eliminated redundant work, not the sole cause of the +live-run duration. Do not extend authentication lifetimes to hide runner cost. + +## Arbitrary JSON dictionary members are not collection properties (2026-11-23) + +The live evidence redactor failed on a real public JWKS response because its +`keys` member shadowed PowerShell's adapted `Keys` property. Enumerating +`$dictionary.Keys` returned payload values, producing non-string keys and +breaking serialization. The same access in nested secret discovery could +also miss material needed to mask an earlier sibling. + +Use `$dictionary.PSBase.Keys` when traversing arbitrary `IDictionary` payloads. +Check both recursive copy and material discovery, not just the visible +serialization failure. Permanent hashtable and ordered-dictionary controls +must preserve public shape and original values and verify sibling masking +when a nested dictionary contains a `keys` member. The exact serialization +error was reproduced before the fix; all controls pass afterward. + +Also preserve the collection itself when obtaining a property value. Assigning +`$item = if (...) { $value } else { ... }` enumerated arrays through the +pipeline, collapsing singleton arrays to their element and empty arrays to +null. Assign inside each branch instead. Count/value assertions were blind +because PowerShell also lets a scalar report count one and index zero. +Require actual array type plus member values for singleton and empty cases. +The real JWKS wrapper preflight caught this before another complete suite; +the exact shape contract observed RED/GREEN and now covers both dictionary +and custom-object payloads. + +PowerShell-wrapped arrays can also satisfy both `pscustomobject` and +`IEnumerable`. Prefer enumerable elements over custom-object properties, +after dictionary handling. Otherwise traversing `SyncRoot` reports a false +cycle or recurses through collection metadata during material discovery. +Cover empty, singleton and multiple wrapped arrays, not only plain arrays. +The early real log-download failure and focused RED/GREEN controls +operationalize this representation requirement; actual log-array admission +now precedes the next complete retry. + +Representation handling must cover every semantic JSON consumer, not only +evidence copies and health probes. The real ownership web wrapper still piped +`byte[]` directly to `ConvertFrom-Json`; four late nested contracts exposed +missing UUID registration despite positive string-only mock coverage. +Decode a local admission copy with strict UTF-8, preserve the original HTTP +response/body and keep all UUID ownership checks. Permanent controls must +exercise both string and byte responses, invalid UTF-8, malformed JSON, +unsupported types, unchanged return identity and exact-ID cleanup/readback. + +## Measure both preparation and application cost (2026-11-23) + +Caching material preparation removed redundant encodings but left an +interpreted replacement loop and unnecessary discovery regex calls per text. +A bounded CPU experiment showed either an in-process ordered loop alone or +necessary-signal guards alone missed the local goal; the combination reduced +546.875 ms to 46.875 ms for 100 fields with 30 materials after warmup. +Keep timing experiments separate from deterministic CI contracts. Preserve +order, duplicates and regex/string behavior with explicit equivalence checks. +Necessary-signal prechecks must also preserve the original regex culture. +An ordinal authorization precheck missed a Turkish dotted-I match accepted +by the existing current-culture expression; a permanent RED/GREEN contract +now requires current-culture case comparison in that guard. +Do not infer full-run recovery or API latency from a synthetic helper result. +The small helper stays in the existing evidence file without a new dependency +or speculative service abstraction. + +## Successful early cleanup must discharge the local finally handle (2026-11-23) + +The full suite completed its assertions but failed sticky ownership +reconciliation because an old profile call site deleted the endpoint early, +then deliberately repeated DELETE in `finally` and swallowed the 404. +Do not weaken the newer guard or silently clear its failure. After verified +successful early deletion, clear the local reference. After failure, retain +the reference for retry and preserve the original failure even if retry +succeeds. The pre-existing cleanup assertion must report actual success. + +Exercise the actual early and `finally` AST blocks together, not just +standalone deletion mocks. The positive control observed two DELETEs before +the fix and one after. The negative control preserves the UUID after a 500, +retries successfully and still retains the earlier sticky failure. +Fresh real-fixture admission now executes the same actual lifecycle before +the complete suite. Ownership has 224 passing assertions. + +Redacted evidence is not a raw metadata interface. The next complete runner +passed 1,845 assertions and exited zero, but its private outer verifier tried +to parse a timestamp whose hyphens had been masked by the exact-material +policy. Preserve masking; do not exempt metadata or drop short material. +The private verifier instead checks exact target plus the result file's +write interval within the owned child invocation and changed hash when an +earlier file exists. Wrong-target, stale, future and unchanged-file negative +controls pass; executed source hashes and exact cleanup remain independent. +Keep the original failed outer receipt and a separate reconciled result. + +Design disposition: accepted. These are cohesive call-site and private +verification corrections; no new application abstraction is justified. + ## Live evidence must branch before serialization (2026-11-21, unreleased) The live runner's header masking did not protect plaintext OAuth/admin bodies, diff --git a/scripts/live-evidence.ps1 b/scripts/live-evidence.ps1 index 2a53ac30..764c92c1 100644 --- a/scripts/live-evidence.ps1 +++ b/scripts/live-evidence.ps1 @@ -1,8 +1,42 @@ # Evidence copies only. The HTTP runner retains the original bodies and responses. +# Apply the prepared ordered plan without a PowerShell loop for every text field. +if (-not ('ScimServer.LiveEvidence.PreparedReplacements' -as [type])) { + Add-Type -TypeDefinition @' +using System; +using System.Text.RegularExpressions; + +namespace ScimServer.LiveEvidence +{ + public sealed class PreparedReplacements + { + private readonly object[] entries; + + public PreparedReplacements(object[] entries) + { + this.entries = (object[])entries.Clone(); + } + + public string Apply(string text) + { + foreach (object entry in entries) + { + if (entry is Regex pattern) + text = pattern.Replace(text, "[REDACTED]"); + else + text = text.Replace((string)entry, "[REDACTED]"); + } + return text; + } + } +} +'@ +} + function Initialize-LiveEvidence { param([string[]]$Secrets = @()) # Nested script calls change $script scope; share the root flow's run state. $global:__ScimServerLiveEvidenceSecrets = [System.Collections.Generic.HashSet[string]]::new([StringComparer]::Ordinal) + $global:__ScimServerLiveEvidencePreparation = @{ MaterialCount = -1; Replacements = $null } foreach ($secret in $Secrets) { if ($secret) { $null = $global:__ScimServerLiveEvidenceSecrets.Add($secret) } } @@ -23,11 +57,11 @@ function Add-LiveEvidenceSecret { Add-LiveEvidenceSecret $Matches[1] } } elseif ($Value -is [System.Collections.IDictionary]) { - foreach ($key in $Value.Keys) { Add-LiveEvidenceSecret $Value[$key] } - } elseif ($Value -is [pscustomobject]) { - foreach ($property in $Value.PSObject.Properties) { Add-LiveEvidenceSecret $property.Value } + foreach ($key in $Value.PSBase.Keys) { Add-LiveEvidenceSecret $Value[$key] } } elseif ($Value -is [System.Collections.IEnumerable]) { foreach ($item in $Value) { Add-LiveEvidenceSecret $item } + } elseif ($Value -is [pscustomobject]) { + foreach ($property in $Value.PSObject.Properties) { Add-LiveEvidenceSecret $property.Value } } } @@ -51,15 +85,20 @@ function Convert-LiveEvidenceText { param([AllowEmptyString()][string]$Text) # Discover authority credentials before masking them, so the second copy # also protects earlier siblings that echo userinfo or its password. - $Text = [regex]::Replace($Text, '(?[A-Za-z][A-Za-z0-9+.-]*://)(?[^/\s?#@]+)@', { - param($match) - $raw = $match.Groups['userinfo'].Value - Add-LiveEvidenceUserInfo -Raw $raw -Decoded ([Uri]::UnescapeDataString($raw)) - return $match.Groups['scheme'].Value + '[REDACTED]@' - }) + if ($Text.Contains('://')) { + $Text = [regex]::Replace($Text, '(?[A-Za-z][A-Za-z0-9+.-]*://)(?[^/\s?#@]+)@', { + param($match) + $raw = $match.Groups['userinfo'].Value + Add-LiveEvidenceUserInfo -Raw $raw -Decoded ([Uri]::UnescapeDataString($raw)) + return $match.Groups['scheme'].Value + '[REDACTED]@' + }) + } # Free text, URLs and form assignments use the same exact material-key policy. $assignment = '(?(?>[\w%.-]+))["'']?\s*(?=|:)' - $assignments = [regex]::Matches($Text, $assignment) + $assignments = @() + if ($Text.Contains('=') -or $Text.Contains(':')) { + $assignments = [regex]::Matches($Text, $assignment) + } for ($index = $assignments.Count - 1; $index -ge 0; $index--) { $match = $assignments[$index] $key = [Uri]::UnescapeDataString($match.Groups['key'].Value) @@ -73,30 +112,42 @@ function Convert-LiveEvidenceText { $tail.Substring($value.Length) } } - $Text = [regex]::Replace($Text, '(?i)\b(?Bearer|Basic)\s+(?[A-Za-z0-9._~+/=\[\]-]+)', { - param($match) - $material = $match.Groups['material'].Value - Add-LiveEvidenceSecret $match.Value - if ($match.Groups['scheme'].Value -ieq 'Basic' -and - $material -match '^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$') { - $decoded = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($material)) - Add-LiveEvidenceUserInfo -Raw $decoded -Decoded $decoded - } - return '[REDACTED]' - }) - foreach ($secret in @($global:__ScimServerLiveEvidenceSecrets | Sort-Object Length -Descending)) { - foreach ($variant in @($secret, [Uri]::EscapeDataString($secret), [System.Net.WebUtility]::UrlEncode($secret), (ConvertTo-Json -InputObject $secret -Compress).Trim('"'))) { - if ($variant.Contains('%')) { - $pattern = [regex]::Replace([regex]::Escape($variant), '%[0-9A-Fa-f]{2}', { - param($escape) return '(?i:' + $escape.Value + ')' - }) - $Text = [regex]::Replace($Text, $pattern, '[REDACTED]') - } elseif ($variant) { - $Text = $Text.Replace($variant, '[REDACTED]') + if ($Text.IndexOf('Bearer', [StringComparison]::CurrentCultureIgnoreCase) -ge 0 -or + $Text.IndexOf('Basic', [StringComparison]::CurrentCultureIgnoreCase) -ge 0) { + $Text = [regex]::Replace($Text, '(?i)\b(?Bearer|Basic)\s+(?[A-Za-z0-9._~+/=\[\]-]+)', { + param($match) + $material = $match.Groups['material'].Value + Add-LiveEvidenceSecret $match.Value + if ($match.Groups['scheme'].Value -ieq 'Basic' -and + $material -match '^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$') { + $decoded = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($material)) + Add-LiveEvidenceUserInfo -Raw $decoded -Decoded $decoded } + return '[REDACTED]' + }) + } + # Material only grows within a run. Rebuild encoding and regex preparation + # after discovery, not for every field in both evidence-copy passes. + if ($global:__ScimServerLiveEvidencePreparation.MaterialCount -ne $global:__ScimServerLiveEvidenceSecrets.Count) { + $replacements = [System.Collections.Generic.List[object]]::new() + foreach ($secret in @($global:__ScimServerLiveEvidenceSecrets | Sort-Object Length -Descending)) { + foreach ($variant in @($secret, [Uri]::EscapeDataString($secret), [System.Net.WebUtility]::UrlEncode($secret), (ConvertTo-Json -InputObject $secret -Compress).Trim('"'))) { + if ($variant.Contains('%')) { + $pattern = [regex]::Replace([regex]::Escape($variant), '%[0-9A-Fa-f]{2}', { + param($escape) return '(?i:' + $escape.Value + ')' + }) + $replacements.Add([regex]::new($pattern)) + } elseif ($variant) { + $replacements.Add($variant) + } + } + } + $global:__ScimServerLiveEvidencePreparation = @{ + MaterialCount = $global:__ScimServerLiveEvidenceSecrets.Count + Replacements = [ScimServer.LiveEvidence.PreparedReplacements]::new($replacements.ToArray()) } } - return $Text + return $global:__ScimServerLiveEvidencePreparation.Replacements.Apply($Text) } function Copy-LiveEvidenceValue { @@ -126,11 +177,16 @@ function Copy-LiveEvidenceValue { } $Ancestors.Add($Value) try { - if ($Value -is [System.Collections.IDictionary] -or $Value -is [pscustomobject]) { + if ($Value -is [System.Collections.IDictionary] -or + ($Value -is [pscustomobject] -and $Value -isnot [System.Collections.IEnumerable])) { $copy = [ordered]@{} - $keys = if ($Value -is [System.Collections.IDictionary]) { @($Value.Keys) } else { @($Value.PSObject.Properties.Name) } + $keys = if ($Value -is [System.Collections.IDictionary]) { @($Value.PSBase.Keys) } else { @($Value.PSObject.Properties.Name) } foreach ($key in $keys) { - $item = if ($Value -is [System.Collections.IDictionary]) { $Value[$key] } else { $Value.PSObject.Properties[$key].Value } + if ($Value -is [System.Collections.IDictionary]) { + $item = $Value[$key] + } else { + $item = $Value.PSObject.Properties[$key].Value + } if (Test-LiveEvidenceSecretKey $key) { # Validate first so a cycle cannot bypass the explicit shape error. $null = Copy-LiveEvidenceValue $item $Ancestors ($Depth + 1) diff --git a/scripts/live-test.ps1 b/scripts/live-test.ps1 index ad3c2a23..75226c4f 100644 --- a/scripts/live-test.ps1 +++ b/scripts/live-test.ps1 @@ -224,7 +224,13 @@ function Invoke-WebRequest { try { $result = Microsoft.PowerShell.Utility\Invoke-WebRequest @PSBoundParameters -AllowInsecureRedirect $endpointResponse = if ($endpointRequest -and $endpointRequest.Create -and $result.StatusCode -ge 200 -and $result.StatusCode -lt 300) { - $result.Content | ConvertFrom-Json -ErrorAction Stop + $content = $result.Content + if ($content -is [byte[]]) { + $content = [Text.UTF8Encoding]::new($false, $true).GetString($content) + } elseif ($content -isnot [string]) { + throw 'Endpoint creation response JSON must be text or UTF-8 bytes.' + } + $content | ConvertFrom-Json -ErrorAction Stop } else { $null } Complete-LiveEndpointRequest -Request $endpointRequest -StatusCode $result.StatusCode -Response $endpointResponse Add-FlowStep -StartedAt $requestStart -Method $m -Uri $Uri -RequestHeaders $Headers -RequestBody $Body -StatusCode $result.StatusCode -ResponseHeaders $result.Headers -ResponseBody $result.Content -ErrorMessage $null @@ -6847,16 +6853,22 @@ Test-Result -Success ($p35.profile.settings.UserSoftDeleteEnabled -eq "True") -M Test-Result -Success ($p35.profile.settings.StrictSchemaValidation -eq "True") -Message "9z.35: StrictSchemaValidation present after merged PATCH" # Cleanup PATCH test endpoint -try { Invoke-RestMethod -Uri "$baseUrl/scim/admin/endpoints/$($patchEp.id)" -Method DELETE -Headers $headers | Out-Null } catch {} -Test-Result -Success $true -Message "9z.36: Cleaned up PATCH test endpoint" +$patchEndpointDeleted = $false +try { + Invoke-RestMethod -Uri "$baseUrl/scim/admin/endpoints/$($patchEp.id)" -Method DELETE -Headers $headers | Out-Null + $patchEndpointDeleted = $true + $patchEp = $null +} catch { + Write-LiveEvidenceFailure $_ +} +Test-Result -Success $patchEndpointDeleted -Message "9z.36: Cleaned up PATCH test endpoint" } finally { # --- Guaranteed cleanup: runs on success AND on any throw in the try above --- # Delete all 6 preset endpoints by object (null-guarded so a mid-section throw - # before a given endpoint was created is harmless). Idempotent: on the success - # path the patch endpoint was already deleted above; a second DELETE 404s and - # is swallowed. + # before a given endpoint was created is harmless). The successful early + # PATCH-endpoint cleanup clears its local reference to prevent a second DELETE. Write-Host "`n--- Cleanup: Delete test endpoints ---" -ForegroundColor Cyan @($entraEp, $minimalEp, $rfcEp, $userOnlyEp, $inlineEp, $patchEp) | ForEach-Object { if ($_ -and $_.id) { diff --git a/scripts/test/live-endpoint-ownership.contract.ps1 b/scripts/test/live-endpoint-ownership.contract.ps1 index c5afb67f..ab247948 100644 --- a/scripts/test/live-endpoint-ownership.contract.ps1 +++ b/scripts/test/live-endpoint-ownership.contract.ps1 @@ -60,6 +60,8 @@ function Reset-Mock { $script:deleteStatus = 204 $script:absenceStatus = 404 $script:transportFailure = $false + $script:webContentKind = 'string' + $script:lastWebResponse = $null $script:failOwnedRead = $false $script:probeStatus = 404 $script:probeReuseRejected = $false @@ -105,7 +107,15 @@ function Invoke-MockWeb { $script:calls.Add([pscustomobject]@{ Uri = $Uri; Method = $m; Headers = $Headers; Body = $Body; ContentType = $ContentType; ErrorAction = $PSBoundParameters['ErrorAction']; Skip = $SkipHttpErrorCheck; Redirect = $AllowInsecureRedirect }) if ($script:transportFailure) { throw 'mock transport unavailable' } $status = if ($m -eq 'DELETE') { $script:deleteStatus } elseif ($m -eq 'POST') { $script:createStatus } else { $script:absenceStatus } - return [pscustomobject]@{ StatusCode = $status; Headers = @{}; Content = (@{ id = $script:createId } | ConvertTo-Json) } + $content = @{ id = $script:createId } | ConvertTo-Json + switch ($script:webContentKind) { + 'bytes' { $content = [Text.Encoding]::UTF8.GetBytes($content) } + 'invalid-json' { $content = [Text.Encoding]::UTF8.GetBytes('{ invalid JSON') } + 'invalid-utf8' { $content = [byte[]]@(0xc3, 0x28) } + 'unsupported' { $content = [pscustomobject]@{ id = $script:createId } } + } + $script:lastWebResponse = [pscustomobject]@{ StatusCode = $status; Headers = @{}; Content = $content } + return $script:lastWebResponse } . ([scriptblock]::Create($projection)) $baseUrl = 'http://fixture.invalid' @@ -245,6 +255,59 @@ foreach ($countJson in @( Assert (@($script:calls | Where-Object { $_.Method -eq 'POST' }).Count -eq 0) 'Invalid JSON count must reject before creation transport.' } +foreach ($kind in @('string', 'bytes')) { + Reset-Mock + Initialize-LiveEndpointOwnership + $script:webContentKind = $kind + $response = Invoke-WebRequest -Uri "$baseUrl/scim/admin/endpoints" -Method POST -Headers $headers + Assert ($global:__ScimServerLiveEndpointOwnership.ownedEndpointHandles.ContainsKey($owned)) 'String and UTF-8 byte create responses must register the exact owned UUID.' + $representationUnchanged = ($kind -eq 'bytes' -and $response.Content -is [byte[]]) -or + ($kind -eq 'string' -and $response.Content -is [string]) + Assert ([object]::ReferenceEquals($response, $script:lastWebResponse) -and $representationUnchanged) 'Creation admission must return the original HTTP response and content representation.' + $null = Invoke-WebRequest -Uri "$baseUrl/scim/admin/endpoints/$owned" -Method DELETE -Headers $headers + Assert ($global:__ScimServerLiveEndpointOwnership.ownedEndpointHandles[$owned].Deleted) 'Byte-aware creation admission must retain exact-ID deletion and 404 readback.' +} +foreach ($kind in @('invalid-json', 'invalid-utf8', 'unsupported')) { + Reset-Mock + Initialize-LiveEndpointOwnership + $script:webContentKind = $kind + Expect-Failure { Invoke-WebRequest -Uri "$baseUrl/scim/admin/endpoints" -Method POST -Headers $headers } 'Invalid create-response representation must fail closed.' + Assert ($global:__ScimServerLiveEndpointOwnership.ownedEndpointHandles.Count -eq 0) 'Invalid create-response representation cannot register ownership.' +} + +Reset-Mock +Initialize-LiveEndpointOwnership +$entraEp = $minimalEp = $rfcEp = $userOnlyEp = $inlineEp = $null +$patchEp = Invoke-RestMethod -Uri "$baseUrl/scim/admin/endpoints" -Method POST -Headers $headers +$profileLifecycle = @($ast.EndBlock.Statements | Where-Object { + $_ -is [Management.Automation.Language.TryStatementAst] -and + $_.Body.Extent.Text.Contains('9z.36: Cleaned up PATCH test endpoint') +}) +Assert ($profileLifecycle.Count -eq 1) 'The actual profile lifecycle cleanup must be uniquely identified.' +$patchCleanup = @($profileLifecycle[0].Body.Statements | Where-Object { + $_ -is [Management.Automation.Language.TryStatementAst] -and + $_.Body.Extent.Text.Contains('$patchEp.id') -and $_.Body.Extent.Text.Contains('-Method DELETE') +}) +Assert ($patchCleanup.Count -eq 1) 'The actual early PATCH-endpoint cleanup must be uniquely identified.' +. ([scriptblock]::Create($patchCleanup[0].Extent.Text)) +$profileFinally = $profileLifecycle[0].Finally.Extent.Text +. ([scriptblock]::Create($profileFinally.Substring(1, $profileFinally.Length - 2))) +Assert (@($script:calls | Where-Object { $_.Method -eq 'DELETE' -and $_.Uri -eq "$baseUrl/scim/admin/endpoints/$owned" }).Count -eq 1) 'Successful profile cleanup must not DELETE the same owned endpoint again in finally.' +Assert ($global:__ScimServerLiveEndpointOwnership.ownedEndpointHandles[$owned].Deleted -and + $global:__ScimServerLiveEndpointOwnership.endpointCleanupFailures.Count -eq 0) 'Successful early profile deletion must retain its verified handle without a cleanup failure.' +Reset-Mock +Initialize-LiveEndpointOwnership +$patchEp = Invoke-RestMethod -Uri "$baseUrl/scim/admin/endpoints" -Method POST -Headers $headers +$script:deleteStatus = 500 +$patchEndpointDeleted = $false +. ([scriptblock]::Create($patchCleanup[0].Extent.Text)) +Assert (-not $patchEndpointDeleted -and $patchEp.id -eq $owned -and + -not $global:__ScimServerLiveEndpointOwnership.ownedEndpointHandles[$owned].Deleted) 'Failed early profile deletion must retain its UUID and unsuccessful result.' +$script:deleteStatus = 204 +. ([scriptblock]::Create($profileFinally.Substring(1, $profileFinally.Length - 2))) +Assert ($global:__ScimServerLiveEndpointOwnership.ownedEndpointHandles[$owned].Deleted -and + $global:__ScimServerLiveEndpointOwnership.endpointCleanupFailures.Count -eq 1) 'Finally must finish failed profile cleanup without erasing its earlier failure.' + foreach ($badId in @($null, '', 'malformed', [guid]::Empty.ToString())) { Reset-Mock Initialize-LiveEndpointOwnership diff --git a/scripts/test/live-evidence-redaction.contract.ps1 b/scripts/test/live-evidence-redaction.contract.ps1 index a4ac5d60..e78016b2 100644 --- a/scripts/test/live-evidence-redaction.contract.ps1 +++ b/scripts/test/live-evidence-redaction.contract.ps1 @@ -255,4 +255,98 @@ foreach ($wrapper in @('Invoke-RestMethod', 'Invoke-WebRequest')) { } $gateSource = Get-Content (Join-Path $root 'scripts\pre-push-checks.ps1') -Raw Assert-Contract ($gateSource.Contains("'live evidence: pre-serialization redaction contract'")) 'Default pre-push gate does not run the pure evidence contract.' +foreach ($keySet in @( + @{ keys = @(@{ kid = 'synthetic-public-key'; kty = 'RSA'; n = 'public-modulus'; e = 'AQAB' }) }, + [ordered]@{ keys = @(@{ kid = 'synthetic-public-key'; kty = 'RSA'; n = 'public-modulus'; e = 'AQAB' }) }, + [pscustomobject]@{ keys = @([pscustomobject]@{ kid = 'synthetic-public-key'; kty = 'RSA'; n = 'public-modulus'; e = 'AQAB' }) } +)) { + Initialize-LiveEvidence + $before = ConvertTo-Json -InputObject $keySet -Depth 10 -Compress + $roundTrip = ConvertTo-LiveEvidenceJson $keySet | ConvertFrom-Json + Assert-Contract ($roundTrip.keys -is [array]) 'Singleton JWKS keys evidence changed from an array to an object.' + Assert-Contract ($roundTrip.keys.Count -eq 1 -and $roundTrip.keys[0].kid -ceq 'synthetic-public-key') 'A keys-named member corrupted the public JWKS evidence shape.' + Assert-Contract ($roundTrip.keys[0].n -ceq 'public-modulus') 'Public key metadata was lost.' + Assert-Contract ((ConvertTo-Json -InputObject $keySet -Depth 10 -Compress) -ceq $before) 'JWKS evidence conversion mutated the original response.' +} +$arrayShape = ConvertTo-LiveEvidenceJson ([ordered]@{ empty = @(); single = @('public-value') }) | ConvertFrom-Json +Assert-Contract ($arrayShape.empty -is [array] -and $arrayShape.empty.Count -eq 0) 'Empty evidence array changed to null.' +Assert-Contract ($arrayShape.single -is [array] -and $arrayShape.single.Count -eq 1 -and $arrayShape.single[0] -ceq 'public-value') 'Singleton scalar evidence array lost its shape.' +foreach ($size in 0..2) { + $items = [object[]]::new($size) + for ($index = 0; $index -lt $size; $index++) { $items[$index] = "public-item-$index" } + $wrapped = [psobject]::AsPSObject($items) + $safeWrapped = ConvertTo-LiveEvidence $wrapped + Assert-Contract ($safeWrapped -is [array] -and $safeWrapped.Count -eq $size) 'A PowerShell-wrapped array was mistaken for a custom object or a cycle.' +} +Initialize-LiveEvidence +$wrappedMaterial = [psobject]::AsPSObject(@('synthetic-wrapped-array-material')) +$safeWrappedMaterial = ConvertTo-LiveEvidence ([ordered]@{ + earlier = 'synthetic-wrapped-array-material' + password = $wrappedMaterial +}) +Assert-Contract ($safeWrappedMaterial.earlier -ceq '[REDACTED]' -and $safeWrappedMaterial.password -ceq '[REDACTED]') 'Wrapped array material was not discovered for earlier-sibling masking.' +Assert-Contract ($wrappedMaterial.Count -eq 1 -and $wrappedMaterial[0] -ceq 'synthetic-wrapped-array-material') 'Wrapped array discovery mutated the original value.' +Initialize-LiveEvidence +$keyedMaterial = 'synthetic-dictionary-material-with-keys-member' +$safe = ConvertTo-LiveEvidence ([ordered]@{ + earlier = $keyedMaterial + password = @{ keys = @($keyedMaterial) } +}) +Assert-Contract ($safe.earlier -ceq '[REDACTED]' -and $safe.password -ceq '[REDACTED]') 'A keys-named member bypassed nested material discovery.' +$script:materialPreparations = 0 +function ConvertTo-Json { + param($InputObject, [switch]$Compress, [int]$Depth = 2, [switch]$AsArray) + if ($InputObject -is [string] -and $InputObject.StartsWith('synthetic-preparation-')) { + $script:materialPreparations++ + } + Microsoft.PowerShell.Utility\ConvertTo-Json @PSBoundParameters +} +try { + Initialize-LiveEvidence -Secrets @('synthetic-preparation-first secret') + $null = Convert-LiveEvidenceText 'warmup' + $script:materialPreparations = 0 + foreach ($number in 1..10) { + $text = Convert-LiveEvidenceText 'synthetic-preparation-first secret metadata' + Assert-Contract ($text -ceq '[REDACTED] metadata') 'Repeated evidence changed its masking result.' + } + Assert-Contract ($script:materialPreparations -eq 0) 'Unchanged evidence material is re-encoded for every text field.' + Add-LiveEvidenceSecret 'synthetic-preparation-first secret' + $null = Convert-LiveEvidenceText 'duplicate registration' + Assert-Contract ($script:materialPreparations -eq 0) 'Duplicate registration rebuilds evidence preparation.' + Add-LiveEvidenceSecret 'synthetic-preparation-later/secret?' + $encoded = [Uri]::EscapeDataString('synthetic-preparation-later/secret?') + $text = Convert-LiveEvidenceText "synthetic-preparation-first secret $encoded" + Assert-Contract ($text -ceq '[REDACTED] [REDACTED]') 'Newly discovered material is not masked immediately.' + Assert-Contract ($script:materialPreparations -gt 0) 'New material did not rebuild the evidence preparation.' + $afterDiscovery = $script:materialPreparations + $null = Convert-LiveEvidenceText 'unchanged second generation' + Assert-Contract ($script:materialPreparations -eq $afterDiscovery) 'Second-generation preparation was not reused.' + Initialize-LiveEvidence -Secrets @('synthetic-preparation-newrun') + $text = Convert-LiveEvidenceText 'synthetic-preparation-newrun synthetic-preparation-first secret' + Assert-Contract ($text -ceq '[REDACTED] synthetic-preparation-first secret') 'A fresh run reused stale material with the same registry count.' + $safe = ConvertTo-LiveEvidence ([ordered]@{ + earlier = 'synthetic-preparation-late-discovery' + token = 'synthetic-preparation-late-discovery' + }) + Assert-Contract ($safe.earlier -ceq '[REDACTED]' -and $safe.token -ceq '[REDACTED]') 'Preparation caching broke late-sibling discovery.' +} finally { + Remove-Item -LiteralPath Function:\ConvertTo-Json +} +$orderedPlan = [ScimServer.LiveEvidence.PreparedReplacements]::new(@('overlap-value', 'overlap')) +Assert-Contract ($orderedPlan.Apply('overlap-value overlap') -ceq '[REDACTED] [REDACTED]') 'Prepared replacements changed overlap ordering.' +$regexPlan = [ScimServer.LiveEvidence.PreparedReplacements]::new(@([regex]::new('(?i:%2f)'), 'literal')) +Assert-Contract ($regexPlan.Apply('%2F %2f literal') -ceq '[REDACTED] [REDACTED] [REDACTED]') 'Prepared replacements changed mixed regex/string behavior.' +$duplicatePlan = [ScimServer.LiveEvidence.PreparedReplacements]::new(@('D', 'D')) +$duplicateReference = 'D'.Replace('D', '[REDACTED]').Replace('D', '[REDACTED]') +Assert-Contract ($duplicatePlan.Apply('D') -ceq $duplicateReference) 'Prepared replacements deduplicated ordered entries.' +$originalCulture = [Threading.Thread]::CurrentThread.CurrentCulture +try { + [Threading.Thread]::CurrentThread.CurrentCulture = [Globalization.CultureInfo]::GetCultureInfo('tr-TR') + Initialize-LiveEvidence + $cultureHeader = 'BAS' + [char]0x0130 + 'C synthetic-culture-material' + Assert-Contract ([regex]::IsMatch($cultureHeader, '(?i)\bBasic\s+')) 'Culture regression did not exercise the existing authorization expression.' + Assert-Contract ((Convert-LiveEvidenceText $cultureHeader) -ceq '[REDACTED]') 'Authorization discovery guard changed the regex culture semantics.' +} finally { + [Threading.Thread]::CurrentThread.CurrentCulture = $originalCulture +} Write-Host "PASS: $checks live evidence redaction assertions; no HTTP/runtime started."