procurement-ingest/lambdas/api/handler.py

245 lines
9.8 KiB
Python
Raw Normal View History

feat(api): procurement-api read stack + OpenAPI docs (SHOC reconciliation path) (#127) * feat(api): add procurement-api stack - read API + OpenAPI docs page Third CDK stack: API Gateway REST API (IAM SigV4) over both pipelines' tables, replacing SHOC's retired SyncController cross-account DynamoDB scan as the reconciliation/backfill path. - lambdas/api/: handler (healthcheck + docs-token gate + router dispatch), router (single route table), pagination (opaque cursor, hostile -> 400), Decimal-safe serialization, wo_repo/po_repo reads. No VendorReplies. - OpenAPI 3.1 spec as source of truth incl. top-level webhooks section documenting the outbound SHOC feed; phase-2 write endpoints x-planned (router answers 501). Self-contained /docs page, no CDN. - Auth: AWS_IAM on data routes + resource policy scoped to exactly arn:aws:iam::396287094661:role/shoc-backend-dev on GET/*; /docs and /openapi.json carve-out is token-gated in the Lambda via shared web_ui_auth (fail-closed, INFRA-74 posture). - KMS: explicit Decrypt/DescribeKey on the DynamoDB CMK from SSM (name-imported table drops the key association - INFRA-104 class). - Alarms: errors/throttles/duration(p99>=22.5s) + gateway 5xx, ALARM-only to site-alerts. No access logging in v1 (docs ?token= shim stays out of logs); cloud_watch_role=False. - Tests: handler auth-seam + routing + Decimal round-trip; moto cursor pagination incl. hostile cursors; spec<->router drift gate; bundle AST pins for the api command; pytest.ini --cov + loader siblings. - Deploy role: third stack DescribeStacks ARN + procurement-api smoke invoke ARN (re-run create-deploy-role.sh before merge). * harden(api): apply sh-security-review findings to procurement-api Fan-out (6 detectors) + review findings resolved: Correctness / DoS: - pagination: require EXACT key-set match (was subset) so a partial/foreign composite cursor can't reach DynamoDB as an inconsistent ExclusiveStartKey -> ValidationException -> 500; comments Query now pins the cursor's work_order_id to the path entity. - handler: map botocore ValidationException to 400 (defense in depth) so a crafted cursor can't drive the zero-threshold 5xx alarm. - web_ui_auth: compare tokens as bytes; a non-ASCII presented token now fails closed (401) instead of crashing hmac.compare_digest into a 500. Resolves the pre-existing xfail(strict) follow-up test; hardens the web UIs too. Docs page: - typeStr() now escapes the one spec-derived string that reached innerHTML. - spec inlined into the docs <script> block escapes "<" -> < (</script> breakout guard); /openapi.json still served byte-faithful. - Cache-Control: no-store + Referrer-Policy: no-referrer on docs responses so the ?token= URL stays out of caches/Referer. - spec-drift test asserts the committed spec carries no "</" / "<!--". IAM / IaC: - resource policy enumerates the 7 data GET resources instead of GET/* so a future GET route can't silently inherit SHOC cross-account reach. - kms:Decrypt grant gains a kms:ViaService=dynamodb condition. - stage throttling (50 rps / 100 burst) bounds the unauthenticated /docs blast radius below the 10k account default. - corrected the PATCH/POST comment (same-account callers aren't blocked by the resource policy; 501 handler + absent write grant are the gate). - documented the RETAIN log-group first-deploy rollback trap and the resource-policy-needs-redeploy gotcha in-stack. Mandatory GPT-4.1 cross-family review of the full policy surface: no BLOCK/FIX. 675 tests pass, ruff clean, cdk synth green.
2026-07-23 19:32:20 -04:00
"""Procurement API Lambda (API Gateway REST proxy integration).
Auth is split by route class and enforced at two layers:
- Data routes: AWS_IAM at the gateway (SigV4; cross-account callers allowed by
the API resource policy). The handler does NOT re-check a token there --
authorization is API Gateway's job on those routes.
- Docs routes (/docs, /openapi.json): reachable at the gateway (auth NONE +
resource-policy carve-out) but the handler fails closed on the shared
header token via web_ui_auth (same secret + constant-time compare as the
web UIs), so they are never an unauthenticated data path (INFRA-74).
"""
import logging
from pathlib import Path
import po_repo
import wo_repo
from botocore.exceptions import ClientError
from pagination import BadCursor, clamp_limit
from router import DATA_ROUTES, DOCS_ROUTES, PLANNED_ROUTES
from serialization import error_response, json_response
from web_ui_auth import is_authenticated
logger = logging.getLogger()
logger.setLevel(logging.INFO)
_MODULE_DIR = Path(__file__).resolve().parent
_SPEC_PATH = _MODULE_DIR / "openapi.json"
_DOCS_PATH = _MODULE_DIR / "docs.html"
_REDOC_JS_PATH = _MODULE_DIR / "redoc.standalone.js"
feat(api): Redocly lint gate + SHOC-themed /docs (Redoc theming, topbar, collapsible samples) (#130) * feat(api): Add @redocly/cli as a dev dependency Signed-off-by: Adam Moussa <adam@seahavenind.com> * feat(api): Add Redocly configuration file with custom rules Signed-off-by: Adam Moussa <adam@seahavenind.com> * chore(api): Redocly lint config + bring openapi.json into compliance redocly.yaml from the Redocly guidelines builder, with three generated rules corrected: response-contains-property had the status codes as the required body fields (intent was the Error schema's top-level 'error'; 403 exempt since API Gateway emits AWS's {message} shape, 501 not 503); operation-4xx-problem-details-rfc7807 off (adopting RFC 7807 would be a runtime + SHOC-contract change, decided against); the two inert casing rules (parameter names, schema properties) removed because both name sets are contract-pinned (gateway resource paths, DynamoDB items). Spec changes, no runtime impact: operationIds renamed to method-prefixed kebab-case (get-work-orders, post-work-order-comment, ...); tags added to all 15 operations + root tags object (groups the Redoc sidebar); examples on all six parameters; license field; server description punctuation; two descriptions reworded to start capitalized. Real linter catches fixed: the two x-planned ops were missing their {workOrderId} path parameter and any 4xx response (403 added - true today, gateway rejects unsigned). .redocly.lint-ignore.yaml pins the six deliberate exceptions: webhook keys are the shipped SHOC contract event names (not renameable), and the x-planned ops answer only 501 (no 2xx to document). package.json: npm run lint:api. Verified: lint 0 errors, 675 pytest, headless-Chrome render of the tagged docs page. * feat(api): SHOC design-system theme for /docs (vendored fonts) Themes the Redoc page with the canonical SHOC token set: Montserrat 600 headings / DM Sans body / JetBrains Mono code, primary #1c75bc, navy #262262 sidebar text + right panel, #f9fafb background, 244px sidebar. sortRequiredPropsFirst on; 200 responses pre-expanded. Fonts ship as lambdas/api/fonts.css (latin woff2 subsets from @fontsource 5.3.0, embedded as data URIs, ~90KB) and inline via a new __FONTS_CSS__ placeholder with the same </style breakout guard -- the offline single-response invariant holds, nothing fetches Google Fonts (test-pinned). Bundling cp + bundle-consistency pin + spec-drift asset checks extended. Verified: headless-Chrome render (theme + fonts applied), ruff, 675 pytest, cdk synth + staged-asset check. * feat(api): SHOC gradient topbar on /docs 64px fixed header with the SHOC shell gradient token (#1b1f52 -> #1c4f8f -> #1c75bc), Sea Haven wordmark in Montserrat 600, page name right-aligned in DM Sans. Redoc's scrollYOffset: 64 keeps the sticky sidebar and anchor scrolling clear of the fixed bar. Verified via headless-Chrome render. * style(api): normalize /docs header and right-panel blues The right panel's #262262 is a purple-leaning navy that clashed with the cyan-leaning gradient, and the bar's brightest point sat directly over the dark panel. Right panel now uses #1b1f52 (the gradient's own dark endpoint) and the gradient runs bright-to-dark so its dark end lands flush on the panel -- no seam, one blue family. Verified via headless-Chrome render. * style(api): right-panel gradient on /docs via bundle-pinned override Redoc's theme only takes solid colors (it derives shades from rightPanel.backgroundColor), so the gradient (#1b3d79 -> #1b3068 -> #1b1f52, continuing the topbar blend) rides as a CSS override on the styled-components classes of the per-section right-panel divs (.sc-iGgWBj.sc-gsFSXq + the .sc-dExYaf stub). Those names are deterministic for the vendored 2.5.3 bundle (verified across loads) but change on any Redoc bump: re-derive via headless probe (find elements whose computed background equals the rightPanel color). If they stop matching, the panel falls back to the solid #1b1f52 theme color -- cosmetic only. Verified via headless-Chrome render. * feat(api): collapsible samples column on /docs Redoc CE has no built-in panel toggle, so the topbar gains a Hide/Show samples button that flips .samples-collapsed on <html>: the right-panel divs hide (same bundle-pinned styled-components classes as the gradient override) and each section's content half takes the full width. Choice persists in localStorage; aria-pressed tracks state. If the pinned classes stop matching after a Redoc bump the toggle goes inert -- cosmetic only. Both states verified via headless-Chrome render. * ci(api): spec-lint CI gate + npm Dependabot coverage New spec-lint job mirrors the local npm run lint:api so openapi.json cannot drift from redocly.yaml with green CI. Dependabot gains the npm ecosystem (package.json is new; nothing watched @redocly/cli). * feat(api): docs finishing touches - x-tagGroups, favicon, docs:preview x-tagGroups sections the Redoc sidebar (Read API / Meta / SHOC Feed); inline data-URI SVG favicon (SHOC blue) stops the browser's follow-up /favicon.ico request 403ing at the gateway; npm run docs:preview wraps the real-handler local render (scripts/preview_docs.py); README gains a docs-page architecture section covering the inline pattern, theme, pinned-selector caveat, and tooling. Lint 0 errors, 675 pytest, headless render verified. --------- Signed-off-by: Adam Moussa <adam@seahavenind.com>
2026-07-24 14:04:30 -04:00
_FONTS_CSS_PATH = _MODULE_DIR / "fonts.css"
feat(api): stock Swagger UI for /docs (vendored offline) (#128) * feat(api): use stock Swagger UI for the /docs page Replaces the custom renderer with vendored stock Swagger UI (swagger-ui-dist 5.17.14, Apache-2.0), kept offline (no CDN) and inlined server-side into the single token-gated /docs response alongside the spec. BaseLayout (topbar hidden); try-it-out disabled since data routes need SigV4 (use Postman for live calls). Breakout guards on the inlined css/js/spec. Bundle-consistency + spec-drift + handler tests updated for the two vendored assets. cdk diff = Lambda code asset only (no IAM/API/policy change). * fix(api): render Swagger UI with the canonical StandaloneLayout recipe The BaseLayout-only init (apis preset, no standalone preset) rendered incorrectly. Switch to the canonical swagger-ui-dist recipe: vendor swagger-ui-standalone-preset.js and init with presets:[apis, SwaggerUIStandalonePreset] + layout:"StandaloneLayout" (topbar hidden, try-it-out disabled). Verified via headless Chrome against the live deployed page: all 9 endpoints + 4 webhooks + models render. Tests/bundling updated for the third vendored asset. * fix(api): declutter the Swagger UI docs page The page rendered (stock Swagger UI, StandaloneLayout) but looked cramped: a dense info.description wall of inline-code chips collided across Swagger UI's tight default line-height, and the Servers box showed a SEE-STACK-OUTPUT placeholder. - Trim info.description to a few concise lines (detail lives in README + the webhook contract doc). - Inject the live invoke URL into servers[0].url per request (from the API Gateway request context; committed literal is the fallback), so the Servers box shows the real endpoint and drops the server-variables section. - CSS: loosen description line-height + inline-code padding so chips never overlap; tidy the scheme container spacing. - Handler: cache the heavy CSS/JS/preset shell once; splice the (server- injected) spec per request. Verified via headless Chrome against the live deployed page.
2026-07-23 20:19:47 -04:00
# The docs page template carries these placeholders, filled server-side so
# /docs is a single token-gated request (a browser can't attach the auth
feat(api): Redocly lint gate + SHOC-themed /docs (Redoc theming, topbar, collapsible samples) (#130) * feat(api): Add @redocly/cli as a dev dependency Signed-off-by: Adam Moussa <adam@seahavenind.com> * feat(api): Add Redocly configuration file with custom rules Signed-off-by: Adam Moussa <adam@seahavenind.com> * chore(api): Redocly lint config + bring openapi.json into compliance redocly.yaml from the Redocly guidelines builder, with three generated rules corrected: response-contains-property had the status codes as the required body fields (intent was the Error schema's top-level 'error'; 403 exempt since API Gateway emits AWS's {message} shape, 501 not 503); operation-4xx-problem-details-rfc7807 off (adopting RFC 7807 would be a runtime + SHOC-contract change, decided against); the two inert casing rules (parameter names, schema properties) removed because both name sets are contract-pinned (gateway resource paths, DynamoDB items). Spec changes, no runtime impact: operationIds renamed to method-prefixed kebab-case (get-work-orders, post-work-order-comment, ...); tags added to all 15 operations + root tags object (groups the Redoc sidebar); examples on all six parameters; license field; server description punctuation; two descriptions reworded to start capitalized. Real linter catches fixed: the two x-planned ops were missing their {workOrderId} path parameter and any 4xx response (403 added - true today, gateway rejects unsigned). .redocly.lint-ignore.yaml pins the six deliberate exceptions: webhook keys are the shipped SHOC contract event names (not renameable), and the x-planned ops answer only 501 (no 2xx to document). package.json: npm run lint:api. Verified: lint 0 errors, 675 pytest, headless-Chrome render of the tagged docs page. * feat(api): SHOC design-system theme for /docs (vendored fonts) Themes the Redoc page with the canonical SHOC token set: Montserrat 600 headings / DM Sans body / JetBrains Mono code, primary #1c75bc, navy #262262 sidebar text + right panel, #f9fafb background, 244px sidebar. sortRequiredPropsFirst on; 200 responses pre-expanded. Fonts ship as lambdas/api/fonts.css (latin woff2 subsets from @fontsource 5.3.0, embedded as data URIs, ~90KB) and inline via a new __FONTS_CSS__ placeholder with the same </style breakout guard -- the offline single-response invariant holds, nothing fetches Google Fonts (test-pinned). Bundling cp + bundle-consistency pin + spec-drift asset checks extended. Verified: headless-Chrome render (theme + fonts applied), ruff, 675 pytest, cdk synth + staged-asset check. * feat(api): SHOC gradient topbar on /docs 64px fixed header with the SHOC shell gradient token (#1b1f52 -> #1c4f8f -> #1c75bc), Sea Haven wordmark in Montserrat 600, page name right-aligned in DM Sans. Redoc's scrollYOffset: 64 keeps the sticky sidebar and anchor scrolling clear of the fixed bar. Verified via headless-Chrome render. * style(api): normalize /docs header and right-panel blues The right panel's #262262 is a purple-leaning navy that clashed with the cyan-leaning gradient, and the bar's brightest point sat directly over the dark panel. Right panel now uses #1b1f52 (the gradient's own dark endpoint) and the gradient runs bright-to-dark so its dark end lands flush on the panel -- no seam, one blue family. Verified via headless-Chrome render. * style(api): right-panel gradient on /docs via bundle-pinned override Redoc's theme only takes solid colors (it derives shades from rightPanel.backgroundColor), so the gradient (#1b3d79 -> #1b3068 -> #1b1f52, continuing the topbar blend) rides as a CSS override on the styled-components classes of the per-section right-panel divs (.sc-iGgWBj.sc-gsFSXq + the .sc-dExYaf stub). Those names are deterministic for the vendored 2.5.3 bundle (verified across loads) but change on any Redoc bump: re-derive via headless probe (find elements whose computed background equals the rightPanel color). If they stop matching, the panel falls back to the solid #1b1f52 theme color -- cosmetic only. Verified via headless-Chrome render. * feat(api): collapsible samples column on /docs Redoc CE has no built-in panel toggle, so the topbar gains a Hide/Show samples button that flips .samples-collapsed on <html>: the right-panel divs hide (same bundle-pinned styled-components classes as the gradient override) and each section's content half takes the full width. Choice persists in localStorage; aria-pressed tracks state. If the pinned classes stop matching after a Redoc bump the toggle goes inert -- cosmetic only. Both states verified via headless-Chrome render. * ci(api): spec-lint CI gate + npm Dependabot coverage New spec-lint job mirrors the local npm run lint:api so openapi.json cannot drift from redocly.yaml with green CI. Dependabot gains the npm ecosystem (package.json is new; nothing watched @redocly/cli). * feat(api): docs finishing touches - x-tagGroups, favicon, docs:preview x-tagGroups sections the Redoc sidebar (Read API / Meta / SHOC Feed); inline data-URI SVG favicon (SHOC blue) stops the browser's follow-up /favicon.ico request 403ing at the gateway; npm run docs:preview wraps the real-handler local render (scripts/preview_docs.py); README gains a docs-page architecture section covering the inline pattern, theme, pinned-selector caveat, and tooling. Lint 0 errors, 675 pytest, headless render verified. --------- Signed-off-by: Adam Moussa <adam@seahavenind.com>
2026-07-24 14:04:30 -04:00
# header to a follow-up asset fetch) with the vendored Redoc bundle, the
# design-system fonts, and the spec inlined, no CDN.
feat(api): procurement-api read stack + OpenAPI docs (SHOC reconciliation path) (#127) * feat(api): add procurement-api stack - read API + OpenAPI docs page Third CDK stack: API Gateway REST API (IAM SigV4) over both pipelines' tables, replacing SHOC's retired SyncController cross-account DynamoDB scan as the reconciliation/backfill path. - lambdas/api/: handler (healthcheck + docs-token gate + router dispatch), router (single route table), pagination (opaque cursor, hostile -> 400), Decimal-safe serialization, wo_repo/po_repo reads. No VendorReplies. - OpenAPI 3.1 spec as source of truth incl. top-level webhooks section documenting the outbound SHOC feed; phase-2 write endpoints x-planned (router answers 501). Self-contained /docs page, no CDN. - Auth: AWS_IAM on data routes + resource policy scoped to exactly arn:aws:iam::396287094661:role/shoc-backend-dev on GET/*; /docs and /openapi.json carve-out is token-gated in the Lambda via shared web_ui_auth (fail-closed, INFRA-74 posture). - KMS: explicit Decrypt/DescribeKey on the DynamoDB CMK from SSM (name-imported table drops the key association - INFRA-104 class). - Alarms: errors/throttles/duration(p99>=22.5s) + gateway 5xx, ALARM-only to site-alerts. No access logging in v1 (docs ?token= shim stays out of logs); cloud_watch_role=False. - Tests: handler auth-seam + routing + Decimal round-trip; moto cursor pagination incl. hostile cursors; spec<->router drift gate; bundle AST pins for the api command; pytest.ini --cov + loader siblings. - Deploy role: third stack DescribeStacks ARN + procurement-api smoke invoke ARN (re-run create-deploy-role.sh before merge). * harden(api): apply sh-security-review findings to procurement-api Fan-out (6 detectors) + review findings resolved: Correctness / DoS: - pagination: require EXACT key-set match (was subset) so a partial/foreign composite cursor can't reach DynamoDB as an inconsistent ExclusiveStartKey -> ValidationException -> 500; comments Query now pins the cursor's work_order_id to the path entity. - handler: map botocore ValidationException to 400 (defense in depth) so a crafted cursor can't drive the zero-threshold 5xx alarm. - web_ui_auth: compare tokens as bytes; a non-ASCII presented token now fails closed (401) instead of crashing hmac.compare_digest into a 500. Resolves the pre-existing xfail(strict) follow-up test; hardens the web UIs too. Docs page: - typeStr() now escapes the one spec-derived string that reached innerHTML. - spec inlined into the docs <script> block escapes "<" -> < (</script> breakout guard); /openapi.json still served byte-faithful. - Cache-Control: no-store + Referrer-Policy: no-referrer on docs responses so the ?token= URL stays out of caches/Referer. - spec-drift test asserts the committed spec carries no "</" / "<!--". IAM / IaC: - resource policy enumerates the 7 data GET resources instead of GET/* so a future GET route can't silently inherit SHOC cross-account reach. - kms:Decrypt grant gains a kms:ViaService=dynamodb condition. - stage throttling (50 rps / 100 burst) bounds the unauthenticated /docs blast radius below the 10k account default. - corrected the PATCH/POST comment (same-account callers aren't blocked by the resource policy; 501 handler + absent write grant are the gate). - documented the RETAIN log-group first-deploy rollback trap and the resource-policy-needs-redeploy gotcha in-stack. Mandatory GPT-4.1 cross-family review of the full policy surface: no BLOCK/FIX. 675 tests pass, ruff clean, cdk synth green.
2026-07-23 19:32:20 -04:00
_SPEC_PLACEHOLDER = "__OPENAPI_SPEC_JSON__"
_JS_PLACEHOLDER = "__REDOC_JS__"
feat(api): Redocly lint gate + SHOC-themed /docs (Redoc theming, topbar, collapsible samples) (#130) * feat(api): Add @redocly/cli as a dev dependency Signed-off-by: Adam Moussa <adam@seahavenind.com> * feat(api): Add Redocly configuration file with custom rules Signed-off-by: Adam Moussa <adam@seahavenind.com> * chore(api): Redocly lint config + bring openapi.json into compliance redocly.yaml from the Redocly guidelines builder, with three generated rules corrected: response-contains-property had the status codes as the required body fields (intent was the Error schema's top-level 'error'; 403 exempt since API Gateway emits AWS's {message} shape, 501 not 503); operation-4xx-problem-details-rfc7807 off (adopting RFC 7807 would be a runtime + SHOC-contract change, decided against); the two inert casing rules (parameter names, schema properties) removed because both name sets are contract-pinned (gateway resource paths, DynamoDB items). Spec changes, no runtime impact: operationIds renamed to method-prefixed kebab-case (get-work-orders, post-work-order-comment, ...); tags added to all 15 operations + root tags object (groups the Redoc sidebar); examples on all six parameters; license field; server description punctuation; two descriptions reworded to start capitalized. Real linter catches fixed: the two x-planned ops were missing their {workOrderId} path parameter and any 4xx response (403 added - true today, gateway rejects unsigned). .redocly.lint-ignore.yaml pins the six deliberate exceptions: webhook keys are the shipped SHOC contract event names (not renameable), and the x-planned ops answer only 501 (no 2xx to document). package.json: npm run lint:api. Verified: lint 0 errors, 675 pytest, headless-Chrome render of the tagged docs page. * feat(api): SHOC design-system theme for /docs (vendored fonts) Themes the Redoc page with the canonical SHOC token set: Montserrat 600 headings / DM Sans body / JetBrains Mono code, primary #1c75bc, navy #262262 sidebar text + right panel, #f9fafb background, 244px sidebar. sortRequiredPropsFirst on; 200 responses pre-expanded. Fonts ship as lambdas/api/fonts.css (latin woff2 subsets from @fontsource 5.3.0, embedded as data URIs, ~90KB) and inline via a new __FONTS_CSS__ placeholder with the same </style breakout guard -- the offline single-response invariant holds, nothing fetches Google Fonts (test-pinned). Bundling cp + bundle-consistency pin + spec-drift asset checks extended. Verified: headless-Chrome render (theme + fonts applied), ruff, 675 pytest, cdk synth + staged-asset check. * feat(api): SHOC gradient topbar on /docs 64px fixed header with the SHOC shell gradient token (#1b1f52 -> #1c4f8f -> #1c75bc), Sea Haven wordmark in Montserrat 600, page name right-aligned in DM Sans. Redoc's scrollYOffset: 64 keeps the sticky sidebar and anchor scrolling clear of the fixed bar. Verified via headless-Chrome render. * style(api): normalize /docs header and right-panel blues The right panel's #262262 is a purple-leaning navy that clashed with the cyan-leaning gradient, and the bar's brightest point sat directly over the dark panel. Right panel now uses #1b1f52 (the gradient's own dark endpoint) and the gradient runs bright-to-dark so its dark end lands flush on the panel -- no seam, one blue family. Verified via headless-Chrome render. * style(api): right-panel gradient on /docs via bundle-pinned override Redoc's theme only takes solid colors (it derives shades from rightPanel.backgroundColor), so the gradient (#1b3d79 -> #1b3068 -> #1b1f52, continuing the topbar blend) rides as a CSS override on the styled-components classes of the per-section right-panel divs (.sc-iGgWBj.sc-gsFSXq + the .sc-dExYaf stub). Those names are deterministic for the vendored 2.5.3 bundle (verified across loads) but change on any Redoc bump: re-derive via headless probe (find elements whose computed background equals the rightPanel color). If they stop matching, the panel falls back to the solid #1b1f52 theme color -- cosmetic only. Verified via headless-Chrome render. * feat(api): collapsible samples column on /docs Redoc CE has no built-in panel toggle, so the topbar gains a Hide/Show samples button that flips .samples-collapsed on <html>: the right-panel divs hide (same bundle-pinned styled-components classes as the gradient override) and each section's content half takes the full width. Choice persists in localStorage; aria-pressed tracks state. If the pinned classes stop matching after a Redoc bump the toggle goes inert -- cosmetic only. Both states verified via headless-Chrome render. * ci(api): spec-lint CI gate + npm Dependabot coverage New spec-lint job mirrors the local npm run lint:api so openapi.json cannot drift from redocly.yaml with green CI. Dependabot gains the npm ecosystem (package.json is new; nothing watched @redocly/cli). * feat(api): docs finishing touches - x-tagGroups, favicon, docs:preview x-tagGroups sections the Redoc sidebar (Read API / Meta / SHOC Feed); inline data-URI SVG favicon (SHOC blue) stops the browser's follow-up /favicon.ico request 403ing at the gateway; npm run docs:preview wraps the real-handler local render (scripts/preview_docs.py); README gains a docs-page architecture section covering the inline pattern, theme, pinned-selector caveat, and tooling. Lint 0 errors, 675 pytest, headless render verified. --------- Signed-off-by: Adam Moussa <adam@seahavenind.com>
2026-07-24 14:04:30 -04:00
_FONTS_PLACEHOLDER = "__FONTS_CSS__"
feat(api): procurement-api read stack + OpenAPI docs (SHOC reconciliation path) (#127) * feat(api): add procurement-api stack - read API + OpenAPI docs page Third CDK stack: API Gateway REST API (IAM SigV4) over both pipelines' tables, replacing SHOC's retired SyncController cross-account DynamoDB scan as the reconciliation/backfill path. - lambdas/api/: handler (healthcheck + docs-token gate + router dispatch), router (single route table), pagination (opaque cursor, hostile -> 400), Decimal-safe serialization, wo_repo/po_repo reads. No VendorReplies. - OpenAPI 3.1 spec as source of truth incl. top-level webhooks section documenting the outbound SHOC feed; phase-2 write endpoints x-planned (router answers 501). Self-contained /docs page, no CDN. - Auth: AWS_IAM on data routes + resource policy scoped to exactly arn:aws:iam::396287094661:role/shoc-backend-dev on GET/*; /docs and /openapi.json carve-out is token-gated in the Lambda via shared web_ui_auth (fail-closed, INFRA-74 posture). - KMS: explicit Decrypt/DescribeKey on the DynamoDB CMK from SSM (name-imported table drops the key association - INFRA-104 class). - Alarms: errors/throttles/duration(p99>=22.5s) + gateway 5xx, ALARM-only to site-alerts. No access logging in v1 (docs ?token= shim stays out of logs); cloud_watch_role=False. - Tests: handler auth-seam + routing + Decimal round-trip; moto cursor pagination incl. hostile cursors; spec<->router drift gate; bundle AST pins for the api command; pytest.ini --cov + loader siblings. - Deploy role: third stack DescribeStacks ARN + procurement-api smoke invoke ARN (re-run create-deploy-role.sh before merge). * harden(api): apply sh-security-review findings to procurement-api Fan-out (6 detectors) + review findings resolved: Correctness / DoS: - pagination: require EXACT key-set match (was subset) so a partial/foreign composite cursor can't reach DynamoDB as an inconsistent ExclusiveStartKey -> ValidationException -> 500; comments Query now pins the cursor's work_order_id to the path entity. - handler: map botocore ValidationException to 400 (defense in depth) so a crafted cursor can't drive the zero-threshold 5xx alarm. - web_ui_auth: compare tokens as bytes; a non-ASCII presented token now fails closed (401) instead of crashing hmac.compare_digest into a 500. Resolves the pre-existing xfail(strict) follow-up test; hardens the web UIs too. Docs page: - typeStr() now escapes the one spec-derived string that reached innerHTML. - spec inlined into the docs <script> block escapes "<" -> < (</script> breakout guard); /openapi.json still served byte-faithful. - Cache-Control: no-store + Referrer-Policy: no-referrer on docs responses so the ?token= URL stays out of caches/Referer. - spec-drift test asserts the committed spec carries no "</" / "<!--". IAM / IaC: - resource policy enumerates the 7 data GET resources instead of GET/* so a future GET route can't silently inherit SHOC cross-account reach. - kms:Decrypt grant gains a kms:ViaService=dynamodb condition. - stage throttling (50 rps / 100 burst) bounds the unauthenticated /docs blast radius below the 10k account default. - corrected the PATCH/POST comment (same-account callers aren't blocked by the resource policy; 501 handler + absent write grant are the gate). - documented the RETAIN log-group first-deploy rollback trap and the resource-policy-needs-redeploy gotcha in-stack. Mandatory GPT-4.1 cross-family review of the full policy surface: no BLOCK/FIX. 675 tests pass, ruff clean, cdk synth green.
2026-07-23 19:32:20 -04:00
_spec_cache = None
feat(api): stock Swagger UI for /docs (vendored offline) (#128) * feat(api): use stock Swagger UI for the /docs page Replaces the custom renderer with vendored stock Swagger UI (swagger-ui-dist 5.17.14, Apache-2.0), kept offline (no CDN) and inlined server-side into the single token-gated /docs response alongside the spec. BaseLayout (topbar hidden); try-it-out disabled since data routes need SigV4 (use Postman for live calls). Breakout guards on the inlined css/js/spec. Bundle-consistency + spec-drift + handler tests updated for the two vendored assets. cdk diff = Lambda code asset only (no IAM/API/policy change). * fix(api): render Swagger UI with the canonical StandaloneLayout recipe The BaseLayout-only init (apis preset, no standalone preset) rendered incorrectly. Switch to the canonical swagger-ui-dist recipe: vendor swagger-ui-standalone-preset.js and init with presets:[apis, SwaggerUIStandalonePreset] + layout:"StandaloneLayout" (topbar hidden, try-it-out disabled). Verified via headless Chrome against the live deployed page: all 9 endpoints + 4 webhooks + models render. Tests/bundling updated for the third vendored asset. * fix(api): declutter the Swagger UI docs page The page rendered (stock Swagger UI, StandaloneLayout) but looked cramped: a dense info.description wall of inline-code chips collided across Swagger UI's tight default line-height, and the Servers box showed a SEE-STACK-OUTPUT placeholder. - Trim info.description to a few concise lines (detail lives in README + the webhook contract doc). - Inject the live invoke URL into servers[0].url per request (from the API Gateway request context; committed literal is the fallback), so the Servers box shows the real endpoint and drops the server-variables section. - CSS: loosen description line-height + inline-code padding so chips never overlap; tidy the scheme container spacing. - Handler: cache the heavy CSS/JS/preset shell once; splice the (server- injected) spec per request. Verified via headless Chrome against the live deployed page.
2026-07-23 20:19:47 -04:00
_docs_shell_cache = None
# The server URL committed in openapi.json; swapped for the live invoke URL
# (derived from the request) when the spec is served, so the docs page shows a
# correct, current endpoint even if the RestApi is recreated.
_COMMITTED_SERVER_URL = "https://mvul1efda2.execute-api.us-east-1.amazonaws.com/prod"
feat(api): procurement-api read stack + OpenAPI docs (SHOC reconciliation path) (#127) * feat(api): add procurement-api stack - read API + OpenAPI docs page Third CDK stack: API Gateway REST API (IAM SigV4) over both pipelines' tables, replacing SHOC's retired SyncController cross-account DynamoDB scan as the reconciliation/backfill path. - lambdas/api/: handler (healthcheck + docs-token gate + router dispatch), router (single route table), pagination (opaque cursor, hostile -> 400), Decimal-safe serialization, wo_repo/po_repo reads. No VendorReplies. - OpenAPI 3.1 spec as source of truth incl. top-level webhooks section documenting the outbound SHOC feed; phase-2 write endpoints x-planned (router answers 501). Self-contained /docs page, no CDN. - Auth: AWS_IAM on data routes + resource policy scoped to exactly arn:aws:iam::396287094661:role/shoc-backend-dev on GET/*; /docs and /openapi.json carve-out is token-gated in the Lambda via shared web_ui_auth (fail-closed, INFRA-74 posture). - KMS: explicit Decrypt/DescribeKey on the DynamoDB CMK from SSM (name-imported table drops the key association - INFRA-104 class). - Alarms: errors/throttles/duration(p99>=22.5s) + gateway 5xx, ALARM-only to site-alerts. No access logging in v1 (docs ?token= shim stays out of logs); cloud_watch_role=False. - Tests: handler auth-seam + routing + Decimal round-trip; moto cursor pagination incl. hostile cursors; spec<->router drift gate; bundle AST pins for the api command; pytest.ini --cov + loader siblings. - Deploy role: third stack DescribeStacks ARN + procurement-api smoke invoke ARN (re-run create-deploy-role.sh before merge). * harden(api): apply sh-security-review findings to procurement-api Fan-out (6 detectors) + review findings resolved: Correctness / DoS: - pagination: require EXACT key-set match (was subset) so a partial/foreign composite cursor can't reach DynamoDB as an inconsistent ExclusiveStartKey -> ValidationException -> 500; comments Query now pins the cursor's work_order_id to the path entity. - handler: map botocore ValidationException to 400 (defense in depth) so a crafted cursor can't drive the zero-threshold 5xx alarm. - web_ui_auth: compare tokens as bytes; a non-ASCII presented token now fails closed (401) instead of crashing hmac.compare_digest into a 500. Resolves the pre-existing xfail(strict) follow-up test; hardens the web UIs too. Docs page: - typeStr() now escapes the one spec-derived string that reached innerHTML. - spec inlined into the docs <script> block escapes "<" -> < (</script> breakout guard); /openapi.json still served byte-faithful. - Cache-Control: no-store + Referrer-Policy: no-referrer on docs responses so the ?token= URL stays out of caches/Referer. - spec-drift test asserts the committed spec carries no "</" / "<!--". IAM / IaC: - resource policy enumerates the 7 data GET resources instead of GET/* so a future GET route can't silently inherit SHOC cross-account reach. - kms:Decrypt grant gains a kms:ViaService=dynamodb condition. - stage throttling (50 rps / 100 burst) bounds the unauthenticated /docs blast radius below the 10k account default. - corrected the PATCH/POST comment (same-account callers aren't blocked by the resource policy; 501 handler + absent write grant are the gate). - documented the RETAIN log-group first-deploy rollback trap and the resource-policy-needs-redeploy gotcha in-stack. Mandatory GPT-4.1 cross-family review of the full policy surface: no BLOCK/FIX. 675 tests pass, ruff clean, cdk synth green.
2026-07-23 19:32:20 -04:00
_REPO_FUNCS = {
"list_work_orders": wo_repo.list_work_orders,
"get_work_order": wo_repo.get_work_order,
"list_comments": wo_repo.list_comments,
"list_purchase_orders": po_repo.list_purchase_orders,
"get_purchase_order": po_repo.get_purchase_order,
"list_verified_sites": po_repo.list_verified_sites,
"get_verified_site": po_repo.get_verified_site,
}
_PATH_PARAM_BY_RESOURCE = {
"/work-orders/{workOrderId}": "workOrderId",
"/work-orders/{workOrderId}/comments": "workOrderId",
"/purchase-orders/{poNumber}": "poNumber",
"/verified-sites/{siteCode}": "siteCode",
}
# Headers on the docs responses: the token rides in the ?token= query shim,
# so keep the token-keyed URL and page out of shared/browser caches and out of
# any Referer sent to a followed link.
_DOCS_SECURITY_HEADERS = {
"Cache-Control": "no-store",
"Referrer-Policy": "no-referrer",
}
def _load_spec() -> str:
feat(api): stock Swagger UI for /docs (vendored offline) (#128) * feat(api): use stock Swagger UI for the /docs page Replaces the custom renderer with vendored stock Swagger UI (swagger-ui-dist 5.17.14, Apache-2.0), kept offline (no CDN) and inlined server-side into the single token-gated /docs response alongside the spec. BaseLayout (topbar hidden); try-it-out disabled since data routes need SigV4 (use Postman for live calls). Breakout guards on the inlined css/js/spec. Bundle-consistency + spec-drift + handler tests updated for the two vendored assets. cdk diff = Lambda code asset only (no IAM/API/policy change). * fix(api): render Swagger UI with the canonical StandaloneLayout recipe The BaseLayout-only init (apis preset, no standalone preset) rendered incorrectly. Switch to the canonical swagger-ui-dist recipe: vendor swagger-ui-standalone-preset.js and init with presets:[apis, SwaggerUIStandalonePreset] + layout:"StandaloneLayout" (topbar hidden, try-it-out disabled). Verified via headless Chrome against the live deployed page: all 9 endpoints + 4 webhooks + models render. Tests/bundling updated for the third vendored asset. * fix(api): declutter the Swagger UI docs page The page rendered (stock Swagger UI, StandaloneLayout) but looked cramped: a dense info.description wall of inline-code chips collided across Swagger UI's tight default line-height, and the Servers box showed a SEE-STACK-OUTPUT placeholder. - Trim info.description to a few concise lines (detail lives in README + the webhook contract doc). - Inject the live invoke URL into servers[0].url per request (from the API Gateway request context; committed literal is the fallback), so the Servers box shows the real endpoint and drops the server-variables section. - CSS: loosen description line-height + inline-code padding so chips never overlap; tidy the scheme container spacing. - Handler: cache the heavy CSS/JS/preset shell once; splice the (server- injected) spec per request. Verified via headless Chrome against the live deployed page.
2026-07-23 20:19:47 -04:00
"""The committed spec text (cached)."""
feat(api): procurement-api read stack + OpenAPI docs (SHOC reconciliation path) (#127) * feat(api): add procurement-api stack - read API + OpenAPI docs page Third CDK stack: API Gateway REST API (IAM SigV4) over both pipelines' tables, replacing SHOC's retired SyncController cross-account DynamoDB scan as the reconciliation/backfill path. - lambdas/api/: handler (healthcheck + docs-token gate + router dispatch), router (single route table), pagination (opaque cursor, hostile -> 400), Decimal-safe serialization, wo_repo/po_repo reads. No VendorReplies. - OpenAPI 3.1 spec as source of truth incl. top-level webhooks section documenting the outbound SHOC feed; phase-2 write endpoints x-planned (router answers 501). Self-contained /docs page, no CDN. - Auth: AWS_IAM on data routes + resource policy scoped to exactly arn:aws:iam::396287094661:role/shoc-backend-dev on GET/*; /docs and /openapi.json carve-out is token-gated in the Lambda via shared web_ui_auth (fail-closed, INFRA-74 posture). - KMS: explicit Decrypt/DescribeKey on the DynamoDB CMK from SSM (name-imported table drops the key association - INFRA-104 class). - Alarms: errors/throttles/duration(p99>=22.5s) + gateway 5xx, ALARM-only to site-alerts. No access logging in v1 (docs ?token= shim stays out of logs); cloud_watch_role=False. - Tests: handler auth-seam + routing + Decimal round-trip; moto cursor pagination incl. hostile cursors; spec<->router drift gate; bundle AST pins for the api command; pytest.ini --cov + loader siblings. - Deploy role: third stack DescribeStacks ARN + procurement-api smoke invoke ARN (re-run create-deploy-role.sh before merge). * harden(api): apply sh-security-review findings to procurement-api Fan-out (6 detectors) + review findings resolved: Correctness / DoS: - pagination: require EXACT key-set match (was subset) so a partial/foreign composite cursor can't reach DynamoDB as an inconsistent ExclusiveStartKey -> ValidationException -> 500; comments Query now pins the cursor's work_order_id to the path entity. - handler: map botocore ValidationException to 400 (defense in depth) so a crafted cursor can't drive the zero-threshold 5xx alarm. - web_ui_auth: compare tokens as bytes; a non-ASCII presented token now fails closed (401) instead of crashing hmac.compare_digest into a 500. Resolves the pre-existing xfail(strict) follow-up test; hardens the web UIs too. Docs page: - typeStr() now escapes the one spec-derived string that reached innerHTML. - spec inlined into the docs <script> block escapes "<" -> < (</script> breakout guard); /openapi.json still served byte-faithful. - Cache-Control: no-store + Referrer-Policy: no-referrer on docs responses so the ?token= URL stays out of caches/Referer. - spec-drift test asserts the committed spec carries no "</" / "<!--". IAM / IaC: - resource policy enumerates the 7 data GET resources instead of GET/* so a future GET route can't silently inherit SHOC cross-account reach. - kms:Decrypt grant gains a kms:ViaService=dynamodb condition. - stage throttling (50 rps / 100 burst) bounds the unauthenticated /docs blast radius below the 10k account default. - corrected the PATCH/POST comment (same-account callers aren't blocked by the resource policy; 501 handler + absent write grant are the gate). - documented the RETAIN log-group first-deploy rollback trap and the resource-policy-needs-redeploy gotcha in-stack. Mandatory GPT-4.1 cross-family review of the full policy surface: no BLOCK/FIX. 675 tests pass, ruff clean, cdk synth green.
2026-07-23 19:32:20 -04:00
global _spec_cache
if _spec_cache is None:
_spec_cache = _SPEC_PATH.read_text(encoding="utf-8")
return _spec_cache
feat(api): stock Swagger UI for /docs (vendored offline) (#128) * feat(api): use stock Swagger UI for the /docs page Replaces the custom renderer with vendored stock Swagger UI (swagger-ui-dist 5.17.14, Apache-2.0), kept offline (no CDN) and inlined server-side into the single token-gated /docs response alongside the spec. BaseLayout (topbar hidden); try-it-out disabled since data routes need SigV4 (use Postman for live calls). Breakout guards on the inlined css/js/spec. Bundle-consistency + spec-drift + handler tests updated for the two vendored assets. cdk diff = Lambda code asset only (no IAM/API/policy change). * fix(api): render Swagger UI with the canonical StandaloneLayout recipe The BaseLayout-only init (apis preset, no standalone preset) rendered incorrectly. Switch to the canonical swagger-ui-dist recipe: vendor swagger-ui-standalone-preset.js and init with presets:[apis, SwaggerUIStandalonePreset] + layout:"StandaloneLayout" (topbar hidden, try-it-out disabled). Verified via headless Chrome against the live deployed page: all 9 endpoints + 4 webhooks + models render. Tests/bundling updated for the third vendored asset. * fix(api): declutter the Swagger UI docs page The page rendered (stock Swagger UI, StandaloneLayout) but looked cramped: a dense info.description wall of inline-code chips collided across Swagger UI's tight default line-height, and the Servers box showed a SEE-STACK-OUTPUT placeholder. - Trim info.description to a few concise lines (detail lives in README + the webhook contract doc). - Inject the live invoke URL into servers[0].url per request (from the API Gateway request context; committed literal is the fallback), so the Servers box shows the real endpoint and drops the server-variables section. - CSS: loosen description line-height + inline-code padding so chips never overlap; tidy the scheme container spacing. - Handler: cache the heavy CSS/JS/preset shell once; splice the (server- injected) spec per request. Verified via headless Chrome against the live deployed page.
2026-07-23 20:19:47 -04:00
def _base_url(event: dict) -> str | None:
rc = event.get("requestContext") or {}
domain, stage = rc.get("domainName"), rc.get("stage")
feat(api): custom domain procurement-api.seahaven.com (stacked on PR-2) (#140) * feat(api): custom domain procurement-api.seahaven.com for the read API Stacked on feat/shoc-wo-webhook. Gives the SHOC-facing read API a stable, brandable endpoint instead of the opaque execute-api URL. - procurement_api_stack.py: REGIONAL API Gateway DomainName (TLS 1.2) + empty base-path mapping to the prod stage, so callers hit https://procurement-api.seahaven.com/work-orders (no /prod segment). The ACM cert ARN is read from SSM (/procurement-api/custom-domain/certificate-arn) via value_for_string_parameter, because the seahaven.com zone is in the mgmt account (cross-account DNS) and the cert is issued out of band. Outputs expose the regional alias target + hosted-zone id for the mgmt A-record. - scripts/setup_procurement_api_domain.sh: idempotent two-step runbook (cert: request + mgmt-zone validation + wait + SSM; alias: post-deploy A-record from stack outputs). Verifies both account identities. - handler._base_url: omit the /{stage} segment for a custom-domain request (the base-path mapping serves the stage at the root) so the docs never advertise a broken server URL; execute-api hosts keep /{stage}. - openapi.json: custom domain added as servers[0] (recommended), execute-api kept as the direct fallback + the per-request injection target. No IAM/auth/policy change (same API id + resource policy), so the SigV4 surface and the mandatory cross-family gates are unaffected. 751 pytest, ruff, cdk synth, redocly lint all green. * fix(api): use .endswith('.amazonaws.com') instead of substring check for execute-api detection The prior '.execute-api.' in domain substring check is fragile and triggers CodeQL incomplete-sanitization warnings. All API Gateway default domains end with .amazonaws.com, so a suffix check is more precise and also silences the false-positive alert. Refs: https://github.com/Sea-Haven-Industries/procurement-ingest/security/code-scanning/6
2026-07-24 18:41:10 -04:00
if not domain:
return None
# A custom domain (base-path mapping) serves the stage at the root, so the
# public URL has NO /{stage} segment; only the raw execute-api host carries
# it. Emitting /{stage} for a custom-domain request would advertise a
# broken server URL in the docs. All API Gateway default domains end with
# .amazonaws.com, so check the suffix rather than a substring.
if domain.endswith(".amazonaws.com"):
return f"https://{domain}/{stage}" if stage else None
return f"https://{domain}"
feat(api): stock Swagger UI for /docs (vendored offline) (#128) * feat(api): use stock Swagger UI for the /docs page Replaces the custom renderer with vendored stock Swagger UI (swagger-ui-dist 5.17.14, Apache-2.0), kept offline (no CDN) and inlined server-side into the single token-gated /docs response alongside the spec. BaseLayout (topbar hidden); try-it-out disabled since data routes need SigV4 (use Postman for live calls). Breakout guards on the inlined css/js/spec. Bundle-consistency + spec-drift + handler tests updated for the two vendored assets. cdk diff = Lambda code asset only (no IAM/API/policy change). * fix(api): render Swagger UI with the canonical StandaloneLayout recipe The BaseLayout-only init (apis preset, no standalone preset) rendered incorrectly. Switch to the canonical swagger-ui-dist recipe: vendor swagger-ui-standalone-preset.js and init with presets:[apis, SwaggerUIStandalonePreset] + layout:"StandaloneLayout" (topbar hidden, try-it-out disabled). Verified via headless Chrome against the live deployed page: all 9 endpoints + 4 webhooks + models render. Tests/bundling updated for the third vendored asset. * fix(api): declutter the Swagger UI docs page The page rendered (stock Swagger UI, StandaloneLayout) but looked cramped: a dense info.description wall of inline-code chips collided across Swagger UI's tight default line-height, and the Servers box showed a SEE-STACK-OUTPUT placeholder. - Trim info.description to a few concise lines (detail lives in README + the webhook contract doc). - Inject the live invoke URL into servers[0].url per request (from the API Gateway request context; committed literal is the fallback), so the Servers box shows the real endpoint and drops the server-variables section. - CSS: loosen description line-height + inline-code padding so chips never overlap; tidy the scheme container spacing. - Handler: cache the heavy CSS/JS/preset shell once; splice the (server- injected) spec per request. Verified via headless Chrome against the live deployed page.
2026-07-23 20:19:47 -04:00
def _spec_for_request(event: dict) -> str:
"""Committed spec with servers[0].url set to the live invoke URL when the
request context provides it (falls back to the committed literal)."""
raw = _load_spec()
base = _base_url(event)
return raw.replace(_COMMITTED_SERVER_URL, base) if base else raw
def _docs_shell() -> str:
"""The Redoc page with the vendored bundle inlined; the SPEC placeholder
is left intact so the per-request server-injected spec splices in cheaply
(the heavy ~1.1MB bundle is assembled once and cached).
feat(api): Redocly lint gate + SHOC-themed /docs (Redoc theming, topbar, collapsible samples) (#130) * feat(api): Add @redocly/cli as a dev dependency Signed-off-by: Adam Moussa <adam@seahavenind.com> * feat(api): Add Redocly configuration file with custom rules Signed-off-by: Adam Moussa <adam@seahavenind.com> * chore(api): Redocly lint config + bring openapi.json into compliance redocly.yaml from the Redocly guidelines builder, with three generated rules corrected: response-contains-property had the status codes as the required body fields (intent was the Error schema's top-level 'error'; 403 exempt since API Gateway emits AWS's {message} shape, 501 not 503); operation-4xx-problem-details-rfc7807 off (adopting RFC 7807 would be a runtime + SHOC-contract change, decided against); the two inert casing rules (parameter names, schema properties) removed because both name sets are contract-pinned (gateway resource paths, DynamoDB items). Spec changes, no runtime impact: operationIds renamed to method-prefixed kebab-case (get-work-orders, post-work-order-comment, ...); tags added to all 15 operations + root tags object (groups the Redoc sidebar); examples on all six parameters; license field; server description punctuation; two descriptions reworded to start capitalized. Real linter catches fixed: the two x-planned ops were missing their {workOrderId} path parameter and any 4xx response (403 added - true today, gateway rejects unsigned). .redocly.lint-ignore.yaml pins the six deliberate exceptions: webhook keys are the shipped SHOC contract event names (not renameable), and the x-planned ops answer only 501 (no 2xx to document). package.json: npm run lint:api. Verified: lint 0 errors, 675 pytest, headless-Chrome render of the tagged docs page. * feat(api): SHOC design-system theme for /docs (vendored fonts) Themes the Redoc page with the canonical SHOC token set: Montserrat 600 headings / DM Sans body / JetBrains Mono code, primary #1c75bc, navy #262262 sidebar text + right panel, #f9fafb background, 244px sidebar. sortRequiredPropsFirst on; 200 responses pre-expanded. Fonts ship as lambdas/api/fonts.css (latin woff2 subsets from @fontsource 5.3.0, embedded as data URIs, ~90KB) and inline via a new __FONTS_CSS__ placeholder with the same </style breakout guard -- the offline single-response invariant holds, nothing fetches Google Fonts (test-pinned). Bundling cp + bundle-consistency pin + spec-drift asset checks extended. Verified: headless-Chrome render (theme + fonts applied), ruff, 675 pytest, cdk synth + staged-asset check. * feat(api): SHOC gradient topbar on /docs 64px fixed header with the SHOC shell gradient token (#1b1f52 -> #1c4f8f -> #1c75bc), Sea Haven wordmark in Montserrat 600, page name right-aligned in DM Sans. Redoc's scrollYOffset: 64 keeps the sticky sidebar and anchor scrolling clear of the fixed bar. Verified via headless-Chrome render. * style(api): normalize /docs header and right-panel blues The right panel's #262262 is a purple-leaning navy that clashed with the cyan-leaning gradient, and the bar's brightest point sat directly over the dark panel. Right panel now uses #1b1f52 (the gradient's own dark endpoint) and the gradient runs bright-to-dark so its dark end lands flush on the panel -- no seam, one blue family. Verified via headless-Chrome render. * style(api): right-panel gradient on /docs via bundle-pinned override Redoc's theme only takes solid colors (it derives shades from rightPanel.backgroundColor), so the gradient (#1b3d79 -> #1b3068 -> #1b1f52, continuing the topbar blend) rides as a CSS override on the styled-components classes of the per-section right-panel divs (.sc-iGgWBj.sc-gsFSXq + the .sc-dExYaf stub). Those names are deterministic for the vendored 2.5.3 bundle (verified across loads) but change on any Redoc bump: re-derive via headless probe (find elements whose computed background equals the rightPanel color). If they stop matching, the panel falls back to the solid #1b1f52 theme color -- cosmetic only. Verified via headless-Chrome render. * feat(api): collapsible samples column on /docs Redoc CE has no built-in panel toggle, so the topbar gains a Hide/Show samples button that flips .samples-collapsed on <html>: the right-panel divs hide (same bundle-pinned styled-components classes as the gradient override) and each section's content half takes the full width. Choice persists in localStorage; aria-pressed tracks state. If the pinned classes stop matching after a Redoc bump the toggle goes inert -- cosmetic only. Both states verified via headless-Chrome render. * ci(api): spec-lint CI gate + npm Dependabot coverage New spec-lint job mirrors the local npm run lint:api so openapi.json cannot drift from redocly.yaml with green CI. Dependabot gains the npm ecosystem (package.json is new; nothing watched @redocly/cli). * feat(api): docs finishing touches - x-tagGroups, favicon, docs:preview x-tagGroups sections the Redoc sidebar (Read API / Meta / SHOC Feed); inline data-URI SVG favicon (SHOC blue) stops the browser's follow-up /favicon.ico request 403ing at the gateway; npm run docs:preview wraps the real-handler local render (scripts/preview_docs.py); README gains a docs-page architecture section covering the inline pattern, theme, pinned-selector caveat, and tooling. Lint 0 errors, 675 pytest, headless render verified. --------- Signed-off-by: Adam Moussa <adam@seahavenind.com>
2026-07-24 14:04:30 -04:00
Each blob is spliced into a <style>/<script> block, where the HTML parser
ends the element at the first literal "</style"/"</script" regardless of
quoting, so guard against a breakout a future asset update could add (the
pinned assets have none today): JS "</script" -> "<\\/script" (equivalent
inside a JS string/regex), CSS "</style" -> "<\\/style".
feat(api): stock Swagger UI for /docs (vendored offline) (#128) * feat(api): use stock Swagger UI for the /docs page Replaces the custom renderer with vendored stock Swagger UI (swagger-ui-dist 5.17.14, Apache-2.0), kept offline (no CDN) and inlined server-side into the single token-gated /docs response alongside the spec. BaseLayout (topbar hidden); try-it-out disabled since data routes need SigV4 (use Postman for live calls). Breakout guards on the inlined css/js/spec. Bundle-consistency + spec-drift + handler tests updated for the two vendored assets. cdk diff = Lambda code asset only (no IAM/API/policy change). * fix(api): render Swagger UI with the canonical StandaloneLayout recipe The BaseLayout-only init (apis preset, no standalone preset) rendered incorrectly. Switch to the canonical swagger-ui-dist recipe: vendor swagger-ui-standalone-preset.js and init with presets:[apis, SwaggerUIStandalonePreset] + layout:"StandaloneLayout" (topbar hidden, try-it-out disabled). Verified via headless Chrome against the live deployed page: all 9 endpoints + 4 webhooks + models render. Tests/bundling updated for the third vendored asset. * fix(api): declutter the Swagger UI docs page The page rendered (stock Swagger UI, StandaloneLayout) but looked cramped: a dense info.description wall of inline-code chips collided across Swagger UI's tight default line-height, and the Servers box showed a SEE-STACK-OUTPUT placeholder. - Trim info.description to a few concise lines (detail lives in README + the webhook contract doc). - Inject the live invoke URL into servers[0].url per request (from the API Gateway request context; committed literal is the fallback), so the Servers box shows the real endpoint and drops the server-variables section. - CSS: loosen description line-height + inline-code padding so chips never overlap; tidy the scheme container spacing. - Handler: cache the heavy CSS/JS/preset shell once; splice the (server- injected) spec per request. Verified via headless Chrome against the live deployed page.
2026-07-23 20:19:47 -04:00
"""
global _docs_shell_cache
if _docs_shell_cache is None:
js = _REDOC_JS_PATH.read_text(encoding="utf-8").replace(
feat(api): stock Swagger UI for /docs (vendored offline) (#128) * feat(api): use stock Swagger UI for the /docs page Replaces the custom renderer with vendored stock Swagger UI (swagger-ui-dist 5.17.14, Apache-2.0), kept offline (no CDN) and inlined server-side into the single token-gated /docs response alongside the spec. BaseLayout (topbar hidden); try-it-out disabled since data routes need SigV4 (use Postman for live calls). Breakout guards on the inlined css/js/spec. Bundle-consistency + spec-drift + handler tests updated for the two vendored assets. cdk diff = Lambda code asset only (no IAM/API/policy change). * fix(api): render Swagger UI with the canonical StandaloneLayout recipe The BaseLayout-only init (apis preset, no standalone preset) rendered incorrectly. Switch to the canonical swagger-ui-dist recipe: vendor swagger-ui-standalone-preset.js and init with presets:[apis, SwaggerUIStandalonePreset] + layout:"StandaloneLayout" (topbar hidden, try-it-out disabled). Verified via headless Chrome against the live deployed page: all 9 endpoints + 4 webhooks + models render. Tests/bundling updated for the third vendored asset. * fix(api): declutter the Swagger UI docs page The page rendered (stock Swagger UI, StandaloneLayout) but looked cramped: a dense info.description wall of inline-code chips collided across Swagger UI's tight default line-height, and the Servers box showed a SEE-STACK-OUTPUT placeholder. - Trim info.description to a few concise lines (detail lives in README + the webhook contract doc). - Inject the live invoke URL into servers[0].url per request (from the API Gateway request context; committed literal is the fallback), so the Servers box shows the real endpoint and drops the server-variables section. - CSS: loosen description line-height + inline-code padding so chips never overlap; tidy the scheme container spacing. - Handler: cache the heavy CSS/JS/preset shell once; splice the (server- injected) spec per request. Verified via headless Chrome against the live deployed page.
2026-07-23 20:19:47 -04:00
"</script", "<\\/script"
)
feat(api): Redocly lint gate + SHOC-themed /docs (Redoc theming, topbar, collapsible samples) (#130) * feat(api): Add @redocly/cli as a dev dependency Signed-off-by: Adam Moussa <adam@seahavenind.com> * feat(api): Add Redocly configuration file with custom rules Signed-off-by: Adam Moussa <adam@seahavenind.com> * chore(api): Redocly lint config + bring openapi.json into compliance redocly.yaml from the Redocly guidelines builder, with three generated rules corrected: response-contains-property had the status codes as the required body fields (intent was the Error schema's top-level 'error'; 403 exempt since API Gateway emits AWS's {message} shape, 501 not 503); operation-4xx-problem-details-rfc7807 off (adopting RFC 7807 would be a runtime + SHOC-contract change, decided against); the two inert casing rules (parameter names, schema properties) removed because both name sets are contract-pinned (gateway resource paths, DynamoDB items). Spec changes, no runtime impact: operationIds renamed to method-prefixed kebab-case (get-work-orders, post-work-order-comment, ...); tags added to all 15 operations + root tags object (groups the Redoc sidebar); examples on all six parameters; license field; server description punctuation; two descriptions reworded to start capitalized. Real linter catches fixed: the two x-planned ops were missing their {workOrderId} path parameter and any 4xx response (403 added - true today, gateway rejects unsigned). .redocly.lint-ignore.yaml pins the six deliberate exceptions: webhook keys are the shipped SHOC contract event names (not renameable), and the x-planned ops answer only 501 (no 2xx to document). package.json: npm run lint:api. Verified: lint 0 errors, 675 pytest, headless-Chrome render of the tagged docs page. * feat(api): SHOC design-system theme for /docs (vendored fonts) Themes the Redoc page with the canonical SHOC token set: Montserrat 600 headings / DM Sans body / JetBrains Mono code, primary #1c75bc, navy #262262 sidebar text + right panel, #f9fafb background, 244px sidebar. sortRequiredPropsFirst on; 200 responses pre-expanded. Fonts ship as lambdas/api/fonts.css (latin woff2 subsets from @fontsource 5.3.0, embedded as data URIs, ~90KB) and inline via a new __FONTS_CSS__ placeholder with the same </style breakout guard -- the offline single-response invariant holds, nothing fetches Google Fonts (test-pinned). Bundling cp + bundle-consistency pin + spec-drift asset checks extended. Verified: headless-Chrome render (theme + fonts applied), ruff, 675 pytest, cdk synth + staged-asset check. * feat(api): SHOC gradient topbar on /docs 64px fixed header with the SHOC shell gradient token (#1b1f52 -> #1c4f8f -> #1c75bc), Sea Haven wordmark in Montserrat 600, page name right-aligned in DM Sans. Redoc's scrollYOffset: 64 keeps the sticky sidebar and anchor scrolling clear of the fixed bar. Verified via headless-Chrome render. * style(api): normalize /docs header and right-panel blues The right panel's #262262 is a purple-leaning navy that clashed with the cyan-leaning gradient, and the bar's brightest point sat directly over the dark panel. Right panel now uses #1b1f52 (the gradient's own dark endpoint) and the gradient runs bright-to-dark so its dark end lands flush on the panel -- no seam, one blue family. Verified via headless-Chrome render. * style(api): right-panel gradient on /docs via bundle-pinned override Redoc's theme only takes solid colors (it derives shades from rightPanel.backgroundColor), so the gradient (#1b3d79 -> #1b3068 -> #1b1f52, continuing the topbar blend) rides as a CSS override on the styled-components classes of the per-section right-panel divs (.sc-iGgWBj.sc-gsFSXq + the .sc-dExYaf stub). Those names are deterministic for the vendored 2.5.3 bundle (verified across loads) but change on any Redoc bump: re-derive via headless probe (find elements whose computed background equals the rightPanel color). If they stop matching, the panel falls back to the solid #1b1f52 theme color -- cosmetic only. Verified via headless-Chrome render. * feat(api): collapsible samples column on /docs Redoc CE has no built-in panel toggle, so the topbar gains a Hide/Show samples button that flips .samples-collapsed on <html>: the right-panel divs hide (same bundle-pinned styled-components classes as the gradient override) and each section's content half takes the full width. Choice persists in localStorage; aria-pressed tracks state. If the pinned classes stop matching after a Redoc bump the toggle goes inert -- cosmetic only. Both states verified via headless-Chrome render. * ci(api): spec-lint CI gate + npm Dependabot coverage New spec-lint job mirrors the local npm run lint:api so openapi.json cannot drift from redocly.yaml with green CI. Dependabot gains the npm ecosystem (package.json is new; nothing watched @redocly/cli). * feat(api): docs finishing touches - x-tagGroups, favicon, docs:preview x-tagGroups sections the Redoc sidebar (Read API / Meta / SHOC Feed); inline data-URI SVG favicon (SHOC blue) stops the browser's follow-up /favicon.ico request 403ing at the gateway; npm run docs:preview wraps the real-handler local render (scripts/preview_docs.py); README gains a docs-page architecture section covering the inline pattern, theme, pinned-selector caveat, and tooling. Lint 0 errors, 675 pytest, headless render verified. --------- Signed-off-by: Adam Moussa <adam@seahavenind.com>
2026-07-24 14:04:30 -04:00
fonts = _FONTS_CSS_PATH.read_text(encoding="utf-8").replace(
"</style", "<\\/style"
)
_docs_shell_cache = (
_DOCS_PATH.read_text(encoding="utf-8")
.replace(_JS_PLACEHOLDER, js)
.replace(_FONTS_PLACEHOLDER, fonts)
feat(api): stock Swagger UI for /docs (vendored offline) (#128) * feat(api): use stock Swagger UI for the /docs page Replaces the custom renderer with vendored stock Swagger UI (swagger-ui-dist 5.17.14, Apache-2.0), kept offline (no CDN) and inlined server-side into the single token-gated /docs response alongside the spec. BaseLayout (topbar hidden); try-it-out disabled since data routes need SigV4 (use Postman for live calls). Breakout guards on the inlined css/js/spec. Bundle-consistency + spec-drift + handler tests updated for the two vendored assets. cdk diff = Lambda code asset only (no IAM/API/policy change). * fix(api): render Swagger UI with the canonical StandaloneLayout recipe The BaseLayout-only init (apis preset, no standalone preset) rendered incorrectly. Switch to the canonical swagger-ui-dist recipe: vendor swagger-ui-standalone-preset.js and init with presets:[apis, SwaggerUIStandalonePreset] + layout:"StandaloneLayout" (topbar hidden, try-it-out disabled). Verified via headless Chrome against the live deployed page: all 9 endpoints + 4 webhooks + models render. Tests/bundling updated for the third vendored asset. * fix(api): declutter the Swagger UI docs page The page rendered (stock Swagger UI, StandaloneLayout) but looked cramped: a dense info.description wall of inline-code chips collided across Swagger UI's tight default line-height, and the Servers box showed a SEE-STACK-OUTPUT placeholder. - Trim info.description to a few concise lines (detail lives in README + the webhook contract doc). - Inject the live invoke URL into servers[0].url per request (from the API Gateway request context; committed literal is the fallback), so the Servers box shows the real endpoint and drops the server-variables section. - CSS: loosen description line-height + inline-code padding so chips never overlap; tidy the scheme container spacing. - Handler: cache the heavy CSS/JS/preset shell once; splice the (server- injected) spec per request. Verified via headless Chrome against the live deployed page.
2026-07-23 20:19:47 -04:00
)
return _docs_shell_cache
def _render_docs_html(event: dict) -> str:
# "<" -> < so a spec string can never close the <script> block (same
# value to JSON.parse); the spec object is inlined into Redoc.init.
feat(api): stock Swagger UI for /docs (vendored offline) (#128) * feat(api): use stock Swagger UI for the /docs page Replaces the custom renderer with vendored stock Swagger UI (swagger-ui-dist 5.17.14, Apache-2.0), kept offline (no CDN) and inlined server-side into the single token-gated /docs response alongside the spec. BaseLayout (topbar hidden); try-it-out disabled since data routes need SigV4 (use Postman for live calls). Breakout guards on the inlined css/js/spec. Bundle-consistency + spec-drift + handler tests updated for the two vendored assets. cdk diff = Lambda code asset only (no IAM/API/policy change). * fix(api): render Swagger UI with the canonical StandaloneLayout recipe The BaseLayout-only init (apis preset, no standalone preset) rendered incorrectly. Switch to the canonical swagger-ui-dist recipe: vendor swagger-ui-standalone-preset.js and init with presets:[apis, SwaggerUIStandalonePreset] + layout:"StandaloneLayout" (topbar hidden, try-it-out disabled). Verified via headless Chrome against the live deployed page: all 9 endpoints + 4 webhooks + models render. Tests/bundling updated for the third vendored asset. * fix(api): declutter the Swagger UI docs page The page rendered (stock Swagger UI, StandaloneLayout) but looked cramped: a dense info.description wall of inline-code chips collided across Swagger UI's tight default line-height, and the Servers box showed a SEE-STACK-OUTPUT placeholder. - Trim info.description to a few concise lines (detail lives in README + the webhook contract doc). - Inject the live invoke URL into servers[0].url per request (from the API Gateway request context; committed literal is the fallback), so the Servers box shows the real endpoint and drops the server-variables section. - CSS: loosen description line-height + inline-code padding so chips never overlap; tidy the scheme container spacing. - Handler: cache the heavy CSS/JS/preset shell once; splice the (server- injected) spec per request. Verified via headless Chrome against the live deployed page.
2026-07-23 20:19:47 -04:00
spec = _spec_for_request(event).replace("<", "\\u003c")
return _docs_shell().replace(_SPEC_PLACEHOLDER, spec)
feat(api): procurement-api read stack + OpenAPI docs (SHOC reconciliation path) (#127) * feat(api): add procurement-api stack - read API + OpenAPI docs page Third CDK stack: API Gateway REST API (IAM SigV4) over both pipelines' tables, replacing SHOC's retired SyncController cross-account DynamoDB scan as the reconciliation/backfill path. - lambdas/api/: handler (healthcheck + docs-token gate + router dispatch), router (single route table), pagination (opaque cursor, hostile -> 400), Decimal-safe serialization, wo_repo/po_repo reads. No VendorReplies. - OpenAPI 3.1 spec as source of truth incl. top-level webhooks section documenting the outbound SHOC feed; phase-2 write endpoints x-planned (router answers 501). Self-contained /docs page, no CDN. - Auth: AWS_IAM on data routes + resource policy scoped to exactly arn:aws:iam::396287094661:role/shoc-backend-dev on GET/*; /docs and /openapi.json carve-out is token-gated in the Lambda via shared web_ui_auth (fail-closed, INFRA-74 posture). - KMS: explicit Decrypt/DescribeKey on the DynamoDB CMK from SSM (name-imported table drops the key association - INFRA-104 class). - Alarms: errors/throttles/duration(p99>=22.5s) + gateway 5xx, ALARM-only to site-alerts. No access logging in v1 (docs ?token= shim stays out of logs); cloud_watch_role=False. - Tests: handler auth-seam + routing + Decimal round-trip; moto cursor pagination incl. hostile cursors; spec<->router drift gate; bundle AST pins for the api command; pytest.ini --cov + loader siblings. - Deploy role: third stack DescribeStacks ARN + procurement-api smoke invoke ARN (re-run create-deploy-role.sh before merge). * harden(api): apply sh-security-review findings to procurement-api Fan-out (6 detectors) + review findings resolved: Correctness / DoS: - pagination: require EXACT key-set match (was subset) so a partial/foreign composite cursor can't reach DynamoDB as an inconsistent ExclusiveStartKey -> ValidationException -> 500; comments Query now pins the cursor's work_order_id to the path entity. - handler: map botocore ValidationException to 400 (defense in depth) so a crafted cursor can't drive the zero-threshold 5xx alarm. - web_ui_auth: compare tokens as bytes; a non-ASCII presented token now fails closed (401) instead of crashing hmac.compare_digest into a 500. Resolves the pre-existing xfail(strict) follow-up test; hardens the web UIs too. Docs page: - typeStr() now escapes the one spec-derived string that reached innerHTML. - spec inlined into the docs <script> block escapes "<" -> < (</script> breakout guard); /openapi.json still served byte-faithful. - Cache-Control: no-store + Referrer-Policy: no-referrer on docs responses so the ?token= URL stays out of caches/Referer. - spec-drift test asserts the committed spec carries no "</" / "<!--". IAM / IaC: - resource policy enumerates the 7 data GET resources instead of GET/* so a future GET route can't silently inherit SHOC cross-account reach. - kms:Decrypt grant gains a kms:ViaService=dynamodb condition. - stage throttling (50 rps / 100 burst) bounds the unauthenticated /docs blast radius below the 10k account default. - corrected the PATCH/POST comment (same-account callers aren't blocked by the resource policy; 501 handler + absent write grant are the gate). - documented the RETAIN log-group first-deploy rollback trap and the resource-policy-needs-redeploy gotcha in-stack. Mandatory GPT-4.1 cross-family review of the full policy surface: no BLOCK/FIX. 675 tests pass, ruff clean, cdk synth green.
2026-07-23 19:32:20 -04:00
def _with_token_shim(event: dict) -> dict:
"""Copy a ?token= query parameter into an x-auth-token header.
Browsers can't set headers on plain navigation, so /docs accepts the
shared token as a query parameter too. The constant-time compare still
happens inside web_ui_auth -- this only synthesizes the header on a
shallow copy. Acceptable only while API Gateway access logging stays off
(nothing at the gateway records the query string); rotate the token if
access logging is ever enabled.
"""
qs = event.get("queryStringParameters") or {}
token = qs.get("token")
if not token:
return event
shimmed = dict(event)
headers = dict(event.get("headers") or {})
headers["x-auth-token"] = token
shimmed["headers"] = headers
return shimmed
def _docs_response(resource: str, event: dict) -> dict:
# SECURITY INVARIANT: these routes serve ONLY the committed spec and the
# static docs page -- never table data. The gateway resource policy allows
# Principal "*" on exactly these two GETs on the strength of that; serving
# anything dynamic here requires a resource-policy + security re-review.
if not is_authenticated(_with_token_shim(event)):
return error_response(401, "unauthorized")
if resource == "/openapi.json":
return {
"statusCode": 200,
"headers": {"Content-Type": "application/json", **_DOCS_SECURITY_HEADERS},
feat(api): stock Swagger UI for /docs (vendored offline) (#128) * feat(api): use stock Swagger UI for the /docs page Replaces the custom renderer with vendored stock Swagger UI (swagger-ui-dist 5.17.14, Apache-2.0), kept offline (no CDN) and inlined server-side into the single token-gated /docs response alongside the spec. BaseLayout (topbar hidden); try-it-out disabled since data routes need SigV4 (use Postman for live calls). Breakout guards on the inlined css/js/spec. Bundle-consistency + spec-drift + handler tests updated for the two vendored assets. cdk diff = Lambda code asset only (no IAM/API/policy change). * fix(api): render Swagger UI with the canonical StandaloneLayout recipe The BaseLayout-only init (apis preset, no standalone preset) rendered incorrectly. Switch to the canonical swagger-ui-dist recipe: vendor swagger-ui-standalone-preset.js and init with presets:[apis, SwaggerUIStandalonePreset] + layout:"StandaloneLayout" (topbar hidden, try-it-out disabled). Verified via headless Chrome against the live deployed page: all 9 endpoints + 4 webhooks + models render. Tests/bundling updated for the third vendored asset. * fix(api): declutter the Swagger UI docs page The page rendered (stock Swagger UI, StandaloneLayout) but looked cramped: a dense info.description wall of inline-code chips collided across Swagger UI's tight default line-height, and the Servers box showed a SEE-STACK-OUTPUT placeholder. - Trim info.description to a few concise lines (detail lives in README + the webhook contract doc). - Inject the live invoke URL into servers[0].url per request (from the API Gateway request context; committed literal is the fallback), so the Servers box shows the real endpoint and drops the server-variables section. - CSS: loosen description line-height + inline-code padding so chips never overlap; tidy the scheme container spacing. - Handler: cache the heavy CSS/JS/preset shell once; splice the (server- injected) spec per request. Verified via headless Chrome against the live deployed page.
2026-07-23 20:19:47 -04:00
"body": _spec_for_request(event),
feat(api): procurement-api read stack + OpenAPI docs (SHOC reconciliation path) (#127) * feat(api): add procurement-api stack - read API + OpenAPI docs page Third CDK stack: API Gateway REST API (IAM SigV4) over both pipelines' tables, replacing SHOC's retired SyncController cross-account DynamoDB scan as the reconciliation/backfill path. - lambdas/api/: handler (healthcheck + docs-token gate + router dispatch), router (single route table), pagination (opaque cursor, hostile -> 400), Decimal-safe serialization, wo_repo/po_repo reads. No VendorReplies. - OpenAPI 3.1 spec as source of truth incl. top-level webhooks section documenting the outbound SHOC feed; phase-2 write endpoints x-planned (router answers 501). Self-contained /docs page, no CDN. - Auth: AWS_IAM on data routes + resource policy scoped to exactly arn:aws:iam::396287094661:role/shoc-backend-dev on GET/*; /docs and /openapi.json carve-out is token-gated in the Lambda via shared web_ui_auth (fail-closed, INFRA-74 posture). - KMS: explicit Decrypt/DescribeKey on the DynamoDB CMK from SSM (name-imported table drops the key association - INFRA-104 class). - Alarms: errors/throttles/duration(p99>=22.5s) + gateway 5xx, ALARM-only to site-alerts. No access logging in v1 (docs ?token= shim stays out of logs); cloud_watch_role=False. - Tests: handler auth-seam + routing + Decimal round-trip; moto cursor pagination incl. hostile cursors; spec<->router drift gate; bundle AST pins for the api command; pytest.ini --cov + loader siblings. - Deploy role: third stack DescribeStacks ARN + procurement-api smoke invoke ARN (re-run create-deploy-role.sh before merge). * harden(api): apply sh-security-review findings to procurement-api Fan-out (6 detectors) + review findings resolved: Correctness / DoS: - pagination: require EXACT key-set match (was subset) so a partial/foreign composite cursor can't reach DynamoDB as an inconsistent ExclusiveStartKey -> ValidationException -> 500; comments Query now pins the cursor's work_order_id to the path entity. - handler: map botocore ValidationException to 400 (defense in depth) so a crafted cursor can't drive the zero-threshold 5xx alarm. - web_ui_auth: compare tokens as bytes; a non-ASCII presented token now fails closed (401) instead of crashing hmac.compare_digest into a 500. Resolves the pre-existing xfail(strict) follow-up test; hardens the web UIs too. Docs page: - typeStr() now escapes the one spec-derived string that reached innerHTML. - spec inlined into the docs <script> block escapes "<" -> < (</script> breakout guard); /openapi.json still served byte-faithful. - Cache-Control: no-store + Referrer-Policy: no-referrer on docs responses so the ?token= URL stays out of caches/Referer. - spec-drift test asserts the committed spec carries no "</" / "<!--". IAM / IaC: - resource policy enumerates the 7 data GET resources instead of GET/* so a future GET route can't silently inherit SHOC cross-account reach. - kms:Decrypt grant gains a kms:ViaService=dynamodb condition. - stage throttling (50 rps / 100 burst) bounds the unauthenticated /docs blast radius below the 10k account default. - corrected the PATCH/POST comment (same-account callers aren't blocked by the resource policy; 501 handler + absent write grant are the gate). - documented the RETAIN log-group first-deploy rollback trap and the resource-policy-needs-redeploy gotcha in-stack. Mandatory GPT-4.1 cross-family review of the full policy surface: no BLOCK/FIX. 675 tests pass, ruff clean, cdk synth green.
2026-07-23 19:32:20 -04:00
}
return {
"statusCode": 200,
"headers": {
"Content-Type": "text/html; charset=utf-8",
**_DOCS_SECURITY_HEADERS,
},
feat(api): stock Swagger UI for /docs (vendored offline) (#128) * feat(api): use stock Swagger UI for the /docs page Replaces the custom renderer with vendored stock Swagger UI (swagger-ui-dist 5.17.14, Apache-2.0), kept offline (no CDN) and inlined server-side into the single token-gated /docs response alongside the spec. BaseLayout (topbar hidden); try-it-out disabled since data routes need SigV4 (use Postman for live calls). Breakout guards on the inlined css/js/spec. Bundle-consistency + spec-drift + handler tests updated for the two vendored assets. cdk diff = Lambda code asset only (no IAM/API/policy change). * fix(api): render Swagger UI with the canonical StandaloneLayout recipe The BaseLayout-only init (apis preset, no standalone preset) rendered incorrectly. Switch to the canonical swagger-ui-dist recipe: vendor swagger-ui-standalone-preset.js and init with presets:[apis, SwaggerUIStandalonePreset] + layout:"StandaloneLayout" (topbar hidden, try-it-out disabled). Verified via headless Chrome against the live deployed page: all 9 endpoints + 4 webhooks + models render. Tests/bundling updated for the third vendored asset. * fix(api): declutter the Swagger UI docs page The page rendered (stock Swagger UI, StandaloneLayout) but looked cramped: a dense info.description wall of inline-code chips collided across Swagger UI's tight default line-height, and the Servers box showed a SEE-STACK-OUTPUT placeholder. - Trim info.description to a few concise lines (detail lives in README + the webhook contract doc). - Inject the live invoke URL into servers[0].url per request (from the API Gateway request context; committed literal is the fallback), so the Servers box shows the real endpoint and drops the server-variables section. - CSS: loosen description line-height + inline-code padding so chips never overlap; tidy the scheme container spacing. - Handler: cache the heavy CSS/JS/preset shell once; splice the (server- injected) spec per request. Verified via headless Chrome against the live deployed page.
2026-07-23 20:19:47 -04:00
"body": _render_docs_html(event),
feat(api): procurement-api read stack + OpenAPI docs (SHOC reconciliation path) (#127) * feat(api): add procurement-api stack - read API + OpenAPI docs page Third CDK stack: API Gateway REST API (IAM SigV4) over both pipelines' tables, replacing SHOC's retired SyncController cross-account DynamoDB scan as the reconciliation/backfill path. - lambdas/api/: handler (healthcheck + docs-token gate + router dispatch), router (single route table), pagination (opaque cursor, hostile -> 400), Decimal-safe serialization, wo_repo/po_repo reads. No VendorReplies. - OpenAPI 3.1 spec as source of truth incl. top-level webhooks section documenting the outbound SHOC feed; phase-2 write endpoints x-planned (router answers 501). Self-contained /docs page, no CDN. - Auth: AWS_IAM on data routes + resource policy scoped to exactly arn:aws:iam::396287094661:role/shoc-backend-dev on GET/*; /docs and /openapi.json carve-out is token-gated in the Lambda via shared web_ui_auth (fail-closed, INFRA-74 posture). - KMS: explicit Decrypt/DescribeKey on the DynamoDB CMK from SSM (name-imported table drops the key association - INFRA-104 class). - Alarms: errors/throttles/duration(p99>=22.5s) + gateway 5xx, ALARM-only to site-alerts. No access logging in v1 (docs ?token= shim stays out of logs); cloud_watch_role=False. - Tests: handler auth-seam + routing + Decimal round-trip; moto cursor pagination incl. hostile cursors; spec<->router drift gate; bundle AST pins for the api command; pytest.ini --cov + loader siblings. - Deploy role: third stack DescribeStacks ARN + procurement-api smoke invoke ARN (re-run create-deploy-role.sh before merge). * harden(api): apply sh-security-review findings to procurement-api Fan-out (6 detectors) + review findings resolved: Correctness / DoS: - pagination: require EXACT key-set match (was subset) so a partial/foreign composite cursor can't reach DynamoDB as an inconsistent ExclusiveStartKey -> ValidationException -> 500; comments Query now pins the cursor's work_order_id to the path entity. - handler: map botocore ValidationException to 400 (defense in depth) so a crafted cursor can't drive the zero-threshold 5xx alarm. - web_ui_auth: compare tokens as bytes; a non-ASCII presented token now fails closed (401) instead of crashing hmac.compare_digest into a 500. Resolves the pre-existing xfail(strict) follow-up test; hardens the web UIs too. Docs page: - typeStr() now escapes the one spec-derived string that reached innerHTML. - spec inlined into the docs <script> block escapes "<" -> < (</script> breakout guard); /openapi.json still served byte-faithful. - Cache-Control: no-store + Referrer-Policy: no-referrer on docs responses so the ?token= URL stays out of caches/Referer. - spec-drift test asserts the committed spec carries no "</" / "<!--". IAM / IaC: - resource policy enumerates the 7 data GET resources instead of GET/* so a future GET route can't silently inherit SHOC cross-account reach. - kms:Decrypt grant gains a kms:ViaService=dynamodb condition. - stage throttling (50 rps / 100 burst) bounds the unauthenticated /docs blast radius below the 10k account default. - corrected the PATCH/POST comment (same-account callers aren't blocked by the resource policy; 501 handler + absent write grant are the gate). - documented the RETAIN log-group first-deploy rollback trap and the resource-policy-needs-redeploy gotcha in-stack. Mandatory GPT-4.1 cross-family review of the full policy surface: no BLOCK/FIX. 675 tests pass, ruff clean, cdk synth green.
2026-07-23 19:32:20 -04:00
}
def _data_response(route_key: tuple, event: dict) -> dict:
method, resource = route_key
func = _REPO_FUNCS[DATA_ROUTES[route_key]]
qs = event.get("queryStringParameters") or {}
path_params = event.get("pathParameters") or {}
if DATA_ROUTES[route_key].startswith("list_"):
limit = clamp_limit(qs.get("limit"))
cursor = qs.get("cursor")
if resource in _PATH_PARAM_BY_RESOURCE:
entity_id = path_params.get(_PATH_PARAM_BY_RESOURCE[resource], "")
items, next_cursor = func(entity_id, limit, cursor)
else:
items, next_cursor = func(limit, cursor)
return json_response(200, {"items": items, "next_cursor": next_cursor})
entity_id = path_params.get(_PATH_PARAM_BY_RESOURCE[resource], "")
item = func(entity_id)
if item is None:
return error_response(404, "not found")
return json_response(200, item)
def _dispatch(route_key: tuple, event: dict) -> dict:
if route_key in PLANNED_ROUTES:
return error_response(501, "planned endpoint - not implemented (phase 2)")
if route_key in DOCS_ROUTES:
return _docs_response(route_key[1], event)
if route_key in DATA_ROUTES:
return _data_response(route_key, event)
return error_response(404, "not found")
def handler(event, context):
# Deploy-guard healthcheck: a direct-invoke {"healthcheck": true} probe
# returns before any routing/auth so the post-deploy smoke gate can verify
# the bundle imports and the runtime boots.
if isinstance(event, dict) and event.get("healthcheck") is True:
return {"healthcheck": "ok"}
method = (event.get("httpMethod") or "").upper()
resource = event.get("resource") or ""
try:
return _dispatch((method, resource), event)
except BadCursor as exc:
return error_response(400, str(exc))
except ClientError as exc:
# A client-supplied cursor that survives validation but is still
# inconsistent at the data layer makes DynamoDB raise
# ValidationException; map it to 400, not 500, so a crafted cursor
# can't drive the 5xx alarm. Any other AWS error is a real 500.
if exc.response.get("Error", {}).get("Code") == "ValidationException":
return error_response(400, "cursor is not valid")
logger.exception("AWS error serving %s %s", method, resource)
return error_response(500, "internal error")
except Exception:
# A raised exception would surface as an opaque 502 from the proxy
# integration; return a clean 500 instead. The API Gateway 5XX alarm
# pages on these; the exception (never the request token) is logged.
logger.exception("Unhandled error serving %s %s", method, resource)
return error_response(500, "internal error")