mirror of
https://github.com/Sea-Haven-Industries/procurement-ingest.git
synced 2026-09-30 03:43:12 +00:00
* 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.
304 lines
11 KiB
Python
304 lines
11 KiB
Python
"""Stream-record -> SHOC webhook envelope mapping tests (plan Phase 5).
|
|
|
|
Pins the emitter's classification and envelope-building contract
|
|
(docs/shoc-webhook-contract.md sections 3-4) against realistic DynamoDB
|
|
stream records: event-type classification incl. the cancelled transition and
|
|
the already-cancelled no-false-cancel case, the write_origin echo guard,
|
|
exact eventSourceARN table discrimination, delivery_id/occurred_at mapping,
|
|
data null-fill + source_email_s3_key exclusion, and Decimal JSON-safety.
|
|
|
|
Also the enum golden pin: the emitted event_type set must equal the four
|
|
contract names AND the published spec's webhooks keys (lambdas/api/
|
|
openapi.json), and the classification's status/record_type value space must
|
|
stay anchored to the WO pipeline's template_parser enums.
|
|
|
|
Offline and pure -- envelope.py has no boto3 clients, no env reads.
|
|
"""
|
|
|
|
import json
|
|
from datetime import datetime, timezone
|
|
from decimal import Decimal
|
|
from pathlib import Path
|
|
|
|
import pytest
|
|
|
|
from tests.support import REPO_ROOT, load_lambda_module
|
|
|
|
# Realistic stream ARNs for BOTH tables: "WorkOrders" is a leading substring
|
|
# of "WorkOrderComments", which is exactly the trap the exact-segment parse
|
|
# in envelope._table_name exists to avoid.
|
|
WO_STREAM_ARN = (
|
|
"arn:aws:dynamodb:us-east-1:011934824531:table/WorkOrders"
|
|
"/stream/2026-07-23T00:00:00.000"
|
|
)
|
|
COMMENTS_STREAM_ARN = (
|
|
"arn:aws:dynamodb:us-east-1:011934824531:table/WorkOrderComments"
|
|
"/stream/2026-07-23T00:00:00.000"
|
|
)
|
|
|
|
CONTRACT_EVENT_TYPES = {
|
|
"work_order.created",
|
|
"work_order.updated",
|
|
"work_order.cancelled",
|
|
"work_order.comment_added",
|
|
}
|
|
|
|
|
|
@pytest.fixture(scope="module")
|
|
def envelope():
|
|
return load_lambda_module("wo", "shoc_emitter/envelope")
|
|
|
|
|
|
def _record(arn, event_name, new_image=None, old_image=None, **meta):
|
|
"""Build a stream record; ``meta`` overrides event_id / creation."""
|
|
stream = {
|
|
"ApproximateCreationDateTime": meta.get("creation", 1784642602.0),
|
|
"SequenceNumber": meta.get("sequence_number", "100"),
|
|
"StreamViewType": "NEW_AND_OLD_IMAGES",
|
|
}
|
|
if new_image is not None:
|
|
stream["NewImage"] = new_image
|
|
if old_image is not None:
|
|
stream["OldImage"] = old_image
|
|
return {
|
|
"eventID": meta.get("event_id", "4b7c2f0e-0001"),
|
|
"eventName": event_name,
|
|
"eventSource": "aws:dynamodb",
|
|
"eventSourceARN": arn,
|
|
"dynamodb": stream,
|
|
}
|
|
|
|
|
|
def _wo_image(**overrides):
|
|
image = {
|
|
"work_order_id": {"S": "11144580730"},
|
|
"wo_status": {"S": "new"},
|
|
"description": {"S": "Dock door 14 won't close"},
|
|
"record_type": {"S": "new_work_order"},
|
|
"created_at": {"S": "2026-07-16T14:03:22.114208+00:00"},
|
|
"updated_at": {"S": "2026-07-16T14:03:22.114208+00:00"},
|
|
}
|
|
image.update(overrides)
|
|
return image
|
|
|
|
|
|
def _comment_image(**overrides):
|
|
image = {
|
|
"work_order_id": {"S": "11144580730"},
|
|
"comment_id": {"S": "11144580730#2026-04-27T23:51:48#a1b2c3d4e5f6"},
|
|
"record_type": {"S": "comment"},
|
|
"commenter": {"S": "APM Technician"},
|
|
"text": {"S": "Vendor dispatched, ETA tomorrow AM."},
|
|
"created_at": {"S": "2026-04-27T23:51:48"},
|
|
"ingested_at": {"S": "2026-07-16T14:05:00+00:00"},
|
|
}
|
|
image.update(overrides)
|
|
return image
|
|
|
|
|
|
# --- Classification ----------------------------------------------------------
|
|
|
|
|
|
def test_workorders_insert_is_created(envelope):
|
|
event = envelope.build_event(_record(WO_STREAM_ARN, "INSERT", _wo_image()))
|
|
assert event["event_type"] == "work_order.created"
|
|
|
|
|
|
def test_workorders_modify_is_updated(envelope):
|
|
event = envelope.build_event(
|
|
_record(
|
|
WO_STREAM_ARN,
|
|
"MODIFY",
|
|
_wo_image(wo_status={"S": "assigned"}),
|
|
_wo_image(wo_status={"S": "new"}),
|
|
)
|
|
)
|
|
assert event["event_type"] == "work_order.updated"
|
|
|
|
|
|
def test_cancelled_transition_is_cancelled(envelope):
|
|
event = envelope.build_event(
|
|
_record(
|
|
WO_STREAM_ARN,
|
|
"MODIFY",
|
|
_wo_image(wo_status={"S": "cancelled"}),
|
|
_wo_image(wo_status={"S": "assigned"}),
|
|
)
|
|
)
|
|
assert event["event_type"] == "work_order.cancelled"
|
|
|
|
|
|
def test_already_cancelled_modify_is_updated_not_cancelled(envelope):
|
|
# OLD already cancelled + NEW cancelled: any later touch to a cancelled
|
|
# WO must NOT re-emit a cancelled event (no false cancels on retries).
|
|
event = envelope.build_event(
|
|
_record(
|
|
WO_STREAM_ARN,
|
|
"MODIFY",
|
|
_wo_image(wo_status={"S": "cancelled"}),
|
|
_wo_image(wo_status={"S": "cancelled"}),
|
|
)
|
|
)
|
|
assert event["event_type"] == "work_order.updated"
|
|
|
|
|
|
def test_comment_insert_is_comment_added(envelope):
|
|
event = envelope.build_event(
|
|
_record(COMMENTS_STREAM_ARN, "INSERT", _comment_image())
|
|
)
|
|
assert event["event_type"] == "work_order.comment_added"
|
|
assert set(event["data"]) == set(envelope.COMMENT_DATA_FIELDS)
|
|
|
|
|
|
def test_remove_is_skipped(envelope):
|
|
assert envelope.build_event(_record(WO_STREAM_ARN, "REMOVE")) is None
|
|
assert envelope.build_event(_record(COMMENTS_STREAM_ARN, "REMOVE")) is None
|
|
|
|
|
|
def test_comment_modify_is_skipped(envelope):
|
|
record = _record(COMMENTS_STREAM_ARN, "MODIFY", _comment_image(), _comment_image())
|
|
assert envelope.build_event(record) is None
|
|
|
|
|
|
def test_shoc_write_origin_echo_guard_skips(envelope):
|
|
record = _record(
|
|
WO_STREAM_ARN,
|
|
"INSERT",
|
|
_wo_image(write_origin={"S": "shoc-write-api"}),
|
|
)
|
|
assert envelope.build_event(record) is None
|
|
# Any OTHER write_origin value is not an echo and must still deliver.
|
|
record = _record(
|
|
WO_STREAM_ARN,
|
|
"INSERT",
|
|
_wo_image(write_origin={"S": "email-processor"}),
|
|
)
|
|
assert envelope.build_event(record) is not None
|
|
|
|
|
|
# --- eventSourceARN table discrimination -------------------------------------
|
|
|
|
|
|
def test_table_discrimination_is_exact_segment_not_substring(envelope):
|
|
# The WorkOrders stream must classify as a WO state event and the
|
|
# WorkOrderComments stream as a comment event -- never cross-parsed even
|
|
# though "WorkOrders" is a leading substring of "WorkOrderComments".
|
|
wo_event = envelope.build_event(_record(WO_STREAM_ARN, "INSERT", _wo_image()))
|
|
assert wo_event["event_type"] == "work_order.created"
|
|
comment_event = envelope.build_event(
|
|
_record(COMMENTS_STREAM_ARN, "INSERT", _comment_image())
|
|
)
|
|
assert comment_event["event_type"] == "work_order.comment_added"
|
|
|
|
# Superstring table names must not substring-match either known table.
|
|
for table in ("WorkOrdersLegacy", "WorkOrderCommentsArchive", "XWorkOrders"):
|
|
arn = (
|
|
f"arn:aws:dynamodb:us-east-1:011934824531:table/{table}"
|
|
"/stream/2026-07-23T00:00:00.000"
|
|
)
|
|
assert envelope.build_event(_record(arn, "INSERT", _wo_image())) is None
|
|
|
|
# A malformed / missing ARN skips rather than raises (total function).
|
|
assert envelope.build_event(_record("", "INSERT", _wo_image())) is None
|
|
|
|
|
|
# --- Envelope fields ---------------------------------------------------------
|
|
|
|
|
|
def test_envelope_constant_fields_and_delivery_id(envelope):
|
|
record = _record(WO_STREAM_ARN, "INSERT", _wo_image(), event_id="evt-abc-123")
|
|
event = envelope.build_event(record)
|
|
assert event["schema_version"] == 1
|
|
assert event["source"] == "procurement-ingest/workorder-shoc-emitter"
|
|
assert event["replay"] is False
|
|
# delivery_id is the stream record eventID: unique per source event and
|
|
# stable across ESM retries (the receiver's idempotency key).
|
|
assert event["delivery_id"] == "evt-abc-123"
|
|
|
|
|
|
def test_occurred_at_from_decimal_creation_time(envelope):
|
|
# ApproximateCreationDateTime arrives as epoch seconds; via the low-level
|
|
# stream API it deserializes as Decimal -- must still map to an aware
|
|
# ISO-8601 +00:00 instant.
|
|
creation = Decimal("1784642602")
|
|
record = _record(WO_STREAM_ARN, "INSERT", _wo_image(), creation=creation)
|
|
event = envelope.build_event(record)
|
|
expected = datetime.fromtimestamp(1784642602.0, tz=timezone.utc).isoformat()
|
|
assert event["occurred_at"] == expected
|
|
assert event["occurred_at"].endswith("+00:00")
|
|
|
|
|
|
def test_data_null_fills_absent_fields_and_excludes_s3_key(envelope):
|
|
image = {
|
|
"work_order_id": {"S": "11144580730"},
|
|
"wo_status": {"S": "unknown"},
|
|
# Internal pointer: must never leave the account via the webhook.
|
|
"source_email_s3_key": {"S": "inbound/2026/07/abc.eml"},
|
|
}
|
|
event = envelope.build_event(_record(WO_STREAM_ARN, "INSERT", image))
|
|
assert set(event["data"]) == set(envelope.WO_DATA_FIELDS)
|
|
assert "source_email_s3_key" not in event["data"]
|
|
assert event["data"]["work_order_id"] == "11144580730"
|
|
for field in set(envelope.WO_DATA_FIELDS) - {"work_order_id", "wo_status"}:
|
|
assert event["data"][field] is None
|
|
|
|
|
|
def test_decimal_image_values_become_json_safe(envelope):
|
|
image = _wo_image(
|
|
severity={"N": "3"},
|
|
priority={"N": "2.5"},
|
|
)
|
|
event = envelope.build_event(_record(WO_STREAM_ARN, "INSERT", image))
|
|
assert event["data"]["severity"] == 3
|
|
assert isinstance(event["data"]["severity"], int)
|
|
assert event["data"]["priority"] == 2.5
|
|
assert isinstance(event["data"]["priority"], float)
|
|
# The whole envelope must serialize -- this is the raw body that gets
|
|
# signed and POSTed.
|
|
json.dumps(event)
|
|
|
|
|
|
# --- Enum golden pin ---------------------------------------------------------
|
|
|
|
|
|
def test_event_type_set_matches_contract_and_openapi_webhooks(envelope):
|
|
scenarios = [
|
|
_record(WO_STREAM_ARN, "INSERT", _wo_image()),
|
|
_record(
|
|
WO_STREAM_ARN,
|
|
"MODIFY",
|
|
_wo_image(wo_status={"S": "assigned"}),
|
|
_wo_image(wo_status={"S": "new"}),
|
|
),
|
|
_record(
|
|
WO_STREAM_ARN,
|
|
"MODIFY",
|
|
_wo_image(wo_status={"S": "cancelled"}),
|
|
_wo_image(wo_status={"S": "assigned"}),
|
|
),
|
|
_record(COMMENTS_STREAM_ARN, "INSERT", _comment_image()),
|
|
]
|
|
emitted = {envelope.build_event(record)["event_type"] for record in scenarios}
|
|
assert emitted == CONTRACT_EVENT_TYPES
|
|
|
|
# The published read-API spec documents the same four outbound webhook
|
|
# events; emitter and spec must move together.
|
|
spec_path = Path(REPO_ROOT) / "lambdas" / "api" / "openapi.json"
|
|
spec = json.loads(spec_path.read_text(encoding="utf-8"))
|
|
assert set(spec["webhooks"]) == emitted
|
|
|
|
|
|
def test_status_and_record_type_value_space_anchored_to_template_parser(envelope):
|
|
# The WO pipeline's template_parser enums are the wo_status/record_type
|
|
# value space the stream carries (prompts.py mirrors them for the AI
|
|
# path). The cancelled-transition trigger value must be a real status,
|
|
# and the contract's record_type enum must be exactly the pipeline's
|
|
# email-type enum -- widen either side only in a PR that updates both.
|
|
template_parser = load_lambda_module("wo", "email_processor/template_parser")
|
|
assert envelope.CANCELLED_STATUS in template_parser.VALID_STATUSES
|
|
assert template_parser.VALID_EMAIL_TYPES == {
|
|
"new_work_order",
|
|
"update",
|
|
"comment",
|
|
"cancellation",
|
|
}
|