diff --git a/.beads/.gitignore b/.beads/.gitignore new file mode 100644 index 0000000..d9b3882 --- /dev/null +++ b/.beads/.gitignore @@ -0,0 +1,85 @@ +# Dolt database (managed by Dolt, not git) +dolt/ +embeddeddolt/ +proxieddb/ + +# Runtime files +bd.sock +bd.sock.startlock +sync-state.json +last-touched +.exclusive-lock + +# Daemon runtime (lock, log, pid) +daemon.* + +# Push state (runtime, per-machine) +push-state.json + +# Prime safety-net pointer (generated by the beads-superpowers plugin, disposable) +PRIME.md + +# Lock files (various runtime locks) +*.lock + +# Credential key (encryption key for federation peer auth — never commit) +.beads-credential-key + +# Local version tracking (prevents upgrade notification spam after git ops) +.local_version + +proxied_server_client_info.json + +# Worktree redirect file (contains relative path to main repo's .beads/) +# Must not be committed as paths would be wrong in other clones +redirect + +# Sync state (local-only, per-machine) +# These files are machine-specific and should not be shared across clones +.sync.lock + +# Workspace operation gate (internal/workspacegate): physical-root gate +# files live beside the guarded root inside .beads (e.g. dolt.gate.lock) +*.gate.lock* +export-state/ +export-state.json +last_pull + +# Ephemeral store (SQLite - wisps/molecules, intentionally not versioned) +ephemeral.sqlite3 +ephemeral.sqlite3-journal +ephemeral.sqlite3-wal +ephemeral.sqlite3-shm + +# Dolt server management (auto-started by bd) +dolt-server.pid +dolt-server.log +dolt-server.lock +dolt-server.port +dolt-server.activity +dolt-server-config.yaml + +# Debug-mode pprof artifacts (written when dolt.debug: true in config.yaml) +dolt-pprof/ + +# Corrupt backup directories (created by bd doctor --fix recovery) +*.corrupt.backup/ + +# Backup data (auto-exported JSONL, local-only) +backup/ + +# Per-project environment file (Dolt connection config, GH#2520) +.env + +# Legacy files (from pre-Dolt versions) +*.db +*.db?* +*.db-journal +*.db-wal +*.db-shm +db.sqlite +bd.db +# NOTE: Do NOT add negation patterns here. +# They would override fork protection in .git/info/exclude. +# Config files (metadata.json, config.yaml) are tracked by git by default +# since no pattern above ignores them. diff --git a/.beads/README.md b/.beads/README.md new file mode 100644 index 0000000..63e8f4c --- /dev/null +++ b/.beads/README.md @@ -0,0 +1,81 @@ +# Beads - AI-Native Issue Tracking + +Welcome to Beads! This repository uses **Beads** for issue tracking - a modern, AI-native tool designed to live directly in your codebase alongside your code. + +## What is Beads? + +Beads is issue tracking that lives in your repo, making it perfect for AI coding agents and developers who want their issues close to their code. No web UI required - everything works through the CLI and integrates seamlessly with git. + +**Learn more:** [github.com/steveyegge/beads](https://github.com/steveyegge/beads) + +## Quick Start + +### Essential Commands + +```bash +# Create new issues +bd create "Add user authentication" + +# View all issues +bd list + +# View issue details +bd show + +# Update issue status +bd update --claim +bd update --status done + +# Sync with Dolt remote +bd dolt push +``` + +### Working with Issues + +Issues in Beads are: +- **Git-native**: Stored in Dolt database with version control and branching +- **AI-friendly**: CLI-first design works perfectly with AI coding agents +- **Branch-aware**: Issues can follow your branch workflow +- **Sync-ready**: Uses Dolt remotes for backup and team sharing + +## Why Beads? + +✨ **AI-Native Design** +- Built specifically for AI-assisted development workflows +- CLI-first interface works seamlessly with AI coding agents +- No context switching to web UIs + +🚀 **Developer Focused** +- Issues live in your repo, right next to your code +- Works offline, syncs when you push +- Fast, lightweight, and stays out of your way + +🔧 **Git Integration** +- Dolt-native sync via bd dolt push / bd dolt pull +- Branch-aware issue tracking +- Dolt-native three-way merge resolution + +## Get Started with Beads + +Try Beads in your own projects: + +```bash +# Install Beads +curl -sSL https://raw.githubusercontent.com/steveyegge/beads/main/scripts/install.sh | bash + +# Initialize in your repo +bd init + +# Create your first issue +bd create "Try out Beads" +``` + +## Learn More + +- **Documentation**: [github.com/steveyegge/beads/docs](https://github.com/steveyegge/beads/tree/main/docs) +- **Quick Start Guide**: Run `bd quickstart` +- **Examples**: [github.com/steveyegge/beads/examples](https://github.com/steveyegge/beads/tree/main/examples) + +--- + +*Beads: Issue tracking that moves at the speed of thought* ⚡ diff --git a/.beads/config.yaml b/.beads/config.yaml new file mode 100644 index 0000000..049b3dc --- /dev/null +++ b/.beads/config.yaml @@ -0,0 +1,81 @@ +# Beads Configuration File +# This file configures default behavior for all bd commands in this repository +# All settings can also be set via environment variables (BD_* prefix) +# or overridden with command-line flags + +# Issue prefix for this repository (used by bd init) +# If not set, bd init will auto-detect from directory name +# Example: issue-prefix: "myproject" creates issues like "myproject-1", "myproject-2", etc. +issue-prefix: "cdkc" + +# Use no-db mode: JSONL-only, no Dolt database +# When true, .beads/issues.jsonl is the only local store +# no-db: false + +# Enable JSON output by default +# json: false + +# Feedback title formatting for mutating commands (create/update/close/dep/edit) +# 0 = hide titles, N > 0 = truncate to N characters +# output: +# title-length: 255 + +# Default actor for audit trails (overridden by BEADS_ACTOR or --actor) +# actor: "" + +# Optional JSONL sidecar for explicit agent/tool interaction audit records. +# Issue history is always recorded in the database and is visible with +# bd history --events; this only controls .beads/interactions.jsonl. +# audit: +# enabled: false + +# Export events (audit trail) to .beads/events.jsonl on each flush/sync +# When enabled, new events are appended incrementally using a high-water mark. +# Use 'bd export --events' to trigger manually regardless of this setting. +# events-export: false + +# Multi-repo configuration (experimental - bd-307) +# Allows hydrating from multiple repositories and routing writes to the correct database +# repos: +# primary: "." # Primary repo (where this database lives) +# additional: # Additional repos to hydrate from (read-only) +# - ~/beads-planning # Personal planning repo +# - ~/work-planning # Work planning repo + +# Dolt-native backup (periodic backup for off-machine recovery) +# This is full database backup only. Cross-machine sync uses Dolt remotes. +# backup: +# enabled: false # Disable auto-backup entirely +# interval: 15m # Minimum time between auto-backups +# git-push: false # Disable git push (backup locally only) +# git-repo: "" # Separate git repo for backups (default: project repo) + +# Optional JSONL auto-export for viewers, interchange, and issue-level migration. +# Disabled by default; enable only when an integration needs fresh .beads/issues.jsonl. +# Use relative paths under .beads/ for JSONL import/export filenames. +# export: +# auto: false +# path: issues.jsonl +# interval: 60s +# git-add: false +# import: +# path: issues.jsonl + +# Integration settings (access with 'bd config get/set') +# Non-secret keys (stored in the database): +# - jira.url, jira.project +# - linear.team_id +# - github.org, github.repo +# +# Secret keys (stored in this file but prefer env vars to avoid git exposure): +# - linear.api_key → use LINEAR_API_KEY env var instead +# - github.token → use GITHUB_TOKEN env var instead + +sync: + remote: "git+ssh://git@github.com/LayeredCraft/cdk-constructs.git" +dolt: + auto-push: false +export: + auto: true + git-add: false +no-git-ops: true diff --git a/.beads/issues.jsonl b/.beads/issues.jsonl new file mode 100644 index 0000000..62efd26 --- /dev/null +++ b/.beads/issues.jsonl @@ -0,0 +1,18 @@ +{"_type":"issue","id":"cdkc-18e.17","title":"Sharedale consumer validation and stable release gate","description":"Gate before a stable v2.6.0 release. Tracks end-to-end consumer validation of the published Lambda Web Functions preview package. Stable v2.6.0 must NOT be published until every acceptance criterion here is satisfied.","acceptance_criteria":"1. Lambda Web Functions PR merged to main.\n2. v2.6.0 preview NuGet package published successfully.\n3. Sharedale milestone 6 completed.\n4. Sharedale consumes the actual published preview NuGet package.\n5. Web Function constructs successfully integrated and validated in Sharedale.\n6. Any integration-discovered library defects resolved.\n7. Maintainer explicitly authorizes stable v2.6.0.","notes":"External dependency: Sharedale milestone 6 (external repo — do not modify Sharedale from this repository). This bead and epic cdkc-18e remain OPEN until stable v2.6.0 release acceptance.","status":"open","priority":1,"issue_type":"task","owner":"ncipollina@gmail.com","created_at":"2026-10-25T23:45:13Z","created_by":"Nick Cipollina","updated_at":"2026-10-25T23:45:13Z","external_ref":"sharedale-milestone-6","labels":["lambda-web-functions"],"dependencies":[{"issue_id":"cdkc-18e.17","depends_on_id":"cdkc-18e","type":"parent-child","created_at":"2026-10-25T23:45:13Z","created_by":"Nick Cipollina","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} +{"_type":"issue","id":"cdkc-18e.15","title":"T3c: Correct IAM grant, resource-policy, and endpoint-import review findings","description":"Purpose: correct the confirmed findings of the independent T1–T3b implementation review before T4 builds on them. Design: docs/designs/lambda-web-functions-integration.md REVISION 4. Authoritative sections: §8 (namespace note), §8.3 (reserved child IDs, read-only Endpoints, execution-role ordering), §8.4 (AddToResourcePolicy restrictions, imported-endpoint validation and account rule), §10.2 (updated table + \"Revision 4 corrections\" items 1–6), §10.3 (statement integrity), §12.1, §14 (revision-4 rows), §15 (revision-4 additions), §21 revision 4.\n\nImplement revision 4 exactly. If any rule cannot be implemented as written (for example a CDK public API behaves differently from what the design states), STOP and record a blocker with bd update \u003cid\u003e --append-notes. Do not change the design yourself.\n\nDeliverables (files: WebFunctionGrants.cs, WebFunctionEndpointConstruct.cs, WebFunctionImportedEndpoint.cs, WebFunctionConstruct.cs, Models/WebFunctionEndpoint.cs → move, tests):\n\n1. F1 Service principals (§10.2 rev-4 item 1). GrantInvoke throws InvalidOperationException for any principal whose PolicyFragment.PrincipalJson is a \"Service\" principal (bare ServicePrincipal or PrincipalWithConditions wrapping one), under BOTH CallerPolicy values. The service name is a token in CDK 2.274, so resolve it (Stack.Of(endpoint).Resolve) to detect cloudfront.amazonaws.com. Remedy text: CloudFront → \"use GrantCloudFrontInvoke(distributionArn)\"; other services → \"add an explicit, condition-scoped statement with endpoint.AddToResourcePolicy(...)\". Do NOT add aws:SourceAccount automatically. Do NOT add a new public API for scoped service grants (deferred).\n2. Wildcards (§10.2 rev-4 item 2; §8.4).\n - GrantInvoke throws InvalidOperationException for EVERY wildcard principal (PrincipalJson AWS=\"*\" or LiteralString=\"*\"; AnyPrincipal, StarPrincipal, OrganizationPrincipal, conditioned or not) under both CallerPolicy values. Remedy text: use an explicit, conditioned AddToResourcePolicy statement.\n - AddToResourcePolicy rejects (ArgumentException) Allow statements that have no conditions and name a wildcard or service principal, and Allow statements using NotPrincipal.\n - Deny statements are unrestricted.\n - An explicit Allow with a wildcard AND conditions is accepted. Check only that conditions are present; do NOT build any IAM-condition analyzer. XML docs state the consumer is responsible for the conditions meaningfully restricting access.\n - GrantCloudFrontInvoke (conditioned) keeps working.\n3. F3 Account principals (§10.2 rev-4 item 3). AccountPrincipal and AccountRootPrincipal (by .NET type), and any principal whose LITERAL AWS principal is an account root ARN, are never established. Automatic throws, even for the same account. ExternallyManaged behavior unchanged.\n4. P1 Verified identity writes (§10.2 rev-4 item 4) for owned AND imported principals. The identity side counts as written only when (a) the grant principal is a concrete owned mutable CDK identity (.NET Amazon.CDK.AWS.IAM.Role, User, Group, or LazyRole with Resource.IsOwnedResource == true), or (b) AddToPrincipalPolicy returned StatementAdded == true with PolicyDependable is Amazon.CDK.AWS.IAM.Policy (replacing the current \"is IConstruct\" check). Everything else is not written: fallback to the resource statement on an owned endpoint, throw on an imported endpoint. Never infer a write from Grant.PrincipalStatements. Verified facts on 2.274.0: an owned Role returns an EMPTY DependencyGroup (so signal (b) alone would break owned roles); ImmutableRole returns an empty DependencyGroup; imported mutable role/user/group return Policy; a classic Function's role, LazyRole, and User surface as concrete .NET types; owned.WithoutPolicyUpdates() surfaces as an IPrincipal proxy (not Role).\n5. F2 Role dependency (§8.3 notes, §12.1). Replace _revision.Node.AddDependency(Role) with a dependency on the role's CfnRole only (Role.Node.DefaultChild when it is a CfnResource; nothing extra for imported roles; ExecutionRoleArn already references the role). Never depend on the DefaultPolicy subtree. Keep every other DependsOn edge (Function, created LogGroup, bucket PolicyDependable).\n6. F5 Imported endpoints (§8.4; public API addition approved by the maintainer).\n - Add `public string? Account { get; init; }` to WebFunctionEndpointAttributes, with XML docs.\n - Validation:\n - a literal EndpointArn must match arn:{p}:lambda:{r}:{12 digits}:web-function/{fn}/endpoint/{ep} (ArgumentException);\n - a literal DomainName must be non-empty (null → ArgumentNullException, empty → ArgumentException);\n - a literal Account must be 12 digits;\n - when Account and the ARN are both literal, they must be equal (ArgumentException);\n - tokens are not validated.\n - Environment: Env.Account = the literal ARN account, else Account; Env.Region from the ARN. Use ResourceProps.EnvironmentFromArn, or explicit Account/Region if CDK does not allow combining them. Assert the result in tests either way.\n - Endpoint account = the literal ARN account, else a literal Account; anything else is NOT established.\n - If the endpoint account is not established, GrantInvoke throws for EVERY grantee, owned included (this replaces the revision-3 owned-only rule and its annotation). The message names both remedies (supply a literal Account; configure caller access outside this app) and notes that the endpoint remains usable as a CloudFront origin with ExternallyManaged origin permissions.\n - If the endpoint account is established, a grantee is established only when its account is literally SAME (owned → its stack account; imported → PrincipalAccount). ONE_UNRESOLVED and BOTH_UNRESOLVED are not established.\n - Constructing an imported endpoint with a token ARN and no Account must succeed; it must not throw at FromEndpointAttributes.\n7. P6 Statement integrity (§10.3). AddToResourcePolicy validates, then stores statement.Copy() with Freeze() applied. WebFunctionConstruct registers a node validation that returns PolicyDocument.ValidateForResourcePolicy() errors for the resource policy (when one exists). Keep StatementAdded/PolicyDependable return semantics.\n8. P3 Reserved ids (§8.3). AddEndpoint throws ArgumentException for the ids Function, Revision, DefaultEndpoint, ExecutionRole, LogGroup, ResourcePolicy (ordinal).\n9. Endpoints read-only. Return a cached ReadOnlyCollection (or equivalent) that cannot be cast back to a mutable List; the public type stays IReadOnlyList\u003cWebFunctionEndpointConstruct\u003e.\n10. F4 Diagnostics (§10.2 rev-4 item 6). Errors and annotations identify the grantee by the IGrantable's construct path when it is an IConstruct (jsii IRole proxies are), else the principal's resolved policy-fragment JSON, else the type name. Identify the endpoint by construct path + EndpointName, never by an ARN token. No human-facing text contains \"${Token[\". The ExternallyManaged annotation describes caller-side identity policies only for IAM identities.\n11. Namespace (§8 rev-4 note). Move IWebFunctionEndpoint to namespace LayeredCraft.Cdk.Constructs, in file IWebFunctionEndpoint.cs at the project root. XML docs state it is not intended for consumer implementation. Also correct the stale WebFunctionConstruct XML summary (\"added by later releases\").\n\nRegression tests (WebFunctionInvokeGrantTests / WebFunctionResourcePolicyTests / WebFunctionConstructTests; [Collection(\"CDK Tests\")]; assert on templates and messages, not on internals):\n- Service principals: cloudfront (message names GrantCloudFrontInvoke), another service, and a conditioned one each throw under Automatic AND ExternallyManaged; no ResourcePolicy synthesized.\n- Wildcards:\n - GrantInvoke with AnyPrincipal, StarPrincipal, and a conditioned OrganizationPrincipal throws under BOTH policies; no ResourcePolicy is created.\n - AddToResourcePolicy: an unconditioned \"*\" Allow throws; Allow+NotPrincipal throws; a Deny with \"*\" is accepted; an explicit Allow with \"*\" plus an aws:PrincipalOrgID StringEquals condition writes exactly that statement (condition preserved).\n- Same-account AccountPrincipal and AccountRootPrincipal under Automatic throw.\n- No-op identity writes (real CDK types, no fakes): Role.FromRoleArn(Mutable=false); Mutable=false + AddGrantsToResources=true; owned.WithoutPolicyUpdates(). Each → resource statement with the role ARN principal, ZERO AWS::IAM::Policy, and returned Grant.PrincipalStatements empty; the same grantees on an imported endpoint throw.\n- Real identity policies: owned Role, classic Lambda Function, WebFunctionConstruct, mutable imported role, imported User, imported Group → exactly one AWS::IAM::Policy statement with Action lambda:InvokeWebFunctionEndpoint and Resource = that endpoint's ARN, attached to the right role/user/group; no ResourcePolicy.\n- Unresolved imported ARNs: token role ARN (Fn.ImportValue) and a literal role ARN in an env-agnostic stack under Automatic → throw, zero AWS::IAM::Policy.\n- Imported endpoints:\n - Throw at FromEndpointAttributes: an invalid literal ARN (a function ARN, a missing endpoint segment); null and empty DomainName; a non-12-digit Account; an Account that differs from a literal ARN's account.\n - A literal ARN with an equal Account is accepted.\n - Env.Account/Env.Region equal the endpoint's (literal ARN; token ARN + literal Account).\n - A literal foreign ARN with an owned caller in an env-agnostic stack throws.\n - A token ARN with no Account: construction succeeds, and GrantInvoke throws for an owned Role AND for an imported mutable role, with ZERO AWS::IAM::Policy.\n - A token ARN with a literal Account equal to the caller stack's account and an owned caller writes the identity policy.\n - A token ARN with a literal Account different from the caller's account throws.\n - An immutable same-account role on an imported endpoint throws.\n- CDK upgrade guard: group the real-CDK principal-behavior tests (no-op writes, real identity policies, service/wildcard/account classification) in a clearly named class or trait (e.g. CdkPrincipalBehaviorRegressionTests). Its class doc comment states that these pin CDK/jsii behavior observed in 2.274.0 and that a failure on an Amazon.CDK.Lib upgrade blocks the upgrade until the signals are re-verified (design §10.2 rev-4 item 4).\n- Diagnostics: error messages contain the grantee construct path (imported role id), EndpointName, and both remedies; annotations asserted via Annotations.FromStack (info level, expected text); no message or annotation contains \"${Token[\".\n- Cycles: mutual invocation (A↔B), self-invocation, and BFF/API (API env var = web.DefaultEndpoint.Url, api.DefaultEndpoint.GrantInvoke(web)) → Template.FromStack succeeds. Assert that the revision DependsOn contains the CfnRole logical id and does NOT contain any DefaultPolicy id.\n- Statement integrity: mutating the caller's statement after AddToResourcePolicy (AddResources(\"*\")) leaves the template unchanged; a principal-less statement fails synthesis validation; the GrantInvoke resource path renders exactly one statement (dedupe of the double add).\n- Reserved ids: each reserved id passed to AddEndpoint throws ArgumentException. Endpoints: casting to List\u003cT\u003e/ICollection\u003cT\u003e mutation fails.\n- Replace the existing StatementAdded=false regression so it exercises a GrantInvoke-level path where feasible; keep a direct test of the internal helper only as a supplement.\n\nGolden templates (§12.4): the revision-dependency change intentionally alters web-function-use-log-group.json (SuppliedRoleDefaultPolicy… drops from the Revision DependsOn) and possibly other goldens whose role has a DefaultPolicy. Regenerate ONLY affected files with UPDATE_GOLDEN_TEMPLATES=1, then review every diff line. Record in the bead notes each changed golden, the exact changed lines, and why. Any diff beyond DependsOn removal of DefaultPolicy ids is a defect. The 17 existing-construct goldens must remain byte-identical. Add one new golden: a mutual-invocation pair + an explicit conditioned-wildcard AddToResourcePolicy statement (aws:PrincipalOrgID).\n\nRequired synthesis validation (record commands and results in notes): from the repo root, run dotnet restore LayeredCraft.Cdk.Constructs.slnx; dotnet build LayeredCraft.Cdk.Constructs.slnx -c Release (0 warnings); and dotnet test --solution LayeredCraft.Cdk.Constructs.slnx -c Release across net8.0–net11.0 (JSII_SILENCE_WARNING_UNTESTED_NODE_VERSION=1). Then grep src/ for AddToPrincipalOrResource|\\.Success\\b|AssertSuccess (must be empty) and for PrincipalStatements.Length used as write evidence (must be absent).\n\nExclusions: WebFunctionOrigin/T4; Testing-namespace helpers; user docs (T6a/T6b); owned-bucket inspection and DSSE (separate follow-up bead); existing constructs; any AWS deployment. No commits or pushes unless separately authorized.\n\nSecurity: never synthesize an unconditioned service-principal or wildcard Allow statement; never report a grant as complete when no policy was verifiably written; never write an identity policy for a principal whose account is not literally established for an imported endpoint.\n","acceptance_criteria":"• Every design revision-4 rule in §8.3/§8.4/§10.2/§10.3/§14 for this task is implemented; any deviation is recorded as a blocker note rather than taken silently.\n• GrantInvoke rejects all service principals (CloudFront remedy → GrantCloudFrontInvoke) and ALL wildcard principals, conditioned or not, under both CallerPolicy values.\n• AddToResourcePolicy rejects unconditioned wildcard/service-principal Allow statements and Allow+NotPrincipal, and accepts explicit conditioned wildcard Allow statements. There is no condition analyzer, and the consumer-responsibility XML doc is present.\n• Same-account AccountPrincipal/AccountRootPrincipal under Automatic throw.\n• Identity writes are counted only by the two revision-4 signals, for owned and imported principals. ImmutableRole, AddGrantsToResources=true, and WithoutPolicyUpdates() never produce a silent no-op (real-CDK tests, zero AWS::IAM::Policy). Unestablished authorization fails closed.\n• The real-CDK principal-behavior regression tests are grouped as a named CDK-upgrade guard whose doc comment cites the 2.274.0 observations and the upgrade-blocking rule.\n• Mutual, self, and BFF/API invocation patterns synthesize; the revision depends on the CfnRole and never on a DefaultPolicy.\n• WebFunctionEndpointAttributes.Account (string?) exists.\n• Literal ARN, domain, and Account are validated, and Account must match a literal ARN.\n• Env is the endpoint's.\n• GrantInvoke throws for every grantee when the endpoint account is not established (token ARN without a literal Account), and constructing such an endpoint still succeeds.\n• For an established endpoint account, only literal SAME grantee accounts are established.\n• Stored resource-policy statements are frozen copies; ValidateForResourcePolicy runs at synthesis; reserved AddEndpoint ids are rejected; Endpoints is genuinely read-only; IWebFunctionEndpoint lives in LayeredCraft.Cdk.Constructs.\n• Errors and annotations name the grantee and endpoint meaningfully and never contain ${Token[; annotations are asserted in tests.\n• Golden changes are limited to the intentional DependsOn removals (each diff recorded and explained in notes) plus the one new golden; the 17 existing-construct goldens are unchanged.\n• Release build has 0 warnings; the full suite passes on net8.0–net11.0; grep checks are clean; evidence is recorded in notes.","notes":"T3c BLOCKED on one revision-4 requirement (section 10.3 synthesis-time resource-policy validation) — STOPPED per task rule, bead NOT closed.\n\nIMPLEMENTED (all source edits applied; src builds 0 warnings/0 errors on all 4 TFMs):\n- WebFunctionValidation.cs: added using Amazon.CDK.AWS.IAM; regex WebFunctionEndpointArnPattern (^arn:[a-z0-9-]+:lambda:[a-z0-9-]+:[0-9]{12}:web-function/[^/]+/endpoint/[^/]+$), AccountPattern (^[0-9]{12}$); ReservedEndpointChildIds {Function,Revision,DefaultEndpoint,ExecutionRole,LogGroup,ResourcePolicy}; validators ValidateEndpointArn, ValidateEndpointDomainName (null-\u003eArgumentNullException, empty-\u003eArgumentException, tokens skipped), ValidateAccount, ValidateImportedAccountConsistency, ValidateEndpointChildId (reserved-\u003eArgumentException), ValidateResourcePolicyStatement (Deny ok; NotPrincipal-\u003eArgumentException; Allow with conditions ok; Allow with unconditioned service/wildcard principal-\u003eArgumentException), IsServicePrincipal, IsWildcardPrincipal.\n- Models/WebFunctionEndpointAttributes.cs: added public string? Account { get; init; }.\n- IWebFunctionEndpoint moved to root namespace LayeredCraft.Cdk.Constructs (new src/.../IWebFunctionEndpoint.cs); deleted Models/WebFunctionEndpoint.cs.\n- WebFunctionConstruct.cs: revision now depends on the owned role CfnRole ONLY (if Role.Node.DefaultChild is CfnResource roleCfn then _revision.Node.AddDependency(roleCfn); replacing _revision.Node.AddDependency(Role)) so the DefaultPolicy subtree is never a dependency; Endpoints is a genuinely read-only view (_endpoints.AsReadOnly()); AddEndpoint rejects reserved child ids.\n- WebFunctionEndpointConstruct.cs: AddToResourcePolicy validates then stores a frozen copy (statement.Copy(null); Freeze()) before forwarding.\n- WebFunctionImportedEndpoint.cs: validates ARN/DomainName/Account + consistency; resource Env = the endpoint's (ResourceProps.EnvironmentFromArn for a literal ARN, else Account); _account = literal ARN account else literal Account (else null = not established).\n- WebFunctionGrants.cs: full rev-4 rewrite — reject every service principal (both CallerPolicy; CloudFront remedy = GrantCloudFrontInvoke(distributionArn), detected by resolving the service token; other services remedy = explicit conditioned AddToResourcePolicy) and every wildcard principal (both modes); AccountPrincipal/AccountRootPrincipal never established (Automatic throws even same account); verified identity write ONLY via signal (a) concrete owned mutable CDK identity (Role/User/Group/LazyRole with Resource.IsOwnedResource) or signal (b) AddToPrincipalPolicy StatementAdded AND PolicyDependable is Amazon.CDK.AWS.IAM.Policy; never Grant.PrincipalStatements/Grant.Success/AssertSuccess; not-written -\u003e owned endpoint resource fallback / imported endpoint throw; imported endpoint account unestablished -\u003e throw for every grantee; ExternallyManaged -\u003e resource statement only + annotation (IAM identities only).\n\nBLOCKER (exact incompatibility): revision-4 section 10.3 requires registering a synthesis-time node validation that returns PolicyDocument.ValidateForResourcePolicy() errors. Constructs.Node.AddValidation(Constructs.IValidation) cannot accept a C#-implemented IValidation from this (non-jsii) library: every WebFunctionConstruct construction threw System.ArgumentException : Could not convert argument 'LayeredCraft.Cdk.Constructs.WebFunctionResourcePolicyValidation' to Jsii (Parameter 'arguments') at Constructs.Node.AddValidation — reproduced for BOTH a private nested class and a public top-level class. Note Constructs 10.5.0 DOES generate Constructs.IValidation._Proxy and Node.AddValidation exists, so jsii nominally advertises .NET implementations of IValidation, yet the 2.274.0 runtime rejects one; no concrete Amazon.CDK type implements Constructs.IValidation either. Hence the requirement is not implementable as written with CDK 2.274.0 + Constructs 10.5.0.\nREVERT: removed the Node.AddValidation(...) registration and deleted WebFunctionResourcePolicyValidation.cs. The fail-closed intent is currently served only by the EAGER WebFunctionValidation.ValidateResourcePolicyStatement(...) call in WebFunctionEndpointConstruct.AddToResourcePolicy.\nRECOMMENDED MINIMAL CORRECTIONS (need authorization; do NOT change the design unilaterally): (a) accept eager-only statement validation as the rev-4 equivalent, or (b) additionally call PolicyDocument.ValidateForResourcePolicy(null) eagerly inside WebFunctionConstruct.AddResourcePolicyStatement and throw (covers pre-synthesis adds but not later ones), or (c) investigate a jsii-marshallable IValidation (concrete/base-type/attribute requirement) or an alternate hook.\n\nNOT DONE (because stopped): existing WebFunction* tests not yet updated to rev-4 semantics (service principals now throw; AccountPrincipal throws; env-agnostic owned endpoint now throws), section 15 rev-4 new tests + named CDK-upgrade guard not added, web-function goldens not yet regenerated for the role-dependency DependsOn change (the 17 existing-construct goldens remain byte-identical; the 7 web-function golden tests currently fail against the altered DependsOn), full suite not re-run. Bead remains in_progress.\nT3c COMPLETE (all revision-4 acceptance criteria met). Not committed per instruction.\n\nDESIGN-CORRECTION / DEVIATION (authorized): The design's literal wording required registering a synthesis-time node validation (Node.AddValidation with a custom Constructs.IValidation) returning PolicyDocument.ValidateForResourcePolicy() errors. That is NOT implementable from this non-jsii assembly on CDK 2.274.0: Node.AddValidation throws \"Could not convert argument '...' to Jsii\" for both private-nested and public-top-level C# IValidation implementations. The maintainer authorized Option B: eager PolicyDocument validation instead. Implemented in WebFunctionConstruct.AddResourcePolicyStatement (see below). No other deviation.\n\nHOW DOCUMENT VALIDATION WAS IMPLEMENTED (Option B, transactional): WebFunctionConstruct.AddResourcePolicyStatement(statement):\n1. WebFunctionValidation.ValidateResourcePolicyStatement(statement) (revision-4 security checks: Deny allowed; Allow+NotPrincipal rejected; Allow with conditions accepted; otherwise Allow naming a service or wildcard principal rejected).\n2. var stored = statement.Copy(null); stored.Freeze();\n3. Build a candidate: new PolicyDocument(new PolicyDocumentProps { Statements = [.. _resourcePolicyStatements, stored] }).\n4. var errors = candidate.ValidateForResourcePolicy(null); if errors.Length \u003e 0 throw InvalidOperationException($\"The resource policy for Web Function '{Node.Path}' is invalid: {string.Join(\"; \", errors)}\").\n5. Only after validation: append to a private List\u003cPolicyStatement\u003e _resourcePolicyStatements, lazily create the single real _resourcePolicy PolicyDocument + single AWS::Lambda::CfnResourcePolicy child id \"ResourcePolicy\" (ResourceArn = _function.AttrFunctionArn).\nEvery subsequent addition revalidates the COMPLETE candidate document (no invalid partial state is applied). Single-policy ownership, endpoint-scoped resources, wildcard/service checks, and Deny behavior are preserved.\n\nFILES CHANGED (uncommitted):\nsrc/LayeredCraft.Cdk.Constructs/\n- Models/WebFunctionValidation.cs (MOD): added using Amazon.CDK.AWS.IAM; regexes WebFunctionEndpointArnPattern (arn:{p}:lambda:{r}:{12 digits}:web-function/{fn}/endpoint/{ep}) + AccountPattern (12 digits); ReservedEndpointChildIds {Function,Revision,DefaultEndpoint,ExecutionRole,LogGroup,ResourcePolicy}; ValidateEndpointArn / ValidateEndpointDomainName (null-\u003eArgumentNullException, empty-\u003eArgumentException, tokens skipped) / ValidateAccount / ValidateImportedAccountConsistency / ValidateEndpointChildId / ValidateResourcePolicyStatement / IsServicePrincipal / IsWildcardPrincipal / IsWildcardValue (IEnumerable-aware, so array-valued PrincipalJson like {\"AWS\":[\"*\"]} is detected).\n- Models/WebFunctionEndpointAttributes.cs (MOD): added public string? Account { get; init; }.\n- WebFunctionConstruct.cs (MOD): role dependency corrected to the owned role's CfnRole only (if (Role.Node.DefaultChild is CfnResource roleCfn) _revision.Node.AddDependency(roleCfn); never the whole Role/DefaultPolicy subtree); Endpoints is a genuinely read-only view (_endpoints.AsReadOnly()); AddEndpoint rejects reserved child IDs (ArgumentException) before the per-function EndpointName uniqueness check (InvalidOperationException); _resourcePolicyStatements + Option-B eager AddResourcePolicyStatement.\n- WebFunctionEndpointConstruct.cs (MOD): AddToResourcePolicy validates the statement (endpoint-scoped resource must equal this endpoint's ARN) then stores a frozen copy (statement.Copy(null); Freeze()).\n- WebFunctionImportedEndpoint.cs (MOD): validates attribute ARN/DomainName/Account + account consistency BEFORE the base environment; imported resource Env is the ENDPOINT's (ResourceProps.EnvironmentFromArn for a literal ARN, else ResourceProps.Account); _account = literal ARN account else literal Account (else null = not established).\n- WebFunctionGrants.cs (MOD, rev-4 rewrite): rejects SERVICE principals and ALL WILDCARD principals under BOTH CallerPolicy values with InvalidOperationException + remedies (CloudFront -\u003e \"Use GrantCloudFrontInvoke(distributionArn)...\"; other services -\u003e explicit condition-scoped endpoint.AddToResourcePolicy); AccountPrincipal/AccountRootPrincipal + literal account-root ARN principals are never established (Automatic throws even same account); ExternallyManaged -\u003e resource statement only + Annotations.AddInfo (IAM identities only, never identity); Automatic with an unestablished ENDPOINT account -\u003e throw for EVERY grantee (names both remedies + notes the endpoint remains usable as a CloudFront origin with ExternallyManaged permissions); established grantee ONLY when accounts are literally SAME (TokenComparison.SAME; owned -\u003e its stack account, imported -\u003e PrincipalAccount); verified identity write = signal (a) concrete owned mutable CDK identity (Amazon.CDK.AWS.IAM.Role/User/Group/LazyRole with Resource.IsOwnedResource) OR signal (b) AddToPrincipalPolicy returned StatementAdded \u0026\u0026 PolicyDependable is Amazon.CDK.AWS.IAM.Policy; written -\u003e Grant.AddToPrincipal; not written -\u003e OWNED endpoint: resource statement, IMPORTED endpoint: throw. Grant.Success / AssertSuccess / AddToPrincipalOrResource / Grant.PrincipalStatements are NOT used anywhere.\n- IWebFunctionEndpoint.cs (NEW, root namespace LayeredCraft.Cdk.Constructs); Models/WebFunctionEndpoint.cs DELETED (moved).\n\ntests/LayeredCraft.Cdk.Constructs.Tests/\n- WebFunctionSecurityTests.cs (NEW, 36 tests) incl. the named CDK-UPGRADE GUARD group (CdkUpgradeGuard_*) — real-CDK no-op-writer behavior (Role.FromRoleArn(Mutable=false), Mutable=false + AddGrantsToResources=true, owned.WithoutPolicyUpdates()) asserting NO AWS::IAM::Policy and pass-to-resource (owned) behavior; doc comment cites the 2.274.0 observations and the upgrade-blocking rule.\n- WebFunctionInvokeGrantTests.cs (MOD): 4 rev-4 updates (service principal now throws; env-agnostic owned throws; scoped-endpoint test now uses non-service grantees).\n- WebFunctionResourcePolicyTests.cs (MOD): statement now names a principal (resource policies require one).\n- WebFunctionConstructGoldenTemplateTests.cs (MOD): rev-4 adjustments.\n- GoldenTemplates/web-function-use-log-group.json (MOD, regenerated).\n\nGOLDEN-TEMPLATE DIFF (recorded): exactly ONE golden changed — test/LayeredCraft.Cdk.Constructs.Tests/GoldenTemplates/web-function-use-log-group.json. CloudFormation difference: the revision's DependsOn no longer lists \"SuppliedRoleDefaultPolicy1B06B14F\"; it retains \"SuppliedRole699D3B4C\" (the CfnRole) and \"webfunctionFunction46F1F768\". REASON: the rev-4 execution-role dependency correction makes the revision depend on the owned role's CfnRole only, never on the whole Role/DefaultPolicy subtree; this is the only scenario whose supplied role carries an inline DefaultPolicy (from logGroup.GrantWrite(role) for the non-/aws/lambda/ group \"/custom/web/logs\"). The other 6 web-function goldens were byte-identical (created roles have no inline DefaultPolicy). ALL 17 existing-construct goldens remain BYTE-IDENTICAL (unchanged).\n\nVALIDATION EVIDENCE: full Release build 0 warnings / 0 errors (net8.0/net9.0/net10.0/net11.0). Full suite `JSII_SILENCE_WARNING_UNTESTED_NODE_VERSION=1 dotnet test --solution LayeredCraft.Cdk.Constructs.slnx -c Release` -\u003e total 1700, failed 0, succeeded 1700, skipped 0 (425 x 4 TFMs; prior baseline 1556 = 389x4; +36/TFM). Golden tests: 24 total, all zero-diff. Focused runs: WebFunctionSecurityTests 36/36; -class \"*WebFunction*\" 203+ pass.\nT3c CORRECTIVE PASS (independent review R1-R3; bead reopened to in_progress).\n\nR1 (security, confirmed): GrantInvoke used an identity-policy WRITE as a capability probe (IdentityPolicyCanBeWritten called grantee.GrantPrincipal.AddToPrincipalPolicy(principal-less Allow statement)). This is not a dry run: for PrincipalWithConditions wrapping an owned role, the probe writes an UNCONDITIONAL Allow identity statement, bypassing the intended condition, then falls back to a conditioned resource statement. Correction required: never use an identity-policy write as a probe; explicitly reject PrincipalWithConditions and unsupported/unknown principal wrappers BEFORE any policy mutation; classify supported principals by concrete type (owned Role/User/Group/LazyRole; mutable imported; established immutable same-account resource fallback); fail closed otherwise; keep the endpoint-specific lambda:InvokeWebFunctionEndpoint action; no new public API. Tests must inspect synthesized policy documents.\n\nR2 (security, confirmed): AccountPrincipal.WithConditions bypasses the plain AccountPrincipal check (IsAccountPrincipal only matched AccountPrincipal/AccountRootPrincipal types or literal \":root\" ARNs; a PrincipalWithConditions wrapper and tokenized fragments slip through). Correction: account-root/account-wide principals must not be accepted through wrappers/tokenized fragments/alternate representations; do not rely on matching an unresolved raw JSON string; recognize known-unsupported categories; reject ambiguous wrappers rather than attempt a resource-policy fallback; never report an AccountPrincipal resource-policy statement as a complete automatic invocation grant. Tests: plain + conditioned AccountPrincipal, AccountRootPrincipal, literal root ArnPrincipal.\n\nR3 (test gaps in WebFunctionSecurityTests + related): (a) self-invocation and mutual-invocation cycle tests must call Template.FromStack; add a real BFF/API cross-reference scenario; assert synthesis succeeds + verify dependency edges. (b) AddToResourcePolicy must defensively copy statements: add a statement, mutate the original, synthesize, assert stored scope/conditions retained; a rejected statement must leave no partially created resource policy. (c) Assert ExternallyManaged annotations actually exist with accurate instructions; assert error messages identify endpoint + grantee; verify no raw ${Token[ leaks. (d) Authorization tests must verify actual identity-policy action/resource ARN/conditions; rejection paths leave no unexpected authorization statements; pin CDK 2.274.0 real principal behavior.\n\nAlso: review whether revision 4 implies unsupported principal wrappers should succeed (report inconsistency; do not edit the design). Validation: Release build; full suite net8.0/9.0/10.0/11.0; all golden tests; focused security/synthesis tests; the 17 existing-construct goldens must stay byte-identical. Keep cdkc-18e.15 open (in_progress) until independent review passes. Export .beads/issues.jsonl. Do not commit T3c. Do not start T4/cdkc-18e.16. No push/PR/deploy/publish.\nT3c CORRECTIVE PASS (R1-R3) COMPLETE. Bead deliberately LEFT OPEN (in_progress): per assignment, do not close until independent review passes.\n\nR1 - ELIMINATED MUTATION-BASED IDENTITY PROBING. WebFunctionGrants no longer calls AddToPrincipalPolicy as a capability probe. Deleted IdentityPolicyCanBeWritten (it wrote an unconditional identity Allow via PrincipalWithConditions and then fell back, bypassing conditions). Identity writes are now decided by pure type classification: IsOwnedMutableIdentity(principal) = principal is Amazon.CDK.AWS.IAM.Role/User/Group/LazyRole AND Resource.IsOwnedResource == true. Added RejectUnsupportedPrincipalWrapper(principal, endpointName): any PrincipalWithConditions is rejected with InvalidOperationException BEFORE any policy mutation. Grant.PrincipalStatements / Grant.Success / AssertSuccess / AddToPrincipalOrResource are not used anywhere.\n\nR2 - CONDITIONED AccountPrincipal BYPASS CLOSED. Replaced IsAccountRootArn with IsAccountRootOrId (recurse IEnumerable (PrincipalJson values are arrays); string: fail-literal when it is an account-root ARN (arn:...:root) OR a 12-digit account id; unresolved tokens not matched). IsAccountPrincipal still keys off the concrete .NET types AccountPrincipal/AccountRootPrincipal first. Account/account-root principals are never established: Automatic throws even same-account, ExternallyManaged writes only a resource statement.\n\nCONSEQUENCE / REQUIRED DESIGN CLARIFICATION (report; do NOT edit design): a mutable imported role and an immutable imported role are indistinguishable via jsii (both IRole._Proxy/IPrincipal._Proxy, is Role false, IsOwnedResource false). With probing forbidden, imported principals can no longer be credited an identity write, so they take the resource-policy fallback on an owned endpoint (0 AWS::IAM::Policy, 1 AWS::Lambda::ResourcePolicy statement) or throw on an imported endpoint. Rev-4 section 10.2 row 'E2 imported same-account role, mutable -\u003e identity policy' is therefore UNIMPLEMENTABLE without a probe; maintainer must reconcile the wording.\n\nFILES CHANGED (T3c, uncommitted): src - Models/WebFunctionValidation.cs (rev-4 validators incl ValidateResourcePolicyStatement/IsServicePrincipal/IsWildcardPrincipal, IEnumerable-aware wildcard detection), Models/WebFunctionEndpointAttributes.cs (added string? Account), WebFunctionConstruct.cs (revision depends on owned role CfnRole only; read-only Endpoints via _endpoints.AsReadOnly(); reserved AddEndpoint id validation; Option-B eager AddResourcePolicyStatement: ValidateResourcePolicyStatement -\u003e statement.Copy(null)+Freeze() -\u003e candidate PolicyDocument(ValidateForResourcePolicy) -\u003e throw on errors -\u003e append to single real PolicyDocument/CfnResourcePolicy), WebFunctionEndpointConstruct.cs (AddToResourcePolicy validates + stores frozen copy), WebFunctionImportedEndpoint.cs (ARN/Domain/Account validation before base Env; Env from endpoint ARN/account), WebFunctionGrants.cs (rev-4 rewrite + R1/R2); NEW IWebFunctionEndpoint.cs (root namespace); DELETED Models/WebFunctionEndpoint.cs. Tests - NEW WebFunctionSecurityTests.cs (43 tests; service/wildcard/account rejection, AddToResourcePolicy restrictions, imported-endpoint validation/Env, cycles incl. BFF/API + self + mutual, frozen-copy, reserved ids, read-only Endpoints, no ${Token[ leaks, annotations via endpoint.Node.Metadata, named CdkUpgradeGuard_* group); modified WebFunctionInvokeGrantTests.cs (service principal throws; env-agnostic owned throws; mutable imported role now resource fallback) + WebFunctionResourcePolicyTests.cs (principal added). GOLDEN: test/.../GoldenTemplates/web-function-use-log-group.json regenerated (only change: SuppliedRoleDefaultPolicy1B06B14F removed from the Revision DependsOn because the revision now depends on the owned role's CfnRole only). All 17 existing-construct goldens byte-identical.\n\nEVIDENCE: Release build 0 warnings / 0 errors. Focused WebFunctionSecurityTests 43/43 pass. Focused WebFunction 239/239 pass. Full suite --solution LayeredCraft.Cdk.Constructs.slnx -c Release: total 1728, failed 0, succeeded 1728, skipped 0 (432 x net8.0/net9.0/net10.0/net11.0; prior 1700 = 425x4). 24 golden tests pass with the 17 existing-construct goldens byte-identical.\nT3c corrective pass #2 (environment-agnostic E1 + R3 test completion) — COMPLETE; bead intentionally left in_progress for independent acceptance.\n\n1) ENVIRONMENT-AGNOSTIC E1 (maintainer-approved): src/WebFunctionGrants.cs GrantInvoke Automatic branch now:\n - owned mutable identity + ENDPOINT in the SAME stack =\u003e WriteIdentityPolicy even when the stack account is an unresolved token (ownership of both in one stack is sufficient).\n - different stacks with MATCHING LITERAL accounts =\u003e identity policy.\n - different stacks with unresolved or mismatched accounts =\u003e InvalidOperationException (matching literal accounts required).\n - imported principals: literal SAME account required; on an owned endpoint they use the resource-policy fallback (never identity).\n - imported endpoints: literal same-account required; GrantInvoke throws for every grantee when the endpoint account cannot be established.\n - cross-account callers fail closed. NO speculative AddToPrincipalPolicy probing anywhere; PrincipalWithConditions / service-principal / wildcard / AccountPrincipal protections unchanged.\n\n2) R1 preserved: no identity-policy mutation probes (type-based IsOwnedMutableIdentity only). R2 preserved: AccountPrincipal/AccountRootPrincipal and account-root/12-digit-id principals rejected (incl. wrapped/tokenized). Unsupported wrapper (PrincipalWithConditions) rejected.\n\n3) R3 test corrections/app additions (test/.../WebFunctionSecurityTests.cs + WebFunctionInvokeGrantTests.cs):\n - SelfInvocationGrant_Synthesizes and MutualInvocationGrant_Synthesizes now call Template.FromStack and assert ResourceCountIs IAM::Policy (1 / 2) and no ResourcePolicy; BFF/API cross-reference test retained.\n - Diagnostics test repurposed to a token-ARN imported endpoint (no Account): asserts InvalidOperationException naming the endpoint construct path + grantee + reason and containing no \"${Token[\" nor \"\u003cunresolved\u003e\"; endpoint construction from a token ARN without Account succeeds.\n - Env-agnostic E1 test now expects identity synthesis (1 AWS::IAM::Policy, 0 AWS::Lambda::ResourcePolicy).\n - New ownership tests: different stacks with matching literal accounts =\u003e identity; different stacks with unresolved accounts =\u003e throws (\"different stack\"); different stacks with mismatched literal accounts =\u003e throws (\"matching literal accounts\"); imported role on imported endpoint =\u003e throws with ZERO policy mutation (serialized template contains neither AWS::IAM::Policy nor AWS::Lambda::ResourcePolicy).\n\n4) VERIFICATION (JSII_SILENCE_WARNING_UNTESTED_NODE_VERSION=1, -c Release): focused -class \"*WebFunction*\" net8.0 =\u003e 250/250 pass. Full suite =\u003e total 1744, failed 0, succeeded 1744, skipped 0 (436 x net8.0/net9.0/net10.0/net11.0; prior 1728=432x4; +4/TFM). Release build 0 warnings / 0 errors. 24 golden tests pass; the 17 existing-construct goldens are byte-identical; the ONLY modified golden is web-function-use-log-group.json (rev-4 execution-role dependency correction: removed SuppliedRoleDefaultPolicy1B06B14F from the Revision DependsOn; the revision now depends on the owned role's CfnRole only).\n\n5) DESIGN CONFLICT (reported, not changed): rev-4 section 10.2 row \"E2 imported same-account role, mutable =\u003e identity policy\" is not implementable without a write-probe because mutable and immutable imported roles are indistinguishable via jsii (.NET); per R1 probing is forbidden, so imported principals use the resource-policy fallback. Maintainer to reconcile wording.\n\nFiles (T3c, uncommitted): src models/constructs/grants as previously listed; tests WebFunctionSecurityTests.cs (new), WebFunctionInvokeGrantTests.cs, WebFunctionResourcePolicyTests.cs (modified); GoldenTemplates/web-function-use-log-group.json (regenerated). T3c NOT committed; no push/PR/deploy/publish; T4/cdkc-18e.16 not started.\nT3c FINAL-ACCEPTANCE CORRECTIONS (independent review: CHANGES REQUIRED — one missing mandatory CDK upgrade-guard regression test + minor diagnostic/doc corrections).\n\nNEW MANDATORY TEST: CdkUpgradeGuard_WithConditionsWrappers_RejectedWithoutPolicies (added to the existing CdkUpgradeGuard_* group in test/.../WebFunctionSecurityTests.cs). Uses real AWS CDK 2.274.0 principal types (NOT mocks):\n var conditions = new Dictionary\u003cstring, object\u003e { [\"Bool\"] = new Dictionary\u003cstring, object\u003e { [\"aws:SecureTransport\"] = \"true\" } };\n var accountWrapped = new AccountPrincipal(\"123456789012\").WithConditions(conditions);\n var arnWrapped = new ArnPrincipal(role.RoleArn).WithConditions(conditions); // role = OwnedRole(stack)\nAssertions: (1) accountWrapped.GetType().FullName == \"Amazon.CDK.AWS.IAM.PrincipalWithConditions\" and same for arnWrapped (plus BeAssignableTo\u003cPrincipalWithConditions\u003e()) — this exercises the ACTUAL jsii-returned wrapper produced by WithConditions (not a manually constructed PrincipalWithConditions); (2) endpoint.GrantInvoke(accountWrapped) and endpoint.GrantInvoke(arnWrapped) each throw InvalidOperationException under CallerPolicy Automatic; (3) same two calls throw under CallerPolicy = ExternallyManaged; (4) after the rejected grants, Template.FromStack synthesis shows ZERO AWS::IAM::Policy and ZERO AWS::Lambda::ResourcePolicy (rejected before any authorization mutation; no partial policy).\nPurpose: detect future CDK upgrades that change principal-wrapper materialization and could reopen the AccountPrincipal authorization bypass.\n\nRUNTIME TYPES OBSERVED FROM JSII: AccountPrincipal(...).WithConditions(...) and ArnPrincipal(...).WithConditions(...) both return runtime type Amazon.CDK.AWS.IAM.PrincipalWithConditions (the CDK 2.274.0 wrapper), which the library rejects via RejectUnsupportedPrincipalWrapper before any policy mutation.\n\nMINOR CORRECTION 1 (diagnostic): src/.../WebFunctionGrants.cs — in the Automatic owned-principal branch, an owned role in an environment-agnostic stack invoking an IMPORTED endpoint no longer throws the misleading \"different stack\" message. It now throws a dedicated message describing the ACTUAL missing condition: the endpoint is imported (its resource policy is externally owned) and the caller's stack account cannot be established, so the library will not write an unverifiable identity policy; remedies = give the caller's stack an explicit environment account matching the endpoint's, import the caller with a literal ARN in the endpoint's account, or use CallerPolicy = ExternallyManaged. The distinct \"different stack ... matching literal accounts are required\" message is retained for the owned-endpoint different-stack case (so GrantInvoke_DifferentStacksUnresolvedAccount_Throws and GrantInvoke_DifferentStacksMismatchedLiteralAccount_ReportsMismatch still pass). No grant behavior changed.\n\nMINOR CORRECTION 2 (XML docs only, no API/behavior change):\n- src/.../IWebFunctionEndpoint.cs: interface docs now state owned endpoints own the function's single resource policy while imported endpoints stay externally owned, that invoke grants are endpoint-scoped to lambda:InvokeWebFunctionEndpoint on that endpoint's ARN, and that GrantInvoke writes the caller's identity policy only when the caller's account can be established (otherwise fail closed) with service/wildcard/account and condition-wrapped principals rejected; the options overload documents Automatic vs ExternallyManaged.\n- src/.../WebFunctionImportedEndpoint.cs: class docs now state it owns no AWS resources, configures a caller identity policy only when caller and endpoint accounts are established and literally equal, never touches the function's resource policy, and derives its account from a literal endpoint ARN else a literal WebFunctionEndpointAttributes.Account (otherwise not established, automatic grants rejected).\n\nTEST STRENGTHENING: SelfInvocationGrant_Synthesizes now inspects the actual emitted identity statement (Action == \"lambda:InvokeWebFunctionEndpoint\"; Resource.GetAtt[1] == \"EndpointArn\") in addition to ResourceCountIs(IAM::Policy,1)/(Lambda::ResourcePolicy,0).\n\nPRESERVED (unchanged, per instruction): pure principal-classification algorithm; same-stack environment-agnostic E1 support; cross-stack literal-account restrictions; imported-role resource-policy fallback; imported-endpoint ownership; service-principal/wildcard/AccountPrincipal rejection; PrincipalWithConditions rejection; eager transactional ValidateForResourcePolicy; revision dependency on the underlying CfnRole; approved rev-4 public API.\n\nVALIDATION: Release build 0 warnings / 0 errors. Focused `-class \"*WebFunctionSecurityTests*\"` (net8.0) 48/48. Full suite `JSII_SILENCE_WARNING_UNTESTED_NODE_VERSION=1 dotnet test --solution LayeredCraft.Cdk.Constructs.slnx -c Release` -\u003e 1748 passed / 0 failed / 0 skipped (437 x net8.0/9.0/10.0/11.0; prior 1744 = 436x4; +1/TFM). All 24 golden tests pass; the 17 existing-construct goldens are byte-identical; the ONLY golden difference remains test/.../GoldenTemplates/web-function-use-log-group.json (intentional rev-4 execution-role dependency correction: removal of SuppliedRoleDefaultPolicy1B06B14F from the Revision DependsOn).\n\nBEADS/GIT: cdkc-18e.15 kept in_progress (open; awaiting maintainer acceptance). T3c remains UNCOMMITTED. Branch main, ahead of origin/main by 5; HEAD ceafce5 (T3b) -\u003e 12ae64b (T3a) -\u003e 705c515 (T2) -\u003e e184a7b (T1) -\u003e 4cf2cb0 (T0) -\u003e b05ca90; NOT pushed. No commit/push/PR/deploy/publish. T4 and cdkc-18e.16 not started.\nT3c ACCEPTED (2026-10-23) after independent security review and the final jsii upgrade-guard test.\n\nREVISION-4 DESIGN VERIFICATION (docs/designs/lambda-web-functions-integration.md)\n- Env-agnostic E1 clarification present: §10.2 E1 restatement (lines 1081-1091): same-stack ownership with an owned endpoint is sufficient even in an env-agnostic stack; cross-stack grants require both stack accounts literal and SAME; unresolved/different accounts rejected before any policy write. §21 third maintainer clarification (lines 1937-1939) records it.\n- Eager transactional resource-policy validation present: §10.3 (lines 1263-1284) and §14 rev-4 row (line 1509): Node.AddValidation is not used; each contribution validates statement-level rules, copies+frozen the statement, builds a candidate PolicyDocument and calls ValidateForResourcePolicy, and only then records it and creates the single CfnResourcePolicy. Implemented in WebFunctionConstruct.AddResourcePolicyStatement and WebFunctionEndpointConstruct.AddToResourcePolicy.\n- All other rev-4 corrections (service principals, wildcards, account principals, verified identity writes, CfnRole-only dependency, imported-endpoint account attribute) are present (§10.2 rev-4 items 1-6; §8.3, §8.4; §21 items 1-10).\n\nJSII UPGRADE-GUARD TEST\n- CdkUpgradeGuard_WithConditionsWrappers_RejectedWithoutPolicies (test/LayeredCraft.Cdk.Constructs.Tests/WebFunctionSecurityTests.cs:678) uses real jsii-returned wrappers: AccountPrincipal('123456789012').WithConditions(...) and ArnPrincipal(role.RoleArn).WithConditions(...); asserts both materialize as Amazon.CDK.AWS.IAM.PrincipalWithConditions; asserts rejection under BOTH CallerPolicy values (Automatic default and ExternallyManaged); and asserts the synthesized template has no AWS::IAM::Policy and no AWS::Lambda::ResourcePolicy.\n\nBUILD/TEST EVIDENCE\n- dotnet build -c Release: Build succeeded, 0 Warning(s), 0 Error(s).\n- Full suite (xUnit v3) on all four TFMs: net8.0 437/0 failed, net9.0 437/0 failed, net10.0 437/0 failed, net11.0 437/0 failed.\n\nGOLDEN TEMPLATES\n- The 17 original (non-Web-Function) golden templates are byte-identical (git reports none modified).\n- Exactly one Web Function golden changed intentionally: web-function-use-log-group.json drops 'SuppliedRoleDefaultPolicy1B06B14F' from the revision DependsOn, per rev-4 item 5 (revision depends on CfnRole only, not the role DefaultPolicy). All other 6 Web Function goldens unchanged; golden tests pass in compare mode.","spec_id":"docs/designs/lambda-web-functions-integration.md","status":"closed","priority":1,"issue_type":"task","assignee":"Nick Cipollina","owner":"ncipollina@gmail.com","created_at":"2026-10-23T12:49:06Z","created_by":"Nick Cipollina","updated_at":"2026-10-23T14:34:20Z","started_at":"2026-10-23T13:14:26Z","closed_at":"2026-10-23T14:34:20Z","close_reason":"T3c accepted after independent security review and the final jsii upgrade-guard test. Revision-4 design verified complete (env-agnostic E1 clarification §10.2; eager transactional resource-policy validation §10.3/§14). CdkUpgradeGuard_WithConditionsWrappers_RejectedWithoutPolicies uses real jsii wrappers and both CallerPolicy modes. Release build 0 warnings; 437 tests pass on net8.0-net11.0. 17 original goldens byte-identical; single intentional web-function-use-log-group.json change (CfnRole-only dependency).","external_ref":"gh-98","labels":["iam","lambda-web-functions","security","t3"],"dependencies":[{"issue_id":"cdkc-18e.15","depends_on_id":"cdkc-18e","type":"parent-child","created_at":"2026-10-23T12:49:06Z","created_by":"Nick Cipollina","metadata":"{}"},{"issue_id":"cdkc-18e.15","depends_on_id":"cdkc-18e.5","type":"blocks","created_at":"2026-10-23T12:49:06Z","created_by":"Nick Cipollina","metadata":"{}"}],"dependency_count":1,"dependent_count":1,"comment_count":0} +{"_type":"issue","id":"cdkc-18e.14","title":"T8: Verify release acceptance criteria and feature completion","description":"Purpose: final completion gate for the feature (closes before the epic). Design §19.1 (items 1–4), §13, §2 goals.\n\nChecklist to verify and record:\n1. Validation gates pass on a clean checkout of the working tree: restore, Release build, full tests on net8.0–net11.0, coverage ≥ 80%, mkdocs build.\n2. Golden templates: existing four constructs zero diff vs the T0 baseline; new construct goldens present.\n3. Workload compatibility: Next.js, ASP.NET Core shim, Blazor Static SSR synthesize via the same public API; no workload-specific construct/helper/packaging in src/.\n4. Sandbox gate bead closed with full evidence (incl. Blazor page + asset).\n5. Scope audit against the design: no EncryptionKey, no FromAsset, no upstream L2/alpha dependency, no changes to existing constructs' source, explicit AuthType everywhere,\n GrantInvoke matches §10.2 rev 3 (no AddToPrincipalOrResource/AssertSuccess), single resource policy, docs complete.\n6. Optional spike bead (T4a) status recorded but does not block.\nOutcome: notes summarizing readiness for the maintainer. Do NOT publish NuGet packages, bump versions, commit, push, open PRs, or close GitHub issue #98 — those require separate maintainer authorization.\n","acceptance_criteria":"- All six checklist items verified with evidence recorded in notes.\n- Any gap results in a linked bug bead and this bead stays open.\n- No publishing/commit/PR actions taken.","notes":"T6a REVIEW FINDING (documentation task; production code NOT changed): the KMS error text in src/LayeredCraft.Cdk.Constructs/Models/WebFunctionCode.cs may mislead about which principal reads the S3 artifact. KmsManagedMessage (L227-228) and DsseManagedMessage (L232) both end with \"...a customer-managed key the function role can read\". In reality Lambda reads and decrypts the code artifact with the Lambda service principal (lambda.amazonaws.com), so the KMS key policy must allow that principal kms:Decrypt; it is not (only) the function execution role. Evaluate rewording before publication (for example \"...a customer-managed key whose key policy allows the Lambda service principal to decrypt\"), and confirm the docs' SSE-KMS guidance (docs/constructs/web-function.md) matches. No production-code change was made during T6a.\nT8 Final release acceptance (2026-10-25). Branch main. Evidence commits: a3a284a (T7c evidence), 1bfe687 (KMS diagnostic wording + service-default log-group docs + tests).\n\nCLEAN CHECKOUT VALIDATION (isolated worktree at a3a284a): restore OK; Release build for 4 TFMs (net8.0/net9.0/net10.0/net11.0) 0 warnings 0 errors; tests 2140/2140 pass, 0 fail, 0 skip (535 x 4); coverage 94.30% line / 98.78% branch (gate 80%); mkdocs build --clean --strict EXIT 0; golden templates 17 existing with zero diff plus 8 new Web Function goldens present; dotnet pack produced nupkg + snupkg, 4 TFMs, MIT, icon/README, sourcelink commit, Amazon.CDK.Lib dependency pinned 2.274.0 (floor confirmed).\n\nPUBLIC API / ARCHITECTURE AUDIT vs design revision 4: conforms. Single resource policy; reserved child ids (Function, Revision, DefaultEndpoint, ExecutionRole, LogGroup, ResourcePolicy) rejected by AddEndpoint; no AddToPrincipalOrResource/AssertSuccess/Grant.Success; no reflection in src; explicit required AuthType; deferrals intact (FromAsset, customer-managed revision KmsKeyArn, upstream CDK L2 replacement). Documented deviation: WebFunctionEndpointConstruct implements IResourceWithPolicyV2 (T3a).\n\nKMS WORDING FIXED: owned-bucket SSE-KMS and DSSE messages now name lambda.amazonaws.com (verified against AWS docs: a customer-managed key policy must allow lambda.amazonaws.com kms:GenerateDataKey and kms:Decrypt because Lambda reads the artifact with its service principal, not the function execution role). Docs were already correct; construct tests strengthened to pin the wording.\n\nDOCS FOLLOW-UP: added service-created default log-group teardown guidance (the Lambda service creates /aws/lambda/web/{name} on first invocation; it is not stack-owned, has no expiry, and survives CloudFormation teardown; delete leftovers by exact name in disposable sandboxes only).\n\nAWS ACCEPTANCE MATRIX (from T7c sandbox; account \u003csandbox-account-id\u003e, us-east-1, library HEAD 47fa84d, AWS CLI 2.38.5): design 19.1 items 3.1, 3.2, 3.3, 3.4, 3.5, 3.6, 3.8 PASS; 3.7 cross-account SKIP (SANDBOX_CROSS_ACCOUNT_CALLER_ROLE_ARN unset; optional; documented as unverified, not unsupported); MultiRegion / PerRegion / SigV4A NOT TESTED. Verified end to end: v1 deploy (3 stacks CREATE_COMPLETE), v1 to v2 revision updates, active revision + endpoint routing, signed/unsigned invocation, imported-role authorization, CloudFront OAC + static assets, second-distribution add/remove, live resource-policy evidence, full teardown with no residual sandbox resources.\n\nT4a (cdkc-18e.7): Outcome B, closed as wont-implement (not feasible with public CDK APIs without template resolution).\n\nRELEASE READINESS: READY FOR RELEASE with documented limitations. Next version v2.6.0 (release-drafter minor via type:feat); CDK floor 2.274.0. Residual risks: cross-account path unverified; MultiRegion/SigV4A runtime-untested; F3006 warnings documented; docs CI runs mkdocs --clean (not --strict) though local strict passes; VersionPrefix in Directory.Build.props is 2.4.0 (local pack-local.sh only; release workflow derives the version from the tag).\n\nSTOPPED before publish: nothing pushed, no merge, no NuGet publish, issue #98 left OPEN. Changes committed locally only.","spec_id":"docs/designs/lambda-web-functions-integration.md","status":"closed","priority":1,"issue_type":"task","assignee":"Nick Cipollina","owner":"ncipollina@gmail.com","created_at":"2026-10-23T01:14:59Z","created_by":"Nick Cipollina","updated_at":"2026-10-25T23:45:50Z","started_at":"2026-10-25T18:14:26Z","closed_at":"2026-10-25T18:19:50Z","close_reason":"T8 final release acceptance complete: clean-checkout validation, public API audit, KMS wording fix, docs follow-up, AWS acceptance matrix, release-readiness verdict READY FOR RELEASE. Stopped before publish.","external_ref":"gh-98","labels":["lambda-web-functions","release-gate","t8"],"dependencies":[{"issue_id":"cdkc-18e.14","depends_on_id":"cdkc-18e","type":"parent-child","created_at":"2026-10-23T01:14:59Z","created_by":"Nick Cipollina","metadata":"{}"},{"issue_id":"cdkc-18e.14","depends_on_id":"cdkc-18e.10","type":"blocks","created_at":"2026-10-23T01:15:24Z","created_by":"Nick Cipollina","metadata":"{}"},{"issue_id":"cdkc-18e.14","depends_on_id":"cdkc-18e.13","type":"blocks","created_at":"2026-10-23T01:15:22Z","created_by":"Nick Cipollina","metadata":"{}"},{"issue_id":"cdkc-18e.14","depends_on_id":"cdkc-18e.8","type":"blocks","created_at":"2026-10-23T01:15:23Z","created_by":"Nick Cipollina","metadata":"{}"},{"issue_id":"cdkc-18e.14","depends_on_id":"cdkc-18e.9","type":"blocks","created_at":"2026-10-23T01:15:23Z","created_by":"Nick Cipollina","metadata":"{}"}],"dependency_count":4,"dependent_count":0,"comment_count":0} +{"_type":"issue","id":"cdkc-18e.13","title":"T7c: Run AWS sandbox deployment and smoke test (mandatory release gate)","description":"MANDATORY release gate before NuGet publication. Requires explicit maintainer authorization and maintainer-provided NON-PRODUCTION sandbox AWS credentials. Do not start without both.\nDesign §19.1 (AUTHORITATIVE), §15 \"Deployed validation\".\n\nSteps: using samples/web-functions (previous beads), build artifacts, deploy (artifacts stack → upload → app stack), run smoke.sh, then perform the update scenarios\n(v2 artifacts → new revision active and endpoints moved; add then remove second distribution → statement added then removed), and destroy everything.\n\nMust verify and record (status codes, revision IDs, policy JSON excerpts):\n3.1 artifact deployment from both bucket-policy modes (Automatic owned bucket, ExternallyManaged pre-provisioned bucket);\n3.2 function/revision/endpoints Active; redeploy with changed artifact activates a new revision and moves endpoints;\n3.3 SigV4-signed request by the granted caller role → 2xx;\n3.4 unsigned → 403; signed by an ungranted role → 403; signed for the second endpoint the role was not granted → 403;\n3.5 through CloudFront → 2xx; direct unsigned to the IamAuth endpoint → 403;\n3.6 get-resource-policy contains exactly the expected statements; second distribution adds a scoped statement; removing it removes the statement;\n3.7 cross-account (only if a second sandbox account is available): ExternallyManaged grant + caller-account identity policy → success; without identity policy → denied; otherwise record \"not verified\";\n3.8 Next.js page via CloudFront; ASP.NET Core endpoint (signed); Blazor Static SSR rendered page AND static asset served.\nAlso record: date, account alias (no account secrets), region, CDK version, library commit/working-tree state, and any criterion not verified.\n\nCleanup is required: run destroy.sh, verify no stacks, buckets (all versions), log groups, distributions, or roles remain; record verification.\nThis bead must NOT be closed on synthesis results alone. If any check fails, record it, file a bug bead linked to the responsible implementation bead, and leave this bead open.\nExclusions: production accounts, Sharedale resources, publishing, commits/PRs.\n","acceptance_criteria":"- Every §19.1 item 3.1–3.8 is recorded as passed with evidence (3.7 may be \"not verified\" only when no second sandbox account exists, stated explicitly).\n- Blazor Static SSR page and static asset verified in AWS.\n- All sandbox resources destroyed and verified.\n- Evidence stored in bead notes (and the release PR description when one is authorized).","notes":"REVIEW ROUTING (2026-10-23, design revision 4 §19.1 item 3.3): also verify and record:\n- first-deploy behavior while the caller's identity policy propagates (the revision no longer depends on the role DefaultPolicy; record any transient 403 window);\n- a same-account grant written only as a resource-policy statement (immutable imported role) returns 2xx;\n- an identity-only same-account grant returns 2xx;\n- the deployed ResourceArn (function ARN) and the code-bucket aws:SourceArn .../revision/* + aws:SourceAccount conditions are accepted and effective.\nThis bead now also waits for cdkc-18e.16 (owned-bucket inspection follow-up).\nFrom T4 independent review: during sandbox validation, verify OriginAccessControl naming across AWS Regions. CDK auto-generates the OAC Name; confirm there is no account-global OAC naming collision when the same Web Function origin is deployed in multiple Regions/stacks, and that the generated name is stable.\nT7c AWS deployment + smoke acceptance gate COMPLETE (observed 2026-10-24).\n\nTARGET: account \u003csandbox-account-id\u003e (IAM user \u003csandbox-iam-user\u003e), region us-east-1, sandbox id \u003csandbox-id\u003e, namespace lccdk-wf-sandbox-\u003csandbox-id\u003e. Library revision at test time: HEAD 47fa84d (T7b 0e9ecde; CLI-2.38.x smoke align 80a61a1; shared-account auth 90675e4; live-policy parser fix 47fa84d). AWS CLI 2.38.5.\n\nARTIFACTS (build id 90675e42785c; v2 = 90675e42785c-v2):\nnextjs.zip sha256 50931ee444d3c25e / nextjs-v2 50a7ec8bd967c804\naspnetcore.zip 710da153c1c6bcc2 / aspnetcore-v2 446e5151ca1abf12\nblazor.zip 3f4a861d7e2bfdc0 / blazor-v2 155af1b566ecf663\n\nV1 DEPLOY: 3 stacks CREATE_COMPLETE (artifacts/external/app), app deploy 238.22s. CloudFormation ACCEPTED the experimental AWS::Lambda::WebFunction / WebFunctionRevision / WebFunctionEndpoint resource types (only F3006 warnings). v1 revisions: nextjs rev-gkdoq, aspnetcore rev-23ls9, blazor rev-gsy99. v1 smoke PASS=44 FAIL=0 SKIP=1 BLOCKED=0; build ids 90675e42785c; cold 200 ~2.0s warm 200 ~0.16s; signed caller/imported-immutable/imported-mutable all 200 (resource-policy-only immutable+mutable = 200 =\u003e design 19.1 3.3 rev-4 satisfied); unsigned 403, no-grant role 403, endpoint-scoped 403; Next.js+Blazor via CloudFront OAC 200; Next.js/blazor policies 1 CloudFront statement each; aspnetcore policy 2 role principals; imported roles have no identity invoke policy; caller identity policy scoped to lambda:InvokeWebFunctionEndpoint; policy completeness 3/3. Cross-account SKIP.\n\nV2 UPDATE: update-to-v2.sh; revisions nextjs rev-bfcec, aspnetcore rev-sxp6k, blazor rev-rpzmu (all changed, Active, weight 100). v2 smoke PASS=48 FAIL=0 SKIP=1 BLOCKED=0; build ids 90675e42785c-v2; v1-\u003ev2 transition 'all functions advanced' PASS.\n\nSECOND DISTRIBUTION: add (deploy --revision 2 --second-distribution) -\u003e new distribution \u003ccf-dist-c\u003e (\u003ccf-dist-c-domain\u003e); Next.js resource policy 2 CloudFront statements; smoke PASS=49 FAIL=0 SKIP=1 BLOCKED=0. remove (deploy --revision 2) -\u003e policy back to 1 statement, second OAC removed, original distribution still 200; post-remove smoke PASS=48 FAIL=0 SKIP=1 BLOCKED=0. Each app deploy advances the revision (construct creates a revision per deploy); post-remove generation rev-bjzgq/rev-lx7eh/rev-bmist.\n\nTRANSIENT 403: authorization checks use retry/backoff; no persistent 403 observed - first-deploy propagation window recorded, all granted invocations succeeded.\n\nNOT VERIFIED: cross-account (19.1 3.7) - SANDBOX_CROSS_ACCOUNT_CALLER_ROLE_ARN unset (SKIP, optional). MultiRegion/PerRegion/SigV4A NOT tested (single HomeRegion endpoint). OAC cross-Region naming not exercised (single region).\n\nTEARDOWN: destroy.sh --yes with SANDBOX_CONFIRM_DESTROY=\u003csandbox-id\u003e + shared-account ack; all 3 stacks destroyed. Independent verification: no active stacks (all DELETE_COMPLETE), no \u003csandbox-id\u003e S3 buckets, no \u003csandbox-id\u003e IAM roles/policies, distributions \u003ccf-dist-a\u003e/\u003ccf-dist-b\u003e/\u003ccf-dist-c\u003e all NoSuchDistribution, no OACs, no /aws/lambda/web log groups, resourcegroupstaggingapi sandbox-id=\u003csandbox-id\u003e returns none, lambda-web functionCount=0. Note: 3 service-created orphaned log groups (/aws/lambda/web/\u003csandbox-id\u003e-*.local; AppStack used service-default logs so CFN never owned them; untagged, 0 bytes) survived the CFN destroy and were removed explicitly by exact name, then re-verified absent.\n\nRESULT: 19.1 3.1, 3.2, 3.3, 3.4, 3.5, 3.6, 3.8 PASS on live AWS; 3.7 SKIP (optional/unconfigured). All mandatory scenarios PASS; sandbox fully removed.","spec_id":"docs/designs/lambda-web-functions-integration.md","status":"closed","priority":1,"issue_type":"task","owner":"ncipollina@gmail.com","created_at":"2026-10-23T01:14:58Z","created_by":"Nick Cipollina","updated_at":"2026-10-25T23:45:51Z","started_at":"2026-10-24T23:32:13Z","closed_at":"2026-10-25T03:10:54Z","close_reason":"T7c mandatory AWS deployment + smoke gate PASSED and sandbox torn down. Account \u003csandbox-account-id\u003e/us-east-1, sandbox \u003csandbox-id\u003e. 19.1: 3.1-3.6,3.8 PASS on live AWS; 3.7 cross-account SKIP (optional, unconfigured). v1 revisions rev-gkdoq/rev-23ls9/rev-gsy99; v2 rev-bfcec/rev-sxp6k/rev-rpzmu; build ids 90675e42785c[-v2]. Second-distribution add/remove verified (policy stmt added then removed). Teardown verified: no stacks/buckets/roles/policies/distributions/OACs/log groups/tagged resources; lambda-web functionCount 0. Full evidence in notes.","external_ref":"gh-98","labels":["lambda-web-functions","release-gate","requires-aws","requires-maintainer-authorization","sandbox","t7"],"dependencies":[{"issue_id":"cdkc-18e.13","depends_on_id":"cdkc-18e","type":"parent-child","created_at":"2026-10-23T01:14:58Z","created_by":"Nick Cipollina","metadata":"{}"},{"issue_id":"cdkc-18e.13","depends_on_id":"cdkc-18e.12","type":"blocks","created_at":"2026-10-23T01:15:20Z","created_by":"Nick Cipollina","metadata":"{}"},{"issue_id":"cdkc-18e.13","depends_on_id":"cdkc-18e.16","type":"blocks","created_at":"2026-10-23T12:49:20Z","created_by":"Nick Cipollina","metadata":"{}"},{"issue_id":"cdkc-18e.13","depends_on_id":"cdkc-18e.8","type":"blocks","created_at":"2026-10-23T01:15:20Z","created_by":"Nick Cipollina","metadata":"{}"},{"issue_id":"cdkc-18e.13","depends_on_id":"cdkc-18e.9","type":"blocks","created_at":"2026-10-23T01:15:21Z","created_by":"Nick Cipollina","metadata":"{}"}],"dependency_count":4,"dependent_count":1,"comment_count":0} +{"_type":"issue","id":"cdkc-18e.8","title":"T5: Add Web Function testing helpers, consumer example and workload synthesis tests","description":"Purpose: consumer-facing Testing helpers plus consumer/workload compilation and synthesis tests. Design §8.6, §9 (all examples), §15 (Consumer helpers, Workloads), §19.1 item 2.\n\nDeliverables:\n- src/LayeredCraft.Cdk.Constructs/Testing/WebFunctionConstructAssertions.cs: extension methods on Template per §8.6 (ShouldHaveWebFunction, ShouldHaveRevision, ShouldHaveRevisionCode,\n ShouldHaveEndpoint, ShouldHaveEndpointScaling, ShouldHaveInvokeGrant, ShouldHaveSingleResourcePolicy, ShouldHaveNoResourcePolicy, ShouldAllowCloudFront,\n ShouldAllowResourcePolicyPrincipal, ShouldHaveWebFunctionOac, ShouldHaveCodeBucketReadStatement). Match by function/endpoint NAMES (resolve the endpoint's logical ID\n from its EndpointName), never by logical-ID prefixes; must distinguish multiple endpoints. Follow existing *ConstructAssertions style.\n- src/LayeredCraft.Cdk.Constructs/Testing/WebFunctionConstructPropsBuilder.cs per §8.6 (private fields; WithFunctionName, WithCode, WithTestArtifact(Construct scope, key),\n WithIamAuthEndpoint, WithApplicationManagedEndpoint, WithEndpoint(IWebFunctionEndpointOptions), WithEnvironmentVariable, WithEntryPoint, WithTimeout,\n WithMaxConcurrencyPerEnvironment, WithRole, WithLogs; Build() throws InvalidOperationException without Code or endpoint; no Action\u003c\u003e callbacks; never chooses an AuthType).\n- CdkTestHelper.CreateWebFunctionPropsBuilder() (additive change to CdkTestHelper only).\n- Internal test kit: WebFunctionConstructAutoData attribute + customization (deterministic names) following existing TestKit patterns.\n- Consumer example tests: compile and synthesize §9.1–§9.7 verbatim-equivalent code using only the public API.\n- Workload synthesis tests (acceptance criterion §19.1 item 2): Next.js, ASP.NET Core (execve shim), Blazor Static SSR — each via the same public API, differences only in\n Code, EntryPoint, EnvironmentVariables, and consumer CloudFront behaviors.\n\nTests: assertion helpers have positive and negative tests (failing assertions throw); builder tests (Build() throws without auth/code; WithTestArtifact synthesizes without credentials).\nExclusions: new production behavior in constructs (if a gap is found, record a blocker rather than changing construct semantics); docs.\n","acceptance_criteria":"- Assertions and builder exist with the §8.6 signatures; CdkTestHelper entry added without changing existing helper behavior.\n- §9 examples and three workload configurations compile and synthesize in tests.\n- Assertions distinguish multiple endpoints and verify exactly-one resource policy.\n- Coverage threshold (80%) maintained; existing goldens unchanged; validation gates pass.","notes":"T5 IMPLEMENTATION COMPLETE (not committed).\n\nDeliverables:\n- NEW src/LayeredCraft.Cdk.Constructs/Testing/WebFunctionConstructAssertions.cs: 12 Template extension methods per design 8.6 (ShouldHaveWebFunction, ShouldHaveRevision, ShouldHaveRevisionCode, ShouldHaveEndpoint, ShouldHaveEndpointScaling, ShouldHaveInvokeGrant, ShouldHaveSingleResourcePolicy, ShouldHaveNoResourcePolicy, ShouldAllowCloudFront, ShouldAllowResourcePolicyPrincipal, ShouldHaveWebFunctionOac, ShouldHaveCodeBucketReadStatement). Matches by function/endpoint NAMES, resolving the endpoint logical id from its EndpointName; discriminates multiple endpoints; verifies exactly-one resource policy.\n- NEW src/LayeredCraft.Cdk.Constructs/Testing/WebFunctionConstructPropsBuilder.cs per design 8.6: private fields; With* methods (WithFunctionName, WithCode, WithTestArtifact, WithIamAuthEndpoint, WithApplicationManagedEndpoint, WithEndpoint, WithEnvironmentVariable, WithEntryPoint, WithTimeout, WithMaxConcurrencyPerEnvironment, WithDescription, WithRole, WithLogs); Build() throws InvalidOperationException when Code or the endpoint (AuthType) was never chosen; never picks an auth mode.\n- MODIFIED src/LayeredCraft.Cdk.Constructs/Testing/CdkTestHelper.cs: additive CreateWebFunctionPropsBuilder() only; existing helpers unchanged.\n- NEW test/LayeredCraft.Cdk.Constructs.Tests/TestKit/Attributes/WebFunctionConstructAutoDataAttribute.cs and test/.../TestKit/Customizations/WebFunctionConstructCustomization.cs: deterministic props via a substitute IBucket (BucketName test-web-function-artifacts) with ExternallyManaged code so synthesis needs no AWS credentials.\n- NEW test/.../WebFunctionConsumerExamplesTests.cs: 7 tests compiling and synthesizing design 9.1-9.7 using only the public API.\n- NEW test/.../WebFunctionWorkloadTests.cs: 4 tests (Next.js, ASP.NET Core Node.js execve shim, Blazor Static SSR shim, AllWorkloads) using only the same public construct; differences only in Code, EntryPoint, EnvironmentVariables, and consumer CloudFront behaviors.\n- NEW test/.../Testing/WebFunctionConstructTestingHelpersTests.cs: about 34 tests covering the assertion helpers (positive and negative) and the props builder.\n\nEvidence:\n- dotnet build LayeredCraft.Cdk.Constructs.slnx -c Release: 0 Warning(s), 0 Error(s).\n- JSII_SILENCE_WARNING_UNTESTED_NODE_VERSION=1 dotnet test --solution LayeredCraft.Cdk.Constructs.slnx -c Release: Passed, total 2084, failed 0 (521 per TFM x net8.0/net9.0/net10.0/net11.0; +45 per TFM vs the 1904 baseline).\n- Golden templates: no file added or modified; the 17 original existing-construct goldens remain byte-identical.\n\nNotes: no production construct behavior changed and no gap requiring a construct change was found. Do not commit T5 automatically.\nT5 CORRECTIONS APPLIED (independent review D1-D10) — awaiting maintainer acceptance, NOT committed.\n\nReview verdict was CHANGES REQUIRED: public testing assertions could produce false positives/negatives. All findings addressed within T5 scope; no production construct changed.\n\nD1 (function-specific endpoint lookup): WebFunctionConstructAssertions.EndpointLogicalId now requires BOTH the literal FunctionName and EndpointName (calls FunctionLogicalId first, then filters endpoints on EndpointName==name \u0026\u0026 FunctionName==name); throws \"No Web Function endpoint named '\u003cname\u003e' was found on function '\u003cfn\u003e'.\" Tests: ShouldHaveInvokeGrant_ShouldNotBeSatisfiedByAnotherFunctionsEndpoint and ShouldAllowCloudFront_ShouldNotBeSatisfiedByAnotherFunctionsEndpoint (two functions, each with a \"default\" endpoint; grant only on function-b; function-a assertions throw).\n\nD2 (function-specific S3 assertion): ShouldHaveCodeBucketReadStatement(functionName) now requires the statement's ArnLike aws:SourceArn condition to contain \"web-function/{functionName}/revision/*\" (new StatementSourceArnContains + FlattenArn that flattens Fn::Join literal segments), plus Effect=Allow, s3:GetObject, lambda.amazonaws.com service principal, and StringEquals aws:SourceAccount. Test: ShouldHaveCodeBucketReadStatement_ShouldNotBeSatisfiedByAnotherFunctionsPolicy (only function-a owns an Automatic bucket policy).\n\nD3 (IAM policy minimization): assertion now accepts Resource as either a single endpoint ARN or an array (ResourceTargetsEndpoint handles IEnumerable). Real synthesis test ShouldHaveInvokeGrant_ShouldMatchMinimizedArrayResourceStatement enables @aws-cdk/aws-iam:minimizePolicies via AppProps.Context before construct creation, grants one role both endpoints, asserts both ShouldHaveInvokeGrant calls succeed AND asserts the merged AWS::IAM::Policy statement Resource is a 2-element array (proves the flag really merged; array path genuinely exercised). Deterministic array case also covered by ShouldHaveInvokeGrant_ShouldMatchArrayResourceStatement (explicit PolicyStatement with Resources=[arn1,arn2]).\n\nD4 (ambiguous scaling): public signature of ShouldHaveEndpointScaling unchanged; when multiple endpoints share the requested EndpointName it now throws InvalidOperationException containing \"ambiguous\" (actionable text) instead of selecting the first. Test: ShouldHaveEndpointScaling_ShouldThrowWhenEndpointNameIsAmbiguous.\n\nD5 (authorization semantics): ShouldHaveInvokeGrant, ShouldAllowCloudFront and ShouldAllowResourcePolicyPrincipal now all require Effect=Allow + Action=lambda:InvokeWebFunctionEndpoint + exact endpoint resource (and principal/condition as appropriate). Deny-only and wrong-action statements are rejected. Negative tests use real synthesized resource policies incl. valid Deny: ShouldHaveInvokeGrant_ShouldRejectDenyStatement, ShouldHaveInvokeGrant_ShouldRejectUnrelatedAction (lambda:InvokeFunction), ShouldAllowCloudFront_ShouldRejectDenyStatement, ShouldAllowCloudFront_ShouldRejectWrongActionStatement, ShouldAllowResourcePolicyPrincipal_ShouldRejectDenyStatement.\n\nD6 (jsii-safe AutoData): WebFunctionConstructCustomization no longer substitutes IBucket (jsii-unmarshalable). It now builds a real imported bucket via Bucket.FromBucketName on a stack-scoped fixture (new App + Stack \"WebFunctionFixtureStack\"). Test [Theory][WebFunctionConstructAutoData] WebFunctionConstructAutoData_ShouldSupplySynthesizableProps(WebFunctionConstructProps props) consumes the attribute and synthesizes (ShouldHaveWebFunction/ShouldHaveEndpoint; ResourceCountIs AWS::S3::Bucket 0), proving attribute+customization work end-to-end without AWS credentials.\n\nD7 (artifact construct-ID collisions): WithTestArtifact reuses an existing compatible bucket (scope.Node.TryFindChild(\"WebFunctionTestArtifacts\") as IBucket) before creating the imported bucket, so multiple Web Functions in one stack share it. Test: WithTestArtifact_ShouldSupportMultipleFunctionsInOneStack.\n\nD8 (builder state isolation): Build() now copies the environment dictionary (new Dictionary\u003cstring,string\u003e(_environmentVariables)) instead of exposing the live field. Test: Build_ShouldIsolateEnvironmentDictionary (mutating the builder after Build() does not change previously built props).\n\nD9 (workload examples): Next.js entry point aligned with the approved index.js shim (code key artifacts/web.zip, EntryPoint index.js, NODE_ENV=production, NEXT_TELEMETRY_DISABLED=1). Removed invented DOTNET_RUNNING_IN_CONTAINER and BLAZOR_STATIC_SSR env vars. ASP.NET Core and Blazor Static SSR now differ by artifact (api.zip vs blazor.zip) and are documented as the same shim contract. Class doc states these are synthesis-only; runtime behavior is covered by deployed smoke tests in T7c. Recipes cite design §16.\n\nD10 (consumer examples): §9.2 now asserts the revision S3Object Key=web.zip + VersionId=version-1 directly; §9.6 asserts the worker's invocation grant (ShouldHaveInvokeGrant(\"worker\",\"default\")); §9.1/§9.3/§9.7 comments document externally-managed permission ownership (caller policy, bucket policy, origin permissions). All examples use only the public API.\n\nVALIDATION EVIDENCE: dotnet build LayeredCraft.Cdk.Constructs.slnx -c Release =\u003e 0 warnings / 0 errors. Full 4-TFM suite =\u003e total 2140, failed 0, skipped 0 (535 per TFM on net8.0/net9.0/net10.0/net11.0; +56 vs the pre-correction 2084). Focused WebFunctionConstructTestingHelpersTests =\u003e 48/48 pass. Consumer examples 7/7. GoldenTemplates dir: no files added or modified — all 17 existing-construct goldens byte-identical. No production construct behavior changed; no unresolved design issue.\nT5 ACCEPTED by maintainer after independent review and correction of D1-D8 (plus D9-D10). Final validation: Release build 0 warnings/0 errors; full 4-TFM suite total 2140, failed 0; all 17 existing-construct goldens byte-identical. Committed locally as 'test: add Web Function testing helpers and consumer examples'. Not pushed.","spec_id":"docs/designs/lambda-web-functions-integration.md","status":"closed","priority":1,"issue_type":"task","assignee":"Nick Cipollina","owner":"ncipollina@gmail.com","created_at":"2026-10-23T01:14:53Z","created_by":"Nick Cipollina","updated_at":"2026-10-23T16:32:04Z","started_at":"2026-10-23T15:49:15Z","closed_at":"2026-10-23T16:32:04Z","close_reason":"T5 accepted and complete: WebFunctionConstructAssertions + WebFunctionConstructPropsBuilder + CdkTestHelper entry, jsii-safe AutoData/customization, consumer examples 9.1-9.7, three workload synthesis tests, helper tests (48); review findings D1-D10 corrected; full suite 2140 pass on 4 TFMs; 17 goldens unchanged.","external_ref":"gh-98","labels":["lambda-web-functions","t5","testing"],"dependencies":[{"issue_id":"cdkc-18e.8","depends_on_id":"cdkc-18e","type":"parent-child","created_at":"2026-10-23T01:14:53Z","created_by":"Nick Cipollina","metadata":"{}"},{"issue_id":"cdkc-18e.8","depends_on_id":"cdkc-18e.5","type":"blocks","created_at":"2026-10-23T01:15:16Z","created_by":"Nick Cipollina","metadata":"{}"},{"issue_id":"cdkc-18e.8","depends_on_id":"cdkc-18e.6","type":"blocks","created_at":"2026-10-23T01:15:15Z","created_by":"Nick Cipollina","metadata":"{}"}],"dependency_count":2,"dependent_count":3,"comment_count":0} +{"_type":"issue","id":"cdkc-18e.6","title":"T4: Implement WebFunctionOrigin with OAC and automatic same-stack permissions","description":"Purpose: CloudFront origin factory with OAC and automatic, same-stack permission granting. Design §5.4, §8.5, §9.4, §9.7, §11.1 (AUTHORITATIVE steps), §11.2 (spike results), §12.3, §14, §15 (CloudFront/OAC).\n\nDeliverables (src/LayeredCraft.Cdk.Constructs/WebFunctionOrigin.cs + internal origin class):\n- public static class WebFunctionOrigin:\n * WithOriginAccessControl(IWebFunctionEndpoint, WebFunctionOriginWithOacProps? = null): throws immediately for ApplicationManaged endpoints.\n * WithoutOriginAccessControl(IWebFunctionEndpoint, WebFunctionOriginProps? = null): throws for IamAuth endpoints; returns an HTTPS HttpOrigin.\n- internal sealed class WebFunctionOacOrigin : DeputyBase, IOrigin (jsii interface implemented from .NET; proven by spike) whose Bind(scope, options):\n 1. Signing: HomeRegion/PerRegion → Signing.SIGV4_ALWAYS_AMZ_AUTH; MultiRegion → new Signing(SigningProtocol.SIGV4A, SigningBehavior.ALWAYS_AMZ_AUTH).\n 2. OAC: use supplied IOriginAccessControl unchanged (not inspected), else create one L2 FunctionUrlOriginAccessControl with child id \"WebFunctionOac\" in the bind scope. No CfnOriginAccessControl.\n 3. Permissions Automatic: imported endpoint → throw; Stack.Of(scope) != Stack.Of(endpoint) → throw with the same-stack/dependency-cycle message and ExternallyManaged remedy;\n else endpoint.GrantCloudFrontInvoke(Stack.Of(scope).FormatArn({Service=\"cloudfront\", Region=\"\", Resource=\"distribution\", ResourceName=options.DistributionId})).\n ExternallyManaged: no statement; Annotations info naming the distribution that must be allowed.\n 4. Return new HttpOrigin(endpoint.DomainName, {mapped WebFunctionOriginProps members, ProtocolPolicy=HTTPS_ONLY, OriginAccessControlId=oac id}).Bind(scope, options).\n- No opt-in Region list, no distribution behavior inspection, no IValidation (design §11.1 \"Removed in revision 2\").\n\nTests: OAC lambda/always-amz-auth/sigv4 for HomeRegion \u0026 PerRegion, sigv4a for MultiRegion; origin DomainName = endpoint DomainName, https-only, OriginAccessControlId set;\nevery WebFunctionOriginProps member passes through; auto statement aws:SourceArn = distribution ARN; same origin on two behaviors → one statement and one OAC;\ntwo distributions → two scoped statements; origin for a second endpoint → statement on that endpoint ARN; supplied OAC reused (none created); ExternallyManaged → no statement + annotation;\nexplicit GrantCloudFrontInvoke(literal ARN) without a Distribution; negatives: ApplicationManaged+OAC, IamAuth+WithoutOriginAccessControl, imported+Automatic, cross-stack+Automatic\n(assert the library's error message, not a CDK DependencyCycle). Golden template: Next.js-style distribution (§9.4) with default + /_next/static/* behaviors on one origin.\n\nExclusions: Distribution/certificate/DNS creation by the library; behavior helpers; Testing helpers; docs.\nSecurity: OAC only for IamAuth; never forward-compatible \"convenience\" that would let an ApplicationManaged endpoint appear protected.\n","acceptance_criteria":"- WebFunctionOrigin public API matches §8.5; Bind behavior matches §11.1 steps 1–5.\n- Uses L2 FunctionUrlOriginAccessControl with correct Signing; no L1 OAC, no custom resources.\n- Automatic permissions only for owned endpoints in the same stack; imported/cross-stack fail with library messages; ExternallyManaged annotated.\n- All listed tests pass; new golden template added; existing goldens unchanged; validation gates pass.","notes":"REVIEW ROUTING (2026-10-23, design revision 4): T4 is now blocked by T3c (cdkc-18e.15).\nConsume the post-T3c API:\n- IWebFunctionEndpoint moves to namespace LayeredCraft.Cdk.Constructs.\n- Treat any IWebFunctionEndpoint other than WebFunctionEndpointConstruct as imported (Automatic permissions throw).\n- Imported endpoints take Env from their ARN.\n- AddToResourcePolicy stores frozen copies and rejects unconditioned wildcard/service-principal Allow statements. GrantCloudFrontInvoke is unaffected because it is SourceArn-conditioned.\n- 'ResourcePolicy' and the other reserved ids are rejected by AddEndpoint, so the lazily created policy cannot collide during Bind.\nMaintainer clarification (2026-10-23):\n- WebFunctionEndpointAttributes gains an optional Account (T3c).\n- Imported endpoints whose account is not established (token ARN, no literal Account) cannot be GrantInvoke'd, but MUST be accepted by WebFunctionOrigin.WithOriginAccessControl with Permissions = WebFunctionOriginPermissions.ExternallyManaged. Add a T4 test for a token-ARN imported endpoint as an ExternallyManaged OAC origin.\n- IWebFunctionEndpoint is in namespace LayeredCraft.Cdk.Constructs.\nT4 IMPLEMENTED (not committed). Files: src/LayeredCraft.Cdk.Constructs/WebFunctionOrigin.cs (factory: WithOriginAccessControl requires IamAuth; WithoutOriginAccessControl requires ApplicationManaged; maps WebFunctionOriginProps -\u003e HttpOriginProps, forces HTTPS_ONLY), src/LayeredCraft.Cdk.Constructs/WebFunctionOacOrigin.cs (internal sealed : DeputyBase, IOrigin; binds at distribution time), test/LayeredCraft.Cdk.Constructs.Tests/WebFunctionOriginTests.cs (+20 tests), WebFunctionConstructGoldenTemplateTests.cs (+1), GoldenTemplates/web-function-cloudfront-oac.json (new). Architecture: one FunctionUrlOriginAccessControl child 'WebFunctionOac' created in the bind/origin scope unless supplied; signing = sigv4 (HomeRegion/PerRegion) or sigv4a (MultiRegion) via new Signing(SIGV4A, ALWAYS_AMZ_AUTH), always-amz-auth, origin type lambda; HttpOrigin uses endpoint DomainName, HTTPS_ONLY, OriginAccessControlId. Permissions: Automatic same-stack owned endpoint -\u003e single WebFunctionConstruct resource-policy statement via endpoint.GrantCloudFrontInvoke(Stack.FormatArn cloudfront distribution id), cloudfront.amazonaws.com + aws:SourceArn; imported endpoint and cross-stack distribution -\u003e actionable InvalidOperationException message; ExternallyManaged -\u003e no statement + info annotation naming distribution. Imported/token-ARN endpoints supported with ExternallyManaged. Test evidence: Release build 0 warnings/0 errors; full suite total 1884 (471 x net8/9/10/11), 0 failed, 0 skipped; 17 original goldens byte-identical (no diff); new OAC golden verified. CDK compat finding: validation exceptions thrown inside IOrigin.Bind cross the jsii boundary and surface to .NET callers as System.Exception embedding the InvalidOperationException text; factory-time validation (auth mismatch, nulls) still throws InvalidOperationException directly. Design requirement 'actionable message, not CDK cycle' is satisfied; tests assert the message. CDK 2.274.0 L2 extension points (HttpOrigin, FunctionUrlOriginAccessControl, IOrigin.Bind) are sufficient.\nT4 INDEPENDENT-REVIEW CORRECTIONS (F1-F5) APPLIED (round 2, not committed). Architecture unchanged: WebFunctionOrigin factory API, WebFunctionOacOrigin (DeputyBase/IOrigin), HttpOrigin delegation, FunctionUrlOriginAccessControl, IamAuth/ApplicationManaged restrictions, sigv4/sigv4a behavior, single-owner resource policy, and imported-endpoint permissions model all preserved.\n\nF1 - No partial mutation during binding:\n- WebFunctionOrigin gains private ValidateOriginConfiguration(domainName, props) =\u003e _ = new HttpOrigin(domainName, BuildHttpOriginProps(props, null)). It reuses CDK's own HttpOrigin constructor validation (no duplicated rules) and runs at factory time in WithOriginAccessControl before any OAC or policy statement exists. WithoutOriginAccessControl already validates because it returns a real HttpOrigin at factory.\n- WebFunctionOacOrigin.Bind reordered: (1) resolve/create OAC, (2) build HttpOrigin (validates), (3) ApplyPermissions, (4) origin.Bind.\n- New test WithOriginAccessControl_InvalidConnectionAttempts_ShouldFailBeforeCreatingResources: factory throws (\"*connectionAttempts*\") and the stack is left with zero AWS::CloudFront::OriginAccessControl and zero AWS::Lambda::ResourcePolicy.\n\nF2 - ExternallyManaged guidance corrected:\n- Owned endpoints: annotation keeps GrantCloudFrontInvoke guidance and names the distribution, the cloudfront.amazonaws.com service principal, and the aws:SourceArn condition.\n- Imported endpoints: annotation now tells the Web Function owner to add an endpoint-scoped resource-policy statement for cloudfront.amazonaws.com guarded by a StringEquals aws:SourceArn condition, names the distribution, and identifies the endpoint by literal ARN when available, otherwise by name+domain (never raw token placeholders).\n\nF3 - Origin property forwarding: new WithOriginAccessControl_ShouldForwardAllOriginProps and WithoutOriginAccessControl_ShouldForwardAllOriginProps cover every supported WebFunctionOriginProps member (OriginId, OriginPath, CustomHeaders, ConnectionAttempts, ConnectionTimeout, ReadTimeout, KeepaliveTimeout, ResponseCompletionTimeout, OriginShieldEnabled, OriginShieldRegion) in synthesized CloudFormation for both paths. No extra abstractions added.\n\nF4 - Annotation assertions: ExternallyManaged tests now assert the actual distribution path (test-stack/distribution), that owned vs imported guidance differ, and that each message is actionable (principal, condition, remedy). Generic single-word assertions removed.\n\nF5 - Same origin reused across distributions: new WithOriginAccessControl_SameOriginInstanceAcrossDistributions_ShouldScopeEachGrant reuses one IOrigin instance in two distributions and verifies two OACs, two endpoint-scoped aws:SourceArn statements (distinct distributions), one owning AWS::Lambda::ResourcePolicy, and no construct-id collision.\n\nValidation evidence:\n- dotnet build LayeredCraft.Cdk.Constructs.slnx -c Release: 0 warnings, 0 errors.\n- Full suite: total 1904, failed 0, skipped 0 (476 x net8.0/9.0/10.0/11.0).\n- Focused: WebFunctionOriginTests 25/25; WebFunctionConstructGoldenTemplateTests 8/8; ExistingConstructsGoldenTemplateTests 17/17.\n- The 17 original existing-construct goldens are byte-identical. The new web-function-cloudfront-oac.json golden was NOT changed by these corrections (no intentional change; the corrections do not alter the synthesized OAC/IAM for the same-stack Automatic path).\n\nCDK compatibility fact (IOrigin.Bind exception behavior): new HttpOrigin(domainName, props) validates synchronously at construction and throws System.Exception (jsii-wrapped). Ranges: connectionAttempts 1-3; connectionTimeout 1-10 seconds; readTimeout/keepaliveTimeout 1-60 seconds. This is why F1 validation is possible at factory time.\n\nFollow-ups recorded on existing beads (no new bead created, T4 not reopened):\n- T6a (cdkc-18e.9) / T6b (cdkc-18e.10): document that errors thrown during IOrigin.Bind cross the jsii boundary and surface to .NET callers as System.Exception (with the original message), while factory-time validation throws InvalidOperationException directly.\n- T7c (cdkc-18e.13): validate OAC naming across AWS Regions and the potential account-global naming collision.","spec_id":"docs/designs/lambda-web-functions-integration.md","status":"closed","priority":1,"issue_type":"task","assignee":"Nick Cipollina","owner":"ncipollina@gmail.com","created_at":"2026-10-23T01:14:51Z","created_by":"Nick Cipollina","updated_at":"2026-10-23T15:33:34Z","started_at":"2026-10-23T14:51:32Z","closed_at":"2026-10-23T15:02:51Z","close_reason":"T4 complete: WebFunctionOrigin OAC/non-OAC factories, FunctionUrlOriginAccessControl (sigv4/sigv4a), automatic same-stack CloudFront invoke grants, ExternallyManaged/imported/cross-stack handling, 20 new synthesis tests + 1 golden; 1884 tests pass on 4 TFMs; 17 original goldens unchanged.","external_ref":"gh-98","labels":["cloudfront","lambda-web-functions","security","t4"],"dependencies":[{"issue_id":"cdkc-18e.6","depends_on_id":"cdkc-18e","type":"parent-child","created_at":"2026-10-23T01:14:51Z","created_by":"Nick Cipollina","metadata":"{}"},{"issue_id":"cdkc-18e.6","depends_on_id":"cdkc-18e.15","type":"blocks","created_at":"2026-10-23T12:49:06Z","created_by":"Nick Cipollina","metadata":"{}"},{"issue_id":"cdkc-18e.6","depends_on_id":"cdkc-18e.4","type":"blocks","created_at":"2026-10-23T01:15:12Z","created_by":"Nick Cipollina","metadata":"{}"},{"issue_id":"cdkc-18e.6","depends_on_id":"cdkc-18e.5","type":"blocks","created_at":"2026-10-23T01:15:13Z","created_by":"Nick Cipollina","metadata":"{}"}],"dependency_count":3,"dependent_count":4,"comment_count":0} +{"_type":"issue","id":"cdkc-18e.5","title":"T3b: Implement GrantInvoke (revision-3 account rules) and endpoint imports","description":"Purpose: GrantInvoke with the revision-3 account-establishment rules, and limited endpoint imports. Design §8.4 (IWebFunctionEndpoint, FromEndpointAttributes, ownership semantics), §10.1, §10.2 (AUTHORITATIVE algorithm + table), §14, §15 (IAM matrix).\n\nCRITICAL: implement §10.2 revision 3 exactly. Do NOT use Grant.AddToPrincipalOrResource and do NOT rely on Grant.Success/AssertSuccess\n(verified CDK pitfall: success only checks that a statement object exists). Compose Grant.AddToPrincipal / Grant.AddStatementToResourcePolicy, check StatementAdded yourself,\nand return Grant.Combine of statements actually written.\n\nDeliverables:\n- IWebFunctionEndpoint : IResource with EndpointName, EndpointArn, DomainName, Url, AuthType, EndpointType, GrantInvoke(IGrantable), GrantInvoke(IGrantable, WebFunctionInvokeGrantOptions), GrantCloudFrontInvoke(string).\n WebFunctionEndpointConstruct implements it.\n- GrantInvoke algorithm (§10.2): throw for ApplicationManaged; identity side ONLY when the account is established:\n E1 = grant principal is an owned construct (Resource.IsOwnedResource) whose stack account is not literally different from the endpoint stack's;\n E2 = imported principal with literal PrincipalAccount equal (TokenComparison.SAME) to the literal endpoint stack account.\n Resource side when: identity side not written for an established same-account immutable role; service principal; or CallerPolicy = ExternallyManaged.\n Under Automatic, fail with InvalidOperationException (grantee, endpoint, reason, two remedies) for: imported principals with any unresolved account (ONE_ or BOTH_UNRESOLVED),\n different literal account, AccountPrincipal/ArnPrincipal. ExternallyManaged never writes identity policy and adds an Annotations info naming the required caller-side identity policy.\n- WebFunctionEndpointConstruct.FromEndpointAttributes(scope, id, WebFunctionEndpointAttributes) → IWebFunctionEndpoint that owns nothing: identity grants for established (E1/E2) grantees only;\n any grant requiring the resource policy, ExternallyManaged grants, and GrantCloudFrontInvoke throw (\"resource policy of an imported endpoint is externally owned\").\n Parse endpoint name/account/region from a literal ARN; token ARN ⇒ unresolved account (only E1 grantees can be granted).\n\nTests (one per §10.2 table row + §15 IAM bullets): E1 role/Function/WebFunctionConstruct (incl. env-agnostic stacks) → identity statement on the specific endpoint ARN only, no ResourcePolicy;\nE2 mutable → attached policy; E2 Mutable=false → resource statement only (imported endpoint throws); imported role with token ARN or env-agnostic stack under Automatic → throws AND no AWS::IAM::Policy synthesized;\nsame under ExternallyManaged → resource statement + annotation; different literal account Automatic throws / ExternallyManaged resource-only with no principal statements in returned Grant;\nservice principal → resource only; Account/ArnPrincipal Automatic throws / ExternallyManaged resource-only; ExternallyManaged with E1 → resource only; ApplicationManaged throws;\nimported endpoint ExternallyManaged throws; regression test with a fake IResourceWithPolicy returning StatementAdded=false → GrantInvoke throws.\nGolden template: cross-account ExternallyManaged grant + same-account grant.\n\nExclusions: WebFunctionOrigin, Testing helpers, docs. Do not change resource-policy ownership semantics from the previous bead.\nSecurity: never synthesize an identity policy for a principal whose account is not established; never report partial cross-account configuration as complete.\n","acceptance_criteria":"- GrantInvoke implements §10.2 revision 3 exactly; no use of AddToPrincipalOrResource, Grant.Success, or AssertSuccess in the implementation (code review check).\n- Every §10.2 table row has a passing test, including the \"no AWS::IAM::Policy synthesized\" check for unresolved imported roles and the StatementAdded=false regression.\n- FromEndpointAttributes returns an endpoint with the documented limited capabilities and clear exceptions.\n- ExternallyManaged emits the info annotation; Automatic failures name grantee, endpoint, reason, and remedies.\n- Golden templates unchanged except the new one; validation gates pass.","notes":"T3b IMPLEMENTED (GrantInvoke revision-3 account rules + endpoint imports). Not committed per task restriction.\n\nFILES: NEW src/LayeredCraft.Cdk.Constructs/Models/WebFunctionEndpoint.cs (public interface IWebFunctionEndpoint : IResource with EndpointName/EndpointArn/DomainName/Url/AuthType/EndpointType + GrantInvoke(IGrantable), GrantInvoke(IGrantable,WebFunctionInvokeGrantOptions), GrantCloudFrontInvoke(string)); NEW src/.../WebFunctionGrants.cs (internal static helper: InvokeAction const, GrantInvoke(...), internal AddResourceStatement(...), private IsEstablished/IdentityPolicyCanBeWritten/Describe); NEW src/.../WebFunctionImportedEndpoint.cs (internal sealed Resource, IWebFunctionEndpoint - owns nothing); MODIFIED src/.../WebFunctionEndpointConstruct.cs (now : Resource, IWebFunctionEndpoint, IResourceWithPolicyV2; added GrantInvoke overloads + static FromEndpointAttributes); NEW test/.../WebFunctionInvokeGrantTests.cs (22 tests); MODIFIED test/.../WebFunctionConstructGoldenTemplateTests.cs (+WebFunction_InvokeGrants_ShouldMatchGoldenTemplate); NEW GoldenTemplates/web-function-invoke-grants.json. No existing construct modified.\n\nGRANTINVOKE ACCOUNT CLASSIFICATION (design 10.2 rev 3): E1 owned principal (Resource.IsOwnedResource(grantPrincipal as IConstruct)) with compatible account -\u003e identity policy via Grant.AddToPrincipal (scoped to exact endpoint ARN); E2 imported principal with literal PrincipalAccount == literal endpoint account -\u003e identity if writable; service principal -\u003e resource-policy statement; any other not-established Automatic grantee -\u003e InvalidOperationException naming grantee/endpoint + two remedies; ExternallyManaged -\u003e resource-policy statement only + Annotations info, never identity. NEVER uses Grant.AddToPrincipalOrResource, Grant.Success, or AssertSuccess.\n\nKEY CORRECTNESS FINDING (fixed): Role.FromRoleArn(..., Mutable=false) returns an ImmutableRole whose AddToPrincipalPolicy returns StatementAdded=true while writing NOTHING (CDK pretendSuccess = !addGrantsToResources). Grant.AddToPrincipal therefore reports a non-empty PrincipalStatements for an immutable imported role, so trusting PrincipalStatements.Length caused a SILENT NO-OP (no identity, no resource statement). Detection now probes grantee.GrantPrincipal.AddToPrincipalPolicy(principal-less statement) and treats the identity as written only when result.StatementAdded \u0026\u0026 result.PolicyDependable is IConstruct (a real Policy for a mutable imported role; a bare DependencyGroup for an immutable one). Mutable vs immutable imported roles are otherwise indistinguishable from .NET (both surface as IRole+_Proxy / IPrincipal+_Proxy; IsOwnedResource false), so this PolicyDependable check is the reliable signal. The probe's extra statement is deduplicated by PolicyDocument at resolution.\n\nENDPOINT IMPORTS: WebFunctionEndpointConstruct.FromEndpointAttributes(scope,id,WebFunctionEndpointAttributes) returns an internal WebFunctionImportedEndpoint (owns no resources) exposing EndpointArn/DomainName/Url/AuthType/EndpointType and EndpointName/account parsed from a literal ARN (token ARN -\u003e unresolved account). It writes identity policies only for established E1/E2 grantees and throws InvalidOperationException for GrantCloudFrontInvoke and for any grant requiring the resource policy ('externally owned'). T3a single-resource-policy guarantees intact (exactly one lazily-created AWS::Lambda::ResourcePolicy per function).\n\nTESTS: 22 WebFunctionInvokeGrantTests cover every 10.2 matrix row (E1 owned Role/WebFunction + env-agnostic stacks; E2 mutable literal-equal -\u003e 1 AWS::IAM::Policy; E2 immutable -\u003e resource statement only; unresolved/different-account imported roles -\u003e throw with no AWS::IAM::Policy; ExternallyManaged -\u003e resource statement + no identity; service/account/arn principals; ApplicationManaged -\u003e throws; imported endpoint ExternallyManaged/GrantCloudFrontInvoke -\u003e throws; endpoint-scoped statements across multiple endpoints; StatementAdded=false regression via a fake IResourceWithPolicyV2; FromEndpointAttributes capabilities; IWebFunctionEndpoint assignability). New golden web-function-invoke-grants.json = same-account E1 identity grant + cross-account ExternallyManaged resource grant.\n\nRESULTS (JSII_SILENCE_WARNING_UNTESTED_NODE_VERSION=1, -c Release): src build 0 warnings/0 errors. Full suite dotnet test --solution LayeredCraft.Cdk.Constructs.slnx -c Release -\u003e 1556 passed / 0 failed / 0 skipped (389 x net8.0/net9.0/net10.0/net11.0; prior 1464; +23/TFM). Golden tests: 24 total zero-diff (23 pre-existing UNCHANGED + 1 new). No existing golden modified.\n\nDEVIATIONS: none new. IWebFunctionEndpoint is a new public interface; IResourceWithPolicyV2 (T3a deviation) retained. Temporary probe files deleted (no Zz*.cs remain).","spec_id":"docs/designs/lambda-web-functions-integration.md","status":"closed","priority":1,"issue_type":"task","assignee":"Nick Cipollina","owner":"ncipollina@gmail.com","created_at":"2026-10-23T01:14:50Z","created_by":"Nick Cipollina","updated_at":"2026-10-23T12:16:25Z","started_at":"2026-10-23T11:58:18Z","closed_at":"2026-10-23T12:16:25Z","close_reason":"T3b complete: GrantInvoke(IGrantable) + GrantInvoke(IGrantable, WebFunctionInvokeGrantOptions) with revision-3 account rules (E1 owned identity; E2 imported same-account identity when writable; service principal -\u003e resource policy; unestablished Automatic -\u003e clear synthesis failure; ExternallyManaged -\u003e resource statement + annotation, never identity), plus WebFunctionEndpointConstruct.FromEndpointAttributes importing endpoints that own nothing. Fixed the ImmutableRole pretendSuccess pitfall by detecting real identity writes via AddToPrincipalPolicyResult.PolicyDependable is IConstruct. Added public IWebFunctionEndpoint and internal WebFunctionGrants/WebFunctionImportedEndpoint. Never uses Grant.AddToPrincipalOrResource/Grant.Success/AssertSuccess. Build 0 warnings/0 errors; full suite 1556/1556 across net8.0/9.0/10.0/11.0 (+23/TFM); 24 golden tests zero-diff (23 existing unchanged + 1 new). No existing construct modified.","external_ref":"gh-98","labels":["iam","lambda-web-functions","security","t3"],"dependencies":[{"issue_id":"cdkc-18e.5","depends_on_id":"cdkc-18e","type":"parent-child","created_at":"2026-10-23T01:14:50Z","created_by":"Nick Cipollina","metadata":"{}"},{"issue_id":"cdkc-18e.5","depends_on_id":"cdkc-18e.4","type":"blocks","created_at":"2026-10-23T01:15:12Z","created_by":"Nick Cipollina","metadata":"{}"}],"dependency_count":1,"dependent_count":3,"comment_count":0} +{"_type":"issue","id":"cdkc-18e.4","title":"T3a: Add AddEndpoint, single-owner resource policy, and GrantCloudFrontInvoke","description":"Purpose: multiple endpoints and the single-owner resource policy. Design §8.3 (AddEndpoint), §8.4, §10.3, §12.2–§12.3, §14, §15 (Resource-policy ownership).\n\nDeliverables:\n- WebFunctionConstruct.AddEndpoint(string id, IWebFunctionEndpointOptions): validates unique EndpointName per function (a second \"default\" is a duplicate → InvalidOperationException);\n every endpoint routes 100% to the current revision; returns WebFunctionEndpointConstruct; Endpoints list includes default + added.\n- Single-owner resource policy (private to WebFunctionConstruct): lazily create one CfnResourcePolicy child \"ResourcePolicy\" (ResourceArn = function GetAtt FunctionArn,\n PolicyDocument = an iam.PolicyDocument) on first contribution; later contributions AddStatements to the same document. No resource when there are no statements.\n WebFunctionConstruct must NOT expose a public AddToResourcePolicy.\n- WebFunctionEndpointConstruct implements IResourceWithPolicy: AddToResourcePolicy(statement) requires statement Resources to be exactly this endpoint's ARN (else ArgumentException) and forwards to the function's policy.\n- GrantCloudFrontInvoke(string distributionArn): adds {Principal cloudfront.amazonaws.com, Action lambda:InvokeWebFunctionEndpoint, Resource endpoint ARN,\n Condition StringEquals aws:SourceArn = distributionArn}; accepts tokens or literals; throws for ApplicationManaged. Identical statements deduplicate (verify PolicyDocument behavior in a test).\n\nTests: no statements → no ResourcePolicy; many contributions → exactly one; multiple distributions/endpoints → all statements, each scoped to the correct endpoint ARN;\ndifferent contribution orders → equal statement sets; repeated grants → no duplicates; foreign Resource → throws; ApplicationManaged → throws;\nmultiple endpoints with different auth types synthesize correctly; duplicate endpoint names rejected; API-surface test that WebFunctionConstruct has no public AddToResourcePolicy.\nAdd a golden template: two endpoints (IamAuth + ApplicationManaged) with two explicit CloudFront grants.\n\nExclusions: GrantInvoke, imports (FromEndpointAttributes), WebFunctionOrigin, Testing helpers, docs.\nSecurity: never emit wildcard endpoint resources (endpoint/*) or unscoped CloudFront principals.\n","acceptance_criteria":"- AddEndpoint works with unique-name validation; all endpoints weight 100 to the current revision.\n- At most one AWS::Lambda::ResourcePolicy per function, created only when a statement exists; all contributions preserved; duplicates removed.\n- Endpoint-scoped AddToResourcePolicy and GrantCloudFrontInvoke behave per §8.4/§10.3, including negatives.\n- No public AddToResourcePolicy on WebFunctionConstruct.\n- New golden template added; all existing goldens unchanged; validation gates pass.","notes":"T3a IMPLEMENTED (AddEndpoint + single-owner resource policy + endpoint AddToResourcePolicy + GrantCloudFrontInvoke). Not committed per task restriction.\n\nDELIVERABLES:\n- WebFunctionConstruct.AddEndpoint(string id, IWebFunctionEndpointOptions options): ArgumentNullException on null id/options; per-function EndpointName uniqueness via HashSet(StringComparer.Ordinal) seeded with the default endpoint's name -\u003e duplicate (incl. a second 'default') throws InvalidOperationException; returns the endpoint created by the shared private CreateEndpoint (news WebFunctionEndpointConstruct, adds endpoint.CfnEndpoint.AddResourceDependency(revision), appends to the list). New public IReadOnlyList\u003cWebFunctionEndpointConstruct\u003e Endpoints reflects default + added endpoints, in creation order. Every endpoint routes RevisionWeights=[{current revision, 100}].\n- Single-owner resource policy (private to WebFunctionConstruct, NO public AddToResourcePolicy): AddResourcePolicyStatement(statement) lazily creates ONE iam.PolicyDocument and ONE Amazon.CDK.AWS.Lambda.CfnResourcePolicy child id 'ResourcePolicy' (ResourceArn = Function GetAtt FunctionArn, PolicyDocument = the shared document). No statements =\u003e no AWS::Lambda::ResourcePolicy resource. Later contributions AddStatements to the same document; all preserved; identical statements deduplicate at PolicyDocument resolution (verified: 2 identical grants -\u003e 1 statement).\n- WebFunctionEndpointConstruct now : Resource, IResourceWithPolicyV2 and implements AddToResourcePolicy(statement): requires statement.Resources length == 1 and string-equals this endpoint's EndpointArn (ArgumentNullException on null; ArgumentException for foreign resource, another endpoint, the whole function, or wildcard) and forwards to the function policy; returns AddToResourcePolicyResult{StatementAdded=true, PolicyDependable=the policy}.\n- GrantCloudFrontInvoke(string distributionArn): InvalidOperationException when AuthType != IamAuth (ApplicationManaged rejected); ArgumentNullException on null; literal ARNs validated (token-aware: unresolved tokens skipped); emits {Effect Allow, Principal Service cloudfront.amazonaws.com, Action lambda:InvokeWebFunctionEndpoint, Resource = endpoint ARN, Condition StringEquals aws:SourceArn = distributionArn} -\u003e endpoint AddToResourcePolicy. Repeated equivalent grants deduplicate. Never creates/modifies a Distribution.\n\nDEViation (mechanical, contract-identical; reported): the design named IResourceWithPolicy, but that interface is DEPRECATED in CDK 2.274 ('prefer IResourceWithPolicyV2'). Implemented the non-deprecated Amazon.CDK.AWS.IAM.IResourceWithPolicyV2 instead. Because its AddToResourcePolicy returns IAddToResourcePolicyResult (not the concrete AddToResourcePolicyResult), the public method keeps the concrete return type and the interface is satisfied by an explicit implementation that forwards to it. src build stays at 0 warnings.\n\nNEW TESTS/GOLDEN: test/.../WebFunctionResourcePolicyTests.cs (19 tests: no-statements -\u003e no policy; single grant -\u003e one policy with correct ResourceArn/Principal/Action/Condition/Resource; two distributions -\u003e 2 statements / 1 policy; repeated grant -\u003e dedup to 1; order-independence; two endpoints -\u003e 1 policy / 2 statements scoped to 2 distinct endpoint ARNs; ApplicationManaged -\u003e throws; invalid literal ARNs (non-ARN, lambda function ARN, truncated cloudfront) -\u003e ArgumentException; token ARN accepted; foreign/wildcard Resource -\u003e ArgumentException; endpoint.EndpointArn accepted; duplicate endpoint names -\u003e InvalidOperationException; Endpoints + per-endpoint weight-100 assertions; API-surface reflection proving WebFunctionConstruct has no public AddToResourcePolicy; IResourceWithPolicyV2 assignability). New golden web-function-multi-endpoint.json (two endpoints IamAuth + ApplicationManaged, two CloudFront grants -\u003e exactly ONE AWS::Lambda::ResourcePolicy with two SourceArn-scoped statements). Infrastructure: WebFunctionValidation.ValidateCloudFrontDistributionArn added; regex ^arn:[a-z0-9-]+:cloudfront::[0-9]{12}:distribution/[A-Za-z0-9]+$.\n\nRESULTS (JSII_SILENCE_WARNING_UNTESTED_NODE_VERSION=1, -c Release): src build 0 warnings/0 errors on net8.0/9.0/10.0/11.0; full solution suite 1464 passed / 0 failed / 0 skipped (366 x 4 TFMs; prior baseline 1384, +20 tests/TFM = 19 resource-policy + 1 golden); all 22 pre-existing golden templates UNCHANGED (only the new web-function-multi-endpoint.json added; 23 total). No existing construct modified. No new dependencies. Coverage: no local script; CI gate 80% (external devops template); changes additive and covered.\n\nACCEPTANCE: AddEndpoint unique-name validation + every endpoint weight 100; exactly one AWS::Lambda::ResourcePolicy per function created only when a statement exists, all contributions preserved, duplicates removed; endpoint-scoped AddToResourcePolicy and GrantCloudFrontInvoke per section 8.4/10.3 including negatives; no public AddToResourcePolicy on WebFunctionConstruct; new golden added, existing goldens unchanged; validation gates pass. T3b items (GrantInvoke, endpoint imports) intentionally NOT implemented.","spec_id":"docs/designs/lambda-web-functions-integration.md","status":"closed","priority":1,"issue_type":"task","owner":"ncipollina@gmail.com","created_at":"2026-10-23T01:14:49Z","created_by":"Nick Cipollina","updated_at":"2026-10-23T11:47:39Z","closed_at":"2026-10-23T11:47:39Z","close_reason":"T3a complete: AddEndpoint with per-function endpoint-name uniqueness (duplicate incl. second default rejected); Endpoints collection; single lazily-created AWS::Lambda::ResourcePolicy per function (no resource when no statements, all contributions preserved, identical statements deduplicated via PolicyDocument); endpoint-scoped IResourceWithPolicyV2.AddToResourcePolicy (foreign/wildcard resource rejected); GrantCloudFrontInvoke (cloudfront.amazonaws.com, lambda:InvokeWebFunctionEndpoint, StringEquals aws:SourceArn, endpoint-only resource, token-aware ARN validation, ApplicationManaged rejected, dedup). One reported mechanical deviation: IResourceWithPolicy is deprecated in CDK 2.274 -\u003e implemented IResourceWithPolicyV2 with an explicit interface forwarder. Build 0 warnings/0 errors; full suite 1464/1464 passed across net8.0/9.0/10.0/11.0 (+20 tests/TFM); 22 existing goldens unchanged + 1 new multi-endpoint golden. No existing construct modified.","external_ref":"gh-98","labels":["iam","lambda-web-functions","t3"],"dependencies":[{"issue_id":"cdkc-18e.4","depends_on_id":"cdkc-18e","type":"parent-child","created_at":"2026-10-23T01:14:49Z","created_by":"Nick Cipollina","metadata":"{}"},{"issue_id":"cdkc-18e.4","depends_on_id":"cdkc-18e.3","type":"blocks","created_at":"2026-10-23T01:15:11Z","created_by":"Nick Cipollina","metadata":"{}"}],"dependency_count":1,"dependent_count":2,"comment_count":0} +{"_type":"issue","id":"cdkc-18e.3","title":"T2: Implement core WebFunctionConstruct (function, revision, default endpoint, role, logs, code bucket)","description":"Purpose: the core L3 construct that owns one Web Function lifecycle. Design §7, §8.2 (bucket statement), §8.3, §12.1, §12.2, §12.4, §14, §15 (Synthesis/template, Code bucket).\n\nDeliverables:\n- WebFunctionConstruct : Construct, IGrantable (src/LayeredCraft.Cdk.Constructs/WebFunctionConstruct.cs) creating, with these STABLE child IDs:\n \"Function\" (CfnWebFunction; set Node.DefaultChild), \"Revision\" (CfnWebFunctionRevision), \"DefaultEndpoint\" (WebFunctionEndpointConstruct whose L1 child is \"Resource\"),\n \"ExecutionRole\" (only when props.Role is null; AWSLambdaBasicExecutionRole), \"LogGroup\" (only for WebFunctionLogs.Create; name /aws/lambda/web/{FunctionName}).\n- Pass the LITERAL FunctionName (not Ref/ARN) to Revision.FunctionName and Endpoint.FunctionName; add explicit AddResourceDependency function←revision←endpoint (§8.3 notes, §12.4).\n- Revision: S3Object {Bucket, Key, VersionId?}; RuntimeConfig.Runtime; ServiceConfig {ExecutionRoleArn, EnvironmentVariables (+ AWS_LAMBDA_NODEJS_ENTRYPOINT from EntryPoint),\n TimeoutSeconds, MaxConcurrencyPerEnvironment, TelemetryConfig.LoggingConfig {LogGroup (Create/Use only), ApplicationLogLevel, SystemLogLevel}}; Description. No KmsKeyArn.\n- WebFunctionLogs.Use(group): pass name; logGroup.GrantWrite(role) only when the name is outside /aws/lambda/*.\n- WebFunctionEndpointConstruct (src/.../WebFunctionEndpointConstruct.cs): Amazon.CDK.Resource subclass, internal ctor, exposes EndpointName, EndpointArn, DomainName,\n Url (\"https://\"+DomainName), AuthType, EndpointType, Regions, WebFunction. Endpoint L1: AuthType, EndpointName, EndpointType, Regions, RevisionWeights=[{current revision, 100}],\n ScalingConfig/ThrottleConfig only when set, Description. (Grants/policy/AddEndpoint come in later beads; do not stub public members that later beads own unless needed to compile.)\n- Code binding: WebFunctionCode.FromBucket.Bind implementation:\n * Automatic: add the least-privilege statement from §8.2 (lambda.amazonaws.com, s3:GetObject+s3:GetObjectVersion on the object ARN, StringEquals aws:SourceAccount,\n ArnLike aws:SourceArn arn:{partition}:lambda:{region}:{account}:web-function/{FunctionName}/revision/* using the FUNCTION stack's account/region);\n fail (InvalidOperationException) if AddToResourcePolicy returns StatementAdded=false; add revision dependency on the policy dependable.\n * Owned Bucket L2 created in the app: fail if versioning is not enabled or encryption is KMS_MANAGED/DSSE_MANAGED (inspect the owned bucket's CfnBucket; imported buckets are not inspected).\n * Owned bucket in another stack while the function stack's account/region is unresolved → fail.\n * ExternallyManaged: add nothing.\n- Golden templates (using the T0 harness) for: single IamAuth function with defaults; ApplicationManaged with ServiceDefault logs; Use(logGroup) + supplied role; Automatic owned bucket; ExternallyManaged imported bucket.\n\nTests (§15): template assertions for every property above, defaults, DependsOn chain, literal FunctionName on all three, no KmsKeyArn, log group variants, role variants, code-bucket matrix, and §14 construct-level negatives.\nExclusions: AddEndpoint, resource policy, GrantInvoke, GrantCloudFrontInvoke, imports, CloudFront, Testing namespace helpers, docs. No changes to existing constructs.\nSecurity: never grant s3 read beyond the single object key and the /revision/* SourceArn pattern.\n","acceptance_criteria":"- Child IDs exactly Function, Revision, DefaultEndpoint(/Resource), ExecutionRole, LogGroup; Node.DefaultChild is the CfnWebFunction.\n- Revision and endpoint receive the literal FunctionName and explicit DependsOn edges (asserted).\n- Default log group /aws/lambda/web/{name}, 14 days, Delete; ServiceDefault creates none and omits LoggingConfig.LogGroup; Use() creates none.\n- Code-bucket Automatic/ExternallyManaged/owned-validation/cross-stack matrix implemented and tested, statement matches §8.2 exactly.\n- WebFunctionConstruct.GrantPrincipal is the execution role (e.g. table.GrantReadData(webFunction) works; tested).\n- New golden templates added; existing golden templates unchanged.\n- Validation gates pass.","notes":"T2 IMPLEMENTED (core WebFunctionConstruct). Not committed per task restriction.\n\nDELIVERABLES:\n- src/.../WebFunctionConstruct.cs (NEW): public sealed class WebFunctionConstruct : Construct, IGrantable. Validates FunctionName/Timeout/MaxConcurrencyPerEnvironment/EnvironmentVariables/EntryPoint via WebFunctionValidation; creates stable children Function (CfnWebFunction, Node.DefaultChild), Revision (CfnWebFunctionRevision), DefaultEndpoint (WebFunctionEndpointConstruct), ExecutionRole (only when props.Role is null; AWSLambdaBasicExecutionRole), LogGroup (only for WebFunctionLogs.Create). Public: FunctionName, FunctionArn, RevisionId, RevisionArn, Role, GrantPrincipal (=Role.GrantPrincipal), LogGroup (null for ServiceDefault), DefaultEndpoint. Revision ServiceConfig carries ExecutionRoleArn, EnvironmentVariables (+ AWS_LAMBDA_NODEJS_ENTRYPOINT from EntryPoint), TimeoutSeconds, MaxConcurrencyPerEnvironment, TelemetryConfig.LoggingConfig{LogGroup,ApplicationLogLevel,SystemLogLevel}; no KmsKeyArn. FunctionName passed LITERAL to Revision and Endpoint. Explicit deps: Revision.AddResourceDependency(Function); Revision.Node.AddDependency(Role/created LogGroup/bucket PolicyDependable); endpoint.AddResourceDependency(Revision).\n- src/.../WebFunctionEndpointConstruct.cs (NEW): public sealed class WebFunctionEndpointConstruct : Resource; internal ctor (scope,id,webFunction,options); validates EndpointName/Regions(homeRegion=Stack.Of(function).Region)/MaxEnvironments/RateLimit; creates the L1 child id 'Resource' (CfnWebFunctionEndpoint) and sets Node.DefaultChild; exposes WebFunction, EndpointName, AuthType, EndpointType, Regions, EndpointArn, DomainName, Url. ScalingConfig/ThrottleConfig emitted only when set; RevisionWeights=[{current RevisionId, 100}].\n- src/.../Models/WebFunctionCode.cs (MODIFIED, T2-owned completion): added internal abstract WebFunctionCodeConfig Bind(WebFunctionConstruct) on WebFunctionCode + override in WebFunctionCodeFromBucket; automatic bucket policy per design §8.2 EXACTLY (lambda.amazonaws.com; s3:GetObject,s3:GetObjectVersion; Resource arn:{partition}:s3:::{bucket}/{key}; StringEquals aws:SourceAccount; ArnLike aws:SourceArn arn:{partition}:lambda:{region}:{account}:web-function/{FunctionName}/revision/*; partition/account/region from the FUNCTION stack); StatementAdded=false -\u003e InvalidOperationException; ExternallyManaged -\u003e no statement; owned bucket validated (versioning required; AWS-managed KMS aws/s3 or DSSE rejected), imported buckets not inspected; owned bucket in another stack while function stack account/Region unresolved -\u003e InvalidOperationException; revision depends on result.PolicyDependable.\n- src/.../Models/WebFunctionCodeConfig.cs (NEW): internal sealed config {Bucket,Key,VersionId,PolicyDependable}.\n\nFILES: src: WebFunctionConstruct.cs, WebFunctionEndpointConstruct.cs, Models/WebFunctionCode.cs (mod), Models/WebFunctionCodeConfig.cs; tests: WebFunctionConstructTests.cs (45 cases), WebFunctionConstructGoldenTemplateTests.cs (5 goldens); GoldenTemplates: web-function-default / -application-managed / -use-log-group / -owned-bucket / -externally-managed .json. No existing construct changed. No new dependencies.\n\nIMPLEMENTATION FINDING (not a public API deviation): the S3 Bucket L2 sets VersioningConfiguration/BucketEncryption from JavaScript, so the CLR getters expose a JSII AnonymousObject and typed casts to CfnBucket.*Property return null. Owned-bucket inspection therefore reads the values via Stack.Of(bucket).Resolve(...) (plain camelCase dictionaries: 'status', 'serverSideEncryptionConfiguration'[].'serverSideEncryptionByDefault'.'sseAlgorithm'/'kmsMasterKeyId'). Verified empirically: Versioned=true -\u003e {'status':'Enabled'}; KMS_MANAGED -\u003e {'sseAlgorithm':'aws:kms'} (no key) -\u003e rejected; DSSE_MANAGED -\u003e {'sseAlgorithm':'aws:kms:dsse'} -\u003e rejected; default S3-managed bucket emits no BucketEncryption -\u003e allowed.\n\n§18 OPEN QUESTION 5 RESULT: ScalingConfig/ThrottleConfig are emitted only when MaxEnvironments/RateLimit are set (asserted by Construct_ShouldOmitScalingAndThrottleWhenUnset). CloudFormation update semantics are 'omit = keep existing value', so removing these values after a deployment would NOT clear them via omission; clearing would require explicitly sending an empty object. Whether CloudFormation accepts an empty ScalingConfig/ThrottleConfig sub-object is NOT verified (no deploy performed; deploy verification is deferred to T7 per design). Recommendation: document the clear-via-explicit-empty-object requirement and confirm in the T7 sandbox.\n\nTESTS/RESULTS (JSII_SILENCE_WARNING_UNTESTED_NODE_VERSION=1, -c Release):\n- dotnet build LayeredCraft.Cdk.Constructs.slnx -c Release -\u003e Build succeeded, 0 warnings, 0 errors.\n- New behavior suite: 45 tests pass (construct/revision/default endpoint, stable logical ids, literal FunctionName on all three, DependsOn chain, runtime nodejs24.x, S3Object with/without VersionId, env vars incl AWS_LAMBDA_NODEJS_ENTRYPOINT, timeout/concurrency/no KmsKeyArn, default+supplied role, three logging modes + GrantWrite only outside /aws/lambda/*, endpoint name/type/Regions/AuthType/scaling/throttle present-absent/revision-weight-100, GrantPrincipal=dynamodb:GetItem via table.GrantReadData, bucket matrix incl. imported+Automatic throw, ExternallyManaged no-policy, unversioned/KMS_MANAGED/cross-stack throws, token FunctionName allowed, all §14 construct negatives).\n- Golden suite: 22/22 pass with ZERO diff (17 pre-existing UNCHANGED + 5 new Web Function goldens).\n- Full solution: dotnet test --solution LayeredCraft.Cdk.Constructs.slnx -c Release -\u003e 1384 passed / 0 failed / 0 skipped (346 x net8.0/net9.0/net10.0/net11.0); prior baseline 1184; +50 tests/TFM.\n- Coverage: no local script; CI gate 80% (external devops template); src changes are additive and covered by the new tests.\n\nACCEPTANCE: all child IDs stable; DefaultChild=CfnWebFunction; literal FunctionName + DependsOn asserted; logging modes asserted; bucket-policy matrix implemented + tested; GrantPrincipal is the execution role; new goldens added, existing unchanged; no existing construct modified.","spec_id":"docs/designs/lambda-web-functions-integration.md","status":"closed","priority":1,"issue_type":"task","assignee":"Nick Cipollina","owner":"ncipollina@gmail.com","created_at":"2026-10-23T01:14:48Z","created_by":"Nick Cipollina","updated_at":"2026-10-23T02:40:48Z","started_at":"2026-10-23T01:55:28Z","closed_at":"2026-10-23T02:40:48Z","close_reason":"T2 complete: core WebFunctionConstruct (Function/Revision/DefaultEndpoint/ExecutionRole/LogGroup with stable ids), WebFunctionEndpointConstruct (L1 child 'Resource', Node.DefaultChild, revision weight 100, scaling/throttle only when set), and the WebFunctionCode.Bind artifact seam (automatic/external bucket policy per §8.2, versioning + AWS-managed-KMS rejection on owned buckets, cross-stack unresolved-env failure, revision depends on PolicyDependable). Literal FunctionName + explicit DependsOn chain; no revision KMS. Build 0 warnings/0 errors; full suite 1384/1384 passed across net8.0/9.0/10.0/11.0 (+50 tests/TFM); 22/22 golden tests zero-diff (17 existing unchanged + 5 new). GrantPrincipal is the execution role. No existing construct modified. §18 Q5: omit=keep confirmed by design of our output; clearing needs explicit empty objects, deploy verification deferred to T7.","external_ref":"gh-98","labels":["core","lambda-web-functions","t2"],"dependencies":[{"issue_id":"cdkc-18e.3","depends_on_id":"cdkc-18e","type":"parent-child","created_at":"2026-10-23T01:14:48Z","created_by":"Nick Cipollina","metadata":"{}"},{"issue_id":"cdkc-18e.3","depends_on_id":"cdkc-18e.2","type":"blocks","created_at":"2026-10-23T01:15:10Z","created_by":"Nick Cipollina","metadata":"{}"}],"dependency_count":1,"dependent_count":2,"comment_count":0} +{"_type":"issue","id":"cdkc-18e.2","title":"T1: Add Web Function public models, options, and value validation","description":"Purpose: introduce the public model/value types every later bead consumes, with value validation. Design §8.1, §8.2, §8.3 (props + WebFunctionLogs), §8.4 (options/attributes), §8.5 (origin props), §8.7, §10.2 (WebFunctionCallerPolicy, WebFunctionInvokeGrantOptions), §14.\n\nDeliverables (namespace LayeredCraft.Cdk.Constructs.Models unless noted; follow the newest Cognito style: get-only interfaces + init-only sealed records, XML docs):\n- Enums: WebFunctionAuthType {IamAuth, ApplicationManaged}; WebFunctionEndpointType {HomeRegion, MultiRegion, PerRegion};\n WebFunctionCodeBucketPolicy {Automatic, ExternallyManaged}; WebFunctionOriginPermissions {Automatic, ExternallyManaged};\n WebFunctionCallerPolicy {Automatic, ExternallyManaged}.\n- WebFunctionRuntime (sealed; NodeJs24X = \"nodejs24.x\"; Of(string)).\n- WebFunctionCode (abstract, private protected ctor, closed hierarchy) with static FromBucket(IBucket, string key, WebFunctionCodeFromBucketOptions?)\n and WebFunctionCodeFromBucketOptions {ObjectVersion, BucketPolicy = Automatic}. The internal Bind contract to the construct is\n declared but bucket-policy wiring is implemented in the core-construct bead; keep the binding surface internal so FromAsset can be added later.\n- WebFunctionLogs (abstract, closed): Create(RetentionDays? retention = null [→ TWO_WEEKS], RemovalPolicy? [→ DESTROY]), Use(ILogGroup), ServiceDefault().\n- IWebFunctionConstructProps / WebFunctionConstructProps exactly per §8.3 (FunctionName, Code, Endpoint required; Runtime, EntryPoint,\n EnvironmentVariables, Timeout=30s, MaxConcurrencyPerEnvironment, Description, Role, Logs=Create(), ApplicationLogLevel, SystemLogLevel\n reusing Amazon.CDK.AWS.Lambda enums). NO EncryptionKey property.\n- IWebFunctionEndpointOptions / WebFunctionEndpointOptions (EndpointName=\"default\", required AuthType, EndpointType=HomeRegion, Regions, MaxEnvironments, RateLimit, Description).\n- WebFunctionEndpointAttributes (EndpointArn, DomainName, AuthType required; EndpointType=HomeRegion).\n- WebFunctionInvokeGrantOptions {CallerPolicy = Automatic}.\n- WebFunctionOriginProps (explicit members only: OriginId, OriginPath, CustomHeaders, ConnectionAttempts, ConnectionTimeout, ReadTimeout,\n KeepaliveTimeout, ResponseCompletionTimeout, OriginShieldEnabled, OriginShieldRegion) and sealed WebFunctionOriginWithOacProps : WebFunctionOriginProps\n {OriginAccessControl, Permissions = Automatic}. Must NOT expose ProtocolPolicy or OriginAccessControlId.\n- Internal validation helpers (local to new types; do not refactor shared code or existing constructs) for §14 value rules: FunctionName\n regex 1–64; EndpointName 1–64 [A-Za-z0-9_-]; Timeout 3–900 whole seconds; MaxConcurrencyPerEnvironment 1–128; MaxEnvironments 2–10000;\n RateLimit grid {0} ∪ 100..1000 step 100 ∪ 2000..10000 step 1000; Regions rules; env var key regex; EntryPoint relative/no \"..\";\n reserved AWS_LAMBDA_HTTP_ENDPOINT; EntryPoint vs AWS_LAMBDA_NODEJS_ENTRYPOINT conflict. Unresolved tokens (Token.IsUnresolved) are skipped, never rejected.\n Exception types per §14 (ArgumentException / ArgumentOutOfRangeException / InvalidOperationException).\n\nExpected files: src/LayeredCraft.Cdk.Constructs/Models/WebFunction*.cs (one type per file or small cohesive groups); test/.../WebFunctionModelsTests.cs (+ validation tests).\nExclusions: no constructs, no CloudFormation resources, no IBucket policy mutation yet, no testing-namespace helpers, no docs.\nEdge cases: FunctionName must allow tokens; nullable reference types enabled; records must be init-only (no Action\u003c\u003e mutation APIs anywhere).\n","acceptance_criteria":"- All listed public types exist with the exact names, members, and defaults in design §8.1–§8.5, §8.7 (no EncryptionKey), §10.2.\n- WebFunctionConstructProps cannot be constructed without FunctionName, Code, and Endpoint; WebFunctionEndpointOptions cannot be constructed without AuthType (compile-time `required`).\n- Every §14 value rule has a positive and negative unit test; tokens bypass literal validation (tested).\n- WebFunctionLogs.Create() defaults are TWO_WEEKS and DESTROY (tested).\n- No existing source file outside new WebFunction* files changed; existing golden templates still pass.\n- Validation gates pass.","notes":"T1 IMPLEMENTED (public WebFunction model/value types + §14 value validation). Not committed per task restriction.\n\nDELIVERABLES (src/LayeredCraft.Cdk.Constructs/Models/):\n- Enums: WebFunctionAuthType (IamAuth, ApplicationManaged), WebFunctionEndpointType (HomeRegion, MultiRegion, PerRegion), WebFunctionCodeBucketPolicy (Automatic, ExternallyManaged), WebFunctionOriginPermissions (Automatic, ExternallyManaged), WebFunctionCallerPolicy (Automatic, ExternallyManaged).\n- WebFunctionRuntime: sealed; NodeJs24X='nodejs24.x'; Of(string) escape hatch.\n- WebFunctionCode: abstract closed hierarchy (private protected ctor); static FromBucket(IBucket,string,WebFunctionCodeFromBucketOptions?); internal sealed WebFunctionCodeFromBucket. Options: WebFunctionCodeFromBucketOptions { ObjectVersion; BucketPolicy=Automatic }.\n- WebFunctionLogs: abstract closed; Create(RetentionDays?=TWO_WEEKS, RemovalPolicy?=DESTROY) / Use(ILogGroup) / ServiceDefault(); internal concrete subtypes.\n- IWebFunctionConstructProps + WebFunctionConstructProps: FunctionName/Code/Endpoint required; Runtime=NodeJs24X; EntryPoint; EnvironmentVariables; Timeout=30s; MaxConcurrencyPerEnvironment; Description; Role; Logs=Create(); ApplicationLogLevel; SystemLogLevel. NO EncryptionKey (deferred KMS, §8.7).\n- IWebFunctionEndpointOptions + WebFunctionEndpointOptions: EndpointName='default'; required AuthType (explicit selection, no default); EndpointType=HomeRegion; Regions=[]; MaxEnvironments; RateLimit; Description.\n- WebFunctionEndpointAttributes: required EndpointArn/DomainName/AuthType; EndpointType=HomeRegion.\n- WebFunctionInvokeGrantOptions: CallerPolicy=Automatic (explicit ownership contract).\n- WebFunctionOriginProps + sealed WebFunctionOriginWithOacProps (no ProtocolPolicy/OriginAccessControlId).\n- WebFunctionValidation (internal static): §14 helpers (FunctionName, EndpointName, Timeout, MaxConcurrencyPerEnvironment, MaxEnvironments, RateLimit grid, Regions, env var keys, env var map, EntryPoint incl reserved AWS_LAMBDA_HTTP_ENDPOINT and AWS_LAMBDA_NODEJS_ENTRYPOINT conflict). Token-aware: unresolved tokens (Token.IsUnresolved / Fn.Ref) bypass literal validation. Exceptions per §14 (ArgumentException / ArgumentOutOfRangeException).\n- [assembly: InternalsVisibleTo(\"LayeredCraft.Cdk.Constructs.Tests\")] added (new file) so validation is unit-testable.\n\nTESTS (test/LayeredCraft.Cdk.Constructs.Tests/): WebFunctionModelsTests.cs (defaults, required values, immutability, factory arg validation, crypto/logs/endpoint/origin surface) + WebFunctionValidationTests.cs (positive+negative per §14 rule, boundary values, token bypass). +110 tests/TFM ([Collection(\"CDK Tests\")], xUnit v3, AwesomeAssertions).\n\nCOMMANDS/RESULTS (JSII_SILENCE_WARNING_UNTESTED_NODE_VERSION=1):\n- dotnet build LayeredCraft.Cdk.Constructs.slnx -c Release -\u003e 0 warnings, 0 errors.\n- dotnet test --solution LayeredCraft.Cdk.Constructs.slnx -c Release -\u003e 1184 passed / 0 failed / 0 skipped (296 x net8.0/net9.0/net10.0/net11.0). Baseline was 744 (186x4).\n- 17 golden templates UNCHANGED; ExistingConstructsGoldenTemplateTests passed (zero diff). Goldens NOT regenerated.\n\nSCOPE: no constructs, no CFN resources, no IBucket policy mutation, no Testing helpers, no docs. No existing (pre-T1) source file modified; only new WebFunction*.cs files added. No new dependencies.\n\nINTENTIONAL DEVIATION (must be reported): design §8.2 declares internal 'abstract WebFunctionCodeConfig Bind(WebFunctionConstruct function)'. WebFunctionConstruct is created in T2 (cdkc-18e.3), so this internal seam cannot be declared in T1 without the type. Deferred Bind to T2 (which already owns the construct + bucket-policy wiring). Public contract unchanged. Recommendation: T2 declares the abstract Bind on WebFunctionCode and overrides it in WebFunctionCodeFromBucket. No other deviation from the approved design.","spec_id":"docs/designs/lambda-web-functions-integration.md","status":"closed","priority":1,"issue_type":"task","assignee":"Nick Cipollina","owner":"ncipollina@gmail.com","created_at":"2026-10-23T01:14:47Z","created_by":"Nick Cipollina","updated_at":"2026-10-23T01:53:01Z","started_at":"2026-10-23T01:38:29Z","closed_at":"2026-10-23T01:53:01Z","close_reason":"Implemented T1: public WebFunction model/value types (auth/endpoint-type/bucket-policy/origin-permissions/caller-policy enums, WebFunctionRuntime, closed WebFunctionCode+FromBucket, closed WebFunctionLogs with Create/Use/ServiceDefault, IWebFunctionConstructProps+record, IWebFunctionEndpointOptions+record, EndpointAttributes, InvokeGrantOptions, OriginProps+WithOacProps) and internal token-aware WebFunctionValidation for all §14 value rules. Added 2 test files (WebFunctionModelsTests, WebFunctionValidationTests) = +110 tests/TFM. Build 0 warnings/0 errors; full suite 1184/1184 passed across net8.0/9.0/10.0/11.0; all 17 existing golden templates unchanged (goldens not regenerated). No existing source modified, no constructs/CFN resources/IBucket mutation/Testing helpers/docs added. Internal Bind(WebFunctionConstruct) seam intentionally deferred to T2 (cdkc-18e.3) because the construct type does not exist in T1; public contract unaffected.","external_ref":"gh-98","labels":["lambda-web-functions","models","t1"],"dependencies":[{"issue_id":"cdkc-18e.2","depends_on_id":"cdkc-18e","type":"parent-child","created_at":"2026-10-23T01:14:47Z","created_by":"Nick Cipollina","metadata":"{}"},{"issue_id":"cdkc-18e.2","depends_on_id":"cdkc-18e.1","type":"blocks","created_at":"2026-10-23T01:15:09Z","created_by":"Nick Cipollina","metadata":"{}"}],"dependency_count":1,"dependent_count":1,"comment_count":0} +{"_type":"issue","id":"cdkc-18e.1","title":"T0: Upgrade Amazon.CDK.Lib to 2.274.0 and add golden-template baseline for existing constructs","description":"Purpose: separate review checkpoint that raises the CDK floor and proves existing constructs are unchanged. Design §5.5, §12.4 (Enforcement), §13, §19 T0.\n\nREQUIRED ORDER (do not reorder):\n a. Confirm Directory.Packages.props still pins Amazon.CDK.Lib 2.273.0 (`dotnet list test/LayeredCraft.Cdk.Constructs.Tests package --include-transitive | grep Amazon.CDK.Lib`). If it is already 2.274.0, STOP and record a blocker: the baseline can no longer be produced from the original version.\n b. Generate the golden baseline ON 2.273.0, run the tests once to prove the baseline passes on 2.273.0, and record the 2.273.0 SHA-256 of every golden file in the bead notes.\n c. Only then change Amazon.CDK.Lib to 2.274.0, restore, and run the golden tests in COMPARE mode (regeneration env var unset) against the unchanged 2.273.0 baseline.\n d. If any template differs: do NOT regenerate, accept, or edit golden files; do NOT adjust normalization to hide the diff. Record the full diff (construct, resource, property, old → new) on this bead with `bd update \u003cid\u003e --append-notes`, set the bead to blocked (`bd update \u003cid\u003e --status blocked`), and report to the maintainer. Leave 2.274.0 in place only together with the failing tests and the recorded diff.\n\nScope:\n1. BEFORE changing the CDK version, add a test-only golden-template harness and capture golden templates on the current\n Amazon.CDK.Lib 2.273.0 for the four existing constructs (LambdaFunctionConstruct, StaticSiteConstruct, DynamoDbTableConstruct,\n CognitoUserPoolConstruct) in default and representative configurations (e.g. Lambda: OTEL on/off, URL on/off, permissions;\n StaticSite: with/without ApiDomain and alternate domains; DynamoDB: GSI/stream/TTL; Cognito: domain prefix vs custom domain with\n explicit IHostedZone/ICertificate, groups, resource servers). Avoid configurations that require HostedZone.FromLookup unless the\n test supplies context; prefer deterministic inputs (no random AutoFixture values in golden stacks).\n2. Bump Amazon.CDK.Lib to 2.274.0 in Directory.Packages.props (the only dependency change).\n3. Re-run: golden templates must be identical (zero diff).\n\nHarness requirements (reused by later beads):\n- Lives in the test project (e.g. test/LayeredCraft.Cdk.Constructs.Tests/TestKit/Golden/GoldenTemplate.cs) with golden files under\n test/LayeredCraft.Cdk.Constructs.Tests/GoldenTemplates/*.json (copied to output).\n- Compares the COMPLETE synthesized template (Template.FromStack(...).ToJSON()), normalized only for asset hashes / asset\n S3 keys and CDK metadata (aws:cdk:path, CDKMetadata resource, BootstrapVersion parameter/rule). Document normalization in code.\n- Regeneration only when an env var (e.g. UPDATE_GOLDEN_TEMPLATES=1) is set; default mode fails on any diff with a readable diff message.\n- Stable across all target frameworks (net8.0–net11.0).\n\nExpected files: Directory.Packages.props; test/.../TestKit/Golden/*; test/.../GoldenTemplates/*.json; test/.../ExistingConstructsGoldenTemplateTests.cs; test csproj (copy golden files).\n\nExclusions: no changes to src/ production code; no new constructs; no other package bumps.\nEdge cases: CDK 2.274 may change synthesized output of existing constructs (e.g. new defaults/feature flags). If any golden diff\nappears after the bump, STOP and record the diff on this bead as a blocker for maintainer review; do not \"fix\" by editing goldens.\nAlso record whether CDK default-rule validation still warns \"Unknown resource type AWS::Lambda::WebFunction\" on 2.274 (design §5.5).\n","acceptance_criteria":"- Golden templates for all four existing constructs were generated on Amazon.CDK.Lib 2.273.0 BEFORE the upgrade, passed on 2.273.0, and their SHA-256 hashes are recorded in notes.\n- After upgrading to 2.274.0 the comparison ran against that ORIGINAL baseline; golden-file hashes are unchanged (no regeneration or acceptance of snapshots).\n- If the upgrade changed any synthesized template, the bead is blocked with the recorded diff instead of closed.\n- Directory.Packages.props uses Amazon.CDK.Lib 2.274.0; no other dependency changed.\n- After the bump all golden tests pass with zero diff on every target framework.\n- Harness supports regeneration via env var and fails readably on diff by default.\n- Full validation gates (restore/build/test) pass; coverage threshold not reduced.\n- Notes record commands run, the golden file list, and the 2.274 CloudFormation-Validate warning observation.","notes":"T0 (cdkc-18e.1) implementation evidence\n\nFILES CHANGED / ADDED\n- Directory.Packages.props: Amazon.CDK.Lib 2.273.0 -\u003e 2.274.0 (ONLY dependency change; diff is a single line).\n- test/LayeredCraft.Cdk.Constructs.Tests/LayeredCraft.Cdk.Constructs.Tests.csproj: added \u003cNone Update=\"GoldenTemplates\\**\\*.json\"\u003e\u003cCopyToOutputDirectory\u003ePreserveNewest\u003c/CopyToOutputDirectory\u003e.\n- test/LayeredCraft.Cdk.Constructs.Tests/TestKit/Golden/GoldenTemplate.cs (new): golden harness.\n- test/LayeredCraft.Cdk.Constructs.Tests/ExistingConstructsGoldenTemplateTests.cs (new): 17 golden cases across the 4 existing constructs.\n- test/LayeredCraft.Cdk.Constructs.Tests/GoldenTemplates/*.json (new): 17 baseline golden templates.\nNo changes to src/ production code.\n\nGOLDEN COVERAGE ADDED (17 templates)\n- LambdaFunctionConstruct: lambda-default, lambda-otel-amd64, lambda-otel-arm64, lambda-permissions, lambda-url, lambda-otel-url-permissions.\n- StaticSiteConstruct: static-site-default, static-site-api, static-site-alternates, static-site-full.\n- DynamoDbTableConstruct: dynamodb-default, dynamodb-sort-key, dynamodb-gsi, dynamodb-stream-ttl.\n- CognitoUserPoolConstruct: cognito-prefix-domain, cognito-custom-domain, cognito-no-domain.\n\nNORMALIZATION (documented in GoldenTemplate.cs)\nCompares the COMPLETE Template.FromStack(...).ToJSON(). Only: BootstrapVersion parameter + CheckBootstrapVersion rule removed; AWS::CDK::Metadata resource removed; per-resource Metadata removed (aws:cdk:path / aws:asset:path); 64-hex asset content hashes / S3 keys replaced with \u003cASSET-HASH\u003e. No other keys altered. Regeneration only when UPDATE_GOLDEN_TEMPLATES is truthy; default mode fails with a readable -/+ line diff and never overwrites the golden. Golden files resolve from the source tree (walk-up to project dir) with an output-dir fallback.\n\nCOMMANDS + RESULTS\n- Baseline restore on 2.273.0: `dotnet restore LayeredCraft.Cdk.Constructs.slnx` OK.\n- Baseline test on 2.273.0: `dotnet test --solution LayeredCraft.Cdk.Constructs.slnx -c Release` -\u003e PASSED, 186 x net8.0/net9.0/net10.0/net11.0 (744 total), 0 failed, 0 skipped.\n- Golden files SHA-256 recorded, then upgrade to 2.274.0: `dotnet restore` OK; `dotnet list ... package` shows Amazon.CDK.Lib 2.274.0.\n- Post-upgrade test on 2.274.0 (against the ORIGINAL unchanged baseline): `dotnet test --solution LayeredCraft.Cdk.Constructs.slnx -c Release` -\u003e PASSED, 186 x4 TFMs (744 total), 0 failed, 0 skipped, ZERO golden diff on every TFM.\n- `shasum -a 256` before vs after: HASHES IDENTICAL (git tracked files unmodified by the run).\n\nBASELINE SHA-256 (identical before and after upgrade)\n66398f765a746fbe76268e666d0b492ddb8aadec9f2c4c76d17a25b6981cc769 cognito-custom-domain.json\n3396b3ceeedbd15de26119076158e3f1d0c8bc638f1a2be556e8d87fa8dce30b cognito-no-domain.json\nd18cc32d82a07f45534584a59f5431540883baf24d4bf7311a8ebe14c0ac5447 cognito-prefix-domain.json\n0d5397ab86db3dd0194fd4a6463ebd9461005c65f7964be0b617dfab9ade384e dynamodb-default.json\n07a9509cad0feb734c4c48eec96b4271a9e7c80acb7bdcf39a4bfb6de300e80d dynamodb-gsi.json\n1517371079a842ed38ac411b64e1c4093c80e6b896a77b0ca766762ef9e8412b dynamodb-sort-key.json\n5a500b2d5d2073d0747b355aa19aae5092d8754ad8e529776bebb91997679ab8 dynamodb-stream-ttl.json\nd1038f5889457882b0a50736446376b8a05d9430db99429b39bec989bcd3073b lambda-default.json\n796c2acdaca4bb90df681ddfcd05c5867ed3d0e8e05b0ec417d4cac067fed881 lambda-otel-amd64.json\n26f601e11cb042ed163cc595fb9131bbb1fddbaa0d6993ff6d3a1dfcf094c543 lambda-otel-arm64.json\n8aadb2159cc9febd6a73a7aa888ce470b3ef81eabc8c857174615166efd3b1ff lambda-otel-url-permissions.json\n648cd4745abb61979544466c171b72f7cc70b1e239ca43ec4a58c0e50151a9f6 lambda-permissions.json\nf9b86ad9c94ad499e373df8b97536e0525b4d0565c34539a75df0bd720308362 lambda-url.json\nb1bc13271470ae7136b8f085de3f584e51409acb69788764957079df1c3dd639 static-site-alternates.json\nb5e4a36010f31a7666cc0b9fb0ce94754ed046bb1a6cf3a993bf57d7b0970973 static-site-api.json\n1eb6acb8bd3579c9157ee82fe94e24727c35dafa91828dd7f5d9cc3359cc8f38 static-site-default.json\n63bfa34136f47b16bd7829efa91c8b66b1d000bb2096beeccf961e8ff5a09a04 static-site-full.json\n\n2.274 CLOUDFORMATION DEFAULT-RULE VALIDATION OBSERVATION\nStill warn-only (feature flag @aws-cdk/core:validateAgainstDefaultRules remains OFF by default). A temporary probe that synthesized a raw CfnResource of type AWS::Lambda::WebFunction emitted:\n WARNING Unknown resource type 'AWS::Lambda::WebFunction' (CloudFormation Validate) [CloudFormation-Validate::F3006]\n Set feature flag \"@aws-cdk/core:validateAgainstDefaultRules\" to true to turn these into errors.\nSo the unknown AWS::Lambda::WebFunction type is still only a warning (not an error) on 2.274. Note: the 2.274 assembly does now ship CfnWebFunction / CfnWebFunctionEndpoint / CfnWebFunctionRevision L1 types. The temporary probe file was removed and is not part of the deliverable.\n\nCOVERAGE\nsrc/ production code is unchanged, so the CI 80% coverage gate is unaffected.\n\nRESTRICTIONS HONORED\nNo src/ changes, no new constructs, no other dependency bumps, goldens not regenerated/adjusted, normalization not weakened, no commit/push/PR/deploy/publish.","spec_id":"docs/designs/lambda-web-functions-integration.md","status":"closed","priority":1,"issue_type":"task","assignee":"Nick Cipollina","owner":"ncipollina@gmail.com","created_at":"2026-10-23T01:14:46Z","created_by":"Nick Cipollina","updated_at":"2026-10-23T01:32:51Z","started_at":"2026-10-23T01:23:53Z","closed_at":"2026-10-23T01:32:51Z","close_reason":"T0 complete: golden baseline (17 templates, 4 constructs) captured and verified on 2.273.0; Amazon.CDK.Lib bumped to 2.274.0 (only dependency change); goldens re-verified against unchanged baseline with zero diff and identical SHA-256 on all 4 TFMs; 186x4 tests pass. 2.274 default-rule validation still warns (not errors) on unknown AWS::Lambda::WebFunction.","external_ref":"gh-98","labels":["baseline","lambda-web-functions","t0"],"dependencies":[{"issue_id":"cdkc-18e.1","depends_on_id":"cdkc-18e","type":"parent-child","created_at":"2026-10-23T01:14:46Z","created_by":"Nick Cipollina","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0} +{"_type":"issue","id":"cdkc-18e","title":"AWS Lambda Web Functions support — LayeredCraft.Cdk.Constructs","description":"Implement AWS Lambda Web Functions support in LayeredCraft.Cdk.Constructs per the APPROVED design (revision 3):\ndocs/designs/lambda-web-functions-integration.md (authoritative; GitHub issue #98).\n\nScope: new additive constructs WebFunctionConstruct, WebFunctionEndpointConstruct/IWebFunctionEndpoint, WebFunctionOrigin,\nWebFunctionCode.FromBucket, WebFunctionLogs, supporting models, Testing helpers, docs, and a mandatory AWS sandbox release gate.\n\nNon-negotiable constraints (design §2, §6, §8, §10.2, §12.4):\n- Hybrid composition; L3 over CDK L1 (CfnWebFunction/Revision/Endpoint, CfnResourcePolicy); no upstream alpha/L2 dependency;\n upstream L2 types never appear in the public API.\n- Existing constructs (LambdaFunctionConstruct, StaticSiteConstruct, DynamoDbTableConstruct, CognitoUserPoolConstruct) are\n NOT modified; their synthesized templates must not change (golden templates from cdkc T0).\n- Explicit AuthType on every endpoint (no default). Single-owner resource policy per function. Same-stack automatic OAC\n permissions only. Limited endpoint imports (no whole-function import). Existing S3 artifacts only (no FromAsset).\n Default log retention TWO_WEEKS. No customer-managed revision KMS key. Workload-neutral (Next.js, ASP.NET Core shim,\n Blazor Static SSR) with no workload-specific constructs.\n- GrantInvoke follows the revision-3 algorithm in §10.2 (account establishment E1/E2, Automatic vs ExternallyManaged).\n Never use Grant.AddToPrincipalOrResource or trust Grant.Success/AssertSuccess.\n- Amazon.CDK.Lib floor 2.274.0.\n\nRules for every implementation agent:\n- Implement only the claimed bead's scope. If the design is ambiguous or seems wrong, stop and record a blocker note on\n the bead (bd update \u003cid\u003e --append-notes ...) instead of changing the design.\n- Do not commit, push, open PRs, publish NuGet packages, or close GitHub issue #98 unless separately authorized by the maintainer.\n- Do not deploy to AWS except in the sandbox bead, and only with maintainer-provided non-production credentials.\n- Do not modify the Sharedale repository.\n- Validation gates (run from repo root): `dotnet restore LayeredCraft.Cdk.Constructs.slnx`, `dotnet build LayeredCraft.Cdk.Constructs.slnx -c Release`,\n `dotnet test --solution LayeredCraft.Cdk.Constructs.slnx -c Release` (Microsoft.Testing.Platform, see global.json); CI requires\n 80% coverage across net8.0–net11.0. Docs: `uv run mkdocs build --clean`. If Node \u003e24 prints jsii warnings, set\n JSII_SILENCE_WARNING_UNTESTED_NODE_VERSION=1.\n- Test conventions: xUnit v3, AwesomeAssertions, AutoFixture TestKit customizations, `[Collection(\"CDK Tests\")]`, Template.FromStack\n after constructs are added (see CLAUDE.md \"Testing Patterns\").\n- Close a bead only when its acceptance criteria are met; record validation evidence (commands run + results) in notes.\n\nFeature completion is gated by the \"Verify release acceptance criteria\" bead, which depends on the sandbox deployment bead.\nOptional bead T4a never blocks completion.\n","acceptance_criteria":"All required child beads closed, including the AWS sandbox release gate and the release acceptance verification bead; optional spike may be open or closed.","notes":"Agent workflow: find work with 'bd ready --parent cdkc-18e --exclude-type epic'; read 'bd show \u003cid\u003e' (description, acceptance, deps); claim with 'bd update \u003cid\u003e --claim' (or --status in_progress); record evidence with 'bd update \u003cid\u003e --append-notes \"...\"'; close with 'bd close \u003cid\u003e --reason \"...\"' only when acceptance criteria are met; then re-run bd ready. Never claim or close this epic directly: when all children are closed, the maintainer runs 'bd epic close-eligible'. Optional spike cdkc-18e.7 never blocks required work; close it with outcome A or B before epic closure. The feature is complete only after cdkc-18e.14 (which depends on the mandatory AWS sandbox gate cdkc-18e.13).","spec_id":"docs/designs/lambda-web-functions-integration.md","status":"open","priority":1,"issue_type":"epic","owner":"ncipollina@gmail.com","created_at":"2026-10-23T01:14:45Z","created_by":"Nick Cipollina","updated_at":"2026-10-23T01:15:51Z","external_ref":"gh-98","labels":["lambda-web-functions"],"dependency_count":0,"dependent_count":0,"comment_count":0} +{"_type":"issue","id":"cdkc-18e.16","title":"T2 follow-up: Harden owned code-bucket inspection (tokens, unrecognized values, DSSE classification)","description":"Purpose: align WebFunctionCodeFromBucket.ValidateOwnedBucketConfiguration (src/LayeredCraft.Cdk.Constructs/Models/WebFunctionCode.cs) with design §14 and the revision-4 clarification under the §14 table. Source: independent review findings P4 and DSSE.\n\nDefects:\n(1) Tokens are rejected instead of skipped: a VersioningConfiguration.Status token resolves to {Ref:...}, its ToString() is compared to 'Enabled', and the bucket is rejected.\n(2) A Stack.Resolve result whose structure is not recognized should be treated as unknown and skipped, not rejected.\n(3) UsesAwsManagedKey rejects every aws:kms:dsse bucket, including DSSE with a customer-managed key. Per §8.7/§14, reject only DSSE_MANAGED (no key) and KMS_MANAGED/aws/s3, and make each message name the actual problem.\n(4) Versioning enabled only through an escape-hatch property override is a documented limitation, not a fix target. T6a documents the workaround (Bucket.FromBucketName + ExternallyManaged).\n\nKeep the current rule that owned buckets are inspected even under ExternallyManaged; the design does not change that.\n\nTests: token Status skipped; DSSE with a customer key accepted; DSSE_MANAGED rejected with an accurate message; KMS_MANAGED still rejected; customer-key SSE-KMS accepted; unversioned still rejected.\n\nExclusions: IAM/grant code (T3c), docs (T6a). No golden changes expected; verify. No commits or pushes unless authorized.","acceptance_criteria":"• Unresolved bucket configuration values are handled conservatively: a token or unrecognized versioning Status, encryption algorithm, encryption structure, or KMS key id is SKIPPED and never rejected (each case has a test). Unresolved values are never treated as proof of a violation.\n• Literal violations are still rejected: unversioned, KMS_MANAGED/aws/s3, DSSE_MANAGED (no key).\n• DSSE with a customer-managed key is accepted. Messages name the actual problem.\n• Escape-hatch-only versioning remains a documented limitation (T6a); it is not handled in code.\n• New tests pass; all goldens unchanged.\n• Release build has 0 warnings and the full suite passes on net8.0–net11.0; evidence is recorded in notes.","notes":"Maintainer decision (2026-10-23): keep escape-hatch S3 versioning as a documented limitation. Handle unresolved values conservatively: never reject tokenized values.\nIMPLEMENTATION (2026-10-23): Rewrote WebFunctionCodeFromBucket.ValidateOwnedBucketConfiguration in src/LayeredCraft.Cdk.Constructs/Models/WebFunctionCode.cs into ValidateVersioning + ValidateEncryption + ValidateKmsKey, classifying every value as literal-valid, literal-invalid, or unresolved/unrecognized.\n\nStorage/versioning/encryption handling:\n- Versioning: missing VersioningConfiguration or literal Status \"Suspended\" -\u003e reject (VersioningMessage). Literal Status \"Enabled\" -\u003e accept. A token Status, a missing status key, a non-dictionary resolved structure, or any other literal status -\u003e skipped (never rejected).\n- Encryption: missing BucketEncryption -\u003e no violation. Unrecognized structure (not a map, no rules, no ServerSideEncryptionByDefault) -\u003e skipped. Algorithm literal \"aws:kms\": key literal aws/s3 or empty/absent -\u003e reject (KmsManagedMessage names aws/s3); literal customer key -\u003e accept; token/absent-as-token key -\u003e skipped (never treated as AWS-managed). Algorithm literal \"aws:kms:dsse\": no key / aws/s3 -\u003e reject (DsseManagedMessage names customer-managed key); literal customer key -\u003e accept; token key -\u003e skipped. AES256 and any other literal algorithm -\u003e accepted.\n- LiteralString helper returns null for a non-string value or a string containing `${Token[`, so resolved tokens are never misread as literals.\n\nSecurity-policy behavior: ExternallyManaged still inspects owned buckets (versioning/encryption) exactly as before - design §14 row unchanged. The Automatic-only cross-stack account/Region guard and AddToResourcePolicy remain bypassed under ExternallyManaged (no bucket-policy statement is generated). No other semantics changed.\n\nRegression tests added to test/LayeredCraft.Cdk.Constructs.Tests/WebFunctionConstructTests.cs (13 new): enabled+S3-managed accepted (asserts synthesized S3::BucketPolicy); disabled (Versioned=false) rejected with versioning message; suspended rejected; tokenized versioning Status skipped (asserts synthesized policy); unrecognized literal versioning Status skipped; AWS-managed KMS (aws/s3) rejected naming aws/s3; customer-managed KMS accepted; tokenized KMS key skipped; DSSE with customer-managed key accepted; DSSE_MANAGED rejected naming customer-managed; DSSE + aws/s3 rejected; unrecognized encryption structure skipped; ExternallyManaged cross-stack owned bucket with unresolved function env does not throw (Automatic-only guard not applied). Existing fixtures retained (owned-bucket policy statements + revision DependsOn on bucket policy, imported-bucket Automatic error, ExternallyManaged no-policy, unversioned, KMS_MANAGED, cross-stack Automatic error). These exercise the real L1 property structs (CfnBucket.VersioningConfigurationProperty / BucketEncryptionProperty) so validation runs against synthesized configuration.\n\nEvidence: dotnet build -c Release -\u003e Build succeeded, 0 Warning(s), 0 Error(s). Full suite per TFM (dotnet run --project test/LayeredCraft.Cdk.Constructs.Tests/ -c Release --no-build): net8.0/net9.0/net10.0/net11.0 each Total 450, Errors 0, Failed 0, Skipped 0 (was 437 before; +13). All 24 golden templates byte-identical (git reports no GoldenTemplates changes); no golden updates required. dotnet format --verify-no-changes reports no issues in the two changed files. Only two files modified. No commit or push performed (per task restrictions).\n\nUnresolved behavior (documented, not code): versioning enabled solely via an escape-hatch property override is not detected (limitation, T6a workaround); imported buckets remain uninspected.","spec_id":"docs/designs/lambda-web-functions-integration.md","status":"closed","priority":2,"issue_type":"task","assignee":"Nick Cipollina","owner":"ncipollina@gmail.com","created_at":"2026-10-23T12:49:20Z","created_by":"Nick Cipollina","updated_at":"2026-10-23T14:43:43Z","started_at":"2026-10-23T14:34:44Z","closed_at":"2026-10-23T14:43:43Z","close_reason":"Owned-bucket inspection hardened per design §14 rev4. Unresolved values (token/unrecognized versioning Status, encryption algorithm, KMS key id, encryption structure) are skipped and never rejected; literal violations still rejected (unversioned/Suspended, KMS_MANAGED aws/s3, DSSE_MANAGED); DSSE with a customer-managed key accepted; messages name the actual problem. ExternallyManaged still inspects owned buckets but emits no policy and keeps the Automatic-only cross-stack guard. 13 new regression tests; Release build 0 warnings; full suite 450/450 on net8.0-net11.0; all 24 goldens unchanged. Not committed (per task).","external_ref":"gh-98","labels":["core","lambda-web-functions","t2"],"dependencies":[{"issue_id":"cdkc-18e.16","depends_on_id":"cdkc-18e","type":"parent-child","created_at":"2026-10-23T12:49:20Z","created_by":"Nick Cipollina","metadata":"{}"},{"issue_id":"cdkc-18e.16","depends_on_id":"cdkc-18e.3","type":"blocks","created_at":"2026-10-23T12:49:20Z","created_by":"Nick Cipollina","metadata":"{}"}],"dependency_count":1,"dependent_count":1,"comment_count":0} +{"_type":"issue","id":"cdkc-18e.12","title":"T7b: Create sandbox CDK app and deploy/smoke/destroy scripts (no deployment)","description":"Purpose: sandbox CDK app and smoke-test tooling that exercises the implemented constructs exactly as a consumer would. No deployment in this bead. Design §19.1 item 3 (all sub-items), §9, §12.\n\nDeliverables under samples/web-functions/sandbox/ (not in the library slnx/CI):\n- A CDK app (C#) referencing the library project, with explicit Env (account/region from context or env vars; never hard-coded production values):\n * ArtifactsStack: owned versioned SSE-S3 Bucket used with WebFunctionCodeBucketPolicy.Automatic (bucket stack deployed and artifacts uploaded BEFORE the app stack, because the\n object must exist before the revision is created and Automatic adds the statement to the bucket's own stack).\n * A pre-provisioned \"external\" bucket (created by the script or a separate stack with its own lambda.amazonaws.com read policy) imported via Bucket.FromBucketName and used with ExternallyManaged.\n * AppStack: Next.js Web Function (IamAuth) behind a Distribution via WebFunctionOrigin.WithOriginAccessControl (default uncached + ALL_VIEWER_EXCEPT_HOST_HEADER, /_next/static/* cached);\n ASP.NET Core Web Function (IamAuth) with a second endpoint (for the endpoint-specific denial test) and GrantInvoke to a dedicated \"caller\" IAM role assumable by the operator;\n Blazor Web Function (IamAuth) behind OAC (fingerprinted/static assets cached); context flags to (a) switch artifacts to the v2 build (revision update), (b) add/remove a second\n distribution on the Next.js endpoint (resource-policy lifecycle), (c) optionally add an ExternallyManaged cross-account grant for a second sandbox account.\n * Outputs needed by the smoke script (endpoint URLs/ARNs, distribution domains/ids, caller role ARN). Use the library's naming; prefix all names with a sandbox prefix.\n- smoke.sh (bash, AWS CLI v2 + curl with --aws-sigv4 \"aws:amz:\u003cregion\u003e:lambda\" and header x-amz-content-sha256: UNSIGNED-PAYLOAD) implementing every §19.1 3.x check with expected status codes,\n `aws lambda-web get-resource-policy` inspection, revision/endpoint state checks, and a machine-readable summary; deploy.sh (ordered: artifacts stack → upload zips → app stack) and destroy.sh\n (destroys stacks, empties/deletes buckets incl. all object versions, deletes log groups).\n- README.md: prerequisites, required IAM permissions, non-production account requirement, cost notes, step-by-step run, cleanup, and how to record evidence.\n\nValidation in this bead: `cdk synth` of the sandbox app succeeds locally without deploying (use dummy account/region context); scripts pass shellcheck if available. No AWS deployment.\nExclusions: running against AWS (next bead); changes to library production code (record blockers instead).\n","acceptance_criteria":"- Sandbox CDK app synthesizes using only the public library API and covers every §19.1 item 3 scenario via stacks/context flags.\n- deploy/smoke/destroy scripts and README exist; smoke script checks every §19.1 3.1–3.8 item with explicit expected results; cleanup removes all created resources.\n- No deployment performed; library validation gates still pass.","notes":"## T7b implementation + correction record (no AWS deployment performed)\n\n### Sandbox CDK app (samples/web-functions/sandbox/, 20 files, untracked)\nC# CDK app (net10.0) referencing the real LayeredCraft.Cdk.Constructs project and exercising only the public Web Function API (WebFunctionConstruct, AddEndpoint, WebFunctionOrigin OAC, GrantInvoke, GrantCloudFrontInvoke). Stacks: lccdk-wf-sandbox-{id}-artifacts (versioned SSE-S3 bucket, Automatic), -external (versioned bucket + scoped read policy + 2 imported-caller roles), -app (Next.js/ASP.NET Core/Blazor Web Functions, 4 endpoints, 3 resource policies, 2 CloudFront distributions + OACs, caller/denied/imported roles, 28 outputs). Scripts: common.sh, validate-env.sh, synth.sh, upload-artifacts.sh, deploy.sh, update-to-v2.sh, destroy.sh, smoke.sh, run-workflow.sh + README.md.\n\n### Corrections applied (independent review)\n- B1 repeat-deploy: deploy.sh always synthesizes the COMPLETE app (SANDBOX_COMPONENTS=all) so support-stack cross-stack exports survive; support stacks deployed first with guarded placeholder versions, then upload, then app stack with real versions.\n- B2 destroy: destroy.sh synthesizes with SANDBOX_ALLOW_PLACEHOLDER_VERSIONS=1 so teardown works without a manifest / after partial failure; destroys app-\u003eexternal-\u003eartifacts, verifies each stack is gone before removing the manifest.\n- H1 ownership: fixed namespace lccdk-wf-sandbox in stack names; stack tags lc-webfunction-sandbox-id / lc-webfunction-sandbox-owner on every stack; shell stack_ownership (absent|owned|foreign|error) + assert_stack_owned_or_absent (deploy) / require_stack_owned (destroy); fail-closed on foreign or ambiguous results; every aws call pinned to --region and ambient-region mismatch aborts; mutations require SANDBOX_ALLOW_AWS=1 AND SANDBOX_ACKNOWLEDGE_NON_PRODUCTION=1.\n- M1: stack_exists replaced by stack_ownership (distinguishes not-found from AccessDenied/throttling/expired creds).\n- M2: empty_bucket deletes only object versions + delete markers (never delete-bucket); --expected-bucket-owner on head/list/delete; CloudFormation deletes the buckets; only stack-owned buckets are emptied.\n- M3: artifacts prefix consistent (SandboxConfiguration default key now uses the configured SANDBOX_ARTIFACTS_PREFIX; manifest/upload/CDK agree).\n- M4: CDK CLI pinned to 2.1145.0 (common.sh CDK_CLI_VERSION); SANDBOX_CDK override documented.\n- M5: external bucket policy scoped per function (arn:aws:lambda:{region}:{account}:web-function/{wfsbx-aspnetcore|wfsbx-blazor}/revision/*), no broad web-function/*/revision/*.\n- M6: app stack declares explicit CDK dependencies on artifacts + external (AddStackDependency).\n- SM1-SM7: smoke.sh rewritten - errexit disabled during tests + always writes build/smoke-summary.json + non-zero exit on fail/blocked; live resource-policy validation (BLOCKED, never PASS, when lambda-web API unavailable) checking Principal/Action/Effect/Resource/aws:SourceArn; revision/endpoint state via lambda-web get-web-function; Next.js build-id parser strips the 'Build id: ' label; Blazor sample now exposes id=\"build-id\"; real warm-request and Blazor assertions; denial classification (signature vs access-denied) requiring the matching positive to pass; imported immutable/mutable roles verified to have NO caller-side identity policy; cross-account distinguishes not-configured/missing-setup/negative/positive; SigV4 creds passed via a 600-perm curl -K config (never argv); bounded retry with validated numeric input.\n- Phase 7 misc: missing-flag-value guards, explicit SANDBOX_SECOND_DISTRIBUTION=0 reset, manifest target (sandboxId/account/region/prefix) validated before reuse, README documents CDK bootstrap + AWS CLI + missing lambda-web subcommands + prefix + pinned CLI + non-prod ack.\n\n### Offline validation (no AWS mutations)\n- Offline lifecycle harness with stubbed aws/cdk: 61/61 checks across 16 scenarios (fresh prep, support provisioning, upload+manifest, app deploy, repeat deploy, v1-\u003ev2, second-distribution enable/disable, normal/partial/repeated destroy, account mismatch, foreign-stack refusal, credential/API failure, S3 cleanup failure, manifest missing/foreign, nondefault prefix). Proves destroy never calls s3api delete-bucket.\n- Real cdk synth (npx aws-cdk@2.1145.0): verified stack ownership tags on all three stacks, per-function scoped external bucket policy, app-\u003eartifacts/external dependencies, cloudfront SourceArn resource policies, ASP.NET Core 2 imported-role statements, 28 app outputs. Expected F3006 warnings for the new resource types.\n- bash -n clean on all scripts. shellcheck not installed locally.\n- Library tests: 2140 passed / 0 failed (net8/9/10/11); no golden-template regressions.\n- Generated outputs (cdk.out/bin/obj/build) remain gitignored; git add -n lists exactly the 20 intended files.\n- Read-only identity check used a disposable test account (id withheld); NO deploy/destroy/upload performed.\nSecond independent review (Claude) returned CHANGES REQUIRED. Deploy/update/destroy lifecycle, placeholder mechanism, stack ownership, cross-stack deps, and synthesized IAM policies are independently validated and must NOT be redesigned. Correcting: S1 smoke.sh $4 under set -u; S2 CURL_AUTH omitted on CallerRole/imported-role positives; S3 CloudFront ARN empty region; S4 fail-closed live resource-policy verification (parser crash/omission must FAIL/BLOCKED); S5 imported-role identity-policy checks (list-role-policies failure != no policy; inline+attached; IAM sim); S6 Next.js build-ID extraction (HTML comments); S7 per-function revision/update verification; L1 remove unsafe log-group deletion; L2 prevalidate manifest on --skip-upload before any mutation; L3 first-run workflow without manifest; L4 preserve shell command failures; L5 bound --attempts + cross-account negative authorization. No real AWS mutations; do not start T7c.\n## T7b second-round corrections (independent review) — complete\n\n### S1-S7 (smoke execution correctness)\n- S1: smoke.sh settle() and fetch_until() optional positional args now use ${4:-}; regression scenario 1 proves the first passing check no longer aborts the suite.\n- S2: every IAM-signed positive invocation passes ${CURL_AUTH[@]} (curl -K config file, 0600); credentials are never on the curl argv. Scenario 2 asserts the signed requests reached the endpoint.\n- S3: CloudFront ARNs now use the empty region component arn:aws:cloudfront::\u003caccount\u003e:distribution/\u003cid\u003e; scenario 3 validates the policy checks against that ARN.\n- S4 (fail-closed): policy_report catches parse/schema errors and emits FAIL; unreadable/missing live policies emit FAIL/BLOCKED; a completeness check requires all 3 policy-check records (fewer =\u003e FAIL). Validates Effect=Allow, principal, action lambda:InvokeWebFunctionEndpoint, endpoint Resource ARN, aws:SourceArn; detects duplicate statements and unexpected distribution grants. Scenarios 4-8 cover malformed JSON, parser exception, missing policy, duplicate, extra, and second-distribution-removed.\n- S5: role_invoke_state inspects inline AND attached policies; any lookup failure returns error =\u003e BLOCKED (never PASS); scenario 9 (IAM AccessDenied) asserts BLOCKED.\n- S6: Next.js and Blazor samples render a stable data-build-id attribute; smoke extracts it (immune to SSR HTML comments); scenario 10 rejects a wrong build id.\n- S7: per-function revision tracking (each function queried separately; BLOCKED when the API is unavailable); --revision-baseline compares per-function revision identities before/after an update; run-workflow.sh derives --expect-build-id from the local artifact zip build-id.txt; scenarios 11-12 cover distinct per-function revisions and the v1-\u003ev2 transition (advanced vs unchanged).\n\n### L1-L5\n- L1: destroy.sh no longer deletes log groups by predictable name; CloudFormation deletes the CFN-owned log groups with their stacks. Scenario 13 asserts no log-group deletion API call and no delete-bucket.\n- L2: deploy.sh validates the artifact manifest (existence, sandbox id, account, region, prefix, required keys+versions) BEFORE any support-stack mutation when --skip-upload; a mismatched manifest performs zero AWS mutations. Scenario 14.\n- L3: run-workflow.sh no longer synthesizes before deploy (deploy.sh synthesizes), so a fresh checkout works without an existing manifest; placeholder-version protection is unchanged. Scenario 15.\n- L4: common.sh export_artifact_env assigns then exports (no export VAR=$(cmd) masking of failures under errexit).\n- L5: --attempts is bounded 1..60; cross-account adds the negative half (cross-account role on the alt endpoint =\u003e denied) and never PASSes when unconfigured.\n\n### Files changed (all uncommitted)\nsamples/web-functions/sandbox/: smoke.sh, common.sh, deploy.sh, destroy.sh, run-workflow.sh, synth.sh, upload-artifacts.sh, validate-env.sh, README.md, SandboxConfiguration.cs, SandboxNaming.cs, ArtifactsStack.cs, ExternalStack.cs, AppStack.cs, Program.cs; NEW tests/run-scenarios.sh, tests/run-smoke-scenarios.sh, tests/stubs/{aws,cdk,curl}. Also apps/nextjs/app/page.js, apps/blazor/Components/Pages/Home.razor, apps/blazor/Program.cs (S6 data-build-id). Plus .beads/issues.jsonl.\n\n### Regression test results (stubbed AWS/CDK/curl; no real AWS)\n- tests/run-scenarios.sh: 61 passed / 0 failed (lifecycle: stacks-only, upload, deploy, repeat, v1-\u003ev2, second-dist enable/disable, destroy, partial/repeated destroy, account mismatch, foreign stack, credential/API fail, S3 cleanup fail, manifest missing/mismatch, nondefault prefix).\n- tests/run-smoke-scenarios.sh: 38 passed / 0 failed (S1-S7/L1-L5 smoke correctness, fail-closed policy verification, per-function revisions, v1-\u003ev2, L1/L2/L3).\n\n### Other validation\n- bash -n OK for all 11 sandbox+test scripts; shellcheck not installed (noted).\n- Library tests: 2140 passed / 0 failed (net8.0/9.0/10.0/11.0); no golden-template changes.\n- Offline cdk synth OK (stacks lccdk-wf-sandbox-wfsbx-{artifacts,external,app}); H1 ownership tags on all stacks, M5 external bucket policy scoped per function revision ARN, M6 app-\u003esupport dependencies, resource policies 1/2/1 statements.\n\n### Remaining AWS-only uncertainties (deferred to T7c)\nReal deploy/smoke/destroy not performed. lambda-web CLI subcommands are unavailable in the local CLI, so live revision/policy checks report BLOCKED there. Cross-account requires a second sandbox account. IAM identity-policy propagation timing is only observable against real AWS.","spec_id":"docs/designs/lambda-web-functions-integration.md","status":"closed","priority":2,"issue_type":"task","owner":"ncipollina@gmail.com","created_at":"2026-10-23T01:14:57Z","created_by":"Nick Cipollina","updated_at":"2026-10-24T21:05:54Z","started_at":"2026-10-24T01:31:48Z","closed_at":"2026-10-24T21:05:54Z","close_reason":"T7b second-round corrections complete: S1-S7 and L1-L5 resolved; added stub-driven regression harness (tests/run-scenarios.sh 61/61, tests/run-smoke-scenarios.sh 38/38); bash -n clean; library tests 2140/0; offline synth verified (H1/M5/M6). No AWS mutations; T7c still pending.","external_ref":"gh-98","labels":["lambda-web-functions","samples","sandbox","t7"],"dependencies":[{"issue_id":"cdkc-18e.12","depends_on_id":"cdkc-18e","type":"parent-child","created_at":"2026-10-23T01:14:57Z","created_by":"Nick Cipollina","metadata":"{}"},{"issue_id":"cdkc-18e.12","depends_on_id":"cdkc-18e.11","type":"blocks","created_at":"2026-10-23T01:15:19Z","created_by":"Nick Cipollina","metadata":"{}"},{"issue_id":"cdkc-18e.12","depends_on_id":"cdkc-18e.6","type":"blocks","created_at":"2026-10-23T01:15:18Z","created_by":"Nick Cipollina","metadata":"{}"}],"dependency_count":2,"dependent_count":1,"comment_count":0} +{"_type":"issue","id":"cdkc-18e.11","title":"T7a: Create sandbox workload sample apps (Next.js, ASP.NET Core shim, Blazor Static SSR) and artifact builds","description":"Purpose: minimal, deployable workload artifacts for the sandbox release gate. Independent of the library code; can start immediately. Design §16 recipes, §19.1 items 2–3.8.\n\nDeliverables under samples/web-functions/apps/ (consumer-style sample code, NOT library code; must not be added to LayeredCraft.Cdk.Constructs.slnx or the PR CI build):\n1. nextjs/: minimal Next.js app (one server-rendered page that prints a request-time value + one static asset), `output: \"standalone\"`, and an index.js entry that sets\n HOSTNAME/PORT from AWS_LAMBDA_HTTP_ENDPOINT (\"host:port\"), handles SIGTERM with exit(0), then require(\"./server.js\"). Zip layout: standalone output + .next/static + public at zip root.\n2. aspnetcore/: minimal ASP.NET Core API (GET /status returning JSON incl. a build id; one protected-by-IAM-only route is fine) published self-contained linux-arm64 as apphost `server`;\n zip root contains index.js = `process.execve(\"/var/task/server\", [\"/var/task/server\"], process.env);` and the publish output. App listens on http://$AWS_LAMBDA_HTTP_ENDPOINT,\n then POSTs `{}` to http://$AWS_LAMBDA_RUNTIME_API/2025-09-01/ready after StartAsync (skip when the variable is absent); no UseHttpsRedirection/HSTS; invariant globalization\n or app-local ICU (runtime has no libicu).\n3. blazor/: minimal Blazor Static SSR app (one SSR page; wwwroot/app.css), same shim/readiness contract, untrimmed publish, ContentRootPath = AppContext.BaseDirectory\n when AWS_LAMBDA_HTTP_ENDPOINT is set, MapStaticAssets/MapRazorComponents; NO Interactive Server/Auto render modes. Reference https://github.com/j-d-ha/lambda-web-function-not-node (src/blazor, src/node-wrapper).\n4. build script (samples/web-functions/build-artifacts.sh): produces nextjs.zip, aspnetcore.zip, blazor.zip (and a second \"v2\" build id variant for the revision-update test) into an\n output folder; uses Docker/`--platform linux/arm64` or `dotnet publish -r linux-arm64 --self-contained`; documents prerequisites (Node 24+, pnpm/npm, .NET 10 SDK, Docker optional).\n5. Local smoke check per artifact (run the server with AWS_LAMBDA_HTTP_ENDPOINT=127.0.0.1:PORT and a mock readiness endpoint, assert the page/asset/status) — local only.\n\nConstraints: samples get their own Directory.Build.props/Directory.Packages.props overrides if needed so they do not alter the library build; framework-only dependencies for .NET samples\n(do not add packages to the repo's central Directory.Packages.props). Use .NET 10 (GA) for samples. No AWS calls.\n","acceptance_criteria":"- Three sample apps and the build script exist under samples/web-functions/; artifacts build reproducibly and pass local smoke checks (record commands and output).\n- Blazor sample is Static SSR only, serves a rendered page and app.css.\n- Library solution build/tests unaffected (samples not in slnx; central package file unchanged); validation gates pass.","notes":"T7a evidence — samples/web-functions (build id 8024874b91cc)\n\nArtifacts (./build-artifacts.sh --clean):\n- build/nextjs.zip (12M) + nextjs-v2.zip\n- build/aspnetcore.zip (45M) + aspnetcore-v2.zip\n- build/blazor.zip (44M) + blazor-v2.zip\n\nBuild commands:\n- cd samples/web-functions \u0026\u0026 ./build-artifacts.sh [--clean|--only \u003capp\u003e|--build-id \u003cid\u003e|--out \u003cdir\u003e]\n- nextjs: npm ci + next build (output:\"standalone\"); zip root = .next/standalone/. + .next/static + public + index.js + build-id.txt\n- aspnetcore/blazor: dotnet publish -c Release -r linux-arm64 --self-contained -p:PublishTrimmed=false -p:TargetFramework=net10.0; zip root = publish output + index.js + build-id.txt\n\nLocal validation (./smoke-artifacts.sh [--only \u003capp\u003e]):\n- shim parse: node --check on all three apps/*/index.js -\u003e ok\n- nextjs: PASS (SSR heading, build id, sample.txt static asset)\n- aspnetcore: PASS (/health backend+buildId, /status requestTimeUtc, readiness POST received) under mcr.microsoft.com/dotnet/runtime-deps:10.0 --platform linux/arm64\n- blazor: PASS (rendered page, app.css, _framework/blazor.web.js, readiness POST received)\n\nLayout/permission checks:\n- no absolute-path entries in any zip\n- server entry mode -rwxr-xr-x in aspnetcore.zip and blazor.zip\n- nextjs top-level: server.js, index.js, package.json, build-id.txt\n- blazor contains wwwroot/app.css + wwwroot/_framework/blazor.web.js\n- v1 vs v2 build-id.txt differ (8024874b91cc vs 8024874b91cc-v2)\n- Blazor Static SSR only; no Interactive Server/Auto/AddInteractive anywhere in source\n\nLibrary unaffected:\n- dotnet build LayeredCraft.Cdk.Constructs.slnx -c Release =\u003e 0 warnings, 0 errors\n- tests 535/535 pass on net8.0, net9.0, net10.0, net11.0\n- golden templates unchanged; samples not referenced by slnx; central Directory.Packages.props / Directory.Build.props unchanged\n\nLimitations: local smoke covers the HTTP contract and readiness handshake only; real deployment, CloudFront/OAC behavior, and runtime scaling are not verifiable without AWS (deferred to T7b). Docker Desktop on macOS cannot bind-mount the /var/folders TMPDIR, so smoke work dirs live under build/.smoke/.\nT7a corrections (F1-F8) — validated 2026-10-23 (macOS arm64; Node v26.7.0/npm 11.19.0; .NET 10.0.103; Docker 29.2.1).\n\nF1 --out normalization: build-artifacts.sh resolves --out to an absolute path (against the caller's CWD) before any cd. Relative and absolute --out both write zips to the intended directory and leak no build directory into the source tree. Covered by tools/test-tooling.sh.\n\nF2 safe cleanup: --clean removes only generated content (*.zip, stage/, .smoke/) inside --out and never deletes --out itself or unrelated files. tools/test-tooling.sh uses sentinels (KEEP.txt, unrelated.txt, subdir) that survive --clean: 4/4 regression cases PASS.\n\nF3 Next.js platform deps: next.config.mjs sets images.unoptimized=true; the build installs with `npm ci --os=linux --cpu=arm64 --libc=glibc`. nextjs.zip now contains @img/sharp-linux-arm64 + @img/sharp-libvips-linux-arm64 and no darwin/win32 native modules (previously darwin-arm64). The artifact targets linux/arm64 and is not host-independent.\n\nF4 real entrypoints: smoke-artifacts.sh mounts the extracted artifact read-only at /var/task in public.ecr.aws/lambda/nodejs:24 (linux/arm64, Node v24.22.1, process.execve present) and runs `node /var/task/index.js`. ASP.NET Core and Blazor exercise the Node.js execve shim; the readiness POST is verified through a mock runtime API.\n\nF5 stronger checks: asserts the artifact's actual build-id.txt value in the running app (nextjs page, aspnetcore /health), fetches a real /_next/static/*.js chunk (HTTP 200), validates all six zips (v1 + v2), and asserts v2 id == v1 id + \"-v2\".\n\nF6 diagnostics: containers run without --rm; on failure the script prints the container and mock-runtime logs before failing, then removes the containers on exit. Negative test (injected crash) captured the app's \"simulated crash marker\" stderr and left no containers behind.\n\nF7 determinism: README and the build script header state builds are repeatable but not byte-for-byte reproducible (ZIP mtimes/ordering, Next.js generated identifiers).\n\nF8 tracing root: next.config.mjs sets outputFileTracingRoot to the app directory; server.js remains at the zip root.\n\nValidation: `./build-artifacts.sh --clean` =\u003e nextjs.zip 12M, aspnetcore.zip 44M, blazor.zip 44M (+ -v2 variants). `./smoke-artifacts.sh` =\u003e all six artifacts PASS through their index.js in the Lambda nodejs:24 image (nextjs: heading + build id + public asset + static chunk; aspnetcore: /health build id + /status dynamic + readiness; blazor: page + app.css + _framework/blazor.web.js + readiness). Library Release build 0 warnings/0 errors; tests 535/535 on net8.0/net9.0/net10.0/net11.0; golden templates unchanged; root build config, slnx, and src unchanged. Not committed.","spec_id":"docs/designs/lambda-web-functions-integration.md","status":"closed","priority":2,"issue_type":"task","owner":"ncipollina@gmail.com","created_at":"2026-10-23T01:14:56Z","created_by":"Nick Cipollina","updated_at":"2026-10-23T20:03:37Z","started_at":"2026-10-23T19:19:08Z","closed_at":"2026-10-23T20:03:37Z","close_reason":"T7a corrections F1-F8 applied and validated: safe --out handling, targeted cleanup with sentinel regression tests, linux-arm64 Next.js native deps, real index.js execution in the Lambda nodejs:24 base image for all three workloads, stronger build-id/static-chunk/v1-v2 checks, failure diagnostics, corrected determinism claims, pinned tracing root. All six artifacts pass smoke; library build/tests/goldens unaffected. Not committed (awaiting maintainer acceptance).","external_ref":"gh-98","labels":["lambda-web-functions","samples","sandbox","t7"],"dependencies":[{"issue_id":"cdkc-18e.11","depends_on_id":"cdkc-18e","type":"parent-child","created_at":"2026-10-23T01:14:56Z","created_by":"Nick Cipollina","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0} +{"_type":"issue","id":"cdkc-18e.10","title":"T6b: Update README, testing docs, CHANGELOG, and repo CLAUDE.md for Web Functions","description":"Purpose: repository-level docs for the release. Design §16 (last bullets), §13 (semver/CDK floor).\n\nDeliverables:\n- docs/testing/index.md: WebFunctionConstructAssertions and WebFunctionConstructPropsBuilder usage (from the Testing helpers bead).\n- README.md: construct list entry and short example.\n- docs/index.md: construct list.\n- CHANGELOG.md: new types; Amazon.CDK.Lib minimum raised to 2.274.0; no changes to existing constructs; KMS deferral; FromAsset not yet available.\n- CLAUDE.md (repo): architecture section entry for the Web Function constructs and Testing helpers (keep style).\nExclusions: version number bumps / VersionPrefix changes (maintainer decides at release; design §18 item 7); release notes publishing.\nValidation: `uv run mkdocs build --clean`; samples match the API.\n","acceptance_criteria":"- README, docs/index.md, docs/testing/index.md, CHANGELOG.md, CLAUDE.md updated consistently with the implemented API.\n- No version-number changes; mkdocs build succeeds.","notes":"T6b IMPLEMENTATION (2026-10-23, session T6b-docs).\\n\\nFiles changed (docs only; no production/dependency changes):\\n- README.md: +Web Functions feature bullet; new 'Quick Start \u003e Web Function' example (WebFunctionCode.FromBucket + IamAuth endpoint; compiles against public API); Documentation links for Web Function Construct + Web Function Workloads; Requirements CDK floor 2.203.1+ -\u003e 2.274.0+.\\n- docs/index.md: +Web Functions key-feature bullet; +Web Function Construct entry under Available Constructs; +Web Function Workloads link; CDK floor -\u003e 2.274.0+.\\n- docs/testing/index.md: +'## Web Function Testing' section (Props Builder, Assertion Methods, AutoData Support, Golden-Template Conventions, CDK/jsii Compatibility Considerations); +WebFunctionConstructAutoDataAttribute in Custom Attributes; +Web Function test files in Examples list.\\n- CHANGELOG.md: +'## [Unreleased]' entry (Added: WebFunctionConstruct/Endpoint/Origin + models + testing helpers; Changed: Amazon.CDK.Lib min 2.274.0; Notes/Deferrals: existing constructs zero diff, FromAsset not available, customer-managed revision KMS deferred, principal-behavior regression rule, F3006 warnings). No package version claimed.\\n- CLAUDE.md: Project Overview +Core Components WebFunctionConstruct; Configuration Models Web Function line; Target Frameworks 2.274.0; Test Architecture attr/customization; Testing Helpers CreateWebFunctionPropsBuilder + WebFunctionConstructAssertions/WebFunctionConstructPropsBuilder/Golden Templates; new 'CDK Upgrade Regression Rule' section (CdkUpgradeGuard_* gate + jsii principal-materialization detection).\\n- .beads/issues.jsonl: status update.\\n\\nVALIDATION EVIDENCE:\\n- uv run mkdocs build --strict --clean =\u003e RC=0. Only expected INFO: design doc not in nav. No link/validation errors.\\n- README Quick Start + docs/testing Props Builder/Assertion/AutoData snippets compiled in isolated consumer project (/var/folders/.../t6adocs-compile, Amazon.CDK.Lib 2.274.0 + ProjectReference): Build succeeded, 0 warnings, 0 errors. Used all public APIs only (including Constructs namespace fix added to README example).\\n- dotnet build -c Release =\u003e Build succeeded, 0 warnings, 0 errors.\\n- dotnet run --project test/LayeredCraft.Cdk.Constructs.Tests/ --framework net8.0 =\u003e Total: 535, Errors: 0, Failed: 0, Skipped: 0.\\n- Golden templates untouched: git status --porcelain test/.../GoldenTemplates/ empty (no existing-construct golden changes).\\n- Only docs + .beads changed; no public API/dependency changes (Directory.Packages.props untouched).\\n- T6b NOT committed (per instructions).","spec_id":"docs/designs/lambda-web-functions-integration.md","status":"closed","priority":2,"issue_type":"task","owner":"ncipollina@gmail.com","created_at":"2026-10-23T01:14:55Z","created_by":"Nick Cipollina","updated_at":"2026-10-23T19:10:54Z","started_at":"2026-10-23T19:06:42Z","closed_at":"2026-10-23T19:10:54Z","close_reason":"T6b complete: README, docs/testing, CHANGELOG, CLAUDE.md updated for Lambda Web Functions. Evidence: mkdocs --strict RC=0; examples compile against public API (0 warn/0 err); dotnet build Release 0/0; tests 535 passed/0 failed; zero golden changes; no dependency changes. Not committed (per instructions).","external_ref":"gh-98","labels":["docs","lambda-web-functions","t6"],"dependencies":[{"issue_id":"cdkc-18e.10","depends_on_id":"cdkc-18e","type":"parent-child","created_at":"2026-10-23T01:14:55Z","created_by":"Nick Cipollina","metadata":"{}"},{"issue_id":"cdkc-18e.10","depends_on_id":"cdkc-18e.8","type":"blocks","created_at":"2026-10-23T01:15:17Z","created_by":"Nick Cipollina","metadata":"{}"}],"dependency_count":1,"dependent_count":1,"comment_count":0} +{"_type":"issue","id":"cdkc-18e.9","title":"T6a: Write Web Function construct docs, security guidance, and workload recipes","description":"Purpose: user documentation for the constructs and the three workload recipes. Design §16 (AUTHORITATIVE content list), §5 (facts), §10–§12 (security/deployment), §14 (documented-not-validated list), §8.7.\n\nDeliverables:\n- docs/constructs/web-function.md: overview; auth modes and who can reach an endpoint (ApplicationManaged is public even behind CloudFront; IamAuth ≠ user auth);\n WebFunctionCode.FromBucket requirements (versioning, s3:GetObject/GetObjectVersion, /revision/* SourceArn statement, optional VersionId semantics, cross-account buckets,\n SSE-KMS key policy, CDK bootstrap bucket incompatibility, object must exist before deploy); WebFunctionLogs (TWO_WEEKS default, ONE_MONTH example, ServiceDefault no expiry);\n endpoints/AddEndpoint and revision-change behavior; GrantInvoke table from §10.2 incl. ExternallyManaged contract and caller-side SigV4 (service lambda, UNSIGNED-PAYLOAD,\n Authorization stripping); single-owner resource-policy contract; WebFunctionOrigin (OAC, same-stack rule, ExternallyManaged, imported endpoints);\n cache/header guidance (§11.3: never forward Host / use ALL_VIEWER_EXCEPT_HOST_HEADER, Authorization in cache policy, Lambda@Edge origin triggers rejected, opt-in Regions 403);\n replacement table (§12.2); validation errors (§14); KMS deferral + unsupported escape hatch (§8.7); limitations.\n- Workload recipes (same page or docs/examples/web-functions.md): Next.js standalone; ASP.NET Core via Node.js execve shim (self-contained linux-arm64 apphost \"server\", index.js\n `process.execve(\"/var/task/server\", [\"/var/task/server\"], process.env);`, Kestrel on http://$AWS_LAMBDA_HTTP_ENDPOINT, readiness POST to\n http://$AWS_LAMBDA_RUNTIME_API/2025-09-01/ready after start, app-local ICU or invariant globalization, no HTTPS redirection/HSTS); Blazor Static SSR (same shim; untrimmed server;\n ContentRootPath = AppContext.BaseDirectory when AWS_LAMBDA_HTTP_ENDPOINT is set; wwwroot/_framework shipped; cache fingerprinted assets; Interactive Server/Auto/legacy Blazor Server\n UNSUPPORTED — WebSockets rejected). Mark execve/readiness as not documented by AWS. Reference https://github.com/j-d-ha/lambda-web-function-not-node.\n- mkdocs.yml nav entry under Constructs (and examples page if created). Do NOT add the design doc to nav.\n- docs/examples/index.md: §9 examples.\n\nExclusions: README/CHANGELOG/testing docs (separate bead); no code changes.\nValidation: `uv run mkdocs build --clean` succeeds; every code sample matches the implemented public API (cross-check against src/).\n","acceptance_criteria":"- docs/constructs/web-function.md and recipes cover every §16 item, including security callouts and the §10.2 grant table.\n- Three workload recipes are complete and explicitly distinguish Blazor Static SSR from Interactive Server.\n- mkdocs nav updated; mkdocs build succeeds; samples match the real API.","notes":"Also document (derived from design §8.2 + §12.1, found during planning): with WebFunctionCodeBucketPolicy.Automatic the code object must exist before the revision is created, so in practice the owned bucket must live in a separately deployed stack (deploy bucket stack -\u003e upload artifact -\u003e deploy function stack). A bucket created in the same stack as the function cannot be pre-populated.\nREVIEW ROUTING (2026-10-23, design revision 4). Add to docs/constructs/web-function.md:\n(1) Log-group switching: moving an EXISTING function from WebFunctionLogs.ServiceDefault() to Create(), or redeploying after stack deletion while /aws/lambda/web/{name} still exists, fails with AlreadyExists because Lambda auto-creates the group. Document the remedies: Use(LogGroup.FromLogGroupName(...)), or delete/import the group.\n(2) CDK 2.274 emits F3006 'Unknown resource type AWS::Lambda::WebFunction*' validation warnings, which become synthesis ERRORS when @aws-cdk/core:validateAgainstDefaultRules is enabled. Document the acknowledgement IDs (CloudFormation-Validate::F3006) and the consequence.\n(3) GrantInvoke rejects service principals (CloudFront → GrantCloudFrontInvoke; other services → explicit condition-scoped AddToResourcePolicy) and unconditioned wildcards; same-account AccountPrincipal is not 'complete'.\n(4) The revision no longer waits for execution-role DefaultPolicy statements; a brief IAM-propagation window can occur on first deploy.\n(5) Owned-bucket limitation: versioning enabled only by an escape-hatch override is not detected; workaround Bucket.FromBucketName + ExternallyManaged.\n(6) IWebFunctionEndpoint is not intended for consumer implementation.\nMaintainer clarification (2026-10-23):\n(7) Conditioned wildcard resource-policy statements are supported only through explicit AddToResourcePolicy. The consumer is responsible for ensuring the conditions meaningfully restrict access; the library checks only that conditions are present.\n(8) Imported endpoints: document the optional Account attribute. GrantInvoke needs an established endpoint account (literal ARN or literal Account); a token-ARN endpoint is still usable as an ExternallyManaged OAC origin.\nFrom T4 independent review (F1): document the IOrigin.Bind exception behavior. Exceptions thrown inside IOrigin.Bind (and inside CDK's HttpOrigin constructor) cross the jsii boundary and surface to .NET callers as System.Exception carrying the original message (e.g. \"connectionAttempts: Must be an int between 1 and 3 (inclusive); received 5.\"), whereas WebFunctionOrigin factory-time validation (auth mismatch, nulls) throws InvalidOperationException directly. Cover this in the Web Function security/usage docs.\nT6a DOCUMENTATION COMPLETE (not committed).\n\nFiles: NEW docs/constructs/web-function.md (construct reference); NEW docs/examples/web-functions.md (three workload recipes); MODIFIED mkdocs.yml (added \"Web Function\" under Constructs and split Examples into Overview + \"Web Function Workloads\"; design doc intentionally NOT added to nav); MODIFIED docs/examples/index.md (new \"Web Function Examples\" section reproducing design 9.1-9.7 using only the real public API).\n\nConstruct page contents: when to use WebFunctionConstruct; intentional non-goals (v1); prerequisites (CDK \u003e= 2.274.0, explicit-Env stack, versioned bucket with an uploaded artifact, bootstrap not usable); S3 artifact requirements and ownership (versioning required, VersionId pinning, Lambda service-principal read with the /revision/* aws:SourceArn statement, Automatic vs ExternallyManaged, SSE-KMS key-policy requirement, cross-account/cross-region, 409 Platform.RevisionNotActive when the pinned object/read access disappears) with a warning that the artifact (and an externally managed bucket policy) must exist before deploy and that an owned bucket must be separately deployed; execution role (AWSLambdaBasicExecutionRole default / Role override) and logging (WebFunctionLogs Create/ServiceDefault/Use, retention default TWO_WEEKS, log levels); function revisions and endpoints (default endpoint, AddEndpoint, reserved child ids, replace-vs-no-interruption semantics); authentication modes table (IamAuth vs ApplicationManaged) with the explicit warning that IamAuth is a transport boundary, not user authentication; invocation grants (GrantInvoke overloads, GrantCloudFrontInvoke, identity vs resource policy); resource-policy single-owner contract (endpoint-only entry points, Resource must be exactly the endpoint ARN, validate-then-freeze, dedup, no other AWS::Lambda::ResourcePolicy/Permission); imported endpoints (FromEndpointAttributes, owns nothing, literal validation, optional Account for token ARNs); CloudFront OAC integration (With/WithoutOriginAccessControl, factory-time auth check, same-stack automatic rule, ExternallyManaged two-phase, one OAC per distribution, supplied OAC used unchanged) plus caching/header guidance (never forward Host use ALL_VIEWER_EXCEPT_HOST_HEADER, CACHING_DISABLED for dynamic routes, Authorization cache-policy caveat, CloudFront Function host recovery, CACHING_OPTIMIZED for content-hashed assets, Lambda@Edge origin triggers rejected, opt-in Region 403, transient 403 after deploy); public testing helpers; known limitations and operational guidance; validation-error table; links to the testing guide and examples.\n\nSecurity/IAM model documented plainly: owned vs imported principals; owned vs imported endpoints; same-stack environment-agnostic grants; cross-stack and cross-account restrictions; identity-policy vs resource-policy permissions; Automatic vs ExternallyManaged caller policies with an explicit warning that ExternallyManaged does NOT mean invocation permissions have been configured; why GrantInvoke rejects service principals (use GrantCloudFrontInvoke or an explicit AddToResourcePolicy), account principals, wildcard principals, PrincipalWithConditions and WithoutPolicyUpdates; GrantCloudFrontInvoke SourceArn scoping; consumer responsibility for explicit conditioned wildcard policies; the imported endpoint optional Account attribute; conditions that cannot be fully validated during synthesis.\n\nWorkload recipes: Next.js standalone (artifact prep, index.js shim env mapping, entry-point expectation, CloudFront OAC + static-asset caching, ISR/image caveats); ASP.NET Core (self-contained linux-arm64 server apphost + Node.js execve shim, Kestrel on AWS_LAMBDA_HTTP_ENDPOINT, readiness POST to the runtime API, no HTTPS redirection/HSTS, app-local ICU or invariant globalization, CloudFront integration); Blazor Static SSR (same shim/readiness, untrimmed publish, ContentRootPath, wwwroot/_framework size, cache fingerprinted assets; Interactive Server/Auto/legacy UNSUPPORTED). Each recipe states that configurations synthesize but runtime behavior still requires AWS deployment; a \"Sandbox validation\" section lists exactly what synthesis tests do NOT prove (execve shim, readiness POST, first request, OAC end-to-end including transient 403), leaving real deployed smoke validation to T7c.\n\nKnown issues/operational guidance: S3 versioning configured exclusively through escape hatches is not inspected; tokenized bucket configuration is skipped by validation; log-group switching AlreadyExists with remedies; IAM policy propagation when revisions become active (CfnRole-only dependency); CloudFront origin-binding exceptions surface as System.Exception through jsii vs InvalidOperationException at the factory; F3006 warnings and the CloudFormation-Validate::F3006 acknowledgement / validateAgainstDefaultRules consequence; OAC naming; origin-request policy requirements (AllViewerExceptHostHeader vs AllViewer); imported endpoints with externally managed permissions.\n\nVALIDATION: `uv run mkdocs build --clean` =\u003e rc=0, \"Documentation built\" (the only notice is the Material for MkDocs 2.0 team announcement; the design doc is expectedly absent from nav). Relative links verified to resolve: docs/constructs/web-function.md -\u003e ../examples/web-functions.md, ../testing/index.md, ../examples/index.md; docs/examples/web-functions.md -\u003e ../constructs/web-function.md and ../constructs/web-function.md#caching-and-header-guidance (heading \"### Caching and header guidance\" at line 307); docs/examples/index.md -\u003e ../constructs/web-function.md. Every code sample cross-checked against the implemented public API in src via grep (WebFunctionConstruct, IWebFunctionEndpoint, WebFunctionLogs, WebFunctionOrigin, WebFunctionEndpointConstruct.FromEndpointAttributes, WebFunctionConstructProps, WebFunctionEndpointOptions, WebFunctionCode.FromBucket/options, WebFunctionEndpointAttributes, WebFunctionInvokeGrantOptions, WebFunctionOriginProps/WithOacProps). No contradiction with revision 4. `dotnet build LayeredCraft.Cdk.Constructs.slnx -c Release` =\u003e 0 warnings / 0 errors (docs are markdown only and do not affect build inputs). mkdocs artifacts .venv/ and site/ are gitignored. No production construct changed; Sharedale untouched.\nT6a CORRECTION EVIDENCE (independent-review findings 1-9 resolved; awaiting maintainer acceptance; NOT committed).\n\nDocs changed: docs/constructs/web-function.md (~413 lines), docs/examples/web-functions.md (~205 lines), docs/examples/index.md (Web Function Examples section), mkdocs.yml (nav). No production construct changed.\n\nFinding 1 (grant direction): docs/examples/web-functions.md ASP.NET Core recipe now calls api.DefaultEndpoint.GrantInvoke(web) (was web.DefaultEndpoint.GrantInvoke(api)). The identity policy is written on the caller (the Next.js front end \"web\"); the API remains the invoke target.\n\nFinding 2 (code-bucket ownership): docs/constructs/web-function.md - the S3 Artifact Requirements read-access bullet now states Lambda reads with the Lambda service principal and the Automatic statement is scoped with BOTH StringEquals aws:SourceAccount and ArnLike aws:SourceArn (arn:aws:lambda:{region}:{account}:web-function/{FunctionName}/revision/*); the Automatic bullet now says it manages an owned bucket, including a bucket owned by another stack when that stack's account and Region are explicitly resolvable, while an imported bucket or a cross-stack bucket with unresolved environment info fails and asks for ExternallyManaged. The \"artifact must exist before you deploy\" warning now says a same-stack owned bucket does not contain the artifact at first deployment and the artifact must be uploaded before the function stack deploys (a separately deployed bucket is a good fit; any pre-populated bucket works). docs/examples/index.md Next.js comment corrected accordingly.\n\nFinding 3 (wildcard conditions): \"Why GrantInvoke rejects certain principals\" now explains AddToResourcePolicy only checks that an Allow wildcard statement HAS conditions and does not verify they restrict access; the consumer owns the condition semantics (aws:PrincipalOrgID given as a potentially meaningful restriction); the mere presence of a condition proves nothing.\n\nFinding 4 (ExternallyManaged + account principals): the account-principal bullet now states account-root is never a complete Automatic grant, and under ExternallyManaged an explicitly requested account principal may be recorded in the OWNED endpoint's resource policy while caller-side authorization is still not configured. The Imported Endpoints section now states GrantInvoke with CallerPolicy = ExternallyManaged also throws on an imported endpoint because there is no owned resource policy to receive the statement.\n\nFinding 5 (reference material): three new sections added to docs/constructs/web-function.md before \"Public Testing Helpers\": \"Grant Behavior Reference\" (grantee x caller-policy matrix matching rev-4 section 10.2, incl. \"partial by contract\" definition), \"Signing Requests\" (SigV4 service name lambda; x-amz-content-sha256: UNSIGNED-PAYLOAD; MultiRegion SigV4A with region *; direct IAM invocation vs CloudFront OAC signing; Lambda strips its own SigV4 Authorization), and \"Resource Replacement and Update Behavior\" (rev-4 section 12.2 table: revision-triggering changes, Endpoint AuthType transitions with transient 403, EndpointName/EndpointType/Regions/FunctionName replacement, distribution replacement, clearing scaling/throttling, no unverified AWS behavior asserted as proven).\n\nFinding 6 (namespaces + real compilation): added a \"Required namespaces\" section to docs/examples/web-functions.md. Created an isolated consumer project (/var/folders/d5/h9s1_byj70391flgcvsfsqn40000gn/T/opencode/t6adocs-compile: net8.0 exe, ProjectReference to src/LayeredCraft.Cdk.Constructs, Amazon.CDK.Lib 2.274.0) whose Examples.cs reproduces the documented examples via the public API only; it compiles green (Basic Usage; ASP.NET Core api + api.DefaultEndpoint.GrantInvoke(web); Next.js web with ObjectVersion; cross-account partner with ExternallyManaged; Next.js CloudFront OAC distribution; Blazor CloudFront distribution; imported-endpoint ExternallyManaged origin). NOTE for consumers with ImplicitUsings enabled: qualify Amazon.CDK.Environment (System.Environment is otherwise ambiguous).\n\nFinding 7 (config/exception accuracy): MaxConcurrencyPerEnvironment now reads \"Max concurrent requests per environment, 1-128 (AWS default 64)\". The Known Limitations section retains that bind-time CloudFront origin exceptions surface as System.Exception through jsii while factory-time checks throw InvalidOperationException. The \"Same-stack, environment-agnostic grants\" paragraph now says Automatic grants are valid when the owned caller and endpoint belong to the same Stack instance, and that two separate env-agnostic stacks are NOT the same stack.\n\nFinding 8 (operational): supplied execution roles are documented as receiving no AWSLambdaBasicExecutionRole and no automatic log-write grant; Create()-to-ServiceDefault() is documented as deleting the stack-owned log group (default DESTROY) with Lambda recreating the default group without expiry; OAC naming collisions are documented as identical names across Regions within the SAME account; cross-stack ExternallyManaged CloudFront is documented to use a literal distribution ARN; linux-arm64 is described as the recipe's tested target (not asserted as AWS-confirmed); the 10-second listen deadline on AWS_LAMBDA_HTTP_ENDPOINT is documented; internal \"Sharedale-style\" wording removed; the Blazor CloudFront example was completed with a full Distribution (DefaultBehavior + /_framework/* and /_content/* CACHING_OPTIMIZED + DomainNames + Certificate).\n\nFinding 9 (KMS): recorded on cdkc-18e.14 (T8 release-readiness) for evaluation before publication - the KMS error messages say \"a customer-managed key the function role can read\" but Lambda reads/decrypts the artifact with the Lambda service principal, so the KMS key policy must allow that principal kms:Decrypt. No production code changed in T6a.\n\nValidation evidence: uv run mkdocs build --strict --clean succeeded (only the intentional INFO that docs/designs/lambda-web-functions-integration.md is not in nav); dotnet build LayeredCraft.Cdk.Constructs.slnx -c Release = 0 warnings / 0 errors; full 4-TFM suite = total 2140, failed 0, skipped 0; relative links and anchors verified (web-function.md headings caching-and-header-guidance, grant-behavior-reference, signing-requests, resource-replacement-and-update-behavior, public-testing-helpers all exist; mkdocs nav has \"Web Function\" and \"Web Function Workloads\"); git status --porcelain test/LayeredCraft.Cdk.Constructs.Tests/GoldenTemplates/ is empty, so all 17 existing-construct goldens remain byte-identical.\n\nStatus: bead reopened and set in_progress; T6a docs are NOT committed pending maintainer acceptance.","spec_id":"docs/designs/lambda-web-functions-integration.md","status":"closed","priority":2,"issue_type":"task","assignee":"Nick Cipollina","owner":"ncipollina@gmail.com","created_at":"2026-10-23T01:14:54Z","created_by":"Nick Cipollina","updated_at":"2026-10-23T17:06:12Z","started_at":"2026-10-23T16:32:30Z","closed_at":"2026-10-23T17:06:12Z","close_reason":"T6a documentation corrections complete (independent-review findings 1-9 resolved): grant direction fixed; code-bucket ownership guidance corrected (service-principal read, SourceAccount+SourceArn, cross-stack Automatic only when account/Region resolvable, artifact-must-exist warning); wildcard-condition responsibility documented; ExternallyManaged/account-principal and imported-endpoint rules corrected; added Grant Behavior Reference, Signing Requests, and Resource Replacement and Update Behavior sections; required namespaces added and representative examples compiled green against the library in an isolated consumer project; MaxConcurrencyPerEnvironment, jsii System.Exception, and env-agnostic same-stack wording corrected; operational items fixed (supplied-role log-write, Create-\u003eServiceDefault log-group deletion, OAC naming scope, literal distribution ARN cross-stack, linux-arm64 as tested target, 10s listen deadline, Sharedale references removed, Blazor CloudFront example completed); KMS message issue recorded on cdkc-18e.14. Validation: mkdocs --strict green, Release build 0/0, full 4-TFM suite 2140 pass, links/anchors verified, 17 goldens byte-identical. NOT committed pending maintainer acceptance.","external_ref":"gh-98","labels":["docs","lambda-web-functions","t6"],"dependencies":[{"issue_id":"cdkc-18e.9","depends_on_id":"cdkc-18e","type":"parent-child","created_at":"2026-10-23T01:14:54Z","created_by":"Nick Cipollina","metadata":"{}"},{"issue_id":"cdkc-18e.9","depends_on_id":"cdkc-18e.6","type":"blocks","created_at":"2026-10-23T01:15:16Z","created_by":"Nick Cipollina","metadata":"{}"}],"dependency_count":1,"dependent_count":2,"comment_count":0} +{"_type":"issue","id":"cdkc-18e.7","title":"T4a (optional): Spike narrow warning for managed AllViewer policy on Web Function origins","description":"OPTIONAL, time-boxed (≤ 4 hours). The feature must not depend on the outcome. Design §11.1 (\"Removed in revision 2\" paragraph), §18 item 4, §19 T4a.\n\nQuestion: can a narrow, warning-only check detect a Distribution behavior that targets a WebFunctionOrigin with the MANAGED AllViewer origin request policy\n(id 216adef6-5c7f-47e4-b989-5492eafa07d3) using only public CDK APIs on objects the library already holds (e.g. the BehaviorOptions/Origin object identity), WITHOUT resolving\nCloudFormation templates, tokens, or CfnDistribution.DistributionConfig?\n\nRules: disposable spike code first (scratch or a throwaway test); no template-resolution machinery; zero false positives; emits Annotations warning only (never an error).\nOutcome A (feasible and simple): implement it within WebFunctionOrigin with tests (warning present for AllViewer; absent for ALL_VIEWER_EXCEPT_HOST_HEADER and custom policies).\nOutcome B (not feasible): record findings in notes and close as \"won't implement\"; documentation (cdkc docs bead) already covers the Host-header rule.\nExclusions: Lambda@Edge detection, opt-in Region detection, any IValidation that resolves templates.\n","acceptance_criteria":"- Findings recorded in notes with the exact approach tried and the decision (A or B).\n- If A: warning-only check, tests prove no false positives, golden templates unchanged, validation gates pass.\n- If B: no production code changes remain.","notes":"T4a spike (2026-10-25): Decision = Outcome B (will not implement). Question: can a narrow warning-only check detect a Distribution behavior that targets a WebFunctionOrigin using the MANAGED AllViewer origin request policy (216adef6-5c7f-47e4-b989-5492eafa07d3), using only public CDK APIs on objects the library already holds. Finding: the library holds only the IOrigin and, in Bind, receives IOriginBindOptions; in Amazon.CDK.Lib 2.274.0 IOriginBindOptions exposes only DistributionId and OriginId (verified in the package XML docs). The behavior origin request policy is not reachable without resolving the distribution config or CfnDistribution, both excluded by the spike rules. No zero-false-positive public-API signal exists, so implementing would violate the spike constraints. Docs already cover the rule (docs/constructs/web-function.md Known Limitations: use ALL_VIEWER_EXCEPT_HOST_HEADER, never ALL_VIEWER; design section 11.3). No production code changes. Closing as wont-implement.","spec_id":"docs/designs/lambda-web-functions-integration.md","status":"closed","priority":4,"issue_type":"spike","owner":"ncipollina@gmail.com","created_at":"2026-10-23T01:14:52Z","created_by":"Nick Cipollina","updated_at":"2026-10-25T18:19:49Z","closed_at":"2026-10-25T18:19:49Z","close_reason":"Outcome B: not feasible with public CDK APIs without template resolution (IOriginBindOptions exposes only DistributionId and OriginId); docs already cover the Host-header rule; no production code changes.","external_ref":"gh-98","labels":["lambda-web-functions","optional","t4a"],"dependencies":[{"issue_id":"cdkc-18e.7","depends_on_id":"cdkc-18e","type":"parent-child","created_at":"2026-10-23T01:14:52Z","created_by":"Nick Cipollina","metadata":"{}"},{"issue_id":"cdkc-18e.7","depends_on_id":"cdkc-18e.6","type":"blocks","created_at":"2026-10-23T01:15:14Z","created_by":"Nick Cipollina","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0} diff --git a/.beads/metadata.json b/.beads/metadata.json new file mode 100644 index 0000000..3e7d417 --- /dev/null +++ b/.beads/metadata.json @@ -0,0 +1,7 @@ +{ + "database": "dolt", + "backend": "dolt", + "dolt_mode": "embedded", + "dolt_database": "cdkc", + "project_id": "38acb13c-880a-4177-9877-f0773549aa4a" +} \ No newline at end of file diff --git a/.gitignore b/.gitignore index 249982b..11acc35 100644 --- a/.gitignore +++ b/.gitignore @@ -431,3 +431,10 @@ scripts/ .Trashes ehthumbs.db Thumbs.db + +# Beads / Dolt files (added by bd init) +.dolt/ +*.db +.beads-credential-key +.beads/proxieddb/ +*.gate.lock* diff --git a/CHANGELOG.md b/CHANGELOG.md index 8a676be..4dfc852 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,37 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [Unreleased] + +> **This feature is not released yet.** It is documented here ahead of the version bump the maintainer applies at release time. No released package version is claimed by this entry. + +### ✨ Added + +**Lambda Web Functions** — deploy an ordinary HTTP server (Next.js, ASP.NET Core, Blazor Static SSR, and so on) from a zip in a versioned S3 bucket, behind a managed HTTPS endpoint: + +- **`WebFunctionConstruct`**: owns one Web Function's function, revision, default endpoint, execution role (optional), log group (optional), and single resource-based policy. Supports `AddEndpoint` for additional endpoints. +- **`WebFunctionEndpointConstruct`** (`IWebFunctionEndpoint`): an individual endpoint, with `GrantInvoke` (identity- or resource-policy based), `GrantCloudFrontInvoke`, `AddToResourcePolicy`, and `FromEndpointAttributes` for imported endpoints. +- **`WebFunctionOrigin`**: returns a CloudFront `IOrigin` with origin access control (OAC) and the required resource-policy statement, for `IamAuth` endpoints. +- **Models**: `WebFunctionCode` / `WebFunctionCodeFromBucketOptions` / `WebFunctionCodeBucketPolicy`, `WebFunctionRuntime`, `WebFunctionLogs`, `WebFunctionEndpointOptions` (and `IWebFunctionEndpointOptions`), `WebFunctionEndpointAttributes`, `WebFunctionEndpointType`, `WebFunctionAuthType`, `WebFunctionCallerPolicy` / `WebFunctionInvokeGrantOptions`, `WebFunctionOriginProps` / `WebFunctionOriginWithOacProps` / `WebFunctionOriginPermissions`, and `WebFunctionConstructProps`. +- **Testing helpers**: `WebFunctionConstructAssertions` fluent `Template` assertions and `WebFunctionConstructPropsBuilder` via `CdkTestHelper.CreateWebFunctionPropsBuilder()` (plus `WebFunctionConstructAutoData`). + +### 🔄 Changed + +- **Minimum AWS CDK version**: `Amazon.CDK.Lib` minimum raised to **2.274.0**. Consumers below 2.274.0 receive an automatic NuGet resolution upgrade. This floor is required for the enum values the OAC signing configuration needs. + +### 📖 Notes and Deferrals + +- **No changes to existing constructs.** The Lambda Function, Static Site, DynamoDB Table, and Cognito User Pool constructs are unchanged; their golden templates show zero diff. +- **Artifacts** are read from an existing S3 object with `WebFunctionCode.FromBucket`. `WebFunctionCode.FromAsset` is **not available** in this release; the artifact must be uploaded to a versioned bucket before deployment. +- **Customer-managed revision encryption** (`KmsKeyArn`) is **deferred**. S3 artifact encryption (SSE-S3 / SSE-KMS on the code bucket) is supported. +- **Principal-behavior regression rule**: identity-policy write detection and principal classification rely partly on CDK/jsii behavior observed in `Amazon.CDK.Lib` 2.274.0. Every `Amazon.CDK.Lib` upgrade (including Dependabot bumps) must pass the focused real-CDK Web Function security tests — especially the `CdkUpgradeGuard_*` suite — and a failure blocks the upgrade until the signals are re-verified. The library fails closed when authorization cannot be established. +- **Compatibility**: Lambda Web Functions require a Region where the feature is available; CDK 2.274.0 emits `F3006` default-rule validation warnings for the new `AWS::Lambda::WebFunction*` resource types (warnings by default). +- **Service-created default log groups**: with `WebFunctionLogs.ServiceDefault()` the construct creates no `AWS::Logs::LogGroup`; the Lambda service creates `/aws/lambda/web/{name}` on first invocation. That group has no expiry and is **not** removed by CloudFormation on teardown, so it keeps your invocation history. CDK-managed `Create()` groups are stack-owned and follow their `RemovalPolicy`. + +### 🐛 Fixed + +- **KMS diagnostic wording**: the owned-artifact-bucket SSE-KMS and DSSE error messages now name the **Lambda service principal** (`lambda.amazonaws.com`) as the principal whose key policy must allow `kms:Decrypt`, instead of the function execution role. Authorization behavior is unchanged; only the message text and its tests changed. + ## [2.0.0] - 2025-08-06 ### ⚠️ BREAKING CHANGES diff --git a/CLAUDE.md b/CLAUDE.md index 8d1a30c..78c0947 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -7,6 +7,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co This is a .NET library that provides reusable AWS CDK constructs for serverless applications and static websites. The library is designed specifically for LayeredCraft projects and includes: - **Lambda Functions**: Comprehensive Lambda construct with integrated OpenTelemetry support, IAM management, and environment configuration +- **Web Functions**: AWS Lambda Web Functions served from an S3 artifact, with IAM or application-managed endpoints, endpoint-scoped grants, and CloudFront OAC origin integration - **Static Sites**: Complete static website hosting with S3, CloudFront, SSL certificates, Route53 DNS, and optional API proxying ## Commands @@ -51,6 +52,13 @@ dotnet add test/LayeredCraft.Cdk.Constructs.Tests/ package PackageName - Creates function versions and aliases for deployment management - Handles Lambda permissions for multiple targets (function, version, alias) +**WebFunctionConstruct** (`src/LayeredCraft.Cdk.Constructs/WebFunctionConstruct.cs`) +- Creates an AWS Lambda Web Function from a versioned S3 artifact (`WebFunctionCode.FromBucket`), plus its immutable revision, default endpoint, execution role (optional), log group (optional), and the function's **single** resource-based policy +- `WebFunctionEndpointConstruct` (`IWebFunctionEndpoint`) represents each endpoint; `AddEndpoint` adds more; `GrantInvoke` (identity- or resource-policy based) and `GrantCloudFrontInvoke` are endpoint-scoped +- `WebFunctionOrigin` returns a CloudFront `IOrigin` that configures origin access control (OAC) and the required resource-policy statement for `IamAuth` endpoints +- Workload-neutral: Next.js, ASP.NET Core, and Blazor Static SSR deploy through the same public API; the differences live in the artifacts and configuration only +- Requires `Amazon.CDK.Lib` 2.274.0+ (Lambda Web Functions have L1-only support in CDK) + **StaticSiteConstruct** (`src/LayeredCraft.Cdk.Constructs/StaticSiteConstruct.cs`) - Comprehensive CDK construct for static website hosting - Creates S3 bucket with public access for website hosting @@ -74,6 +82,7 @@ dotnet add test/LayeredCraft.Cdk.Constructs.Tests/ package PackageName - `LambdaPermission`: Record for defining Lambda invocation permissions - `StaticSiteConstructProps`: Configuration interface and record for static site construct - `DynamoDbTableConstructProps`: Configuration interface and record for DynamoDB table construct +- `WebFunctionConstructProps`, `WebFunctionCode`/`WebFunctionCodeFromBucketOptions`/`WebFunctionCodeBucketPolicy`, `WebFunctionEndpointOptions`/`IWebFunctionEndpointOptions`, `WebFunctionEndpointAttributes`, `WebFunctionLogs`, `WebFunctionRuntime`, `WebFunctionAuthType`, `WebFunctionEndpointType`, `WebFunctionCallerPolicy`/`WebFunctionInvokeGrantOptions`, `WebFunctionOriginProps`/`WebFunctionOriginWithOacProps`/`WebFunctionOriginPermissions`: Web Function configuration (see `docs/constructs/web-function.md`) **Extensions** (`src/LayeredCraft.Cdk.Constructs/Extensions/`) - `StackExtensions`: Utility methods for CDK Stack operations @@ -89,7 +98,7 @@ dotnet add test/LayeredCraft.Cdk.Constructs.Tests/ package PackageName ### Target Frameworks - .NET 8.0 and .NET 9.0 -- Uses AWS CDK v2 (Amazon.CDK.Lib 2.213.0) +- Uses AWS CDK v2 (Amazon.CDK.Lib 2.274.0 minimum; the Web Function constructs require the 2.274.0 enum values) ### OpenTelemetry Configuration (v2.0.0+) Starting with version 2.0.0, the OpenTelemetry layer configuration has been updated: @@ -121,10 +130,12 @@ var props = new LambdaFunctionConstructProps ### Test Architecture **Custom Attributes**: - `LambdaFunctionConstructAutoDataAttribute`: AutoFixture attribute with customizable parameters +- `WebFunctionConstructAutoDataAttribute`: AutoFixture attribute supplying deterministic Web Function props (imported, externally managed artifact bucket) - `BaseFixtureFactory`: Factory for creating configured AutoFixture instances **Test Customizations**: - `LambdaFunctionConstructCustomization`: Configures realistic test data for Lambda constructs +- `WebFunctionConstructCustomization`: Configures realistic test data for Web Function constructs - `StaticSiteConstructCustomization`: Configures realistic test data for static site constructs - Supports parameterized test scenarios for Lambda (OTEL layer on/off, permissions included/excluded) and static sites (API domain on/off, alternate domains included/excluded) @@ -146,6 +157,7 @@ The library includes comprehensive testing helpers for consumers: - `CreatePropsBuilder()`: Creates fluent builder with Lambda test defaults - `CreateStaticSitePropsBuilder()`: Creates fluent builder with static site test defaults - `CreateDynamoDbTablePropsBuilder()`: Creates fluent builder with DynamoDB table test defaults +- `CreateWebFunctionPropsBuilder()`: Creates fluent builder with Web Function test defaults (choose the auth mode explicitly) **LambdaFunctionConstructAssertions** (`LambdaFunctionConstructAssertions.cs`): - Extension methods for Template assertions @@ -171,6 +183,20 @@ The library includes comprehensive testing helpers for consumers: - Fluent builder for creating DynamoDB table test props with scenario-based configurations - Methods like `WithTableName()`, `WithPartitionKey()`, `WithSortKey()`, `WithGlobalSecondaryIndex()`, `WithStream()`, `WithTimeToLiveAttribute()`, `ForUserTable()`, `ForSessionTable()`, `ForEventSourcing()` +**WebFunctionConstructAssertions** (`WebFunctionConstructAssertions.cs`): +- Extension methods for `Template` assertions specific to Web Functions +- `ShouldHaveWebFunction()`, `ShouldHaveRevision()`, `ShouldHaveRevisionCode()`, `ShouldHaveEndpoint()`, `ShouldHaveEndpointScaling()`, `ShouldHaveInvokeGrant()`, `ShouldHaveSingleResourcePolicy()`, `ShouldHaveNoResourcePolicy()`, `ShouldAllowCloudFront()`, `ShouldAllowResourcePolicyPrincipal()`, `ShouldHaveWebFunctionOac()`, `ShouldHaveCodeBucketReadStatement()` +- Match by function and endpoint **names**, not logical IDs; require `Effect = Allow` with the expected action and endpoint resource + +**WebFunctionConstructPropsBuilder** (`WebFunctionConstructPropsBuilder.cs`): +- Fluent builder for Web Function props: `WithFunctionName()`, `WithCode()`, `WithTestArtifact()`, `WithIamAuthEndpoint()`, `WithApplicationManagedEndpoint()`, `WithEndpoint()`, `WithEnvironmentVariable()`, `WithEntryPoint()`, `WithTimeout()`, `WithMaxConcurrencyPerEnvironment()`, `WithRole()`, `WithLogs()`, `Build()` +- `Build()` throws without code or an endpoint; the builder never selects an auth mode + +**Golden Templates** (`test/LayeredCraft.Cdk.Constructs.Tests/GoldenTemplates/`): +- Full synthesized templates pinned for every construct via `GoldenTemplate.AssertMatches(stack, ".json")` +- Existing-construct goldens must show **zero diff** on any dependency or `Amazon.CDK.Lib` bump +- Regenerate intentionally with `UPDATE_GOLDEN_TEMPLATES=1` (the harness rewrites the checked-in file and fails once so the change is reviewed) + **Critical Testing Pattern**: - Always create CDK templates AFTER adding constructs to stacks - Use `Template.FromStack(stack)` after construct creation, not before @@ -204,6 +230,11 @@ The library includes comprehensive testing helpers for consumers: - Default memory: 1024MB, timeout: 6 seconds, log retention: 2 weeks - Uses `RemovalPolicy.RETAIN` for Lambda versions to prevent deletion +### CDK Upgrade Regression Rule +- The Web Function constructs classify IAM principals and decide whether to write an identity policy partly from the concrete .NET types jsii materializes (exported `Role`/`User`/`Group`/`LazyRole`/`PrincipalWithConditions`) versus interface proxies for CDK-private classes (immutable/imported roles). A `Amazon.CDK.Lib` upgrade can silently change that materialization and therefore the authorization outcome. +- Every `Amazon.CDK.Lib` upgrade — including Dependabot bumps — MUST run the focused real-CDK Web Function security tests, especially the `CdkUpgradeGuard_*` suite in `WebFunctionSecurityTests.cs`, before the upgrade is accepted. A failure blocks the upgrade until the behavior is re-verified. +- Authorization-behavior changes surface as an assertion mismatch on the expected policy direction (identity policy vs. resource policy vs. thrown error), not as a compile error. Review the `CdkUpgradeGuard_*` failures first when a CDK bump changes IAM output; the library fails closed when authorization cannot be established. + ## Testing Patterns ### CDK Infrastructure Testing diff --git a/Directory.Packages.props b/Directory.Packages.props index 764447b..bf4fe73 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -7,7 +7,7 @@ - + diff --git a/README.md b/README.md index cf6eca9..8bb6606 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,7 @@ A comprehensive library of reusable AWS CDK constructs for .NET projects, design ## Features - **🚀 Lambda Functions**: Comprehensive Lambda construct with configurable OpenTelemetry support, IAM management, and environment configuration +- **🕸️ Web Functions**: AWS Lambda Web Functions served from an S3 artifact, with IAM or application-managed endpoints, endpoint-scoped grants, and CloudFront OAC origin integration - **🌐 Static Sites**: Complete static website hosting with S3, CloudFront, SSL certificates, and Route53 DNS management - **📊 DynamoDB Tables**: Full-featured DynamoDB construct with streams, TTL, and global secondary indexes - **🔐 Cognito User Pools**: Complete Cognito user pool with custom domains, resource servers, OAuth clients, and Managed Login branding @@ -87,21 +88,59 @@ var table = new DynamoDbTableConstruct(this, "UserTable", new DynamoDbTableConst }); ``` +### Web Function + +An AWS Lambda Web Function runs an ordinary HTTP server (Next.js, ASP.NET Core, Blazor Static SSR, and so on) from a zip in a versioned S3 bucket. See the [Web Function Construct](https://layeredcraft.github.io/cdk-constructs/constructs/web-function) reference for the full configuration surface and the [Web Function Workloads](https://layeredcraft.github.io/cdk-constructs/examples/web-functions) page for per-framework recipes. + +```csharp +using Amazon.CDK; +using Amazon.CDK.AWS.S3; +using Constructs; +using LayeredCraft.Cdk.Constructs; +using LayeredCraft.Cdk.Constructs.Models; + +public class MyStack : Stack +{ + public MyStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props) + { + // The bucket must have versioning enabled and already contain the artifact. + var artifacts = Bucket.FromBucketName(this, "artifacts", "acme-artifacts"); + + var web = new WebFunctionConstruct(this, "Web", new WebFunctionConstructProps + { + FunctionName = "acme-web", + Code = WebFunctionCode.FromBucket(artifacts, "1.2.3/web.zip", new WebFunctionCodeFromBucketOptions + { + BucketPolicy = WebFunctionCodeBucketPolicy.ExternallyManaged, + }), + Endpoint = new WebFunctionEndpointOptions + { + AuthType = WebFunctionAuthType.IamAuth, + }, + }); + } +} +``` + +> **Compatibility:** Lambda Web Functions require **`Amazon.CDK.Lib` 2.274.0 or later** and a Region where the feature is available. `IamAuth` endpoints are invoked by signed (SigV4) callers; `ApplicationManaged` endpoints are publicly reachable, including behind CloudFront. + ## Documentation 📖 **[Complete Documentation](https://layeredcraft.github.io/cdk-constructs/)** - **[Lambda Function Construct](https://layeredcraft.github.io/cdk-constructs/constructs/lambda-function)** - Full-featured Lambda functions with OpenTelemetry, IAM, and more +- **[Web Function Construct](https://layeredcraft.github.io/cdk-constructs/constructs/web-function)** - Lambda Web Functions with S3 artifacts, IAM/application-managed endpoints, and CloudFront OAC - **[Static Site Construct](https://layeredcraft.github.io/cdk-constructs/constructs/static-site)** - Complete static website hosting with CloudFront and SSL - **[DynamoDB Table Construct](https://layeredcraft.github.io/cdk-constructs/constructs/dynamodb-table)** - Production-ready DynamoDB tables with streams and indexes - **[Cognito User Pool Construct](https://layeredcraft.github.io/cdk-constructs/constructs/cognito-user-pool)** - Full-featured Cognito user pool with custom domains, OAuth clients, and branding - **[Testing Guide](https://layeredcraft.github.io/cdk-constructs/testing)** - Comprehensive testing utilities and patterns - **[Examples](https://layeredcraft.github.io/cdk-constructs/examples)** - Real-world usage examples and patterns +- **[Web Function Workloads](https://layeredcraft.github.io/cdk-constructs/examples/web-functions)** - Next.js, ASP.NET Core, and Blazor Static SSR recipes ## Requirements - **.NET 8.0** or **.NET 9.0** -- **AWS CDK v2** (Amazon.CDK.Lib 2.203.1+) +- **AWS CDK v2** (Amazon.CDK.Lib 2.274.0+) - **AWS CLI** configured with appropriate permissions - **Node.js** (for CDK deployment) diff --git a/docs/constructs/web-function.md b/docs/constructs/web-function.md new file mode 100644 index 0000000..3b4c902 --- /dev/null +++ b/docs/constructs/web-function.md @@ -0,0 +1,414 @@ +# Web Function Construct + +The `WebFunctionConstruct` deploys an [AWS Lambda Web Function](https://docs.aws.amazon.com/lambda/latest/dg/lambda-web-functions.html): an ordinary HTTP server packaged as a zip, uploaded to S3, and run behind a managed HTTPS endpoint. It owns one Web Function's lifecycle — the function, its current immutable revision, its execution role and log group (each optional), one default endpoint plus any added with `AddEndpoint`, and the function's **single** resource-based policy. + +It is intentionally workload-neutral: Next.js, ASP.NET Core, and Blazor Static SSR deploy through the same public API, and the differences live in the artifacts and configuration only. See the [workload recipes](../examples/web-functions.md). + +!!! info "Lambda Web Functions are a new AWS feature" + CloudFormation exposes them as `AWS::Lambda::WebFunction`, `WebFunctionRevision`, `WebFunctionEndpoint`, and + `AWS::Lambda::ResourcePolicy`. AWS CDK 2.274.0 has only L1 support; this construct wraps the L1s with secure + wiring, synthesis-time validation of invalid combinations, and CDK-idiomatic grants. + +## :rocket: Features + +- **:package: S3-backed artifacts**: Deploy from an existing S3 object with `WebFunctionCode.FromBucket`, with optional object-version pinning. +- **:key: Explicit endpoint authentication**: Every endpoint chooses `IamAuth` or `ApplicationManaged`; there is no default auth type. +- **:link: Endpoint-scoped grants**: `GrantInvoke` grants `lambda:InvokeWebFunctionEndpoint` on a specific endpoint ARN. +- **:globe_with_meridians: CloudFront OAC integration**: `WebFunctionOrigin` returns a CloudFront `IOrigin` that configures origin access control and the required resource-policy statement. +- **:shield: One resource policy per function**: Every resource-policy contribution flows through a single policy owned by the construct. +- **:label: Immutable revisions**: Each deployment creates a new revision; endpoints move to it without interruption. +- **:gear: Configurable role and logs**: Bring your own execution role and log group, or let the construct create them. +- **:test_tube: Consumer test helpers**: Fluent `Template` assertions and a props builder in the `Testing` namespace. + +## Intentional Non-Goals (v1) + +- Building, publishing, zipping, or uploading artifacts. The S3 object must exist before deployment. +- `WebFunctionCode.FromAsset` (designed for later; not built). +- Weighted revisions, canary or blue-green routing, traffic shifting, or retaining previous revisions. +- Network connectors (VPC egress). +- Whole-function imports (`FromWebFunctionAttributes`); only endpoints can be imported. +- Owning or creating CloudFront distributions, ACM certificates, Route 53 records, or WAF. Composition with those is plain CDK. +- Workload-specific constructs or CloudFront behavior helpers. +- Caller-side request signing (SigV4 in your application) or injecting caller configuration. +- Alarms and dashboards. +- Revision encryption with a customer-managed key (`KmsKeyArn`). Deferred; see [Known Limitations](#known-limitations-and-operational-guidance). S3 artifact encryption (SSE-S3/SSE-KMS on the code bucket) is supported. + +## Prerequisites + +- **AWS CDK for .NET 2.274.0 or later** (`Amazon.CDK.Lib`). This release adds the enum values the construct needs for OAC signing. +- A region where Lambda Web Functions are available. +- A **versioned** S3 bucket that holds the application zip, and an artifact uploaded before you deploy. +- `aws-cdk` bootstrapped in the account/region if you use CDK assets elsewhere in the same app. + +## Basic Usage + +```csharp +using Amazon.CDK; +using Amazon.CDK.AWS.S3; +using LayeredCraft.Cdk.Constructs; +using LayeredCraft.Cdk.Constructs.Models; + +public class MyStack : Stack +{ + public MyStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props) + { + // Artifacts live in a versioned bucket (owned elsewhere or imported by name). + var artifacts = Bucket.FromBucketName(this, "artifacts", "acme-artifacts"); + + var web = new WebFunctionConstruct(this, "web", new WebFunctionConstructProps + { + FunctionName = "acme-web", + Code = WebFunctionCode.FromBucket(artifacts, "1.2.3/web.zip", new WebFunctionCodeFromBucketOptions + { + BucketPolicy = WebFunctionCodeBucketPolicy.ExternallyManaged, + }), + Endpoint = new WebFunctionEndpointOptions + { + AuthType = WebFunctionAuthType.IamAuth, + }, + }); + } +} +``` + +## Configuration Properties + +### Required Properties + +| Property | Type | Description | +|----------|------|-------------| +| `FunctionName` | `string` | Web Function name, 1–64 chars matching `^[A-Za-z0-9](?:[A-Za-z0-9_-]*[A-Za-z0-9])?$` | +| `Code` | `WebFunctionCode` | The artifact source, created with `WebFunctionCode.FromBucket` | +| `Endpoint` | `IWebFunctionEndpointOptions` | The default endpoint; `AuthType` is required | + +### Optional Properties + +| Property | Type | Default | Description | +|----------|------|---------|-------------| +| `Runtime` | `WebFunctionRuntime` | `NodeJs24X` | The only supported runtime is `nodejs24.x` | +| `EntryPoint` | `string?` | `null` | Exported as `AWS_LAMBDA_NODEJS_ENTRYPOINT`; defaults to `index.js` in the zip root | +| `EnvironmentVariables` | `IReadOnlyDictionary` | `{}` | Environment variables for the revision | +| `Timeout` | `Duration` | `30s` | Revision timeout, 3–900 seconds | +| `MaxConcurrencyPerEnvironment` | `int?` | `null` | Max concurrent **requests per environment**, 1–128 (AWS default 64) | +| `Description` | `string?` | `null` | Revision description | +| `Role` | `IRole?` | `null` | Execution role; when `null` a role with `AWSLambdaBasicExecutionRole` is created | +| `Logs` | `WebFunctionLogs` | `WebFunctionLogs.Create()` | Where revision logs go | +| `ApplicationLogLevel` | `ApplicationLogLevel?` | `null` | Application log level for the revision | +| `SystemLogLevel` | `SystemLogLevel?` | `null` | System log level for the revision | + +### Endpoint options (`WebFunctionEndpointOptions`) + +| Property | Type | Default | Description | +|----------|------|---------|-------------| +| `EndpointName` | `string` | `"default"` | Unique per function, 1–64 chars | +| `AuthType` | `WebFunctionAuthType` | *(required)* | `IamAuth` or `ApplicationManaged` | +| `EndpointType` | `WebFunctionEndpointType` | `HomeRegion` | `HomeRegion`, `MultiRegion`, or `PerRegion` | +| `Regions` | `IReadOnlyList` | `[]` | Required for `MultiRegion`/`PerRegion`; at least one non-home region | +| `MaxEnvironments` | `int?` | `null` | 2–10000; `null` means the account vCPU quota only | +| `RateLimit` | `int?` | `null` | `0`, `100..1000` step 100, or `2000..10000` step 1000 | +| `Description` | `string?` | `null` | Endpoint description | + +## :package: S3 Artifact Requirements + +`WebFunctionCode.FromBucket(bucket, key, options)` is the only supported source. The bucket **must have versioning enabled**, and the object must exist before CloudFormation creates the revision — the construct cannot verify that at synthesis time. + +- **Version pinning**: set `WebFunctionCodeFromBucketOptions.ObjectVersion` to pin an exact object version. If you omit it, Lambda pins the latest version at revision-creation time. +- **Read access**: Lambda reads the artifact with the **Lambda service principal** (`lambda.amazonaws.com`), not with the caller. When the construct manages the policy (`Automatic`) the statement grants `s3:GetObject` and `s3:GetObjectVersion` and is scoped with **both** `StringEquals aws:SourceAccount` (the function's account) **and** `ArnLike aws:SourceArn` of the form `arn:aws:lambda:{region}:{account}:web-function/{FunctionName}/revision/*`. An externally managed policy must grant at least those actions with equivalent scoping. +- **`Automatic` vs `ExternallyManaged`**: + - `Automatic` (default) adds that statement and makes the revision depend on the resulting bucket policy. It manages a bucket **owned in this app**, including a bucket owned by **another stack when that stack's account and region are explicitly resolvable** (for example a stack created with an explicit `Env`). If the bucket is imported, or is owned by another stack whose required environment information cannot be resolved, `AddToResourcePolicy` reports that nothing was added and synthesis fails asking you to switch to `ExternallyManaged`. + - `ExternallyManaged` adds nothing; the bucket's owner must already grant the service-principal read (for example a long-lived artifact bucket deployed and managed in its own stack). +- **SSE-KMS**: if the code bucket uses SSE-KMS, its key policy must allow `lambda.amazonaws.com` `kms:Decrypt`, because Lambda reads with its service principal. CDK-managed `aws/s3` and DSSE-managed keys cannot grant that, so an owned bucket using them is rejected. This is separate from the revision's own `KmsKeyArn`, which is not supported in v1. +- **Cross-account / cross-region buckets**: allowed within the same partition (not an opt-in region). Cross-account access needs a bucket-policy grant. +- **Object lifecycle**: deleting the pinned version (or removing read access) moves revisions to permanent `Failed`; requests then receive `409 Platform.RevisionNotActive`. +- **CDK bootstrap bucket is not usable**: the bootstrap asset bucket does not grant the service-principal read, which is why v1 is `FromBucket` only. + +!!! warning "The artifact must exist before you deploy" + The object must exist before CloudFormation creates the revision, and a bucket created in the **same stack** as + the function does not contain it at first deployment. In practice the artifact is uploaded **before** you deploy + the function stack. A separately deployed artifact bucket is a good fit (deploy the bucket stack, upload the + artifact, then deploy the function stack), but any bucket you populate first — including a runtime upload from a + pipeline or a bucket shared across applications — works equally well. + +## :shield: Execution Role and Logging + +- **Role**: when `Role` is `null`, the construct creates a role with the `AWSLambdaBasicExecutionRole` managed policy, which includes the CloudWatch Logs write permissions. When you supply a role, the construct uses it as-is and does **not** attach the managed policy **or** grant it log-write permissions — make sure a supplied role can write to wherever its logs go (for example by letting the log group's `GrantWrite` apply, or by granting `logs:CreateLogStream` and `logs:PutLogEvents` yourself). +- **Logs** (`WebFunctionLogs`): + - `WebFunctionLogs.Create(retention, removalPolicy)` — the default. Creates `/aws/lambda/web/{FunctionName}` with `RetentionDays.TWO_WEEKS` and `RemovalPolicy.DESTROY`. The name matches Lambda's own default group, so switching between `Create()` and `ServiceDefault()` never moves your logs. Because the default removal policy is `DESTROY`, switching from `Create()` to `ServiceDefault()` deletes the stack-owned log group; Lambda then recreates its default group (with no expiry) on the next invocation. Use `Use(LogGroup.FromLogGroupName(...))` to keep a group under your own lifecycle. + - `WebFunctionLogs.ServiceDefault()` — uses the Lambda-provided default group with no expiry and creates no `AWS::Logs::LogGroup`. + - `WebFunctionLogs.Use(logGroup)` — routes logs to an existing group. The group is referenced by name, and the execution role is granted `logs:GrantWrite` when the group name is outside `/aws/lambda/*`. +- **Log levels**: `ApplicationLogLevel` and `SystemLogLevel` reuse the CDK types `Amazon.CDK.AWS.Lambda.ApplicationLogLevel` and `SystemLogLevel`. + +## Function Revisions and Endpoints + +### Revisions + +Every deploy creates a new **immutable revision**. Changing the code key/version, environment variables, timeout, role, logging, or description produces a new revision and moves every endpoint to it without interruption. The previous revision is deleted during cleanup. Rollback is a redeploy of an earlier artifact (which creates another new revision); there is no re-selection of an old revision. + +### Endpoints + +The construct always creates a `DefaultEndpoint` (endpoint name `default`) and exposes it as the `DefaultEndpoint` property. Add more with `AddEndpoint(id, options)`; each added endpoint has identical semantics to the default one. Endpoint names must be unique per function, so passing `EndpointName = "default"` to `AddEndpoint` fails as a duplicate. + +`AddEndpoint` rejects the reserved construct IDs `Function`, `Revision`, `DefaultEndpoint`, `ExecutionRole`, `LogGroup`, and `ResourcePolicy` with an `ArgumentException`. + +```csharp +var webhooks = web.AddEndpoint("webhooks", new WebFunctionEndpointOptions +{ + EndpointName = "webhooks", + AuthType = WebFunctionAuthType.ApplicationManaged, + RateLimit = 100, +}); +``` + +To change an endpoint's `EndpointName`, `EndpointType`, or `Regions` you cannot update in place — CloudFormation would try to replace a fixed name and fail with "already exists", and the domain changes. Add a new endpoint, move consumers, then remove the old one. + +## Authentication Modes + +`AuthType` is a decision you make on every endpoint: + +| Mode | Who can reach the endpoint | +|------|----------------------------| +| `IamAuth` | Only callers that SigV4/SigV4A-sign with `lambda:InvokeWebFunctionEndpoint` and are authorized by an identity policy and/or the function's resource policy. | +| `ApplicationManaged` | **Anyone who knows the URL.** Lambda does not authenticate the request or evaluate the resource policy. The endpoint stays publicly reachable at its own domain, **even behind CloudFront**. | + +!!! warning "IamAuth is not user authentication" + `IamAuth` is a transport boundary between AWS principals. It never identifies an end user. Lambda strips the + SigV4 `Authorization` header before your server sees it, so application authentication (cookies, JWTs, session + tokens) is entirely your server's responsibility. With a CloudFront OAC origin, the **viewer's** `Authorization` + header passes through unchanged. + +ApplicationManaged is appropriate when your application authenticates every request itself (for a genuinely public API). IamAuth is appropriate for service-to-service calls and for endpoints fronted by CloudFront with OAC. + +## Invocation Grants + +Use `GrantInvoke` on an endpoint to authorize callers. An endpoint is an `IResource` and exposes: + +- `endpoint.GrantInvoke(grantee)` — the default `Automatic` caller policy. +- `endpoint.GrantInvoke(grantee, new WebFunctionInvokeGrantOptions { CallerPolicy = WebFunctionCallerPolicy.ExternallyManaged })`. +- `endpoint.GrantCloudFrontInvoke(distributionArn)` — CloudFront-specific (see [CloudFront OAC](#cloudfront-oac-integration)). + +`GrantInvoke` throws for an `ApplicationManaged` endpoint: there is no IAM boundary to grant against. + +### Identity policy vs resource policy + +- A **same-account** caller needs only an **identity policy** (an `AWS::IAM::Policy` attached to the caller) allowing `lambda:InvokeWebFunctionEndpoint` on the endpoint ARN. +- A **cross-account** caller needs the identity policy **and** a statement in the function's **resource policy**. + +`GrantInvoke` writes the correct side for you whenever it can establish ownership, and fails synthesis when it cannot, rather than silently producing a nonfunctional grant. + +### Owned versus imported principals + +The construct distinguishes two kinds of grantee: + +- **Owned mutable identities** — `Role`, `User`, `Group`, or `LazyRole` **created in this app** (for example, a `Role` L2 or a `WebFunctionConstruct` itself). These can receive an identity policy. +- **Everything else** — imported roles/users (`Role.FromRoleArn`), principals without a concrete owned identity, and any principal whose account cannot be established. Whether an identity policy may be written depends on the rules below. + +### Same-stack, environment-agnostic grants + +`Automatic` grants are valid when the owned caller and the endpoint belong to the **same `Stack` instance**, even when that stack's environment is unresolved. This is specifically about a single stack (or one stack reference) — two **separate** env-agnostic stacks are *not* the same stack. Their accounts are unresolved, so an `Automatic` grant between them is rejected; use `ExternallyManaged` across such stacks. + +### Cross-stack and cross-account restrictions + +`Automatic` (the default) requires the library to fully configure invocation within this deployment. It rejects, at synthesis: + +- Two different stacks where either stack's account is unresolved. +- Two different stacks with different literal accounts. +- Cross-account imported roles. +- Any grantee whose account cannot be established. + +For these cases use `ExternallyManaged` (below) and configure the caller's identity policy in the caller's own account/stack. + +### Automatic versus ExternallyManaged caller policies + +| `CallerPolicy` | Behavior | +|----------------|----------| +| `Automatic` | The library must write a working grant. If it cannot fully configure invocation, **synthesis fails** with a message naming the grantee, the endpoint, the reason, and two remedies. | +| `ExternallyManaged` | The library writes **only** the endpoint's resource-policy statement (if the endpoint is owned) and adds an info annotation. You are responsible for the caller's identity policy. | + +!!! warning "ExternallyManaged does not mean permissions are configured" + Selecting `ExternallyManaged` does **not** grant anything on the caller's side. It records the resource-policy + statement and annotates that *Invocation by {principal} requires an identity policy in the caller's account + allowing `lambda:InvokeWebFunctionEndpoint` on {endpoint ARN}.* Invocation fails until that policy exists. + +### Why GrantInvoke rejects certain principals + +To avoid confused-deputy grants and false confidence, `GrantInvoke` fails synthesis for: + +- **Service principals** — bare or conditioned. An unconditioned service-principal statement would let, for example, *any* distribution in *any* account with an OAC origin for this endpoint invoke it. Use `GrantCloudFrontInvoke(distributionArn)` for CloudFront, or an explicit condition-scoped `AddToResourcePolicy` statement for any other service, including the scoping condition that service documents. `GrantInvoke` cannot know which condition keys a service supplies, so it neither adds `aws:SourceAccount` nor accepts arbitrary conditions as proof of scoping. +- **Account principals** (`AccountPrincipal`, `AccountRootPrincipal`, and any principal whose literal AWS principal is an account-root ARN), including the same account. An account-root resource statement authorizes no specific caller by itself, so it is never treated as a complete `Automatic` grant. Under `ExternallyManaged` an explicitly requested account principal *can* be recorded in the owned endpoint's resource policy, but that is only half the picture — caller-side authorization is still not configured, and the result must not be described as a working grant. +- **Wildcard principals** (conditioned or not) — `AnyPrincipal`, `StarPrincipal`, `OrganizationPrincipal`, `*`. Conditioned wildcards are supported only through an explicit `AddToResourcePolicy` statement (see below). `AddToResourcePolicy` only checks that an Allow wildcard statement **has** conditions — it does **not** verify that those conditions actually restrict access. You own the condition semantics: a condition such as `aws:PrincipalOrgID` can meaningfully restrict who may invoke, but the mere presence of a condition proves nothing, so design and validate the condition yourself. +- **`PrincipalWithConditions`** wrapping any principal, under either caller policy. Grant the underlying principal directly, or use `AddToResourcePolicy`. +- **`Role.WithoutPolicyUpdates()`** and every imported role as an identity-policy target — they are not concrete owned mutable identities, so the library falls back to the resource policy on an owned endpoint, or throws on an imported one. + +If a case cannot be safely configured on either side, `GrantInvoke` throws. A false negative (requiring you to act) is always preferred over a false positive. + +## Resource-Policy Ownership + +A Web Function has **exactly one** resource policy, attached to the function ARN, and the construct owns it. Every contribution flows through that single policy: + +- The construct exposes no public "add to function policy" entry point. The only resource-policy entry points are on the **endpoint**: `GrantInvoke`, `GrantCloudFrontInvoke`, and `AddToResourcePolicy`. +- `endpoint.AddToResourcePolicy(statement)` requires `statement.Resources` to be **exactly** that endpoint's ARN; anything else throws an `ArgumentException`. +- Statements are validated when added (a Deny is unrestricted; an Allow must not use `NotPrincipal`; an Allow naming a wildcard or service principal must carry conditions), copied, frozen, and validated as part of the candidate policy document. A rejected statement leaves no partial state. +- Identical statements are deduplicated at synthesis. +- Multiple distributions or endpoints never create competing policy resources. + +Because the policy is a single PUT-replace resource, an out-of-band `aws lambda-web put-resource-policy` is overwritten the next time the policy changes, and AWS warns against combining it with `AWS::Lambda::Permission` on the same function. Keep this function's invocation authorization in this construct. + +## Imported Endpoints + +Use `WebFunctionEndpointConstruct.FromEndpointAttributes` to reference an endpoint owned by another stack or app: + +```csharp +var shared = WebFunctionEndpointConstruct.FromEndpointAttributes(this, "shared", new WebFunctionEndpointAttributes +{ + EndpointArn = "arn:aws:lambda:us-east-1:111122223333:web-function/shared/endpoint/default", + DomainName = "abc123.lambda-web.us-east-1.on.aws", + AuthType = WebFunctionAuthType.IamAuth, +}); +``` + +An imported endpoint owns nothing. Its `GrantCloudFrontInvoke` and any grant that would need its resource policy throw — the resource policy is owned externally. `GrantInvoke` with `CallerPolicy = ExternallyManaged` **also** throws on an imported endpoint, because there is no owned resource policy to receive the statement; configure the caller's access in the endpoint owner's policy instead. It is usable as a CloudFront origin with `WebFunctionOriginPermissions.ExternallyManaged`, and it writes identity policies only for an owned mutable caller whose account is literally the same as the endpoint's. + +- Literal `EndpointArn` values are validated against `arn:{partition}:lambda:{region}:{12-digit account}:web-function/{function}/endpoint/{endpoint}`; literal `DomainName` must be non-empty; literal `Account` must be 12 digits and agree with a literal ARN's account. +- **Account (`WebFunctionEndpointAttributes.Account`)** is required when `EndpointArn` is a **token** and you want identity grants: the endpoint's account = the literal ARN account, else the literal `Account`, otherwise it is **not established** and `GrantInvoke` throws for every grantee. A token-ARN endpoint can still be used as a CloudFront origin with `ExternallyManaged` permissions. + +## CloudFront OAC Integration + +`WebFunctionOrigin` is a static factory that returns a CloudFront `IOrigin`, analogous to CDK's `FunctionUrlOrigin`. + +```csharp +var origin = WebFunctionOrigin.WithOriginAccessControl(web.DefaultEndpoint, new WebFunctionOriginWithOacProps +{ + CustomHeaders = new Dictionary { ["x-origin-verify"] = secret }, +}); + +var distribution = new Distribution(this, "distribution", new DistributionProps +{ + DefaultBehavior = new BehaviorOptions + { + Origin = origin, + ViewerProtocolPolicy = ViewerProtocolPolicy.REDIRECT_TO_HTTPS, + AllowedMethods = AllowedMethods.ALLOW_ALL, + CachePolicy = CachePolicy.CACHING_DISABLED, + OriginRequestPolicy = OriginRequestPolicy.ALL_VIEWER_EXCEPT_HOST_HEADER, + }, + AdditionalBehaviors = new Dictionary + { + ["/_next/static/*"] = new BehaviorOptions { Origin = origin, CachePolicy = CachePolicy.CACHING_OPTIMIZED }, + }, + DomainNames = ["app.example.com"], + Certificate = certificate, +}); +``` + +- `WithOriginAccessControl(endpoint, props)` requires an `IamAuth` endpoint. When bound to a distribution it creates one `FunctionUrlOriginAccessControl` (origin type `lambda`, `always-amz-auth`, `sigv4` for HomeRegion/PerRegion and `sigv4a` for MultiRegion) and adds the resource-policy statement `cloudfront.amazonaws.com → lambda:InvokeWebFunctionEndpoint` on the endpoint ARN with `StringEquals aws:SourceArn = arn:aws:cloudfront::{account}:distribution/{id}`. +- `WithoutOriginAccessControl(endpoint, props)` requires an `ApplicationManaged` endpoint; the endpoint remains directly reachable and CloudFront adds no access control. +- Passing an **`ApplicationManaged` endpoint to the OAC factory**, or an **`IamAuth` endpoint to the non-OAC factory**, throws an `InvalidOperationException` at the factory call. +- **Automatic permissions** (the default) require the distribution and the Web Function to be in the **same stack**; otherwise synthesis fails with a dependency-cycle explanation. For a cross-stack distribution, use `Permissions = WebFunctionOriginPermissions.ExternallyManaged` and grant the distribution ARN via `endpoint.GrantCloudFrontInvoke(...)` in the owner's stack (a two-phase rollout). +- The same origin object reused on several behaviors of one distribution binds once, producing one OAC and one policy statement. +- A supplied `OriginAccessControl` is used unchanged and not inspected; the consumer is responsible for it being `lambda`/`always-amz-auth`/correct protocol. + +### Caching and header guidance + +- **Never forward the viewer `Host` header.** Use `OriginRequestPolicy.ALL_VIEWER_EXCEPT_HOST_HEADER`, not `ALL_VIEWER`. Forwarding `Host` makes the endpoint return `404`. +- **Dynamic/personalized routes** should use `CACHING_DISABLED`. +- For **GET/HEAD**, CloudFront drops the viewer `Authorization` header unless it is part of the cache policy; prefer cookies or custom headers, and add `Authorization` to a cache policy only when you truly need it. +- **Host-dependent applications** (multi-tenant hosts) must recover the viewer host through a CloudFront Function that copies it into a custom header, and trust that header only after an origin-verification check. +- **Content-hashed static assets** (`/_next/static/*`, Blazor fingerprinted `/_framework/*` files, `/_content/*`) should use `CACHING_OPTIMIZED`. +- Lambda@Edge origin-request/origin-response triggers are **rejected** by CloudFront on behaviors that use a Web Function origin with OAC. +- OAC is **not** supported for global endpoints that include opt-in regions (requests get `403`). +- OAC takes effect only after the distribution deploys (and, for MultiRegion, after the policy replicates); brief `403`s in between are expected. + +## Grant Behavior Reference + +The table below summarizes `GrantInvoke` behavior for an **owned** endpoint (an endpoint on a function in this app). An imported endpoint is stricter: it owns no resource policy, so only an owned mutable caller whose account is literally the same as the endpoint's can be granted (via an identity policy), and every other case throws. + +| Grantee | `Automatic` (default) | `ExternallyManaged` | +|---------|------------------------|---------------------| +| Owned mutable identity (`Role`, `User`, `Group`, `LazyRole` created in this app) — same stack, or different stacks with the same literal account | Complete — identity policy written | Partial by contract — only the resource-policy statement is written; you configure the caller's identity policy | +| `Role.FromRoleArn` (imported) whose literal account equals the endpoint's | Complete — the owned endpoint's resource policy is used | Partial by contract | +| `Role.WithoutPolicyUpdates()` (owned, but not a mutable identity) | Complete via the resource policy (no identity policy written) | Partial by contract | +| Account principal / account-root principal | Synthesis error | Partial by contract — the account principal may appear in the endpoint's resource policy, but caller-side authorization is not configured | +| Service principal (for example `cloudfront.amazonaws.com`) | Synthesis error — use `GrantCloudFrontInvoke` for CloudFront, or a condition-scoped `AddToResourcePolicy` | Synthesis error | +| Wildcard principal (`AnyPrincipal`, `StarPrincipal`, `*`) | Synthesis error | Synthesis error — use an explicit conditioned `AddToResourcePolicy` | +| `PrincipalWithConditions` wrapper | Synthesis error | Synthesis error | +| Cross-account caller (different literal account) | Synthesis error | Partial by contract | +| Caller whose account cannot be established (unresolved) | Synthesis error | Partial by contract | +| Any grantee on an **imported** endpoint | Treated as owned-mutable-same-account only; otherwise synthesis error | Synthesis error (no owned resource policy) | + +"Partial by contract" means the library writes the resource-policy statement (on an owned endpoint) and annotates what the caller must do; it never claims the caller side is configured. + +## Signing Requests + +A direct IAM invocation of an `IamAuth` endpoint must be signed with AWS Signature Version 4: + +- **Service name**: `lambda`. +- **Payload hash**: send `x-amz-content-sha256: UNSIGNED-PAYLOAD` (chunked payload signing is not supported). +- **Protocol**: `HomeRegion` and `PerRegion` endpoints use **SigV4** signed for the endpoint's Region; `MultiRegion` endpoints use **SigV4A** with the signing region set to `*`. +- The construct (and CloudFront, when not using OAC) does **not** sign requests on your behalf — the calling SDK or your BFF signs itself. + +CloudFront OAC signing is different: with `always-amz-auth`, CloudFront signs the origin request in its own dedicated header and passes the viewer's `Authorization` header through unchanged. Lambda strips its own SigV4 `Authorization` (and `X-Amz-Security-Token`) before forwarding, so application code sees the viewer's header, not the caller's signature. + +## Resource Replacement and Update Behavior + +| Change | Effect | +|--------|--------| +| Code key/version, environment variables, timeout, execution role, logging, description | Creates a **new revision**; endpoints move to it without interruption; the previous revision is removed during cleanup. | +| `MaxEnvironments`, `RateLimit`, endpoint `Description` | Updated in place (no interruption). Omitting the option keeps the current value; clearing it removes the setting. | +| Endpoint `AuthType` | No interruption, but switching `ApplicationManaged` → `IamAuth` while introducing an OAC can return transient `403`s until the distribution deploys. | +| `EndpointName`, `EndpointType`, `Regions` | **Replacement.** Reusing a fixed name fails with "already exists" and the endpoint domain changes — add a new endpoint, move consumers to it, then remove the old one. | +| `FunctionName` | **Replacement of everything.** Fails while the old name still exists; endpoint domains change. | +| Distribution replacement | The distribution ID changes; the policy statement is updated in the same deployment (no interruption), though the new distribution may return `403` until the policy update propagates. | +| Resource-policy statement changes | The `PolicyDocument` is updated in place (no interruption). | + +A deployment that fails is rolled back by CloudFormation to the previous revision. These behaviors follow the CloudFormation resource model in the approved design; anything not listed here should be treated as unverified. + +## Public Testing Helpers + +The `LayeredCraft.Cdk.Constructs.Testing` namespace ships fluent helpers for synthesized templates: + +- `WebFunctionConstructAssertions` extension methods on `Template`: `ShouldHaveWebFunction`, `ShouldHaveRevision`, `ShouldHaveRevisionCode`, `ShouldHaveEndpoint`, `ShouldHaveEndpointScaling`, `ShouldHaveInvokeGrant`, `ShouldHaveSingleResourcePolicy`, `ShouldHaveNoResourcePolicy`, `ShouldAllowCloudFront`, `ShouldAllowResourcePolicyPrincipal`, `ShouldHaveWebFunctionOac`, and `ShouldHaveCodeBucketReadStatement`. They match by function and endpoint **names** (not logical IDs) and require `Effect = Allow` with the expected action and the exact endpoint resource, so a Deny or an unrelated action never satisfies them. +- `WebFunctionConstructPropsBuilder` via `CdkTestHelper.CreateWebFunctionPropsBuilder()`: `WithFunctionName`, `WithCode`, `WithTestArtifact`, `WithIamAuthEndpoint`, `WithApplicationManagedEndpoint`, `WithEndpoint`, `WithEnvironmentVariable`, `WithEntryPoint`, `WithTimeout`, `WithMaxConcurrencyPerEnvironment`, `WithRole`, `WithLogs`, then `Build()`. `Build()` throws without code or an endpoint. + +```csharp +var template = Template.FromStack(stack); +template.ShouldHaveWebFunction("acme-web"); +template.ShouldHaveEndpoint("acme-web", "default", WebFunctionAuthType.IamAuth); +template.ShouldAllowCloudFront("acme-web", "default"); +``` + +## Workload Recipes + +Detailed recipes for Next.js, ASP.NET Core (Node.js `execve` shim), and Blazor Static SSR are in the [Web Function Workloads](../examples/web-functions.md) page. They show how to build each artifact and wire CloudFront, and they are explicit about what synthesis tests verify versus what requires a real AWS deployment. + +## Known Limitations and Operational Guidance + +- **S3 versioning via escape hatches is not detected.** The owned-bucket inspection only reads literal values in the rendered L2 properties. Versioning enabled through a property override (`CfnBucket`) is not detected; reference such a bucket by name (`Bucket.FromBucketName`) with `ExternallyManaged` instead. +- **Tokenized configuration is skipped, never rejected.** A token versioning status, encryption algorithm, or key ID can be shown neither compliant nor non-compliant, so validation skips it. +- **Log-group switching.** Moving an existing function from `WebFunctionLogs.ServiceDefault()` to `Create()` — or redeploying after a stack deletion while `/aws/lambda/web/{name}` still exists — fails with `AlreadyExists`, because Lambda auto-creates the group. Remedy: use `WebFunctionLogs.Use(LogGroup.FromLogGroupName(...))`, or delete/import the existing group. +- **Service-created default log groups outlive the stack.** With `WebFunctionLogs.ServiceDefault()` (or a supplied role and no group) the construct creates no `AWS::Logs::LogGroup`; the Lambda service creates `/aws/lambda/web/{name}` on first invocation. That group is not part of the stack, has no expiry, and is **not** removed by CloudFormation on teardown, so it keeps the invocation history after the stack is deleted. CDK-managed `Create()` groups are stack-owned and follow their `RemovalPolicy`. In disposable sandboxes, delete leftover service-created groups explicitly by exact name after destroying the stack. Do not routinely delete production log groups. +- **IAM policy propagation.** The revision depends on the execution role's `CfnRole` only, never the role's default policy, so permissions granted to the role may not have propagated when the revision first activates. This avoids CloudFormation cycles for mutually-referencing functions. +- **CloudFront origin-binding exceptions across jsii.** Validation that runs inside the CDK `IOrigin.Bind` path (and inside `HttpOrigin` construction) surfaces in .NET as a `System.Exception` carrying CDK's message, whereas factory-time checks throw `InvalidOperationException`. +- **F3006 resource-type warnings.** CDK 2.274.0 emits `F3006` "Unknown resource type `AWS::Lambda::WebFunction*`" validation warnings. They are warnings by default and become **synthesis errors** when `@aws-cdk/core:validateAgainstDefaultRules` is enabled; acknowledge with `CloudFormation-Validate::F3006`. +- **OAC naming.** The auto-created OAC name is derived from the distribution's origin scope. OAC names are unique per AWS **account** across **Regions**, so the collision risk is identical names within the *same* account — not across different accounts. If you deploy the same distribution shape repeatedly in one account, verify the generated naming still meets your conventions. +- **Origin request policy.** Use `ALL_VIEWER_EXCEPT_HOST_HEADER`, never `ALL_VIEWER` (see [Caching and header guidance](#caching-and-header-guidance)). +- **Customer-managed revision keys.** `KmsKeyArn` is not supported in v1. The only workaround is an unsupported escape hatch — `((CfnWebFunctionRevision)web.Node.FindChild("Revision")).KmsKeyArn = key.KeyArn` plus the key-policy grants you write. +- **Sandbox validation.** Runtime behavior (actual invocation, execve shims, readiness, CloudFront end-to-end) is validated only by a real deployment in a sandbox account; synthesis tests do not prove runtime support. + +## Validation Errors + +The construct fails at synthesis with `ArgumentException`, `ArgumentOutOfRangeException`, or `InvalidOperationException`, following repository style. Literal values are validated; tokens (`Token.IsUnresolved`) are skipped, never rejected. Notable cases: + +- OAC origin for an `ApplicationManaged` endpoint, or non-OAC origin for an `IamAuth` endpoint → `InvalidOperationException` at the origin factory. +- Automatic OAC permissions with an imported endpoint or a cross-stack distribution → `InvalidOperationException` at bind. +- `GrantInvoke`/`GrantCloudFrontInvoke` on an `ApplicationManaged` endpoint, or a resource-policy grant on an imported endpoint → `InvalidOperationException`. +- An `Automatic` grant that cannot be fully configured → `InvalidOperationException` naming the grantee, endpoint, reason, and remedies. +- `AddToResourcePolicy` with a resource that is not exactly the endpoint ARN, or an unconditioned wildcard/service-principal Allow, or `NotPrincipal` → `ArgumentException`. +- A props-builder `Build()` without code or endpoint → `InvalidOperationException`. + +## Testing + +See the [Testing Guide](../testing/index.md) for the test helpers and patterns shared across constructs. + +## Examples + +See the [Examples](../examples/index.md) page and the [Web Function Workloads](../examples/web-functions.md) page. diff --git a/docs/designs/lambda-web-functions-integration.md b/docs/designs/lambda-web-functions-integration.md new file mode 100644 index 0000000..fa6270a --- /dev/null +++ b/docs/designs/lambda-web-functions-integration.md @@ -0,0 +1,1939 @@ +# Design: Lambda Web Functions, IAM endpoint authentication, and CloudFront OAC + +| | | +|---|---| +| **Status** | **Approved** (revision 4, 2026-10-23) for implementation planning ([#98](https://github.com/LayeredCraft/cdk-constructs/issues/98)). Implementation proceeds through separately planned tasks. | +| **Date** | 2026-10-22 (revisions 2–3 address design review feedback; revision 4, 2026-10-23, records corrections from the independent T1–T3b implementation review; see [§21](#21-revision-history)) | +| **Authority** | This document is the authoritative architectural record for the feature. No standalone ADRs are written for it at this time. | +| **Target package** | `LayeredCraft.Cdk.Constructs` (next minor after v2.5.0) | +| **AWS CDK floor** | `Amazon.CDK.Lib` 2.274.0 (raised from 2.273.0; see [§5.5](#55-cdk-version-floor)) | +| **Reference implementation** | Sharedale `infra/Sharedale.Infrastructure/SharedaleHostedStack.cs` (commit `b44b0a6`) | + +> This page is a design record, not user documentation. It is not in the MkDocs `nav`; the user-facing +> page proposed in [§16](#16-documentation-strategy) is. + +--- + +## 1. Executive summary + +AWS Lambda Web Functions (launched 2026-10-12) run an ordinary HTTP server per execution environment behind +managed HTTPS endpoints. CloudFormation exposes them as `AWS::Lambda::WebFunction`, `WebFunctionRevision`, +`WebFunctionEndpoint`, and `AWS::Lambda::ResourcePolicy`. AWS CDK 2.274.0 has **only L1** support for them; two +competing upstream L2 proposals are open and unmerged. + +Sharedale runs its Next.js BFF and its ASP.NET Core API as two Web Functions with `IamAuth` endpoints: CloudFront +reaches the BFF through Origin Access Control (OAC), and the BFF reaches the API by SigV4-signing with its execution +role. That works today, but it takes about 170 lines of hand-wired L1 code, an L1 OAC with literal strings, a +hand-built resource policy, and implicit ordering rules. + +**Recommendation — hybrid composition (Approach C):** + +- **`WebFunctionConstruct`**: a focused L3 that owns one Web Function's lifecycle — the function, its current + immutable revision, its execution role and log group (each optional), one default endpoint plus any added with + `AddEndpoint`, and the function's **single** resource-based policy. +- **`WebFunctionEndpointConstruct` / `IWebFunctionEndpoint`**: a first-class endpoint with `GrantInvoke(IGrantable)`, + `GrantCloudFrontInvoke(distributionArn)`, and limited import support. `GrantInvoke` writes identity policies only to + principals whose account it can establish. Anything it cannot fully configure (cross-account or unresolved + imported principals) fails synthesis unless the consumer opts into `CallerPolicy = ExternallyManaged` + ([§10.2](#102-grantinvoke-semantics)). +- **`WebFunctionOrigin`**: a static factory, analogous to CDK's `FunctionUrlOrigin`, that returns a CloudFront + `IOrigin`. It configures OAC correctly (`lambda`, `always-amz-auth`, SigV4 or SigV4A chosen from the endpoint type) + and, when the origin is bound to a `Distribution`, adds the `aws:SourceArn`-scoped statement for that distribution + to the function's resource policy. A spike confirmed this works through the .NET jsii bindings ([§11.2](#112-spike-results)). +- Code comes from an **existing S3 object** (`WebFunctionCode.FromBucket`). Packaging and uploading stay with the + consumer. `FromAsset` can be added later without breaking changes. +- **Workload-neutral.** The same API deploys Next.js, ASP.NET Core (Node.js `execve` shim), and Blazor Static SSR. + The differences live in artifacts and configuration only. Recipes are documentation, not types. +- **Existing constructs are untouched.** Acceptance includes zero synthesis diff for `LambdaFunctionConstruct`, + `StaticSiteConstruct`, `DynamoDbTableConstruct`, and `CognitoUserPoolConstruct`. +- **Release gate.** A successful sandbox deployment and smoke test is required before the feature is published + ([§19.1](#191-release-acceptance-criteria)). It does not run in normal CI. + +The construct stays thin over CloudFormation. It adds secure wiring, synth-time validation of invalid combinations, +and CDK-idiomatic grants. It does not add a deployment framework. + +--- + +## 2. Goals and non-goals + +### Goals + +1. Deploy a Web Function from an S3 artifact with one construct and strongly typed configuration. +2. Make endpoint authentication an explicit decision on **every** endpoint. There is no default `AuthType`. +3. Grant `lambda:InvokeWebFunctionEndpoint` on a **specific endpoint** through CDK-conventional `GrantInvoke`. +4. Integrate an `IamAuth` endpoint with an existing CloudFront `Distribution` through OAC, including the required + resource-policy permission, without taking ownership of the distribution, certificate, or DNS. +5. Own exactly one resource policy per Web Function. Every contribution flows through it. +6. Fail at synthesis for configurations that are insecure, nonfunctional, or misleading (for example, OAC on an + `ApplicationManaged` endpoint). +7. Support Next.js, ASP.NET Core, and Blazor Static SSR through the same public API (an acceptance criterion). +8. Ship consumer test helpers that follow the repository's `Testing` namespace conventions. +9. Keep the public C# API independent of upstream L2 types. Adopting an upstream L2 later is then an optional + internal refactor. It is permitted only if it also preserves deployment compatibility, which covers logical IDs, + resource properties, dependencies, and replacement semantics ([§12.4](#124-compatibility-guarantees-and-future-upstream-l2-adoption)). + +### Non-goals (v1) + +- Building, publishing, zipping, or uploading application artifacts. No `BucketDeployment`, no custom resources. +- `WebFunctionCode.FromAsset` (designed for, not built). +- Weighted revisions, canary or blue-green routing, traffic shifting, or retaining previous revisions. +- Network connectors (VPC egress, `AWS::Lambda::NetworkConnector`). +- Whole-function imports (`FromWebFunctionAttributes`). +- Owning or creating CloudFront distributions, ACM certificates, Route 53 records, or WAF. +- Workload-specific constructs or CloudFront behavior helpers (Next.js, ASP.NET Core, Blazor). +- Caller-side request signing (SigV4 in the BFF) or injecting caller configuration (endpoint URL or region + environment variables). These belong to the consumer's application. +- Alarms and dashboards. Metric helpers are a follow-up. +- Revision encryption with a customer managed key (`KmsKeyArn`). Deferred; see [§8.7](#87-kms-scope-decision). S3 + artifact encryption (SSE-S3/SSE-KMS on the code bucket) remains supported and documented. +- Maintained data lists (for example, opt-in Regions) and deep inspection of CloudFront distribution behaviors. + Validation stays narrow ([§14](#14-validation-and-error-handling)). +- Any change to existing constructs. + +--- + +## 3. Existing Sharedale implementation + +Primary sources: `infra/Sharedale.Infrastructure/SharedaleHostedStack.cs`, +`SharedaleAccountBootstrapStack.cs`, `infra/web-functions/*.js`, `infra/scripts/build-web-functions.sh`, +`app/lib/server/api/web-function-iam.ts`, ADR-0009, ADR-0010, ADR-0011, `docs/architecture/hosted-environment.md`, +and `docs/architecture/lambda-web-functions-poc.md`. + +### 3.1 Topology + +```text +Browser ─HTTPS─> CloudFront (*.{domain}, ACM us-east-1, Route 53 A/AAAA aliases) + │ viewer-request CloudFront Function: X-Sharedale-Viewer-Host, cookie filter + │ origin custom header: X-Sharedale-Origin-Verification (Secrets Manager dynamic ref) + │ OAC: lambda / always-amz-auth / sigv4 + │ origin request policy: ALL_VIEWER_EXCEPT_HOST_HEADER; default CACHING_DISABLED + │ /_next/static/* → CACHING_OPTIMIZED + ▼ + Web Function sharedale-{env}-web (nodejs24.x, Next.js standalone; endpoint "default", HomeRegion, IamAuth) + │ resource policy: cloudfront.amazonaws.com, aws:SourceArn = this distribution + │ HTTPS, SigV4 (service "lambda", UNSIGNED-PAYLOAD) with the web execution role + ▼ + Web Function sharedale-{env}-api (nodejs24.x → execve self-contained .NET 11 linux-arm64; IamAuth) + no resource policy; the web role's identity policy grants invoke on the endpoint ARN +``` + +There is no `/api/*` CloudFront behavior. The browser never calls the API. + +### 3.2 Web Function definition (`SharedaleHostedStack.WebFunction`, lines 526–577) + +| Concern | Sharedale | Generic or specific? | +|---|---|---| +| Resources | `CfnWebFunction` (name only), `CfnWebFunctionRevision`, `CfnWebFunctionEndpoint` | Generic | +| Ordering | `revision.AddResourceDependency(function)`, `endpoint.AddResourceDependency(revision)`; `FunctionName` is the **literal name** on all three | Generic (CFN needs it) | +| Runtime | `nodejs24.x` for both (the only supported runtime) | Generic | +| Code | `S3Object { Bucket = sharedale-artifacts-{account}, Key = {artifactTag}/{id}.zip }`, **no `VersionId`** | Bucket/key scheme is specific | +| Role | New `Role` per function, `AWSLambdaBasicExecutionRole`, statements added afterwards | Generic shape; statements specific | +| Logs | `LogGroup /aws/lambda/{name}`, one month, `DESTROY`; `TelemetryConfig.LoggingConfig.LogGroup` | Generic; name and retention are choices | +| Service config | `TimeoutSeconds = 30`, `MaxConcurrencyPerEnvironment = 16`, env vars | Values specific | +| Endpoint | `EndpointName = "default"`, `HomeRegion`, `IamAuth`, 100% to the revision, `MaxEnvironments = 10`, `RateLimit = 100` | Shape generic; values specific | +| Region | Stack throws unless `us-east-1` (because of the CloudFront certificate) | Specific | + +### 3.3 Artifact bucket (`SharedaleAccountBootstrapStack.cs:113–167`) + +The bucket is owned by a separate, long-lived stack: versioned, `S3_MANAGED`, `BLOCK_ALL`, `EnforceSSL`, `RETAIN`. Its +bucket policy grants `lambda.amazonaws.com` `s3:GetObject` and `s3:GetObjectVersion` with `aws:SourceAccount` and +`ArnLike aws:SourceArn` matching `web-function/sharedale-*` and `function:sharedale-*`. Uploads are denied unless +conditional (`s3:if-none-match`), and deletes are denied. Immutability comes from the bucket policy, not from a +pinned `VersionId`. Build: `infra/scripts/build-web-functions.sh`, publish: `publish-hosted-artifacts.sh`. Artifacts +must exist before CloudFormation creates the revisions. + +**Implication for the library:** buckets that are imported or owned by another stack must be supported with an +*externally managed* bucket policy. + +### 3.4 IAM-authenticated BFF → API + +- Caller: the BFF execution role, through the Node.js default credential chain (`@aws-sdk/credential-provider-node`). +- Policy: an identity statement on the web role, `lambda:InvokeWebFunctionEndpoint` on + `apiFunction.Endpoint.AttrEndpointArn` only (lines 247–251). There is no resource policy on the API, because the + caller is in the same account. +- Signing: `app/lib/server/api/web-function-iam.ts`, SigV4 via `@smithy/signature-v4`, service `lambda`, region from + `AWS_REGION`, `x-amz-content-sha256: UNSIGNED-PAYLOAD`. Enabled by `SHAREDALE_API_AUTH=iam`. The endpoint URL is + wired as `SHAREDALE_API_URL = https://{Endpoint.AttrDomainName}`. +- The user's Cognito token travels in `X-Sharedale-User-Token`, never `Authorization`. Lambda strips the SigV4 + `Authorization` header before the request reaches ASP.NET Core (ADR-0010). Application authentication is + independent of the AWS IAM boundary. +- Strictly server-to-server; no browser-side signing. + +### 3.5 CloudFront and OAC (lines 327–418) + +- OAC: `CfnOriginAccessControl` with `lambda`, `always-amz-auth`, `sigv4` (the L2 enums were missing in 2.273). +- Origin: `HttpOrigin(webEndpoint.AttrDomainName, HTTPS_ONLY, OriginAccessControlId, CustomHeaders{origin secret})`. +- Resource policy: `Amazon.CDK.AWS.Lambda.CfnResourcePolicy` on `webFunction.Function.AttrFunctionArn`, one statement + for `cloudfront.amazonaws.com`, `lambda:InvokeWebFunctionEndpoint` on the endpoint ARN, `StringEquals + aws:SourceArn = distribution.DistributionArn`. Same stack, so there is no cycle. +- Behaviors: default `CACHING_DISABLED` + `ALL_VIEWER_EXCEPT_HOST_HEADER` + viewer-request function; `/_next/static/*` + `CACHING_OPTIMIZED`. TLS 1.2_2021, HTTP/2 and HTTP/3, `PRICE_CLASS_100`, wildcard ACM certificate, A and AAAA + aliases for `app.` and `*.`. +- Host handling: the endpoint routes by `Host`, so the viewer host is moved into a custom header by a CloudFront + Function and the BFF trusts it only after origin verification. +- Personalized responses are protected from caching because the default behavior uses `CACHING_DISABLED`. Only + content-hashed assets are cached. +- Known one-time window: switching an endpoint to `IamAuth` before the distribution finishes deploying produces + transient 403s (ADR-0011). + +### 3.6 Generic vs. Sharedale-specific + +**Generic (candidates for the library):** the function, revision, and endpoint triple with its dependencies; the +default role and log group; identity-policy invoke grants on an endpoint ARN; OAC configuration; the CloudFront +resource-policy statement scoped by `aws:SourceArn`; single-owner resource policy; HTTPS-only origin; the +host-header rule. + +**Sharedale-specific (stay with the consumer):** the artifact bucket and its immutability policy; commit-addressed +keys; env var names; scaling values; the origin-verification secret header; the viewer-host CloudFront Function and +cookie filter; cache behaviors; the wildcard domain and DNS; Cognito wiring; alarms; the `us-east-1` restriction; the +SigV4 signer. + +--- + +## 4. Existing LayeredCraft.Cdk.Constructs architecture + +Source: `src/LayeredCraft.Cdk.Constructs/`, `test/LayeredCraft.Cdk.Constructs.Tests/`, `CLAUDE.md`, `docs/`. + +| Area | Finding | Consequence for this design | +|---|---|---| +| Constructs | `LambdaFunctionConstruct` (classic Lambda, `PROVIDED_AL2023`, version + `live` alias, optional `FunctionUrlAuthType.NONE` URL), `StaticSiteConstruct` (public S3 website + CloudFront + ACM + `HostedZone.FromLookup`), `DynamoDbTableConstruct`, `CognitoUserPoolConstruct` | No CloudFront-generic or IAM-endpoint abstraction to extend. Web Functions are a different resource model from `AWS::Lambda::Function`. Extending `LambdaFunctionConstruct` would mix them (Approach A rejected). | +| Props convention | Interface + record. Older: mutable `{ get; set; }` + `required`. Newest (Cognito, #99): get-only interface, `init` record, injected `ICertificate?` / `IHostedZone?` instead of lookups | Follow the **newest** Cognito style | +| Naming | `*Construct` + `I*ConstructProps` / `*ConstructProps`; models in `Models/` namespace | `WebFunctionConstruct`, `IWebFunctionConstructProps`, … | +| Validation | `ArgumentNullException.ThrowIfNull`, `ArgumentException.ThrowIfNullOrWhiteSpace`, `NotSupportedException` (SnapStart) | Same exception style for synth-time validation | +| Exposed resources | Mixed: `public readonly Function LambdaFunction`, `UserPool UserPool { get; }` | Expose capability-oriented members (role, endpoint URL and ARN); L1s only via `Node.DefaultChild` and documented child IDs | +| Outputs | `LambdaFunctionConstruct`, `DynamoDbTableConstruct`, `CognitoUserPoolConstruct` emit `CfnOutput` exports via `StackExtensions.CreateExportName` | Do **not** emit outputs by default (decision: only the role and log group are owned infra) | +| Testing kit | Public `Testing` namespace: `CdkTestHelper`, `*ConstructAssertions`, `*ConstructPropsBuilder`; internal tests use AutoFixture `*AutoData` attributes and `[Collection("CDK Tests")]` | Add `WebFunctionConstructAssertions`, `WebFunctionConstructPropsBuilder`, `CdkTestHelper.CreateWebFunctionPropsBuilder()` | +| Targets | `net8.0;net9.0;net10.0;net11.0`; `Amazon.CDK.Lib` central version 2.273.0; CI `pr-build.yaml` with 80% coverage threshold | Bump to 2.274.0; keep TFMs | +| Docs | MkDocs Material, `docs/constructs/*.md`, `docs/examples/index.md`, `docs/testing/index.md`; non-strict build | New `docs/constructs/web-function.md` + nav entry | +| Versioning | Tags `v2.x.y`; release-drafter; `CHANGELOG.md` (last entry 2.0.0); `VersionPrefix` 2.4.0 in `Directory.Build.props` is stale versus tag v2.5.0 | Additive minor release. Ask the maintainer to reconcile `VersionPrefix` at release time (out of scope here). | + +**Composition with existing constructs.** There is no CloudFront or DNS construct a Web Function could plug into +today. `StaticSiteConstruct` owns its distribution internally and exposes nothing. That confirms the decision: +`WebFunctionOrigin` composes with the CDK `Distribution` L2 the consumer creates, and certificates and DNS are plain +CDK (`Certificate`, `ARecord`/`AaaaRecord` + `CloudFrontTarget`), matching the Cognito construct's injected +`ICertificate` / `IHostedZone` style. + +--- + +## 5. AWS / CDK capability findings + +All claims below were verified on 2026-10-22 against the AWS documentation and the installed CDK packages. +References are in [§20](#20-references). + +### 5.1 Resource model (CloudFormation) + +| Resource | Key properties (update behavior) | Return values | +|---|---|---| +| `AWS::Lambda::WebFunction` | `FunctionName` (**Replacement**; 1–64 chars, `[A-Za-z0-9_-]`, cannot begin/end with `-`/`_`), `Tags` (no interruption) | `Ref` → ARN; `FunctionArn`, `State`, … | +| `AWS::Lambda::WebFunctionRevision` | **Every property → Replacement** (`BuildConfig{CodeConfig.S3Object{Bucket,Key,VersionId?}, RuntimeConfig.Runtime}`, `ServiceConfig{ExecutionRoleArn (req), EnvironmentVariables, TimeoutSeconds 3–900 (30), MaxConcurrencyPerEnvironment 1–128 (64), TelemetryConfig.LoggingConfig{LogGroup, ApplicationLogLevel, SystemLogLevel}, EgressNetworkConnectorArn}`, `KmsKeyArn`, `Description`, `FunctionName` name-or-ARN) | `RevisionId`, `RevisionArn`, … | +| `AWS::Lambda::WebFunctionEndpoint` | `AuthType` `IamAuth`/`ApplicationManaged` (**no interruption**), `EndpointName` (**Replacement**), `EndpointType` `HomeRegion`/`MultiRegion`/`PerRegion` (**Replacement**), `Regions` (**Replacement**; required for Multi/PerRegion, must include a non-home Region), `FunctionName` (**Replacement**), `RevisionWeights` 1–2 (no interruption), `ScalingConfig.MaxEnvironments` 2–10000, `ThrottleConfig.RateLimit` 0 or 100–1000 step 100 or 2000–10000 step 1000 (“can vary by Region”) | `DomainName`, `EndpointArn`, `RegionalEndpoints`, … | +| `AWS::Lambda::ResourcePolicy` | `ResourceArn` — function or **web-function ARN** (`…:web-function/{name}`, unqualified, no wildcards) (**Replacement**); `PolicyDocument` (no interruption). AWS warns against combining it with `AWS::Lambda::Permission` on the same function. | `Ref` → ResourceArn | + +Runtime facts: `nodejs24.x` is the only runtime. The server must listen on `AWS_LAMBDA_HTTP_ENDPOINT` within 10 s. +The entry file defaults to `index.js`; `AWS_LAMBDA_NODEJS_ENTRYPOINT` overrides it. Each environment has 2 GB of +memory. HTTPS only on 443; HTTP/1.1; **no WebSocket upgrades**. Up to 50 revisions per function, with automatic +cleanup. The package is ≤ 512 MB unzipped. Endpoints scale to zero (cold starts). Default log group: +`/aws/lambda/web/{function-name}`. CloudWatch metric namespace observed in Sharedale: `AWS/Lambda/Web` (not +confirmed on the doc pages read). + +Not confirmed by the AWS pages read (and **not** relied on by the library): arm64-only execution (asserted by +community samples), and the runtime-API readiness callback `POST /2025-09-01/ready` used by `execve` shims. + +### 5.2 Code in S3 + +- S3 is the only code source. **The bucket must have versioning enabled.** `VersionId` is optional; if it is omitted, + Lambda pins the latest version *at revision creation*. +- Lambda reads with the **service principal**, not the caller. The bucket policy grants `lambda.amazonaws.com` + `s3:GetObject` and `s3:GetObjectVersion` with `ArnLike aws:SourceArn + arn:aws:lambda:{region}:{account}:web-function/{name}/revision/*`. +- SSE-KMS **on the code bucket** (artifact encryption at rest in S3): the key policy must allow + `lambda.amazonaws.com` `kms:Decrypt`, because Lambda reads the object with its service principal. The AWS-managed + `aws/s3` key cannot grant that (upstream PRs reject `KMS_MANAGED`/`DSSE_MANAGED`). This is unrelated to the + revision's own `KmsKeyArn` (§5.1), which encrypts the code and environment variables that Lambda stores for the + revision, and for multi-Region endpoints requires a multi-Region key with replicas. v1 supports the first and + defers the second ([§8.7](#87-kms-scope-decision)). +- Cross-account and cross-Region buckets are allowed (same partition, not an opt-in Region). Cross-account needs a + bucket-policy grant. +- Deleting the pinned object version, or removing read access, moves revisions to a permanent `Failed` state, and + requests get 409 `Platform.RevisionNotActive`. +- **The CDK bootstrap asset bucket does not work** (no service-principal read). Both upstream PRs work around this by + copying into a compliant bucket with a custom resource. That is why v1 is `FromBucket` only. + +### 5.3 IAM authentication + +- Action `lambda:InvokeWebFunctionEndpoint` on `arn:aws:lambda:{r}:{a}:web-function/{fn}/endpoint/{ep}`; + `…/endpoint/*` for all endpoints of a function. +- **Same account: an identity policy alone is sufficient.** Cross-account: identity policy **and** a resource-policy + statement are both required. +- The resource policy is attached to the **function ARN**. There is one policy per function, and `put` replaces it. + Statements scope `Resource` to an endpoint ARN. +- Signing: HomeRegion and PerRegion use SigV4 (endpoint Region). MultiRegion uses **SigV4A** with region set `*`. + Service name `lambda`. Every request needs `X-Amz-Content-SHA256` (`UNSIGNED-PAYLOAD` allowed; chunked signing is + not supported). Lambda strips the SigV4 `Authorization` header (and `X-Amz-Security-Token`) before forwarding. +- Condition keys: `lambda:Resource/WebFunctionAuthType`, `lambda:Request/WebFunctionAuthType`, + `aws:ResourceTag/*` (endpoints and revisions inherit function tags), and `aws:SourceArn` (CloudFront). +- `ApplicationManaged`: Lambda does not authenticate or evaluate the resource policy. The endpoint “stays publicly + reachable at its own domain, even behind CloudFront.” + +### 5.4 CloudFront OAC for Web Function origins + +- OAC origin type `lambda` (shared with Function URLs). **Only `always-amz-auth`** works for Web Function origins, + and it works for no other origin type. CloudFront signs in a dedicated header and passes the viewer's + `Authorization` header through unchanged. +- Protocol: `sigv4` for regional hostnames (`*.lambda-web.{region}.on.aws`, HomeRegion/PerRegion); `sigv4a` for + global hostnames (`*.lambda-web.global.on.aws`, MultiRegion). +- The endpoint must be `IamAuth`. The resource-policy statement: `cloudfront.amazonaws.com`, + `lambda:InvokeWebFunctionEndpoint`, endpoint ARN, `StringEquals aws:SourceArn + arn:aws:cloudfront::{account}:distribution/{id}`. +- **The viewer `Host` header must not be forwarded**, or the endpoint returns 404. Use + `AllViewerExceptHostHeader`, not `AllViewer`. +- For GET and HEAD, CloudFront drops `Authorization` unless it is in the **cache policy**. +- Bodies are signed as `UNSIGNED-PAYLOAD`, so viewers send nothing extra. +- **Lambda@Edge origin-request/origin-response triggers are rejected** on behaviors that use a Web Function origin + with OAC. +- OAC is not supported for global endpoints that include **opt-in Regions** (403). +- OAC takes effect only after the distribution deploys (and, for multi-Region endpoints, after the policy + replicates). Transient 403s occur in between. + +### 5.5 CDK version floor + +| Capability | 2.273.0 | 2.274.0 | Unreleased | +|---|---|---|---| +| Web Function L1s, `CfnResourcePolicy` | ✅ | ✅ | | +| `SigningBehavior.ALWAYS_AMZ_AUTH`, `SigningProtocol.SIGV4A` | ❌ | ✅ | | +| `Signing.SIGV4_ALWAYS_AMZ_AUTH` | ❌ | ✅ | | +| `Signing.SIGV4A_ALWAYS_AMZ_AUTH` static | ❌ | ❌ (use `new Signing(SIGV4A, ALWAYS_AMZ_AUTH)`) | aws-cdk#39216, merged 2026-10-22 | +| Web Function L2 | ❌ | ❌ | aws-cdk#39210, #39235 (open) | +| Web Function CloudFront origin | ❌ | ❌ | aws-cdk#39434 (open issue) | + +Spike: on 2.274.0, `new FunctionUrlOriginAccessControl(..., Signing = new Signing(SigningProtocol.SIGV4A, +SigningBehavior.ALWAYS_AMZ_AUTH))` synthesizes `lambda` / `always-amz-auth` / `sigv4a`, and `Signing.SIGV4_ALWAYS_AMZ_AUTH` +synthesizes `sigv4`. **Decision: bump the floor to 2.274.0 and use the L2 `FunctionUrlOriginAccessControl`** +(origin type `lambda` is shared). There is no L1 OAC and no custom resource. + +Observed on 2.273.0 during the spike: CDK's built-in template validation emits `WARNING Unknown resource type +'AWS::Lambda::WebFunction' (CloudFormation Validate, F3006)` for Web Function L1s. It is a warning by default and an +error with `@aws-cdk/core:validateAgainstDefaultRules`. Re-check on 2.274.0 during implementation and document it. + +### 5.6 Native vs. gap vs. workaround + +| Need | Native CDK | Library gap filled | Sharedale workaround to drop | +|---|---|---|---| +| Function/revision/endpoint | L1 only | Typed props, dependencies, validation | Hand-wired L1s | +| OAC | L2 `FunctionUrlOriginAccessControl` + `Signing` (2.274) | Correct signing per endpoint type | `CfnOriginAccessControl` with literals | +| Origin | `HttpOrigin` | `WebFunctionOrigin` factory + auto-grant at `Bind` | Manual `HttpOrigin` + manual policy | +| Resource policy | `CfnResourcePolicy` L1 | Single-owner, lazy, deduplicated | Manual `CfnResourcePolicy` | +| Grants | `Grant.AddToPrincipal`, `Grant.AddStatementToResourcePolicy` | `GrantInvoke` with explicit same/cross-account handling (§10.2) | Manual `PolicyStatement` | +| Code bucket policy | `IBucket.AddToResourcePolicy` | Least-privilege statement + dependency | Bootstrap-stack statement (kept, as *externally managed*) | + +**No custom resources or escape hatches are required for v1.** + +--- + +## 6. Architectural alternatives and tradeoffs + +| | A — Extend existing | B — Dedicated full-stack | **C — Hybrid composition (chosen)** | +|---|---|---|---| +| Shape | Web Function modes on `LambdaFunctionConstruct`; OAC on `StaticSiteConstruct` | `WebApplicationConstruct` owning Web Function + CloudFront + ACM + DNS | `WebFunctionConstruct` + endpoint + `WebFunctionOrigin`; consumer owns Distribution, certificate, DNS | +| Evidence for | Reuses names | Least boilerplate for one simple site | Sharedale's edge (wildcard hosts, viewer-host function, cookie filter, secret header) is app-specific; the Cognito construct already moved to injected `ICertificate`/`IHostedZone`; CDK's `FunctionUrlOrigin` precedent | +| Evidence against | Different CFN resources (no versions/aliases/handler/memory/architecture; revisions instead); existing constructs are opinionated in incompatible ways (`PROVIDED_AL2023`, `live` alias, `Code.FromAsset`); regression risk; zero-diff requirement | Re-creates `StaticSiteConstruct`'s rigidity (zone lookup, fixed behaviors); can't represent Sharedale | More types than A | +| Breaking risk | High | None | None (additive) | + +**Upstream relationship.** Build the L3 over L1s. Keep upstream L2 types out of the public API. Use upstream +*design ideas* where sound: required `authType` with no default; `grants.invoke` on the endpoint; synth-time +validation; owned-bucket checks; `node.defaultChild` set explicitly (their KMS service-grant pattern is noted for the deferred `EncryptionKey`). +Do **not** adopt either PR's API or package as a dependency or compatibility contract. Track aws-cdk#39434. + +--- + +## 7. Recommended design and rationale + +1. **One construct per Web Function** owning the resources whose lifecycle is the function's: the function, the + current revision, endpoints, the resource policy, and *optionally* the role and log group. +2. **Endpoints are first-class** because grants, OAC, URLs, and auth are per endpoint. All endpoints route 100% to the + construct's single current revision. +3. **Authorization is resource-oriented.** `endpoint.GrantInvoke(grantee)` and `endpoint.GrantCloudFrontInvoke(arn)`. + The endpoint implements CDK's `IResourceWithPolicy` contract and composes CDK's `Grant` primitives, but it checks + what was actually written instead of trusting `Grant.Success` (§10.2). +4. **CloudFront integration is an origin, not a distribution.** `WebFunctionOrigin.WithOriginAccessControl(endpoint)` + mirrors `FunctionUrlOrigin.WithOriginAccessControl` and auto-grants at `Bind`. +5. **Fail closed and fail early.** Explicit `AuthType`, synth-time validation ([§14](#14-validation-and-error-handling)), + an explicit check of every grant side the library is responsible for, no silent no-ops. +6. **Thin and honest.** Typed knobs exist only for AWS-defined capabilities. No workload presets. No derived + environment variables except the AWS-defined entry point. +7. **Stable synthesis contract.** Construct child IDs, properties, and dependencies are pinned by full golden + templates, separate from C# API stability ([§12.4](#124-compatibility-guarantees-and-future-upstream-l2-adoption)). + +--- + +## 8. Proposed public API + +Namespaces follow the repository: constructs and origin in `LayeredCraft.Cdk.Constructs`, props, options, enums, and +code types in `LayeredCraft.Cdk.Constructs.Models`, test helpers in `LayeredCraft.Cdk.Constructs.Testing`. Signatures +are normative for naming and shape. XML docs are abbreviated. + +**Revision 4:** the resource interface `IWebFunctionEndpoint` lives in `LayeredCraft.Cdk.Constructs`, next to +`WebFunctionEndpointConstruct` (CDK's `IFoo`-beside-`Foo` convention). It is not a props, options, enum, or code type, and +moving it after release would be a breaking change. `IWebFunctionEndpoint` is implemented by the library's own owned and +imported endpoints; it is not intended for consumer implementation, and library code treats any implementation other +than `WebFunctionEndpointConstruct` as imported. + +### 8.1 Enums and value types (`Models/`) + +```csharp +public enum WebFunctionAuthType +{ + /// Lambda authenticates SigV4/SigV4A callers and authorizes them with IAM + /// (identity policy and the function's resource policy). Required for OAC and GrantInvoke. + IamAuth, + /// Lambda performs no authentication; the endpoint is publicly reachable at its own domain, + /// even behind CloudFront. The application must authenticate every request. + ApplicationManaged, +} + +public enum WebFunctionEndpointType { HomeRegion, MultiRegion, PerRegion } + +/// Who maintains the lambda.amazonaws.com read statement on the code bucket. +public enum WebFunctionCodeBucketPolicy +{ + /// The construct adds a least-privilege statement. Requires a bucket the app can modify + /// (an owned IBucket); an imported bucket fails synthesis. + Automatic, + /// The bucket policy is managed elsewhere (another stack, account, or process). Nothing is added. + ExternallyManaged, +} + +/// Who maintains the CloudFront statement in the endpoint's resource policy. +public enum WebFunctionOriginPermissions +{ + /// When the origin is bound to a distribution, add an aws:SourceArn-scoped statement for that + /// distribution to the function's resource policy. Requires an endpoint owned by a WebFunctionConstruct + /// in the distribution's stack. + Automatic, + /// The consumer guarantees that the function's resource policy already allows this distribution + /// (for example, an imported endpoint, or an explicit GrantCloudFrontInvoke). + ExternallyManaged, +} + +public sealed class WebFunctionRuntime +{ + public static readonly WebFunctionRuntime NodeJs24X = new("nodejs24.x"); + /// Escape hatch for runtimes AWS adds before this package does. + public static WebFunctionRuntime Of(string name); + public string Name { get; } +} +``` + +Log levels reuse CDK's existing `Amazon.CDK.AWS.Lambda.ApplicationLogLevel` and `SystemLogLevel`. They are not +redefined. + +### 8.2 Code + +```csharp +public abstract class WebFunctionCode +{ + private protected WebFunctionCode() { } // closed hierarchy: FromAsset can be added later + + public static WebFunctionCode FromBucket(IBucket bucket, string key, WebFunctionCodeFromBucketOptions? options = null); + + // internal: produces S3Object {Bucket, Key, VersionId?} and applies the bucket policy for `function` + internal abstract WebFunctionCodeConfig Bind(WebFunctionConstruct function); +} + +public sealed record WebFunctionCodeFromBucketOptions +{ + /// Pins the revision to this S3 object version. When null, Lambda pins the latest version + /// at revision creation; later overwrites of the key do not affect existing revisions but do affect + /// the next one CloudFormation creates. + public string? ObjectVersion { get; init; } + public WebFunctionCodeBucketPolicy BucketPolicy { get; init; } = WebFunctionCodeBucketPolicy.Automatic; +} +``` + +`Automatic` adds this statement to an owned bucket (`IBucket.AddToResourcePolicy(...).StatementAdded` must be +`true`, or synthesis fails telling the consumer to use `ExternallyManaged`): + +```json +{ "Effect": "Allow", "Principal": { "Service": "lambda.amazonaws.com" }, + "Action": ["s3:GetObject", "s3:GetObjectVersion"], + "Resource": "arn:{partition}:s3:::{bucket}/{key}", + "Condition": { + "StringEquals": { "aws:SourceAccount": "{account}" }, + "ArnLike": { "aws:SourceArn": "arn:{partition}:lambda:{region}:{account}:web-function/{FunctionName}/revision/*" } } } +``` + +The revision gets a dependency on the bucket policy (`PolicyDependable`). Region and account come from the +**function's** stack. If they are unresolved and the bucket is in a different stack, synthesis fails and asks for an +explicit stack `Env` (otherwise pseudo-parameters would resolve in the wrong stack). + +### 8.3 `WebFunctionConstruct` + +```csharp +public interface IWebFunctionConstructProps +{ + string FunctionName { get; } // required; see §14 + WebFunctionCode Code { get; } // required + IWebFunctionEndpointOptions Endpoint { get; } // required: the default endpoint (AuthType required) + WebFunctionRuntime Runtime { get; } // NodeJs24X + string? EntryPoint { get; } // → AWS_LAMBDA_NODEJS_ENTRYPOINT + IReadOnlyDictionary EnvironmentVariables { get; } + Duration Timeout { get; } // 30 s; 3–900 s + int? MaxConcurrencyPerEnvironment { get; } // AWS default 64; 1–128 + string? Description { get; } // revision description + IRole? Role { get; } // null → created + WebFunctionLogs Logs { get; } // WebFunctionLogs.Create() + ApplicationLogLevel? ApplicationLogLevel { get; } + SystemLogLevel? SystemLogLevel { get; } +} + +public sealed record WebFunctionConstructProps : IWebFunctionConstructProps +{ + public required string FunctionName { get; init; } + public required WebFunctionCode Code { get; init; } + public required IWebFunctionEndpointOptions Endpoint { get; init; } + public WebFunctionRuntime Runtime { get; init; } = WebFunctionRuntime.NodeJs24X; + public string? EntryPoint { get; init; } + public IReadOnlyDictionary EnvironmentVariables { get; init; } = new Dictionary(); + public Duration Timeout { get; init; } = Duration.Seconds(30); + public int? MaxConcurrencyPerEnvironment { get; init; } + public string? Description { get; init; } + public IRole? Role { get; init; } + public WebFunctionLogs Logs { get; init; } = WebFunctionLogs.Create(); + public ApplicationLogLevel? ApplicationLogLevel { get; init; } + public SystemLogLevel? SystemLogLevel { get; init; } +} + +/// Where the revision's logs go. A closed choice, so "supplied group" and "create a group" +/// can never be combined or contradict each other. +public abstract class WebFunctionLogs +{ + private protected WebFunctionLogs() { } + + /// Create /aws/lambda/web/{FunctionName}. Defaults: RetentionDays.TWO_WEEKS, RemovalPolicy.DESTROY. + public static WebFunctionLogs Create(RetentionDays? retention = null, RemovalPolicy? removalPolicy = null); + + /// Write to an existing log group, passed by name to the revision. + public static WebFunctionLogs Use(ILogGroup logGroup); + + /// Create nothing and let Lambda use its default group (/aws/lambda/web/{FunctionName}), + /// which has no expiry. + public static WebFunctionLogs ServiceDefault(); +} + +public sealed class WebFunctionConstruct : Construct, IGrantable +{ + public WebFunctionConstruct(Construct scope, string id, IWebFunctionConstructProps props); + + public string FunctionName { get; } // the literal name (or token) from props + public string FunctionArn { get; } // GetAtt FunctionArn + public string RevisionId { get; } // current revision + public string RevisionArn { get; } + public IRole Role { get; } // created or supplied execution role + public IPrincipal GrantPrincipal { get; } // Role.GrantPrincipal: lets table.GrantReadData(webFunction) etc. + // (permissions OF this function, never invoke permissions ON it) + public ILogGroup? LogGroup { get; } // the created or supplied group; null for ServiceDefault() + + public WebFunctionEndpointConstruct DefaultEndpoint { get; } + public IReadOnlyList Endpoints { get; } // a genuinely read-only view (rev 4) + + /// Adds another endpoint for the current revision. EndpointName must be unique within the function. + /// The id must not be one of the reserved child IDs below (ArgumentException, rev 4). + public WebFunctionEndpointConstruct AddEndpoint(string id, IWebFunctionEndpointOptions options); +} +``` + +Resources created (stable child IDs, a public contract for `Node.FindChild` escape hatches): + +| Child ID | Resource | When | +|---|---|---| +| `Function` (`Node.DefaultChild`) | `AWS::Lambda::WebFunction` | always | +| `Revision` | `AWS::Lambda::WebFunctionRevision` | always | +| `DefaultEndpoint` | `WebFunctionEndpointConstruct` → `Resource` = `AWS::Lambda::WebFunctionEndpoint` | always | +| *(consumer id)* | additional `WebFunctionEndpointConstruct` | `AddEndpoint` | +| `ExecutionRole` | `AWS::IAM::Role` + `AWSLambdaBasicExecutionRole` | `Role == null` | +| `LogGroup` | `AWS::Logs::LogGroup` named `/aws/lambda/web/{FunctionName}` | `Logs = WebFunctionLogs.Create(...)` (default) | +| `ResourcePolicy` | `AWS::Lambda::ResourcePolicy` (`ResourceArn` = function ARN) | first statement only | + +**Reserved child IDs (revision 4).** `Function`, `Revision`, `DefaultEndpoint`, `ExecutionRole`, `LogGroup`, and +`ResourcePolicy` are reserved whether or not the corresponding resource exists in a given configuration. `AddEndpoint` +rejects them with `ArgumentException`, so a lazily created child (the resource policy) or a later configuration change +(switching `Logs` to `Create()`) can never collide with a consumer endpoint. + +Notes: + +- The created log group's name equals AWS's default, so switching between `Create()` and `ServiceDefault()` never + moves logs. Switching from `Create()` to `ServiceDefault()` deletes the CloudFormation-managed group under the + default `DESTROY` policy; Lambda then recreates it without expiry. A group supplied with `Use(...)` is passed by + name, and the role gets `logGroup.GrantWrite(role)` when the name is outside `/aws/lambda/*`. +- **Default retention is `RetentionDays.TWO_WEEKS`.** That matches the only existing retention convention in the + library (`LambdaFunctionConstruct.cs:69`) and keeps a fresh deployment's log storage modest. It is a default, not a + policy: Sharedale's 30 days is `WebFunctionLogs.Create(RetentionDays.ONE_MONTH)`. A Web Function-only default of 30 + days would make the library's two compute constructs disagree for no technical reason. **Decided (revision 3): `TWO_WEEKS`.** +- `FunctionName` is passed as the **literal name** to `Revision.FunctionName` and `Endpoint.FunctionName`, with + explicit `AddResourceDependency` (function ← revision ← endpoints). This is CloudFormation's documented form and + Sharedale's deployed shape. Switching to `Ref` (an ARN) later would *replace every endpoint*, so it is pinned. +- **Execution-role ordering (revision 4).** The revision depends on the execution role's `CfnRole` only: through its + `ExecutionRoleArn` reference, plus an explicit `DependsOn` on the role's `CfnRole` when the role is owned. It never + depends on the whole `Role` construct, because that subtree includes the role's `DefaultPolicy`. Invoke grants and + other permissions written to that policy reference other resources (for example another function's endpoint), and + depending on it creates CloudFormation cycles for mutual invocation, self-invocation, and BFF/API cross-references + (an API environment variable holding the BFF URL while the BFF is granted invoke on the API). Consequence: on a + first deployment, policy statements attached to the role may not yet have propagated when the revision activates. + This is an IAM eventual-consistency window, verified in the sandbox gate ([§19.1](#191-release-acceptance-criteria)), + not a correctness dependency the template can express without cycles. +- No revision KMS key in v1 ([§8.7](#87-kms-scope-decision)). +- Tags: `Tags.Of(construct)` reaches the taggable `CfnWebFunction`. Endpoints and revisions inherit function tags + for ABAC. + +### 8.4 Endpoints + +```csharp +public interface IWebFunctionEndpointOptions +{ + string EndpointName { get; } // "default"; must be unique per function + WebFunctionAuthType AuthType { get; } // required, no default + WebFunctionEndpointType EndpointType { get; } // HomeRegion + IReadOnlyList Regions { get; } // Multi/PerRegion only + int? MaxEnvironments { get; } // 2–10000; null = account vCPU quota only + int? RateLimit { get; } // 0 | 100..1000 step 100 | 2000..10000 step 1000 + string? Description { get; } +} + +public sealed record WebFunctionEndpointOptions : IWebFunctionEndpointOptions +{ + public string EndpointName { get; init; } = "default"; + public required WebFunctionAuthType AuthType { get; init; } + public WebFunctionEndpointType EndpointType { get; init; } = WebFunctionEndpointType.HomeRegion; + public IReadOnlyList Regions { get; init; } = []; + public int? MaxEnvironments { get; init; } + public int? RateLimit { get; init; } + public string? Description { get; init; } +} + +public interface IWebFunctionEndpoint : IResource +{ + string EndpointName { get; } + string EndpointArn { get; } + string DomainName { get; } + string Url { get; } // "https://" + DomainName + WebFunctionAuthType AuthType { get; } + WebFunctionEndpointType EndpointType { get; } + Grant GrantInvoke(IGrantable grantee); + Grant GrantInvoke(IGrantable grantee, WebFunctionInvokeGrantOptions options); + void GrantCloudFrontInvoke(string distributionArn); +} + +public sealed class WebFunctionEndpointConstruct : Resource, IWebFunctionEndpoint, IResourceWithPolicy +{ + // created only by WebFunctionConstruct (internal ctor) + public WebFunctionConstruct WebFunction { get; } + public IReadOnlyList Regions { get; } + + /// Allows the grantee to call lambda:InvokeWebFunctionEndpoint on this endpoint only. Writes the + /// policies this app can write and throws when a side it is responsible for cannot be written; see §10.2 for + /// exactly which policies are modified and what a cross-account caller must configure itself. + /// Throws for ApplicationManaged endpoints. + public Grant GrantInvoke(IGrantable grantee); + public Grant GrantInvoke(IGrantable grantee, WebFunctionInvokeGrantOptions options); // §10.2 + + /// Allows cloudfront.amazonaws.com to invoke this endpoint for one distribution + /// (StringEquals aws:SourceArn). Accepts a token or a literal ARN; no Distribution construct required. + /// Throws for ApplicationManaged and imported endpoints. Idempotent: identical statements are deduplicated. + public void GrantCloudFrontInvoke(string distributionArn); + + /// IResourceWithPolicy: adds to the owning function's single resource policy. The statement's + /// Resource must be exactly this endpoint's ARN (otherwise ArgumentException). This is the only public + /// resource-policy entry point; WebFunctionConstruct has none of its own. + /// Revision 4: the statement is validated, then a frozen copy is stored, so later mutation of the caller's + /// object cannot widen it. An Allow statement is rejected (ArgumentException) when it has no conditions and + /// names a wildcard principal ("*" / AnyPrincipal / StarPrincipal) or a service principal, or when it uses + /// NotPrincipal. Deny statements are not restricted. An explicit Allow statement with a wildcard principal AND + /// conditions (for example aws:PrincipalOrgID) is accepted: the consumer is responsible for ensuring the conditions + /// meaningfully restrict access. The library does not analyze condition semantics. + public AddToResourcePolicyResult AddToResourcePolicy(PolicyStatement statement); + + public static IWebFunctionEndpoint FromEndpointAttributes(Construct scope, string id, WebFunctionEndpointAttributes attributes); +} + +public sealed record WebFunctionEndpointAttributes +{ + public required string EndpointArn { get; init; } + public required string DomainName { get; init; } + public required WebFunctionAuthType AuthType { get; init; } + public WebFunctionEndpointType EndpointType { get; init; } = WebFunctionEndpointType.HomeRegion; + /// Revision 4: the endpoint's 12-digit account. Optional. Needed only when EndpointArn is a token and + /// identity grants are wanted; when EndpointArn is literal, its account is used and a supplied Account must match. + public string? Account { get; init; } +} +``` + +Ownership semantics: + +- `WebFunctionEndpointConstruct` instances are created only by `WebFunctionConstruct` (internal constructor). The + function owns the revision, the endpoints, and the resource policy. An endpoint never creates resources of its own + beyond its L1. +- An imported `IWebFunctionEndpoint` owns nothing. It can write identity policies only on owned, mutable CDK + identities whose account is established (§10.2 rev-4 item 4; imported roles, mutable or not, are not written to) + and nothing else. `GrantCloudFrontInvoke` and any grant that needs the resource policy throw ("the resource policy of an + imported endpoint is externally owned"). Endpoint name, account, and Region are parsed from the ARN when it is + literal. ~~When the ARN is a token, the account is unresolved, so only owned (E1) grantees can be granted.~~ + *(Superseded by the revision-4 account rule below.)* +- **Imported endpoint validation (revision 4).** + - A literal `EndpointArn` must match + `arn:{partition}:lambda:{region}:{12-digit account}:web-function/{function}/endpoint/{endpoint}`. + - A literal `DomainName` must be non-empty (empty → `ArgumentException`; null → `ArgumentNullException`). + - A literal `Account` must be 12 digits. When both `Account` and a literal `EndpointArn` are supplied, they must be + equal (`ArgumentException`). + - Tokens are not validated. + - The imported resource's environment is the endpoint's, not the importing stack's: `Env.Account` is the literal ARN + account or else `Account`, and `Env.Region` comes from the ARN. +- **Imported endpoint account rule (revision 4).** The *endpoint account* is the literal ARN's account, or else a + literal `Account`. Otherwise it is **not established**: a token ARN with no `Account` or with a token `Account`. + - When the endpoint account is not established, `GrantInvoke` throws for **every** grantee, owned ones included. The + message names both remedies: supply a literal `Account`, or configure the caller's access outside this app. Such an + endpoint remains fully usable as a CloudFront origin with `WebFunctionOriginPermissions.ExternallyManaged`, which + needs no `GrantInvoke`. + - When the endpoint account is established, a grantee is established only if its account is literally `SAME`: an + owned principal's stack account, or an imported principal's `PrincipalAccount`. `ONE_UNRESOLVED` (for example an + env-agnostic caller stack) and `BOTH_UNRESOLVED` are **not** established. The library cannot write the owner's + resource policy, and could otherwise report a cross-account grant as complete. + - An imported endpoint never writes a resource policy, so `ExternallyManaged` grants and `GrantCloudFrontInvoke` still + throw (revision 3). +- The default endpoint and `AddEndpoint` endpoints have identical semantics. The only difference is that the default + one is created from `props.Endpoint`. Leaving `EndpointName` at `"default"` in `AddEndpoint` fails as a duplicate. + +### 8.5 CloudFront origin + +```csharp +public static class WebFunctionOrigin +{ + /// An HTTPS origin for an IamAuth endpoint, signed by OAC (origin type lambda, always-amz-auth, + /// sigv4 for HomeRegion/PerRegion, sigv4a for MultiRegion). + public static IOrigin WithOriginAccessControl(IWebFunctionEndpoint endpoint, WebFunctionOriginWithOacProps? props = null); + + /// An HTTPS origin for an ApplicationManaged endpoint. The endpoint remains directly reachable + /// on the internet; CloudFront adds no access control. + public static IOrigin WithoutOriginAccessControl(IWebFunctionEndpoint endpoint, WebFunctionOriginProps? props = null); +} + +/// The HttpOrigin settings a consumer may choose. Domain, protocol (HTTPS only), and the OAC id are +/// owned by the factory and deliberately not expressible here (revision 1 passed HttpOriginProps through +/// and rejected the conflicting members at runtime; that made ownership ambiguous). +public record WebFunctionOriginProps +{ + public string? OriginId { get; init; } + public string? OriginPath { get; init; } + public IReadOnlyDictionary? CustomHeaders { get; init; } + public double? ConnectionAttempts { get; init; } + public Duration? ConnectionTimeout { get; init; } + public Duration? ReadTimeout { get; init; } + public Duration? KeepaliveTimeout { get; init; } + public Duration? ResponseCompletionTimeout { get; init; } + public bool? OriginShieldEnabled { get; init; } + public string? OriginShieldRegion { get; init; } +} + +/// Mirrors CDK's FunctionUrlOriginWithOACProps extending FunctionUrlOriginProps. +public sealed record WebFunctionOriginWithOacProps : WebFunctionOriginProps +{ + /// An existing OAC (for example, one shared across distributions). When null, one + /// FunctionUrlOriginAccessControl is created in the binding distribution's scope. A supplied OAC is used as is; + /// the consumer is responsible for its configuration (lambda / always-amz-auth / protocol matching the endpoint). + public IOriginAccessControl? OriginAccessControl { get; init; } + public WebFunctionOriginPermissions Permissions { get; init; } = WebFunctionOriginPermissions.Automatic; +} +``` + +New CDK `HttpOriginProps` members are not exposed automatically. Each is added deliberately in a minor release. That +is a small maintenance cost, accepted in exchange for unambiguous ownership. + +### 8.6 Testing helpers (`Testing/`) + +```csharp +public static class WebFunctionConstructAssertions +{ + public static void ShouldHaveWebFunction(this Template t, string functionName); + public static void ShouldHaveRevision(this Template t, string functionName, string runtime = "nodejs24.x"); + public static void ShouldHaveRevisionCode(this Template t, string bucketName, string key, string? versionId = null); + public static void ShouldHaveEndpoint(this Template t, string functionName, string endpointName, + WebFunctionAuthType authType, WebFunctionEndpointType type = WebFunctionEndpointType.HomeRegion); + public static void ShouldHaveEndpointScaling(this Template t, string endpointName, int? maxEnvironments, int? rateLimit); + // Matches by names (like the Cognito assertions), never by logical-ID prefixes: + public static void ShouldHaveInvokeGrant(this Template t, string functionName, string endpointName); // an identity statement on that endpoint's ARN + public static void ShouldHaveSingleResourcePolicy(this Template t, string functionName); // exactly one, ResourceArn = that function + public static void ShouldHaveNoResourcePolicy(this Template t); + public static void ShouldAllowCloudFront(this Template t, string functionName, string endpointName); // cloudfront.amazonaws.com + aws:SourceArn condition + public static void ShouldAllowResourcePolicyPrincipal(this Template t, string functionName, string endpointName, string principalArn); + public static void ShouldHaveWebFunctionOac(this Template t, string signingProtocol = "sigv4"); + public static void ShouldHaveCodeBucketReadStatement(this Template t, string functionName); +} + +/// Follows the repository's builder convention (CognitoUserPoolConstructPropsBuilder, +/// StaticSiteConstructPropsBuilder): private fields, With*/Without* methods taking values or whole props +/// objects, Build() returning the init-only record. No mutation callbacks: the props records are init-only, +/// and callers customize an options record with a `with` expression before passing it in. +public class WebFunctionConstructPropsBuilder // CdkTestHelper.CreateWebFunctionPropsBuilder() +{ + // Defaults: FunctionName "test-web-function"; no Code; no endpoint. + public WebFunctionConstructPropsBuilder WithFunctionName(string functionName); + public WebFunctionConstructPropsBuilder WithCode(WebFunctionCode code); + /// Imports bucket "test-web-function-artifacts" in and uses + /// FromBucket(bucket, key, ExternallyManaged): synthesizes without AWS credentials or a bucket resource. + public WebFunctionConstructPropsBuilder WithTestArtifact(Construct scope, string key = "artifacts/app.zip"); + public WebFunctionConstructPropsBuilder WithIamAuthEndpoint(); // = WithEndpoint(new() { AuthType = IamAuth }) + public WebFunctionConstructPropsBuilder WithApplicationManagedEndpoint(); // = WithEndpoint(new() { AuthType = ApplicationManaged }) + public WebFunctionConstructPropsBuilder WithEndpoint(IWebFunctionEndpointOptions endpoint); + public WebFunctionConstructPropsBuilder WithEnvironmentVariable(string key, string value); + public WebFunctionConstructPropsBuilder WithEntryPoint(string entryPoint); + public WebFunctionConstructPropsBuilder WithTimeout(Duration timeout); + public WebFunctionConstructPropsBuilder WithMaxConcurrencyPerEnvironment(int maxConcurrency); + public WebFunctionConstructPropsBuilder WithRole(IRole role); + public WebFunctionConstructPropsBuilder WithLogs(WebFunctionLogs logs); + /// Throws InvalidOperationException when Code or the endpoint (and therefore AuthType) was never + /// chosen: the builder never picks an auth mode. Performs no other validation; the construct validates. + public WebFunctionConstructProps Build(); +} +``` + +Typical use: + +```csharp +var props = CdkTestHelper.CreateWebFunctionPropsBuilder() + .WithTestArtifact(stack) + .WithEndpoint(new WebFunctionEndpointOptions { AuthType = WebFunctionAuthType.IamAuth, MaxEnvironments = 10 }) + .Build(); +var web = new WebFunctionConstruct(stack, "web", props); +Template.FromStack(stack).ShouldHaveEndpoint("test-web-function", "default", WebFunctionAuthType.IamAuth); +``` + +### 8.7 KMS scope decision + +**Revision encryption (`KmsKeyArn`) is deferred from v1.** + +| | S3 artifact encryption | Revision encryption | +|---|---|---| +| What it protects | The zip object at rest in the consumer's bucket | Code and environment variables that Lambda stores for the revision | +| Configured on | The bucket (SSE-S3 or SSE-KMS) | `AWS::Lambda::WebFunctionRevision.KmsKeyArn` (Replacement) | +| v1 | **Supported.** Owned bucket with `KMS_MANAGED`/`DSSE_MANAGED` rejected; SSE-KMS key-policy requirement (`lambda.amazonaws.com` `kms:Decrypt`) documented, consumer-managed | **Deferred** | + +Why defer: + +- The security model is not validated. The required key-policy grants for the service principal (which actions, + whether `aws:SourceArn` on `…/revision/*` is evaluated for these calls) come only from upstream PR #39210's + reasoning. They are not documented on the AWS pages read, and they are untested in a deployment. +- Multi- and Per-Region endpoints need a multi-Region key with replicas in every endpoint Region. That is a + validation and documentation surface of its own. +- Imported keys cannot be granted, so the feature would ship with a warning path from day one. +- Without `KmsKeyArn`, Lambda applies its default encryption for revision data. Deferral does not remove encryption + at rest; it removes customer-key control. + +Escape hatch for advanced consumers (unsupported, documented as such): +`((CfnWebFunctionRevision)webFunction.Node.FindChild("Revision")).KmsKeyArn = key.KeyArn;` plus key-policy grants +they write themselves. A future minor release can add a typed `EncryptionKey` after a deployed validation, without +breaking changes. + +--- + +## 9. Consumer usage examples + +All examples assume a stack with an explicit `Env` and these usings: `Amazon.CDK`, `.AWS.CloudFront`, +`.AWS.CloudFront.Origins`, `.AWS.CertificateManager`, `.AWS.Route53`, `.AWS.Route53.Targets`, `.AWS.S3`, +`.AWS.DynamoDB`, `LayeredCraft.Cdk.Constructs`, `LayeredCraft.Cdk.Constructs.Models`. + +### 9.1 ASP.NET Core API (Node.js `execve` shim) + +```csharp +// Artifacts are published by CI to a versioned bucket owned by another stack (its policy grants +// lambda.amazonaws.com read on web-function/acme-*/revision/*). +var artifacts = Bucket.FromBucketName(this, "artifacts", $"acme-artifacts-{Account}"); + +var api = new WebFunctionConstruct(this, "api", new WebFunctionConstructProps +{ + FunctionName = "acme-prod-api", + Code = WebFunctionCode.FromBucket(artifacts, $"{artifactTag}/api.zip", new WebFunctionCodeFromBucketOptions + { + BucketPolicy = WebFunctionCodeBucketPolicy.ExternallyManaged, + }), + // index.js at the zip root is the execve shim; no EntryPoint needed. + EnvironmentVariables = new Dictionary + { + ["ASPNETCORE_ENVIRONMENT"] = "Production", + ["Acme__TableName"] = table.TableName, + }, + MaxConcurrencyPerEnvironment = 16, + Endpoint = new WebFunctionEndpointOptions + { + AuthType = WebFunctionAuthType.IamAuth, // only granted callers reach Kestrel + MaxEnvironments = 10, + RateLimit = 100, + }, +}); +table.GrantReadWriteData(api); // WebFunctionConstruct is IGrantable +``` + +### 9.2 Next.js application + +```csharp +var web = new WebFunctionConstruct(this, "web", new WebFunctionConstructProps +{ + FunctionName = "acme-prod-web", + Code = WebFunctionCode.FromBucket(codeBucket, $"{artifactTag}/web.zip", new WebFunctionCodeFromBucketOptions + { + ObjectVersion = webZipVersionId, // optional: pin an exact object version + }), // codeBucket is owned in this stack → Automatic policy + // The zip's index.js sets HOSTNAME/PORT from AWS_LAMBDA_HTTP_ENDPOINT, then require("./server.js"). + EnvironmentVariables = new Dictionary + { + ["NODE_ENV"] = "production", + ["NEXT_TELEMETRY_DISABLED"] = "1", + ["ACME_API_URL"] = api.DefaultEndpoint.Url, // consumer-owned wiring + }, + Endpoint = new WebFunctionEndpointOptions { AuthType = WebFunctionAuthType.IamAuth }, +}); +``` + +### 9.3 Next.js granted permission to invoke the API + +```csharp +// Identity policy on web's execution role: lambda:InvokeWebFunctionEndpoint on api's "default" endpoint ARN only. +// Same account → no resource-policy statement and no AWS::Lambda::ResourcePolicy on api. +api.DefaultEndpoint.GrantInvoke(web); + +// The BFF signs requests itself (SigV4, service "lambda", region of the API endpoint, +// x-amz-content-sha256: UNSIGNED-PAYLOAD). The construct does not inject signing configuration. +``` + +Cross-account variant. It must be explicit, because `Automatic` fails at synthesis for a role in another account: + +```csharp +var partner = Role.FromRoleArn(this, "partner", "arn:aws:iam::222233334444:role/caller"); +api.DefaultEndpoint.GrantInvoke(partner, new WebFunctionInvokeGrantOptions +{ + CallerPolicy = WebFunctionCallerPolicy.ExternallyManaged, +}); +// Writes only api's resource-policy statement (principal = that role ARN, resource = the endpoint ARN) and adds an +// info annotation. Invocation works only after account 222233334444 attaches an identity policy allowing +// lambda:InvokeWebFunctionEndpoint on this endpoint ARN to its role. +``` + +### 9.4 CloudFront distribution with an IAM-protected Web Function origin (OAC) + +```csharp +var origin = WebFunctionOrigin.WithOriginAccessControl(web.DefaultEndpoint, new WebFunctionOriginWithOacProps +{ + CustomHeaders = new Dictionary { ["x-origin-verify"] = secret }, +}); + +var distribution = new Distribution(this, "distribution", new DistributionProps +{ + DefaultBehavior = new BehaviorOptions + { + Origin = origin, + ViewerProtocolPolicy = ViewerProtocolPolicy.REDIRECT_TO_HTTPS, + AllowedMethods = AllowedMethods.ALLOW_ALL, + CachePolicy = CachePolicy.CACHING_DISABLED, // personalized SSR + OriginRequestPolicy = OriginRequestPolicy.ALL_VIEWER_EXCEPT_HOST_HEADER, // never forward Host + }, + AdditionalBehaviors = new Dictionary + { + ["/_next/static/*"] = new BehaviorOptions { Origin = origin, CachePolicy = CachePolicy.CACHING_OPTIMIZED }, + }, + DomainNames = ["app.example.com"], + Certificate = certificate, +}); +// Bind created one FunctionUrlOriginAccessControl (lambda/always-amz-auth/sigv4) and added to web's resource policy: +// cloudfront.amazonaws.com → lambda:InvokeWebFunctionEndpoint on web's default endpoint, +// StringEquals aws:SourceArn = arn:aws:cloudfront::{account}:distribution/{distribution id} +``` + +### 9.5 Custom domain and Route 53 + +There is no library DNS construct to integrate with; composition is plain CDK. That matches +`CognitoUserPoolConstruct`'s injected `ICertificate`/`IHostedZone`, and the same certificate can be shared with a +Cognito custom domain: + +```csharp +var zone = HostedZone.FromHostedZoneAttributes(this, "zone", new HostedZoneAttributes { HostedZoneId = zoneId, ZoneName = "example.com" }); +var certificate = new Certificate(this, "cert", new CertificateProps // CloudFront certificates live in us-east-1 +{ + DomainName = "*.example.com", + Validation = CertificateValidation.FromDns(zone), +}); +// ... distribution from §9.4 with DomainNames = ["app.example.com"], Certificate = certificate ... +var target = RecordTarget.FromAlias(new CloudFrontTarget(distribution)); +_ = new ARecord(this, "app-a", new ARecordProps { Zone = zone, RecordName = "app", Target = target }); +_ = new AaaaRecord(this, "app-aaaa", new AaaaRecordProps { Zone = zone, RecordName = "app", Target = target }); // see #97 + +var auth = new CognitoUserPoolConstruct(this, "users", new CognitoUserPoolConstructProps +{ + UserPoolName = "acme", + Domain = new CognitoUserPoolDomainProps { DomainName = "example.com", AuthSubDomain = "auth", Certificate = certificate, HostedZone = zone }, +}); +``` + +### 9.6 Web Functions without CloudFront or without inter-function IAM + +```csharp +// (a) Public API, no CloudFront: the application authenticates every request. +var publicApi = new WebFunctionConstruct(this, "public-api", new WebFunctionConstructProps +{ + FunctionName = "acme-public-api", + Code = WebFunctionCode.FromBucket(codeBucket, "public-api.zip"), + Endpoint = new WebFunctionEndpointOptions { AuthType = WebFunctionAuthType.ApplicationManaged }, +}); +// publicApi.DefaultEndpoint.Url → https://….lambda-web.us-east-1.on.aws + +// (b) IAM-only internal service invoked by a classic Lambda (no CloudFront): +var worker = new WebFunctionConstruct(this, "internal", new WebFunctionConstructProps +{ + FunctionName = "acme-internal", + Code = WebFunctionCode.FromBucket(codeBucket, "internal.zip"), + Endpoint = new WebFunctionEndpointOptions { AuthType = WebFunctionAuthType.IamAuth }, +}); +worker.DefaultEndpoint.GrantInvoke(existingLambdaConstruct.LambdaFunction); + +// (c) Two endpoints on one function: public for webhooks, IamAuth for CloudFront. +var hooks = web.AddEndpoint("webhooks", new WebFunctionEndpointOptions +{ + EndpointName = "webhooks", + AuthType = WebFunctionAuthType.ApplicationManaged, + RateLimit = 100, +}); +``` + +### 9.7 Imported endpoint as a CloudFront origin (externally managed permissions) + +```csharp +var shared = WebFunctionEndpointConstruct.FromEndpointAttributes(this, "shared", new WebFunctionEndpointAttributes +{ + EndpointArn = "arn:aws:lambda:us-east-1:111122223333:web-function/shared/endpoint/default", + DomainName = "abc123.lambda-web.us-east-1.on.aws", + AuthType = WebFunctionAuthType.IamAuth, +}); +var origin = WebFunctionOrigin.WithOriginAccessControl(shared, new WebFunctionOriginWithOacProps +{ + Permissions = WebFunctionOriginPermissions.ExternallyManaged, // Automatic would fail synthesis +}); +// The owner of "shared" must allow this distribution (aws:SourceArn) in the function's resource policy. +// Revision 4: with a token EndpointArn (e.g. from SSM), this origin use still works. Identity grants +// (shared.GrantInvoke(...)) additionally need a literal Account on the attributes. +``` + +--- + +## 10. IAM authentication and authorization design + +### 10.1 Layers + +| Layer | Who decides | Mechanism | +|---|---|---| +| Endpoint authentication | Lambda | `IamAuth`: SigV4/SigV4A + `lambda:InvokeWebFunctionEndpoint` | +| Caller authorization | IAM | Identity policy (same account) and/or the function's resource policy | +| CloudFront-only access | IAM + OAC | Resource-policy statement with `aws:SourceArn` = distribution | +| User authentication/authorization | Application | Cookies, JWTs, etc. Never inferred from IAM. Lambda strips the SigV4 `Authorization`; with OAC the viewer `Authorization` passes through. | + +The library configures only the first three layers. Documentation states plainly that `IamAuth` is a transport +boundary, not user authorization. + +### 10.2 `GrantInvoke` semantics + +**Verified CDK behavior (aws-cdk v2.274.0, `aws-iam/lib/grant.ts` 149–182, 369–379; `role.ts` 347–391).** Revision 1 +proposed `Grant.AddToPrincipalOrResource` + `Grant.AssertSuccess()`. Reading the source shows that is not safe here: + +- On the not-same-account path, `AddToPrincipalOrResource` attempts the principal statement and then **discards + that result**. The returned `Grant` carries only the resource statement. +- `Grant.Success` is `principalStatement != null || resourceStatement != null`. That tests whether a statement + **object** exists, not whether it was written. The resource statement object always exists on that path, so + `AssertSuccess()` passes even when `AddToResourcePolicy` returned `StatementAdded = false`. +- `Role.FromRoleArn` returns a **mutable** imported role whenever either account is unresolved. CDK would then + attach an `AWS::IAM::Policy` to that role name **in the deploying account**. If the role actually lives in another + account, the deployment fails, because no such role exists there. CDK's `BOTH_UNRESOLVED ⇒ same account` rule + makes the same assumption. + +**Decision (revision 3): the library writes an identity policy only to a principal whose account it can +establish.** Otherwise it writes nothing on the identity side and requires an explicit contract. + +```csharp +public enum WebFunctionCallerPolicy +{ + /// The library must fully configure invocation within this deployment, or synthesis fails. + Automatic, + /// The caller's identity policy is configured outside this app. The library writes only the + /// endpoint's resource-policy statement. + ExternallyManaged, +} + +public sealed record WebFunctionInvokeGrantOptions +{ + public WebFunctionCallerPolicy CallerPolicy { get; init; } = WebFunctionCallerPolicy.Automatic; +} + +// on IWebFunctionEndpoint / WebFunctionEndpointConstruct +Grant GrantInvoke(IGrantable grantee); // = Automatic +Grant GrantInvoke(IGrantable grantee, WebFunctionInvokeGrantOptions options); +``` + +**Account establishment.** The grantee principal's account is *established as the endpoint's account* only when: + +- **(E1) Owned principal:** the grant principal is a construct created in this app (`Resource.IsOwnedResource`, for + example a `Role` L2, the role of a `Function`, or a `WebFunctionConstruct`). Its stack deploys its policy, and + that stack's account must not be literally different from the endpoint stack's account. ~~Both unresolved, or the + same stack, is accepted, because the construct deploys where the role is created.~~ *(Revision 4 clarification, + maintainer-approved 2026-10-23, replaces the struck sentence:)* E1 is established, and the identity side may be + written only for an owned mutable identity (rev-4 item 4), in exactly two cases: + - **Same stack:** the caller and an **owned** endpoint are in the same `Stack` (`Stack.Of` reference equality). + This holds even when the stack is environment-agnostic, because one stack deploys to one account. + - **Different stacks:** both stack accounts are literal and `SAME`. + + Rejected, before any policy is written: different stacks where either account is unresolved (including two + env-agnostic stacks, `BOTH_UNRESOLVED`), different stacks with different literal accounts, and every imported + endpoint without a literal `SAME` account. The same-stack rule does not apply to imported endpoints: an imported + endpoint's account is the ARN's account (or `Account`), not the importing stack's. +- **(E2) Imported principal with matching literal accounts:** the principal (for example `Role.FromRoleArn`) has a + literal `PrincipalAccount` equal (`TokenComparison.SAME`) to a literal endpoint stack account. + +Everything else is *not established*: imported principals with any unresolved account (`ONE_UNRESOLVED`, or +`BOTH_UNRESOLVED` from token ARNs or env-agnostic stacks), literal different accounts, and principals without +`PrincipalAccount`. + +**Algorithm** + +1. `AuthType != IamAuth` → throw. +2. **Identity side.** Only when the account is established: `Grant.AddToPrincipal(action + lambda:InvokeWebFunctionEndpoint, resource = this endpoint ARN)`. ~~A mutable imported same-account role gets an + attached policy. An immutable one (`Mutable = false`) writes nothing; continue to step 3.~~ *(Revision 4 + clarification: the identity side is written only for an owned, mutable CDK identity (rev-4 item 4). Every imported + role, mutable or immutable, continues to step 3.)* +3. **Resource side.** Write `{Principal = grantee principal, Action, Resource = endpoint ARN}` through the function's + single policy when: + - the identity side was not written (an established same-account imported role, mutable or immutable, or an + owned role's `WithoutPolicyUpdates()` view, where a same-account resource-policy grant is sufficient per AWS); or + - ~~the principal is a **service principal** (complete without an identity policy)~~ *(superseded by revision 4: + `GrantInvoke` rejects service principals; see "Revision 4 corrections" below)*; or + - `CallerPolicy = ExternallyManaged`. + + An imported endpoint cannot write the resource side. If the resource side is required there, it throws. +4. **Completeness check under `Automatic`.** Synthesis fails unless invocation is fully configured by this app: + identity side written (owned mutable identity), or established same-account role with resource side written ~~, or service principal + with resource side written~~ *(revision 4: service principals are rejected)*. In particular these **fail**: an + imported principal with an unresolved account, a different literal account, and account or ARN principals of other + accounts (revision 4: account principals of **any** account). The message names the grantee, the + endpoint, the reason ("account of imported role 'X' cannot be established"), and the two remedies: give the stacks + explicit, matching `Env` accounts (or import the role with a literal ARN in the deployment account), or pass + `CallerPolicy = ExternallyManaged` and configure the caller's identity policy in its own account. +5. **`ExternallyManaged`.** Never writes an identity policy, even when the account is established. It writes the + resource-policy statement and adds an `Annotations` info: "Invocation by {principal} requires an identity policy in + the caller's account allowing lambda:InvokeWebFunctionEndpoint on {endpoint ARN}." On an imported endpoint it + throws, since there is no policy to write. +6. Return `Grant.Combine` of the statements actually written (`StatementAdded == true`). `Grant.Success` is never + consulted. + +| Grantee | Option | Identity policy written | Resource policy written | Consumer must configure | Result | +|---|---|---|---|---|---| +| Role/Function/WebFunction created in this app (E1) | Automatic | ✅ | — | nothing | **Complete** | +| ~~`Role.FromRoleArn`, literal account = literal endpoint account (E2), mutable~~ | ~~Automatic~~ | ~~✅ (role must exist)~~ | ~~—~~ | ~~nothing~~ | ~~**Complete**~~ *(superseded by the next row, rev 4)* | +| `Role.FromRoleArn`, literal account = literal endpoint account (E2), **mutable or** `Mutable = false` (rev 4) | Automatic | ❌ | ✅ | nothing | **Complete** (resource grant suffices same-account); imported endpoint → **throws** | +| Owned `Role`/`User`/`Group`/`LazyRole` (E1), imported endpoint whose account is literally `SAME` | Automatic | ✅ | — | nothing | **Complete** (rev 4) | +| `PrincipalWithConditions` around any principal (for example `AccountPrincipal.WithConditions(...)` or `new PrincipalWithConditions(role, ...)`) | any | — | — | — | **Synthesis error** (rev 4), before any policy is written | +| Imported role, any unresolved account | Automatic | — | — | — | **Synthesis error** with remedies | +| Imported role, any unresolved account | ExternallyManaged | ❌ | ✅ | caller identity policy (in its account) | Partial by contract, annotated | +| `Role.FromRoleArn`, different literal account | Automatic | — | — | — | **Synthesis error** | +| `Role.FromRoleArn`, different literal account | ExternallyManaged | ❌ | ✅ | caller-account identity policy | Partial by contract, annotated | +| Service principal (bare or with conditions) | Automatic or ExternallyManaged | — | — | — | **Synthesis error** (rev 4). `cloudfront.amazonaws.com` → use `GrantCloudFrontInvoke`; other services → explicit, condition-scoped `AddToResourcePolicy` statement | +| `AccountPrincipal`/`AccountRootPrincipal`/`ArnPrincipal`, **including the same account** | Automatic | — | — | — | **Synthesis error** (rev 4: a same-account account-root resource statement authorizes no caller by itself) | +| `AccountPrincipal`/`ArnPrincipal` | ExternallyManaged | ❌ | ✅ | that account's identity policies | Partial by contract, annotated | +| Any wildcard principal through `GrantInvoke`, conditioned or not (`AnyPrincipal`, `StarPrincipal`, `OrganizationPrincipal`, `"*"`) | any | — | — | — | **Synthesis error** (rev 4). Conditioned wildcards use an explicit `AddToResourcePolicy` statement; unconditioned wildcard Allow statements are rejected everywhere | +| Any grantee, imported endpoint whose account is not established (token ARN, no literal `Account`) | Automatic | — | — | — | **Synthesis error** (rev 4); the endpoint stays usable as an origin with `ExternallyManaged` origin permissions | +| `Role.WithoutPolicyUpdates()` of an owned role (same account) | Automatic | ❌ (not an owned mutable identity) | ✅ | nothing | **Complete**; imported endpoint → **throws** (rev 4) | +| Any grantee, owned endpoint | ExternallyManaged | ❌ | ✅ | caller identity policy | Partial by contract (useful to keep identity policies in the caller's stack/app) | + +#### Revision 4 corrections (independent implementation review of T1–T3b) + +These rules supersede revision 3 where they conflict. Everything else in this section stands. + +1. **Service principals are not granted through `GrantInvoke`.** Revision 3 treated a service-principal grant as complete. + An unconditioned service-principal statement is a confused-deputy grant: for `cloudfront.amazonaws.com` it lets *any* + distribution in *any* account with an OAC origin for this endpoint invoke it. The library cannot establish which + condition keys (`aws:SourceArn`, `aws:SourceAccount`) a given service supplies for this action, so it neither adds + `aws:SourceAccount` automatically nor accepts arbitrary consumer conditions as proof of scoping. `GrantInvoke` + therefore throws `InvalidOperationException` for any principal whose policy fragment is a `Service` principal, under + either `CallerPolicy`: + - `cloudfront.amazonaws.com` (detected by resolving the service name, which CDK renders as a token): "use + `GrantCloudFrontInvoke(distributionArn)`". + - other services: "service-principal invocation is not supported by `GrantInvoke`; add an explicit statement with + `endpoint.AddToResourcePolicy(...)` that includes the scoping conditions the service documents". + + A typed, condition-scoped service grant is **deferred** (additive later, if a second AWS service is documented to + invoke Web Function endpoints). +2. **Wildcard principals.** + - `GrantInvoke` rejects every wildcard principal (`AWS: "*"` or `"*"`), conditioned or not, under either + `CallerPolicy`. A wildcard is never an automatically complete grant. + - `AddToResourcePolicy`, the single entry point for resource-policy statements, rejects Allow statements that have a + wildcard principal and no conditions, and Allow statements that use `NotPrincipal`. + - An explicit, conditioned wildcard Allow statement added through `AddToResourcePolicy` (for example with + `aws:PrincipalOrgID`) is supported. The consumer is responsible for ensuring its conditions meaningfully restrict + access. The library checks only that conditions are present; it does not include, and will not add, an + IAM-condition analyzer. +3. **Account principals.** `AccountPrincipal` and `AccountRootPrincipal` (by type), and any principal whose literal AWS + principal is an account root ARN, are never "established". A matching account does not make the grant complete, + because a same-account resource statement naming the account root delegates to IAM and authorizes no caller by itself. +4. **Verified identity writes (applies to owned and imported principals).** The returned `Grant` is never trusted as + evidence that a policy was written: CDK's `ImmutableRole` (from `Role.FromRoleArn(..., Mutable = false)`, a + cross-account literal ARN, or `Role.WithoutPolicyUpdates()`) reports `StatementAdded = true` and writes nothing. + Return values cannot be used uniformly either: in CDK 2.274.0 an owned `Role` returns an *empty* `DependencyGroup` + (filled later), and an `ImmutableRole` also returns an empty `DependencyGroup`. ~~The identity side counts as written + only when one of two positive signals holds: (a) … or (b) `AddToPrincipalPolicy` returned `StatementAdded == true` + and a `PolicyDependable` that is an `Amazon.CDK.AWS.IAM.Policy`.~~ *(Maintainer clarification, 2026-10-23: signal + (b) is withdrawn. It required calling `AddToPrincipalPolicy` as a speculative probe, which mutates IAM before the + grant is decided and can leave an unconditional identity Allow behind on a path that is later rejected, for + example a `PrincipalWithConditions` around an owned role. Through jsii, mutable and immutable imported roles both + arrive as `IRole`/`IPrincipal` proxies, so without probing they cannot be told apart.)* + + The identity side is written only when the grant principal is classified, **before any IAM mutation**, as a + concrete, owned, mutable CDK identity: a .NET `Amazon.CDK.AWS.IAM.Role`, `User`, `Group`, or `LazyRole` instance + with `Resource.IsOwnedResource == true` (an `ImmutableRole`, including `WithoutPolicyUpdates()`, and every imported + role, user, or group is never materialized as one of these types). The library never calls `AddToPrincipalPolicy` + to discover a capability. + + Clarified contract (maintainer-approved, 2026-10-23): + 1. Owned mutable principals (above) may receive identity policies. + 2. An established same-account imported role on an **owned** endpoint uses the endpoint's resource policy, + regardless of its `Mutable` setting. No `AWS::IAM::Policy` is attached to an imported role. + 3. An **imported** endpoint uses an identity-side grant only where an effective write can be established without + speculative mutation, which means only an owned mutable principal whose account is literally `SAME` as the + endpoint's. + 4. If neither side can be safely configured (for example an imported role, or a `WithoutPolicyUpdates()` view, on an + imported endpoint), `GrantInvoke` throws rather than report a complete grant. + 5. The cross-account and unresolved caller-ownership restrictions above are unchanged. + 6. `ExternallyManaged` semantics are unchanged: the resource-policy statement only, never an identity policy, and + an annotation for IAM identities. + 7. The sandbox gate must show that a same-account caller authorized only by the resource-policy statement can + invoke (§19.1 item 3.3). + + A false negative is therefore always safe (a resource-policy fallback or an error), never a silent no-op. The + classification is pinned by real-CDK regression tests, so a CDK upgrade that changes jsii type materialization + fails CI. + + **Principal wrappers.** `GrantInvoke` rejects a `PrincipalWithConditions` around any principal (including + `AccountPrincipal.WithConditions(...)`) under either `CallerPolicy`, before any policy is written. The library cannot + verify exactly what authorization a conditioned wrapper produces on each side. Consumers grant the underlying + principal directly, or add an explicit statement with `AddToResourcePolicy`. Any other principal that is not an + owned mutable identity and whose account is not established (for example a `CompositePrincipal`) fails closed + under `Automatic`. + + **Reliance on observed CDK/jsii behavior.** The owned-mutable-identity classification, and the classification of + service, wildcard, account, and wrapper principals, depend partly on behavior observed in `Amazon.CDK.Lib` 2.274.0: + - CDK's private principal classes (for example `ImmutableRole` and the imported role) not being exported types; + - jsii .NET type materialization (exported classes such as `Role` and `PrincipalWithConditions` arrive as concrete + types, including when jsii returns them from `WithConditions(...)`; private classes such as `ImmutableRole` and + the imported role arrive as interface proxies); + - the shape of `PolicyFragment`, for example service names rendered as tokens. + + This is not a CDK contract. Therefore: + - every `Amazon.CDK.Lib` upgrade must pass the focused real-CDK regression tests for these behaviors (§15), and a + failure blocks the upgrade until the signals are re-verified; + - whenever successful authorization cannot be established, the library fails closed. It falls back to the + resource-policy statement on an owned endpoint, and throws otherwise. It never reports an unverified write as + complete, and it never mutates a principal's policy to find out. +5. **Imported endpoints** use the stricter account rule (no grants when the endpoint account is not established), + the optional `Account` attribute, and the validation in [§8.4](#84-endpoints). +6. **Diagnostics.** Errors and annotations identify the grantee by the construct path of the `IGrantable` when it is a + construct (jsii proxies for imported roles implement `IConstruct`). Otherwise they use the principal's rendered + policy fragment with tokens resolved, or its type name only as a last resort. The endpoint is identified by its + construct path and `EndpointName`, never by an unresolved ARN token. Human-facing text never contains + `${Token[...]}`. The `ExternallyManaged` annotation describes the caller-side identity policy only for IAM + identities. + +The library therefore never synthesizes an identity policy that could fail at deployment because the role is in +another account. It also never silently produces a half-configured grant: anything short of complete requires the +consumer to state `ExternallyManaged`. + +### 10.3 Resource-policy ownership + +- `WebFunctionConstruct` holds a private `PolicyDocument? _resourcePolicy`. The first contribution creates + `CfnResourcePolicy("ResourcePolicy", ResourceArn = Function.AttrFunctionArn, PolicyDocument = _resourcePolicy)`. + Later contributions call `_resourcePolicy.AddStatements(...)`. `PolicyDocument` resolves at synthesis, so statements + added later (including during `Distribution` binding) are included and none overwrite earlier ones + (spike-verified). +- Identical statements are deduplicated by `PolicyDocument` resolution (the spike added the same distribution grant + twice and synthesized one statement). +- The only public entry points are on the endpoint: `AddToResourcePolicy` (whose `Resource` must be exactly that + endpoint's ARN), `GrantInvoke`, `GrantCloudFrontInvoke`, and OAC binding. `WebFunctionConstruct` has no public + `AddToResourcePolicy`, so every statement is endpoint-scoped by construction. +- **Statement integrity (revision 4).** `AddToResourcePolicy` validates the caller's statement, then stores + `statement.Copy()` frozen with `Freeze()`, so mutating the caller's object afterwards cannot widen the stored + statement. +- **Eager transactional validation (revision 4, approved implementation change).** Node-level synthesis validation + (`Node.AddValidation`) is not used: a C# implementation of `Constructs.IValidation` cannot be marshalled through + jsii in CDK 2.274.0. Instead every contribution is validated when it is added, as one transaction: + 1. Statement-level checks (`WebFunctionValidation.ValidateResourcePolicyStatement`): Deny statements are + unrestricted; an Allow statement must not use `NotPrincipal`; an Allow statement naming a wildcard or service + principal must carry conditions. + 2. The statement is copied (`Copy()`) and frozen (`Freeze()`). + 3. A candidate `PolicyDocument` is built from every previously accepted statement plus the new copy, and + `candidate.ValidateForResourcePolicy()` is called. Any error (for example a statement without a principal) + throws `InvalidOperationException` naming the Web Function. + 4. Only after validation succeeds is the copy recorded and added to the real `_resourcePolicy`, and the single + `CfnResourcePolicy` created on first use. A rejected statement therefore leaves no partial state: no stored + statement and no `ResourcePolicy` resource. + + The full resulting policy is validated on each add, single-resource-policy ownership is unchanged, and statement + de-duplication still happens at `PolicyDocument` resolution. `Grant.AddStatementToResourcePolicy` calls + `AddToResourcePolicy` a second time with the same statement; the identical copies are de-duplicated (pinned by a + test). Because validation is eager, a statement whose content is still unresolved at add time is validated in the + form it has when added. +- Contract (documented): no other `AWS::Lambda::ResourcePolicy` or `AWS::Lambda::Permission` may target the + function. An out-of-band `aws lambda-web put-resource-policy` is overwritten on the next deployment that changes + the policy (drift). No detection machinery is added. + +--- + +## 11. CloudFront OAC integration design + +### 11.1 `Bind` behavior (`WithOriginAccessControl`) + +Implemented as an internal `sealed class WebFunctionOacOrigin : DeputyBase, IOrigin`. Validation is limited to facts +the library knows with certainty (its own inputs and construct ownership). It does not inspect distribution +behaviors or maintain AWS data lists. + +1. **Auth check (at factory call).** The endpoint must be `IamAuth`, or throw ("OAC cannot restrict an + ApplicationManaged endpoint; it stays publicly reachable. Use IamAuth, or WebFunctionOrigin.WithoutOriginAccessControl + to state that the endpoint is public."). +2. **Signing.** `HomeRegion`/`PerRegion` → `Signing.SIGV4_ALWAYS_AMZ_AUTH`; `MultiRegion` → `new + Signing(SigningProtocol.SIGV4A, SigningBehavior.ALWAYS_AMZ_AUTH)`. Use `Signing.SIGV4A_ALWAYS_AMZ_AUTH` once + released. +3. **OAC.** When none is supplied, create one `FunctionUrlOriginAccessControl` with child ID `WebFunctionOac` in the + bind `scope` (the distribution's origin scope), as CDK does for `FunctionUrlOrigin`. The same origin object reused on + several behaviors of one distribution binds **once** (spike-verified), so there is one OAC per distribution. A + supplied `IOriginAccessControl` is used unchanged and not inspected (inspecting it would depend on CDK internals). + Its correct configuration is a documented consumer responsibility. +4. **Permissions.** `Automatic`: + - The endpoint is imported → throw ("cannot manage the resource policy of an imported endpoint; use + Permissions = ExternallyManaged and grant the distribution in the owner's policy"). + - `Stack.Of(scope) != Stack.Of(endpoint)` → throw ("the distribution and the Web Function must be in the same + stack for automatic permissions; otherwise CloudFormation has a dependency cycle (the distribution reads the + endpoint domain, the policy reads the distribution id). Use ExternallyManaged and + endpoint.GrantCloudFrontInvoke()"). + - Otherwise `endpoint.GrantCloudFrontInvoke(Stack.Of(scope).FormatArn({ Service = "cloudfront", Region = "", + Resource = "distribution", ResourceName = options.DistributionId }))`. + + `ExternallyManaged`: add nothing and add an info annotation naming the distribution that must be allowed. +5. **Return** `new HttpOrigin(endpoint.DomainName, { …WebFunctionOriginProps, ProtocolPolicy = HTTPS_ONLY, + OriginAccessControlId = oac.OriginAccessControlId }).Bind(scope, options)`. + +`WithoutOriginAccessControl` requires `ApplicationManaged` (an `IamAuth` endpoint without OAC answers 403 to every +request) and returns an HTTPS `HttpOrigin`. + +**Removed in revision 2.** The opt-in Region list (stale data, and the AWS failure is a clear 403) and deep +`Distribution` inspection for `AllViewer`/Lambda@Edge (token resolution of `DistributionConfig` couples the library +to CDK internals). Both become documentation ([§11.3](#113-cache-and-header-guidance-documented-not-enforced)). The +optional T4a spike may test whether a **narrow** check (exact match of the managed `AllViewer` policy ID on +behaviors whose `Origin` object is this origin) can be done through public CDK APIs. It ships only if it needs no +template-resolution machinery, emits a warning (not an error), and has no false positives. Otherwise the check is +dropped. The design does not depend on it. + +### 11.2 Spike results + +The spike was disposable code under the session scratchpad, not committed (CDK 2.273.0 and 2.274.0, .NET 10, Node 26). + +| Question | Result | +|---|---| +| Can a .NET class implement jsii `IOrigin` (via `DeputyBase`) and override `Bind`? | **Yes.** `Bind` is invoked once per distribution with `scope = {dist}/Origin1`. | +| Is `OriginBindOptions.DistributionId` available? | **Yes** (a token → `Ref` of the distribution). `Stack.FormatArn` produced `arn:${AWS::Partition}:cloudfront::{account}:distribution/${Ref}`. | +| Can `Bind` add resource-policy statements to a policy created earlier? | **Yes.** One `AWS::Lambda::ResourcePolicy`; two distributions → two statements; a repeated explicit grant was deduplicated. | +| Same origin object on two behaviors of one distribution? | Bound **once**; one origin entry. | +| Same stack: dependency cycle? | **No.** Policy → endpoint ARN + distribution `Ref`; distribution → endpoint `DomainName`. | +| Distribution in another stack? | **`DependencyCycle: 'fn' depends on 'dist' … (dist -> fn/web/Endpoint.DomainName) would create a cyclic reference`** → confirms §11.1 step 6 fail-fast. | +| L2 OAC for Web Functions on 2.274? | `FunctionUrlOriginAccessControl` + `Signing` → `lambda`/`always-amz-auth`/`sigv4` or `sigv4a`. | + +### 11.3 Cache and header guidance (documented, not enforced) + +- Dynamic or personalized routes: `CACHING_DISABLED` + `ALL_VIEWER_EXCEPT_HOST_HEADER`. Never `AllViewer`. +- Apps that read the viewer `Authorization` header on GET/HEAD must add it to a **cache policy** (CloudFront drops it + otherwise). Prefer cookies or custom headers, as Sharedale does. +- Host-dependent apps (multi-tenant hosts, Better Auth origins) must recover the viewer host through a CloudFront + Function that copies it to a custom header (Sharedale's `ViewerRequestFunctionCode` pattern) and trust it only + after an origin-verification check. +- Content-hashed static assets (`/_next/static/*`, Blazor `/_framework/*` fingerprinted files, `/_content/*`): + `CACHING_OPTIMIZED`. + +--- + +## 12. Deployment and resource dependency considerations + +### 12.1 Ordering + +`Bucket policy (Automatic) → Revision`, `Function → Revision → each Endpoint`, `Endpoint → Distribution (origin +domain)`, `Endpoint + Distribution → ResourcePolicy`, `Role/LogGroup → Revision`. The S3 object (and the externally +managed bucket policy) **must exist before the stack deploys**. The construct cannot verify that at synthesis. + +Revision 4: `Role → Revision` means the role's `CfnRole` only, never the role's `DefaultPolicy` ([§8.3](#83-webfunctionconstruct) +notes). Permissions granted to the execution role through its default policy are therefore not ordered before the +revision, which avoids cycles when functions reference each other. + +### 12.2 Updates, replacement, rollback + +| Change | Effect | Guidance | +|---|---|---| +| Code key/version, env vars, timeout, role, logging, description | New revision (Replacement). Endpoints move to it (no interruption). The old revision is deleted in cleanup. | Normal deploy (~1–2 min in Sharedale). | +| Failed deploy | CloudFormation rolls back endpoint weights to the previous revision, which still exists until cleanup. | — | +| Roll back after success | No re-selection of old revisions. Redeploy the earlier artifact (a new revision). | Matches Sharedale's runbook. | +| `AuthType` change | No interruption. | `ApplicationManaged → IamAuth` with a new OAC causes transient 403s until the distribution deploys (ADR-0011). | +| `MaxEnvironments`, `RateLimit`, `Description` | No interruption. | CloudFormation treats an omitted config as "keep" and `{}` as "clear", so removing a value may need an explicit `{}` (open question 4). | +| `EndpointName`, `EndpointType`, `Regions` | **Replacement** with a fixed name → CloudFormation fails ("already exists"), and the domain changes. | Documented. To change, add a new endpoint with a new name, move consumers, then remove the old one. | +| `FunctionName` | **Replacement** of everything. Fails while the old name exists; endpoint domains change. | Documented as a breaking infrastructure change. | +| Distribution replacement | New ID → policy statement updated in the same deployment (no interruption). The new distribution may 403 until the policy update and propagation finish. | Documented. | +| Policy statement churn | `PolicyDocument` update, no interruption. | — | + +### 12.3 Cross-stack + +- The Web Function and its caller in different stacks: `GrantInvoke` adds an identity policy in the caller's stack + referencing the endpoint ARN (caller → function). OK. +- The Distribution in a different stack: automatic OAC permissions fail fast ([§11.1](#111-bind-behavior-withoriginaccesscontrol)). + Use `ExternallyManaged` + `GrantCloudFrontInvoke(literal ARN)`, which needs a two-phase rollout, or keep them in one + stack (recommended, like Sharedale). +- An owned code bucket in a different stack: `Automatic` adds the statement to the bucket's stack (bucket stack → + literal names only). OK when the function's stack `Env` is resolved. + +### 12.4 Compatibility guarantees and future upstream L2 adoption + +The library makes two separate guarantees. + +**(1) C# public API stability (semver).** Within a major version, public type names, members, signatures, defaults, +and documented behavior do not change incompatibly. Upstream L2 types never appear in the public API, so adopting an +upstream L2 cannot break consumer code. + +**(2) Deployment compatibility.** Upgrading the package within a major version, with unchanged consumer code and +props, must not produce a CloudFormation change set that replaces, removes, or materially changes a deployed +resource, unless the change is a documented fix in `CHANGELOG.md`. Logical-ID preservation is **necessary but not +sufficient**. Compatibility means equivalence of: + +- logical IDs and resource types; +- **all** resource properties, not only replacement-triggering ones, because any change to a + `WebFunctionRevision` property creates a new revision and shifts traffic; +- the literal `FunctionName` form on the revision and endpoints (name, not `Ref`/ARN, since endpoint `FunctionName` + is replacement-triggering); +- `DependsOn` edges and implicit reference dependencies (function → revision → endpoints; bucket policy → + revision; endpoint and distribution → resource policy), which govern create, update, and rollback order; +- `DeletionPolicy`/`UpdateReplacePolicy` (e.g. log group `DESTROY`); +- the content of IAM identity statements, the resource policy, and the code-bucket statement (permission changes are + behavior changes); +- outputs and exports (none in v1). + +Consequences of breaking (2): + +| Resource | Replacement consequence | +|---|---| +| WebFunction (named) | **Deployment fails** (name conflict) or outage | +| Endpoint (named) | **Deployment fails**; domain changes; CloudFront origin breaks | +| ExecutionRole | New role ARN; revision replaced | +| LogGroup (named) | **Deployment fails** (name conflict) | +| ResourcePolicy | Window without CloudFront or cross-account permission (403) | +| Revision | New revision and traffic shift. Expected for consumer changes, not acceptable as a side effect of a package upgrade | + +**Enforcement.** A golden-template test synthesizes representative stacks (single IamAuth function; two endpoints +with OAC on two distributions; cross-account grant; `ExternallyManaged` code and permissions; `Use(logGroup)`) and +compares the **complete** templates, normalized only for asset hashes and CDK metadata, against checked-in files. Any +diff fails CI, and an intentional diff requires updating the golden file and a CHANGELOG entry in the same PR. + +**Upstream L2 adoption** is optional and never required of consumers. It is permitted only if the golden templates +are unchanged, which in practice means: nest the L2 under the existing construct, `OverrideLogicalId` every L1 it +creates, keep passing the literal function name, disable any upstream-created role, log group, or code bucket that +duplicates ours, keep resource-policy ownership in this construct, and reproduce the dependency edges. If equivalence +cannot be reached, the library does not adopt the L2 in that major version. An eventual adoption that changes +deployments is a **major** version with a documented migration (for example, `OverrideLogicalId` guidance or a +planned recreate). + +### 12.5 Upgrade/rollback of the package itself + +Additive. Existing constructs are untouched (their golden templates are asserted). Downgrading the package after +adopting the new constructs removes the types, so consumer code would not compile. Deployed infrastructure is +unaffected until the consumer changes it. + +--- + +## 13. Backward compatibility and migration + +- **Semver:** minor release (2.6.0 if released next). New public types only, so guarantee (1) holds trivially for + existing APIs. The CDK floor rises to 2.274.0, a dependency-minimum bump called out in `CHANGELOG.md`. + Consumers on < 2.274 get a NuGet resolution upgrade. +- **Existing constructs:** zero code changes. Guarantee (2) is enforced by golden templates of all four constructs + (default and representative configurations), added in the CDK-bump PR before any new code, and kept as regression + tests. +- **Sharedale:** not migrated (issue #98 constraint). For the record, a future Sharedale migration would change + construct paths and therefore logical IDs of named resources (function, endpoint, log group), and would change the + log group default. It would need `OverrideLogicalId` and `WebFunctionLogs.Use(...)`, or a planned recreate. + Its bucket policy maps to `ExternallyManaged`. + +--- + +## 14. Validation and error handling + +Errors are thrown at construction or bind time (synthesis) with `ArgumentException`/`ArgumentOutOfRangeException`/ +`InvalidOperationException`, following repository style. Literal values are validated; tokens are skipped +(`Token.IsUnresolved`), never rejected. Scope rule: validate the library's **own inputs and ownership facts**. Do not +validate AWS facts that change over time (Region lists, per-Region quotas) or the contents of constructs the library +does not own (distribution behaviors, supplied OACs, imported buckets). + +| Rule | Where | Failure | +|---|---|---| +| `FunctionName` 1–64, `^[A-Za-z0-9](?:[A-Za-z0-9_-]*[A-Za-z0-9])?$` | ctor | `ArgumentException` | +| `EndpointName` 1–64, `[A-Za-z0-9_-]`; unique per function | ctor/AddEndpoint | `ArgumentException` / duplicate `InvalidOperationException` | +| `Timeout` 3–900 s, whole seconds | ctor | `ArgumentOutOfRangeException` | +| `MaxConcurrencyPerEnvironment` 1–128 | ctor | `ArgumentOutOfRangeException` | +| `MaxEnvironments` 2–10000 | endpoint | `ArgumentOutOfRangeException` | +| `RateLimit` ∈ {0} ∪ {100..1000 step 100} ∪ {2000..10000 step 1000} (documented grid; Regional variance left to AWS) | endpoint | `ArgumentOutOfRangeException` | +| `Regions`: empty for HomeRegion (or only the home Region); ≥ 1 non-home Region for Multi/PerRegion; ≤ 50; no duplicates | endpoint | `ArgumentException` | +| Env var keys `^[A-Za-z][A-Za-z0-9_]*$`; `EntryPoint` and `AWS_LAMBDA_NODEJS_ENTRYPOINT` not both set; `AWS_LAMBDA_HTTP_ENDPOINT` reserved | ctor | `ArgumentException` | +| `EntryPoint` relative, no leading `/`, no `..` | ctor | `ArgumentException` | +| Code: key non-empty; `Automatic` when `AddToResourcePolicy` reports `StatementAdded = false` (imported bucket) | Code.Bind | `InvalidOperationException` | +| Code: owned `Bucket` (L2 created in this app) without versioning, or with `KMS_MANAGED`/`DSSE_MANAGED` | Code.Bind | `InvalidOperationException` (owned buckets only; imported buckets are not inspected) | +| Code: owned bucket in another stack while the function stack's account or Region is unresolved | Code.Bind | `InvalidOperationException` | +| `GrantInvoke` / `GrantCloudFrontInvoke` on `ApplicationManaged` | endpoint | `InvalidOperationException` | +| `GrantCloudFrontInvoke`, or a grant needing the resource policy, on an imported endpoint | endpoint | `InvalidOperationException` | +| `Automatic` grant not fully configurable (imported principal with unresolved account, different literal account, account/ARN principals) | endpoint | `InvalidOperationException` naming grantee, endpoint, reason, and remedies (§10.2 step 4) | +| `ExternallyManaged` grant on an imported endpoint | endpoint | `InvalidOperationException` | +| `AddToResourcePolicy` whose `Resource` is not exactly this endpoint's ARN | endpoint | `ArgumentException` | +| OAC origin for `ApplicationManaged`; non-OAC origin for `IamAuth` | origin factory | `InvalidOperationException` | +| Automatic OAC permissions with an imported endpoint or a cross-stack distribution | Bind | `InvalidOperationException` | +| Props builder `Build()` without code or endpoint | Testing | `InvalidOperationException` | +| *Revision 4:* `GrantInvoke` with a service principal (bare or conditioned; CloudFront gets a dedicated remedy) | endpoint | `InvalidOperationException` | +| *Revision 4:* Allow statement with an unconditioned wildcard or service principal, or with `NotPrincipal` (`AddToResourcePolicy`, therefore also `ExternallyManaged` grants) | endpoint | `ArgumentException` | +| *Revision 4:* `Automatic` grant to `AccountPrincipal`/`AccountRootPrincipal`, including the same account | endpoint | `InvalidOperationException` | +| *Revision 4:* grantee is not an owned mutable identity (for example any imported role, or `WithoutPolicyUpdates()`) on an imported endpoint (§10.2 rev-4 item 4) | endpoint | `InvalidOperationException` | +| *Revision 4:* `GrantInvoke` with a `PrincipalWithConditions` around any principal, under either `CallerPolicy` | endpoint | `InvalidOperationException` | +| *Revision 4:* literal imported `EndpointArn` not a Web Function endpoint ARN; literal empty `DomainName`; literal `Account` not 12 digits or different from a literal ARN's account | `FromEndpointAttributes` | `ArgumentException` | +| *Revision 4:* `GrantInvoke` on an imported endpoint whose account is not established (token ARN, no literal `Account`) | endpoint | `InvalidOperationException` | +| *Revision 4:* `GrantInvoke` with any wildcard principal, conditioned or not | endpoint | `InvalidOperationException` | +| *Revision 4:* `AddEndpoint` id is reserved (`Function`, `Revision`, `DefaultEndpoint`, `ExecutionRole`, `LogGroup`, `ResourcePolicy`) | `AddEndpoint` | `ArgumentException` | +| *Revision 4:* resource-policy statement invalid for a resource policy (`ValidateForResourcePolicy` on the candidate document) | `AddToResourcePolicy` (eager, transactional; §10.3) | `InvalidOperationException` | + +Revision 4 clarification of the owned-bucket rule (implementation follow-up, not T3c). Owned-bucket inspection checks +only literal values in the L2-rendered properties. It treats unresolved values conservatively: a token or unrecognized +value (for example a token versioning `Status`, a token encryption algorithm, or a token key ID) can be shown neither +compliant nor non-compliant, so it is skipped and never rejected. `DSSE_MANAGED` +(DSSE without a customer key) is rejected; DSSE with a customer-managed key is allowed, like SSE-KMS with one. Messages +name the actual problem. Versioning enabled only through an escape-hatch property override is not detected; that is a +documented limitation, and the workaround is to reference such a bucket by name (`Bucket.FromBucketName`) with +`ExternallyManaged`. + +Documented, not validated: forwarding the viewer `Host` (`AllViewer`) → 404; Lambda@Edge origin triggers → rejected by +CloudFront; OAC with opt-in Regions on global endpoints → 403; a supplied OAC's configuration; imported buckets' +versioning, encryption, and policy; S3 object existence. + +--- + +## 15. Testing strategy + +All tests go in `test/LayeredCraft.Cdk.Constructs.Tests/`, `[Collection("CDK Tests")]`, xUnit v3, AwesomeAssertions, +`Template.FromStack`, and AutoFixture `WebFunctionConstructAutoData` with customization classes following the +existing TestKit. The 80% coverage gate applies. + +**Synthesis/template** + +- Function, revision, and default endpoint exist with literal `FunctionName` on all three; `DependsOn` chain; runtime + `nodejs24.x`; `S3Object` with/without `VersionId`; env vars incl. `AWS_LAMBDA_NODEJS_ENTRYPOINT`; timeout, + concurrency, logging levels; **no** `KmsKeyArn`. +- Defaults: created role with `AWSLambdaBasicExecutionRole`. `WebFunctionLogs.Create()` → `/aws/lambda/web/{name}`, + 14 days, `Delete`. `Create(ONE_MONTH)` → 30. `ServiceDefault()` → no log group and no `LoggingConfig.LogGroup`. + `Use(group)` → that name, no group created, `GrantWrite` only outside `/aws/lambda/*`. A supplied role is used and + none is created. +- Endpoint: name, type, `Regions`, `AuthType` per endpoint, scaling/throttle present/absent, revision weight 100 to + the current revision on **every** endpoint. +- Multiple endpoints with different auth types; duplicate names (including a second `"default"`) rejected. + +**IAM (one test per row of the §10.2 table)** + +- E1 owned role, Function, or WebFunctionConstruct grantee → identity statement on the specific endpoint ARN only + (not `endpoint/*`, not other endpoints); **no** `AWS::Lambda::ResourcePolicy`. Also covers an env-agnostic stack + with the caller and the endpoint in the **same** stack. *(Revision 4 clarification:)* different stacks with matching + literal accounts write the identity statement in the caller's stack; different stacks with an unresolved account + (including two env-agnostic stacks) or different literal accounts throw and write no policy. +- ~~E2 `Role.FromRoleArn` with literal account equal to the literal stack account → policy attached by name; no + resource policy.~~ *(Revision 4 clarification:)* E2 `Role.FromRoleArn` with literal account equal to the literal + stack account, mutable **or** `Mutable = false` → resource statement only, **no** `AWS::IAM::Policy`; imported + endpoint throws and writes no `AWS::IAM::Policy`. +- Imported role with a token ARN, or a literal ARN in an env-agnostic stack, under `Automatic` → throws, and **no** + `AWS::IAM::Policy` is synthesized. Under `ExternallyManaged` → resource statement + annotation, no identity policy. +- Different literal account: `Automatic` throws; `ExternallyManaged` → resource statement only + annotation; the + returned `Grant` has no principal statements. +- ~~Service principal → resource only (complete).~~ *(Revision 4: service principals throw; see below.)* + `AccountPrincipal`/`ArnPrincipal`: `Automatic` throws (revision 4: including the same account); + `ExternallyManaged` → resource only. +- `ExternallyManaged` with an E1 grantee → resource statement only, no identity policy. +- `ApplicationManaged` → throws; `ExternallyManaged` on an imported endpoint → throws. +- Regression test pinning the CDK pitfall: a fake `IResourceWithPolicy` returning `StatementAdded = false` makes + `GrantInvoke` throw (it must not rely on `Grant.Success`). +- *Revision 4 additions:* + - Service principals (CloudFront remedy text; another service; a conditioned one) throw under both policies. + - `GrantInvoke` with `AnyPrincipal`, `StarPrincipal`, or a conditioned `OrganizationPrincipal` throws under both + policies. + - Through `AddToResourcePolicy`: an unconditioned wildcard Allow throws; Allow with `NotPrincipal` throws; Deny with + `"*"` is accepted; an explicit Allow with `"*"` and an `aws:PrincipalOrgID` condition writes exactly that statement. + - Same-account `AccountPrincipal`/`AccountRootPrincipal` under `Automatic` throws. + - Real-CDK no-op identity writes go to the resource side (owned endpoint) or throw (imported endpoint), with **no** + `AWS::IAM::Policy`: `Role.FromRoleArn(Mutable = false)`, `Mutable = false` with `AddGrantsToResources = true`, and + `owned.WithoutPolicyUpdates()`. + - Real identity-policy assertions (statement content and exactly one statement) for an owned `Role`, a classic + `Function`, a `WebFunctionConstruct`, and an owned `User` and `Group`. ~~a mutable imported role, and an imported + user and group~~ *(clarification: a mutable imported role uses the resource-policy fallback on an owned endpoint + and throws on an imported endpoint, in both cases with no `AWS::IAM::Policy`.)* + - Principal wrappers: `PrincipalWithConditions` around an owned role, around `AccountPrincipal` (also as returned by + `AccountPrincipal.WithConditions(...)` through jsii), and around a service or organization principal each throw, + under both `CallerPolicy` values. The synthesized template then has **no** `AWS::IAM::Policy` (no leftover + unconditional identity Allow) and **no** `AWS::Lambda::ResourcePolicy`. + - No speculative mutation: no code path calls `AddToPrincipalPolicy` outside `Grant.AddToPrincipal` for an owned + mutable identity; the rejected-wrapper tests above are the observable guard. + - Alternate account-root forms (`ArnPrincipal("arn:…:root")`, `AccountPrincipal` with a token account) throw under + `Automatic` and leave no authorization statement. + - An owned mutable `Role` granted on an imported endpoint whose account is literally `SAME` writes exactly one + identity statement on the literal endpoint ARN. + - An env-agnostic stack with a literal imported role ARN under `Automatic` throws. + - Imported endpoints: + - An invalid literal ARN, an empty domain, a non-12-digit `Account`, or an `Account` that differs from a literal + ARN's account each throw. + - `Env` is the endpoint's. + - A literal ARN with an env-agnostic owned caller throws. + - A token ARN without `Account` throws for owned and imported callers alike, and writes no `AWS::IAM::Policy`. + - A token ARN with a literal matching `Account` and an owned caller in that account writes the identity side. + - Constructing a token-ARN endpoint without `Account` succeeds; it is usable for an `ExternallyManaged` origin, + exercised in T4. + - Upgrade guard: the real-CDK principal-behavior tests (identity-write signals and principal classification) are + grouped and named so a CDK upgrade PR's failure points directly to the changed behavior. + - Error and annotation text names the grantee path or principal and the endpoint, and contains no `${Token[`. + - `ExternallyManaged` annotations are asserted. + - Cycles: mutual invocation, self-invocation, and the BFF/API cross-reference all synthesize (`Template.FromStack` + succeeds). + - Statement integrity: mutation after `AddToResourcePolicy` does not change the template; a principal-less statement + fails eager validation at `AddToResourcePolicy` and leaves no `ResourcePolicy` resource behind. + - Reserved `AddEndpoint` ids throw; `Endpoints` cannot be cast to a mutable list. + +**Resource-policy ownership** + +- No statements → no resource; many grants → exactly one; multiple distributions → all statements; different + orders → equal statement *sets*; repeated grants → no duplicates; foreign `Resource` → throws; `WebFunctionConstruct` + exposes no `AddToResourcePolicy` (a compile-time API surface test). + +**CloudFront/OAC** + +- OAC `lambda`/`always-amz-auth`/`sigv4` (HomeRegion, PerRegion) and `sigv4a` (MultiRegion); the origin uses the + endpoint `DomainName`, `https-only`, `OriginAccessControlId`; `WebFunctionOriginProps` members pass through. +- Auto statement `aws:SourceArn` = distribution ARN; same origin on two behaviors → one statement; two + distributions → two statements, each scoped; a second endpoint's origin → statement scoped to that endpoint ARN. +- Supplied OAC reused, none created; `ExternallyManaged` → no statement + annotation; explicit + `GrantCloudFrontInvoke(literal)` works with no Distribution construct. +- Negatives: `ApplicationManaged` + OAC; `IamAuth` + `WithoutOriginAccessControl`; imported + Automatic; cross-stack + + Automatic (library error message, not a CDK cycle). + +**Code bucket** + +- `Automatic` on an owned bucket → least-privilege statement (`/revision/*`, `aws:SourceAccount`) + revision + dependency; imported + `Automatic` → error; `ExternallyManaged` → no statement; unversioned or `KMS_MANAGED` owned + bucket → error; cross-stack owned bucket with unresolved function env → error. + +**Validation negatives:** each row of §14. + +**Compatibility and regression:** the golden templates of §12.4 for the new construct, and of the four existing +constructs (zero-diff acceptance). + +**Workloads (acceptance criterion):** compiled consumer-example tests reproducing §9.1–9.7, plus one synthesis test +per workload recipe (Next.js, ASP.NET Core shim, Blazor Static SSR shim). Each must use only the public API, with +differences expressed only through `Code`, `EntryPoint`, `EnvironmentVariables`, and the consumer's CloudFront +behaviors. + +**Consumer helpers:** tests for `WebFunctionConstructAssertions` (including multi-endpoint discrimination and +single-resource-policy checks) and for `WebFunctionConstructPropsBuilder` (`Build()` throws without an auth choice +or code; `WithTestArtifact` synthesizes without credentials). + +**Deployed validation:** a **release gate**, not CI; see [§19.1](#191-release-acceptance-criteria). + +--- + +## 16. Documentation strategy + +- **New `docs/constructs/web-function.md`** (added to `nav` under Constructs): overview; auth modes and security + implications (a table: who can reach the endpoint); `WebFunctionCode.FromBucket` requirements (versioning, + `s3:GetObject`/`s3:GetObjectVersion`, the `/revision/*` SourceArn statement, optional `VersionId` pinning + semantics, cross-account buckets, SSE-KMS key policy, bootstrap bucket incompatibility, the object must exist + before deploy); endpoints and `AddEndpoint`; behavior on revision change; `GrantInvoke` (same- vs cross-account, + the caller signs SigV4 with `UNSIGNED-PAYLOAD`, strip semantics); resource-policy single-owner contract; OAC + origin; cache/header guidance; replacement table; validation errors; limitations. +- **Workload recipes** (in the same page or `docs/examples/web-functions.md`): + 1. *Next.js*: `output: "standalone"`; zip root = standalone output + `.next/static` + `public`; `index.js` that sets + `HOSTNAME`/`PORT` from `AWS_LAMBDA_HTTP_ENDPOINT`, adjusts `NODE_PATH` for pnpm, handles SIGTERM, and requires + `server.js` (Sharedale `infra/web-functions/next-index.js`); `NODE_ENV=production`; OAC; `/_next/static/*` + cached, everything else uncached + `AllViewerExceptHostHeader`; host recovery via a CloudFront Function if + host-dependent; ISR/image optimization caveats (no shared cache across environments, ephemeral FS). + 2. *ASP.NET Core API*: self-contained `linux-arm64` publish (`server` apphost) + `index.js` shim + `process.execve("/var/task/server", …)` (Sharedale `infra/web-functions/dotnet-index.js`); Kestrel on + `http://{AWS_LAMBDA_HTTP_ENDPOINT}`; readiness `POST /2025-09-01/ready` to `AWS_LAMBDA_RUNTIME_API` after start + (e.g. `LayeredCraft.LambdaWebFunctions.Hosting`); app-local ICU (`Microsoft.ICU.ICU4C.Runtime`) or invariant + globalization (the runtime has no `libicu`); no `UseHttpsRedirection`/HSTS (TLS terminates at the endpoint); + `IamAuth` + `GrantInvoke` from callers; usually no CloudFront. Flagged: `execve` and the readiness path are not + documented by AWS. + 3. *Blazor Static SSR* (per `j-d-ha/lambda-web-function-not-node` `src/blazor`): same shim and readiness contract as + ASP.NET Core; untrimmed server publish (reflection-based rendering); `ContentRootPath = AppContext.BaseDirectory` + when `AWS_LAMBDA_HTTP_ENDPOINT` is set so `wwwroot`/`MapStaticAssets` resolve; zip contains `wwwroot/_framework` + (~57 MB zipped / ~136 MB unzipped measured, under the 512 MB limit); optional Interactive WebAssembly components + (plain HTTP); cache fingerprinted `/_framework/*` and `/_content/*`, uncached SSR pages, `AllViewerExceptHostHeader`. + **Blazor Interactive Server / Auto / legacy Blazor Server are unsupported**: they need a SignalR WebSocket (Web + Functions reject upgrades) and session affinity, and long polling does not help on a half-duplex, + timeout-bounded request path. +- `README.md` construct list; `docs/index.md`; `docs/testing/index.md` (new assertions/builder); + `docs/examples/index.md` (§9 examples); `CHANGELOG.md` (new types, CDK floor 2.274.0); repository `CLAUDE.md` + architecture section. +- Security guidance callouts: `ApplicationManaged` is public even behind CloudFront; `IamAuth` ≠ user auth; never + forward `Host`; Lambda@Edge origin triggers are incompatible; same-stack requirement for automatic OAC permissions. + +Documented rather than abstracted: artifact build and upload; `execve` shim; readiness; ICU; viewer-host recovery; +origin-verification secrets and their rotation (Sharedale runbook); cold starts (~3–5 s measured by Sharedale); +regional `RateLimit` variance; deployment-time 403 windows. + +--- + +## 17. Risks and limitations + +| Risk | Mitigation | +|---|---| +| Upstream L2 lands with different semantics, and consumers expect parity | Public API independent of upstream; adoption gated by full golden-template equivalence (§12.4) | +| jsii override behavior changes across CDK versions | Spike-proven on 2.273/2.274; origin tests run in CI on every CDK bump | +| CDK `Grant` semantics change | `GrantInvoke` checks `StatementAdded` itself; a regression test pins the behavior (§15) | +| Identity-write detection depends on jsii type materialization (rev 4) | One positive classification (owned mutable `Role`/`User`/`Group`/`LazyRole`) decided before any IAM mutation, so a false negative is a safe fallback or an error (§10.2 rev-4 item 4); real-CDK regression tests fail on any CDK bump that changes it | +| Same-account imported roles are authorized only by the resource-policy statement (rev 4 clarification) | Sandbox gate verifies resource-policy-only invocation for a mutable and an immutable imported role (§19.1 3.3) | +| Execution-role permissions not yet propagated when a new revision activates (rev 4, no `DefaultPolicy` dependency) | Sandbox gate observes first-deploy behavior (§19.1 3.3); documented | +| Consumers assume `GrantInvoke` configured a cross-account caller | §10.2 table, annotation, XML docs, and user docs state the caller-side requirement | +| Misconfigured CloudFront behaviors (Host forwarded, Lambda@Edge) are not caught at synthesis | Documented; the deployed smoke test exercises the documented configuration; AWS fails loudly (404 / config rejection) | +| Opt-in Region global endpoints with OAC | Documented; AWS answers 403, which fails closed | +| Imported buckets cannot be inspected | Documented; deploy-time failure surfaces as a `Failed` revision | +| `RateLimit` supported values vary by Region | Validate the documented grid only; document | +| Fixed-name replacement failures (function, endpoint, log group) | Replacement table + docs; golden templates prevent accidental drift | +| Out-of-band resource-policy edits are overwritten | Documented single-owner contract | +| Revision cleanup quota (50) under frequent deploys | AWS cleans up automatically; documented | +| AWS service still new (behavior, Regions, quotas changing) | Required sandbox deployment before every release that changes these constructs (§19.1) | +| CDK default-rule validation warnings for Web Function types | Document; re-check on 2.274+ | +| No customer-managed revision key in v1 | Documented deferral and L1 escape hatch (§8.7) | + +--- + +## 18. Open questions + +Maintainer decisions (resolved in revision 3): + +1. Default log retention: **`TWO_WEEKS`**, following `LambdaFunctionConstruct`. + `WebFunctionLogs.Create(RetentionDays.ONE_MONTH)` remains available. +2. Blazor Static SSR: **required deployed validation** in the release gate (§19.1, item 3.8), using the Node.js + `execve` shim approach. A minimal rendered SSR page and one successfully served static asset are sufficient. +3. `GrantInvoke` with unresolved accounts: **no identity policies on imported principals whose account cannot be + established**. Fail under `Automatic`, or use the explicit `ExternallyManaged` contract (§10.2). + +Implementation-phase questions (no maintainer input needed unless the result changes scope): + +4. T4a, optional: can a narrow, warning-only `AllViewer` check be done through public CDK APIs without resolving + templates? If not, drop it. +5. Does removing `MaxEnvironments`/`RateLimit` after deployment need an explicit `{}` in the template to clear the + value (CloudFormation: omit = keep)? Decide in T2, test it, and verify it in the sandbox. +6. Metric helpers on `AWS/Lambda/Web` (namespace confirmed only by Sharedale's working alarms) are a follow-up. +7. Reconcile the stale `VersionPrefix` 2.4.0 in `Directory.Build.props` with tag v2.5.0 at release time. + +--- + +## 19. Suggested implementation breakdown + +| # | Task | Depends on | Notes | +|---|---|---|---| +| T0 | Bump `Amazon.CDK.Lib` to 2.274.0; golden templates for the four existing constructs; confirm zero diff | — | Separate PR; establishes deployment-compatibility enforcement | +| T1 | Models: enums, `WebFunctionRuntime`, `WebFunctionCode.FromBucket` + options, `WebFunctionLogs`, endpoint options/attributes; validation local to the new types | T0 | Unit tests for every §14 rule on these types | +| T2 | `WebFunctionConstruct`: function, revision, default endpoint, role, logs, code-bucket policy, dependencies, child IDs; golden templates | T1 | | +| T3 | Endpoints: `WebFunctionEndpointConstruct` (`Resource`, `IResourceWithPolicy`), `AddEndpoint`, single-owner resource policy, `GrantInvoke` (§10.2 algorithm), `GrantCloudFrontInvoke`, `FromEndpointAttributes` | T2 | IAM and policy test matrix | +| T3c | *Revision 4:* corrective task for the independent T1–T3b review (service/wildcard/account principals, verified identity writes, role-dependency cycles, imported-endpoint validation and account rule, statement integrity, reserved ids, read-only `Endpoints`, diagnostics, `IWebFunctionEndpoint` namespace) | T3 | Blocks T4 | +| T4 | `WebFunctionOrigin` (OAC, automatic/explicit permissions, imported and cross-stack guards) | T3, T3c | Origin test matrix | +| T4a | *Optional*, time-boxed spike: narrow `AllViewer` warning (§11.1) | T4 | Drop if it needs template resolution | +| T5 | Testing helpers: assertions, props builder, `CdkTestHelper` entry; consumer-example and workload tests | T3, T4 | | +| T6 | Docs: `docs/constructs/web-function.md` + nav, three workload recipes, examples, testing page, README, CHANGELOG, `CLAUDE.md` | T4 (API stable) | Can run in parallel with T5 | +| T7 | **Required** sandbox deployment and smoke test (§19.1); record results in the release PR | T4, T6 recipes | Release gate; not normal CI | + +T1–T4 can ship as one feature PR, or T0 + (T1–T3) + (T4–T6). Publishing to NuGet waits for T7. + +### 19.1 Release acceptance criteria + +The feature is **not published** until all of the following hold: + +1. Validation gates pass: build, the full test suite, the coverage threshold, and golden templates (including + zero diff for existing constructs). +2. **Workload compatibility:** Next.js, ASP.NET Core (Node.js `execve` shim), and **Blazor Static SSR** (same shim + approach, per `j-d-ha/lambda-web-function-not-node`) synthesize through the same public API, with differences only + in artifacts and configuration. No workload-specific construct, behavior helper, or packaging logic exists in the + library. +3. **Sandbox deployment and smoke test** succeeds in a non-production AWS account. It is run manually or by a + dedicated workflow, never in normal CI, from a small checked-in sample app under `samples/` or `test/` (no + production code). At minimum it verifies: + 1. **Artifact deployment from the supported S3 model**: zips in a versioned bucket, once with `Automatic` bucket + policy (an owned bucket) and once with `ExternallyManaged` (a pre-provisioned bucket); revisions read the code. + 2. **Revision activation**: function, revision, and endpoints reach `Active`; a second deployment with a changed + artifact activates a new revision and moves the endpoints to it. + 3. **IAM-authorized invocation**: a request SigV4-signed by a role granted with `GrantInvoke` returns 2xx. + Revision 4 additions: + - Record first-deployment behavior while the caller's identity policy propagates (the revision no longer depends + on the role's `DefaultPolicy`; transient 403s within an IAM propagation window are acceptable but must be + recorded). + - A same-account grant written only as a resource-policy statement returns 2xx, once for a role imported with + `Mutable = false` and once for a role imported with the default (mutable) setting. In both cases the + caller role has no identity policy allowing `lambda:InvokeWebFunctionEndpoint`, so the resource policy + alone authorizes the call. **Required** (rev 4 clarification): if this fails, the imported-role contract in + §10.2 rev-4 item 4 must be revisited before release. + - An identity-only same-account grant returns 2xx. + - The deployed `ResourceArn` (the function ARN) and the code-bucket `aws:SourceArn …/revision/*` plus + `aws:SourceAccount` conditions are accepted and effective. + 4. **Unauthorized invocation is denied**: unsigned → 403; signed by a role without the grant → 403; signed for a + different endpoint of the same function → 403. + 5. **CloudFront OAC invocation**: requests through the distribution return 2xx; direct unsigned requests to the + `IamAuth` endpoint return 403. + 6. **Resource-policy behavior**: the deployed policy (`aws lambda-web get-resource-policy`) contains exactly the + expected statements; a second distribution adds a second scoped statement; removing it removes the statement + on the next deploy. + 7. **Cross-account side** (if a second sandbox account is available): with an `ExternallyManaged` grant and a + caller-account identity policy, invocation succeeds; without the identity policy, it is denied. If no second + account is available, record this as not verified. + 8. **Workloads**: a Next.js page and an ASP.NET Core endpoint serve (through CloudFront, or directly with a + signed request for the API). **Blazor Static SSR (required):** a minimal server-rendered page and one static + asset (e.g. `app.css` or a `_framework` file) are served successfully, using the Node.js `execve` shim approach + from `j-d-ha/lambda-web-function-not-node` (apphost `server` + `index.js` shim + readiness POST). The sample is + ordinary consumer code; no Blazor-specific library abstraction or packaging logic is introduced. +4. The results (date, account alias, CDK version, revision IDs, observed status codes) are recorded in the release + PR. Any criterion not verified is listed explicitly. + +**Follow-ups (independent, not part of this work):** `StaticSiteConstruct` public bucket → OAC review; +`StaticSiteConstruct` `HostedZone.FromLookup` → accept `IHostedZone`; `LambdaFunctionConstruct` `NONE`-auth Function +URL → IAM/OAC option; IPv6/AAAA support (#97); `WebFunctionCode.FromAsset`; typed revision `EncryptionKey` after +deployed validation; metric helpers; network connectors; weighted revisions; `Signing.SIGV4A_ALWAYS_AMZ_AUTH` once +released; tracking aws-cdk#39434. + +--- + +## 20. References + +**Repositories (local paths at time of writing)** + +- Sharedale: `infra/Sharedale.Infrastructure/SharedaleHostedStack.cs` (Web Functions 526–577; grants 230–252; + OAC/origin/distribution 327–379; resource policy 381–403; DNS 405–418), `SharedaleAccountBootstrapStack.cs` + (artifact bucket 113–167), `infra/web-functions/{next-index.js,dotnet-index.js,readiness-mock.js}`, + `infra/scripts/build-web-functions.sh`, `app/lib/server/api/web-function-iam.ts`, + `docs/adr/0009…`, `0010…`, `0011…`, `docs/architecture/hosted-environment.md`, + `docs/architecture/lambda-web-functions-poc.md`. +- LayeredCraft.Cdk.Constructs: `src/LayeredCraft.Cdk.Constructs/{LambdaFunctionConstruct,StaticSiteConstruct,CognitoUserPoolConstruct}.cs`, + `Models/CognitoUserPoolDomainProps.cs`, `Testing/*`, `test/LayeredCraft.Cdk.Constructs.Tests/*`, `CLAUDE.md`, + `Directory.Packages.props`, `mkdocs.yml`. +- Blazor/.NET shim reference: (`src/blazor/AGENTS.md`, + `src/blazor/BlazorApp/Program.cs`, `src/node-wrapper/index.js`, `infra/lib/web-function.ts`). +- ASP.NET Core hosting: `LayeredCraft.LambdaWebFunctions.Hosting` 0.1.0 (). + +**GitHub issues and PRs** + +- LayeredCraft/cdk-constructs#98 (this design), #97 (IPv6/AAAA), #99 (explicit hosted zone, Cognito). +- aws/aws-cdk#39210 (WebFunction + NetworkConnector L2, open), #39235 / #39234 (alpha module, open), + #39434 (Web Function origin with OAC, open), #39196 (`ALWAYS_AMZ_AUTH`, v2.274.0), #38629 (`SIGV4A`, v2.274.0), + #39216 (`Signing.SIGV4A_ALWAYS_AMZ_AUTH`, merged 2026-10-22, unreleased), #39195. + +**AWS documentation (read 2026-10-22)** + +- Lambda Web Functions: , `web-functions-runtimes.html`, + `web-functions-how-it-works.html`, `web-functions-revisions.html`, `web-functions-scaling.html`, + `web-functions-networking.html`, `web-functions-code-s3.html`, + `web-functions-endpoint-access-control.html` (same base path). +- CloudFront: . +- CloudFormation: `AWS::Lambda::WebFunction`, `WebFunctionRevision` (+ `BuildConfig`, `ServiceConfig`), + `WebFunctionEndpoint` (+ `RevisionWeight`, `ScalingConfig`, `ThrottleConfig`), `AWS::Lambda::ResourcePolicy`, under + . +- CDK source (v2.274.0): `packages/aws-cdk-lib/aws-iam/lib/grant.ts` (`addToPrincipalOrResource` 149–182, `success`/`assertSuccess` 369–379), `aws-iam/lib/role.ts` (`fromRoleArn` 347–391). +- CDK API: `Amazon.CDK.Lib` 2.273.0 / 2.274.0 XML docs (`CfnWebFunction*`, `CfnResourcePolicy`, + `FunctionUrlOriginAccessControl`, `Signing`, `SigningBehavior`, `SigningProtocol`, `OriginBindOptions`). + +Not verified in the docs pages read (treated as consumer concerns): arm64-only execution, the runtime readiness +callback `/2025-09-01/ready`, the `AWS/Lambda/Web` metric namespace, the region availability list, and the +CloudFormation `RuntimeConfig`/`CodeConfig` allowed-value pages. + +--- + +## 21. Revision history + +**Revision 2 (2026-10-22): first-review feedback.** + +1. *Public API correctness.* The builder no longer takes `Action` (incompatible with + init-only records). It follows the repository's builder convention instead (`WithEndpoint(IWebFunctionEndpointOptions)`, + `WithIamAuthEndpoint()`, `WithTestArtifact(scope)`, `Build()` throws without code or auth). Other changes: + `HttpOriginProps` pass-through replaced by explicit `WebFunctionOriginProps` members; `ILogGroup?`/`CreateLogGroup`/ + retention flags replaced by the closed `WebFunctionLogs` choice; `EndpointName` is non-nullable with default + `"default"` everywhere; public `AddToResourcePolicy` exists only on endpoints (endpoint-ARN scoped); assertions + match by names, not logical-ID prefixes; ownership semantics written out (§8.4). +2. *KMS.* Revision `EncryptionKey` deferred with rationale and an escape hatch; S3 artifact encryption distinguished + and kept (§5.2, §8.7). +3. *Cross-account grants.* CDK `Grant` source verified. `AddToPrincipalOrResource`/`AssertSuccess` dropped for an + explicit algorithm that checks `StatementAdded`. A per-grantee table states which policies the library writes and + what consumers must configure. Cross-account invocation is never reported as configured (§10.2). +4. *Upstream L2.* Guarantees split into C# API stability and deployment compatibility. Logical IDs are necessary + but not sufficient; full golden-template equivalence is required (§12.4). +5. *Log retention.* Default `TWO_WEEKS` (library convention), with rationale; 30 days is an override; the decision + is flagged (§8.3, §18). +6. *CloudFront validation.* Opt-in Region list and deep distribution inspection removed; validation scoped to the + library's own inputs and ownership; T4a optional and warning-only (§11.1, §14). +7. *Deployed validation.* A required sandbox deployment and smoke test is now a release acceptance criterion + (§19.1). +8. *Blazor Static SSR.* Kept as an explicit acceptance criterion, with no Blazor-specific code (§15, §19.1). +9. *ADRs.* None written. This document is authoritative (header). + +**Revision 3 (2026-10-22): final decisions; status Approved.** + +1. Default log retention fixed at `TWO_WEEKS` (`LambdaFunctionConstruct` convention); 30 days via + `WebFunctionLogs.Create(RetentionDays.ONE_MONTH)`. +2. Blazor Static SSR deployed smoke test confirmed as a required release criterion: a minimal SSR page and a static + asset, using the Node.js shim approach. No Blazor-specific abstractions. +3. `GrantInvoke` ambiguity resolved. Identity policies are written only to principals whose account is established + (owned principals, or imported principals with literal accounts matching the endpoint's). Anything not fully + configurable fails under `Automatic` or requires the new explicit `WebFunctionInvokeGrantOptions { CallerPolicy = + ExternallyManaged }` contract. That contract writes only the resource-policy statement. No synthesized identity + policy can fail at deployment because its role lives in another account (§10.2, §14, §15). + +**Revision 4 (2026-10-23): independent implementation review of T1–T3b; status remains Approved.** Implemented by the +corrective task T3c, which blocks T4. + +1. *Service principals.* `GrantInvoke` rejects all service principals. Revision 3's "service principal → complete" row + allowed an unconditioned, confused-deputy grant (for example any CloudFront distribution in any account). CloudFront + is directed to `GrantCloudFrontInvoke`. Other services use an explicit, condition-scoped `AddToResourcePolicy` + statement. A typed scoped-service grant is deferred (§10.2 rev-4 item 1). +2. *Wildcards.* `GrantInvoke` rejects all wildcard principals. Unconditioned wildcard Allow statements and + `NotPrincipal` Allow statements are rejected everywhere. Explicit conditioned wildcard statements through + `AddToResourcePolicy` are supported, and the consumer owns the adequacy of their conditions; there is no condition + analyzer (§8.4, §10.2). +3. *Account principals.* Same-account `AccountPrincipal`/`AccountRootPrincipal` no longer count as complete (§10.2). +4. *Identity writes.* ~~Verified by two positive signals for owned and imported principals alike~~ Written only to an + owned, mutable CDK identity classified by type before any IAM mutation, because CDK's return values cannot + distinguish real from no-op writes (owned `Role` and `ImmutableRole` both return an empty `DependencyGroup`) and + probing with `AddToPrincipalPolicy` mutates IAM. Same-account imported roles, mutable or not, use the resource + policy on owned endpoints and throw on imported endpoints. `PrincipalWithConditions` is rejected. The checks rely + partly on CDK/jsii behavior observed in 2.274.0. Focused real-CDK regression tests gate every CDK upgrade, and the + library fails closed when authorization cannot be established (§10.2 rev-4 item 4). +5. *Role dependency.* The revision depends on the `CfnRole` only, not the role's `DefaultPolicy`; this removes the + mutual-invocation, self-invocation, and BFF/API cycles. IAM propagation is moved to the sandbox gate (§8.3, §12.1, + §19.1). This intentionally changes golden templates whose role has a default policy (for example + `web-function-use-log-group.json`); the diff is reviewed and explained in T3c, not silently regenerated. +6. *Imported endpoints.* Literal ARN, domain, and account validation; an optional `Account` attribute (which must + match a literal ARN); the endpoint's own environment; the strict `SAME`-account rule; and no `GrantInvoke` at all + when the endpoint account is not established. Such endpoints remain usable as CloudFront origins with + `ExternallyManaged` origin permissions (§8.4). +7. *Resource policy integrity.* Frozen copies of validated statements; eager transactional `ValidateForResourcePolicy` + on a candidate document before the real policy is mutated (§10.3). +8. *API surface.* Reserved `AddEndpoint` ids; a genuinely read-only `Endpoints`; `IWebFunctionEndpoint` moved to the + root namespace and documented as not for consumer implementation (§8, §8.3). +9. *Diagnostics.* Meaningful grantee and endpoint names, no raw tokens, accurate annotations (§10.2 rev-4 item 6). +10. *Clarified, not T3c.* Owned-bucket inspection treats token or unrecognized values conservatively (skipped, never + rejected); DSSE with a customer key is allowed (implementation follow-up). Versioning enabled only through an + escape hatch stays a documented limitation. Log-group switching and F3006/`validateAgainstDefaultRules` guidance go + to the documentation tasks. + +Maintainer clarifications (2026-10-23) were folded into revision 4 in place: items 2, 4, and 6 above, plus +`WebFunctionEndpointAttributes.Account`. A second clarification (2026-10-23, after the T3c corrective review) +withdrew the `AddToPrincipalPolicy` probe signal, moved same-account imported roles to the resource-policy side +regardless of `Mutable`, rejected `PrincipalWithConditions`, and made resource-policy-only invocation a required +sandbox check (§10.2 rev-4 item 4, §15, §19.1 3.3). A third clarification (2026-10-23, T3c acceptance) restated E1: +same-stack ownership with an owned endpoint is sufficient even in an env-agnostic stack, and cross-stack grants need +matching literal accounts (§10.2 E1). diff --git a/docs/examples/index.md b/docs/examples/index.md index 4ed3633..657de3e 100644 --- a/docs/examples/index.md +++ b/docs/examples/index.md @@ -590,4 +590,191 @@ public class Program } ``` +## Web Function Examples + +These examples use the [Web Function Construct](../constructs/web-function.md). They assume a stack with an explicit +`Env` and the usings `Amazon.CDK`, `Amazon.CDK.AWS.CloudFront`, `Amazon.CDK.AWS.CloudFront.Origins`, +`Amazon.CDK.AWS.CertificateManager`, `Amazon.CDK.AWS.Route53`, `Amazon.CDK.AWS.Route53.Targets`, `Amazon.CDK.AWS.S3`, +`Amazon.CDK.AWS.DynamoDB`, `LayeredCraft.Cdk.Constructs`, and `LayeredCraft.Cdk.Constructs.Models`. + +### ASP.NET Core API (Node.js `execve` shim) + +```csharp +// Artifacts are published by CI to a versioned bucket owned by another stack (its policy grants +// lambda.amazonaws.com read on web-function/acme-*/revision/*). +var artifacts = Bucket.FromBucketName(this, "artifacts", $"acme-artifacts-{Account}"); + +var api = new WebFunctionConstruct(this, "api", new WebFunctionConstructProps +{ + FunctionName = "acme-prod-api", + Code = WebFunctionCode.FromBucket(artifacts, $"{artifactTag}/api.zip", new WebFunctionCodeFromBucketOptions + { + BucketPolicy = WebFunctionCodeBucketPolicy.ExternallyManaged, + }), + // index.js at the zip root is the execve shim; no EntryPoint needed. + EnvironmentVariables = new Dictionary + { + ["ASPNETCORE_ENVIRONMENT"] = "Production", + ["Acme__TableName"] = table.TableName, + }, + MaxConcurrencyPerEnvironment = 16, + Endpoint = new WebFunctionEndpointOptions + { + AuthType = WebFunctionAuthType.IamAuth, // only granted callers reach Kestrel + MaxEnvironments = 10, + RateLimit = 100, + }, +}); +table.GrantReadWriteData(api); // WebFunctionConstruct is IGrantable +``` + +### Next.js application + +```csharp +var web = new WebFunctionConstruct(this, "web", new WebFunctionConstructProps +{ + FunctionName = "acme-prod-web", + Code = WebFunctionCode.FromBucket(codeBucket, $"{artifactTag}/web.zip", new WebFunctionCodeFromBucketOptions + { + ObjectVersion = webZipVersionId, // optional: pin an exact object version + }), // codeBucket is owned in this stack, so the construct + // manages the bucket policy (Automatic); the artifact must + // already be uploaded when the stack deploys + // The zip's index.js sets HOSTNAME/PORT from AWS_LAMBDA_HTTP_ENDPOINT, then require("./server.js"). + EnvironmentVariables = new Dictionary + { + ["NODE_ENV"] = "production", + ["NEXT_TELEMETRY_DISABLED"] = "1", + ["ACME_API_URL"] = api.DefaultEndpoint.Url, // consumer-owned wiring + }, + Endpoint = new WebFunctionEndpointOptions { AuthType = WebFunctionAuthType.IamAuth }, +}); +``` + +### Next.js granted permission to invoke the API + +```csharp +// Identity policy on web's execution role: lambda:InvokeWebFunctionEndpoint on api's "default" endpoint ARN only. +// Same account → no resource-policy statement and no AWS::Lambda::ResourcePolicy on api. +api.DefaultEndpoint.GrantInvoke(web); + +// The BFF signs requests itself (SigV4, service "lambda", region of the API endpoint, +// x-amz-content-sha256: UNSIGNED-PAYLOAD). The construct does not inject signing configuration. +``` + +Cross-account variant. It must be explicit, because `Automatic` fails at synthesis for a role in another account: + +```csharp +var partner = Role.FromRoleArn(this, "partner", "arn:aws:iam::222233334444:role/caller"); +api.DefaultEndpoint.GrantInvoke(partner, new WebFunctionInvokeGrantOptions +{ + CallerPolicy = WebFunctionCallerPolicy.ExternallyManaged, +}); +// Writes only api's resource-policy statement (principal = that role ARN, resource = the endpoint ARN) and adds an +// info annotation. Invocation works only after account 222233334444 attaches an identity policy allowing +// lambda:InvokeWebFunctionEndpoint on this endpoint ARN to its role. +``` + +### CloudFront distribution with an IAM-protected Web Function origin (OAC) + +```csharp +var origin = WebFunctionOrigin.WithOriginAccessControl(web.DefaultEndpoint, new WebFunctionOriginWithOacProps +{ + CustomHeaders = new Dictionary { ["x-origin-verify"] = secret }, +}); + +var distribution = new Distribution(this, "distribution", new DistributionProps +{ + DefaultBehavior = new BehaviorOptions + { + Origin = origin, + ViewerProtocolPolicy = ViewerProtocolPolicy.REDIRECT_TO_HTTPS, + AllowedMethods = AllowedMethods.ALLOW_ALL, + CachePolicy = CachePolicy.CACHING_DISABLED, // personalized SSR + OriginRequestPolicy = OriginRequestPolicy.ALL_VIEWER_EXCEPT_HOST_HEADER, // never forward Host + }, + AdditionalBehaviors = new Dictionary + { + ["/_next/static/*"] = new BehaviorOptions { Origin = origin, CachePolicy = CachePolicy.CACHING_OPTIMIZED }, + }, + DomainNames = ["app.example.com"], + Certificate = certificate, +}); +// Bind created one FunctionUrlOriginAccessControl (lambda/always-amz-auth/sigv4) and added to web's resource policy: +// cloudfront.amazonaws.com → lambda:InvokeWebFunctionEndpoint on web's default endpoint, +// StringEquals aws:SourceArn = arn:aws:cloudfront::{account}:distribution/{distribution id} +``` + +### Custom domain and Route 53 + +There is no library DNS construct to integrate with; composition is plain CDK, matching `CognitoUserPoolConstruct`'s +injected `ICertificate`/`IHostedZone`, and the same certificate can be shared with a Cognito custom domain: + +```csharp +var zone = HostedZone.FromHostedZoneAttributes(this, "zone", new HostedZoneAttributes { HostedZoneId = zoneId, ZoneName = "example.com" }); +var certificate = new Certificate(this, "cert", new CertificateProps // CloudFront certificates live in us-east-1 +{ + DomainName = "*.example.com", + Validation = CertificateValidation.FromDns(zone), +}); +// ... distribution with DomainNames = ["app.example.com"], Certificate = certificate ... +var target = RecordTarget.FromAlias(new CloudFrontTarget(distribution)); +_ = new ARecord(this, "app-a", new ARecordProps { Zone = zone, RecordName = "app", Target = target }); +_ = new AaaaRecord(this, "app-aaaa", new AaaaRecordProps { Zone = zone, RecordName = "app", Target = target }); + +var auth = new CognitoUserPoolConstruct(this, "users", new CognitoUserPoolConstructProps +{ + UserPoolName = "acme", + Domain = new CognitoUserPoolDomainProps { DomainName = "example.com", AuthSubDomain = "auth", Certificate = certificate, HostedZone = zone }, +}); +``` + +### Web Functions without CloudFront or without inter-function IAM + +```csharp +// (a) Public API, no CloudFront: the application authenticates every request. +var publicApi = new WebFunctionConstruct(this, "public-api", new WebFunctionConstructProps +{ + FunctionName = "acme-public-api", + Code = WebFunctionCode.FromBucket(codeBucket, "public-api.zip"), + Endpoint = new WebFunctionEndpointOptions { AuthType = WebFunctionAuthType.ApplicationManaged }, +}); +// publicApi.DefaultEndpoint.Url → https://….lambda-web.us-east-1.on.aws + +// (b) IAM-only internal service invoked by a classic Lambda (no CloudFront): +var worker = new WebFunctionConstruct(this, "internal", new WebFunctionConstructProps +{ + FunctionName = "acme-internal", + Code = WebFunctionCode.FromBucket(codeBucket, "internal.zip"), + Endpoint = new WebFunctionEndpointOptions { AuthType = WebFunctionAuthType.IamAuth }, +}); +worker.DefaultEndpoint.GrantInvoke(existingLambdaConstruct.LambdaFunction); + +// (c) Two endpoints on one function: public for webhooks, IamAuth for CloudFront. +var hooks = web.AddEndpoint("webhooks", new WebFunctionEndpointOptions +{ + EndpointName = "webhooks", + AuthType = WebFunctionAuthType.ApplicationManaged, + RateLimit = 100, +}); +``` + +### Imported endpoint as a CloudFront origin (externally managed permissions) + +```csharp +var shared = WebFunctionEndpointConstruct.FromEndpointAttributes(this, "shared", new WebFunctionEndpointAttributes +{ + EndpointArn = "arn:aws:lambda:us-east-1:111122223333:web-function/shared/endpoint/default", + DomainName = "abc123.lambda-web.us-east-1.on.aws", + AuthType = WebFunctionAuthType.IamAuth, +}); +var origin = WebFunctionOrigin.WithOriginAccessControl(shared, new WebFunctionOriginWithOacProps +{ + Permissions = WebFunctionOriginPermissions.ExternallyManaged, // Automatic would fail synthesis +}); +// The owner of "shared" must allow this distribution (aws:SourceArn) in the function's resource policy. +// With a token EndpointArn (e.g. from SSM), this origin use still works. Identity grants +// (shared.GrantInvoke(...)) additionally need a literal Account on the attributes. +``` + For more examples, see the test files in the [repository](https://github.com/LayeredCraft/cdk-constructs/tree/main/test) which demonstrate comprehensive usage patterns. diff --git a/docs/examples/web-functions.md b/docs/examples/web-functions.md new file mode 100644 index 0000000..6fd348d --- /dev/null +++ b/docs/examples/web-functions.md @@ -0,0 +1,213 @@ +--- +layout: default +title: Web Function Workloads +permalink: /examples/web-functions/ +--- + +# Web Function Workloads + +This page documents the three workloads that deploy through the same [Web Function Construct](../constructs/web-function.md) public API: **Next.js**, **ASP.NET Core** (via a Node.js `execve` shim), and **Blazor Static SSR**. The construct is workload-neutral; only the artifact and configuration differ. + +!!! warning "What these recipes do and do not prove" + These recipes describe how each workload is packaged and wired, and the synthesis tests in the repository prove + that each configuration compiles and synthesizes through the public API. They do **not** prove runtime behavior. + Actual invocation, shim execution, readiness, and CloudFront end-to-end flows are validated only by a real + deployment in a sandbox account (see [Sandbox validation](#sandbox-validation)). + + Every recipe also assumes the code artifact is uploaded to a versioned S3 bucket **before** the stack deploys. The + construct never builds, zips, or uploads code, and an owned bucket created in the same stack does not contain the + artifact at first deployment (see [S3 Artifact Requirements](../constructs/web-function.md)). + +The ASP.NET Core and Blazor recipes rely on a Node.js `execve` shim and a runtime readiness callback that are **not +documented by AWS**; they follow the `lambda-web-function-not-node` reference +([j-d-ha/lambda-web-function-not-node](https://github.com/j-d-ha/lambda-web-function-not-node)). + +## Required namespaces + +The snippets below are fragments of a stack; they assume the following usings: + +```csharp +using System.Collections.Generic; +using Amazon.CDK; +using Amazon.CDK.AWS.CertificateManager; +using Amazon.CDK.AWS.CloudFront; +using Amazon.CDK.AWS.IAM; +using Amazon.CDK.AWS.S3; +using LayeredCraft.Cdk.Constructs; +using LayeredCraft.Cdk.Constructs.Models; +``` + +## Next.js + +Next.js deploys as a **standalone** build. + +### Artifact preparation + +1. Build with `output: "standalone"` in `next.config.js`. +2. Assemble the zip with the standalone output at the root, plus `.next/static` and `public/`: + - `server.js` (the standalone server), + - `.next/static/**`, + - `public/**`, + - an `index.js` at the zip root (see below). + +### The `index.js` shim and environment mapping + +Lambda Web Functions run the zip's `index.js` by default. The shim: + +- reads `AWS_LAMBDA_HTTP_ENDPOINT` and sets `HOSTNAME` and `PORT` so Next.js binds the endpoint the runtime expects, +- adjusts `NODE_PATH` (needed for pnpm layouts), +- handles `SIGTERM` for graceful shutdown, +- then `require("./server.js")`. + +Because the shim is `index.js`, no `EntryPoint` is needed; set `EntryPoint` only if you rename the entry file. + +### Wiring + +```csharp +var web = new WebFunctionConstruct(this, "web", new WebFunctionConstructProps +{ + FunctionName = "acme-web", + Code = WebFunctionCode.FromBucket(codeBucket, $"{artifactTag}/web.zip", new WebFunctionCodeFromBucketOptions + { + ObjectVersion = webZipVersionId, + }), + EnvironmentVariables = new Dictionary + { + ["NODE_ENV"] = "production", + ["NEXT_TELEMETRY_DISABLED"] = "1", + ["ACME_API_URL"] = api.DefaultEndpoint.Url, + }, + Endpoint = new WebFunctionEndpointOptions { AuthType = WebFunctionAuthType.IamAuth }, +}); +``` + +### CloudFront and static assets + +Front the endpoint with a CloudFront OAC origin. Cache the content-hashed assets and leave personalized SSR uncached: + +```csharp +var origin = WebFunctionOrigin.WithOriginAccessControl(web.DefaultEndpoint); + +var distribution = new Distribution(this, "distribution", new DistributionProps +{ + DefaultBehavior = new BehaviorOptions + { + Origin = origin, + ViewerProtocolPolicy = ViewerProtocolPolicy.REDIRECT_TO_HTTPS, + CachePolicy = CachePolicy.CACHING_DISABLED, + OriginRequestPolicy = OriginRequestPolicy.ALL_VIEWER_EXCEPT_HOST_HEADER, + }, + AdditionalBehaviors = new Dictionary + { + ["/_next/static/*"] = new BehaviorOptions { Origin = origin, CachePolicy = CachePolicy.CACHING_OPTIMIZED }, + }, + DomainNames = ["app.example.com"], + Certificate = certificate, +}); +``` + +**Caveats.** Each execution environment has its own ephemeral filesystem and cache, so ISR and Next.js image optimization do not share state across environments. Host-dependent rendering must recover the viewer host through a CloudFront Function that copies it into a custom header (see the [caching and header guidance](../constructs/web-function.md#caching-and-header-guidance)). + +## ASP.NET Core + +ASP.NET Core runs as a self-contained server binary (`server`) launched by a Node.js `execve` shim. + +### Hosting approach and the shim + +- Publish the app **self-contained for `linux-arm64`** (the target this recipe is tested against; confirm the architecture your deployment uses); the published apphost is `server`. +- Put an `index.js` shim at the zip root that calls + `process.execve("/var/task/server", ["/var/task/server"], process.env)` so the .NET process replaces the Node.js process. +- Because the shim is `index.js`, no `EntryPoint` override is needed. + +### Application startup and HTTP endpoint + +- Configure Kestrel to listen on `http://{AWS_LAMBDA_HTTP_ENDPOINT}` (the runtime-provided endpoint). The runtime + requires the server to begin listening on that endpoint within **10 seconds** of startup. +- After startup, POST to the runtime readiness API at `http://{AWS_LAMBDA_RUNTIME_API}/2025-09-01/ready`. +- Do **not** call `UseHttpsRedirection()` or add HSTS: TLS terminates at the endpoint. +- The runtime image has **no `libicu`**; either enable globalization-invariant mode or ship an app-local ICU (`Microsoft.ICU.ICU4C.Runtime`). + +### Artifact packaging and CloudFront + +Publish, zip, and upload like the other workloads. An internal API usually needs **no CloudFront**; callers reach it +directly with `IamAuth` and `GrantInvoke`: + +```csharp +var api = new WebFunctionConstruct(this, "api", new WebFunctionConstructProps +{ + FunctionName = "acme-api", + Code = WebFunctionCode.FromBucket(artifacts, $"{artifactTag}/api.zip", new WebFunctionCodeFromBucketOptions + { + BucketPolicy = WebFunctionCodeBucketPolicy.ExternallyManaged, + }), + EnvironmentVariables = new Dictionary + { + ["ASPNETCORE_ENVIRONMENT"] = "Production", + ["Acme__TableName"] = table.TableName, + }, + MaxConcurrencyPerEnvironment = 16, + Endpoint = new WebFunctionEndpointOptions + { + AuthType = WebFunctionAuthType.IamAuth, + MaxEnvironments = 10, + RateLimit = 100, + }, +}); +table.GrantReadWriteData(api); + +// Same-account caller: the Next.js front end ("web", from the Next.js recipe) invokes the API. +// An identity policy on the caller's role is all that is required. +api.DefaultEndpoint.GrantInvoke(web); +``` + +## Blazor Static SSR + +Blazor **Static SSR** uses the same hosting approach and Node.js `execve` shim as ASP.NET Core, and the same runtime +readiness contract. + +- Publish an **untrimmed** server build (Blazor Static SSR renders via reflection, so trimming is unsafe). +- When `AWS_LAMBDA_HTTP_ENDPOINT` is set, set the content root to `AppContext.BaseDirectory` so `wwwroot` and `MapStaticAssets` resolve. +- The zip carries `wwwroot/_framework` (roughly 57 MB zipped, about 136 MB unzipped — under the 512 MB unzipped limit). +- Optional Interactive **WebAssembly** components work over plain HTTP. + +Static assets are fingerprinted, so cache them; keep SSR pages uncached: + +```csharp +var origin = WebFunctionOrigin.WithOriginAccessControl(web.DefaultEndpoint); + +var distribution = new Distribution(this, "distribution", new DistributionProps +{ + DefaultBehavior = new BehaviorOptions + { + Origin = origin, + ViewerProtocolPolicy = ViewerProtocolPolicy.REDIRECT_TO_HTTPS, + CachePolicy = CachePolicy.CACHING_DISABLED, + OriginRequestPolicy = OriginRequestPolicy.ALL_VIEWER_EXCEPT_HOST_HEADER, + }, + AdditionalBehaviors = new Dictionary + { + ["/_framework/*"] = new BehaviorOptions { Origin = origin, CachePolicy = CachePolicy.CACHING_OPTIMIZED }, + ["/_content/*"] = new BehaviorOptions { Origin = origin, CachePolicy = CachePolicy.CACHING_OPTIMIZED }, + }, + DomainNames = ["app.example.com"], + Certificate = certificate, +}); +``` + +!!! danger "Blazor Interactive Server is unsupported" + Blazor **Interactive Server** (and `Auto`, and legacy Blazor Server) require a SignalR WebSocket with session + affinity. Web Functions reject protocol upgrades, and long polling does not solve the affinity requirement. Use + Static SSR (optionally with Interactive WebAssembly) instead. + +## Sandbox validation + +The repository's synthesis tests prove that all three workloads compile and synthesize through the same public API +with no workload-specific construct, helper, or packaging logic in the library. The following still require a real +AWS deployment to a sandbox account and are **not** claimed as passing here: + +- the `execve` shim replacing the Node.js process with the .NET `server`, +- the runtime readiness POST to `http://{AWS_LAMBDA_RUNTIME_API}/2025-09-01/ready`, +- a first request served by each workload, +- CloudFront OAC end-to-end invocation (including the transient `403` window while the distribution deploys). + +For more examples, see the [Examples](index.md) page. diff --git a/docs/index.md b/docs/index.md index 93a4fc6..aee9cd7 100644 --- a/docs/index.md +++ b/docs/index.md @@ -12,6 +12,7 @@ A comprehensive library of reusable AWS CDK constructs for .NET projects, design ## Key Features - **🚀 Lambda Functions**: Comprehensive Lambda construct with configurable OpenTelemetry support, IAM management, and environment configuration +- **🕸️ Web Functions**: AWS Lambda Web Functions served from an S3 artifact, with IAM or application-managed endpoints, endpoint-scoped grants, and CloudFront OAC origin integration - **🌐 Static Sites**: Complete static website hosting with S3, CloudFront, SSL certificates, and Route53 DNS management - **📊 DynamoDB Tables**: Full-featured DynamoDB construct with streams, TTL, and global secondary indexes - **🧪 Testing Helpers**: Extensive testing utilities with fluent assertions and builders @@ -71,6 +72,16 @@ Full-featured Lambda functions with: - SnapStart support - Versioning and aliases +### [Web Function Construct](constructs/web-function.md) + +AWS Lambda Web Functions with: + +- S3-backed artifacts (`WebFunctionCode.FromBucket`) +- IAM or application-managed endpoints +- Endpoint-scoped invocation grants +- CloudFront OAC origin integration +- A single resource policy per function + ### [Static Site Construct](constructs/static-site.md) Complete static website hosting with: @@ -104,11 +115,12 @@ Full-featured Cognito User Pool with: - **[Testing Guide](testing/index.md)** - Comprehensive testing utilities and patterns - **[Examples](examples/index.md)** - Real-world usage examples and patterns +- **[Web Function Workloads](examples/web-functions.md)** - Next.js, ASP.NET Core, and Blazor Static SSR recipes ## Requirements - **.NET 8.0** or **.NET 9.0** -- **AWS CDK v2** (Amazon.CDK.Lib 2.203.1+) +- **AWS CDK v2** (Amazon.CDK.Lib 2.274.0+) - **AWS CLI** configured with appropriate permissions - **Node.js** (for CDK deployment) diff --git a/docs/testing/index.md b/docs/testing/index.md index f7887d4..248781a 100644 --- a/docs/testing/index.md +++ b/docs/testing/index.md @@ -276,6 +276,85 @@ template.ShouldExportUserPoolArn("test-stack", "auth-pool"); template.ShouldExportAppClientId("test-stack", "auth-pool", "web-app"); ``` +## Web Function Testing + +The Web Function helpers follow the same convention as the other constructs: a fluent props builder and assertion extension methods on `Template`. Assertions match resources by **function and endpoint names**, not by logical ID, so they keep working as IDs change and can distinguish multiple endpoints on one function. + +The lowest-friction setup uses an imported, externally managed artifact bucket, so a test synthesizes without AWS credentials and without an `AWS::S3::Bucket` resource. + +### Props Builder + +```csharp +var (_, stack) = CdkTestHelper.CreateTestStack("test-stack"); + +var props = CdkTestHelper.CreateWebFunctionPropsBuilder() + .WithFunctionName("my-web") // default: "test-web-function" + .WithTestArtifact(stack) // imported bucket, no bucket resource; key defaults to "artifacts/app.zip" + .WithIamAuthEndpoint() // or WithApplicationManagedEndpoint() + .WithEnvironmentVariable("NODE_ENV", "production") + .WithEntryPoint("server.js") + .WithTimeout(Duration.Seconds(60)) + .Build(); + +var web = new WebFunctionConstruct(stack, "web", props); +``` + +`Build()` throws an `InvalidOperationException` when code or an endpoint was never chosen: the builder never selects an authentication mode for you. Use `WithCode(WebFunctionCode.FromBucket(...))` for a real bucket and `WithEndpoint(...)` for a fully customized `WebFunctionEndpointOptions` record. + +### Assertion Methods + +```csharp +var template = Template.FromStack(stack); + +// Function, revision and code +template.ShouldHaveWebFunction("my-web"); +template.ShouldHaveRevision("my-web"); // runtime defaults to "nodejs24.x" +template.ShouldHaveRevisionCode("my-artifacts", "artifacts/app.zip"); // optional versionId + +// Endpoints +template.ShouldHaveEndpoint("my-web", "default", WebFunctionAuthType.IamAuth); +template.ShouldHaveEndpointScaling("default", maxEnvironments: 5, rateLimit: 100); // null asserts the block is absent + +// IAM and resource policy +template.ShouldHaveInvokeGrant("my-web", "default"); // identity-policy statement +template.ShouldHaveSingleResourcePolicy("my-web"); +template.ShouldAllowCloudFront("my-web", "default"); +template.ShouldAllowResourcePolicyPrincipal("my-web", "default", "arn:aws:iam::222233334444:role/partner"); +template.ShouldHaveNoResourcePolicy(); + +// CloudFront OAC and the code-bucket statement +template.ShouldHaveWebFunctionOac(); // signing protocol defaults to "sigv4" +template.ShouldHaveCodeBucketReadStatement("my-web"); +``` + +The assertions require `Effect = Allow`, the expected action (`lambda:InvokeWebFunctionEndpoint`), and the exact endpoint resource, so a `Deny` statement or an unrelated action never satisfies them. `ShouldHaveInvokeGrant` also matches a minimized policy whose `Resource` is an array of endpoint ARNs. + +### AutoData Support + +```csharp +[Theory] +[WebFunctionConstructAutoData] +public void Should_Synthesize_Generated_Props(WebFunctionConstructProps props) +{ + var (_, stack) = CdkTestHelper.CreateTestStack(); + + _ = new WebFunctionConstruct(stack, "web", props); + + Template.FromStack(stack).ShouldHaveWebFunction("test-web-function"); +} +``` + +`[WebFunctionConstructAutoData]` supplies deterministic props whose default code artifact is an imported, externally managed bucket, so the fixture synthesizes without credentials or a bucket resource. + +### Golden-Template Conventions + +Representative Web Function configurations are pinned as full synthesized templates under `test/LayeredCraft.Cdk.Constructs.Tests/GoldenTemplates/` (`web-function-default.json`, `web-function-cloudfront-oac.json`, and so on), alongside the golden templates for the four existing constructs. `GoldenTemplate.AssertMatches(stack, "web-function-default.json")` compares the complete, normalized template and fails with a readable diff. Regenerate intentionally with `UPDATE_GOLDEN_TEMPLATES=1`; the harness rewrites the checked-in file and then fails once so the change is reviewed. Existing-construct goldens must show **zero diff** on any dependency or CDK bump. + +### CDK/jsii Compatibility Considerations + +- **Origin exceptions.** Validation that runs inside CDK's `IOrigin.Bind` path (and inside `HttpOrigin` construction) surfaces in .NET as a `System.Exception` carrying CDK's message, while factory-time checks in `WebFunctionOrigin` throw `InvalidOperationException`. Assert with the matching exception type, and prefer validating origin props at factory time. +- **Principal materialization.** Identity-policy writes and principal classification depend partly on how jsii materializes types in `Amazon.CDK.Lib`: exported classes such as `Role`, `User`, `Group`, `LazyRole` and `PrincipalWithConditions` arrive as concrete .NET types, while CDK's private classes (`ImmutableRole`, the imported role) arrive as interface proxies. The real-CDK `CdkUpgradeGuard_*` tests in `WebFunctionSecurityTests.cs` pin this behavior; they must pass before any `Amazon.CDK.Lib` upgrade is accepted. + ## AutoFixture Integration ### Custom Attributes @@ -302,6 +381,7 @@ public void Should_Create_Lambda_With_Custom_Settings(LambdaFunctionConstructPro - `StaticSiteConstructAutoDataAttribute`: Generates static site props - `DynamoDbTableConstructAutoDataAttribute`: Generates DynamoDB props - `CognitoUserPoolConstructAutoDataAttribute`: Generates Cognito user pool props (pass `includeBranding: true` to include Managed Login branding) +- `WebFunctionConstructAutoDataAttribute`: Generates Web Function props (imported, externally managed artifact bucket; IAM-auth endpoint) ## Testing Patterns @@ -421,3 +501,5 @@ For complete testing examples, see the test files in the repository: - `StaticSiteConstructTests.cs` - `DynamoDbTableConstructTests.cs` - `CognitoUserPoolConstructTests.cs` +- `WebFunctionConstructTests.cs`, `WebFunctionSecurityTests.cs`, `WebFunctionInvokeGrantTests.cs`, `WebFunctionOriginTests.cs` +- `WebFunctionConstructTestingHelpersTests.cs`, `WebFunctionConstructGoldenTemplateTests.cs` diff --git a/mkdocs.yml b/mkdocs.yml index 9420536..8cd6117 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -110,8 +110,11 @@ nav: - Static Site: constructs/static-site.md - DynamoDB Table: constructs/dynamodb-table.md - Cognito User Pool: constructs/cognito-user-pool.md + - Web Function: constructs/web-function.md - Testing: testing/index.md - - Examples: examples/index.md + - Examples: + - Overview: examples/index.md + - Web Function Workloads: examples/web-functions.md # Social links extra: diff --git a/samples/web-functions/.gitignore b/samples/web-functions/.gitignore new file mode 100644 index 0000000..051e58b --- /dev/null +++ b/samples/web-functions/.gitignore @@ -0,0 +1,9 @@ +# Artifact build output (zips, staging trees) — never committed. +build/ + +# Next.js build output. +apps/nextjs/.next/ +apps/nextjs/out/ + +# Node dependency trees. +apps/nextjs/node_modules/ diff --git a/samples/web-functions/Directory.Build.props b/samples/web-functions/Directory.Build.props new file mode 100644 index 0000000..207164c --- /dev/null +++ b/samples/web-functions/Directory.Build.props @@ -0,0 +1,21 @@ + + + + + + false + enable + enable + latest + true + + + diff --git a/samples/web-functions/Directory.Packages.props b/samples/web-functions/Directory.Packages.props new file mode 100644 index 0000000..d96a1db --- /dev/null +++ b/samples/web-functions/Directory.Packages.props @@ -0,0 +1,13 @@ + + + + + + false + + + diff --git a/samples/web-functions/README.md b/samples/web-functions/README.md new file mode 100644 index 0000000..c67689a --- /dev/null +++ b/samples/web-functions/README.md @@ -0,0 +1,157 @@ +# Web Function workload samples + +Deployment-ready sample workloads for the [`WebFunctionConstruct`](../../src/LayeredCraft.Cdk.Constructs/WebFunctionConstruct.cs) +(`AWS::Lambda::WebFunction`). Each app produces an S3 artifact that matches the approved +runtime contract in [`docs/designs/lambda-web-functions-integration.md`](../../docs/designs/lambda-web-functions-integration.md) +(revision 4, section 16). + +These samples are **not** part of the library solution (`LayeredCraft.Cdk.Constructs.slnx`) +and are never built or packed by CI. They exist to prove that real Next.js, ASP.NET Core, +and Blazor Static SSR workloads package into the runtime's expected layout and run under +the Node.js `execve` shim. + +## Layout + +``` +samples/web-functions/ + apps/nextjs/ Next.js standalone app (Node.js runtime, no shim) + apps/aspnetcore/ ASP.NET Core minimal API (execve shim + self-contained apphost) + apps/blazor/ Blazor Web App, Static SSR only (execve shim + self-contained apphost) + tools/mock-runtime-api.mjs Local stand-in for the Lambda runtime API (/2025-09-01/ready) + tools/test-tooling.sh Regression tests for build-artifacts.sh path/cleanup handling + build-artifacts.sh Builds deployment ZIPs into build/ + smoke-artifacts.sh Local HTTP smoke tests against the built ZIPs +``` + +## Prerequisites + +- Node.js 24+ (samples built with v26) and npm 11+ +- .NET SDK 10.0 (pinned via `samples/web-functions/global.json`; `rollForward=latestFeature`) +- Docker (required for the local smoke tests; the artifacts build without it) +- `zip`/`unzip` + +Building the artifacts requires **no AWS credentials and makes no AWS calls**. + +## Build artifacts + +```bash +cd samples/web-functions +./build-artifacts.sh # all three workloads + v2 variants +./build-artifacts.sh --clean # remove generated artifacts first (repeatable builds) +./build-artifacts.sh --only blazor # one workload +./build-artifacts.sh --build-id abc123 # override the baked build id +./build-artifacts.sh --out /tmp/out # custom output directory (relative paths allowed) +``` + +By default the build id is `git rev-parse --short=12 HEAD`. Outputs land in +`samples/web-functions/build/`: + +| Artifact | Workload | +| --- | --- | +| `nextjs.zip` | Next.js standalone | +| `aspnetcore.zip` | ASP.NET Core | +| `blazor.zip` | Blazor Static SSR | +| `nextjs-v2.zip`, `aspnetcore-v2.zip`, `blazor-v2.zip` | Same apps with a `-v2` build id, for exercising revision updates | + +`--clean` only removes content the script generates (`*.zip`, `stage/`, `.smoke/`) inside the +output directory; it never deletes the output directory itself or unrelated files in it, so +`--out` may safely point at an existing directory (including the sample root). + +Artifacts are built for **`linux/arm64`**, the only architecture Web Functions support. The +Next.js build installs its optional native dependencies for that platform +(`npm ci --os=linux --cpu=arm64 --libc=glibc`) so the bundle carries `sharp-linux-arm64` +binaries rather than the build host's. The artifact therefore targets the Lambda +`linux/arm64` runtime and is **not** host-independent. + +Builds are **repeatable but not byte-for-byte reproducible**: ZIP records file modification +times and stores entries in directory order, and the Next.js build stamps its own generated +identifiers. Two runs from the same source produce functionally equivalent but not +byte-identical archives. + +## Artifact layout + +All ZIPs are rooted at `/var/task` (no top-level wrapper directory). + +**Next.js** (Node.js is the runtime, so there is no shim): + +``` +index.js entry point (shim: sets HOSTNAME/PORT from AWS_LAMBDA_HTTP_ENDPOINT, SIGTERM handling, requires ./server.js) +server.js Next.js standalone server +.next/ server + static output (.next/static included) +public/ static assets (e.g. sample.txt) +node_modules/ standalone server dependencies (linux-arm64 native modules) +package.json +build-id.txt build id consumed by the SSR page +``` + +The sample does not use the Next.js image optimizer; `images.unoptimized` is set so the +revision never invokes the sharp/libvips image pipeline. (The traced `sharp` packages are +still shipped, pinned to `linux-arm64`, so the layout stays a faithful standalone bundle.) + +**ASP.NET Core / Blazor** (single file `index.js` is the execve shim): + +``` +index.js process.execve("/var/task/server", ["/var/task/server"], process.env) +server self-contained apphost (executable bit preserved: -rwxr-xr-x) +server.dll managed entry assembly +server.deps.json, server.runtimeconfig.json, *.dll, *.so self-contained runtime assets +wwwroot/ (Blazor only) app.css + _framework/blazor.web.js +build-id.txt +``` + +Both .NET apps bind Kestrel to `http://$AWS_LAMBDA_HTTP_ENDPOINT` and POST `{}` to +`http://$AWS_LAMBDA_RUNTIME_API/2025-09-01/ready` once listening (skipped when the +variable is absent), which the runtime requires to leave `Runtime.InitTimeout`. +The Blazor app sets `ContentRootPath` to `AppContext.BaseDirectory` so published +`wwwroot` assets resolve at runtime. + +## Local validation + +```bash +cd samples/web-functions +./smoke-artifacts.sh # validate all built artifacts (v1 and v2) +./smoke-artifacts.sh --only nextjs # one artifact (accepts nextjs-v2, etc.) +./smoke-artifacts.sh --artifacts /tmp/out +./tools/test-tooling.sh # build-artifacts.sh path/cleanup regression tests +``` + +Every workload is exercised through its **real entrypoint**: the extracted artifact is +mounted read-only at `/var/task` inside the AWS Lambda Node.js 24 base image +(`public.ecr.aws/lambda/nodejs:24`, `linux/arm64`) and `node /var/task/index.js` is run. For +the .NET workloads that means the Node.js `execve` shim actually replaces Node with the +self-contained apphost, so the deployed runtime contract — not a direct launch of the +executable — is what gets tested. + +Without AWS, the smoke suite verifies: + +- every `apps/*/index.js` entry point parses (`node --check`); +- static artifact checks: required entries, the `server` executable bit, and (Next.js) the + presence of `linux-arm64` native modules with no host-only modules; +- **nextjs** — the SSR heading renders, the page reflects the artifact's `build-id.txt`, the + `public/` asset is served, and a real `/_next/static/*.js` chunk returns HTTP 200; +- **aspnetcore** — `/health` reports the artifact's build id, `/status` returns a + dynamically generated response, and the readiness POST reaches the mock runtime API; +- **blazor** — the rendered page, `/app.css`, and `/_framework/blazor.web.js` are served, + and the readiness POST reaches the mock runtime API; +- the v1 and v2 archives differ by exactly the baked build id (`` vs `-v2`). + +Containers are started without `--rm` so their logs survive a failure; the smoke script +prints the container and mock-runtime logs before failing, then removes the containers on +exit. + +## Environment-specific limitations + +- Docker is required for the smoke tests. If it is unavailable the container-backed checks + are reported as **SKIPPED** (never as passed) and only the static artifact checks run. +- On Docker Desktop for macOS the build/smoke working directories live under the artifact + directory (`build/.smoke/`) rather than the OS temp directory, because Docker Desktop does + not share the macOS `TMPDIR` under `/var/folders`. +- Running `linux/arm64` images on an `x86_64` Linux host requires QEMU/binfmt emulation + (e.g. `docker run --privileged --rm tonistiigi/binfmt --install arm64`). Without it, pull + or exec of the base image fails; the smoke script does not install it automatically. +- Local smoke tests exercise the HTTP contract, the Node.js entrypoint shim, and the + readiness handshake. Actual `AWS::Lambda::WebFunction` deployment, CloudFront/OAC + behavior, image-optimizer behavior, and runtime scaling cannot be verified without AWS and + are covered by the deployed validation in T7b. +- Blazor uses Static SSR only. Interactive Server / Auto are unsupported by the runtime + (SignalR WebSocket is rejected), so no interactive render mode is configured. diff --git a/samples/web-functions/apps/aspnetcore/Acme.AspNetCore.csproj b/samples/web-functions/apps/aspnetcore/Acme.AspNetCore.csproj new file mode 100644 index 0000000..78a1b6e --- /dev/null +++ b/samples/web-functions/apps/aspnetcore/Acme.AspNetCore.csproj @@ -0,0 +1,14 @@ + + + + net10.0 + + server + Acme.AspNetCore + + true + + false + + + diff --git a/samples/web-functions/apps/aspnetcore/Program.cs b/samples/web-functions/apps/aspnetcore/Program.cs new file mode 100644 index 0000000..7015158 --- /dev/null +++ b/samples/web-functions/apps/aspnetcore/Program.cs @@ -0,0 +1,105 @@ +using System.Text; +using System.Text.Json; + +var builder = WebApplication.CreateBuilder(args); + +// The Web Function runtime hands the process the address it must listen on. Outside +// Lambda the variable is absent and Kestrel keeps its default binding. +var httpEndpoint = Environment.GetEnvironmentVariable("AWS_LAMBDA_HTTP_ENDPOINT"); +if (!string.IsNullOrEmpty(httpEndpoint)) +{ + builder.WebHost.UseUrls($"http://{httpEndpoint}"); +} + +builder.Services.ConfigureHttpJsonOptions(options => +{ + options.SerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase; +}); + +var buildId = BuildId.Resolve(); +var startedAt = DateTimeOffset.UtcNow; + +var app = builder.Build(); + +// A trivial liveness route. Every route is only reachable through the IAM-protected +// endpoint, so this doubles as the "protected route" the sample recipe calls for. +app.MapGet("/health", () => Results.Json(new { status = "Ok", backend = "aspnetcore", buildId })); + +// The dynamically generated response the sample exists to demonstrate: values computed +// per request rather than baked in at build time. +app.MapGet("/status", () => Results.Json(new +{ + status = "Ok", + backend = "aspnetcore", + buildId, + requestTimeUtc = DateTimeOffset.UtcNow, + uptimeSeconds = Math.Round((DateTimeOffset.UtcNow - startedAt).TotalSeconds, 3), +})); + +await app.StartAsync(); +await LambdaRuntime.NotifyReadyAsync(app.Logger); +await app.WaitForShutdownAsync(); + +internal static class BuildId +{ + public static string Resolve() + { + var fromEnvironment = Environment.GetEnvironmentVariable("BUILD_ID"); + if (!string.IsNullOrWhiteSpace(fromEnvironment)) + { + return fromEnvironment; + } + + // The artifact build writes build-id.txt next to the apphost. + var fromFile = Path.Join(AppContext.BaseDirectory, "build-id.txt"); + if (File.Exists(fromFile)) + { + var value = File.ReadAllText(fromFile).Trim(); + if (value.Length > 0) + { + return value; + } + } + + return "dev"; + } +} + +internal static class LambdaRuntime +{ + // The execve shim replaces the Node runtime, which also replaces the Lambda runtime + // interface client that normally POSTs /ready once the port is up. The server has to + // send that signal itself, or the first invocation fails with Runtime.InitTimeout. + public static async Task NotifyReadyAsync(ILogger logger) + { + var runtimeApi = Environment.GetEnvironmentVariable("AWS_LAMBDA_RUNTIME_API"); + if (string.IsNullOrEmpty(runtimeApi)) + { + return; + } + + using var client = new HttpClient { BaseAddress = new Uri($"http://{runtimeApi}") }; + + // The runtime API is always up inside Lambda; retry briefly so a local smoke test + // that starts its mock slightly later still observes the handshake. + Exception? lastFailure = null; + for (var attempt = 1; attempt <= 10; attempt++) + { + try + { + using var content = new StringContent("{}", Encoding.UTF8, "application/json"); + using var response = await client.PostAsync("/2025-09-01/ready", content); + response.EnsureSuccessStatusCode(); + logger.LogInformation("Reported readiness to the Lambda runtime API at {RuntimeApi}.", runtimeApi); + return; + } + catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException) + { + lastFailure = ex; + await Task.Delay(200); + } + } + + throw new InvalidOperationException($"Failed to report readiness to the Lambda runtime API at {runtimeApi}.", lastFailure); + } +} diff --git a/samples/web-functions/apps/aspnetcore/index.js b/samples/web-functions/apps/aspnetcore/index.js new file mode 100644 index 0000000..4b02d34 --- /dev/null +++ b/samples/web-functions/apps/aspnetcore/index.js @@ -0,0 +1,5 @@ +// Lambda boots Node.js and imports this file as `index.js`. process.execve replaces the +// entire process image with the .NET server sitting next to it, so the revision's declared +// nodejs24.x runtime only ever runs this shim. The server then owns the readiness +// handshake (see Program.cs). +process.execve("/var/task/server", ["/var/task/server"], process.env); diff --git a/samples/web-functions/apps/blazor/Acme.Blazor.csproj b/samples/web-functions/apps/blazor/Acme.Blazor.csproj new file mode 100644 index 0000000..a914bd5 --- /dev/null +++ b/samples/web-functions/apps/blazor/Acme.Blazor.csproj @@ -0,0 +1,14 @@ + + + + net10.0 + + server + Acme.Blazor + + true + + false + + + diff --git a/samples/web-functions/apps/blazor/Components/App.razor b/samples/web-functions/apps/blazor/Components/App.razor new file mode 100644 index 0000000..9e0c512 --- /dev/null +++ b/samples/web-functions/apps/blazor/Components/App.razor @@ -0,0 +1,18 @@ + + + + + + + Blazor Static SSR Web Function Sample + + + + + + + + + + + diff --git a/samples/web-functions/apps/blazor/Components/Layout/MainLayout.razor b/samples/web-functions/apps/blazor/Components/Layout/MainLayout.razor new file mode 100644 index 0000000..724fc91 --- /dev/null +++ b/samples/web-functions/apps/blazor/Components/Layout/MainLayout.razor @@ -0,0 +1,5 @@ +@inherits LayoutComponentBase + +
+ @Body +
diff --git a/samples/web-functions/apps/blazor/Components/Pages/Home.razor b/samples/web-functions/apps/blazor/Components/Pages/Home.razor new file mode 100644 index 0000000..97c80b3 --- /dev/null +++ b/samples/web-functions/apps/blazor/Components/Pages/Home.razor @@ -0,0 +1,13 @@ +@page "/" + +Blazor Static SSR Web Function Sample + +

Blazor Static SSR Web Function Sample

+ +

Build id: @BuildId.Resolve()

+ +

Rendered at @DateTimeOffset.UtcNow.ToString("O")

+ +

+ Static asset: app.css +

diff --git a/samples/web-functions/apps/blazor/Components/Routes.razor b/samples/web-functions/apps/blazor/Components/Routes.razor new file mode 100644 index 0000000..faa2a8c --- /dev/null +++ b/samples/web-functions/apps/blazor/Components/Routes.razor @@ -0,0 +1,6 @@ + + + + + + diff --git a/samples/web-functions/apps/blazor/Components/_Imports.razor b/samples/web-functions/apps/blazor/Components/_Imports.razor new file mode 100644 index 0000000..3f6f13a --- /dev/null +++ b/samples/web-functions/apps/blazor/Components/_Imports.razor @@ -0,0 +1,8 @@ +@using System.Net.Http +@using Microsoft.AspNetCore.Components.Forms +@using Microsoft.AspNetCore.Components.Routing +@using Microsoft.AspNetCore.Components.Web +@using Microsoft.AspNetCore.Components.Web.Virtualization +@using Acme.Blazor +@using Acme.Blazor.Components +@using Acme.Blazor.Components.Layout diff --git a/samples/web-functions/apps/blazor/Program.cs b/samples/web-functions/apps/blazor/Program.cs new file mode 100644 index 0000000..c90599e --- /dev/null +++ b/samples/web-functions/apps/blazor/Program.cs @@ -0,0 +1,96 @@ +using System.Text; +using Acme.Blazor.Components; + +var builder = WebApplication.CreateBuilder(args); + +var httpEndpoint = Environment.GetEnvironmentVariable("AWS_LAMBDA_HTTP_ENDPOINT"); +if (!string.IsNullOrEmpty(httpEndpoint)) +{ + builder.WebHost.UseUrls($"http://{httpEndpoint}"); + + // Static assets and Razor components resolve relative to the content root. The execve + // shim starts the app from /var/task, so pin the content root to the app base directory + // rather than the process working directory. + builder.WebHost.UseContentRoot(AppContext.BaseDirectory); +} + +// Static SSR only. Interactive Server / Auto render modes open a SignalR circuit over a +// WebSocket, which Web Functions do not support, so they are deliberately not registered. +builder.Services.AddRazorComponents(); + +var app = builder.Build(); + +app.UseStaticFiles(); +app.UseAntiforgery(); + +app.MapStaticAssets(); +app.MapRazorComponents(); + +await app.StartAsync(); +await LambdaRuntime.NotifyReadyAsync(app.Logger); +await app.WaitForShutdownAsync(); + +internal static class BuildId +{ + // The artifact build writes build-id.txt next to the apphost and the smoke test reads the value + // back off the rendered page, so the deployed revision is observable from the outside. + public static string Resolve() + { + var fromEnvironment = Environment.GetEnvironmentVariable("BUILD_ID"); + if (!string.IsNullOrWhiteSpace(fromEnvironment)) + { + return fromEnvironment; + } + + var fromFile = Path.Join(AppContext.BaseDirectory, "build-id.txt"); + if (File.Exists(fromFile)) + { + var value = File.ReadAllText(fromFile).Trim(); + if (value.Length > 0) + { + return value; + } + } + + return "dev"; + } +} + +internal static class LambdaRuntime +{ + // The execve shim replaces the Node runtime, which also replaces the Lambda runtime + // interface client that normally POSTs /ready once the port is up. The server has to + // send that signal itself, or the first invocation fails with Runtime.InitTimeout. + public static async Task NotifyReadyAsync(ILogger logger) + { + var runtimeApi = Environment.GetEnvironmentVariable("AWS_LAMBDA_RUNTIME_API"); + if (string.IsNullOrEmpty(runtimeApi)) + { + return; + } + + using var client = new HttpClient { BaseAddress = new Uri($"http://{runtimeApi}") }; + + // The runtime API is always up inside Lambda; retry briefly so a local smoke test + // that starts its mock slightly later still observes the handshake. + Exception? lastFailure = null; + for (var attempt = 1; attempt <= 10; attempt++) + { + try + { + using var content = new StringContent("{}", Encoding.UTF8, "application/json"); + using var response = await client.PostAsync("/2025-09-01/ready", content); + response.EnsureSuccessStatusCode(); + logger.LogInformation("Reported readiness to the Lambda runtime API at {RuntimeApi}.", runtimeApi); + return; + } + catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException) + { + lastFailure = ex; + await Task.Delay(200); + } + } + + throw new InvalidOperationException($"Failed to report readiness to the Lambda runtime API at {runtimeApi}.", lastFailure); + } +} diff --git a/samples/web-functions/apps/blazor/index.js b/samples/web-functions/apps/blazor/index.js new file mode 100644 index 0000000..4b02d34 --- /dev/null +++ b/samples/web-functions/apps/blazor/index.js @@ -0,0 +1,5 @@ +// Lambda boots Node.js and imports this file as `index.js`. process.execve replaces the +// entire process image with the .NET server sitting next to it, so the revision's declared +// nodejs24.x runtime only ever runs this shim. The server then owns the readiness +// handshake (see Program.cs). +process.execve("/var/task/server", ["/var/task/server"], process.env); diff --git a/samples/web-functions/apps/blazor/wwwroot/app.css b/samples/web-functions/apps/blazor/wwwroot/app.css new file mode 100644 index 0000000..e43c643 --- /dev/null +++ b/samples/web-functions/apps/blazor/wwwroot/app.css @@ -0,0 +1,17 @@ +:root { + color-scheme: light dark; +} + +body { + font-family: system-ui, -apple-system, "Segoe UI", sans-serif; + margin: 2rem; + line-height: 1.5; +} + +h1 { + color: #512bd4; +} + +#rendered-at { + font-family: ui-monospace, SFMono-Regular, Menlo, monospace; +} diff --git a/samples/web-functions/apps/nextjs/app/layout.js b/samples/web-functions/apps/nextjs/app/layout.js new file mode 100644 index 0000000..7787215 --- /dev/null +++ b/samples/web-functions/apps/nextjs/app/layout.js @@ -0,0 +1,11 @@ +export const metadata = { + title: "Next.js Web Function Sample", +}; + +export default function RootLayout({ children }) { + return ( + + {children} + + ); +} diff --git a/samples/web-functions/apps/nextjs/app/page.js b/samples/web-functions/apps/nextjs/app/page.js new file mode 100644 index 0000000..820b0f1 --- /dev/null +++ b/samples/web-functions/apps/nextjs/app/page.js @@ -0,0 +1,26 @@ +import { headers } from "next/headers"; + +// Render on every request so the page proves the server executes at request time rather +// than being served from a prebuilt static cache. +export const dynamic = "force-dynamic"; + +export default async function Home() { + const requestHeaders = await headers(); + const requestId = requestHeaders.get("x-amzn-trace-id") ?? "local"; + const renderedAt = new Date().toISOString(); + const buildId = process.env.BUILD_ID ?? "dev"; + + return ( +
+

Next.js Web Function Sample

+

+ Build id: {buildId} +

+

Rendered at {renderedAt}

+

Request id: {requestId}

+

+ Static asset: /sample.txt +

+
+ ); +} diff --git a/samples/web-functions/apps/nextjs/index.js b/samples/web-functions/apps/nextjs/index.js new file mode 100644 index 0000000..fc771cf --- /dev/null +++ b/samples/web-functions/apps/nextjs/index.js @@ -0,0 +1,41 @@ +// Lambda Web Function entry point for the Next.js standalone server. +// +// The managed runtime boots Node.js and imports this file as `index.js`. Node's HTTP +// server wrapper reads its listen address from HOSTNAME/PORT, while Lambda exposes the +// address the function must bind to as AWS_LAMBDA_HTTP_ENDPOINT ("host:port"). This shim +// bridges the two, then hands control to the generated standalone server. +const path = require("path"); + +const endpoint = process.env.AWS_LAMBDA_HTTP_ENDPOINT; +if (endpoint) { + const separator = endpoint.lastIndexOf(":"); + if (separator > 0) { + process.env.HOSTNAME = endpoint.slice(0, separator); + process.env.PORT = endpoint.slice(separator + 1); + } +} + +// The artifact build writes build-id.txt next to this file; surface it to the app so a +// revision update can be observed from the rendered page. +if (!process.env.BUILD_ID) { + try { + process.env.BUILD_ID = require("fs") + .readFileSync(path.join(__dirname, "build-id.txt"), "utf8") + .trim(); + } catch { + // build-id.txt is optional; the page falls back to "dev". + } +} + +// pnpm installs packages behind symlinks. Making the local node_modules discoverable via +// NODE_PATH keeps `require` resolution working regardless of the package manager used. +process.env.NODE_PATH = [process.env.NODE_PATH, path.join(__dirname, "node_modules")] + .filter(Boolean) + .join(path.delimiter); +require("module").Module._initPaths(); + +// Lambda sends SIGTERM before freezing the environment; exit cleanly so the shutdown +// fits inside the one-second grace window. +process.on("SIGTERM", () => process.exit(0)); + +require("./server.js"); diff --git a/samples/web-functions/apps/nextjs/next.config.mjs b/samples/web-functions/apps/nextjs/next.config.mjs new file mode 100644 index 0000000..dca72c2 --- /dev/null +++ b/samples/web-functions/apps/nextjs/next.config.mjs @@ -0,0 +1,20 @@ +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +const projectDir = path.dirname(fileURLToPath(import.meta.url)); + +/** @type {import('next').NextConfig} */ +const nextConfig = { + // Emit a self-contained server bundle under .next/standalone so the revision does not + // need the full node_modules tree at runtime. This is the layout the Web Function + // artifact recipe expects (standalone output + .next/static + public at the zip root). + output: "standalone", + // Pin the tracing root to this app so a lockfile in a parent directory cannot move the + // standalone server: server.js must stay at the artifact root. + outputFileTracingRoot: projectDir, + // The sample does not use the Next.js image optimizer. Disabling it keeps the revision + // from depending on the platform-specific sharp/libvips image pipeline. + images: { unoptimized: true }, +}; + +export default nextConfig; diff --git a/samples/web-functions/apps/nextjs/package-lock.json b/samples/web-functions/apps/nextjs/package-lock.json new file mode 100644 index 0000000..646b242 --- /dev/null +++ b/samples/web-functions/apps/nextjs/package-lock.json @@ -0,0 +1,1012 @@ +{ + "name": "web-function-nextjs-sample", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "web-function-nextjs-sample", + "version": "1.0.0", + "dependencies": { + "next": "16.4.3", + "react": "19.3.1", + "react-dom": "19.3.1" + } + }, + "node_modules/@emnapi/runtime": { + "version": "1.11.3", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.3.tgz", + "integrity": "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==", + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@img/colour": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz", + "integrity": "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=18" + } + }, + "node_modules/@img/sharp-darwin-arm64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.35.5.tgz", + "integrity": "sha512-QRUlFQ0WxvdWyqqG/WtI3iupfD5rBzmCHXSdPsY91sAtVtTo7Q4cb6zOccZ3gqEqkr0f1As1ehLqmEpDsRf+lg==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-arm64": "1.3.4" + } + }, + "node_modules/@img/sharp-darwin-x64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.35.5.tgz", + "integrity": "sha512-+BR255RhDlpygUpOc/Jdt1nT6DQ3XG/ERo5wbcdOf5Q320dKtPCKPLR1LJs9VGXRaMa8l1uUa0tkCNOXiAxZUw==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-x64": "1.3.4" + } + }, + "node_modules/@img/sharp-freebsd-wasm32": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-freebsd-wasm32/-/sharp-freebsd-wasm32-0.35.5.tgz", + "integrity": "sha512-Y/z91nEZ4uIBX5X3nfTovjU9lHNKFYbL2lpHCLVNmXQK03VIZvXBBt0KxbPGp2SdGSF+2mQU4e+hQaWOt86iAw==", + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "dependencies": { + "@img/sharp-wasm32": "0.35.5" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-darwin-arm64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.3.4.tgz", + "integrity": "sha512-5R89nBYiRdUlSWJxPhO+GVtaXzXSxKnRu/xqMn3KTA3L9EB9Oy/P+Nn2f2vlhPuUdy/Zusb2DarbyTpGCfEDuw==", + "cpu": [ + "arm64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-darwin-x64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.3.4.tgz", + "integrity": "sha512-iR2OKH80yi0U+dUplyh3/xdpFvps6YkCwsXenIJxqxR1v9o+xtKTGbS9H7cps+2Vxjc8B1j96p75NmTGjIhtpQ==", + "cpu": [ + "x64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.3.4.tgz", + "integrity": "sha512-LmRtTsOHuvM2+wlO2Db37dx5MiZhB0FvSunciw48YjdOkZz9KAiRbm8ujeMOA1INqmei5NapFxYEK1D1ZSidmw==", + "cpu": [ + "arm" + ], + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.3.4.tgz", + "integrity": "sha512-Y3dgX/6lE2QhQb+Gxy0WZxfg9MEm/JBjamZpS2IklP7xIQoKN4hzAm7KcMVGtaVDt3neE9OKBC7vAfonA/Lr1A==", + "cpu": [ + "arm64" + ], + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-ppc64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.3.4.tgz", + "integrity": "sha512-Le6boB8Tai0Nis+gIxIpKx68UDVVIqdR8Tin5Yf1z2LJJQLDJvCDRqRu+jC2qCoD+eIomonmOwB4smBRxfVpYQ==", + "cpu": [ + "ppc64" + ], + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-riscv64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-riscv64/-/sharp-libvips-linux-riscv64-1.3.4.tgz", + "integrity": "sha512-aHkkIEHPRdQEegJN20MLmGtxYD9R2wQr3Cwpddnu5+YKMt6Uzax7S9h5gpZTo8wyrGuZSlfQ63OevL5mTyOC7Q==", + "cpu": [ + "riscv64" + ], + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-s390x": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.3.4.tgz", + "integrity": "sha512-ra/mB6MikESDUO7Yg+Mi95bFBb9GsObURuhnOv3OqknjGe9sZrG8tCe9q0xSIGrtLgvgw0gKnFWcK4blSgQOuQ==", + "cpu": [ + "s390x" + ], + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-x64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.3.4.tgz", + "integrity": "sha512-GJ//SSXbnwSDes02umB3nDJLFcQzw8a18V8fyhqr6tV515tOEMdImjjxj1AoafMRz56F3PHgftnj1QEKSU1zkw==", + "cpu": [ + "x64" + ], + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linuxmusl-arm64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.3.4.tgz", + "integrity": "sha512-hvulFwtjUcagsis6BBxHwGFwWoNZjgYmULGVrZcyfNbjA8hKILbRxGg15/7w5HDyXHXUos/j6baAWqnCyQ2DWA==", + "cpu": [ + "arm64" + ], + "libc": [ + "musl" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linuxmusl-x64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.3.4.tgz", + "integrity": "sha512-6zXKeE/p39I1AmA3cJG35eyBGNqNddLnUXjhwBnsGjFPWqf5VKkDBEqaEkPDoTEtkxwi2vv8Tcr2mDyP4So7Fg==", + "cpu": [ + "x64" + ], + "libc": [ + "musl" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-linux-arm": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.35.5.tgz", + "integrity": "sha512-LEaXK2WdXVK5ykcw0buWyPMsmLLL2vpHLD6yrNSW+JGEL3BZPA4tpKN6iaMc4AxTTAoaX/sU1rOL51lcIz48ZQ==", + "cpu": [ + "arm" + ], + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm": "1.3.4" + } + }, + "node_modules/@img/sharp-linux-arm64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.35.5.tgz", + "integrity": "sha512-LYVx5JTsOM2CBzmxreh+nl64/3H6Xb09iSLknqH47z2T2DFFxDeFLP5y4dJwe6H7uGQlHPyEEtIqyo3DYsRwdQ==", + "cpu": [ + "arm64" + ], + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm64": "1.3.4" + } + }, + "node_modules/@img/sharp-linux-ppc64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.35.5.tgz", + "integrity": "sha512-QVxAAq8evVRI9ia2vqgwrmWucn5Dfv+JdWzj75pD8omHLPSP7f8p20O8jxzjCcuCEQEOtYOZUmX1hkiZ0kdevA==", + "cpu": [ + "ppc64" + ], + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-ppc64": "1.3.4" + } + }, + "node_modules/@img/sharp-linux-riscv64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-riscv64/-/sharp-linux-riscv64-0.35.5.tgz", + "integrity": "sha512-LtdreXguaavKODPIfzJ4kffx7UNt1omwtK0rch4EBbbSTXPnxWmYSayXdLJw0fJzQ97kHt1gL/yh4tvU+nCyRQ==", + "cpu": [ + "riscv64" + ], + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-riscv64": "1.3.4" + } + }, + "node_modules/@img/sharp-linux-s390x": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.35.5.tgz", + "integrity": "sha512-UZasTOFiYzotTsGOCu42BfUzP6Tu6Do/947iRm1RsLKvlllxwGcn4RN27LibGWceix4Y+Pmw3jsnTcCQIgWjqA==", + "cpu": [ + "s390x" + ], + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-s390x": "1.3.4" + } + }, + "node_modules/@img/sharp-linux-x64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.35.5.tgz", + "integrity": "sha512-SxFtLTeJInhAA9Q836kux2vZNeOBQEx658qvbboZScr0wIARym3IcGmW7KpVD5sbVg0Ojy+udFQdayYIZyoNog==", + "cpu": [ + "x64" + ], + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-x64": "1.3.4" + } + }, + "node_modules/@img/sharp-linuxmusl-arm64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.35.5.tgz", + "integrity": "sha512-9HbMclmI1zlNkFRs3z9/eBtDjfD0sGlrX1z6b1qwmiFY5ElDLh4BC0LPBdVp7z1DXFiKlIcznf+ZlsuZzLxQqg==", + "cpu": [ + "arm64" + ], + "libc": [ + "musl" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-arm64": "1.3.4" + } + }, + "node_modules/@img/sharp-linuxmusl-x64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.35.5.tgz", + "integrity": "sha512-4KOphqB035HrVdqLZfCgMzzERrQkkzOwRhl4OAkRO1YCldbaFjySXMaK534Mo0V+LndnlJk+sbUyLeU0ULyD1A==", + "cpu": [ + "x64" + ], + "libc": [ + "musl" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-x64": "1.3.4" + } + }, + "node_modules/@img/sharp-wasm32": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.35.5.tgz", + "integrity": "sha512-Ptsga1su4tQx+LLF1ECS9U6nz5kmrXKo6XVbtR48Ke3ZRxxgaWBu7IDtEe1quo8hiupwm6WFqxVlXaSf7IINGQ==", + "license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT", + "optional": true, + "dependencies": { + "@emnapi/runtime": "^1.11.3" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-webcontainers-wasm32": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-webcontainers-wasm32/-/sharp-webcontainers-wasm32-0.35.5.tgz", + "integrity": "sha512-hfhF/FmoQyTUkA0bIKFOtw536BQSeBMe6BF6QyWlrPxT754+TFLaZ7sKKTfvvM0yJgKgaYTwnFCIZ/GuDw5SUA==", + "cpu": [ + "wasm32" + ], + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "@img/sharp-wasm32": "0.35.5" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-arm64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.35.5.tgz", + "integrity": "sha512-X4t7g+7ZA5DKblCBEXGjUqqemj4vczING/5viFwAL8h4N3qYeyjwdCvRLHi4EdOUI+2Z7UFlp1VM+p/AuEtm6Q==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-ia32": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.35.5.tgz", + "integrity": "sha512-5Zm82LoBc43nhwNybZlG7Y1KO//Zhsn306fQl29ZOuStHLGTo3BWL83q3cznX0poxSAMuYL1On/BHBxkBeKr6A==", + "cpu": [ + "ia32" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-x64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.35.5.tgz", + "integrity": "sha512-x76eH0vEiHlcMQu8Y8IenntaACtddpT6W0wmXtWrnKcnKI7ME5DdgqhAD6SEWOEl1v2zDvkZDhFA9KnURwpfqg==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@next/env": { + "version": "16.4.3", + "resolved": "https://registry.npmjs.org/@next/env/-/env-16.4.3.tgz", + "integrity": "sha512-a7tz1QCcWWkwC/rPJcPMJk/UNRu9CFhDd3OHYE5hddbJrs8BqRTalxI6GlKCWEGzRLHN+S/B7a4PAHCtm25aBQ==", + "license": "MIT" + }, + "node_modules/@next/swc-darwin-arm64": { + "version": "16.4.3", + "resolved": "https://registry.npmjs.org/@next/swc-darwin-arm64/-/swc-darwin-arm64-16.4.3.tgz", + "integrity": "sha512-4yq5EXBt+VDtAZwTyfijaFp5D2C5oz3Ikw5a2kiX2K9nw72vrZX2q5UuAlkPtUMO1tQz6JTKpaKWjS7OOefTDQ==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@next/swc-darwin-x64": { + "version": "16.4.3", + "resolved": "https://registry.npmjs.org/@next/swc-darwin-x64/-/swc-darwin-x64-16.4.3.tgz", + "integrity": "sha512-1Rvkn/LUhnEF8WxnRkOrqGhbwXui1bkWFxONKIbN+r7C+9KHDSZ+iUoj4CzymVMWUyZIyx9szcb9+kbKhD500A==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@next/swc-linux-arm64-gnu": { + "version": "16.4.3", + "resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-gnu/-/swc-linux-arm64-gnu-16.4.3.tgz", + "integrity": "sha512-dCKpXErGg3abUM6t5JTJV/ottVBTStJB5lRJTbgdUdQaQ+jNHiK56Hsc0YAEg/rinSh42hYG3HWiYmEMdilnxg==", + "cpu": [ + "arm64" + ], + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@next/swc-linux-arm64-musl": { + "version": "16.4.3", + "resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-musl/-/swc-linux-arm64-musl-16.4.3.tgz", + "integrity": "sha512-WwYbhWkhYBvBtib1K4W0kL8MW2snBD2A5b3SN4vPpqalZbZs5+bQ1yzAdepVoOqrFfEW3dmREy4Zs1MrWcrFbw==", + "cpu": [ + "arm64" + ], + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@next/swc-linux-x64-gnu": { + "version": "16.4.3", + "resolved": "https://registry.npmjs.org/@next/swc-linux-x64-gnu/-/swc-linux-x64-gnu-16.4.3.tgz", + "integrity": "sha512-QymWvfUwDEC5/lpJOsxX5VAbyoR2D13+2Jsjz4be7gT4LPqEgdpkeLIR/HFfCLgKzoMhpJbp6I/JnogyNZHcaA==", + "cpu": [ + "x64" + ], + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@next/swc-linux-x64-musl": { + "version": "16.4.3", + "resolved": "https://registry.npmjs.org/@next/swc-linux-x64-musl/-/swc-linux-x64-musl-16.4.3.tgz", + "integrity": "sha512-Vmjd9D7DpA4Vv3cUlr82QWgJD/BQZmns801vtC5VWHg6jCIA4a5vMKpQnfrM2pyCrp2eV0ENdUg4PlN3bAc2Yw==", + "cpu": [ + "x64" + ], + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@next/swc-win32-arm64-msvc": { + "version": "16.4.3", + "resolved": "https://registry.npmjs.org/@next/swc-win32-arm64-msvc/-/swc-win32-arm64-msvc-16.4.3.tgz", + "integrity": "sha512-lG1pPdPLk7gTyGb00n5JIMLdBJgjb+UEhSdZvFbhUMg0DyC6z4B7RnpSKF9VCd4imkLObVbXOFA0kFCpw7yFow==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@next/swc-win32-x64-msvc": { + "version": "16.4.3", + "resolved": "https://registry.npmjs.org/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-16.4.3.tgz", + "integrity": "sha512-NmQC9RkJdnPXRaMxtkCzobB3teVjqF33oSOnwDfi+XYGWWYpt+xlGK3mtktSKLbdjwaWbJu2OkkMiRFGUUncKg==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@swc/helpers": { + "version": "0.5.23", + "resolved": "https://registry.npmjs.org/@swc/helpers/-/helpers-0.5.23.tgz", + "integrity": "sha512-5lSsMOTXURePglDfvuAQUqkGek9Hg2kksOYay2m0+XR++b2NWYL/4sWyuvVBIs8oKnJaxkdi9whaL/sqN13afw==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.8.0" + } + }, + "node_modules/baseline-browser-mapping": { + "version": "2.11.32", + "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.32.tgz", + "integrity": "sha512-UvuxFU9P3hM29LrQdwu0cD6w6/+SFr+UlB9s/knI7+O2rK9xFxKUwSDWxGdbbqQ9/V7BJ5s0NI5nQAE4uJp3gQ==", + "license": "Apache-2.0", + "bin": { + "baseline-browser-mapping": "dist/cli.cjs" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/caniuse-lite": { + "version": "1.0.30001819", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001819.tgz", + "integrity": "sha512-LFUqIIAwpzsIuevnKnsR9qnStBcgzPShTX61lBwN9uFkkf8o8zLiebEjbW8AYtZiF+1YKDWfdt/pWDtMuG8Xwg==", + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/caniuse-lite" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "CC-BY-4.0" + }, + "node_modules/client-only": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/client-only/-/client-only-0.0.1.tgz", + "integrity": "sha512-IV3Ou0jSMzZrd3pZ48nLkT9DA7Ag1pnPzaiQhpW7c3RbcqqzvzzVu+L8gfqMp/8IM2MQtSiqaCxrrcfu8I8rMA==", + "license": "MIT" + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "license": "Apache-2.0", + "optional": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/nanoid": { + "version": "3.3.20", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz", + "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/next": { + "version": "16.4.3", + "resolved": "https://registry.npmjs.org/next/-/next-16.4.3.tgz", + "integrity": "sha512-OqxKTGi9u80FydydsMNYNjnuje9Au+kvHlt2GZ//ftdpDHm1dxKqAaENoOOTX5wKzn+9vaKUNIfZeyZUuLhCnA==", + "license": "MIT", + "dependencies": { + "@next/env": "16.4.3", + "@swc/helpers": "0.5.23", + "baseline-browser-mapping": "^2.9.19", + "caniuse-lite": "^1.0.30001579", + "postcss": "8.5.23", + "styled-jsx": "5.1.6" + }, + "bin": { + "next": "dist/bin/next" + }, + "engines": { + "node": ">=20.9.0" + }, + "optionalDependencies": { + "@next/swc-darwin-arm64": "16.4.3", + "@next/swc-darwin-x64": "16.4.3", + "@next/swc-linux-arm64-gnu": "16.4.3", + "@next/swc-linux-arm64-musl": "16.4.3", + "@next/swc-linux-x64-gnu": "16.4.3", + "@next/swc-linux-x64-musl": "16.4.3", + "@next/swc-win32-arm64-msvc": "16.4.3", + "@next/swc-win32-x64-msvc": "16.4.3", + "sharp": "^0.35.5" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.1.0", + "@playwright/test": "^1.51.1", + "babel-plugin-react-compiler": "*", + "react": "^18.2.0 || 19.0.0-rc-de68d2f4-20241204 || ^19.0.0", + "react-dom": "^18.2.0 || 19.0.0-rc-de68d2f4-20241204 || ^19.0.0", + "sass": "^1.3.0" + }, + "peerDependenciesMeta": { + "@opentelemetry/api": { + "optional": true + }, + "@playwright/test": { + "optional": true + }, + "babel-plugin-react-compiler": { + "optional": true + }, + "sass": { + "optional": true + } + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "license": "ISC" + }, + "node_modules/postcss": { + "version": "8.5.23", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.23.tgz", + "integrity": "sha512-g50586zr4bZmwFiTlflMu8E0bDTb5I5gertgwAKmsdUlTQIhZtunzUlD1WSzwcVWPoAVpsrA6vlfCD7oXvRwgg==", + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.16", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/react": { + "version": "19.3.1", + "resolved": "https://registry.npmjs.org/react/-/react-19.3.1.tgz", + "integrity": "sha512-QNhWdt7nrgVWWQG58QuGsAR3jv3Hbe4mb4vz7w2csnHavciZJgda1CPNaldF6eVxv90ud3jUXpKlHL69gO38yw==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/react-dom": { + "version": "19.3.1", + "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.3.1.tgz", + "integrity": "sha512-Y0bARz53lhEC1NMCASs0/j+faB/zqt3R8hpvg1e8+61ZVJ4UL0UdC4cBbXfZMcIuhrfgeILTLe+ZeBCavQPtKQ==", + "license": "MIT", + "dependencies": { + "scheduler": "^0.28.0" + }, + "peerDependencies": { + "react": "^19.3.1" + } + }, + "node_modules/scheduler": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.28.0.tgz", + "integrity": "sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw==", + "license": "MIT" + }, + "node_modules/semver": { + "version": "7.8.5", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", + "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", + "license": "ISC", + "optional": true, + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/sharp": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.35.5.tgz", + "integrity": "sha512-Ywn4OnzGukp7CDMrp08RQ50YKmuwG47brZgIVPTvBaaAfQlRlygrRqSrxdCiL9M+LlzLBiJ68IR1QqvzHyjC7g==", + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "@img/colour": "^1.1.0", + "detect-libc": "^2.1.2", + "semver": "^7.8.5" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-darwin-arm64": "0.35.5", + "@img/sharp-darwin-x64": "0.35.5", + "@img/sharp-freebsd-wasm32": "0.35.5", + "@img/sharp-libvips-darwin-arm64": "1.3.4", + "@img/sharp-libvips-darwin-x64": "1.3.4", + "@img/sharp-libvips-linux-arm": "1.3.4", + "@img/sharp-libvips-linux-arm64": "1.3.4", + "@img/sharp-libvips-linux-ppc64": "1.3.4", + "@img/sharp-libvips-linux-riscv64": "1.3.4", + "@img/sharp-libvips-linux-s390x": "1.3.4", + "@img/sharp-libvips-linux-x64": "1.3.4", + "@img/sharp-libvips-linuxmusl-arm64": "1.3.4", + "@img/sharp-libvips-linuxmusl-x64": "1.3.4", + "@img/sharp-linux-arm": "0.35.5", + "@img/sharp-linux-arm64": "0.35.5", + "@img/sharp-linux-ppc64": "0.35.5", + "@img/sharp-linux-riscv64": "0.35.5", + "@img/sharp-linux-s390x": "0.35.5", + "@img/sharp-linux-x64": "0.35.5", + "@img/sharp-linuxmusl-arm64": "0.35.5", + "@img/sharp-linuxmusl-x64": "0.35.5", + "@img/sharp-webcontainers-wasm32": "0.35.5", + "@img/sharp-win32-arm64": "0.35.5", + "@img/sharp-win32-ia32": "0.35.5", + "@img/sharp-win32-x64": "0.35.5" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/source-map-js": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", + "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/styled-jsx": { + "version": "5.1.6", + "resolved": "https://registry.npmjs.org/styled-jsx/-/styled-jsx-5.1.6.tgz", + "integrity": "sha512-qSVyDTeMotdvQYoHWLNGwRFJHC+i+ZvdBRYosOFgC+Wg1vx4frN2/RG/NA7SYqqvKNLf39P2LSRA2pu6n0XYZA==", + "license": "MIT", + "dependencies": { + "client-only": "0.0.1" + }, + "engines": { + "node": ">= 12.0.0" + }, + "peerDependencies": { + "react": ">= 16.8.0 || 17.x.x || ^18.0.0-0 || ^19.0.0-0" + }, + "peerDependenciesMeta": { + "@babel/core": { + "optional": true + }, + "babel-plugin-macros": { + "optional": true + } + } + }, + "node_modules/tslib": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", + "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "license": "0BSD" + } + } +} diff --git a/samples/web-functions/apps/nextjs/package.json b/samples/web-functions/apps/nextjs/package.json new file mode 100644 index 0000000..75a7597 --- /dev/null +++ b/samples/web-functions/apps/nextjs/package.json @@ -0,0 +1,14 @@ +{ + "name": "web-function-nextjs-sample", + "version": "1.0.0", + "private": true, + "description": "Minimal Next.js standalone app packaged as an AWS Lambda Web Function revision.", + "scripts": { + "build": "next build" + }, + "dependencies": { + "next": "16.4.3", + "react": "19.3.1", + "react-dom": "19.3.1" + } +} diff --git a/samples/web-functions/apps/nextjs/public/sample.txt b/samples/web-functions/apps/nextjs/public/sample.txt new file mode 100644 index 0000000..5d06458 --- /dev/null +++ b/samples/web-functions/apps/nextjs/public/sample.txt @@ -0,0 +1 @@ +Next.js static asset for CloudFront cache verification. diff --git a/samples/web-functions/build-artifacts.sh b/samples/web-functions/build-artifacts.sh new file mode 100755 index 0000000..4b800fd --- /dev/null +++ b/samples/web-functions/build-artifacts.sh @@ -0,0 +1,288 @@ +#!/usr/bin/env bash +# +# Build deployment-ready Web Function artifacts for the three sandbox workloads. +# +# Produces, in samples/web-functions/build/ (override with --out): +# nextjs.zip aspnetcore.zip blazor.zip +# nextjs-v2.zip aspnetcore-v2.zip blazor-v2.zip +# +# Each zip is a self-contained Lambda Web Function revision payload: the execve shim (or +# the Next.js entry) at the zip root, the server entrypoint at the zip root, and every +# runtime file the server needs. The -v2 variants carry a different build id so a +# revision-update test can observe a change between two artifact versions. +# +# Builds are repeatable but NOT byte-for-byte reproducible: zip records file modification +# times and stores entries in directory order, and the Next.js build stamps its own +# generated identifiers. Two runs from the same source therefore differ at the byte level. +# +# No AWS access or credentials are required: this only compiles and packages. +# +# Prerequisites: +# - .NET 10 SDK (GA) -> https://dotnet.microsoft.com/download +# - Node.js 24+ and npm -> https://nodejs.org +# - zip / unzip (preinstalled on macOS and most Linux) +# +# Usage: +# ./build-artifacts.sh # build all three workloads (+ v2 variants) +# ./build-artifacts.sh --clean # remove generated artifacts first, then build +# ./build-artifacts.sh --build-id abc # override the baked build id +# ./build-artifacts.sh --out /tmp/out # override the output directory (relative ok) +# ./build-artifacts.sh --only nextjs # build a single workload + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +APPS_DIR="${SCRIPT_DIR}/apps" + +RUNTIME_IDENTIFIER="linux-arm64" +TARGET_FRAMEWORK="net10.0" + +# Web Functions run on Graviton (linux/arm64) only. Install the Next.js optional +# dependencies for that platform so the standalone bundle carries linux-arm64 native +# modules (sharp/libvips) instead of whatever the build host happens to be. +NPM_PLATFORM_ARGS=(--os=linux --cpu=arm64 --libc=glibc) + +WORKLOADS=(nextjs aspnetcore blazor) + +OUT_DIR="${SCRIPT_DIR}/build" +CLEAN=0 +ONLY="" + +log() { printf '\033[1;34m==>\033[0m %s\n' "$*"; } +die() { printf '\033[1;31merror:\033[0m %s\n' "$*" >&2; exit 1; } +arg_error() { printf '\033[1;31merror:\033[0m %s\n' "$*" >&2; exit 2; } + +while [[ $# -gt 0 ]]; do + case "$1" in + --clean) CLEAN=1; shift ;; + --build-id) [[ $# -ge 2 ]] || arg_error "--build-id requires a value"; BUILD_ID="$2"; shift 2 ;; + --out) [[ $# -ge 2 ]] || arg_error "--out requires a value"; OUT_DIR="$2"; shift 2 ;; + --only) [[ $# -ge 2 ]] || arg_error "--only requires a value"; ONLY="$2"; shift 2 ;; + -h|--help) + sed -n '2,30p' "${BASH_SOURCE[0]}" | sed 's/^# \{0,1\}//' + exit 0 + ;; + *) arg_error "unknown argument: $1" ;; + esac +done + +if [[ -n "${ONLY}" ]]; then + match=0 + for w in "${WORKLOADS[@]}"; do [[ "${ONLY}" == "${w}" ]] && match=1; done + [[ ${match} -eq 1 ]] || arg_error "--only must be one of: ${WORKLOADS[*]}" +fi + +# Resolve the output directory to an absolute path before any `cd`. A relative --out is +# interpreted against the caller's directory, and later `cd`-based steps (the dotnet +# publish working directory, the zip staging directory) must not re-interpret it, which +# would scatter build output into the source tree. +case "${OUT_DIR}" in + /*) ;; + *) OUT_DIR="${PWD}/${OUT_DIR}" ;; +esac + +STAGE_DIR="${OUT_DIR}/stage" + +# A stable build id by default so repeated builds from the same commit share an id. +if [[ -z "${BUILD_ID:-}" ]]; then + BUILD_ID="$(git -C "${SCRIPT_DIR}" rev-parse --short=12 HEAD 2>/dev/null || echo dev)" +fi + +require_cmd() { + command -v "$1" >/dev/null 2>&1 || die "required command not found: $1" +} + +require_cmd zip +require_cmd unzip + +# Remove only content this script generates. The output directory itself is never deleted: +# a caller may point --out at an existing directory that also holds unrelated files, so a +# blanket `rm -rf "${OUT_DIR}"` would destroy them. +clean_outputs() { + local name + for name in "${WORKLOADS[@]}"; do + rm -f "${OUT_DIR}/${name}.zip" "${OUT_DIR}/${name}-v2.zip" + done + rm -rf "${OUT_DIR}/stage" "${OUT_DIR}/.smoke" +} + +if [[ ${CLEAN} -eq 1 ]]; then + log "Removing generated artifacts in ${OUT_DIR}" + clean_outputs +fi + +mkdir -p "${STAGE_DIR}" + +should_build() { + [[ -z "${ONLY}" || "${ONLY}" == "$1" ]] +} + +# Zip the contents of a staging directory so archive entries are relative to the root +# (the layout Lambda extracts to /var/task). -X keeps the archives free of host-specific +# extra attributes while still storing the Unix permission bits. +zip_stage() { + local stage="$1" archive="$2" + rm -f "${archive}" + ( cd "${stage}" && zip -q -r -X "${archive}" . ) +} + +# Assert a set of required entries exists in an archive, and that `server` (when present) +# round-trips with its executable bit set. +validate_zip() { + local archive="$1" name="$2" + shift 2 + local entries + entries="$(unzip -Z1 "${archive}")" + + local required + for required in "$@"; do + if ! grep -qxF "${required}" <<<"${entries}"; then + die "${name}: archive is missing required entry '${required}'" + fi + done + + if grep -qxF "server" <<<"${entries}"; then + local probe + probe="$(mktemp -d)" + unzip -oq "${archive}" server -d "${probe}" + if [[ ! -x "${probe}/server" ]]; then + die "${name}: 'server' entry is not executable after extraction" + fi + rm -rf "${probe}" + fi + + local size + size="$(du -h "${archive}" | cut -f1 | tr -d ' ')" + log "Validated ${name} (${size}): ${archive}" +} + +write_build_id() { + printf '%s\n' "$1" > "$2" +} + +# --- Next.js ----------------------------------------------------------------------------- + +build_nextjs() { + local app_dir="${APPS_DIR}/nextjs" + local stage="${STAGE_DIR}/nextjs" + local zip="${OUT_DIR}/nextjs.zip" + + log "Building Next.js standalone output (${NPM_PLATFORM_ARGS[*]})" + rm -rf "${stage}" "${app_dir}/.next" + mkdir -p "${stage}" + + ( + cd "${app_dir}" + if [[ -f package-lock.json ]]; then + npm ci --no-audit --no-fund "${NPM_PLATFORM_ARGS[@]}" + else + npm install --no-audit --no-fund "${NPM_PLATFORM_ARGS[@]}" + fi + npm run build + ) + + # The zip root is the standalone server plus the static/public assets the recipe calls + # for: standalone output + .next/static + public, with index.js alongside server.js. + cp -R "${app_dir}/.next/standalone/." "${stage}/" + mkdir -p "${stage}/.next" + cp -R "${app_dir}/.next/static" "${stage}/.next/static" + cp -R "${app_dir}/public" "${stage}/public" + cp "${app_dir}/index.js" "${stage}/index.js" + write_build_id "${BUILD_ID}" "${stage}/build-id.txt" + + zip_stage "${stage}" "${zip}" + validate_zip "${zip}" "nextjs" index.js server.js package.json public/sample.txt build-id.txt + + make_v2 "${stage}" "${zip}" +} + +# --- ASP.NET Core ------------------------------------------------------------------------ + +build_aspnetcore() { + local app_dir="${APPS_DIR}/aspnetcore" + local stage="${STAGE_DIR}/aspnetcore" + local zip="${OUT_DIR}/aspnetcore.zip" + + log "Publishing ASP.NET Core self-contained ${RUNTIME_IDENTIFIER}" + rm -rf "${stage}" + mkdir -p "${stage}" + + ( + cd "${SCRIPT_DIR}" + dotnet publish "${app_dir}/Acme.AspNetCore.csproj" \ + --configuration Release \ + --runtime "${RUNTIME_IDENTIFIER}" \ + --self-contained true \ + -p:PublishTrimmed=false \ + -p:TargetFramework="${TARGET_FRAMEWORK}" \ + --output "${stage}" + ) + + cp "${app_dir}/index.js" "${stage}/index.js" + write_build_id "${BUILD_ID}" "${stage}/build-id.txt" + + zip_stage "${stage}" "${zip}" + validate_zip "${zip}" "aspnetcore" index.js server server.dll build-id.txt + + make_v2 "${stage}" "${zip}" +} + +# --- Blazor Static SSR ------------------------------------------------------------------- + +build_blazor() { + local app_dir="${APPS_DIR}/blazor" + local stage="${STAGE_DIR}/blazor" + local zip="${OUT_DIR}/blazor.zip" + + log "Publishing Blazor Static SSR self-contained ${RUNTIME_IDENTIFIER}" + rm -rf "${stage}" + mkdir -p "${stage}" + + ( + cd "${SCRIPT_DIR}" + dotnet publish "${app_dir}/Acme.Blazor.csproj" \ + --configuration Release \ + --runtime "${RUNTIME_IDENTIFIER}" \ + --self-contained true \ + -p:PublishTrimmed=false \ + -p:TargetFramework="${TARGET_FRAMEWORK}" \ + --output "${stage}" + ) + + cp "${app_dir}/index.js" "${stage}/index.js" + write_build_id "${BUILD_ID}" "${stage}/build-id.txt" + + zip_stage "${stage}" "${zip}" + validate_zip "${zip}" "blazor" index.js server server.dll wwwroot/app.css build-id.txt + + make_v2 "${stage}" "${zip}" +} + +# Produce a second archive that differs only by the baked build id, so a revision-update +# test has two distinct artifact versions to move between. +make_v2() { + local stage="$1" zip="$2" + local v2_stage="${stage}-v2" + local v2_zip="${zip%.zip}-v2.zip" + + rm -rf "${v2_stage}" + cp -R "${stage}" "${v2_stage}" + write_build_id "${BUILD_ID}-v2" "${v2_stage}/build-id.txt" + + zip_stage "${v2_stage}" "${v2_zip}" + log "Built v2 variant: ${v2_zip}" +} + +# --- Drive ------------------------------------------------------------------------------- + +log "Build id: ${BUILD_ID}" +log "Output directory: ${OUT_DIR}" + +should_build nextjs && build_nextjs +should_build aspnetcore && build_aspnetcore +should_build blazor && build_blazor + +log "Artifacts:" +for archive in "${OUT_DIR}"/*.zip; do + [[ -e "${archive}" ]] && printf ' %s\n' "${archive}" +done diff --git a/samples/web-functions/global.json b/samples/web-functions/global.json new file mode 100644 index 0000000..d46d21e --- /dev/null +++ b/samples/web-functions/global.json @@ -0,0 +1,7 @@ +{ + "sdk": { + "version": "10.0.100", + "rollForward": "latestFeature", + "allowPrerelease": false + } +} diff --git a/samples/web-functions/sandbox/.gitignore b/samples/web-functions/sandbox/.gitignore new file mode 100644 index 0000000..2fedfa7 --- /dev/null +++ b/samples/web-functions/sandbox/.gitignore @@ -0,0 +1,9 @@ +# CDK application build and synthesis outputs. +bin/ +obj/ +cdk.out/ +.cdk.staging/ + +# Artifact upload manifest and working files produced by the deployment scripts. +build/ +*.artifacts.json \ No newline at end of file diff --git a/samples/web-functions/sandbox/AppStack.cs b/samples/web-functions/sandbox/AppStack.cs new file mode 100644 index 0000000..add5d68 --- /dev/null +++ b/samples/web-functions/sandbox/AppStack.cs @@ -0,0 +1,248 @@ +using System.Collections.Generic; +using Amazon.CDK; +using Amazon.CDK.AWS.CloudFront; +using Amazon.CDK.AWS.IAM; +using Amazon.CDK.AWS.S3; +using Constructs; +using LayeredCraft.Cdk.Constructs; +using LayeredCraft.Cdk.Constructs.Models; + +namespace WebFunctionSandbox; + +/// +/// The sandbox workload stacks. Every workload is created through the public +/// API - no raw CloudFormation resources are used - so the sandbox exercises the same code path a consumer does. +/// +internal sealed class AppStack : Stack +{ + public AppStack( + Construct scope, + string id, + IStackProps? props, + SandboxConfiguration configuration, + SandboxNaming naming, + IBucket artifactsBucket) + : base(scope, id, props) + { + ArgumentNullException.ThrowIfNull(configuration); + ArgumentNullException.ThrowIfNull(naming); + ArgumentNullException.ThrowIfNull(artifactsBucket); + + naming.ApplyTags(this); + + // Imported by name: the app stack does not own this bucket, so every workload that reads from it must use + // the ExternallyManaged bucket policy (the ExternalStack bucket policy supplies the read grant). + var externalBucket = Bucket.FromBucketName(this, "ExternalArtifacts", naming.ExternalBucketName); + + // --- Next.js standalone: owned versioned bucket (Automatic policy) behind an OAC distribution. --- + var nextJs = new WebFunctionConstruct(this, "NextJs", new WebFunctionConstructProps + { + FunctionName = naming.NextJsFunctionName, + Code = WebFunctionCode.FromBucket(artifactsBucket, configuration.NextJs.ObjectKey, new WebFunctionCodeFromBucketOptions + { + ObjectVersion = configuration.NextJs.ObjectVersion, + }), + EnvironmentVariables = new Dictionary + { + ["NODE_ENV"] = "production", + ["NEXT_TELEMETRY_DISABLED"] = "1", + }, + Endpoint = new WebFunctionEndpointOptions { AuthType = WebFunctionAuthType.IamAuth }, + Description = "Sandbox Next.js standalone Web Function", + }); + + var nextJsDistribution = CreateDistribution( + this, + "NextJsDistribution", + nextJs.DefaultEndpoint, + "Sandbox Next.js distribution (dynamic SSR default, immutable assets cached)", + "/_next/static/*"); + + // Optional second distribution on the same endpoint: exercises adding a second scoped resource-policy + // statement, and (when removed) the statement lifecycle on the next deploy. + Distribution? nextJsSecondDistribution = configuration.SecondDistribution + ? CreateDistribution( + this, + "NextJsSecondDistribution", + nextJs.DefaultEndpoint, + "Sandbox second Next.js distribution (resource-policy lifecycle)", + "/_next/static/*") + : null; + + // --- ASP.NET Core: externally managed bucket. Default endpoint is invoke-granted; a second endpoint + // exists to prove endpoint-scoped denial. --- + var aspNetCore = new WebFunctionConstruct(this, "AspNetCore", new WebFunctionConstructProps + { + FunctionName = naming.AspNetCoreFunctionName, + Code = WebFunctionCode.FromBucket(externalBucket, configuration.AspNetCore.ObjectKey, new WebFunctionCodeFromBucketOptions + { + BucketPolicy = WebFunctionCodeBucketPolicy.ExternallyManaged, + ObjectVersion = configuration.AspNetCore.ObjectVersion, + }), + Endpoint = new WebFunctionEndpointOptions + { + AuthType = WebFunctionAuthType.IamAuth, + MaxEnvironments = 10, + RateLimit = 100, + }, + Description = "Sandbox ASP.NET Core Web Function", + }); + + var aspNetCoreAlt = aspNetCore.AddEndpoint("AltEndpoint", new WebFunctionEndpointOptions + { + EndpointName = "alt", + AuthType = WebFunctionAuthType.IamAuth, + Description = "Second endpoint on the same function for endpoint-scoped denial checks", + }); + + // --- Blazor Static SSR: externally managed bucket behind an OAC distribution. --- + var blazor = new WebFunctionConstruct(this, "Blazor", new WebFunctionConstructProps + { + FunctionName = naming.BlazorFunctionName, + Code = WebFunctionCode.FromBucket(externalBucket, configuration.Blazor.ObjectKey, new WebFunctionCodeFromBucketOptions + { + BucketPolicy = WebFunctionCodeBucketPolicy.ExternallyManaged, + ObjectVersion = configuration.Blazor.ObjectVersion, + }), + Endpoint = new WebFunctionEndpointOptions { AuthType = WebFunctionAuthType.IamAuth }, + Description = "Sandbox Blazor Static SSR Web Function", + }); + + var blazorDistribution = CreateDistribution( + this, + "BlazorDistribution", + blazor.DefaultEndpoint, + "Sandbox Blazor distribution (dynamic document, immutable framework assets cached)", + "/_framework/*", + "/_content/*"); + + // --- Operator roles. --- + // Granted caller: an owned mutable identity in the same stack, so the library writes an identity policy. + var callerRole = new Role(this, "CallerRole", new RoleProps + { + AssumedBy = new AccountPrincipal(configuration.Account), + Description = "Operator role granted invoke on the ASP.NET Core default endpoint (identity policy).", + }); + aspNetCore.DefaultEndpoint.GrantInvoke(callerRole); + + // Denied caller: an owned role with no invoke grant - a signed request from it must be denied. + var deniedRole = new Role(this, "DeniedRole", new RoleProps + { + AssumedBy = new AccountPrincipal(configuration.Account), + Description = "Operator role with no invoke grant, used to observe a 403.", + }); + + // Imported callers: two roles owned by the external stack and imported by literal ARN. Because each is + // imported (not an owned mutable identity) the library records the grant in the endpoint resource policy + // only. One is imported with Mutable = false, the other with the default mutable setting, so both + // resource-policy-only sub-cases in the acceptance matrix are synthesized. + var immutableCaller = Role.FromRoleArn(this, "ImportedCallerImmutableRole", naming.ImportedCallerImmutableRoleArn, new FromRoleArnOptions + { + Mutable = false, + }); + aspNetCore.DefaultEndpoint.GrantInvoke(immutableCaller); + + var mutableCaller = Role.FromRoleArn(this, "ImportedCallerMutableRole", naming.ImportedCallerMutableRoleArn, new FromRoleArnOptions + { + Mutable = true, + }); + aspNetCore.DefaultEndpoint.GrantInvoke(mutableCaller); + + // Cross-account caller (optional): an explicitly ExternallyManaged resource-policy grant to a role in a + // second sandbox account, per the approved design. + if (configuration.CrossAccountCallerRoleArn is not null) + { + var crossAccountRole = Role.FromRoleArn(this, "CrossAccountCallerRole", configuration.CrossAccountCallerRoleArn, new FromRoleArnOptions + { + Mutable = false, + }); + aspNetCore.DefaultEndpoint.GrantInvoke(crossAccountRole, new WebFunctionInvokeGrantOptions + { + CallerPolicy = WebFunctionCallerPolicy.ExternallyManaged, + }); + } + + // --- Outputs consumed by smoke.sh (read with aws cloudformation describe-stacks). --- + Output(this, "SandboxId", configuration.SandboxId); + Output(this, "SandboxAccount", configuration.Account); + Output(this, "SandboxRegion", configuration.Region); + Output(this, "ArtifactsBucketName", artifactsBucket.BucketName); + Output(this, "ExternalBucketName", naming.ExternalBucketName); + + Output(this, "NextJsFunctionName", nextJs.FunctionName); + Output(this, "NextJsEndpointUrl", nextJs.DefaultEndpoint.Url); + Output(this, "NextJsEndpointDomain", nextJs.DefaultEndpoint.DomainName); + Output(this, "NextJsEndpointArn", nextJs.DefaultEndpoint.EndpointArn); + Output(this, "NextJsDistributionDomain", nextJsDistribution.DistributionDomainName); + Output(this, "NextJsDistributionId", nextJsDistribution.DistributionId); + if (nextJsSecondDistribution is not null) + { + Output(this, "NextJsSecondDistributionDomain", nextJsSecondDistribution.DistributionDomainName); + Output(this, "NextJsSecondDistributionId", nextJsSecondDistribution.DistributionId); + } + + Output(this, "AspNetCoreFunctionName", aspNetCore.FunctionName); + Output(this, "AspNetCoreEndpointUrl", aspNetCore.DefaultEndpoint.Url); + Output(this, "AspNetCoreEndpointDomain", aspNetCore.DefaultEndpoint.DomainName); + Output(this, "AspNetCoreEndpointArn", aspNetCore.DefaultEndpoint.EndpointArn); + Output(this, "AspNetCoreAltEndpointUrl", aspNetCoreAlt.Url); + Output(this, "AspNetCoreAltEndpointDomain", aspNetCoreAlt.DomainName); + Output(this, "AspNetCoreAltEndpointArn", aspNetCoreAlt.EndpointArn); + + Output(this, "BlazorFunctionName", blazor.FunctionName); + Output(this, "BlazorEndpointUrl", blazor.DefaultEndpoint.Url); + Output(this, "BlazorEndpointDomain", blazor.DefaultEndpoint.DomainName); + Output(this, "BlazorEndpointArn", blazor.DefaultEndpoint.EndpointArn); + Output(this, "BlazorDistributionDomain", blazorDistribution.DistributionDomainName); + Output(this, "BlazorDistributionId", blazorDistribution.DistributionId); + + Output(this, "CallerRoleArn", callerRole.RoleArn); + Output(this, "DeniedRoleArn", deniedRole.RoleArn); + Output(this, "ImportedCallerImmutableRoleArn", naming.ImportedCallerImmutableRoleArn); + Output(this, "ImportedCallerMutableRoleArn", naming.ImportedCallerMutableRoleArn); + } + + /// + /// Builds a CloudFront distribution fronting one IAM-authenticated endpoint via origin access control. The + /// default behavior is uncached so dynamic responses stay live; the supplied path patterns are cached. + /// + private static Distribution CreateDistribution( + Construct scope, + string id, + IWebFunctionEndpoint endpoint, + string comment, + params string[] cachedPathPatterns) + { + // Bound once; the same origin instance is referenced by the default behavior and every cached behavior. + var origin = WebFunctionOrigin.WithOriginAccessControl(endpoint); + + var additionalBehaviors = new Dictionary(); + foreach (var pattern in cachedPathPatterns) + { + additionalBehaviors[pattern] = new BehaviorOptions + { + Origin = origin, + ViewerProtocolPolicy = ViewerProtocolPolicy.REDIRECT_TO_HTTPS, + CachePolicy = CachePolicy.CACHING_OPTIMIZED, + }; + } + + return new Distribution(scope, id, new DistributionProps + { + Comment = comment, + PriceClass = PriceClass.PRICE_CLASS_100, + DefaultBehavior = new BehaviorOptions + { + Origin = origin, + ViewerProtocolPolicy = ViewerProtocolPolicy.REDIRECT_TO_HTTPS, + AllowedMethods = AllowedMethods.ALLOW_ALL, + CachePolicy = CachePolicy.CACHING_DISABLED, + OriginRequestPolicy = OriginRequestPolicy.ALL_VIEWER_EXCEPT_HOST_HEADER, + }, + AdditionalBehaviors = additionalBehaviors, + }); + } + + private static void Output(Construct scope, string id, string value) + => _ = new CfnOutput(scope, id, new CfnOutputProps { Value = value }); +} \ No newline at end of file diff --git a/samples/web-functions/sandbox/ArtifactsStack.cs b/samples/web-functions/sandbox/ArtifactsStack.cs new file mode 100644 index 0000000..1e5ff32 --- /dev/null +++ b/samples/web-functions/sandbox/ArtifactsStack.cs @@ -0,0 +1,50 @@ +using Amazon.CDK; +using Amazon.CDK.AWS.S3; +using Constructs; + +namespace WebFunctionSandbox; + +/// +/// Owns the versioned SSE-S3 artifact bucket that the app stack consumes with the default +/// policy. It is a +/// separate stack so the scripts can deploy it and upload the artifact before the revision is created. +/// +internal sealed class ArtifactsStack : Stack +{ + public ArtifactsStack( + Construct scope, + string id, + IStackProps? props, + SandboxConfiguration configuration, + SandboxNaming naming) + : base(scope, id, props) + { + ArgumentNullException.ThrowIfNull(configuration); + ArgumentNullException.ThrowIfNull(naming); + + naming.ApplyTags(this); + + // RemovalPolicy.DESTROY and no AutoDeleteObjects: the sandbox destroy script empties every object version + // before deleting the stack, and a plain `cdk destroy` that skips that step must fail rather than silently + // delete data. Versioning is required by the Automatic bucket policy check. + ArtifactsBucket = new Bucket(this, "ArtifactsBucket", new BucketProps + { + BucketName = naming.ArtifactsBucketName, + Versioned = true, + Encryption = BucketEncryption.S3_MANAGED, + BlockPublicAccess = BlockPublicAccess.BLOCK_ALL, + EnforceSSL = true, + RemovalPolicy = RemovalPolicy.DESTROY, + AutoDeleteObjects = false, + }); + + _ = new CfnOutput(this, "ArtifactsBucketName", new CfnOutputProps + { + Value = ArtifactsBucket.BucketName, + Description = "Versioned S3 bucket holding sandbox artifacts (owned bucket, Automatic read policy).", + ExportName = $"{naming.Prefix}-artifacts-bucket-name", + }); + } + + public IBucket ArtifactsBucket { get; } +} \ No newline at end of file diff --git a/samples/web-functions/sandbox/ExternalStack.cs b/samples/web-functions/sandbox/ExternalStack.cs new file mode 100644 index 0000000..8f79ae2 --- /dev/null +++ b/samples/web-functions/sandbox/ExternalStack.cs @@ -0,0 +1,131 @@ +using System.Collections.Generic; +using Amazon.CDK; +using Amazon.CDK.AWS.IAM; +using Amazon.CDK.AWS.S3; +using Constructs; + +namespace WebFunctionSandbox; + +/// +/// Owns a pre-provisioned artifact bucket the app stack imports by name and consumes with +/// . The bucket +/// owner writes the lambda.amazonaws.com read statement here, scoped to exactly the two function +/// revisions that read from it, so the app stack adds nothing to the policy. +/// +internal sealed class ExternalStack : Stack +{ + public ExternalStack( + Construct scope, + string id, + IStackProps? props, + SandboxConfiguration configuration, + SandboxNaming naming) + : base(scope, id, props) + { + ArgumentNullException.ThrowIfNull(configuration); + ArgumentNullException.ThrowIfNull(naming); + + naming.ApplyTags(this); + + ExternalBucket = new Bucket(this, "ExternalBucket", new BucketProps + { + BucketName = naming.ExternalBucketName, + Versioned = true, + Encryption = BucketEncryption.S3_MANAGED, + BlockPublicAccess = BlockPublicAccess.BLOCK_ALL, + EnforceSSL = true, + RemovalPolicy = RemovalPolicy.DESTROY, + AutoDeleteObjects = false, + }); + + // ExternallyManaged read grants, written by the bucket owner with the same scoping the construct's + // Automatic policy would use, but narrowed to exactly the ASP.NET Core and Blazor web-function revision + // ARNs that read from this bucket - never a wildcard function name. One statement per workload keeps each + // object readable only by its own function's revisions. + ExternalBucket.AddToResourcePolicy(new PolicyStatement(new PolicyStatementProps + { + Effect = Effect.ALLOW, + Actions = ["s3:GetObject", "s3:GetObjectVersion"], + Resources = [$"{ExternalBucket.BucketArn}/{configuration.AspNetCore.ObjectKey}"], + Principals = [new ServicePrincipal("lambda.amazonaws.com")], + Conditions = new Dictionary + { + ["StringEquals"] = new Dictionary + { + ["aws:SourceAccount"] = configuration.Account, + }, + ["ArnLike"] = new Dictionary + { + ["aws:SourceArn"] = + $"arn:aws:lambda:{configuration.Region}:{configuration.Account}:web-function/{naming.AspNetCoreFunctionName}/revision/*", + }, + }, + })); + + ExternalBucket.AddToResourcePolicy(new PolicyStatement(new PolicyStatementProps + { + Effect = Effect.ALLOW, + Actions = ["s3:GetObject", "s3:GetObjectVersion"], + Resources = [$"{ExternalBucket.BucketArn}/{configuration.Blazor.ObjectKey}"], + Principals = [new ServicePrincipal("lambda.amazonaws.com")], + Conditions = new Dictionary + { + ["StringEquals"] = new Dictionary + { + ["aws:SourceAccount"] = configuration.Account, + }, + ["ArnLike"] = new Dictionary + { + ["aws:SourceArn"] = + $"arn:aws:lambda:{configuration.Region}:{configuration.Account}:web-function/{naming.BlazorFunctionName}/revision/*", + }, + }, + })); + + // Two owned roles the app stack imports by literal ARN and grants invoke with the default Automatic caller + // policy. Because each is imported (not an owned mutable identity) and its literal account matches the + // endpoint's, the library records each grant in the function's resource policy only - the callers carry no + // identity policy. One is imported with Mutable = false and one with the default (mutable), so both + // resource-policy-only sub-cases in §19.1 3.3 are exercised. + ImportedCallerImmutableRole = new Role(this, "ImportedCallerImmutableRole", new RoleProps + { + RoleName = naming.ImportedCallerImmutableRoleName, + AssumedBy = new AccountPrincipal(configuration.Account), + Description = "Sandbox role imported with Mutable = false (resource-policy-only invoke authorization).", + }); + + ImportedCallerMutableRole = new Role(this, "ImportedCallerMutableRole", new RoleProps + { + RoleName = naming.ImportedCallerMutableRoleName, + AssumedBy = new AccountPrincipal(configuration.Account), + Description = "Sandbox role imported with the default mutable setting (resource-policy-only invoke authorization).", + }); + + _ = new CfnOutput(this, "ExternalBucketName", new CfnOutputProps + { + Value = ExternalBucket.BucketName, + Description = "Versioned S3 bucket holding externally managed sandbox artifacts.", + ExportName = $"{naming.Prefix}-external-bucket-name", + }); + + _ = new CfnOutput(this, "ImportedCallerImmutableRoleArn", new CfnOutputProps + { + Value = ImportedCallerImmutableRole.RoleArn, + Description = "Literal ARN of the imported caller role created with Mutable = false.", + ExportName = $"{naming.Prefix}-imported-caller-immutable-role-arn", + }); + + _ = new CfnOutput(this, "ImportedCallerMutableRoleArn", new CfnOutputProps + { + Value = ImportedCallerMutableRole.RoleArn, + Description = "Literal ARN of the imported caller role created with the default mutable setting.", + ExportName = $"{naming.Prefix}-imported-caller-mutable-role-arn", + }); + } + + public IBucket ExternalBucket { get; } + + public IRole ImportedCallerImmutableRole { get; } + + public IRole ImportedCallerMutableRole { get; } +} \ No newline at end of file diff --git a/samples/web-functions/sandbox/Program.cs b/samples/web-functions/sandbox/Program.cs new file mode 100644 index 0000000..e6967f6 --- /dev/null +++ b/samples/web-functions/sandbox/Program.cs @@ -0,0 +1,67 @@ +using Amazon.CDK; +using WebFunctionSandbox; + +// CDK entry point. Configuration comes exclusively from SANDBOX_* environment variables (see +// SandboxConfiguration) - the app never reads or infers an ambient account or Region, so an operator must state +// the sandbox target explicitly. The AWS-mutating behaviour lives in the shell scripts, never here. +// +// The output directory follows the CDK CLI protocol (CDK_OUTDIR) when set, which also lets the scripts run a +// synthesis offline without a version-compatible CDK CLI. +var outdir = System.Environment.GetEnvironmentVariable("CDK_OUTDIR"); +var app = string.IsNullOrWhiteSpace(outdir) + ? new App() + : new App(new AppProps { Outdir = outdir }); + +SandboxConfiguration configuration; +try +{ + configuration = SandboxConfiguration.FromEnvironment(); +} +catch (SandboxConfigurationException exception) +{ + Console.Error.WriteLine(exception.Message); + return 1; +} + +var naming = new SandboxNaming(configuration); + +var stackProps = new StackProps +{ + Env = new Amazon.CDK.Environment + { + Account = configuration.Account, + Region = configuration.Region, + }, + Description = "Temporary LayeredCraft Web Function sandbox resources (T7c validation).", +}; + +ArtifactsStack? artifacts = null; +ExternalStack? external = null; + +if (configuration.BuildsArtifacts) + artifacts = new ArtifactsStack(app, naming.ArtifactsStackName, stackProps, configuration, naming); + +if (configuration.BuildsExternal) + external = new ExternalStack(app, naming.ExternalStackName, stackProps, configuration, naming); + +if (configuration.BuildsApp) +{ + // BuildsApp always implies BuildsArtifacts and BuildsExternal, so the support stacks are present. + var appStack = new AppStack(app, naming.AppStackName, stackProps, configuration, naming, artifacts!.ArtifactsBucket); + + // Explicit cross-stack dependencies so CloudFormation never creates the workloads before the buckets they + // read from exist. The scripts also order the deploys, but the CDK graph is the source of truth. + appStack.AddStackDependency(artifacts!); + appStack.AddStackDependency(external!); + + if (configuration.HasPlaceholderVersions) + { + Console.Error.WriteLine( + "WARNING: the app stack was synthesized with placeholder artifact versions " + + "(SANDBOX_ALLOW_PLACEHOLDER_VERSIONS). This synthesis must never be deployed; " + + "deploy the app stack with the real uploaded object versions."); + } +} + +app.Synth(); +return 0; \ No newline at end of file diff --git a/samples/web-functions/sandbox/README.md b/samples/web-functions/sandbox/README.md new file mode 100644 index 0000000..07230cb --- /dev/null +++ b/samples/web-functions/sandbox/README.md @@ -0,0 +1,182 @@ +# Web Function sandbox + +A temporary AWS sandbox that exercises the LayeredCraft Web Function constructs end to end. It exists to +run the approved design's AWS acceptance matrix (sections 3.1-3.8) for `LayeredCraft.Cdk.Constructs` +against a **selected existing account**, using its own fixed namespace and ownership tags, and to be torn +down afterwards. + +> **This sandbox is for validation only.** It creates real, billable AWS resources in a shared account. It +> only ever creates, updates, and deletes resources inside its own `lccdk-wf-sandbox-*` namespace and never +> touches unrelated resources. Nothing here is intended for production use. + +The sandbox app is a small C# CDK application that consumes the real library project (`WebFunctionConstruct`, +`WebFunctionEndpointConstruct`, `WebFunctionOrigin`, ...) - it does **not** re-implement any construct +behaviour with raw CloudFormation. It is intentionally excluded from the library solution and CI. + +## What it deploys + +Three stacks. Every stack name carries the fixed sandbox namespace `lccdk-wf-sandbox` **and** the sandbox id +(`lccdk-wf-sandbox--`), and every stack carries the ownership tags `lc-webfunction-sandbox-owner` +and `lc-webfunction-sandbox-id`. Buckets, functions and roles keep the shorter `-...` prefix. + +| Stack | Resources | Purpose | +| --- | --- | --- | +| `lccdk-wf-sandbox--artifacts` | versioned, SSE-S3, private S3 bucket | Owned artifact bucket used with the library's default `Automatic` code-bucket policy | +| `lccdk-wf-sandbox--external` | versioned, SSE-S3, private bucket; two IAM roles | Pre-provisioned "external" bucket (`ExternallyManaged` policy) and the imported caller roles | +| `lccdk-wf-sandbox--app` | 3 Web Functions, 4 endpoints, 2 CloudFront distributions (3 with the second distribution), 2 OACs, 5 IAM roles, 1 IAM policy, 3 log groups | Next.js standalone, ASP.NET Core (with a second endpoint), and Blazor Static SSR | + +The app stack declares an explicit CDK dependency on the artifacts and external stacks, and every deploy +synthesizes the **complete** app (all three stacks) so the support stacks keep the cross-stack exports the +app stack imports. Deploying a reduced app is what breaks repeat deployments, so it is never done. + +Workloads: + +- **Next.js standalone** - `IamAuth` default endpoint behind a CloudFront distribution using origin access + control (`WebFunctionOrigin.WithOriginAccessControl`). Dynamic document behaviour is uncached; + `/_next/static/*` is cached. +- **ASP.NET Core** (Node.js `execve` shim entrypoint) - `IamAuth` default endpoint plus an `alt` endpoint, + using the `ExternallyManaged` code-bucket policy. +- **Blazor Static SSR** - `IamAuth` default endpoint behind an OAC distribution; `/_framework/*` and + `/_content/*` are cached. + +## Prerequisites + +- The sandbox is a .NET 10 application. Its local `global.json` rolls the SDK forward so the library's + `net11.0` preview target can be referenced. +- **A CDK CLI that understands cloud assembly schema 55** (the library's `Amazon.CDK.Lib` 2.274.0 output). + This needs CLI **2.1145.0 or newer**. The scripts pin `npx --yes aws-cdk@2.1145.0` in one place + (`CDK_CLI_VERSION` in `common.sh`); override the whole command with `SANDBOX_CDK` (for example + `SANDBOX_CDK="npx --yes aws-cdk@2.1146.1"`) if you need a different build. +- **CDK bootstrap is required** in the target account/Region before the first deploy + (`npx --yes aws-cdk@2.1145.0 bootstrap aws:///`), because the app uses the modern + bootstrap (asset publishing roles + `cdk-hnb659fds-*` buckets). +- **`aws` CLI v2** (tested against 2.37.x), `curl` built with `--aws-sigv4`, `python3`, `zip`/`unzip`, and + the .NET SDK. + - The smoke tests prefer the `aws lambda-web get-resource-policy` / `get-web-function` subcommands. If your + CLI does not ship those subcommands (many 2.x builds do not), the affected checks are reported as + **BLOCKED** with the missing-API reason rather than being reported as passing. +- Build the workload artifacts first with `../build-artifacts.sh` (they land in `../build`). + +## Required AWS permissions + +The operator identity needs, scoped to the sandbox account and Region: + +- CloudFormation: create/update/delete stacks, `get-template`, `describe-stack-resources`. +- S3: create/delete versioned buckets, put/get/head objects, get/put bucket policy, get bucket versioning, + delete object versions and delete markers. +- IAM: create/delete roles and inline policies, `PassRole`, `GetRole`, `ListRolePolicies`, `GetRolePolicy`. +- Lambda (Web Functions): create/update/delete functions, revisions and endpoints, and (where the API is + available) read resource policies. +- CloudFront: create/update/delete distributions and origin access controls. +- CloudWatch Logs: create/delete the `/aws/lambda/web/*` log groups. +- `sts:AssumeRole` on the sandbox caller roles (they are created by the sandbox). + +## Safety model (why you cannot hit production by accident) + +- **Explicit target only.** `SANDBOX_ACCOUNT`, `SANDBOX_REGION`, and `SANDBOX_ID` are required. Nothing is + inferred from your ambient profile or default Region. +- **Opt-in to AWS.** Every script that touches AWS requires `SANDBOX_ALLOW_AWS=1`, and every mutating script + additionally requires `SANDBOX_ACKNOWLEDGE_SHARED_ACCOUNT=1` (you accept creating temporary sandbox + resources in the selected existing account while leaving unrelated resources untouched); without them they + exit before making a call. +- **Live identity verification.** Before any mutation the scripts call STS `get-caller-identity` and refuse + to continue unless the live account and Region match the declared sandbox exactly. Every AWS call is pinned + with `--region`, and a disagreeing ambient `AWS_REGION`/`AWS_DEFAULT_REGION` aborts, so an inherited profile + or environment variable cannot silently retarget a command. +- **Namespaced, tagged, verified names.** Stack names carry the fixed `lccdk-wf-sandbox` namespace and the + sandbox id, and every stack carries an ownership tag. Before a stack is updated or deleted the scripts read + its tags (and, when present, its `SandboxId` output) and fail closed if ownership cannot be proven - a + foreign stack is never treated as sandbox-owned. +- **Ambiguity is fatal.** A stack describe that fails for any reason other than "does not exist" (throttling, + expired credentials, `AccessDenied`) aborts the run rather than assuming the stack is gone. +- **Destructive double-gate.** `destroy.sh` requires `--yes`, `SANDBOX_CONFIRM_DESTROY=`, the + shared-account acknowledgement, and a verified sandbox-owned target, checked before any AWS call. It only + ever empties versioned objects from stack-owned buckets and lets CloudFormation delete the buckets, and it + removes the local artifact manifest only after every stack is confirmed gone. +- **No script deploys or destroys as a side effect.** Nothing runs on build or import; every action is an + explicit invocation. + +## Configuration + +| Variable | Required | Meaning | +| --- | --- | --- | +| `SANDBOX_ACCOUNT` | yes | 12-digit sandbox account id | +| `SANDBOX_REGION` | yes | sandbox Region, e.g. `us-east-1` | +| `SANDBOX_ID` | yes | 3-16 char lowercase namespace used for all names | +| `SANDBOX_ALLOW_AWS` | for AWS ops | set to `1` to opt in to AWS calls | +| `SANDBOX_ACKNOWLEDGE_SHARED_ACCOUNT` | for AWS mutations | set to `1` to confirm you accept creating temporary sandbox resources in the selected existing account without modifying unrelated resources | +| `SANDBOX_CONFIRM_DESTROY` | for destroy | must equal `SANDBOX_ID` | +| `SANDBOX_COMPONENTS` | no | `all` (default), or a comma list of `artifacts`, `external`, `app` | +| `SANDBOX_SECOND_DISTRIBUTION` | no | `1`/`true` adds a second Next.js distribution (resource-policy lifecycle) | +| `SANDBOX_CROSS_ACCOUNT_CALLER_ROLE_ARN` | no | enables the optional cross-account grant | +| `SANDBOX_ARTIFACTS_PREFIX` | no | S3 key prefix for uploaded artifacts (default: `SANDBOX_ID`) | +| `SANDBOX_CDK` | no | full CDK CLI command override instead of the pinned `npx --yes aws-cdk@` | +| `SANDBOX_ALLOW_PLACEHOLDER_VERSIONS` | internal | synthesis-only escape hatch used by the deploy/destroy lifecycle; never set it for a real deploy | + +## Step-by-step run + +```bash +export SANDBOX_ACCOUNT=111122223333 +export SANDBOX_REGION=us-east-1 +export SANDBOX_ID=wfsbx + +# 1. Prove the target is safe (validates formats; add --check-aws to verify the live identity). +./validate-env.sh + +# 2. Build the workload artifacts once. +../build-artifacts.sh + +# 3. Synthesize locally (no AWS calls) to inspect the templates. Pass --version