procurement-ingest/tests/support/loader.py
Adam Moussa c040050373
feat(webhook): SHOC WO webhook emitter - dark-ship streams + HMAC secret/rotation (PR-2) (#137)
* docs(webhook): revise SHOC webhook contract and plan for post-migration reality

Branch re-cut on main 2026-07-23 (old base carried stale PR #99 commits).

Contract Rev 2026-07-23:
- Producer account corrected: seahaven-prod (011934824531); mgmt frozen
- Reconciliation backstop is the new procurement read API, not SyncController
- wo_status "unknown" is real; SHOC must map it (checklist item added)
- write_origin forward-compat note for phase-2 write-back echo suppression
- SyncVendorReplies retirement flagged (dead table, no vendor_reply event)

Plan updates:
- Account gate: seahaven-prod only; never enable streams on mgmt tables
- Emitter ships DARK (ESMs enabled=False); activation is a deliberate flip
  after the SHOC receiver passes shared HMAC vectors
- Post-refactor conventions: common.py helpers, bundle-consistency AST pins,
  pytest.ini --cov additions, consolidated test roots
- Dedicated-CMK rationale, secret-ARN handooff step, consumer audit refreshed
  (slack-bot decommissioned), enum golden test, write_origin skip-branch test

* feat(webhook): SHOC WO webhook emitter — dark-ship streams, HMAC secret + rotation

Implements docs/shoc-webhook-plan.md Phases 1-5 (PR-2 of the SHOC
call-and-be-called effort). Everything ships DARK: both DynamoDB event
source mappings deploy enabled=False; activation is a deliberate
one-line follow-up PR gated on the SHOC receiver passing the shared
HMAC test vectors.

- Streams: NEW_AND_OLD_IMAGES on WorkOrders + WorkOrderComments
  (in-place update, RETAIN + logical IDs untouched; no existing
  consumers — verified live, neither table had a stream).
- workorder-shoc-emitter (Py3.12/ARM64): stream -> envelope ->
  HMAC-signed POST per docs/shoc-webhook-contract.md; strict per-shard
  ordering (parallelization 1, bisect off, retry until 24h age,
  ReportBatchItemFailures); 429/5xx/timeout block the shard in order,
  other 4xx park to workorder-shoc-emitter-rejected; ESM failures ->
  workorder-shoc-emitter-failures (metadata; replay rebuilds from
  DynamoDB). Echo guard skips write_origin=shoc-write-api.
- Secret workorder-ingest/shoc-webhook-hmac on a dedicated CMK
  (alias workorder-ingest-shoc-webhook-kms); cross-account
  GetSecretValue/DescribeSecret + kms:Decrypt granted to exactly
  arn:aws:iam::396287094661:role/shoc-backend-dev. RemovalPolicy
  DESTROY deliberately (machine-generated material; avoids the
  fixed-name RETAIN-orphan deadlock).
- workorder-shoc-hmac-rotator: 30-day rotation, dual-key overlap,
  64-hex keys, kid = UTC %Y-%m-%dT%H.
- Alarms (ALARM-only -> site-alerts): emitter errors/throttles/
  duration + iterator-age (>=10 min) + failures/rejected queue
  depth; rotator standard trio.
- scripts/replay_shoc_webhooks.py: dry-run-default operator replay
  (rebuilds from tables, replay:true envelopes).
- Tests: 742 passing, 85.56% aggregate; golden HMAC vectors shared
  with SHOC in docs/shoc-webhook-test-vectors.json (emitter + replay
  signing pinned to identical vectors); bundle-consistency AST pins
  for both new bundles.
- README: WO stack + webhook feed section, alarm table, runbooks;
  removed stale seahaven-slack-bot consumer references.

* fix(webhook): kms:ViaService pins, https-only delivery, cross-account principal CI pin

GPT-4.1 cross-family review of the policy surface (no BLOCK): FIX applied
to the cross-account shoc-backend-dev Decrypt statement and both Lambda
role KMS grants (the key is only ever used via Secrets Manager); its
invariant-enforcement QUESTION answered durably with
tests/test_cross_account_principal_pin.py (any new foreign IAM principal
in cdk/ fails CI). Scanner mediums fixed: delivery.py and the replay
script now refuse non-https URLs (urllib follows file:// and http://).
SQS metadata-action and dynamodb:ListStreams NITs skipped: standard CDK
grant shapes; ListStreams has no resource-level scoping. The 4 gitleaks
HIGHs on docs/shoc-webhook-test-vectors.json are deliberate non-secrets
(shared receiver-verification vectors) suppressed machine-level with
justification.

* harden(webhook): resolve /sh-security-review findings (1 confirmed medium + cheap fixes)

High-recall detector fan-out (injection/authz/secrets-crypto/iac-iam/logic)
+ proof-or-kill verifier. Gate PASSES: 1 confirmed medium, 0 confirmed
critical/high. Confirmed finding fixed; several unverified-but-cheap
hardenings applied since the emitter ships dark and activation is weeks out.

- CONFIRMED medium (confused deputy): the rotation Lambda's generated
  invoke permission for secretsmanager.amazonaws.com carried no
  SourceAccount/SourceArn, so any account's Secrets Manager could invoke
  the rotator. Patched the generated CfnPermission in place (a second
  permission would be additive, not restrictive) to pin account + this
  secret ARN.
- delivery + replay: refuse to follow receiver 3xx redirects (no-redirect
  opener) so live X-SH-* auth headers can't be forwarded to a
  receiver-chosen Location and an http:// Location can't slip past the
  https guard. Fixed the "unfollowed 3xx" comment that was factually wrong.
- delivery: classify 401/403 as retryable (invalidate key cache + retry in
  order) instead of parking -- transient auth failures (rotation outran the
  TTL cache, clock skew) are availability events, not contract bugs.
- envelope: build_event now genuinely total (guarded eventID /
  ApproximateCreationDateTime subscripts) per its own never-raise contract.
- handler: catch-all so an unexpected per-record error (e.g. SQS park
  failure) reports only that record instead of failing the whole batch
  (which would re-deliver every earlier success for 24h); per-invocation
  emit/skip batch summary so a systemic silent drop is queryable/alarmable.
- rotator: narrow the AWSCURRENT-read except to ResourceNotFound/JSONDecode
  (transient SM/KMS errors re-raise so the overlap key isn't silently
  dropped); kid uniqueness checked against ALL retained kids with a random
  suffix on collision (never reissue a kid for a different secret).
- contract: skeleton-upsert required on ANY unknown work_order_id (not just
  comment-before-create) + monotonicity guard (ignore older updated_at), so
  a parked created or an out-of-order replay can't corrupt receiver state.

Unverified/refuted findings left as-is with rationale: the two "high" logic
claims (whole-batch crash triggers, ordering violation) were refuted on
reachability (real stream records carry required fields; persistence writes
strings only; full-state idempotent upsert absorbs the ordering gap). Signed
kid/version binding (AUTHZ-002) declined: coordinated contract change, not
cheap, no exploit with one algorithm/key.

* fix(webhook): drop kid from rotator test_ok log (CodeQL clear-text-logging FP)

GHAS CodeQL flagged py/clear-text-logging-sensitive-data (high) at
_test_secret's success log because head["kid"] is subscripted from the
same parsed-secret dict that holds head["secret"] — the taint tracker
can't tell the non-secret key id from the secret. The secret value is
never logged. Rather than dismiss the alert (fragile; re-alerts on line
moves), remove the flow: kid is already logged at stage time in
_create_secret and version_id correlates the steps, so the test_ok log
keeps only event + version_id. Also hardens against a future edit that
swaps the logged field.
2026-07-24 22:12:20 +00:00

156 lines
7.4 KiB
Python

"""The ONE Lambda-module loader for the whole procurement-ingest test suite.
Every test root (the repo-root ``tests/`` suite AND the two per-pipeline
``lambdas/*/email_processor/tests`` suites) loads Lambda modules through this
single ``load_lambda_module`` -- there is exactly one copy of the sys.modules
save/restore dance in the repo, and the repo-root ``conftest.py`` re-exports it.
``from conftest import ...`` is deliberately NOT used: three ``conftest.py``
files exist across the roots and pytest's per-directory sys.path prepending
makes the bare name ``conftest`` resolve nondeterministically -- exactly the
bare-name-collision class this phase eliminates. The loader lives here instead,
imported the same way from every invocation directory as ``tests.support``.
"""
import importlib.util
import sys
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parents[2]
_SHARED_DIR = REPO_ROOT / "lambdas" / "shared"
# Sibling modules imported by bare name from the handlers (the Lambda runtime
# puts each function's own directory on sys.path; the CDK bundling then cp's the
# shared modules in flat beside handler.py so those bare imports resolve too).
# template_parser/derived_fields are duplicated PER PIPELINE, so their bare
# names MUST be bound to the right pipeline's file around each handler exec --
# relying on sys.path ordering (or on whatever a previously collected suite left
# in sys.modules) silently binds a handler to the OTHER pipeline's sibling.
# ses_auth/email_parsing/emf/web_ui_auth are now single-sourced under
# lambdas/shared/ (Phase 3); the loop below resolves them from there via a
# shared-dir fallback.
#
# Phase 5 decomposed each God-handler into flat siblings (prompts/telemetry/
# extraction/enrichment/persistence). The order below is DEPENDENCY-TOPOLOGICAL,
# not alphabetical: the loader binds each bare name in sys.modules right after
# exec'ing it, so a sibling whose module body does `from <x> import ...` must
# appear AFTER <x> here or its exec ImportErrors. The load-bearing edges are
# emf < telemetry, prompts < extraction, and derived_fields + telemetry <
# enrichment. WO has no enrichment/derived_fields sibling -- the loader's
# `if not sibling_path.exists(): continue` silently skips them there, so one
# unified tuple serves both pipelines.
#
# web_ui_auth was added (no dependencies; after emf) so
# load_lambda_module("po"|"wo", "web_ui/handler") can bind the web_ui handlers'
# bare `from web_ui_auth import is_authenticated` (lambdas/po/web_ui/handler.py:15
# and the wo equivalent) via the same shared-dir fallback.
_SIBLING_MODULES = (
"ses_auth",
"email_parsing",
"emf",
"web_ui_auth",
# procurement-api siblings (lambdas/api/): pagination/serialization/router
# have no sibling deps; wo_repo/po_repo import pagination, so they follow
# it. These names exist only under lambdas/api/, so the po/wo handler
# loads skip them via the exists() check.
"pagination",
"serialization",
"router",
"wo_repo",
"po_repo",
"prompts",
"template_parser",
"derived_fields",
"telemetry",
"extraction",
"enrichment",
"persistence",
# SHOC emitter siblings (lambdas/wo/shoc_emitter/): envelope and delivery
# are both standalone (no sibling deps, stdlib + boto3 only), so appending
# them at the end keeps the tuple dependency-topological; the order between
# the two is irrelevant. They exist only under wo/shoc_emitter/, so every
# other handler load skips them via the exists() check.
"envelope",
"delivery",
)
def _load_module(path, module_name):
if module_name in sys.modules:
return sys.modules[module_name]
spec = importlib.util.spec_from_file_location(module_name, path)
module = importlib.util.module_from_spec(spec)
sys.modules[module_name] = module
spec.loader.exec_module(module)
return module
def load_lambda_module(pipeline, name):
"""Load a Lambda module by file path under a unique, deterministic name.
``pipeline`` is one of ``{"po", "wo", "shared"}`` and ``name`` is the path
under ``lambdas/<pipeline>/`` without the ``.py`` suffix (e.g.
``"email_processor/handler"``, ``"web_ui/handler"``, or ``"ses_auth"`` for
shared). The module name is ``f"{pipeline}_{name.replace('/', '_')}"`` --
this reproduces the existing unique names byte-for-byte
(``po_email_processor_handler``, ``wo_email_processor_handler``,
``shared_ses_auth``), so every existing ``sys.modules`` sibling key
(``po_email_processor_handler__persistence`` etc.) is unchanged.
The handler files all share the basename ``handler.py`` and are not
importable as packages, so a plain ``import handler`` would collide across
Lambdas. The same loader serves leaf modules (``ses_auth.py``,
``web_ui_auth.py``), which are likewise loaded by file path.
Handler modules import their siblings by bare name (e.g. ``from
template_parser import try_deterministic_parse``). Each sibling is loaded
from the handler's own directory (falling back to ``lambdas/shared/``) under
a unique module name and registered under its bare name only for the
duration of the handler exec, then the previous binding is restored -- so
this loader is deterministic regardless of collection order and of what the
per-Lambda test suites (which put their own module dir on sys.path) have
already cached in sys.modules.
The save/restore dance does NOT shrink to nothing: template_parser (and
derived_fields/prompts/telemetry/extraction/enrichment/persistence) remain
duplicated bare names ACROSS pipelines. One pytest session execs BOTH
handlers; without per-exec bare-name binding + restore, whichever pipeline
loads second silently binds to the first pipeline's sibling. Only
ses_auth/email_parsing/emf/web_ui_auth are single-sourced.
"""
path = REPO_ROOT / "lambdas" / pipeline / f"{name}.py"
module_name = f"{pipeline}_{name.replace('/', '_')}"
if module_name in sys.modules:
return sys.modules[module_name]
# Keep the handler dir on sys.path for parity with the Lambda runtime.
handler_dir = str(path.parent)
if handler_dir not in sys.path:
sys.path.insert(0, handler_dir)
if path.name != "handler.py":
# Leaf modules (e.g. ses_auth.py / web_ui_auth.py) have no sibling
# imports of the per-pipeline kind the dance guards.
return _load_module(path, module_name)
saved = {}
for sibling in _SIBLING_MODULES:
# Per-pipeline siblings (template_parser/derived_fields/...) resolve next
# to the handler; the shared, single-sourced siblings (ses_auth/
# email_parsing/emf/web_ui_auth) fall back to lambdas/shared/. No
# ambiguity: post Phase 3 the shared names exist ONLY under shared/, the
# per-pipeline names ONLY next to the handler.
sibling_path = path.parent / f"{sibling}.py"
if not sibling_path.exists():
sibling_path = _SHARED_DIR / f"{sibling}.py"
if not sibling_path.exists():
continue
saved[sibling] = sys.modules.get(sibling)
sys.modules[sibling] = _load_module(sibling_path, f"{module_name}__{sibling}")
try:
module = _load_module(path, module_name)
finally:
for sibling, previous in saved.items():
if previous is not None:
sys.modules[sibling] = previous
else:
sys.modules.pop(sibling, None)
return module