diff --git a/.github/.copilot/breadcrumbs/2026-11-01-0124-afd-retained-live-diagnostic.md b/.github/.copilot/breadcrumbs/2026-11-01-0124-afd-retained-live-diagnostic.md index aec4d779..1e44f8c2 100644 --- a/.github/.copilot/breadcrumbs/2026-11-01-0124-afd-retained-live-diagnostic.md +++ b/.github/.copilot/breadcrumbs/2026-11-01-0124-afd-retained-live-diagnostic.md @@ -411,9 +411,10 @@ approval, controller metadata, replica count or retained resource was changed. - Session `afd-standard-live-12/{environment,preflight,run,launch}.sh`: prior bounded isolated runner; old dates/cleanup behavior must not be reused. - Domain-knowledge/specification directories are absent. -- Microsoft Q&A question 5642906, "Azure Front Door endpoint deployment stuck at +- Microsoft Q&A question `5642906`, "Azure Front Door endpoint deployment stuck at NotStarted" (reference retired; returned HTTP 410 on 2026-11-17). - Standard/custom-domain report with a cosmetic-status reply; not ILB evidence. + Historical Standard/custom-domain report with a cosmetic-status reply, not + ILB evidence. For maintained product guidance, use the canonical FAQ below. - https://learn.microsoft.com/en-us/answers/questions/5988188/azure-front-door-premium-deployment-stuck-at-notst Premium/ACA user reports HTTP 200 while deployment NotStarted and approval Pending; no corresponding ILB/null-state proof or generally validated remedy. diff --git a/.github/.copilot/breadcrumbs/2026-11-09-1854-http-chart-and-logs-review.md b/.github/.copilot/breadcrumbs/2026-11-09-1854-http-chart-and-logs-review.md index 149b6152..8f76a770 100644 --- a/.github/.copilot/breadcrumbs/2026-11-09-1854-http-chart-and-logs-review.md +++ b/.github/.copilot/breadcrumbs/2026-11-09-1854-http-chart-and-logs-review.md @@ -338,11 +338,13 @@ already accepts absent/NotStarted/InProgress projections; endpointProgress and staging diagnostics propagate observed provisioning/deployment/enabled states into conditions. Existing bootstrap/lifecycle tests cover the behavior. No claim of a fully automatic successful live lifecycle is made: the retained -diagnostic traffic required manual activation. The supplied Microsoft Q&A -question 5642906, "Azure Front Door endpoint deployment stuck at NotStarted" -(reference retired; returned HTTP 410 on 2026-11-17), -was read and supports treating deployment projections as advisory rather than -a positive deployment-Succeeded gate; explicit failures are still rejected. +diagnostic traffic required manual activation. The review also consulted +Microsoft Q&A question `5642906`, "Azure Front Door endpoint deployment stuck at +NotStarted" (reference retired; returned HTTP 410 on 2026-11-17). +It is historical context, not a current reference or proof of automatic +convergence. Deployment projections remain advisory rather than a positive +deployment-Succeeded gate; explicit failures are still rejected. For maintained +product guidance, see the [Azure Front Door FAQ](https://learn.microsoft.com/azure/frontdoor/front-door-faq). ## Before/After Comparison diff --git a/.github/.copilot/breadcrumbs/2026-11-12-0252-http-review-live-validation.md b/.github/.copilot/breadcrumbs/2026-11-12-0252-http-review-live-validation.md new file mode 100644 index 00000000..9156ca09 --- /dev/null +++ b/.github/.copilot/breadcrumbs/2026-11-12-0252-http-review-live-validation.md @@ -0,0 +1,259 @@ +# HTTP reviewer-fix live validation + +## Requirements and authorization + +- User: "start live testing now using previous values", followed by "try again". +- Validate committed candidate `07db9bf6ad213bf23a6030a02e8bc07a09e8715e`. +- Reuse the previously authorized Sweden Central shared-VNet test topology: + hub, member-1 and member-2, two Standard_D2s_v5 nodes each. +- AFD enabled, Traffic Manager disabled, standard test-only correlated Private + Link approval enabled, retention disabled, automatic guarded cleanup. +- Fresh disposable parent: `fleet-afd-e2e-20261112-0252`; never reuse old + resources or change unrelated clusters. No Git push. + +## Plan and success criteria + +1. [x] Verify current caller, effective Owner, five execution hours plus + 75-minute cleanup reserve, 12 available vCPUs, prior-group absence and + fresh-group absence. Fail closed before writes. +2. [x] Prepare an isolated exact-commit checkout, kubeconfig, Docker + configuration and verified existing tools. Pass offline harness checks. +3. [ ] Run standard setup, five-minute role propagation wait and full baseline + plus AFD HTTP E2E. Record actual test exit and installed candidate digest. +4. [x] Capture logs and Gateway status before guarded cleanup on success, + failure or deadline. Independently verify the exact parent and three + AKS-managed resource groups absent. +5. [x] Report definitive test and teardown outcomes, including skipped + scenarios and incomplete evidence. + +## Decisions and implementation + +- Reuse the previous run's ownership-checked Azure wrapper, absolute-deadline + monitor and cleanup scripts in session-only run26 artifacts. +- New source is isolated from shared workspace and default kubeconfig. +- Use the existing default Docker builder, avoiding global builder/QEMU setup. +- Owner expiry observed at `2026-11-12T10:44:39.197Z`; execution cutoff + `2026-11-12T09:29:39.197Z`. Launch repeats admission before writes. +- Early retries returned Unauthorized. Access is restored; complete admission + and isolated preparation are in progress. No live pass is implied. + +## Validation and references + +- Full local tests, builds, lint, offline chart/script/E2E checks, Python tests, + Markdown links and native amd64 image smoke/registry checks passed before + live authorization; source remained unchanged. +- Session artifacts: `files/afd-standard-live-26` in this Copilot session. +- Previous runner and topology: + [HTTP live review validation](2026-11-09-2128-http-live-review-validation.md). +- Standard lifecycle and safety: [E2E guide](../../../test/README.md). + +## Results and unresolved risks + +Admission is complete; setup, full suite and cleanup are pending. Azure platform +convergence and successful teardown must be observed; a launcher or setup +success alone is not test proof. + +Read-only admission passed at `2026-11-12T02:53:45Z`; all 16 previous/fresh +group names were absent. DSv5 usage/limit was 0/100, regional cores 128/1230, +versus 12 required. Isolated harness/tool compatibility tests passed in +19.228s. Source and builder identity were verified without global mutations. +Launch will repeat admission. The run-scoped Windows sleep guard is released +when the launcher exits; the absolute UTC execution cutoff remains enforced. + +Launch repeated admission and started at `2026-11-12T02:59:14Z`. The tagged +parent was independently read back as Succeeded in Sweden Central. The ACR +is created and candidate image publication is underway. The launcher, +absolute-deadline monitor and work process are active; no suite result yet. +Detached shell ID: `http-live26-authorized`. + +## Setup failure and cleanup recovery + +The MCS controller image built, but registry publication failed with +`unexpected EOF`. Standard setup exited 2 before creating AKS clusters or +starting E2E; `test.exit` is absent. This is not a live test pass. + +The launcher exited 1 after recording `run.exit=2`, without cleanup/launch +completion markers. The reason for that premature launcher exit is unverified; +do not claim that automatic cleanup ran successfully. No competing owned +runner remains. + +Independent reads found the tagged parent, VNet and ACR still present, with +all three managed groups absent. A cleanup-only recovery revalidates the +original caller, current effective Owner permissions and active lease before +using the unchanged ownership-checked cleanup under an absolute deadline. +No provisioning retry or source/test change is authorized by this recovery. +Recovery shell ID: `live26-cleanup-recovery`; final absence is pending. + +Cleanup recovery exited 0. Independent Windows Azure CLI reads at +`2026-11-12T03:12:41Z` through `03:12:52Z` verified the exact parent and all +three managed groups absent. Receipt: +`logs/independent-cleanup-verification.txt` in the run26 artifacts. +No cluster existed, so Gateway status and controller logs were unavailable. +The live attempt is concluded as setup failure, not test failure or success; +the complete E2E suite remains unverified for this commit. No automatic retry. +Scheduled progress updates stop after this final verified outcome. + +## Authorized run27 retry + +User: "do another live test?" after run26 failed during registry publication. +Retry the unchanged committed source in a fresh disposable parent +`fleet-afd-e2e-20261112-0315`, with the same topology, approval behavior and +cleanup scope. No hidden provisioning retry or product-source change. + +The old Bash launcher's premature exit remains unexplained. Replace its +session-only lifecycle orchestration with an explicit Python `finally` block +that always invokes the existing ownership-checked cleanup, including after +setup failure or evidence-collection failure. Reuse the absolute UTC +deadline monitor for both work and cleanup and the scoped Windows sleep guard. +Six offline regression cases passed in 11.086s: setup failure, expired work +deadline, log collection failure, proven success, unproven success rejection +and cleanup failure propagation. + +- [x] Reverify original caller/Owner, prior/fresh-group absence and quota. +- [x] Prepare exact-commit isolated checkout and pass harness/tool checks. +- [ ] Launch standard setup/full suite and capture actual results. +- [ ] Verify parent and all managed groups absent, then report. + +Admission passed at `2026-11-12T03:18:08Z`. All 20 old/fresh group names +were absent; quota remains DSv5 0/100 and regional cores 128/1230, versus +12 required. Owner expiry and execution cutoff are unchanged. Artifacts: +`files/afd-standard-live-27`; preparation is still underway. + +Isolated harness/tool compatibility passed (17.702s). Launch repeated +admission and started `2026-11-12T03:23:14Z`; setup's own offline harness +passed (18.132s). The parent was independently read back as Succeeded, +ACR is created and candidate images are publishing. The finally-based driver +and owned work process are active. Detached shell: +`http-live27-authorized`. Progress schedule #2 runs every 15 minutes. +No actual E2E result yet. + +### Run27 final outcome + +Image publication succeeded, but hub AKS creation was denied by subscription +policy `aks1p-nodepools-azurelinux-assignment`: node pools must use AzureLinux. +The existing setup defaults did not specify that OS SKU. No policy exemption, +policy change or additional provisioning retry was attempted. + +The hardened runner performed automatic guarded cleanup successfully: +`run.exit=2`, `cleanup.exit=0`, `launch.exit=2`, `powershell.exit=2`. +`test.exit` is absent: E2E never started. Cleanup completed at +`2026-11-12T03:33:03Z`. Independent Windows Azure CLI reads from +`03:39:51Z` through `03:40:02Z` verified the exact parent and all three +managed groups absent. Receipt: run27 +`logs/independent-cleanup-verification.txt`. + +The attempt is concluded as setup failure, not a test result. Progress +schedule #2 stops. A subsequent authorized attempt must use the required +AzureLinux OS SKU without weakening subscription policy and must recheck +source, access, quota, lifetime and prior/fresh-group absence. + +## Authorized run28 retry with AzureLinux + +User: "retry" after run27's policy denial and independently verified teardown. +Fresh disposable parent: `fleet-afd-e2e-20261112-0340`. Candidate remains +`07db9bf`; topology, resource bounds, approvals and cleanup scope are unchanged. + +The session-only Azure wrapper now supplies `--os-sku AzureLinux` for every +AKS create, deduplicates matching inputs and rejects conflicting OS values +before any cloud call. It still enforces NodeImage and Standard_D2s_v5. +No subscription policy modification or exemption is requested or performed. +Installed Azure CLI help confirms AzureLinux is supported. + +- [x] Run policy-wrapper and cleanup lifecycle regressions: 10 tests passed + in 11.360s, including explicit conflicting-option rejection. +- [x] Reverify current Owner/lifetime, quota and all prior/fresh groups absent. +- [x] Prepare exact-commit isolated checkout and pass offline harness checks. +- [x] Run standard setup/full E2E and capture actual results. +- [x] Verify parent and all managed groups absent, then report. + +Artifacts: `files/afd-standard-live-28`. Initial Owner verification at +`2026-11-12T03:42:35Z` observed the same expiry/cutoff; remaining admission +and preparation are in progress. No new Azure writes yet. + +Run28 admission and isolated preparation passed; all 24 old/fresh groups +were absent, DSv5 usage/limit 0/100 and regional cores 128/1230. Offline +harness/tool compatibility passed (16.360s). Launch repeated admission and +started at `2026-11-12T03:48:00Z`; setup's harness passed (17.165s). +The tagged parent was independently read back as Succeeded, ACR is created, +and registry authentication is underway. Finally-based driver and owned +work process are active. Detached shell `http-live28-authorized`, progress +schedule #3 every 15 minutes. Actual E2E and cleanup remain pending. + +Run28 progress at `2026-11-12T04:05Z`: all three AKS clusters independently +report Succeeded, each with two Standard_D2s_v5 AzureLinux nodes. Image +publication completed and setup is installing hub/member Helm resources. +Owned driver/work processes remain active; all outcome markers are pending. +E2E has not started, so no test pass is claimed. + +Run28 progress at `2026-11-12T04:22Z`: standard setup reached its five-minute +CI-matching role propagation wait at `04:19Z`, after deploying the hub Gateway +controller Helm release and upgrading both member controllers. `e2e.log` is +not present and all five exit markers remain pending. Full E2E and teardown +are still unverified. + +Run28 progress at `2026-11-12T04:38Z`: the full 44-spec E2E suite started +around `04:24Z`. The private HTTP proof discovered both exact correlated PLS +requests, independently verified their approvals at `04:29:48Z`, and passed +post-approval owned/enabled AFD graph convergence at `04:33:30Z`. It is now +requiring fresh responses from both members with Host preservation. This is +an intermediate milestone, not a traffic or suite pass. All five exit markers +remain pending; teardown has not started. + +Run28 progress at `2026-11-12T04:56Z`: fresh private HTTP responses were +observed from member-1 (`04:49:01Z`) and member-2 (`04:50:01Z`), both +preserving the AFD request Host and carrying this fixture's proof ID. +Probe Host observations were also recorded for both members. The test +advanced at `04:50:05Z` to route withdrawal and actual endpoint disablement +verification. All exit markers remain pending; no full-suite pass or +infrastructure teardown is claimed. + +Run28 progress at `2026-11-12T05:11Z`: route withdrawal passed at +`05:02:28Z`, observing an actually Disabled endpoint, absent owned +route/origins, and sustained negative edge responses. The private HTTP spec +is now requiring controller-owned profile cleanup and persisted Gateway +removal. All five exit markers remain pending, and fixture teardown has +not started. No final spec or suite pass is claimed. + +Run28 progress at `2026-11-12T05:26Z`: the private HTTP spec passed +(`3378.156 seconds`), including controller-owned profile cleanup and +persisted Gateway removal. The suite advanced to Gateway API contract and +baseline service export/import tests; recent baseline cases are passing. +No failure markers were found in the inspected E2E log. All five exit +markers remain pending, so full-suite completion and fixture teardown +remain unverified. + +Run28 progress at `2026-11-12T05:34Z`: the standard full-suite invocation +finished successfully: `25 Passed | 0 Failed | 0 Pending | 19 Skipped`, +with Go package PASS in `3999.100s`. Both `test.exit` and `run.exit` are +0. Ownership-checked fixture cleanup has started and issued asynchronous +deletion of the exact tagged parent resource group. Cleanup, launcher and +PowerShell exit markers are pending. Independent absence verification of +the parent and all three managed groups is still required; this is not +yet a completed live-validation outcome. + +## Run28 final outcome + +The standard `make e2e-tests` invocation passed: 25 specs passed, zero failed, +19 skipped; Go package PASS in 3999.100s. Skips include Traffic Manager +(disabled for this approved fixture) and networking-disabled cases (networking +is enabled). The private HTTP proof passed both-member delivery with preserved +Host, exact-correlated Private Link approval, graph convergence, withdrawal, +profile cleanup and persisted Gateway removal. `test.exit=0`, `run.exit=0`. + +The cleanup monitor did not complete successfully: `cleanup.exit=124`, +`launch.exit=124`, `powershell.exit=124`. Its log reports stopping the owned +cleanup process group at the deadline; the cleanup log ends at asynchronous +parent deletion. Launcher output was last written at `12:38:26Z`. The reason +for this delayed monitor completion is not established; no clean harness +success or exact infrastructure deletion time is claimed. + +Independent read-only Windows Azure CLI checks at `2026-11-12T14:56:17Z` +through `14:56:32Z` returned exit 0 and `false` from `az group exists` for +the exact parent and all three AKS managed groups. The fixture, including +hub and both member clusters, is gone. Receipt: +`files/afd-standard-live-28/logs/independent-cleanup-verification.txt`. +No additional Azure writes or provisioning retries were performed. + +Live validation is concluded with passing tested behavior and independently +verified teardown, but a recorded cleanup-harness timeout. Candidate remains +`07db9bf`; no product-source changes or push. Progress schedule #3 stops. diff --git a/.github/.copilot/breadcrumbs/2026-11-16-2239-https-origins-proposal.md b/.github/.copilot/breadcrumbs/2026-11-16-2239-https-origins-proposal.md new file mode 100644 index 00000000..0cadbd50 --- /dev/null +++ b/.github/.copilot/breadcrumbs/2026-11-16-2239-https-origins-proposal.md @@ -0,0 +1,433 @@ +# HTTPS origins proposal + +## Requirements and user input + +- Baseline: merged GEP-1748/AFD commit + `4f80e9e42de24d3a775d2f877fd27b51185fde7e`. +- "Let's now work on a HTTPs origins proposal aligning with the customer howto and ux" +- Approved scope: "Approve origin-focused proposal: AFD-to-member TLS, with + frontend HTTPS documented as a separate boundary/dependency". +- "create a new PR branch (rchinchani/*) for ths" +- "use also this reference": + . +- "capture all the requirements that a customer would need to get right etc": + include an owner/evidence checklist spanning prerequisites, permissions, + networking, certificates, app/probe behavior, rollout and ongoing operations. +- "custoemr facing documentation should be a in a howto (extend the existing AFD one if it makes sense)": + put the complete checklist, customer examples and private preflight in the + existing AFD how-to; keep the design focused on the technical contract. +- "the engineering,implementation documentation can be separate which should include e2e testing requirements, etc": + include engineering work packages, dependencies, offline checks, live fixture + requirements, scenario matrix, evidence and release gates in the design doc. +- "add clarifying but brief comments wherever applicable": annotate proposed + manifests and diagnostic/test commands at the non-obvious TLS boundaries. +- "commit all changes and categorize commits similarly as PR #400 (docs, feat, build, test)": + commit the proposal/how-to as `docs(https)` and the existing HTTP live-validation + record separately as `test(http)`. No feature/build changes exist to categorize. +- "ensure that https://multicluster.sigs.k8s.io/concepts/multicluster-services-api/ API shape is not violated": + explicitly preserve public ServiceExport/ServiceImport fields and baseline + MCS behavior; distinguish existing Fleet schema differences from conformance. +- "backtlspolicy approach looks good": retain the separate policy, document + customer control through delegated hub namespace RBAC, and include complete + certificate/workload/routing examples without new TLS annotations. +- "remember this split but work only on docs(https) so reviewers can review this plan first.": + document the eventual `docs(https)`, `feat(https)`, `build(https)` and + `test(https)` split; only documentation is authorized now. +- "Also fold a79887e342ce341503dd763cd9631e609d6a6555 into the docs commit": + squash the two existing branch commits and current documentation updates into + one `docs(https)` review commit, preserving the historical validation record. + This supersedes its earlier separate `test(http)` categorization. +- Scope remains documentation only; the later request authorizes commits, not + controller implementation, Azure operations, push or PR creation. + +### Mermaid and PR update follow-up + +- "use mermaid diagrams wherever applicable instead of ascii art and update/amend PR": + replace the three topology sketches in the design/how-to with Mermaid, + retaining the separate client/origin TLS sessions and private member boundary. + Leave command-output tables as text rather than treating them as diagrams. +- This explicitly authorizes amending the single docs commit and updating the + existing PR #450 head on `rchincha/fleet-networking` branch + `rchinchani/https-origins-proposal`; no new PR or runtime work is requested. +- Validation checklist: + 1. [x] Render all three diagrams using the available Mermaid CLI and verify + that the two TLS diagrams remain consistent. + 2. [x] Check affected Markdown links, remaining text blocks and whitespace. + 3. [x] Amend the docs commit, push with an explicit expected-head lease and + verify PR #450 points at the new commit. Verified at `9cb1a22` before the + subsequent review follow-ups below. +- Validation results: + - Mermaid CLI rendered all three diagrams successfully with local Edge to + valid, nonempty SVGs outside the repository. The two TLS diagrams match. + - The configured `markdown-link-check` passed all 49 links across the design, + how-to and this breadcrumb; `git diff --check` passed. + - Fences are balanced in all eight PR Markdown files. The only remaining + `text` block is unchanged GatewayClass command output, not a topology. + - No runtime changes or live Azure/Kubernetes tests were required or run. + +### Client hostname continuity review follow-up + +- Review concern: whether an endpoint-lifetime hostname is acceptable or a + stable custom domain is still needed. User approval: "update the docs + appropriately then". +- Keep the approved generated-domain scope. Clarify that normal reconciliation + and member churn retain the endpoint/URL, while replacement may change it. + Record custom domains as a production follow-up for workloads requiring + replacement-independent identity, not as supported behavior. +- Preserve member-only customer Kubernetes access and unchanged public MCS + schemas. A CNAME alone is insufficient; the follow-up includes DNS ownership, + AFD validation/routing, certificates and replacement cutover/recovery. +- Checklist: + 1. [x] Align the design contract, customer how-to and readiness checklist. + 2. [x] Check affected Markdown links and whitespace. +- Validation: configured `markdown-link-check` passed all 49 links across the + three changed documents; `git diff --check` passed. Documentation only; + no runtime or live Azure/Kubernetes tests were required or run. + +### Explicit member-policy export review follow-up + +- Review concern: distinguish member BackendTLSPolicies intended for Fleet from + policies used by other implementations. Clarified the two objects: customers + author member Service-targeted intent; Fleet generates the hub + ServiceImport-targeted projection automatically. +- User approval: "ok, update the PR and give me a response". +- Proposed contract: require + `networking.fleet.azure.com/export-to-fleet: "true"` on the member policy. + This is explicit export consent, not exclusive ownership or a standard + controller selector. Preserve other-controller configuration/status and + resolve shared-target precedence before requiring the winner's opt-in. +- Include metadata-only opt-out invalidation without a generation change, + internal opt-in provenance, fail-closed withdrawal, customer examples, + first-party fixture guidance and regression/E2E requirements. Preserve + member-only access and unchanged public MCS schemas. +- Include the preceding hostname-continuity clarification in the same amended + docs commit. No runtime implementation, new PR or live test is authorized. +- Checklist: + 1. [x] Align design, how-to and first-party fixture documentation. + 2. [x] Validate affected links, YAML/contract examples and whitespace. + 3. [x] Amend/push the single docs commit with an explicit expected-head lease; + verify PR #450's head and give the user a review-thread reply. Verified at + `03a34c2` before the single-policy follow-up below. +- Validation results: + - Configured `markdown-link-check` passed all 58 links in the four changed + documents; `git diff --check` passed. + - Parsed seven proposed YAML resources: the member policy has the exact + string opt-in and local Service target, the route references the matching + ServiceImport/port, and the public MCS example shape is unchanged. + - Balanced fences; all three Mermaid diagrams and 31 Bash blocks are + unchanged. All fifteen TLS scenario IDs are retained. + - These are documentation checks, not admission, controller or live Azure + results. Runtime implementation remains deferred. + +### Single-policy eligibility review follow-up + +- Review concern: multiple policies are unnecessary when all but one are + ineffective. User approval: "ok update the PR". +- Supersede the preceding member-policy precedence selection with exactly one + applicable policy per Service for Fleet TLS eligibility. Count all policies + in that namespace targeting the core Service, including unmarked and + identical policies. The sole policy must explicitly opt into Fleet export. +- This is a stricter Fleet subset, not upstream oldest-policy conflict + resolution or cluster-wide admission enforcement. Multiple policies block/ + withdraw the affected AFD route; Fleet neither chooses a winner nor deletes/ + edits other implementations' policies. A single shared policy may serve + multiple implementations when their requirements agree. +- Update member watches/invalidation, diagnostics, truth table, implementation + gates, customer readiness/troubleshooting and first-party regression/E2E + requirements. Retain automatic hub projection and unchanged public MCS APIs. +- Checklist: + 1. [x] Align the design, how-to and first-party fixture contract. + 2. [x] Validate affected links, YAML/contract examples and whitespace. + 3. [x] Amend/push the single docs commit with an explicit expected-head lease; + verify PR #450's head and clean worktree. Verified at `449b3b2` before the + failure-scope follow-up below. +- Validation: configured `markdown-link-check` passed all 58 links across the + four changed documents; `git diff --check` passed. Seven proposed YAML + resources parsed, with one explicitly opted-in member policy and unchanged + public MCS example shape. Fences are balanced; three Mermaid diagrams, + 31 Bash blocks and seven YAML blocks are unchanged; all fifteen TLS scenario + IDs are retained. Superseded precedence/reselection instructions are absent + from active contract docs. No runtime/admission or live tests were run. + +### Member-local failure isolation review follow-up + +- Review concern: one member's configuration failure must not unnecessarily + cause global failure. User approval: "update the PR with all the decisions and + text". +- Supersede unconditional all-member policy agreement/route withdrawal with + complete source inventory, independent member eligibility and explicit + exclusions. Local missing/invalid/duplicate/opted-out/stale or unreadable + intent excludes only the attributable member; never silently omit it. +- Continue eligible members only after verifying excluded origins absent or + administratively disabled/removed and agreement among all otherwise eligible + intents. Conflicting valid TLS identities remain backend-wide ambiguity, + never majority selection or an exclusion chosen to manufacture agreement. +- Withdraw/suspend the affected route for no eligible origins, shared dependency/ + protocol/ownership failures, incomplete authoritative inventory or inability + to verify isolation. Health-probe failure alone is not isolation. Preserve + bounded ownership-safe operations; propagation/in-flight requests preclude + instantaneous isolation or a zero-error guarantee. +- If provider errors also prevent route suspension, expose enforcement failure + and retry/escalate; requested withdrawal is not evidence that traffic stopped. +- Report excluded identity/reason, isolation state and degraded capacity through + existing diagnostics/platform handoff, not new public MCS fields or a portable + Degraded condition. Keep runtime certificate failures distinct from observed + policy errors. Repair/re-admission needs fresh validation and agreement. +- Align aggregation/projection provenance, watches, truth table, lifecycle, + customer onboarding/readiness/troubleshooting, first-party fixture guidance + and offline/live scenario requirements. Runtime implementation remains deferred. +- Checklist: + 1. [x] Align the design, how-to and first-party fixture contract. + 2. [x] Validate affected links, examples, failure-scope consistency and whitespace. + 3. [ ] Amend/push the single docs commit with an explicit expected-head lease; + verify PR #450's head and clean worktree. Publication verification follows + commit creation and is recorded in the PR handoff. +- Validation: configured `markdown-link-check` passed all 58 links in the four + changed documents; `git diff --check` passed. Seven proposed YAML resources + parsed with unchanged opt-in, Service target, route/import/port wiring and + public MCS example shape. Fences are balanced; three Mermaid diagrams, + 31 Bash blocks and seven YAML blocks are unchanged; all fifteen TLS scenario + IDs are retained. Superseded unconditional all-member failure instructions + are absent from active contracts. These are documentation checks, not + admission/controller or live Azure validation. + +### Approved end-to-end TLS follow-up + +- "ok close that gap also since we want tls end-to-end": supersedes the + original origin-only boundary. Include client-to-AFD HTTPS in the proposal, + not merely a different client URL. +- "and make sure customer only touches member clusters (as always) and no changes to MCS api shape": + remove the optional customer hub-access workflow. Platform operators alone + manage hub Gateway/HTTPRoute/BackendTLSPolicy; application customers retain + member-only access and receive the endpoint through the platform handoff. +- "and in the user guide also add the curl example (use curl instead of curl.exe)". +- Approved hostname scope: "Generated AFD hostname only; custom domains deferred". + Azure supplies/renews the generated hostname's edge certificate; member + application certificates remain separately customer-owned. +- "also include separate test documentation (makes sense in the \"docs\" commit or the \"test\" commit) for first-party on how to get a SNI hostname and certificate/private key (OneCert?)": + add `test/https-origins-certificates.md` to the docs review and link it from + the E2E guide/engineering proposal. Cover controlled DNS identity, + conditional approved public-CA enrollment, key custody/export constraints, + certificate/key/chain checks, member deployment, rotation and negative + fixtures. Keep internal enrollment/access procedures and real identities + out of this public repository. +- Follow-up plan and success criteria: + 1. [x] Extend the contract with an explicit HTTPS/443 listener and + implementation-specific default-certificate option, HTTPS-only accepted + protocols, and unchanged MCS schemas. + 2. [x] Separate member-only customer tasks from operator-only hub tasks; + add endpoint handoff, plain HTTPS curl, certificate/lifecycle guidance + and required independent proof of both TLS hops. + 3. [x] Update offline/live validation gates, run link/YAML/command/anchor + checks, and inspect the docs-only diff. No live operations are authorized. + +The follow-up supersedes the original frontend deferral and optional customer +hub-policy access below. It does not change the documentation-only runtime +boundary or authorize Azure/certificate provisioning. + +### Follow-up implementation notes and validation + +- Extended the design and customer how-to with HTTPS/443, explicit proposed + `networking.fleet.azure.com/afd-default-certificate: "true"` under Gateway + `tls.options`, default-domain association, HTTPS-only accepted edge protocols, + no redirect, and independent HTTPS origin forwarding/probes/name checks. + The pinned v1.2.1 TLS schema permits the nonempty-options alternative to + certificate references; actual admission/runtime tests remain future work. +- Removed the customer hub-access alternative. The platform operator applies/ + reads hub resources, coordinates identity changes/cleanup and supplies the + observed HTTPS URL. Customers configure/inspect members and use plain `curl`. + No MCS API, generated manifest or controller changes were made. +- Added `test/https-origins-certificates.md` and an E2E README link. The runbook + covers first-party name reservation, conditional OneCert/public-CA enrollment, + approved key custody/exportability, certificate/key checks and negative/ + rotation fixtures. Internal enrollment/access details and real identities + are intentionally excluded from the checked-in guide. +- Configured link check passed: 73 checked links across all five changed files: + + ```powershell + npx --no-install markdown-link-check --config .github\workflows\markdown.links.config.json docs\design\gep-1748-https-origins-proposal.md docs\howtos\gateway-api-afd-configuration.md .github\.copilot\breadcrumbs\2026-11-16-2239-https-origins-proposal.md test\https-origins-certificates.md test\README.md + ``` + +- Offline Python/PyYAML validation passed: seven resource manifests; matching + HTTPS listener/options/route and unchanged example MCS shapes; certificate + mount and TLS/SNI/Host logging; 19 Bash blocks passed `bash -n`; 25 local + anchors; whitespace and balanced fences across five documents. +- These are documentation/structural checks only. No issuance, secret retrieval, + OpenSSL certificate verification, Kubernetes admission, Go tests or live + client/AFD/origin TLS execution was performed. Live proof and the exact + deployment flag/install contract remain required before release claims. + +## Plan and success criteria + +### Approved member-driven policy follow-up + +- "can the controller create this automatically, so everything is just member cluster driven?" + followed by "ok, make the doc changes then": replace manual hub policy + application with customer BackendTLSPolicy targeting the local member + Service and automatic controller-owned hub policy projection. +- Keep both TLS hops, member-only customer credentials and unchanged public + MCS shapes. Platform Gateway/HTTPRoute remains the explicit authorization + to expose a backend; policy/export creation alone must not create ingress. +- This supersedes the earlier platform-applied policy/identity handoff, not + the platform's install, ingress authorization, PLS approval or URL handoff. +- Plan and success criteria: + 1. [x] Define member selection, non-secret internal transport, cross-member + agreement, generated hub ownership and fail-closed invalidation/status. + 2. [x] Update customer manifests/setup/rotation/cleanup and first-party + fixture guidance; remove obsolete manual hub-policy steps. + 3. [x] Validate links, member/route/policy YAML references, Bash syntax, + anchors and documentation-only scope. No runtime/live operations. + +Validation: the configured five-file Markdown link-check command recorded above +passed again (73 checked links). Python/PyYAML checks passed for seven manifests: +member core-Service target/apply/rotation, unchanged MCS shapes and ServiceImport +route target, HTTPS listener/Secret/log wiring, and absence of manual hub-policy +apply/delete steps. All 15 scenario IDs, 19 Bash blocks (`bash -n` only), 25 +local anchors, whitespace/fences and `git diff --check` passed. + +The design now requires member/hub CRD and RBAC changes, non-secret internal +transport with source provenance, complete current agreement, controller-owned +projection repair/cleanup and fail-closed invalidation. It leaves the concrete +freshness/liveness bound, safe disable/upgrade mechanics and any richer durable +member readiness API as explicit implementation-review decisions. Member +diagnostics use events, never invented cross-cluster ancestors or MCS fields. +No controller, API/CRD, chart, dependency or live resource was changed in this +documentation update. +The user explicitly approved "Amend the existing docs commit" to retain one +docs review commit. Preserve the unchanged base, historical HTTP record and +required trailers; no push is authorized. + +The checklist below records the earlier review stages. + +1. [x] Inspect the merged resolver, model, provider, API and customer how-to. + Success: distinguish current HTTP behavior from future TLS support. +2. [x] Obtain approval of origin-focused documentation scope and create + `rchinchani/https-origins-proposal`. +3. [x] Draft the proposal with explicit customer/platform responsibilities, + proposed API, trust/identity, lifecycle, compatibility and validation gates. + Success: no implicit HTTP fallback or claim of frontend HTTPS support. +4. [x] Link a clearly proposed customer workflow from the current how-to. + Success: examples do not require editing generated ServiceImports. +5. [x] Check Markdown links and whitespace and inspect the complete diff. + Success: record exact results; preserve unrelated local work. +6. [x] Finish task-oriented customer setup, verification, renewal, lifecycle, + troubleshooting and cleanup examples and document the future commit split. +7. [x] Validate the final docs/examples. Success: links/anchors, YAML references, + command syntax, whitespace and code-fence checks pass without live operations. + +The requested final history rewrite folds the historical test record into the +docs review commit above unchanged base +`b48652c04f54904808da10ef10d99fcbd06c4399`. Verify one docs-only commit, preserved +historical record, required trailers and clean worktree after committing; +feature/build/test implementation and push remain outside this review. + +## Evidence and decisions + +- Current backend resolution accepts TCP with absent/http appProtocol only. + `Origin.Validate` requires a discovered internal IPv4 address. Provider + requests use HTTP forwarding and probes; setting certificate-name checks in + these HTTP requests does not implement TLS. +- Gateway API is pinned to v1.2.1. Its experimental v1alpha3 BackendTLSPolicy + permits implementation-specific non-Service targets. The user selected a + separate hub policy targeting Fleet ServiceImport, not a new annotation + on generated objects or a new member policy controller. +- The proposed first subset uses one HTTPS port and a shared certificate DNS + identity across members. Member certificates may have different keys. + Per-member identities and multi-port policy semantics are deferred. +- Existing HTTP discovery already transports appProtocol in exported ports. + Keep the private IP/PLS binding separate from TLS identity; do not replace + discovery provenance with an application-supplied hostname. +- The user-provided AFD TLS reference and the AFD ILB/Private Link guide establish + separate TLS sessions, trusted origin chains, hostname/SNI and name checks. + No custom CA upload, origin mTLS or certificate-check bypass is proposed. +- BackendTLSPolicy targeting ServiceImport is the selected design direction, not + an implemented or portable Gateway API capability. +- Upstream MCS and Fleet already differ in group and ServiceImport field + placement. Preserve Fleet's baseline without claiming upstream wire + compatibility. Existing Fleet aggregation compares complete exported port + structs including targetPort; do not promise differing member targetPorts. + +## Changes and behavior + +- Added technical design: + `docs/design/gep-1748-https-origins-proposal.md`. + Includes seven implementation work packages and fourteen E2E scenarios, + separate origin/frontend proof and explicit future test-command requirements. +- Added clearly proposed customer workflow, owner/evidence checklist and + private TLS preflight: + `docs/howtos/gateway-api-afd-configuration.md`. +- Added concise example comments distinguishing TLS intent from certificate + provisioning, Service port from workload port, SNI from Host, AFD from hub + trust, and private/offline checks from live AFD proof. +- Follow-up: selected BackendTLSPolicy, documented public MCS schema/behavior + invariants and isolation tests, and added member certificate Secret creation, + TLS workload wiring and a complete origin-TLS Gateway/HTTPRoute example. +- Final docs-review scope: task navigation, ordered file/apply workflow, + configuration versus TLS/probe verification and expected responses, + certificate renewal/reload and identity rotation, member addition/removal, + symptom/action troubleshooting and scoped cleanup. Examples remain proposed. +- The engineering plan records four future categories but feature/build/test + implementation remains deferred until a separate explicit approval. +- Before/after runtime: unchanged HTTP-only implementation. New text describes + proposed origin TLS, with frontend HTTPS separately deferred. +- Preserve the contents of the pre-existing + `.github/.copilot/breadcrumbs/2026-11-12-0252-http-review-live-validation.md`; + it was initially committed as `test(http)` and is now being folded into + `docs(https)` at the user's request. Reviewed the full record without + modifying it. Its historical live + results are not a new TLS test or a fresh validation run. + +## Validation and unresolved risks + +- Final task-oriented documentation checks passed: + + ```powershell + npx --no-install markdown-link-check --config .github\workflows\markdown.links.config.json docs\design\gep-1748-https-origins-proposal.md docs\howtos\gateway-api-afd-configuration.md .github\.copilot\breadcrumbs\2026-11-16-2239-https-origins-proposal.md .github\.copilot\breadcrumbs\2026-11-12-0252-http-review-live-validation.md + ``` + +- Link check: 47 checked links across all four documents. Offline Python checks: + 18 local anchor references; seven parsed YAML resources with cross-resource + and TLS Secret/log wiring checks; 13 proposed-guide Bash blocks passed + `bash -n`; Markdown whitespace/code fences and `git diff --check` passed. + No documented command was executed against a cluster/Azure, no NGINX workload + ran and no Kubernetes admission/runtime TLS behavior was verified. +- Follow-up configured Markdown link check passed for all three changed + documents (39 checked links across files): + + ```powershell + npx --no-install markdown-link-check --config .github\workflows\markdown.links.config.json docs\design\gep-1748-https-origins-proposal.md docs\howtos\gateway-api-afd-configuration.md .github\.copilot\breadcrumbs\2026-11-16-2239-https-origins-proposal.md + ``` + +- Follow-up Python/PyYAML checks parsed all seven proposed YAML resources and + verified export identity, generated-import boundary, policy/backend references + and certificate mount/configuration consistency. Whitespace/code-fence checks + and `git diff --check` passed. This is structural example validation, not + Kubernetes admission, a live NGINX run or AFD TLS proof. +- No runtime implementation is included; the final documentation commit will + fold the earlier documentation/history commits as explicitly requested. +- Pre-commit baseline Markdown link check passed for all four documents then + committed (36 checked links across files): + + ```powershell + npx --no-install markdown-link-check --config .github\workflows\markdown.links.config.json docs\design\gep-1748-https-origins-proposal.md docs\howtos\gateway-api-afd-configuration.md .github\.copilot\breadcrumbs\2026-11-16-2239-https-origins-proposal.md .github\.copilot\breadcrumbs\2026-11-12-0252-http-review-live-validation.md + ``` + +- `git diff --check`: passed. Explicit PowerShell trailing-whitespace and + balanced-fenced-code checks passed for all three documents, including the + two new untracked files. +- Reviewed the documentation changes and verified the requested branch. + No production code, generated artifacts, dependency manifests, + remote branches or Azure resources were changed. +- No Go or Azure tests needed for text-only work; none performed. +- Implementation still requires API/UX review, exact policy attachment/status + tests, AFD SNI/probe verification and separately approved live evidence. +- Public-trust certificates for private applications are a real customer + prerequisite, not supplied by an AFD-managed frontend certificate. + +## References + +- [Proposal](../../../docs/design/gep-1748-https-origins-proposal.md) +- [Customer how-to](../../../docs/howtos/gateway-api-afd-configuration.md) +- [Earlier broader HTTPS/native-routing plan](2026-11-01-1932-afd-https-native-routing.md) +- [AFD Private Link ILB guidance](https://learn.microsoft.com/azure/frontdoor/standard-premium/how-to-enable-private-link-internal-load-balancer) +- [Pinned BackendTLSPolicy API](https://github.com/kubernetes-sigs/gateway-api/blob/v1.2.1/apis/v1alpha3/backendtlspolicy_types.go) diff --git a/.github/.copilot/breadcrumbs/2026-11-23-1917-https-origins-implementation.md b/.github/.copilot/breadcrumbs/2026-11-23-1917-https-origins-implementation.md new file mode 100644 index 00000000..1411a1a1 --- /dev/null +++ b/.github/.copilot/breadcrumbs/2026-11-23-1917-https-origins-implementation.md @@ -0,0 +1,144 @@ +# HTTPS origins implementation + +## Requirements and authorization + +- User: "assume that an AKV, a cert and corresponding private key is available + (via env vars), go ahead and implement the \"feat\", \"build\", and \"test\" commits". +- Implement the reviewed [HTTPS contract](../../../docs/design/gep-1748-https-origins-proposal.md) + following the [review history](2026-11-16-2239-https-origins-proposal.md). +- Preserve public MCS APIs, member-only customer configuration, automatic owned + hub policy projection, platform ingress authorization and a control-plane-only hub. +- One applicable member policy, explicit Fleet export opt-in, system trust, + shared SNI, HTTPS on both hops, no downgrade/custom domains or Secret reads + by controllers. Member-local policy failure isolates the exact origin; + shared ambiguity/no eligible origins/unverifiable isolation suspends the route. +- AKV and certificate inputs are test-fixture inputs only. No live subscription, + resource group or cluster scope has been approved; do not provision, retrieve + secrets or run live tests. Do not print environment values or private material. + +## Plan and success criteria + +1. [x] Implement typed internal TLS transport, member validation/watch/heartbeat, + hub agreement/projection, model and provider HTTPS lifecycle/isolation. +2. [x] Wire default-off capability, startup prerequisites, conditional RBAC, + generated internal artifacts and charts; preserve TLS-off HTTP startup. +3. [x] Add regression tests and separately gated env-var certificate fixtures. + Run focused tests, generation/type/vet/lint and relevant controller suites. +4. [x] Partition runtime, build and test changes into three substantive commits; + verify staged contents and required trailers. No push unless requested. + +## Implementation decisions + +- Refresh member intent every minute; expire observations after five minutes. + Future timestamps beyond one minute are invalid. This bounds stale authority + during partitions without claiming immediate revocation. +- Opt-in changes are metadata updates: do not rely on policy generation alone. +- Bind a metadata-only internal heartbeat to the SHA-256 digest of the typed + snapshot (including source UID/policy observation). Preserve the snapshot + timestamp while intent is unchanged. Otherwise a minute-by-minute spec write + would invalidate the existing MCS conflict-generation acknowledgement and + spuriously withdraw healthy routes. No arbitrary member annotations propagate. +- Linux validation uses the existing WSL Go 1.26.10, matching go.mod; the host + Windows Go differs. Existing tools/envtest assets are preferred. +- Installation/manager wiring is delegated in an independent scope. Runtime, + internal API, fixtures and this record remain coordinated here. +- Owned hub policies are target-UID-bound and shared across real authorized + Gateway ancestors. Last-reference cleanup uses UID/resourceVersion + preconditions and never adopts foreign policies. +- AFD keeps Private Link identity separate from shared origin SNI, selects the + Service's HTTPS port, enables certificate-name checks, omits the Host override, + uses HTTPS GET probes and independently requires HTTPS on the frontend. + Stale origins are removed before replacements; hostname publication requires + complete provider inventory. TLS uncertainty attempts owned suspension and + preserves both the original and enforcement errors. +- Default-off manager/chart capabilities require uncached prerequisite checks. + The opt-in E2E installer upgrades the internal hub CRD first and grants each + member credential only the additional named hub-CRD read before startup. +- Member Makefile/run/image commands compile the complete manager package; + startup helpers must not be omitted by building only main.go. +- The original fixture accepted certificate/key file paths outside the checkout. + The approved [AKV CSI follow-up](2026-11-23-2121-https-akv-csi-fixture.md) + replaces that interface with AKV/Workload Identity identifiers and member-only + application mounts. Neither controllers nor runner handle private-key bytes. + +## Commit partition + +- `f04abb1` - `feat(https): reconcile validated private HTTPS origins`. +- `f12c348` - `build(https): wire opt-in capabilities and CRD-first installation`. + Manager signature/startup regression adaptations stay with their build wiring + so the intermediate manager tests compile. +- `test(https)` carries the remaining runtime/API-server regressions, Helm/script + tests, certificate fixtures, separately gated live proof and this final record. + Final worktree/trailer verification follows creation of that commit. + +### Target-branch conflict resolution + +Rebased the same four docs/feat/build/test commits onto `58e51b6` from `main`, +without adding a merge commit. The two older breadcrumb conflicts concerned +the retired Microsoft Q&A reference only. Preserved main's historical title and +HTTP-410 observation date, the proposal's current-FAQ guidance, and the explicit +warning that the old report does not prove automatic convergence. +Range-diff confirmed no changes to the runtime/build/test patches before this +record update. Post-rebase `go test ./test/scripts` and +`git diff --check origin/main..HEAD` passed; the branch remains four commits. + +## Changed files and behavior + +- `api/v1alpha1/internalserviceexport_types.go`, its generated deepcopy and + internal CRD: non-secret TLS snapshot; no public MCS API changes. +- `pkg/common/origintls`, member `serviceexport`, hub `gatewayresolver`, + `gatewaymodel`, `gateway`, `httproute` and AFD provider: policy validation, + current intent, owned projection, HTTPS configuration and verified isolation. +- Both manager packages/charts, `config/rbac/role.yaml`, `Makefile`, member + Dockerfile and E2E install/config scripts: explicit capability and prerequisites. +- Existing adjacent suites plus `origintls*_test.go`/`https_test.go`, API-server + TLS integration, chart/script tests, `test/fixtures/origintls` and the separate + `gateway_private_https_test.go`/Python application fixture: offline regressions + and opt-in live proof, without replacing HTTP tests. +- Design, customer how-to, chart READMEs and test guides distinguish this + experimental branch from released HTTP-only images and live certification. +- Before: only the HTTP graph could be provisioned. After explicit enablement: + both TLS hops and validated current member intent are mandatory. Invalid + attributable members are excluded; shared conflict/uncertainty fails closed. + The hub remains outside the data path. + +## Validation and unresolved risks + +- Passed with WSL Go 1.26.10, matching go.mod: + + ```bash + export KUBEBUILDER_ASSETS="$(hack/tools/bin/setup-envtest-release-0.22 use 1.33.0 -p path)" + go test -race ./pkg/common/origintls ./pkg/controllers/hub/gatewaymodel ./pkg/controllers/hub/gatewayresolver ./pkg/providers/azure/frontdoor ./pkg/controllers/hub/gateway ./pkg/controllers/hub/httproute ./pkg/controllers/member/serviceexport ./cmd/member-net-controller-manager ./cmd/hub-gateway-controller-manager ./test/fixtures/origintls ./test/scripts ./test/apis/v1alpha1 ./cmd/net-crd-installer/utils + go test -tags helm ./test/helm + go test -tags=e2e ./test/e2e -run "^$" + go build ./cmd/member-net-controller-manager ./cmd/hub-gateway-controller-manager + make lint + ``` + +- Passed focused `go vet` on the affected runtime, manager, fixture and script + packages; the final repository lint also runs govet/staticcheck. +- Passed `make manifests generate`; retained internal TLS/RBAC deltas only, + removing unrelated pre-existing generated-description/import drift. +- Changed Go files formatted with the repository's configured goimports. +- Passed local Markdown link/anchor and fence checks, YAML parsing, Bash syntax + (documented angle-bracket inputs substituted), changed-script syntax and Python + AST parsing. Existing Mermaid diagrams were not changed. +- Container build unverified: `docker buildx build --platform linux/amd64 --load -f + docker/member-net-controller-manager.Dockerfile --tag + fleet-networking/member-net-controller-manager:copilot-0fbf921e-https-validation .` + failed because Buildx is absent. Standard `docker build -f + docker/member-net-controller-manager.Dockerfile --tag + fleet-networking/member-net-controller-manager:copilot-0fbf921e-https-validation .` + reached the existing cache-mount instruction and failed because the legacy + builder lacks BuildKit. No replacement tool/version or Dockerfile workaround + was introduced; package builds passed. +- No live Azure operations, secret retrieval or end-to-end TLS run performed. +- Offline checks cannot establish certificate trust at AFD, application/probe + SNI/Host behavior, provider propagation or end-to-end availability. +- The complete TLS-01...TLS-15 live negative/rotation/restart/upgrade matrix is + not claimed. The live fixture covers positive traffic/probes, member opt-out, + all-ineligible withdrawal and cleanup only. +- Shared-policy reference reconciliation currently inventories hub routes on + Gateway reconciliation; large-fleet scalability is unmeasured. Sequential ARM + checks cannot exclude concurrent external writers; retain exclusive profile + ownership. No instantaneous-stop or zero-downtime migration guarantee. diff --git a/.github/.copilot/breadcrumbs/2026-11-23-2121-https-akv-csi-fixture.md b/.github/.copilot/breadcrumbs/2026-11-23-2121-https-akv-csi-fixture.md new file mode 100644 index 00000000..bab8529e --- /dev/null +++ b/.github/.copilot/breadcrumbs/2026-11-23-2121-https-akv-csi-fixture.md @@ -0,0 +1,95 @@ +# AKV CSI HTTPS fixture + +## Requirements and authorization + +- User: "ok, implement and adapt to akv csi driver method then". +- User: "also add the AKV env var then for the e2e?" +- Replace runner-local certificate/key handling with direct AKV CSI mounts in + member application pods. Keep controller/private-key and hub boundaries intact. +- Preserve the PR's four docs/feat/build/test commits when publishing. +- No live Azure environment, identity grants, secret retrieval or cleanup is + authorized. Existing AKV, certificate, CSI installation and federated identity + are prerequisites supplied by the approved test owner. + +## Plan and success criteria + +1. [x] Add validated AKV reference/identity environment inputs and a deterministic + fixture namespace compatible with preconfigured federated subjects. +2. [x] Create only member ServiceAccounts/SecretProviderClasses and mount the + exportable certificate's backing secret as a PEM bundle, without Secret sync. + Validate certificate/key/trust/name/lifetime inside the pod before serving. +3. [x] Test malformed/missing inputs, CSI pod wiring and local TLS validation; + update the customer how-to and E2E runbook; run focused checks. +4. [x] Prepare publication in the existing test commit and confirm the remote + lease/four-commit baseline. After the explicit-lease push, verify the remote + PR head, unchanged first three commits and clean worktree. + +## Decisions + +- Environment variables contain identifiers only, never PEM, keys or tokens. +- Require a fresh `https-proof-*` namespace selected before the run, so an + operator can preauthorize the exact ServiceAccount subject in both member + OIDC issuers. Never create federated credentials or Azure role assignments + from the fixture, and never reuse/delete a pre-existing namespace. +- Use CSI-native Workload Identity token requests, not node-identity fallback or + application SDK credentials. Certificate/key contents never reach the runner + or a Kubernetes Secret. The hub receives no SecretProviderClass or AKV identity. +- CSI rotation and application reload are distinct; this proof does not claim + hot reload, renewal, or a full live rotation matrix. + +## Implementation and before/after + +- `test/fixtures/origintls/csi.go` replaces the runner-local PEM loader with + validated `ORIGIN_AKV_NAME`, `ORIGIN_AKV_CERT_NAME`, `ORIGIN_AKV_TENANT_ID`, + `ORIGIN_AKV_CLIENT_ID`, optional `ORIGIN_AKV_CERT_VERSION`, and required + `ORIGIN_TLS_HOSTNAME`/`ORIGIN_TLS_NAMESPACE`. Legacy file inputs fail explicitly. +- `test/e2e/gateway_private_https_test.go` preflights fresh namespaces, the CSI + token-request audience and SPC CRD. It creates member-only identity/reference + objects and mounts the PEM backing secret directly. Namespace cleanup is bound + to the created UID. No TLS Secret, raw key, Azure grant or hub CSI object is + created. Existing traffic, probes, isolation and withdrawal proof is retained. +- `test/e2e/fixtures/https_server.py` validates the loaded key/chain with a bounded + in-memory TLS handshake, system trust, SAN/server use and seven-day lifetime + before binding the listener. It still loads certificates only at startup. +- `csi_test.go`, Python certificate tests and `test/scripts/afd_test.go` cover + missing/malformed/legacy inputs, direct CSI identity/mount wiring, script + refusal before executing commands, and nine certificate failure/success cases. + `e2e-config.sh` requires identifiers only for explicit HTTPS proof selection. +- Updated the customer how-to's NGINX workload/setup/renewal/cleanup, proposal + topology/implementation note, E2E README and certificate runbook. No controller, + chart, public MCS API, dependency or unrelated HTTP behavior changes. + +## Validation and limitations + +Passed in WSL with the repository's configured Go/tool versions: + +```bash +go test -race ./test/fixtures/origintls ./test/scripts +python3 -m unittest discover -s test/e2e/fixtures -p 'test_*.py' -v +go test -tags=e2e ./test/e2e -run "^$" +go vet ./test/fixtures/origintls ./test/scripts +go vet -tags=e2e ./test/e2e +make lint +git diff --check +``` + +- Python: nine tests, using disposable local CA/intermediate/leaf certificates. +- Configured goimports applied to the four changed Go files. +- Markdown structural checks: five current documents, 47 local links/anchors, + 49 Bash blocks (human angle-bracket inputs substituted for syntax checking), + seven YAML blocks; all passed. Python test caches removed. +- Initial script-test formatting and three lint findings were corrected before + the final passing run; no skips or suppression were added. +- No live AKV, IAM, CSI install/mount, certificate retrieval or Azure E2E run. + Offline checks do not prove deployed provider availability, identity/network + authorization, AFD trust, real traffic, renewal or rotation. +- Full runtime/envtest validation and the existing Docker Buildx/BuildKit + limitation remain recorded in the prior implementation breadcrumb. Runtime + code is unchanged by this follow-up. + +## References + +- [Prior implementation](2026-11-23-1917-https-origins-implementation.md). +- [AKS CSI Workload Identity](https://learn.microsoft.com/azure/aks/csi-secrets-store-identity-access#access-with-a-microsoft-entra-workload-id). +- [Certificate components](https://learn.microsoft.com/azure/aks/csi-secrets-store-identity-access#obtain-certificates-and-keys). +- [Rotation](https://learn.microsoft.com/azure/aks/csi-secrets-store-configuration-options). diff --git a/Makefile b/Makefile index d789c923..80a8f03c 100644 --- a/Makefile +++ b/Makefile @@ -186,7 +186,7 @@ generate: $(CONTROLLER_GEN) build: generate fmt vet ## Build binaries. go build -o bin/hub-net-controller-manager cmd/hub-net-controller-manager/main.go go build -o bin/hub-gateway-controller-manager ./cmd/hub-gateway-controller-manager - go build -o bin/member-net-controller-manager cmd/member-net-controller-manager/main.go + go build -o bin/member-net-controller-manager ./cmd/member-net-controller-manager go build -o bin/mcs-controller-manager cmd/mcs-controller-manager/main.go .PHONY: run-hub-gateway-controller-manager @@ -199,7 +199,7 @@ run-hub-net-controller-manager: manifests generate fmt vet ## Run a controllers .PHONY: run-member-net-controller-manager run-member-net-controller-manager: manifests generate fmt vet ## Run a controllers from your host. - go run ./cmd/member-net-controller-manager/main.go + go run ./cmd/member-net-controller-manager .PHONY: run-mcs-controller-manager run-mcs-controller-manager: manifests generate fmt vet ## Run a controllers from your host. diff --git a/api/v1alpha1/internalserviceexport_types.go b/api/v1alpha1/internalserviceexport_types.go index 1a0e55b1..57a228f6 100644 --- a/api/v1alpha1/internalserviceexport_types.go +++ b/api/v1alpha1/internalserviceexport_types.go @@ -39,6 +39,34 @@ type InternalServiceExportSpec struct { // Absence means unknown, including exports from older members. // +optional PrivateLinkOrigin *PrivateLinkOrigin `json:"privateLinkOrigin,omitempty"` + // OriginTLS carries only non-secret, member-observed TLS authorization. + // Absence is unknown, never permission to infer a TLS identity. + // +optional + OriginTLS *OriginTLS `json:"originTLS,omitempty"` +} + +// OriginTLS is internal transport, not a public MCS API or certificate store. +type OriginTLS struct { + Ready bool `json:"ready"` + Reason string `json:"reason"` + ObservedAt metav1.Time `json:"observedAt"` + ServiceUID string `json:"serviceUID"` + // +optional + Hostname string `json:"hostname,omitempty"` + // +optional + Trust string `json:"trust,omitempty"` + // +optional + Policy *OriginTLSPolicyReference `json:"policy,omitempty"` +} + +// OriginTLSPolicyReference binds authorization to one observed member policy. +type OriginTLSPolicyReference struct { + Namespace string `json:"namespace"` + Name string `json:"name"` + UID string `json:"uid"` + Generation int64 `json:"generation"` + ResourceVersion string `json:"resourceVersion"` + ExportToFleet string `json:"exportToFleet"` } // PrivateLinkOrigin describes the private endpoint behind an exported member Service. diff --git a/api/v1alpha1/zz_generated.deepcopy.go b/api/v1alpha1/zz_generated.deepcopy.go index 4cb17aca..6c58daba 100644 --- a/api/v1alpha1/zz_generated.deepcopy.go +++ b/api/v1alpha1/zz_generated.deepcopy.go @@ -320,6 +320,11 @@ func (in *InternalServiceExportSpec) DeepCopyInto(out *InternalServiceExportSpec *out = new(PrivateLinkOrigin) **out = **in } + if in.OriginTLS != nil { + in, out := &in.OriginTLS, &out.OriginTLS + *out = new(OriginTLS) + (*in).DeepCopyInto(*out) + } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new InternalServiceExportSpec. @@ -592,6 +597,42 @@ func (in *MultiClusterServiceStatus) DeepCopy() *MultiClusterServiceStatus { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *OriginTLS) DeepCopyInto(out *OriginTLS) { + *out = *in + in.ObservedAt.DeepCopyInto(&out.ObservedAt) + if in.Policy != nil { + in, out := &in.Policy, &out.Policy + *out = new(OriginTLSPolicyReference) + **out = **in + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new OriginTLS. +func (in *OriginTLS) DeepCopy() *OriginTLS { + if in == nil { + return nil + } + out := new(OriginTLS) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *OriginTLSPolicyReference) DeepCopyInto(out *OriginTLSPolicyReference) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new OriginTLSPolicyReference. +func (in *OriginTLSPolicyReference) DeepCopy() *OriginTLSPolicyReference { + if in == nil { + return nil + } + out := new(OriginTLSPolicyReference) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *OwnerServiceReference) DeepCopyInto(out *OwnerServiceReference) { *out = *in diff --git a/charts/hub-gateway-controller-manager/README.md b/charts/hub-gateway-controller-manager/README.md index 29a4cc36..4c8b6f64 100644 --- a/charts/hub-gateway-controller-manager/README.md +++ b/charts/hub-gateway-controller-manager/README.md @@ -19,7 +19,7 @@ broader future contract shown in some configuration examples. | Area | Current limitation | |---|---| | Listeners | Exactly one listener per Gateway | -| Protocol and port | HTTP on port 80 only; no HTTPS, TLS configuration or certificate lifecycle | +| Protocol and port | HTTP on port 80 by default; HTTPS requires the separate `enableOriginTLS` opt-in and its prerequisites below | | Hostnames | No listener or HTTPRoute hostname restrictions; uses the default AFD endpoint domain, not custom domains | | Path matching | Only `PathPrefix: /` (including the default match); no Exact or non-root paths | | Other matching | No header, query-parameter or method matching | @@ -156,6 +156,7 @@ custom domains or certificate management. |---|---|---| | `fleetSystemNamespace` | `fleet-system` | Namespace for controller workloads, identities and configuration Secret | | `afd.enabled` | `false` | Explicitly enable Gateway/Fleet controllers and cluster RBAC | +| `enableOriginTLS` | `false` | Enable HTTPS/origin TLS; requires `afd.enabled=true` and preinstalled TLS CRDs | | `afd.resourceGroup` | Empty | Required when enabled | | `afd.cloudConfigSecret.name` | Empty | Existing Secret in `fleetSystemNamespace`; required when enabled | | `afd.cloudConfigSecret.key` | `azure.json` | Selected configuration key; required when enabled | @@ -189,9 +190,68 @@ The image runs as UID/GID 65532 with a read-only root filesystem, no privilege escalation, dropped capabilities and RuntimeDefault seccomp. `/healthz` and `/readyz` are exposed on port 8083; metrics use 8082. No Service is -created. Enabled readiness requires initial synchronization of all seven watched -informers, not leadership, Azure uptime or Private Link approval. It does not -prove continuing API freshness or dataplane readiness. +created. Enabled readiness requires initial synchronization of all seven baseline +informers (plus BackendTLSPolicy when TLS is enabled), not leadership, Azure +uptime or Private Link approval. It does not prove continuing API freshness or +dataplane readiness. + +## Opt-in HTTPS installation and upgrade + +`enableOriginTLS` and the binary flag `--enable-origin-tls` default to `false`. +HTTP mode has no BackendTLSPolicy watch or experimental CRD dependency. +Enabling TLS without `afd.enabled=true` (`--enable-afd=true`) is rejected. +The feature operates in the hub control plane; public MCS APIs remain unchanged. + +Upgrade in this order: + +1. Install the release's upgraded hub InternalServiceExport CRD from + `config/crd/bases/networking.fleet.azure.com_internalserviceexports.yaml` + **before** enabling any member or hub TLS option. Its served `v1alpha1` + schema must retain `spec.originTLS`. No additional API field is needed for + the metadata-only heartbeat. +2. Explicitly install the pinned **Gateway API v1.2.1 experimental CRDs** on + the hub and participating members: + + ```bash + kubectl --context apply --server-side \ + -f https://github.com/kubernetes-sigs/gateway-api/releases/download/v1.2.1/experimental-install.yaml + ``` + + BackendTLSPolicy must be served as `gateway.networking.k8s.io/v1alpha3`; + installing only standard-channel CRDs is insufficient. +3. Enable member `enablePrivateLinkOriginDiscovery=true` and + `enableOriginTLS=true`, with the additional hub CRD-read permission + described in the [member chart](../member-net-controller-manager/README.md#opt-in-https-origin-metadata). +4. Enable this chart's `enableOriginTLS=true` alongside the existing + `afd.enabled=true` configuration. Preserve existing image, resource-group + and cloud-config settings when upgrading. + +The enabled hub checks both CRDs through its uncached API reader before +registering controllers. Missing or unserved BackendTLSPolicy versions, old +InternalServiceExport schemas, and forbidden CRD reads fail startup. Neither +manager fetches or installs CRDs dynamically. + +TLS conditionally adds BackendTLSPolicy `get/list/watch/create/update/patch/delete` +and status `get/update/patch`. The chart grants only name-scoped CRD `get` for +the two startup checks. It adds no Secret API or Azure Key Vault permissions. +Certificate/identity provisioning and any required external permissions remain +platform responsibilities. + +The one-minute freshness heartbeat is stored in the InternalServiceExport +`networking.fleet.azure.com/origin-tls-observation` annotation, bound by SHA256 +to the typed `spec.originTLS` snapshot. Unchanged TLS intent therefore does not +increment the export's generation. Existing member hub-side InternalServiceExport +update access and hub export read/watch access cover this metadata; no annotation +subresource, additional schema field or additional RBAC permission is required. + +Before disabling TLS or downgrading the hub, withdraw HTTPS Gateways/routes +while the TLS-enabled controller is running and **observe owned HTTPS cleanup**; +do not simply flip the feature off with HTTPS resources still active. +Then disable the hub option and, if desired, the member option. Member disable +publishes nil TLS metadata on reconciliation; the one-minute heartbeat and +five-minute maximum freshness bound expire stale metadata. Observe +withdrawal/expiry before removing schemas or their read permissions. Existing +HTTP reconciliation remains unaffected. ## Origin-observation diagnostics diff --git a/charts/hub-gateway-controller-manager/templates/_helpers.tpl b/charts/hub-gateway-controller-manager/templates/_helpers.tpl index a76b0759..4590b570 100644 --- a/charts/hub-gateway-controller-manager/templates/_helpers.tpl +++ b/charts/hub-gateway-controller-manager/templates/_helpers.tpl @@ -40,6 +40,9 @@ app.kubernetes.io/managed-by: {{ .Release.Service }} {{- end -}} {{- define "hub-gateway-controller-manager.validate" -}} +{{- if and .Values.enableOriginTLS (not .Values.afd.enabled) -}} +{{- fail "enableOriginTLS requires afd.enabled" -}} +{{- end -}} {{- $_ := required "image.repository must select an explicitly built/published image" (.Values.image.repository | trim) -}} {{- $_ := required "image.tag must select an explicitly built/published image" (.Values.image.tag | trim) -}} {{- if .Values.afd.enabled -}} diff --git a/charts/hub-gateway-controller-manager/templates/deployment.yaml b/charts/hub-gateway-controller-manager/templates/deployment.yaml index 80033d03..3835280c 100644 --- a/charts/hub-gateway-controller-manager/templates/deployment.yaml +++ b/charts/hub-gateway-controller-manager/templates/deployment.yaml @@ -33,6 +33,7 @@ spec: imagePullPolicy: {{ .Values.image.pullPolicy }} args: - --enable-afd={{ .Values.afd.enabled }} + - --enable-origin-tls={{ .Values.enableOriginTLS }} - --leader-elect={{ .Values.leaderElection }} - --leader-election-namespace={{ .Values.leaderElectionNamespace }} - --metrics-bind-address=:8082 diff --git a/charts/hub-gateway-controller-manager/templates/rbac.yaml b/charts/hub-gateway-controller-manager/templates/rbac.yaml index 5b147045..fa839776 100644 --- a/charts/hub-gateway-controller-manager/templates/rbac.yaml +++ b/charts/hub-gateway-controller-manager/templates/rbac.yaml @@ -37,6 +37,18 @@ metadata: name: {{ $clusterRole }} # Fleet inputs are controller-owned: observation never needs backend write access. rules: + {{- if .Values.enableOriginTLS }} + - apiGroups: ["gateway.networking.k8s.io"] + resources: ["backendtlspolicies"] + verbs: ["get", "list", "watch", "create", "update", "patch", "delete"] + - apiGroups: ["gateway.networking.k8s.io"] + resources: ["backendtlspolicies/status"] + verbs: ["get", "update", "patch"] + - apiGroups: ["apiextensions.k8s.io"] + resources: ["customresourcedefinitions"] + resourceNames: ["backendtlspolicies.gateway.networking.k8s.io", "internalserviceexports.networking.fleet.azure.com"] + verbs: ["get"] + {{- end }} - apiGroups: ["gateway.networking.k8s.io"] resources: ["gatewayclasses", "gateways", "httproutes", "referencegrants"] verbs: ["get", "list", "watch"] diff --git a/charts/hub-gateway-controller-manager/values.schema.json b/charts/hub-gateway-controller-manager/values.schema.json index f4ee0eba..a143976a 100644 --- a/charts/hub-gateway-controller-manager/values.schema.json +++ b/charts/hub-gateway-controller-manager/values.schema.json @@ -9,6 +9,7 @@ "pattern": "^[a-z0-9]([-a-z0-9]*[a-z0-9])?$" }, "replicaCount": {"type": "integer", "minimum": 1}, + "enableOriginTLS": {"type": "boolean"}, "leaderElection": {"type": "boolean"}, "leaderElectionNamespace": { "type": "string", diff --git a/charts/hub-gateway-controller-manager/values.yaml b/charts/hub-gateway-controller-manager/values.yaml index f793e200..975c0e02 100644 --- a/charts/hub-gateway-controller-manager/values.yaml +++ b/charts/hub-gateway-controller-manager/values.yaml @@ -3,6 +3,9 @@ fleetSystemNamespace: fleet-system nameOverride: "" fullnameOverride: "" +# Requires afd.enabled and preinstalled origin TLS CRDs. +enableOriginTLS: false + # Select an image explicitly; verify that the chosen release has been published. image: repository: "" diff --git a/charts/member-net-controller-manager/README.md b/charts/member-net-controller-manager/README.md index c9a4acc0..214c226f 100644 --- a/charts/member-net-controller-manager/README.md +++ b/charts/member-net-controller-manager/README.md @@ -116,6 +116,7 @@ helm upgrade member-net-controller-manager ./charts/member-net-controller-manage | tolerations | The toleration to use for pod scheduling | `[]` | | enableTrafficManagerFeature | Set to true to enable the Azure Traffic Manager feature. | `false` | | enablePrivateLinkOriginDiscovery | Discover ILB/PLS origins for Zero-Public-Exposure Ingress independently of Traffic Manager. | `false` | +| enableOriginTLS | Publish private-origin TLS metadata; requires private-origin discovery and preinstalled TLS CRDs. | `false` | | enableNetworkingFeatures | Set to true to enable Networking Controllers on member cluster. | `true` | | azureCloudConfig | The Azure cloud provider configuration | **required if Traffic Manager or private-origin discovery is enabled** | @@ -216,4 +217,86 @@ connection has been approved. **AFD approval remains asynchronous and separately owned.** Gateway reconciliation and traffic programming are later implementation phases. +## Opt-in HTTPS origin metadata + +`enableOriginTLS=false` is the safe default (`--enable-origin-tls=false`). +It adds no BackendTLSPolicy watch or experimental CRD dependency. Enabling it +requires `enablePrivateLinkOriginDiscovery=true`; Traffic Manager is independent. +This is hub control-plane metadata, not a change to the public MCS APIs or the +HTTP service export contract. + +Before enabling TLS: + +1. Upgrade the hub InternalServiceExport CRD first, using the release's + `config/crd/bases/networking.fleet.azure.com_internalserviceexports.yaml`. + Verify that the served `v1alpha1` schema includes `spec.originTLS`; an older + schema prunes this metadata. +2. Explicitly install the pinned **Gateway API v1.2.1 experimental CRDs** on + participating members and the hub, including BackendTLSPolicy served as + `v1alpha3`: + + ```bash + kubectl --context apply --server-side \ + -f https://github.com/kubernetes-sigs/gateway-api/releases/download/v1.2.1/experimental-install.yaml + ``` + +3. Give the member's **hub credential identity** cluster-scoped `get` access to + just `internalserviceexports.networking.fleet.azure.com` in the + `apiextensions.k8s.io/customresourcedefinitions` resource. Its existing + reserved-member-namespace Role cannot grant access to cluster-scoped CRDs. + For the `User` identity in the hub setup above, the additional hub RBAC is: + + ```yaml + apiVersion: rbac.authorization.k8s.io/v1 + kind: ClusterRole + metadata: + name: fleet-origin-tls-schema-reader + rules: + - apiGroups: ["apiextensions.k8s.io"] + resources: ["customresourcedefinitions"] + resourceNames: ["internalserviceexports.networking.fleet.azure.com"] + verbs: ["get"] + --- + apiVersion: rbac.authorization.k8s.io/v1 + kind: ClusterRoleBinding + metadata: + name: fleet-origin-tls-schema-reader- + roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: fleet-origin-tls-schema-reader + subjects: + - kind: User + name: + ``` + + Bind the actual hub credential identity (use a ServiceAccount subject with + its namespace when applicable), not the local member workload identity. + The member chart already grants local CRD reads for its installer; TLS adds + only BackendTLSPolicy `get/list/watch`, with no policy writes, additional + Secret permissions or Azure Key Vault access. +4. Upgrade members with `--set enableOriginTLS=true` and + `--set enablePrivateLinkOriginDiscovery=true`, then enable the + [hub TLS option](../hub-gateway-controller-manager/README.md#opt-in-https-installation-and-upgrade). + +At startup, enabled members verify the member BackendTLSPolicy served version +and hub InternalServiceExport schema using uncached API readers. Missing CRDs, +old schemas or denied reads fail startup; managers never fetch or install CRDs +on demand. + +The one-minute heartbeat updates the InternalServiceExport +`networking.fleet.azure.com/origin-tls-observation` annotation, bound by SHA256 +to its typed `spec.originTLS` snapshot. Unchanged intent does not increment the +export generation. The member's existing hub-side InternalServiceExport update +permission covers the annotation; no additional API field or permission is +needed for heartbeats. + +For disable/downgrade, first withdraw HTTPS Gateways/routes while the TLS-enabled +hub is running and observe owned HTTPS cleanup. Only then disable or downgrade +the hub. Disabling members clears their published `originTLS` metadata on +reconciliation; the one-minute heartbeat and five-minute maximum freshness +bound prevent stale metadata from remaining eligible indefinitely. Wait for +observed withdrawal/expiry before removing schemas or related access. HTTP +exports remain unaffected. + ## Contributing Changes diff --git a/charts/member-net-controller-manager/templates/deployment.yaml b/charts/member-net-controller-manager/templates/deployment.yaml index 91a66a01..74b117a4 100644 --- a/charts/member-net-controller-manager/templates/deployment.yaml +++ b/charts/member-net-controller-manager/templates/deployment.yaml @@ -1,3 +1,9 @@ +{{- if not (kindIs "bool" .Values.enableOriginTLS) }} +{{- fail "enableOriginTLS must be a boolean" }} +{{- end }} +{{- if and .Values.enableOriginTLS (not .Values.enablePrivateLinkOriginDiscovery) }} +{{- fail "enableOriginTLS requires enablePrivateLinkOriginDiscovery" }} +{{- end }} apiVersion: apps/v1 kind: Deployment metadata: @@ -44,6 +50,7 @@ spec: - --add_dir_header - --enable-traffic-manager-feature={{ .Values.enableTrafficManagerFeature }} - --enable-private-link-origin-discovery={{ .Values.enablePrivateLinkOriginDiscovery }} + - --enable-origin-tls={{ .Values.enableOriginTLS }} - --enable-networking-features={{ .Values.enableNetworkingFeatures }} {{- if or .Values.enableTrafficManagerFeature .Values.enablePrivateLinkOriginDiscovery }} - --cloud-config=/etc/kubernetes/provider/azure.json diff --git a/charts/member-net-controller-manager/templates/rbac.yaml b/charts/member-net-controller-manager/templates/rbac.yaml index af0ce2da..f212d3f2 100644 --- a/charts/member-net-controller-manager/templates/rbac.yaml +++ b/charts/member-net-controller-manager/templates/rbac.yaml @@ -4,6 +4,16 @@ metadata: creationTimestamp: null name: {{ include "member-net-controller-manager.fullname" . }}-role rules: +{{- if .Values.enableOriginTLS }} +- apiGroups: + - gateway.networking.k8s.io + resources: + - backendtlspolicies + verbs: + - get + - list + - watch +{{- end }} - apiGroups: - coordination.k8s.io resources: diff --git a/charts/member-net-controller-manager/values.yaml b/charts/member-net-controller-manager/values.yaml index fef40a1b..31918d17 100644 --- a/charts/member-net-controller-manager/values.yaml +++ b/charts/member-net-controller-manager/values.yaml @@ -65,6 +65,8 @@ affinity: {} enableTrafficManagerFeature: false # Independent of Traffic Manager; requires Azure LB/PLS read permissions. enablePrivateLinkOriginDiscovery: false +# Requires private-origin discovery and preinstalled origin TLS CRDs. +enableOriginTLS: false enableNetworkingFeatures: true azureCloudConfig: diff --git a/cmd/hub-gateway-controller-manager/main.go b/cmd/hub-gateway-controller-manager/main.go index 74a3cd5f..2d7dade7 100644 --- a/cmd/hub-gateway-controller-manager/main.go +++ b/cmd/hub-gateway-controller-manager/main.go @@ -24,6 +24,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/log/zap" metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server" gatewayv1 "sigs.k8s.io/gateway-api/apis/v1" + gatewayv1alpha3 "sigs.k8s.io/gateway-api/apis/v1alpha3" gatewayv1beta1 "sigs.k8s.io/gateway-api/apis/v1beta1" "go.goms.io/fleet/pkg/utils/cloudconfig/azure" @@ -43,6 +44,7 @@ var ( leaderElectionNamespace = flag.String("leader-election-namespace", "fleet-system", "The namespace used for leader election.") enableAFD = flag.Bool("enable-afd", false, "Enable Gateway API reconciliation and AFD Premium private HTTP provisioning, observation and owned cleanup; enabling performs Azure writes.") + enableOriginTLS = flag.Bool("enable-origin-tls", false, "Enable HTTPS origin reconciliation; requires enable-afd and installed TLS CRDs.") cloudConfigFile = flag.String("cloud-config", "/etc/kubernetes/provider/azure.json", "The Azure cloud configuration file.") afdResourceGroup = flag.String("afd-resource-group", "", "The resource group in which the controller manages Azure Front Door resources.") ) @@ -72,6 +74,7 @@ func currentOptions() managerOptions { leaderElection: *enableLeaderElection, leaderElectionNamespace: *leaderElectionNamespace, enableAFD: *enableAFD, + enableOriginTLS: *enableOriginTLS, cloudConfigFile: *cloudConfigFile, afdResourceGroup: *afdResourceGroup, } @@ -83,6 +86,7 @@ type managerOptions struct { leaderElection bool leaderElectionNamespace string enableAFD bool + enableOriginTLS bool cloudConfigFile string afdResourceGroup string } @@ -94,7 +98,7 @@ type dependencies struct { loadAFDConfig func(string, string) (*azure.CloudConfig, error) newScheme func() (*runtime.Scheme, error) newAFDProviders func(*azure.CloudConfig, string) (afdProviders, error) - setupControllers func(context.Context, ctrl.Manager, afdProviders) error + setupControllers func(context.Context, ctrl.Manager, afdProviders, bool) error } func productionDependencies() dependencies { @@ -112,6 +116,9 @@ func productionDependencies() dependencies { } func run(options managerOptions, deps dependencies) error { + if options.enableOriginTLS && !options.enableAFD { + return errors.New("enable-origin-tls requires enable-afd") + } scheme, err := deps.newScheme() if err != nil { return fmt.Errorf("register controller schemes: %w", err) @@ -149,8 +156,13 @@ func run(options managerOptions, deps dependencies) error { } ctx := deps.signalHandler() + if options.enableOriginTLS { + if err := validateOriginTLSCRDs(ctx, mgr.GetAPIReader(), mgr.GetAPIReader()); err != nil { + return fmt.Errorf("validate origin TLS prerequisites: %w", err) + } + } if options.enableAFD { - if err := deps.setupControllers(ctx, mgr, providers); err != nil { + if err := deps.setupControllers(ctx, mgr, providers, options.enableOriginTLS); err != nil { return fmt.Errorf("register Gateway controllers: %w", err) } klog.InfoS("Gateway private HTTP reconciliation, origin observation and owned AFD cleanup registered; Private Link approval is asynchronous") @@ -170,7 +182,7 @@ func run(options managerOptions, deps dependencies) error { return nil } -func setupControllers(ctx context.Context, mgr ctrl.Manager, providers afdProviders) error { +func setupControllers(ctx context.Context, mgr ctrl.Manager, providers afdProviders, originTLS bool) error { if err := providers.validate(); err != nil { return err } @@ -187,15 +199,16 @@ func setupControllers(ctx context.Context, mgr ctrl.Manager, providers afdProvid OriginObserver: providers.observer, HTTPProvisioner: providers.provisioner, Recorder: mgr.GetEventRecorder("gateway"), + EnableOriginTLS: originTLS, }).SetupWithManager}, - {"HTTPRoute", (&httproute.Reconciler{Client: mgr.GetClient()}).SetupWithManager}, + {"HTTPRoute", (&httproute.Reconciler{Client: mgr.GetClient(), EnableOriginTLS: originTLS}).SetupWithManager}, } for _, controller := range controllers { if err := controller.setup(mgr); err != nil { return fmt.Errorf("register %s reconciler: %w", controller.name, err) } } - return registerGatewayCacheReadiness(ctx, mgr) + return registerGatewayCacheReadiness(ctx, mgr, originTLS) } func newScheme() (*runtime.Scheme, error) { @@ -205,6 +218,7 @@ func newScheme() (*runtime.Scheme, error) { gatewayv1.Install, // ReferenceGrant remains v1beta1 in Gateway API v1.2.1. gatewayv1beta1.Install, + gatewayv1alpha3.Install, fleetnetv1alpha1.AddToScheme, } for _, install := range installers { diff --git a/cmd/hub-gateway-controller-manager/main_test.go b/cmd/hub-gateway-controller-manager/main_test.go index 5842ebbb..9f480254 100644 --- a/cmd/hub-gateway-controller-manager/main_test.go +++ b/cmd/hub-gateway-controller-manager/main_test.go @@ -12,6 +12,7 @@ import ( "net/http" "os" "path/filepath" + "reflect" "strings" "testing" @@ -21,8 +22,10 @@ import ( "k8s.io/client-go/rest" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/cache" + "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/healthz" gatewayv1 "sigs.k8s.io/gateway-api/apis/v1" + gatewayv1alpha3 "sigs.k8s.io/gateway-api/apis/v1alpha3" gatewayv1beta1 "sigs.k8s.io/gateway-api/apis/v1beta1" "go.goms.io/fleet/pkg/utils/cloudconfig/azure" @@ -42,6 +45,10 @@ func TestNewScheme_RegistersGatewayAndFleetTypes(t *testing.T) { name string gvk schema.GroupVersionKind }{ + { + name: "BackendTLSPolicy", + gvk: gatewayv1alpha3.SchemeGroupVersion.WithKind("BackendTLSPolicy"), + }, { name: "Gateway", gvk: gatewayv1.SchemeGroupVersion.WithKind("Gateway"), @@ -97,6 +104,7 @@ func TestCurrentOptions_UsesCommandLineConfiguration(t *testing.T) { got.leaderElection != *enableLeaderElection || got.leaderElectionNamespace != *leaderElectionNamespace || got.enableAFD != *enableAFD || + got.enableOriginTLS != *enableOriginTLS || got.cloudConfigFile != *cloudConfigFile || got.afdResourceGroup != *afdResourceGroup { t.Errorf("currentOptions() = %#v, want values from command-line flags", got) @@ -109,6 +117,7 @@ func TestFeatureFlagDefaults(t *testing.T) { want string }{ {name: "enable-afd", want: "false"}, + {name: "enable-origin-tls", want: "false"}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { @@ -150,12 +159,37 @@ func TestRun_ManagesStartupLifecycle(t *testing.T) { nilCleanup bool nilObserver bool nilProvisioner bool + crdReadError error + wantCRDReads int wantError string wantConfigLoads int wantManagerStarts int wantRegistrations int wantInitializations int }{ + { + name: "origin TLS requires provisioning", + options: managerOptions{enableOriginTLS: true}, + wantError: "enable-origin-tls requires enable-afd", + }, + { + name: "enabled TLS validates CRDs before registering controllers", + options: managerOptions{enableAFD: true, enableOriginTLS: true}, + wantConfigLoads: 1, + wantManagerStarts: 1, + wantRegistrations: 1, + wantInitializations: 1, + wantCRDReads: 2, + }, + { + name: "denied CRD read stops TLS startup", + options: managerOptions{enableAFD: true, enableOriginTLS: true}, + crdReadError: errors.New("forbidden"), + wantError: "validate origin TLS prerequisites", + wantConfigLoads: 1, + wantInitializations: 1, + wantCRDReads: 1, + }, { name: "scheme registration failure stops startup", schemeError: errors.New("scheme failed"), @@ -267,11 +301,20 @@ func TestRun_ManagesStartupLifecycle(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { + reader := &originTLSCRDReader{err: tt.crdReadError, objects: map[string]map[string]interface{}{ + "backendtlspolicies.gateway.networking.k8s.io": {"name": "v1alpha3", "served": true}, + "internalserviceexports.networking.fleet.azure.com": originTLSExportVersion(), + }} + informerCache := newReadinessTestCache() + if tt.options.enableOriginTLS { + informerCache.informers[reflect.TypeOf(&gatewayv1alpha3.BackendTLSPolicy{})] = &readinessTestInformer{} + } manager := &fakeControllerManager{ healthError: tt.healthError, readyError: tt.readyError, startError: tt.startError, - informerCache: newReadinessTestCache(), + informerCache: informerCache, + apiReader: reader, } configLoads := 0 registrations := 0 @@ -330,7 +373,10 @@ func TestRun_ManagesStartupLifecycle(t *testing.T) { } return newScheme() }, - setupControllers: func(ctx context.Context, got ctrl.Manager, providers afdProviders) error { + setupControllers: func(ctx context.Context, got ctrl.Manager, providers afdProviders, originTLS bool) error { + if originTLS != tt.options.enableOriginTLS { + t.Error("controller registration received a different origin TLS option") + } if got != manager { t.Error("registered controllers on a different manager") } @@ -341,25 +387,20 @@ func TestRun_ManagesStartupLifecycle(t *testing.T) { if tt.setupError != nil { return tt.setupError } - return registerGatewayCacheReadiness(ctx, got) + return registerGatewayCacheReadiness(ctx, got, originTLS) }, } err := run(tt.options, deps) - if tt.wantError != "" { - if err == nil { - t.Fatalf("run() error = nil, want containing %q", tt.wantError) - } - if !strings.Contains(err.Error(), tt.wantError) { - t.Errorf("run() error = %q, want containing %q", err, tt.wantError) - } - } else if err != nil { - t.Fatalf("run() error = %v", err) - } + assertStartupError(t, err, tt.wantError) if configLoads != tt.wantConfigLoads { t.Errorf("Azure configuration loads = %d, want %d", configLoads, tt.wantConfigLoads) } + + if reader.reads != tt.wantCRDReads { + t.Errorf("startup CRD reads = %d, want %d", reader.reads, tt.wantCRDReads) + } if manager.starts != tt.wantManagerStarts { t.Errorf("manager starts = %d, want %d", manager.starts, tt.wantManagerStarts) } @@ -379,6 +420,22 @@ func TestRun_ManagesStartupLifecycle(t *testing.T) { } } +func assertStartupError(t *testing.T, err error, want string) { + t.Helper() + if want == "" { + if err != nil { + t.Fatalf("run() error = %v", err) + } + return + } + if err == nil { + t.Fatalf("run() error = nil, want containing %q", want) + } + if !strings.Contains(err.Error(), want) { + t.Errorf("run() error = %q, want containing %q", err, want) + } +} + func TestLoadAFDConfiguration_RejectsInvalidInput(t *testing.T) { tests := []struct { name string @@ -464,7 +521,7 @@ func TestLoadAFDConfiguration_RejectsMissingSubscription(t *testing.T) { func TestSetupControllers_RegistersWithoutContactingAPIServer(t *testing.T) { mgr := newReadinessTestManager(t) provider := &managerProfileCleaner{} - if err := setupControllers(context.Background(), mgr, afdProviders{cleanup: provider, observer: provider, provisioner: provider}); err != nil { + if err := setupControllers(context.Background(), mgr, afdProviders{cleanup: provider, observer: provider, provisioner: provider}, false); err != nil { t.Fatalf("register runtime controllers: %v", err) } if mgr.check == nil || mgr.checkName != gatewayCacheReadinessCheck { @@ -545,9 +602,14 @@ type fakeControllerManager struct { healthChecks map[string]healthz.Checker readyChecks map[string]healthz.Checker informerCache cache.Cache + apiReader client.Reader cacheRequests int } +func (f *fakeControllerManager) GetAPIReader() client.Reader { + return f.apiReader +} + func (f *fakeControllerManager) GetCache() cache.Cache { f.cacheRequests++ return f.informerCache @@ -621,10 +683,10 @@ func TestCleanupInitializationRejectsMissingDependencies(t *testing.T) { return err }}, {"missing cleanup provider", func() error { - return setupControllers(context.Background(), nil, afdProviders{}) + return setupControllers(context.Background(), nil, afdProviders{}, false) }}, {"missing observer", func() error { - return setupControllers(context.Background(), nil, afdProviders{cleanup: &managerProfileCleaner{}}) + return setupControllers(context.Background(), nil, afdProviders{cleanup: &managerProfileCleaner{}}, false) }}, } for _, tt := range tests { diff --git a/cmd/hub-gateway-controller-manager/origin_tls.go b/cmd/hub-gateway-controller-manager/origin_tls.go new file mode 100644 index 00000000..51a0d046 --- /dev/null +++ b/cmd/hub-gateway-controller-manager/origin_tls.go @@ -0,0 +1,64 @@ +/* +Copyright (c) Microsoft Corporation. +Licensed under the MIT license. +*/ + +package main + +import ( + "context" + "fmt" + "time" + + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime/schema" + "sigs.k8s.io/controller-runtime/pkg/client" +) + +// Readers must bypass the managers' caches: these checks run before cache startup. +func validateOriginTLSCRDs(ctx context.Context, policyReader, exportReader client.Reader) error { + ctx, cancel := context.WithTimeout(ctx, 15*time.Second) + defer cancel() + checks := []struct { + reader client.Reader + name string + version string + field []string + }{ + {policyReader, "backendtlspolicies.gateway.networking.k8s.io", "v1alpha3", nil}, + {exportReader, "internalserviceexports.networking.fleet.azure.com", "v1alpha1", + []string{"schema", "openAPIV3Schema", "properties", "spec", "properties", "originTLS"}}, + } + for _, check := range checks { + crd := &unstructured.Unstructured{} + crd.SetGroupVersionKind(schema.GroupVersionKind{ + Group: "apiextensions.k8s.io", Version: "v1", Kind: "CustomResourceDefinition", + }) + if err := check.reader.Get(ctx, client.ObjectKey{Name: check.name}, crd); err != nil { + return fmt.Errorf("read required origin TLS CRD %s: %w", check.name, err) + } + versions, _, err := unstructured.NestedSlice(crd.Object, "spec", "versions") + if err != nil { + return fmt.Errorf("read versions of origin TLS CRD %s: %w", check.name, err) + } + ready := false + for _, raw := range versions { + version, ok := raw.(map[string]interface{}) + if !ok || version["name"] != check.version || version["served"] != true { + continue + } + ready = true + if len(check.field) > 0 { + _, ready, err = unstructured.NestedMap(version, check.field...) + if err != nil { + return fmt.Errorf("read originTLS schema in %s: %w", check.name, err) + } + } + break + } + if !ready { + return fmt.Errorf("origin TLS requires %s serving %s with the required schema; install upgraded CRDs before enabling", check.name, check.version) + } + } + return nil +} diff --git a/cmd/hub-gateway-controller-manager/origin_tls_test.go b/cmd/hub-gateway-controller-manager/origin_tls_test.go new file mode 100644 index 00000000..c3ee5516 --- /dev/null +++ b/cmd/hub-gateway-controller-manager/origin_tls_test.go @@ -0,0 +1,87 @@ +/* +Copyright (c) Microsoft Corporation. +Licensed under the MIT license. +*/ + +package main + +import ( + "context" + "errors" + "strings" + "testing" + + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "sigs.k8s.io/controller-runtime/pkg/client" +) + +func TestValidateOriginTLSCRDs(t *testing.T) { + tests := []struct { + name string + policy map[string]interface{} + export map[string]interface{} + readError error + wantError string + }{ + {name: "both required served schemas", policy: map[string]interface{}{"name": "v1alpha3", "served": true}, export: originTLSExportVersion()}, + {name: "missing policy CRD", wantError: "backendtlspolicies"}, + {name: "denied CRD read", readError: errors.New("forbidden"), wantError: "forbidden"}, + {name: "wrong policy version", policy: map[string]interface{}{"name": "v1alpha2", "served": true}, wantError: "v1alpha3"}, + {name: "unserved policy version", policy: map[string]interface{}{"name": "v1alpha3", "served": false}, wantError: "v1alpha3"}, + {name: "missing internal CRD", policy: map[string]interface{}{"name": "v1alpha3", "served": true}, wantError: "internalserviceexports"}, + {name: "old internal schema", policy: map[string]interface{}{"name": "v1alpha3", "served": true}, + export: map[string]interface{}{"name": "v1alpha1", "served": true}, wantError: "required schema"}, + {name: "unserved internal schema", policy: map[string]interface{}{"name": "v1alpha3", "served": true}, + export: map[string]interface{}{"name": "v1alpha1", "served": false}, wantError: "v1alpha1"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + reader := &originTLSCRDReader{err: tt.readError, objects: map[string]map[string]interface{}{ + "backendtlspolicies.gateway.networking.k8s.io": tt.policy, + "internalserviceexports.networking.fleet.azure.com": tt.export, + }} + err := validateOriginTLSCRDs(context.Background(), reader, reader) + if tt.wantError == "" && err != nil { + t.Fatal(err) + } + if tt.wantError != "" && (err == nil || !strings.Contains(err.Error(), tt.wantError)) { + t.Fatalf("validation error = %v, want %q", err, tt.wantError) + } + }) + } +} + +func originTLSExportVersion() map[string]interface{} { + return map[string]interface{}{ + "name": "v1alpha1", "served": true, + "schema": map[string]interface{}{"openAPIV3Schema": map[string]interface{}{ + "properties": map[string]interface{}{"spec": map[string]interface{}{ + "properties": map[string]interface{}{"originTLS": map[string]interface{}{"type": "object"}}, + }}, + }}, + } +} + +type originTLSCRDReader struct { + client.Reader + objects map[string]map[string]interface{} + err error + reads int +} + +func (r *originTLSCRDReader) Get(ctx context.Context, key client.ObjectKey, object client.Object, _ ...client.GetOption) error { + r.reads++ + if _, ok := ctx.Deadline(); !ok { + return errors.New("startup CRD read must have a deadline") + } + if r.err != nil { + return r.err + } + version := r.objects[key.Name] + if version == nil { + return errors.New("CRD not found") + } + crd := object.(*unstructured.Unstructured) + crd.Object["spec"] = map[string]interface{}{"versions": []interface{}{version}} + return nil +} diff --git a/cmd/hub-gateway-controller-manager/readiness.go b/cmd/hub-gateway-controller-manager/readiness.go index 1f71783f..18acff14 100644 --- a/cmd/hub-gateway-controller-manager/readiness.go +++ b/cmd/hub-gateway-controller-manager/readiness.go @@ -15,6 +15,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/cache" "sigs.k8s.io/controller-runtime/pkg/client" gatewayv1 "sigs.k8s.io/gateway-api/apis/v1" + gatewayv1alpha3 "sigs.k8s.io/gateway-api/apis/v1alpha3" gatewayv1beta1 "sigs.k8s.io/gateway-api/apis/v1beta1" fleetnetv1alpha1 "go.goms.io/fleet-networking/api/v1alpha1" @@ -22,7 +23,7 @@ import ( const gatewayCacheReadinessCheck = "gateway-cache" -func registerGatewayCacheReadiness(ctx context.Context, mgr ctrl.Manager) error { +func registerGatewayCacheReadiness(ctx context.Context, mgr ctrl.Manager, originTLS bool) error { objects := []client.Object{ &gatewayv1.GatewayClass{}, &gatewayv1.Gateway{}, @@ -32,6 +33,9 @@ func registerGatewayCacheReadiness(ctx context.Context, mgr ctrl.Manager) error &fleetnetv1alpha1.InternalServiceExport{}, &corev1.Namespace{}, } + if originTLS { + objects = append(objects, &gatewayv1alpha3.BackendTLSPolicy{}) + } informers := make([]cache.Informer, 0, len(objects)) informerCache := mgr.GetCache() // Create every watched informer before startup; an empty cache can sync diff --git a/cmd/hub-gateway-controller-manager/readiness_test.go b/cmd/hub-gateway-controller-manager/readiness_test.go index af7017ff..943814b7 100644 --- a/cmd/hub-gateway-controller-manager/readiness_test.go +++ b/cmd/hub-gateway-controller-manager/readiness_test.go @@ -22,6 +22,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/healthz" gatewayv1 "sigs.k8s.io/gateway-api/apis/v1" + gatewayv1alpha3 "sigs.k8s.io/gateway-api/apis/v1alpha3" gatewayv1beta1 "sigs.k8s.io/gateway-api/apis/v1beta1" fleetnetv1alpha1 "go.goms.io/fleet-networking/api/v1alpha1" @@ -56,7 +57,7 @@ func TestGatewayCacheReadiness(t *testing.T) { informer.synced = kind.Elem().Name() != tt.unsynced informer.stopped = kind.Elem().Name() == tt.stopped } - if err := registerGatewayCacheReadiness(ctx, mgr); err != nil { + if err := registerGatewayCacheReadiness(ctx, mgr, false); err != nil { t.Fatal(err) } if mgr.check == nil { @@ -106,7 +107,7 @@ func TestGatewayCacheReadiness(t *testing.T) { func TestGatewayCacheReadinessTracksSynchronization(t *testing.T) { mgr := newReadinessTestManager(t) - if err := registerGatewayCacheReadiness(context.Background(), mgr); err != nil { + if err := registerGatewayCacheReadiness(context.Background(), mgr, false); err != nil { t.Fatal(err) } if mgr.check == nil { @@ -139,7 +140,7 @@ func TestGatewayCacheReadinessFailures(t *testing.T) { wantError := errors.New("informer initialization failed") mgr.informers.failKind = reflect.TypeOf(object) mgr.informers.initError = wantError - err := registerGatewayCacheReadiness(context.Background(), mgr) + err := registerGatewayCacheReadiness(context.Background(), mgr, false) if !errors.Is(err, wantError) || !strings.Contains(err.Error(), reflect.TypeOf(object).Elem().Name()) { t.Fatalf("setup error = %v, want contextual informer initialization error", err) } @@ -152,7 +153,7 @@ func TestGatewayCacheReadinessFailures(t *testing.T) { mgr := newReadinessTestManager(t) wantError := errors.New("readiness registration failed") mgr.checkError = wantError - err := registerGatewayCacheReadiness(context.Background(), mgr) + err := registerGatewayCacheReadiness(context.Background(), mgr, false) if !errors.Is(err, wantError) { t.Fatalf("setup error = %v, want readiness registration error", err) } @@ -161,13 +162,40 @@ func TestGatewayCacheReadinessFailures(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) cancel() mgr := newReadinessTestManager(t) - err := registerGatewayCacheReadiness(ctx, mgr) + err := registerGatewayCacheReadiness(ctx, mgr, false) if !errors.Is(err, context.Canceled) || mgr.check != nil { t.Fatalf("cancelled initialization error = %v, want cancellation without readiness registration", err) } }) } +func TestGatewayCacheReadinessIncludesOriginTLSOnlyWhenEnabled(t *testing.T) { + kind := reflect.TypeOf(&gatewayv1alpha3.BackendTLSPolicy{}) + for _, enabled := range []bool{false, true} { + t.Run(fmt.Sprint(enabled), func(t *testing.T) { + mgr := newReadinessTestManager(t) + policyInformer := &readinessTestInformer{} + mgr.informers.informers[kind] = policyInformer + for objectKind, informer := range mgr.informers.informers { + informer.synced = objectKind != kind + } + if err := registerGatewayCacheReadiness(context.Background(), mgr, enabled); err != nil { + t.Fatal(err) + } + if (mgr.informers.requests[kind] == 1) != enabled { + t.Fatalf("BackendTLSPolicy informer requests = %d, enabled = %v", mgr.informers.requests[kind], enabled) + } + if err := mgr.check(nil); (err != nil) != enabled { + t.Fatalf("readiness with unsynced BackendTLSPolicy = %v, enabled = %v", err, enabled) + } + policyInformer.synced = true + if err := mgr.check(nil); err != nil { + t.Fatal(err) + } + }) + } +} + func requiredReadinessObjects() []client.Object { return []client.Object{ &gatewayv1.GatewayClass{}, diff --git a/cmd/member-net-controller-manager/main.go b/cmd/member-net-controller-manager/main.go index 432aa874..1281d0df 100644 --- a/cmd/member-net-controller-manager/main.go +++ b/cmd/member-net-controller-manager/main.go @@ -40,6 +40,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/manager" metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server" "sigs.k8s.io/controller-runtime/pkg/webhook" + gatewayv1alpha3 "sigs.k8s.io/gateway-api/apis/v1alpha3" //+kubebuilder:scaffold:imports clusterv1beta1 "go.goms.io/fleet/apis/cluster/v1beta1" @@ -79,6 +80,7 @@ var ( enableTrafficManagerFeature = flag.Bool("enable-traffic-manager-feature", true, "If set, the traffic manager feature will be enabled.") enablePrivateLinkOriginDiscovery = flag.Bool("enable-private-link-origin-discovery", false, "Discover private ingress origins and publish ILB/PLS metadata independently of Traffic Manager.") + enableOriginTLS = flag.Bool("enable-origin-tls", false, "Publish origin TLS metadata; requires private-link origin discovery and installed TLS CRDs.") enableNetworkingFeatures = flag.Bool("enable-networking-features", true, "If set, the networking features will be enabled. When disabled, only heartbeat functionality is preserved.") @@ -92,6 +94,7 @@ func init() { utilruntime.Must(fleetnetv1alpha1.AddToScheme(scheme)) utilruntime.Must(fleetnetv1beta1.AddToScheme(scheme)) utilruntime.Must(clusterv1beta1.AddToScheme(scheme)) + utilruntime.Must(gatewayv1alpha3.Install(scheme)) //+kubebuilder:scaffold:scheme } @@ -118,6 +121,11 @@ func main() { // Set up controller-runtime logger ctrl.SetLogger(zap.New(zap.UseDevMode(true))) + if err := validateOriginTLSOptions(*enableOriginTLS, *enablePrivateLinkOriginDiscovery); err != nil { + klog.ErrorS(err, "Invalid origin TLS configuration") + exitWithErrorFunc() + } + memberConfig, memberOptions := prepareMemberParameters() hubConfig, hubOptions, err := prepareHubParameters(memberConfig) @@ -156,6 +164,14 @@ func main() { } ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + if *enableOriginTLS { + if err := validateOriginTLSCRDs(ctx, memberMgr.GetAPIReader(), hubMgr.GetAPIReader()); err != nil { + klog.ErrorS(err, "Origin TLS prerequisites are not installed") + exitWithErrorFunc() + } + } klog.V(1).InfoS("Setup controllers with controller manager") if err := setupControllersWithManager(ctx, hubMgr, memberMgr); err != nil { @@ -380,6 +396,7 @@ func setupControllersWithManager(ctx context.Context, hubMgr, memberMgr manager. klog.V(1).InfoS("Create serviceexport reconciler", "enableTrafficManagerFeature", *enableTrafficManagerFeature) if err := (&serviceexport.Reconciler{ MemberClient: memberClient, + MemberAPIReader: memberMgr.GetAPIReader(), HubClient: hubClient, MemberClusterID: mcName, HubNamespace: mcHubNamespace, @@ -388,6 +405,7 @@ func setupControllersWithManager(ctx context.Context, hubMgr, memberMgr manager. ResourceGroupName: resourceGroupName, AzurePublicIPAddressClient: networkClients.publicIPAddresses, EnablePrivateLinkOriginDiscovery: *enablePrivateLinkOriginDiscovery, + EnableOriginTLS: *enableOriginTLS, AzureLoadBalancerClient: networkClients.loadBalancers, AzurePrivateLinkServiceClient: networkClients.privateLinkServices, }).SetupWithManager(memberMgr); err != nil { diff --git a/cmd/member-net-controller-manager/origin_tls.go b/cmd/member-net-controller-manager/origin_tls.go new file mode 100644 index 00000000..02f2b014 --- /dev/null +++ b/cmd/member-net-controller-manager/origin_tls.go @@ -0,0 +1,72 @@ +/* +Copyright (c) Microsoft Corporation. +Licensed under the MIT license. +*/ + +package main + +import ( + "context" + "errors" + "fmt" + "time" + + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime/schema" + "sigs.k8s.io/controller-runtime/pkg/client" +) + +func validateOriginTLSOptions(enabled, privateOrigins bool) error { + if enabled && !privateOrigins { + return errors.New("enable-origin-tls requires enable-private-link-origin-discovery") + } + return nil +} + +// Readers must bypass the managers' caches: these checks run before cache startup. +func validateOriginTLSCRDs(ctx context.Context, policyReader, exportReader client.Reader) error { + ctx, cancel := context.WithTimeout(ctx, 15*time.Second) + defer cancel() + checks := []struct { + reader client.Reader + name string + version string + field []string + }{ + {policyReader, "backendtlspolicies.gateway.networking.k8s.io", "v1alpha3", nil}, + {exportReader, "internalserviceexports.networking.fleet.azure.com", "v1alpha1", + []string{"schema", "openAPIV3Schema", "properties", "spec", "properties", "originTLS"}}, + } + for _, check := range checks { + crd := &unstructured.Unstructured{} + crd.SetGroupVersionKind(schema.GroupVersionKind{ + Group: "apiextensions.k8s.io", Version: "v1", Kind: "CustomResourceDefinition", + }) + if err := check.reader.Get(ctx, client.ObjectKey{Name: check.name}, crd); err != nil { + return fmt.Errorf("read required origin TLS CRD %s: %w", check.name, err) + } + versions, _, err := unstructured.NestedSlice(crd.Object, "spec", "versions") + if err != nil { + return fmt.Errorf("read versions of origin TLS CRD %s: %w", check.name, err) + } + ready := false + for _, raw := range versions { + version, ok := raw.(map[string]interface{}) + if !ok || version["name"] != check.version || version["served"] != true { + continue + } + ready = true + if len(check.field) > 0 { + _, ready, err = unstructured.NestedMap(version, check.field...) + if err != nil { + return fmt.Errorf("read originTLS schema in %s: %w", check.name, err) + } + } + break + } + if !ready { + return fmt.Errorf("origin TLS requires %s serving %s with the required schema; install upgraded CRDs before enabling", check.name, check.version) + } + } + return nil +} diff --git a/cmd/member-net-controller-manager/origin_tls_test.go b/cmd/member-net-controller-manager/origin_tls_test.go new file mode 100644 index 00000000..bca1338c --- /dev/null +++ b/cmd/member-net-controller-manager/origin_tls_test.go @@ -0,0 +1,70 @@ +/* +Copyright (c) Microsoft Corporation. +Licensed under the MIT license. +*/ + +package main + +import ( + "context" + "errors" + "strings" + "testing" + + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "sigs.k8s.io/controller-runtime/pkg/client" +) + +func TestValidateOriginTLSOptions(t *testing.T) { + for _, enabled := range []bool{false, true} { + for _, privateOrigins := range []bool{false, true} { + err := validateOriginTLSOptions(enabled, privateOrigins) + if (err != nil) != (enabled && !privateOrigins) { + t.Fatalf("TLS=%v discovery=%v error=%v", enabled, privateOrigins, err) + } + } + } +} + +func TestValidateOriginTLSCRDsUsesMemberAndHubReaders(t *testing.T) { + member := &originTLSCRDReader{name: "backendtlspolicies.gateway.networking.k8s.io", version: map[string]interface{}{ + "name": "v1alpha3", "served": true, + }} + hub := &originTLSCRDReader{name: "internalserviceexports.networking.fleet.azure.com", version: map[string]interface{}{ + "name": "v1alpha1", "served": true, + "schema": map[string]interface{}{"openAPIV3Schema": map[string]interface{}{ + "properties": map[string]interface{}{"spec": map[string]interface{}{ + "properties": map[string]interface{}{"originTLS": map[string]interface{}{"type": "object"}}, + }}, + }}, + }} + if err := validateOriginTLSCRDs(context.Background(), member, hub); err != nil { + t.Fatal(err) + } + hub.version = map[string]interface{}{"name": "v1alpha1", "served": true} + if err := validateOriginTLSCRDs(context.Background(), member, hub); err == nil { + t.Fatal("accepted a hub schema that prunes originTLS") + } + member.version["served"] = false + if err := validateOriginTLSCRDs(context.Background(), member, hub); err == nil || !strings.Contains(err.Error(), "v1alpha3") { + t.Fatalf("unserved BackendTLSPolicy error = %v", err) + } +} + +type originTLSCRDReader struct { + client.Reader + name string + version map[string]interface{} +} + +func (r *originTLSCRDReader) Get(ctx context.Context, key client.ObjectKey, object client.Object, _ ...client.GetOption) error { + if _, ok := ctx.Deadline(); !ok { + return errors.New("startup CRD read must have a deadline") + } + if key.Name != r.name { + return errors.New("CRD read used the wrong cluster") + } + crd := object.(*unstructured.Unstructured) + crd.Object["spec"] = map[string]interface{}{"versions": []interface{}{r.version}} + return nil +} diff --git a/config/crd/bases/networking.fleet.azure.com_internalserviceexports.yaml b/config/crd/bases/networking.fleet.azure.com_internalserviceexports.yaml index 571999fe..f698c58e 100644 --- a/config/crd/bases/networking.fleet.azure.com_internalserviceexports.yaml +++ b/config/crd/bases/networking.fleet.azure.com_internalserviceexports.yaml @@ -59,6 +59,55 @@ spec: description: IsInternalLoadBalancer determines if the Service is an internal load balancer type. type: boolean + originTLS: + description: |- + OriginTLS carries only non-secret, member-observed TLS authorization. + Absence is unknown, never permission to infer a TLS identity. + properties: + hostname: + type: string + observedAt: + format: date-time + type: string + policy: + description: OriginTLSPolicyReference binds authorization to one + observed member policy. + properties: + exportToFleet: + type: string + generation: + format: int64 + type: integer + name: + type: string + namespace: + type: string + resourceVersion: + type: string + uid: + type: string + required: + - exportToFleet + - generation + - name + - namespace + - resourceVersion + - uid + type: object + ready: + type: boolean + reason: + type: string + serviceUID: + type: string + trust: + type: string + required: + - observedAt + - ready + - reason + - serviceUID + type: object ports: description: A list of ports exposed by the exported Service. items: diff --git a/config/rbac/role.yaml b/config/rbac/role.yaml index 6b0a90b8..4f46c857 100644 --- a/config/rbac/role.yaml +++ b/config/rbac/role.yaml @@ -24,6 +24,15 @@ rules: verbs: - create - patch +- apiGroups: + - apiextensions.k8s.io + resourceNames: + - backendtlspolicies.gateway.networking.k8s.io + - internalserviceexports.networking.fleet.azure.com + resources: + - customresourcedefinitions + verbs: + - get - apiGroups: - cluster.kubernetes-fleet.io resources: @@ -52,6 +61,26 @@ rules: - patch - update - watch +- apiGroups: + - gateway.networking.k8s.io + resources: + - backendtlspolicies + verbs: + - create + - delete + - get + - list + - patch + - update + - watch +- apiGroups: + - gateway.networking.k8s.io + resources: + - backendtlspolicies/status + verbs: + - get + - patch + - update - apiGroups: - networking.fleet.azure.com resources: diff --git a/docker/member-net-controller-manager.Dockerfile b/docker/member-net-controller-manager.Dockerfile index 0297da2d..bc816e87 100644 --- a/docker/member-net-controller-manager.Dockerfile +++ b/docker/member-net-controller-manager.Dockerfile @@ -13,13 +13,13 @@ COPY go.sum go.sum RUN --mount=type=cache,target=/go/pkg/mod go mod download # Copy the go source -COPY cmd/member-net-controller-manager/main.go main.go +COPY cmd/member-net-controller-manager/ cmd/member-net-controller-manager/ COPY api/ api/ COPY pkg/ pkg/ # Build with CGO enabled for internal usage RUN echo "Building images with GOOS=$GOOS GOARCH=$GOARCH" -RUN --mount=type=cache,target=/go/pkg/mod CGO_ENABLED=1 GOOS=$GOOS GOARCH=$GOARCH GO111MODULE=on go build -o member-net-controller-manager main.go +RUN --mount=type=cache,target=/go/pkg/mod CGO_ENABLED=1 GOOS=$GOOS GOARCH=$GOARCH GO111MODULE=on go build -o member-net-controller-manager ./cmd/member-net-controller-manager # Use Azure Linux distroless base image to package member-net-controller-manager binary # Refer to https://mcr.microsoft.com/en-us/artifact/mar/azurelinux/distroless/base/about for more details diff --git a/docs/design/gep-1748-https-origins-proposal.md b/docs/design/gep-1748-https-origins-proposal.md new file mode 100644 index 00000000..1d6b80df --- /dev/null +++ b/docs/design/gep-1748-https-origins-proposal.md @@ -0,0 +1,907 @@ +# Proposal: End-to-end TLS with HTTPS private origins for GEP-1748 + +**Status: experimental implementation on this branch; not released or live-certified.** Based on merged commit +`4f80e9e42de24d3a775d2f877fd27b51185fde7e`. This is an end-to-end TLS extension +of the [customer how-to](../howtos/gateway-api-afd-configuration.md), not an +production-readiness claim. The contract below remains the engineering acceptance +baseline; the complete live scenario matrix is not established by offline tests. + +### Implementation and rollout + +- Both existing managers expose `--enable-origin-tls` (default `false`); both + charts expose `enableOriginTLS: false`. Member enablement requires private-origin + discovery; hub enablement requires AFD provisioning. TLS-off startup has no + experimental BackendTLSPolicy CRD dependency. +- Install the upgraded internal CRD on the hub **before** enabling members, then + install the pinned Gateway API v1.2.1 experimental BackendTLSPolicy CRD in hub + and members. Enabled managers check the served version and internal transport + schema through uncached API reads before starting. +- Internal `spec.originTLS` contains the typed non-secret observation and policy + identity. A one-minute (jittered) refresh writes a controller-owned internal + metadata heartbeat bound to the SHA-256 digest of that exact snapshot. + Unchanged snapshots retain their spec timestamp/generation, preserving existing + MCS conflict acknowledgement. Intent expires after five minutes; timestamps over + one minute in the future or mismatched heartbeat bindings are rejected. +- Hub agreement/projection and pre-write/post-write authorization use current API + inventory. No policy/export alone creates ingress. The generated policy belongs + to the ServiceImport UID and is shared across real authorized Gateway ancestors. +- Withdraw HTTPS routes/Gateways and observe provider cleanup before disabling + or downgrading the hub. Disabling members clears the envelope on reconciliation; + unreachable members expire rather than retaining authority indefinitely. +- The separately gated installed-controller fixture is + `ENABLE_AFD_PRIVATE_HTTPS_PROOF=true`, label `afd-private-https-proof`. It reads + approved AKV/Workload Identity identifiers from environment variables and + mounts certificate bundles only in member application pods using CSI, never + AKV credentials in controllers. See the [fixture runbook](../../test/https-origins-certificates.md). + It has not been run against live Azure for this change. + +**Audience:** Engineering and design reviewers. Customer prerequisites, manifests, +ownership checklist and diagnostic steps belong in the +[AFD how-to](../howtos/gateway-api-afd-configuration.md#proposed-https-origins), +not in this implementation plan. + +## Goal and boundaries + +Encrypt and authenticate both the client-to-AFD Premium and AFD-to-member +application connections over the existing Private Link/internal LoadBalancer +topology, without introducing a proxy, another controller Deployment, public +member origins, or customer access to the hub. + +```mermaid +flowchart LR + CLIENT["Client"] + AFD["Public AFD Premium edge
Generated azurefd.net hostname
Azure-provided edge certificate"] + subgraph MEMBER["Private member origin"] + APP["Application
SNI: store-origin.example.com
Serving certificate: AKV CSI mount"] + end + CLIENT -->|"HTTPS: client TLS session"| AFD + AFD -->|"HTTPS over Private Link / PLS / internal LB
Separate origin TLS session"| APP +``` + +AFD terminates a client TLS session and establishes a new TLS session to the +origin; this is not TLS passthrough. An Azure Load Balancer/PLS transports the +connection, not the application certificate. The workload behind the selected +Service port terminates origin TLS. + +Both TLS connections are required by the proposed secure workflow. Use AFD's +generated endpoint hostname and its Azure-provided/renewed edge certificate; +custom client domains, their DNS validation/renewal and frontend BYOC remain +deferred. No customer edge Secret, Key Vault or public DNS record is required +for this generated hostname. This does not issue or renew member certificates. +The listener explicitly selects HTTPS; do not enable HTTP or an HTTP redirect +implicitly. Preserve existing HTTP-preview behavior only for separate explicit +HTTP configurations, not as a fallback for this workflow. + +Keep the existing root `PathPrefix: /`, one logical backend port, same-namespace +HTTPRoute backend, capacity, ownership and Private Link authorization limits. +Multi-backend/path-routing expansion, WAF, optional Traffic Manager resilience, +custom client domains, frontend BYOC, custom origin CAs, client mutual TLS and +origin mutual TLS are outside this scope. +AFD does not support mTLS from Front Door to origins. + +## Current implementation versus proposed behavior + +| Area | Merged implementation | Proposed end-to-end TLS subset | +|---|---|---| +| Client listener | One unrestricted HTTP/80 listener | One HTTPS/443 listener, generated AFD hostname, Azure-provided edge certificate | +| Accepted edge protocols | HTTP | HTTPS only; HTTP does not forward to the application | +| Backend protocol | TCP with absent or `http` appProtocol | Also accept explicit `https` with a valid TLS policy | +| Origin destination | Verified internal IPv4 and exact PLS binding | Retain that provenance; configure a separate DNS TLS identity | +| Forwarding | `HTTPOnly` | `HTTPSOnly` for a TLS backend; never `MatchRequest` | +| Application port | Selected ServiceImport port as HTTP port | Selected ServiceImport port as HTTPS port | +| Probes | HTTP `GET /`, 30 seconds | HTTPS `GET /`, 30 seconds on the same backend port | +| HTTP Host | Omit ARM `originHostHeader` to preserve incoming Host | Unchanged; SNI is a separate identity | +| Certificates | No origin TLS handshake | AFD-trusted chain and matching hostname required | +| Customer backend settings | No edits to generated ServiceImport | Member Service-targeted TLS policy; controller-generated hub policy; platform-authorized routing | + +The HTTP implementation already sets `EnforceCertificateNameCheck=true`, but +with HTTP forwarding that field does not establish a TLS connection. Merely +adding `HTTPSPort` or choosing port 443 is insufficient. + +## MCS API shape and compatibility invariants + +Follow the [upstream MCS API model](https://multicluster.sigs.k8s.io/concepts/multicluster-services-api/): +the application exports a same-name, same-namespace Service through ServiceExport; +controllers derive ServiceImport and the associated endpoint state. Origin TLS +must not introduce a different service identity or a customer-authored import. + +The approved BackendTLSPolicy direction preserves that boundary: + +- Add no fields to public ServiceExport/ServiceImport spec, status or port types. + Keep TLS hostname, trust configuration, certificate references and AFD state + outside those objects. A member policy references its Service; the generated + hub policy references an import. Neither extends a public MCS type. +- Use the existing Service `spec.ports[].appProtocol: https` and exported port + metadata. appProtocol is an application-protocol hint, not a certificate + configuration API; the proposed AFD class requires explicit TLS intent and + a supported policy. This is not a new MCS-wide requirement. +- Preserve existing member/export aggregation, namespace sameness, conflict + handling and source identity. The single-port, private IPv4/PLS and trusted-CA + restrictions apply to AFD eligibility, not to the MCS resource schemas. +- Missing/invalid TLS policy or certificate failures affect AFD configuration + and delivery only. The Gateway controller must not unexport the Service, + rewrite ServiceImport membership, or withdraw baseline MCS EndpointSlices + merely because AFD cannot use the backend. +- Preserve the existing annotation boundary from GEP-1748: Azure-specific + Gateway/Service annotations do not require new public MCS fields. A separate + Gateway API policy also preserves MCS shape. A proposed member-policy annotation + opts its typed TLS intent into Fleet export; hostname/trust remain policy fields, + not annotations. Do not accept customer AFD annotations on generated imports. + +**Existing compatibility limit:** Fleet currently uses the +`networking.fleet.azure.com` group and stores imported ports/type/IPs under +ServiceImport `status`; the upstream MCS API uses `multicluster.x-k8s.io` and +places those fields under `spec`. Fleet also carries `targetPort` in its existing +port type. This proposal preserves Fleet's current schema; it does not claim +wire compatibility/full upstream conformance or migrate these existing fields. +Any upstream-API migration requires a separate compatibility design. + +## Selected customer contract + +Use explicit protocol intent in the existing member Service and a same-namespace +member BackendTLSPolicy targeting that Service, explicitly annotated +`networking.fleet.azure.com/export-to-fleet: "true"`. Require exactly one +applicable policy per member Service for Fleet TLS eligibility. Application +customers manage only member workloads, application certificate delivery, Services, ServiceExports and TLS +policies. Fleet transports validated non-secret policy intent and automatically +reconciles one controller-owned hub BackendTLSPolicy targeting the corresponding +ServiceImport. Customers and platform operators do not hand-author that projection. +Neither hub read nor write access is a customer prerequisite, including +identity changes, verification and certificate rotation. + +The platform still authorizes exposure through Gateway/HTTPRoute and returns +the generated HTTPS endpoint through the existing delivery channel. A member +ServiceExport or BackendTLSPolicy alone must not create a Gateway, HTTPRoute or +public AFD endpoint, attach to another tenant's routing, or authorize PLS approval. +Automatic generation of ingress authorization is outside this proposal. +PLS approval remains a separately authorized network/platform-owner task. + +### Client-facing HTTPS and certificate ownership + +The initial secure subset has exactly one listener: `protocol: HTTPS`, +`port: 443`, `tls.mode: Terminate`, no listener/HTTPRoute hostname restrictions, +and this proposed implementation-specific option: + +```yaml +tls: + mode: Terminate + options: + networking.fleet.azure.com/afd-default-certificate: "true" +``` + +This domain-prefixed Gateway API `tls.options` entry explicitly selects the +Azure-provided certificate for the generated AFD endpoint domain. It is not a +new MCS field, member annotation or currently implemented setting. The pinned +v1.2.1 Gateway TLS schema allows nonempty `options` instead of `certificateRefs` +for termination; this is implementation-specific support, not portable Secret +certificate support. Omit `certificateRefs`; no hub Secret or member key is +read for the edge. Reject missing/unknown options, values other than `"true"`, +certificate references, passthrough, explicit hostnames and additional listeners +instead of approximating their meaning. Validate this shape with the installed +pinned CRD in future admission/envtest tests. + +Compile the edge route with `supportedProtocols: [Https]`, +`linkToDefaultDomain: Enabled` and `httpsRedirect: Disabled`; set +`forwardingProtocol: HttpsOnly` independently for the origin connection. +No custom-domain/certificate ARM resource is required for the default domain. +The HTTPRoute attaches explicitly to the HTTPS listener. An HTTPS listener +with an HTTP backend, or an HTTP listener with an HTTPS backend, is outside +this secure subset and must not program as end-to-end TLS. + +Publish the observed generated hostname in existing Gateway `status.addresses`; +the operator hands `https:///` to the customer through the +existing delivery channel. Do not add a URL field to ServiceExport/ServiceImport +or copy Gateway status to member MCS objects. The generated hostname is tied to +the retained AFD endpoint: normal reconciliation and member join/leave must not +rotate that endpoint or customer URL. Endpoint/Gateway replacement is a separate +lifecycle boundary; do not promise hostname continuity across replacement. +Azure owns edge certificate provisioning/renewal; clients must still verify +the actual hostname and chain using normal trust. +Record edge certificate failures separately from origin certificate failures. +Default-domain TLS policy controls are Azure-owned; stricter client TLS/cipher +requirements must be assessed as a product gap, not silently mapped to a custom +domain. Custom-domain support remains a separate reviewed lifecycle. + +### Client hostname continuity and custom-domain follow-up + +A generated hostname establishes end-to-end TLS, but does not provide a +customer-owned application identity independent of the endpoint lifecycle. +Platform operators must disclose that limitation before handing off the URL +and plan client URL updates if replacement changes it. + +Stable custom-domain support is a production requirement for workloads that +need the same application URL across endpoint/Gateway replacement. It remains +a follow-up, not implemented behavior or an expansion of this proposal's +generated-domain subset. A DNS CNAME alone is insufficient for HTTPS: the +follow-up must cover DNS ownership/delegation, AFD domain validation and routing, +edge certificate provisioning/renewal, and replacement cutover/recovery, +including propagation and traffic verification. Assess the resulting HTTP Host +and application compatibility separately from the origin SNI identity. + +That workflow must preserve member-only customer Kubernetes access: platform +operators manage hub/AFD configuration in coordination with authorized DNS and +certificate owners. Do not require customer hub access or add public MCS fields. +Until that lifecycle is supported and validated, this subset does not satisfy +a customer's replacement-independent URL requirement. + +### Member-side intent and certificate ownership + +- Every exporting Service has the same namespace/name and one exported TCP port, + with matching name, port and `appProtocol: https` across participating members. + The port may be 443 or another valid TLS-serving port; do not infer TLS from + its number or name. AFD connects to Service `port`, not `targetPort`. + Fleet currently compares entire exported port lists, including `targetPort`; + use matching exported values across members. Relaxing that existing behavior + is not part of this proposal. +- Each workload serves a currently valid certificate and complete leaf/ + intermediate chain rooted in a CA trusted by AFD. Private enterprise CAs, + self-signed certificates and a Kubernetes-only custom CA bundle cannot satisfy + this contract. +- The policy's single precise DNS hostname must match every member certificate. + For example, each member may have its own certificate/key for + `store-origin.example.com`; sharing private keys across clusters is not + required. A matching wildcard certificate is acceptable under AFD validation, + but the configured hostname itself must not be a wildcard. +- Provision, store, mount/reload, monitor and rotate certificates through the + application's existing certificate tooling. Fleet neither issues them nor + copies private keys to the hub or Azure Front Door. DNS/certificate owners + perform any CA domain-control validation. +- This requires control of a suitable DNS name, not a public application + endpoint. Do not publish a public member LoadBalancer or add a public fallback + to obtain a certificate. Verify the selected issuance/DNS arrangement in the + live gate; do not assume public DNS or a Kubernetes Service DNS name proves + AFD reachability or certificate trust. + +### Member policy and generated hub projection + +Use `gateway.networking.k8s.io/v1alpha3 BackendTLSPolicy`, as defined in the +repository's pinned Gateway API v1.2.1. The customer policy targets core +`Service` (`group: ""`) in the same member namespace. The generated hub policy +uses the **Fleet implementation-specific ServiceImport target** in the import +namespace. Service targeting uses the upstream resource shape; fleet-wide +aggregation and ServiceImport projection are Fleet behavior, not portable +Gateway API conformance. The resource is in that release's experimental CRD +channel; the platform must install it in participating members and the hub. +Today's standard CRD prerequisites are insufficient. + +Recommended initial policy subset: + +| Field | Supported proposal | +|---|---| +| `metadata.annotations["networking.fleet.azure.com/export-to-fleet"]` | Member policy: exact string `"true"` explicitly opts into Fleet export; not required/copied on the controller-owned hub projection | +| `targetRefs` | Customer: exactly one local core Service; generated hub policy: corresponding Fleet ServiceImport | +| `sectionName` | Absent; target has exactly one exported port | +| `validation.hostname` | Required precise DNS name shared by eligible members | +| `validation.wellKnownCACertificates` | Required `System`, meaning AFD's trust store, not the hub host's | +| `caCertificateRefs` | Unsupported; reject rather than ignore | +| `subjectAltNames` | Absent; separate SAN overrides cannot be honored by this AFD mapping | +| `options` | Empty/absent; no certificate-check bypass or arbitrary TLS options | + +The target Service must have the same namespace/name as its ServiceExport and +one exported port. A member policy does not itself export a Service or authorize +an HTTPRoute. Do not infer the origin hostname from a Secret, port number, +cluster DNS name or member-provided ARM annotation. + +#### Explicit Fleet export and coexistence + +BackendTLSPolicy has no `spec.controllerName`. A local Service target alone does +not distinguish Fleet intent from a policy used by another implementation, such +as Istio. Require the proposed `networking.fleet.azure.com/export-to-fleet: "true"` +annotation on the customer-owned member policy before exporting its TLS intent. +Missing or other values do not authorize export. A matching ServiceExport is +also required; neither marker nor export replaces platform ingress authorization. +The hub policy is still generated automatically, not annotated/applied by the +customer, and its ownership is verified independently of this opt-in. + +The annotation is a Fleet-specific export extension, not a standard controller +selector or an exclusive-ownership claim. Other implementations may consume the +same policy. Fleet must not alter their policy spec, metadata or status entries. +An unmarked policy alone is not Fleet TLS intent and is not projected, assigned +Fleet status or subjected to Fleet-specific field validation. Its existence must +not change baseline MCS exports or explicit HTTP-preview behavior. + +The serving certificate/key are configured at the member application, for +example through an AKV CSI mount (or existing application-owned TLS Secret). +BackendTLSPolicy specifies what AFD must +validate, not where to fetch the server's private key. `caCertificateRefs`, when +supported by another implementation, specifies CA trust anchors rather than the +origin's serving certificate/key; it is unsupported by this AFD mapping. +Frontend Gateway certificate configuration is a separate TLS boundary covered +above; it never reuses or replaces the member serving certificate mount. + +Require exactly one applicable BackendTLSPolicy per member Service before +exporting Fleet TLS intent. Count policy objects in the Service namespace whose +`targetRefs` include that core Service, including unmarked policies used by other +implementations. Zero policies or a sole unmarked/invalid/unsupported policy +cannot authorize Fleet TLS. More than one makes the Service ineligible for Fleet +TLS, even if the policies have identical settings or only one is opted in. +Do not choose by age/name, merge settings or skip an unmarked competing policy. + +This is a deliberately stricter Fleet eligibility subset, not Gateway API's +oldest-policy conflict resolution or a claim of upstream precedence conformance. +It is not cluster-wide admission enforcement: other implementations may retain +their policies, and Fleet must not delete/edit them. Diagnose duplicate targets +on the opted-in policy, exclude that member from AFD TLS eligibility and let the +owners resolve the ambiguity. Apply the failure-scope rules below rather than +unconditionally withdrawing healthy members. One shared policy may still be +consumed by multiple implementations if their requirements agree. + +Member policies may precede their Service/export; reconcile target appearance. +Watch all same-Service policy creations, deletions and target changes, including +unmarked policies. Limiting watches/indexes to opted-in objects would hide +duplicates and could leave stale TLS authorization in effect. + +#### Internal transport and agreement + +Extend the controller-owned InternalServiceExport transport, not public MCS +types, with an optional typed origin-TLS envelope. It must carry explicit +resolution state, the validated hostname/`System` contract and source +Service UID plus selected policy namespace/name/UID/generation, the exact +export annotation value and policy resourceVersion as an opaque +observation identifier, not a cross-cluster ordering or authorization token. +Do not copy arbitrary policy annotations. Retain the authenticated +member/reserved-namespace association and current export identity; +never accept another member's source claim or raw policy YAML as authorization. +No Secret, key, certificate chain or custom CA is transported. The branch uses +internal `spec.originTLS` and the digest-bound metadata heartbeat described above, +not a public ServiceExport/ServiceImport API extension. + +Inventory the complete authoritative source set of a referenced logical HTTPS +backend, then resolve each member's local TLS eligibility independently. Missing, +unmarked, duplicate, invalid, unreadable or stale member policy intent makes that +member ineligible; record its identity/reason and safely isolate its owned AFD +origin rather than silently dropping it from the inventory. Absence from an +older member means unknown, not permission to assume a hostname. + +Require at least one eligible member and current agreement on hostname/trust/ +selected port across **all** otherwise eligible member intents. Two different +locally valid TLS identities are backend-wide ambiguity: withdraw the affected +route, not a majority vote or an exclusion chosen to manufacture agreement. +Never reuse stale successful intent or downgrade to HTTP. An ordinary +unexport/departure removes that source through existing ownership/membership +reconciliation. TLS exclusions affect AFD only; policy failures must not +unexport the Service or alter baseline MCS state. +Do not return early from ordinary export reconciliation in a way that suppresses +baseline MCS updates merely because TLS resolution failed. + +Policy create/update/delete, same-Service policy count/target changes, export +opt-in changes, source Service replacement and read failures must refresh or +invalidate the envelope through the existing member export path and enqueue hub +aggregation. Do not preserve the last known valid contract on a known policy +deletion/read failure or opt-out. +Annotation-only updates do not increment policy generation; watch and transport +that change rather than relying on generation-only predicates or cache keys. +Removing/changing the opt-in must invalidate the previous TLS authorization, +not select another policy as an implicit fallback. +Transport interruptions/partitions must be distinguishable from a current +successful observation: the implemented five-minute expiry makes the affected +member ineligible without a fresh bound observation. Apply the +isolation/withdrawal rules below; do not claim instantaneous remote +revocation across a disconnected member. + +#### Failure scope and safe origin isolation + +- **Member-local failure:** missing/invalid/duplicate policy, opt-out or expired/ + unreadable member intent excludes only that attributable member. Continue + serving eligible members with one unambiguous TLS contract after verifying + that every excluded member has no owned origin, or its exact verified origin + is administratively disabled/removed. Update generated-policy provenance and + the desired graph to distinguish eligible sources from explicit exclusions. +- **Backend-wide failure:** withdraw the affected owned route for no eligible + members, conflicting otherwise-valid TLS contracts, shared projection/ + ownership or protocol/port errors, or incomplete authoritative source + inventory. Do not hide a valid conflicting intent as a local exclusion. +- **Unsafe isolation:** if source/binding attribution, owned Azure inventory, + permissions or reconciliation errors prevent verified isolation, withdraw/ + suspend the affected route with bounded retry-safe operations. Never delete + unverified inventory or continue claiming a safe degraded graph. + If provider errors also prevent route suspension, report the enforcement + failure, retry/escalate and never claim that traffic has stopped. + +Do not implement exclusion using health-probe failure alone: AFD can still send +to unhealthy origins. Verify explicit administrative exclusion and include +fresh negative traffic evidence in live tests. Provider propagation and +in-flight requests preclude instantaneous isolation or a zero-error guarantee; +bounded route suspension may be necessary until isolation is verified. +Report excluded members, reasons and degraded capacity through existing +status/events/logs and the platform handoff, without new public MCS fields or a +fabricated portable `Degraded` condition. Re-admit a repaired member only after +fresh single-policy validation, agreement and verified private/TLS programming. + +#### Hub ownership, status and cleanup + +The existing hub ingress reconciliation creates/updates a deterministic policy +named from the target (for example `store-api-origin-tls`), not from an arbitrary +member policy name, for an agreed explicitly referenced backend. Reuse it for +authorized Gateways under this controller. Record verified ServiceImport UID +and source-set provenance; bind ownership to the generated target lifecycle, not whichever +Gateway reconciles first. Do not edit/adopt an unowned same-name policy or +silently override a competing manually authored hub policy. Such collisions +block programming and surface an actionable operator error. + +Invalidate the usable aggregate before projection updates/deletion, and never +treat a previously accepted generated policy alone as current authorization. +Verify both its contents and current source provenance at graph resolution. +Repair deletion/drift only from current agreeing eligible-member intent and +verified ownership. Isolated member failures update the projection's eligible +source/exclusion provenance without removing a valid shared contract. Backend-wide +ambiguity or unsafe isolation withdraws the affected owned route; invalidate/ +remove an unusable projection with bounded retry-safe cleanup. Removing the +last authorized route reference or target/export set removes the generated +policy; deleting one of multiple Gateway references must not break the others. +Never delete customer-owned member policies or certificates during hub cleanup. + +Hub policy acceptance uses real hub Gateway `status.ancestors` entries. The +customer-facing member diagnostic baseline is sanitized events on the opted-in +member policy, including missing target, invalid policy, duplicate targets and +transport failure. Do not invent top-level policy conditions, cross-cluster Gateway +ancestors, or new public MCS TLS status fields. No local Gateway ancestor is +fabricated to make the member policy look accepted; preserve other controllers' +valid status entries. A richer durable member-local projection/readiness API +requires explicit design before being promised. Operator hub diagnostics and +independent client/member evidence remain necessary for end-to-end readiness. + +### Protocol and downgrade rules + +| Listener | Exported appProtocol | Effective policy | Result | +|---|---|---|---| +| Existing HTTP/80 | Absent or `http` | None | Preserve explicit existing HTTP-preview behavior | +| Supported HTTPS/443 | `https` | Exactly one applicable, valid supported policy explicitly opted into Fleet export | HTTPS on both hops and HTTPS probes | +| HTTPS/443 | `https` | A member has zero/multiple applicable policies, or its sole policy is unmarked, invalid or stale | Isolate that member; serve agreeing eligible members only after verified exclusion | +| HTTPS/443 | `https` | No eligible members, conflicting valid intents, shared dependency failure or unsafe isolation | Withdraw the affected route; no HTTP fallback | +| HTTPS/443 | Absent or `http` | Any | Reject cleartext origin for the secure subset | +| HTTP/80 | `https` | Any | Reject cleartext edge for the secure subset | +| Any | Absent or `http` | Any Fleet-exported TLS policy | Configuration mismatch; do not silently serve HTTP | +| Any | Other, mixed or conflicting exports | Any | Reject incompatible protocol/export intent | + +An effective TLS policy requires the single-policy gate in every eligible +member, complete source inventory with explicit verified exclusions, fresh +agreement across all eligible intents and a matching owned hub projection. +An old policy object or status alone is insufficient. + +Deleting a member policy or removing its export opt-in invalidates that member's +authorization and requires origin isolation, not restoration of the HTTP preview. +Continue healthy-member service only under the failure-scope rules above. +Likewise, an unknown or +unsupported policy field or policy read error is not policy absence. A controller +without policy CRDs/RBAC must refuse the TLS capability explicitly, not ignore +HTTPS intent. Existing HTTP-only installations must not acquire an unconditional +experimental-CRD startup dependency. + +## Network identity, SNI and Host + +Keep three concepts separate: + +1. **Network provenance:** member discovery verifies the internal LB IP, PLS + resource ID/location, Service UID and exporting member. Retain all existing + source identity, conflict, namespace and lifecycle checks. +2. **TLS identity:** set ARM origin `hostName` to the policy DNS hostname. The + AFD Private Link ILB guidance specifies that this name supplies SNI and + certificate-name validation. Set `enforceCertificateNameCheck=true`; the exact + shared Private Link target still selects private connectivity. +3. **HTTP authority:** omit `originHostHeader`, preserving incoming Host for + application requests. Do not replace it with the TLS hostname, send an empty + string, or assume setting SNI rewrites Host. + +For example, origin SNI is `store-origin.example.com` while the application sees +the generated AFD endpoint hostname as Host. Client TLS uses that generated +hostname for its separate SNI/certificate check, not the origin identity. +Applications must support this distinction and the actual AFD probe Host. +The origin hostname, certificate identity, HTTP authority and public DNS name +are not interchangeable. + +Do not replace `PrivateLinkOrigin.internalIP` with a DNS string. Add separate +transport/TLS fields to the normalized backend/provider model; derive the shared +TLS hostname from the validated member agreement and matching generated hub +policy, not from unverified annotations. InternalServiceExport already carries +appProtocol; it now also needs the non-secret policy envelope described above. +Do not export certificates/Secrets or introduce per-member TLS identities or +new public ServiceImport fields. + +For TLS backends, request `httpsPort` from the selected ServiceImport port, +`HTTPSOnly` forwarding, HTTPS probes, and name checks. Do not configure HTTP +forwarding/probes as an alternative. An ARM-default HTTP port, if returned by +Azure, does not authorize its use: observe effective forwarding and probe +protocols as well as ports. Verify exact SDK request/response semantics during +implementation. + +Generalize the existing profile-wide PLS/port-sharing guard to effective origin +transport ports; retaining an HTTP-only check would miss TLS conflicts. +Unsupported sharing or mixed-protocol graphs fail before generating a write +plan. Keep the existing capacity limits; TLS does not authorize more origins. + +## Controller lifecycle and observable UX + +Extend existing member export and hub Gateway/HTTPRoute reconciliation, resolver +and AFD provider; no additional controller Deployment is required. Member +policy/Service watches drive envelope invalidation and refresh. Hub internal +export/target/generated-policy watches drive agreement, projection and all +affected Gateways, including same-Service policy count/target changes. Preserve +existing source/membership watches. Members receive policy read/watch and event +permissions; hub projection reconciliation receives scoped policy lifecycle and +status permissions. Member identities still write only their reserved hub +export namespace, never the shared backend policy or Gateway namespace. + +The platform must explicitly enable the capability in member and hub managers, +install the updated internal transport CRD in the hub first, and install the +pinned experimental policy CRD in hub and participating members before use. +Define the concrete flag/chart surface +in the implementation plan; no new supported flag is introduced by this +document. Do not install CRDs opportunistically from the running controller. +No new Azure Key Vault access, origin Secret access or PLS approval permission +is needed by Fleet for application-owned certificates. + +Before creating or activating resources, validate the entire supported graph, +edge certificate option, effective backend TLS policy, private bindings and +current owner. Observe the HTTPS-only accepted edge protocol, default-domain +association, disabled redirect, exact origin hostname/HTTPS port, forwarding/ +probe protocol and name-check policy before reporting resources programmed. +An omitted PATCH property is not +proof that a stale Host override or TLS setting was cleared. Repair through a +verified supported operation, or remain unprogrammed with an actionable error. + +| Signal | Proposed meaning | +|---|---| +| Member policy events | Local selection/validation/transport diagnostics, not hub or live TLS readiness | +| Generated hub policy ancestor `Accepted=True` | Supported aggregate selected for the real hub Gateway, not a successful TLS handshake | +| Existing status/events/logs report excluded members | Verified degraded configuration and explicit member/reason/capacity diagnostics; eligible members may still serve, without a new portable condition or MCS status field | +| Hub policy `Accepted=False` or projection error | Invalid/missing/conflicting aggregate or ownership collision, with a sanitized explanation | +| HTTPRoute parent `ResolvedRefs=False` | Missing/incompatible TLS dependency; use the pinned API reason appropriate to the failure | +| Gateway/listener `Programmed=False` | Desired owned TLS configuration is incomplete, invalid, drifting or withdrawing | +| Gateway/listener `Programmed=True` | Observed owned enabled graph matches desired TLS configuration; not proof of certificate validity or traffic | +| AFD telemetry and independent requests | Actual probe, handshake, member delivery and application-health evidence | + +Retain observed generations and existing parent/controller status ownership. +Define and test exact route/Gateway failure reasons during implementation; do +not invent a new portable condition or claim the hub can inspect a certificate +it never reads. Surface denied policy reads, provisioning errors and unresolved +dependencies through status/events and sanitized logs. + +Manual PLS approval and its authorization remain unchanged. Preserve current +configuration-based programming and endpoint-first activation; do not reinstate +null/Pending AFD approval or `NotStarted` deployment as blanket readiness gates. +Approval is still required for connectivity, independently of Programmed. + +### Health and failures + +Use platform-owned HTTPS `GET /` every 30 seconds on the selected backend port; +applications must return 200 without a redirect or probe authentication +requirement. Distributed probes can produce a higher aggregate rate. +Observe actual SNI, Host and TLS behavior in the live test rather than assuming +probe behavior equals forwarded application traffic. + +Expired/untrusted certificates, an incomplete chain or a hostname mismatch must +fail TLS, never trigger cleartext forwarding or disabled validation. AFD, not +Fleet's configuration reconciler, observes these runtime failures. Do not +promise certificate-expiry alerts from Fleet or a Programmed transition for +unobserved handshake failures; platform monitoring must cover AFD failures +and application certificate expiry. + +AFD's documented all-origins-unhealthy behavior can still send requests to +unhealthy origins. Probe failure alone does not guarantee traffic withdrawal. +TLS validation remains mandatory even in that case, and errors can reach +clients. Healthy-origin failover is not a zero-error or availability guarantee. + +### Updates, withdrawal and rotation + +- Continue adding/re-exporting eligible private members and pruning retired + owned origins with exact Service UID/PLS identity. A transient discovery delay + does not remove other valid private members. Port/protocol conflicts remain + export errors, not an excuse to mix transports. +- Update a certificate for the same hostname at the workload with overlapping + validity and verified reload. No Fleet policy update or hub private-key access + is needed. Prove new TLS handshakes; existing connections can mask a bad reload. +- For a TLS hostname change, first deploy certificates valid for both old and + new names to every participating member, then update each member policy. + During disagreement withdraw the affected route; coordinated rotation may + have an outage. Once all otherwise eligible intents agree, regenerate/observe + the hub policy and AFD graph, prove traffic, then retire the old identity. + Record excluded members; re-admission still requires the current contract. +- Quiesce the affected route before HTTP-to-HTTPS migration or other incompatible + listener/port/transport updates; observe withdrawal before replacing the old + graph. Stage and verify the complete edge-and-origin TLS graph before + activation. Do not leave an enabled HTTP route pointing at a newly TLS-only + application. Coordinate the member rollout or use a separate TLS-serving + deployment during migration; zero-downtime migration is not promised. + Deliver the HTTPS URL through the platform handoff and require clients to + switch explicitly; no automatic HTTP redirect or fallback is introduced. +- On known invalid/missing required policy, withdraw the affected owned route + only if no eligible members remain, shared TLS intent is ambiguous, or safe + member-origin isolation cannot be verified. Otherwise explicitly disable/ + remove that member's verified owned origin, refresh projection provenance and + continue the agreeing eligible members with degraded diagnostics. Read + failures cannot authorize new writes or downgrade; apply bounded suspension + rather than deleting unverified inventory or retaining stale member authority. +- Returning deliberately to HTTP requires an authorized coordinated member + protocol/port change and policy removal. It is never error recovery. +- Preserve bounded operations, shared request pacing, inventory/ownership + verification, retry safety, finalizers and retained-root re-export behavior. + Gateway deletion removes owned AFD resources and its generated-policy + reference; projection cleanup respects other authorized users of the backend. + It does not delete member policies/certificates, application DNS or WAF assets. + +## Customer workflow + +The [proposed how-to addition](../howtos/gateway-api-afd-configuration.md#proposed-https-origins) +keeps the existing actor split and ServiceExport/ServiceImport contract: + +1. The certificate owner supplies trusted origin certificates and a shared + origin DNS identity; application teams configure TLS in every member. +2. Application teams create same-namespace Service-targeted BackendTLSPolicies + with matching hostname/`System` trust in every member, then export matching + private TLS Services with `appProtocol: https`. Fleet aggregates current + intent and creates the hub ServiceImport-targeted policy automatically. +3. The platform operator installs/enables the future member/hub capability and + explicitly authorizes ingress through HTTPS/443 Gateway/default-certificate + option and HTTPRoute. No manual hub-policy apply step remains. +4. Network owners approve the exact AFD-to-PLS connections as today. +5. Operators verify policy/configuration status and independently prove both + TLS connections, private delivery and HTTPS probes, then hand the generated + HTTPS URL to the customer. Customers run plain `curl` with normal trust and + inspect their member application logs; they never need hub credentials. + +Customers change origin identity through their member policies, never the +generated hub policy. Platform ingress authorization, PLS approval, URL handoff +and Azure diagnostics remain operator procedures, not extra customer Kubernetes +permissions. Member-only policy driving does not imply automatic ingress creation. + +No certificate material, trust-bypass annotation, configurable health-probe +annotation or PLS auto-approval is added to the customer workflow. + +The customer-facing [readiness checklist and private preflight](../howtos/gateway-api-afd-configuration.md#customer-readiness-checklist) +live in the how-to alongside the manifests. They assign an accountable owner +and required evidence for platform/access prerequisites, private infrastructure, +certificates, application/probe behavior, production rollout and operations. +The implementation must satisfy that checklist; design review is not customer +onboarding or live-test authorization. + +## Engineering implementation work packages + +Implement only after explicit approval of the reviewed contract. The following +ordering records dependencies, not completed tasks. + +### Review and commit boundaries + +The agreed delivery split is four substantive commits, following #400: + +| Commit | Contents | Current authorization | +|---|---|---| +| `docs(https)` | Customer how-to, API/engineering plan, E2E requirements and historical validation context | Documentation review only; this is the current change | +| `feat(https)` | Member policy resolution/watches, internal transport, hub agreement/generated-policy lifecycle, HTTPS listener/default-certificate mapping and AFD TLS lifecycle | Deferred until explicit implementation approval | +| `build(https)` | Default-off member/hub capabilities, values/schema, internal CRD/deepcopy generation, scoped policy RBAC and member/hub CRD/startup prerequisites | Deferred until explicit implementation approval | +| `test(https)` | Member/hub unit/envtest/manager/chart, transport/projection regressions and separately gated installed-controller TLS E2E fixtures/proof helpers | Deferred until explicit implementation approval; live execution requires separate Azure authorization | + +The separate [first-party certificate fixture runbook](../../test/https-origins-certificates.md) +belongs in this `docs(https)` review: obtain an authorized origin DNS identity, +publicly trusted certificate and usable member private key before planning a +positive live run. OneCert is conditional on the approved public-CA enrollment +and custody path, not a substitute for AFD trust. Internal enrollment/access +details and secrets do not belong in this public repository. Executable fixture +automation remains in `test(https)`. + +Write focused failing tests alongside future implementation, even though test +files will be committed in the separate test category. Do not create empty or +misleading feature/build/test commits during this documentation-only review. +The historical HTTP validation breadcrumb belongs in the docs commit as +background; it does not qualify the proposed HTTPS implementation. + +### Dependency-ordered implementation tasks + +| Work package | Existing areas to extend | Acceptance gate | +|---|---|---| +| 1. Pin API and capability contract | `go.mod`, member/hub manager scheme/startup, member/Gateway charts and installation/test guides | Confirm v1.2.1 experimental schema/status and CRD detection in both planes; document the stricter Fleet single-policy gate rather than upstream precedence behavior. Define opt-in, internal CRD-first upgrade, freshness/liveness bounds and safe disable/rollback before adding watches. TLS-off HTTP installations still start without the experimental CRD. No unrelated Gateway API upgrade. | +| 2. Add member resolution and internal transport tests first | Existing member `serviceexport` reconciliation, policy/Service indexes and InternalServiceExport API/transport | Require exactly one applicable policy with explicit member-policy export opt-in. Reject duplicates including unmarked or identical policies; never choose by age/name. Invalidate on policy count/target changes, deletion/opt-out/error/source replacement, and carry typed non-secret contract/state/source UIDs/generation and observed opt-in metadata. Prove annotation-only revocation without generation change, unmarked-policy coexistence, duplicate appearance/removal, transport retry/partition/freshness and old-member absence cannot authorize stale TLS. No public MCS schema/status changes or key/Secret reads. | +| 3. Aggregate and project current intent | Hub internal export watches, `gatewayresolver`, `gateway`, `httproute`, `gatewaymodel` and existing reconciliation | Inventory every authoritative source; classify eligible intents and explicit member-local exclusions. Require at least one eligible member and agreement across all eligible intents, never majority selection. Carry verified exclusion/source provenance into one deterministic owned ServiceImport-targeted policy and preserve baseline MCS state. Handle ownership collisions, shared Gateway references, source drift and target UID replacement. Shared ambiguity/incomplete inventory produces no usable TLS write plan. Preserve private provenance separately from TLS identities. | +| 4. Compile exact AFD TLS configuration | `pkg/providers/azure/frontdoor` planner, requests and graph construction | Produce HTTPS-only accepted edge protocols, default-domain association and no redirect/custom-domain resources; independently produce HTTPSOnly forwarding, HTTPS probes, correct origin HTTPS port, mandatory name checks and omitted Host override. Generalize sharing/capacity checks. Unsupported edge certificate/trust/transport requests fail before any Azure write. | +| 5. Extend observation and lifecycle | Same provider's inventory, provisioning, staging, observation, withdrawal and cleanup paths; hub Gateway lifecycle | Compare effective edge/origin TLS settings and enforce migration quiescence. Verify exact excluded origins absent or administratively disabled before accepting a degraded graph; probe health is not isolation. Withdraw/suspend the affected route for no eligible origins, conflicting valid intents, shared failures or unverifiable isolation. Preserve bounded calls, pacing, owner/private-target checks and endpoint-first activation. No stale authority, HTTP fallback or instantaneous-isolation claim. | +| 6. Expose diagnostics and installation permissions | Existing member events, hub policy status, member/Gateway chart RBAC and manager capability configuration | Distinguish member-local exclusions from backend-wide withdrawal; report member identity, reason, isolation state and degraded capacity through existing status/events/logs and platform handoff. Hub status uses real ancestors/current generations. No fabricated cross-cluster ancestors, portable Degraded condition or MCS TLS conditions. Members read local policies and write only reserved hub exports; hub owns shared policy lifecycle. No Secret/key or PLS approval permissions. | +| 7. Extend offline/live fixtures and docs | `test/e2e`, `test/scripts`, `test/helm`, `test/README.md` and the customer AFD how-to | Add both-hop TLS application/fixture and proof helpers, keep certificate material out of committed fixtures, publish a specific opt-in and selector, and satisfy the E2E matrix below. Exercise member-only customer credentials and operator endpoint handoff. Update customer examples only to the API actually implemented. | + +Use focused package tests before the relevant broader checks. For the future Go +implementation, configure envtest assets and policy CRDs first because member +controller tests can start a local API server. The focused validation set is: + +```bash +# Offline checks only; these do not prove live AFD TLS delivery. +go test ./pkg/controllers/member/serviceexport ./pkg/controllers/hub/gatewayresolver ./pkg/controllers/hub/gatewaymodel ./pkg/providers/azure/frontdoor +go vet ./pkg/controllers/member/serviceexport ./pkg/controllers/hub/gatewayresolver ./pkg/controllers/hub/gatewaymodel ./pkg/providers/azure/frontdoor +``` + +For member/hub controller and manager changes, use the Makefile's envtest +prerequisites and run affected suites with policy CRDs installed. Run chart/script +tests, changed-file goimports and `make lint`; use `make local-unit-test` and +`make integration-test` when the controller/API scope requires them. Use +`make manifests generate` for the planned internal transport API changes and +review all generated diffs; assert public MCS schemas remain unchanged. The +selected validation must include member/hub TLS-on and TLS-off startup/install. + +These are planned checks, not results from this documentation-only change. + +## Implementation and validation gates + +These are future tasks, not tests performed by this documentation change. + +1. **Review the contract.** Approve member Service targeting, Fleet-specific hub + projection, internal transport/provenance/freshness, experimental member/hub + CRD/opt-in/upgrade path, single-port/shared-hostname limits, status reasons, + the stricter single-policy eligibility gate, member-local isolation versus + backend-wide withdrawal, degraded diagnostics and explicit migration behavior. + Include the implementation-specific + default edge certificate option and pinned Gateway TLS schema. Confirm AFD + trust/DNS/SNI/probe semantics and SDK properties before implementation. +2. **Write focused regressions first.** Cover protocol/policy truth-table cases, + missing and late targets, unmarked policies used by other implementations, + explicit export opt-in, zero/one/multiple applicable policies, member-local + isolation, valid cross-member identity conflicts and no-eligible-member cases, + annotation-only opt-out without a generation change, other-controller status + preservation, metadata-only updates, source UID/generation replacement, + multiple Gateways, + projection ownership/drift, policy deletion/read denial/status ownership, + transport loss/expiry and mixed member versions. Prove HTTPS intent never reaches HTTP + request construction; existing HTTP requests remain unchanged. Cover edge + listener/port/options, wrong/missing option values, certificate references, + hostname restrictions, extra listeners and HTTP/HTTPS mismatches. Validate + examples against the unchanged Fleet ServiceExport/ServiceImport schemas. + Verify that policy changes/failures do not alter baseline MCS membership, + conflict resolution or endpoint distribution; use existing controller suites. + Prove attributed stale/read-failed members cannot retain an enabled origin; + failed isolation, incomplete source inventory and shared read/ownership errors + must request affected-route withdrawal/suspension and surface any enforcement + failure rather than claim safe degradation or stopped traffic. +3. **Extend existing implementation.** Carry TLS identity separately from private + provenance, generalize request/observation/inventory and cleanup assumptions, + and add member watches/transport, hub agreement/projection, HTTPS listener + handling, real-ancestor status, RBAC and explicit capability discovery. + Verify stale Host overrides, disabled name + checks, wrong PLS/hostname/port, edge/origin protocol drift, interrupted + migration, retries and final withdrawal. +4. **Run offline checks.** Use affected package tests and vet, changed-file + goimports, relevant chart/script tests and the Makefile-configured lint. + Configure envtest for controller/policy suites rather than skipping them. + Local TLS fixtures can use their explicit test CA; this does not establish + that AFD trusts that CA or prove private delivery. +5. **Authorize and prove live end-to-end TLS.** Obtain explicit subscription, + resource-group, cluster-context and create/test/cleanup approval. Use two + members, an application-owned AFD-trusted chain and no public origin. Prove + exact owned Private Link bindings, authorized approvals, HTTPS forwarding/ + probes, separate client/origin SNI identities, preserved Host/path/query, + fresh request IDs and both members. Use the generated AFD HTTPS hostname and + normal client chain/name verification. Prove HTTP requests do not reach the + application; an origin-only or insecure-client run cannot pass this gate. +6. **Exercise failures and lifecycle.** In an isolated approved fixture test + wrong-name, expired, untrusted and incomplete-chain certificates, TLS-only + probes, one/all-member failures, policy removal, same-name rotation, hostname + rotation, member/Service replacement and cleanup. No insecure client probes, + certificate-check bypass or manually repaired graph can satisfy success. + Collect sanitized logs before approved owned-resource cleanup. + +Release only after the customer examples match implemented API support and +independently observed behavior. Do not imply that this proposal or the earlier +HTTP proof establishes production TLS or regulatory compliance. + +## E2E testing requirements + +Extend the installed-controller private-HTTP proof pattern in +`test/e2e/gateway_private_http_test.go` and its proof/diagnostic helpers rather +than replacing it or counting synthetic hub exports as private TLS proof. +The [E2E guide](../../test/README.md) remains the authority for environment +authorization, prerequisites and existing commands. + +### Fixture and execution contract + +- Use an explicitly approved test subscription/resource group, hub and two + real members. Record exact contexts, controller image digest/commit, enabled + capabilities, CRD versions, identity scopes and ownership IDs. +- Start with an absent uniquely owned AFD profile. Let the installed controller + create, stage and activate the graph. Manual ARM activation, copied resources + or a previously working retained setup do not prove this lifecycle. +- Use the generated endpoint hostname and Azure-provided edge certificate. + Record its observed address, certificate hostname/chain validation and + negotiated client TLS separately from the member certificates. Do not add a + custom-domain/DNS/Key Vault fixture or override client Host/SNI to bypass the + selected scope. Customer proof runs without hub credentials; an operator + performs hub reads and supplies the URL. +- Deploy a TLS-speaking application behind each private LB/PLS, with + deterministic member identity, request nonce, path/query and observed Host + in responses/logs. Record server-side TLS/SNI evidence as well. A distinct + application/certificate instance in each member must meet the shared-name + contract; no added routing proxy is required. +- Apply Service-targeted policies only in members with explicit Fleet export + opt-in and matching hostname/trust. + Let controllers generate the hub policy; no manual hub-policy apply/repair + counts as a pass. Independently inspect source provenance, current agreement, + generated ownership and real hub ancestor status. Before explicit platform + Gateway/HTTPRoute authorization, member resources must create no AFD ingress. +- Obtain AFD-trusted valid certificates through an owner-approved fixture + provisioning method. Define storage, renewal, expiry and teardown ownership. + Follow the [first-party hostname/certificate preparation guide](../../test/https-origins-certificates.md); + do not assume corporate trust or OneCert enrollment alone establishes AFD trust. + Supply negative certificates only to disposable authorized fixtures; a + mock AFD transport or a locally trusted self-signed CA is not a live positive + certificate fixture. Do not commit keys or expose them in reports. +- Keep PLS approvals attributable and separately authorized. E2E-only approval + automation, if used, must use its explicit existing trust/opt-in boundary; + it does not become a controller feature. +- Add a separate, default-off TLS proof opt-in/selector and document its exact + runnable command in `test/README.md` when implemented. No TLS E2E command or + flag exists today; do not repurpose the HTTP proof name to imply coverage. +- Use bounded timeouts and normal certificate verification. Collect failure + diagnostics before cleanup, and record retained fixtures as incomplete + withdrawal/cleanup evidence. Do not make a fixed propagation-time promise. + +### Required live scenarios and pass criteria + +| ID | Scenario | Required assertions and evidence | +|---|---|---| +| TLS-01 | Initial two-member provisioning | Matching member Service policies automatically generate an owned hub ServiceImport policy with current source provenance and real Gateway acceptance. HTTPS listener/default-certificate option, HTTPS-only edge/default-domain/no redirect, exact private bindings, origin TLS identity/port, forwarding/probes/name checks and enabled graph are observed. No manual hub-policy or ARM repair. | +| TLS-02 | Actual private TLS application delivery | Fresh nonce-bearing HTTPS requests with normal client trust return expected responses from both members with generated AFD Host/path/query preserved. Correlate server TLS/SNI evidence, exact PLS targets and AFD request evidence; client HTTPS success alone cannot prove the origin hop was encrypted. | +| TLS-03 | AFD probes | Observe actual distributed HTTPS `GET /`, selected port, SNI and Host at each application, and 200 responses. Distinguish application probes from LB/Kubernetes probes and ordinary requests. | +| TLS-04 | Trust and name failures | In isolated fixtures, wrong hostname, expired certificate, untrusted root and missing intermediate chain each cause TLS failure. Use a chain fixture that actually fails at AFD, rather than assuming every omitted intermediate will do so. No request can succeed via HTTP, a public origin or disabled name checks. Restore valid configuration and prove recovery with fresh handshakes. | +| TLS-05 | Member-local policy failure and safe degraded service | Delete one member policy, add a duplicate, remove/change export opt-in or submit unsupported settings. Verify its exact owned origin absent/administratively disabled, negative delivery proof for that member, fresh projection/exclusion provenance and sustained HTTPS service from the agreeing eligible member. Report reason/degraded capacity; no silent omission or health-only quarantine. Prove annotation-only opt-out without a generation change, repair/re-admission after fresh validation, and unchanged MCS membership/EndpointSlices. With no eligible members or failed isolation, prove owned-route withdrawal and sustained negative edge proof. Read/transport/freshness failure contracts also get offline tests. | +| TLS-06 | Single/all-member TLS failures | Exercise one member's failed certificate/application/probe and recovery while observing the healthy member, then all-member failure. Record real AFD behavior, including possible routing to unhealthy origins and client errors. Never assert probe failure alone is a traffic firewall. TLS checks remain enforced. | +| TLS-07 | Same-name certificate renewal | Roll each member to a new trusted certificate/key with overlapping validity. Confirm reload, changed certificate identity through independent private inspection and new AFD TLS connections/requests, not merely existing pooled connections. No policy edit or certificate transfer to the hub. | +| TLS-08 | TLS hostname rotation | Deploy dual-name coverage everywhere, update each member policy and observe fail-closed withdrawal during disagreement. After agreement, generated hub policy and every origin use the new name; verify new SNI/traffic before retiring the old coverage. Interrupted rollout must not weaken checks or strand an old identity; zero downtime is not promised. | +| TLS-09 | Membership/export lifecycle | Add, remove and re-export one member; replace a Service UID/PLS. Only eligible current sources become origins, retired verified bindings are removed, and the remaining member still serves. A new member without ready policy/discovery remains explicitly excluded without taking down healthy members when absence/isolation is verified. Conflicting otherwise-valid TLS identities withdraw the affected route instead of selecting a convenient subset. No public or cleartext substitute. | +| TLS-10 | Coordinated HTTP-to-TLS migration | Observe old-route quiescence before incompatible listener/backend updates; stage/observe both-hop TLS before activation. Hand off the HTTPS URL and test interruption/restart at the boundary. Do not accept an enabled HTTP route to a TLS-only backend, introduce an implicit redirect or claim zero downtime. | +| TLS-11 | Controller restart, drift and isolation failures | Restart during convergence, member quarantine and after programming; verify idempotence, ownership and TLS invariants. Test attributed member policy/transport expiry, denied ARM inventory/disable/delete operations, unknown source/binding identity and TLS-setting drift offline; include authorized isolated live failures where practical. Continue healthy members only after verified isolation, otherwise request bounded owned-route withdrawal/suspension. If provider failures also block suspension, prove explicit enforcement-failure diagnostics/retries rather than false stopped-traffic status. Unknown reads never authorize unsafe recreation/deletion, stale member authority or downgrade. | +| TLS-12 | Final withdrawal, re-export and deletion | Remove the last eligible export/route; observe Disabled endpoint, absent owned route/origins, generated-policy cleanup and sustained negative edge proof. Verify re-export regenerates current policy and final Gateway profile cleanup. Shared references retain the needed projection. Member policies/certificates, DNS and unrelated Azure assets are not deleted. | +| TLS-13 | HTTP compatibility and capability opt-out | Re-run the existing private-HTTP proof unchanged in its authorized fixture. Offline member/hub startup/install tests prove HTTP works without experimental policy CRDs when TLS is off; absent/old-member TLS envelopes cannot authorize HTTPS. Disabling/downgrading cannot retain stale TLS authorization or restore HTTP. | +| TLS-14 | Generated-domain edge TLS and member-only UX | Operator hands off the observed HTTPS URL; customer with member-only Kubernetes credentials verifies the Azure-provided edge certificate/name/chain with plain curl and no insecure flags. Correlate both TLS hops and both members. Fresh HTTP requests must not reach the application or redirect into an implicitly supported path. No custom domain, customer hub access, edge Secret or public MCS shape/status addition is required. | +| TLS-15 | Policy coexistence, generated ownership and ingress authorization | An unmarked member policy is never implicitly exported and its spec/metadata/other-controller status remain untouched. Cover zero policies, one opted-in policy and duplicates: duplicates exclude that member regardless of age/name, identical settings or opt-ins; no winner is selected and no policy is deleted/edited. One shared policy may serve multiple implementations. Member Service/export/policy creates no AFD ingress without platform routing. Generated hub policy deletion repairs from current eligible agreement and verified exclusions. Offline tests cover foreign-name/manual hub-policy collisions, cross-member/namespace spoofing, source UID/generation/opt-in replay, partition/freshness and shared-reference cleanup; no unowned policy is adopted or overwritten. | + +### Evidence bundle and release decision + +For each scenario record inputs, expected/observed status, timestamps and timeout, +exact resource identities, sanitized configuration snapshots, request correlation, +member/application TLS and probe logs, controller events and cleanup outcome. +Include certificate public fingerprints/validity metadata where useful, never +private keys, tokens or cloud-config secrets. AFD and application logs must be +configured and accessible to the authorized test operator before the run. + +Separate the results into API/configuration, origin TLS traffic, frontend TLS, +failure/rotation and withdrawal/cleanup coverage. Mark skipped/blocked scenarios +explicitly. A retained resource set, absent negative proof, manual activation or +unverified certificate rotation cannot be reported as a complete E2E pass. +Use failures to revise implementation and examples; do not relax acceptance to +match whichever Azure projections happen to be populated. + +## Alternatives and deferred decisions + +| Alternative | Reason not recommended for the first subset | +|---|---| +| Gateway origin-TLS annotations | Preserve MCS shape without another CRD, but are Fleet-specific and scoped to a Gateway rather than the backend. The selected policy approach provides typed backend attachment/status and avoids ambiguous future multi-backend scope. | +| ServiceImport annotations or manually edited generated fields | Violates existing customer ownership/UX and makes aggregation own customer settings | +| Member ServiceExport hostname annotation | Preserves public MCS schema but is Fleet-specific; the selected member Service-targeted policy keeps hostname/trust typed, with only an export opt-in annotation on the policy | +| Manually applied hub BackendTLSPolicy | Superseded by member-driven projection; requires a separate identity-change handoff and can drift from current member intent | +| Platform ConfigMap for all TLS settings | Possible Azure-specific alternative, but a separate typed backend policy expresses target/validation/status more clearly | +| Kubernetes Secret or custom CA reference | AFD does not use arbitrary Kubernetes trust bundles; certificate keys belong at the application | +| Frontend managed certificate reused as origin certificate | AFD-managed edge certificates do not provision workload certificates/private keys | + +Member Service-targeted BackendTLSPolicy is now selected, with the additional +member CRD/watch, internal transport, source freshness and generated-policy +ownership work explicitly required above. The branch's one-minute refresh, +five-minute expiry and internal-CRD-first/safe-withdrawal rollout are described +above; they do not provide synchronous revocation across partitions. + +Per-member identities, multiple TLS ports, other policy fields and private-CA +backends require a separate reviewed design. If public-trust origin certificates +are unacceptable to a customer, record that product gap rather than weakening +validation or silently introducing a different ingress topology. + +## References + +- [MCS API concepts and ownership](https://multicluster.sigs.k8s.io/concepts/multicluster-services-api/) +- [Upstream ServiceImport shape](https://github.com/kubernetes-sigs/mcs-api/blob/master/pkg/apis/v1alpha1/serviceimport.go) +- [Upstream ServiceExport shape](https://github.com/kubernetes-sigs/mcs-api/blob/master/pkg/apis/v1alpha1/serviceexport.go) +- [Customer-provided AFD end-to-end TLS reference](https://learn.microsoft.com/nb-no/AZURE/frontdoor/end-to-end-tls?pivots=front-door-standard-premium) +- [AFD Private Link to an internal load balancer: SNI, Host and required validation](https://learn.microsoft.com/azure/frontdoor/standard-premium/how-to-enable-private-link-internal-load-balancer) +- [AFD health probes and all-origins-unhealthy behavior](https://learn.microsoft.com/azure/frontdoor/health-probes) +- [AFD origin Host behavior](https://learn.microsoft.com/azure/frontdoor/origin#origin-host-header) +- [Generated AFD endpoint domains](https://learn.microsoft.com/azure/frontdoor/endpoint#endpoint-domain-names) +- [AFD generated hostname versus custom domains](https://learn.microsoft.com/azure/frontdoor/standard-premium/how-to-add-custom-domain) +- [Gateway API v1.2.1 listener TLS/options schema](https://github.com/kubernetes-sigs/gateway-api/blob/v1.2.1/apis/v1/gateway_types.go) +- [Gateway API v1.2.1 BackendTLSPolicy definitions](https://github.com/kubernetes-sigs/gateway-api/blob/v1.2.1/apis/v1alpha3/backendtlspolicy_types.go) +- [Gateway API v1.2.1 policy status definitions](https://github.com/kubernetes-sigs/gateway-api/blob/v1.2.1/apis/v1alpha2/policy_types.go) +- [GEP-1748 TLS context](gep-1748-gateway-api.md#tls-and-certificates) +- [Existing implementation phases](gep-1748-implementation-plan.md#phase-8-add-https-and-certificate-lifecycle) +- [Optional ATM resilience, separate and deferred](gep-1748-optional-atm-resilience.md) diff --git a/docs/howtos/gateway-api-afd-configuration.md b/docs/howtos/gateway-api-afd-configuration.md index 505c1674..c5f05d0e 100644 --- a/docs/howtos/gateway-api-afd-configuration.md +++ b/docs/howtos/gateway-api-afd-configuration.md @@ -60,9 +60,16 @@ for multi-cluster application ingress through Azure Front Door (AFD) Premium. The only supported origin topology is **AFD with Private Link to internal load balancers**: -```text -Clients -> public AFD Premium edge -> Private Link -> member PLS - -> internal Azure Load Balancer -> application +```mermaid +flowchart LR + CLIENT["Clients"] --> AFD["Public AFD Premium edge"] + subgraph MEMBER["Private member origin"] + PLS["Private Link Service"] + ILB["Internal Azure Load Balancer"] + APP["Application"] + PLS --> ILB --> APP + end + AFD -->|"Private Link"| PLS ``` Zero public exposure applies to member application origins: they have no public @@ -81,8 +88,10 @@ The solution uses: cluster. - Optional attachment to an existing Azure Front Door WAF policy. -The examples configure HTTP listeners. HTTPS and certificate lifecycle are a -later implementation phase. +The existing examples configure HTTP listeners. The +[proposed end-to-end TLS workflow](#proposed-https-origins) adds HTTPS on both +connections using the generated AFD client hostname and separate member +certificates. It is not supported by the merged HTTP implementation. > [!IMPORTANT] > **AFD Private Link approval is asynchronous and is a provisioning dependency.** @@ -527,6 +536,895 @@ The DNS owner creates the public DNS record for `${APP_HOSTNAME}` only after the Gateway reports its AFD hostname. Follow the controller's status and instructions for DNS ownership and custom-domain validation. +## Proposed HTTPS origins + +> [!IMPORTANT] +> **Experimental branch capability, default off; not released or live-certified.** +> The [HTTPS-origin design](../design/gep-1748-https-origins-proposal.md) +> defines this end-to-end TLS UX, including HTTPS at the AFD edge. Do not apply +> these manifests to older HTTP-only controllers or infer production readiness +> from offline tests. +> The initial client-facing name is AFD's generated hostname; custom client +> domains and their DNS/certificate lifecycle remain deferred. + +The platform must first upgrade the hub's InternalServiceExport CRD, install the +pinned Gateway API v1.2.1 experimental BackendTLSPolicy CRD in hub and members, and +set `enableOriginTLS=true` in both existing manager charts. The member also needs +`enablePrivateLinkOriginDiscovery=true`; the hub needs `afd.enabled=true`. +The equivalent manager flag is `--enable-origin-tls=true`. Startup checks reject +missing prerequisites; TLS-off HTTP deployments do not need the experimental CRD. +See the [member chart](../../charts/member-net-controller-manager/README.md#opt-in-https-origin-metadata) +and [hub chart](../../charts/hub-gateway-controller-manager/README.md#opt-in-https-installation-and-upgrade) +for installation, upgrade and disable ordering. + +Member TLS intent is refreshed about every minute and expires after five minutes +without a matching observation. Metadata-only policy opt-out is watched without +requiring a policy generation change. Revocation is not instantaneous: member/hub +reconciliation and AFD propagation/in-flight requests still apply. The hub reports +excluded members/reasons and reduced capacity in existing Gateway status; it +publishes an address only after full owned-origin inventory excludes those members. +Before disabling or downgrading the hub, withdraw HTTPS routing and observe cleanup. + +**Customers touch member clusters only.** Application teams configure member +workloads, application-owned certificate delivery, Services, ServiceExports and Service-targeted +BackendTLSPolicies explicitly opted into Fleet export. Fleet validates/aggregates +their non-secret TLS intent and automatically creates the hub +ServiceImport-targeted policy. Customers and +operators never hand-author that projection or annotate generated ServiceImports. +The platform operator owns hub Gateway/HTTPRoute authorization and hub reads, +then supplies the HTTPS URL/readiness evidence through the existing channel. +No customer hub credentials are needed. Network owners separately approve +Private Link connections; this grants customers no extra Azure privileges. + +A ServiceExport or member TLS policy alone does not create an AFD endpoint or +authorize ingress. The platform's Gateway/HTTPRoute must explicitly reference +the backend. TLS identity changes thereafter come from member policy updates, +not manual hub policy edits. + +```mermaid +flowchart LR + CLIENT["Client"] + AFD["Public AFD Premium edge
Generated azurefd.net hostname
Azure-provided edge certificate"] + subgraph MEMBER["Private member origin"] + APP["Application
SNI: store-origin.example.com
Serving certificate: AKV CSI mount"] + end + CLIENT -->|"HTTPS: client TLS session"| AFD + AFD -->|"HTTPS over Private Link / PLS / internal LB
Separate origin TLS session"| APP +``` + +AFD terminates client TLS and opens a separate TLS connection to the application; +this is not TLS passthrough. Azure supplies and renews the edge certificate for +the generated hostname, for example `store-abc.z01.azurefd.net`. Customers do not +upload an edge certificate, configure public client DNS or copy their member key +to the hub. The member certificate is separate and still needs application-owned +issuance, secure storage, reload and renewal. The generated hostname is not a +customer-owned name such as `store.example.com`; that is outside this subset. +Treat the operator-provided URL as deployment output. It remains the same while +the AFD endpoint is retained; normal reconciliation and member join/leave must +not rotate it. Endpoint/Gateway replacement may change it, requiring the +operator to hand off a new URL and client owners to update their configuration. + +A stable custom domain is a production requirement when clients must retain +the same application URL across endpoint replacement. That support remains a +follow-up, not a feature of these examples. It needs coordinated DNS ownership, +AFD domain validation/routing, edge certificate provisioning/renewal and tested +replacement cutover/recovery; adding a CNAME alone does not configure HTTPS. +Customers would still use only member-cluster Kubernetes access, with platform +operators coordinating hub/AFD changes and authorized DNS/certificate owners. +If a replacement-independent URL is required, this generated-domain subset +does not yet meet that requirement. + +This keeps the [MCS ownership model](https://multicluster.sigs.k8s.io/concepts/multicluster-services-api/) +and adds no TLS fields to ServiceExport or ServiceImport. These examples use +Fleet's existing API group; they do not imply upstream MCS wire compatibility. + +Before onboarding, complete the [customer readiness checklist](#customer-readiness-checklist). +It assigns owners and required evidence for controller/CRD versions, Azure and +Kubernetes permissions, private networking/approval, application TLS and probes, +certificate issuance/rotation, monitoring, migration and teardown. Successful +manifest application is not sufficient. + +The proposed customer tasks are: + +- [Prepare member resources and complete the operator handoff](#proposed-setup-order). +- [Verify both TLS connections with curl and member logs](#proposed-verification-and-operational-expectations). +- [Renew certificates or change origin identity](#proposed-certificate-renewal-and-identity-changes). +- [Add or remove an exporting member](#proposed-member-lifecycle). +- [Troubleshoot failures](#proposed-https-origin-troubleshooting). +- [Remove the TLS configuration safely](#proposed-https-origin-cleanup). + +### Proposed member step: serve and export TLS + +**Actors:** Application team and certificate owner + +**Target:** Every participating member cluster + +Provision a certificate for a shared origin identity such as +`store-origin.example.com` and configure the application to serve TLS on port +8443. Each member can use a separate certificate/key for that identity. +Serve the complete leaf/intermediate chain rooted in an AFD-trusted public CA; +self-signed or internal-CA certificates do not work with this proposal. +Use existing application certificate tooling for issuance, secure storage, +reload, expiry monitoring and renewal; Fleet does not distribute private keys. + +#### Configure the serving certificate at the application + +| Item | Where configured | +|---|---| +| Origin certificate chain and matching private key | Application-owned AKV certificate mounted into each member pod using Secrets Store CSI | +| Certificate name/SNI that AFD must validate | Each member's Service-targeted BackendTLSPolicy `validation.hostname`; Fleet projects agreeing intent into the hub | +| Accepted certificate issuers | Policy `wellKnownCACertificates: System`, meaning AFD's trust store | +| Client-facing AFD certificate | Azure-provided/renewed certificate for the generated AFD hostname, selected by the operator's HTTPS listener | + +For this example, first create namespace `store` in each selected member if it +does not exist. The platform/certificate owner must already provide: + +- Secrets Store CSI Driver and Azure Key Vault provider on each member, with + CSI token requests for `api://AzureADTokenExchange` and a configured OIDC issuer. +- An Entra Workload Identity with least-privilege secret-read access to the + approved certificate's backing secret, and AKV network access from each member. +- A federated credential for **each member's issuer**, exact subject + `system:serviceaccount:store:store-origin`, and that audience. +- An exportable server certificate and full intermediate chain in AKV. Select + `objectType: secret`, not `cert` (public certificate only) or `key` (public key). + CSI cannot bypass non-exportable/HSM key policy. + +Use your controlled DNS name instead of `store-origin.example.com`. Replace the +AKV name, backing-secret name, tenant ID and identity client ID placeholders in +the YAML before applying it. These are identifiers, not credentials. The example +uses the latest secret version; set `objectVersion` to an approved backing-secret +version when pinning is required. Different members may reference different +vaults, identities or keys for the same DNS identity. + +The following illustrative NGINX application mounts one PEM bundle containing +the private key and leaf/intermediate chain, without Kubernetes Secret sync or +runner-local key files. CSI-native Workload Identity uses the pod's ServiceAccount +and SPC `clientID`; no application SDK token injection, ServiceAccount annotation +or pod workload-identity label is required for this CSI-only use. +See the [provider Workload Identity guidance](https://azure.github.io/secrets-store-csi-driver-provider-azure/docs/configurations/identity-access-modes/workload-identity-mode/). +It is the application, not an additional Fleet +ingress proxy. Existing applications should configure their own TLS stack +instead of replacing their workload with this example. Select an approved, +pinned image for production. + +```yaml +apiVersion: v1 +kind: ServiceAccount +metadata: + name: store-origin + namespace: store +automountServiceAccountToken: false +--- +apiVersion: secrets-store.csi.x-k8s.io/v1 +kind: SecretProviderClass +metadata: + name: store-origin-tls + namespace: store +spec: + provider: azure + parameters: + usePodIdentity: "false" + useVMManagedIdentity: "false" + clientID: "" + keyvaultName: "" + tenantId: "" + objects: | + array: + - | + objectName: + objectType: secret + objectFormat: pem + objectAlias: serving.pem + objectVersion: "" + filePermission: "0400" +--- +apiVersion: v1 +kind: ConfigMap +metadata: + name: store-api-nginx + namespace: store +data: + default.conf: | + log_format origin_tls '$hostname tls=$ssl_protocol sni=$ssl_server_name ' + 'host=$http_host afd_ref=$http_x_azure_ref "$request"'; + access_log /var/log/nginx/access.log origin_tls; + + server { + listen 8443 ssl default_server; + server_name store-origin.example.com; + ssl_certificate /etc/origin-tls/serving.pem; + ssl_certificate_key /etc/origin-tls/serving.pem; + ssl_protocols TLSv1.2 TLSv1.3; + + # Accept preserved Host and return 200 for AFD probes. + location / { + default_type text/plain; + return 200 "store-api member=member-1 pod=$hostname\n"; + } + } +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: store-api + namespace: store +spec: + replicas: 2 + selector: + matchLabels: + app: store-api + template: + metadata: + labels: + app: store-api + spec: + serviceAccountName: store-origin + automountServiceAccountToken: false + containers: + - name: app + image: nginx:stable-alpine # Illustrative; pin an approved digest. + ports: + - name: https + containerPort: 8443 + volumeMounts: + - name: origin-tls + mountPath: /etc/origin-tls + readOnly: true + - name: nginx-config + mountPath: /etc/nginx/conf.d + readOnly: true + volumes: + - name: origin-tls + csi: + driver: secrets-store.csi.k8s.io + readOnly: true + volumeAttributes: + secretProviderClass: store-origin-tls + - name: nginx-config + configMap: + name: store-api-nginx +``` + +The ServiceAccount, SPC and mount are member-local; the hub policy never fetches +certificate contents. The root-owned `0400` bundle is readable by this example's +NGINX master; adapt ownership/permissions deliberately for a non-root application. +Arrange application reload or rolling replacement on renewal: CSI rotation +updates files only when configured and does not make NGINX reload its certificate. +Use a directory mount, not `subPath`, so atomic CSI updates remain visible. +Change `member=member-1` to the actual member identifier in each cluster's +ConfigMap so responses can distinguish sources. The example logs TLS version, +SNI, HTTP Host and request correlation for diagnosis; these values are not an +authorization mechanism. Configure application-appropriate readiness probes +and log retention before production use. + +#### Export the private TLS Service + +The proposed Service and existing ServiceExport retain the private topology: + +```yaml +# Requires the experimental TLS capability in both member and hub managers. +apiVersion: v1 +kind: Service +metadata: + name: store-api + namespace: store + annotations: + service.beta.kubernetes.io/azure-load-balancer-internal: "true" + service.beta.kubernetes.io/azure-pls-create: "true" + service.beta.kubernetes.io/azure-pls-name: store-api-pls +spec: + type: LoadBalancer + selector: + app: store-api + ports: + - name: https + protocol: TCP + appProtocol: https # Declares TLS intent; does not provision a certificate. + port: 8443 # HTTPRoute selects this Service port. + targetPort: 8443 # The workload must already serve TLS here. +--- +apiVersion: networking.fleet.azure.com/v1alpha1 +kind: ServiceExport +metadata: + name: store-api + namespace: store +``` + +All members must export compatible ports/protocol intent. Fleet currently +compares the complete exported port lists, including `targetPort`; keep those +values consistent across members. AFD connects to Service port 8443, not directly +to targetPort. This example replaces the earlier HTTP Service only through a +coordinated migration, not an in-place change while the old HTTP route remains +active. Port 8443 is an example, not a required TLS port. + +### Proposed member step: declare origin identity and trust + +**Actor:** Customer application owner + +**Target:** Every participating member, in the Service namespace + +After the platform installs/enables the experimental member/hub capability and pinned +experimental BackendTLSPolicy CRDs, create this policy in each member: + +```yaml +# Member policy; requires the platform-installed experimental policy CRD. +apiVersion: gateway.networking.k8s.io/v1alpha3 +kind: BackendTLSPolicy +metadata: + name: store-api-origin-tls + namespace: store + annotations: + # Proposed Fleet export opt-in, not exclusive controller ownership. + networking.fleet.azure.com/export-to-fleet: "true" +spec: + targetRefs: + - group: "" + kind: Service # Local Service; never reference the hub import here. + name: store-api + validation: + hostname: store-origin.example.com # SNI/certificate identity, not HTTP Host. + wellKnownCACertificates: System # AFD's trust store, not the hub's. +``` + +This uses Gateway API's local Service target shape. Fleet-specific behavior is +the explicit policy export opt-in, cross-member aggregation and generated hub +ServiceImport-targeted policy; it is not a portable ServiceImport extension. +The target has exactly one +exported port and every eligible member must declare the same precise hostname and +`System` trust. Here `System` means AFD's trusted CA set, not a customer-uploaded +CA or either cluster's trust store. The policy includes no certificate keys. + +BackendTLSPolicy has no `spec.controllerName`. The proposed annotation's exact +string `"true"` opts this member policy into Fleet export; an unmarked policy +used by another implementation, such as Istio, is not exported just because +its Service is exported. The annotation is not an exclusive controller selector: +another implementation may also consume the same policy, and Fleet does not +edit its policy fields or other-controller status. + +For Fleet TLS eligibility, exactly one policy in the Service namespace may +target that core Service, and it must explicitly opt in. Multiple policies +make that member ineligible for AFD even if their settings match or only one is +opted in; an unmarked policy for another implementation still counts. Fleet +does not choose an oldest/newest policy or combine settings. + +This is a stricter Fleet subset, not Gateway API's oldest-policy conflict +resolution or a cluster-wide admission restriction. Fleet does not delete/edit +other implementations' policies. Coordinate duplicate targets with their owners; +a single shared policy may serve both implementations if their requirements +agree. Removing duplicates must be followed by fresh validation and agreement +before Fleet re-admits that member's origin. + +`caCertificateRefs` would configure trust anchors, not the application's serving +certificate/key; arbitrary CA references are unsupported by this AFD proposal. +The certificate/key mount remains at the workload. Fleet transports only validated +hostname/trust, resolution state, source identity/generation and observed export +opt-in through its internal export metadata; no new public ServiceExport/ServiceImport fields. +Missing, unmarked, duplicate, invalid, unreadable or stale policy intent excludes +that member from AFD eligibility, not baseline MCS networking. Fleet records the +member/reason and verifies its exact origin absent or administratively disabled/ +removed before continuing service through agreeing eligible members. It never +silently omits a source, assumes a hostname for an older member or treats a failed +health probe as administrative isolation. + +All otherwise eligible, locally valid member intents must agree on the shared +TLS hostname/trust/port. Conflicting valid identities withdraw the affected route; +Fleet does not choose a majority or exclude a valid identity to manufacture +agreement. No eligible origins, incomplete authoritative source inventory, +shared dependency/ownership errors or inability to verify safe origin isolation +also require route withdrawal/suspension. Isolation and propagation are +asynchronous; errors and temporary suspension remain possible. +If Azure errors also prevent suspension, operators must escalate the explicit +enforcement failure; a requested withdrawal is not proof that traffic stopped. + +Customers never apply/edit/delete the generated hub policy. Fleet owns its +creation, updates, drift repair and cleanup, based on current eligible-member +agreement and verified exclusion provenance. +Read failures/partitions cannot preserve authorization indefinitely; bounded +freshness behavior still needs implementation review and testing. +Removing/changing the member policy's export annotation withdraws that member's +TLS authority and requires origin isolation, not automatic global withdrawal, +HTTP fallback or changes to baseline MCS exports. Annotation-only changes must +be observed even though generation does not change. The hub projection needs no +customer export marker. Operators report exclusions, isolation state and +degraded capacity through existing diagnostics and the platform handoff. + +### Proposed operator step: authorize ingress + +For completeness, the operator-owned end-to-end TLS Gateway and HTTPRoute are: + +```yaml +apiVersion: gateway.networking.k8s.io/v1 +kind: Gateway +metadata: + name: store-private-global + namespace: store + annotations: + networking.fleet.azure.com/afd-sku: Premium_AzureFrontDoor +spec: + gatewayClassName: azure-fleet-afd + listeners: + - name: https + protocol: HTTPS + port: 443 + tls: + mode: Terminate # AFD opens a separate TLS connection to the origin. + options: + networking.fleet.azure.com/afd-default-certificate: "true" + allowedRoutes: + namespaces: + from: Same +--- +apiVersion: gateway.networking.k8s.io/v1 +kind: HTTPRoute +metadata: + name: store-private-api + namespace: store +spec: + parentRefs: + - name: store-private-global + sectionName: https + rules: + - matches: + - path: + type: PathPrefix + value: / + backendRefs: + - group: networking.fleet.azure.com + kind: ServiceImport # Created by Fleet, not applied by the customer. + name: store-api + port: 8443 +``` + +The HTTPRoute keeps its existing Fleet ServiceImport backend shape and selects +the origin TLS port independently of edge port 443. The proposed domain-prefixed +`tls.options` entry selects Azure's certificate for the generated AFD hostname, +not a member certificate or a hub Secret. This is a Fleet-specific Gateway API +extension; no MCS field changes. It satisfies the pinned Gateway TLS schema's +nonempty-options alternative to certificate references; branch envtest checks +admission and controller reconciliation. No `certificateRefs`, explicit listener/route +hostnames, extra listener, custom domain or passthrough is supported here. + +The operator/controller must configure accepted edge protocols as HTTPS only, +associate the default domain and leave HTTP redirection disabled. It separately +uses HTTPS-only forwarding and HTTPS `GET /` probes on the selected backend port, +with certificate-name checks enforced. HTTP is not an implicit alternate path +on either hop. Existing explicit HTTP-preview deployments remain unchanged. +Application requests preserve the generated AFD Host independently of origin +SNI. The application must accept that Host and return 200 to actual AFD probes. +Probe Host/SNI behavior must be verified before release. + +### Proposed setup order + +**Actors:** Customer application/certificate owner in members; platform operator +in the hub; PLS owner in Azure + +This sequence requires the **experimental TLS-enabled branch images, not the +current released HTTP-only images**. It has not been live-certified. Customers +use only `${MEMBER_CONTEXT}`. Only the operator +uses `${HUB_CONTEXT}` in steps explicitly assigned below. The example namespace +is `store`. Do not reuse these names over an existing deployment without a +migration plan. + +Save the preceding YAML blocks as follows, after replacing the domain, member +identifier and illustrative image as appropriate: + +| File | YAML contents | Actor and target | +|---|---|---| +| `origin-tls-workload.yaml` | ServiceAccount, SecretProviderClass, ConfigMap and Deployment | Customer, each member | +| `private-tls-service.yaml` | Service and ServiceExport | Customer, each member | +| `origin-tls-policy.yaml` | BackendTLSPolicy targeting Service | Customer, each member | +| `private-origin-tls-gateway.yaml` | Gateway and HTTPRoute | Platform operator, hub only | + +1. The platform operator installs the TLS-capable candidate member/hub images, + updated internal transport CRD in the hub first, pinned policy CRDs in the + hub and members, and scoped RBAC, then explicitly enables the capability. No + automatic production enablement is implied. Set both charts' + `enableOriginTLS=true` (manager flag `--enable-origin-tls=true`). + Confirm managed hub membership, + GatewayClass acceptance and member private discovery using the prerequisites + above. The operator verifies the policy CRD in the hub and every member: + + ```bash + kubectl --context "${HUB_CONTEXT}" \ + get crd backendtlspolicies.gateway.networking.k8s.io + kubectl --context "${MEMBER_CONTEXT}" \ + get crd backendtlspolicies.gateway.networking.k8s.io + ``` + +2. The customer ensures namespace `store` exists in every member and the + operator has prepared AKV/CSI/federation as above, then applies its workload, policy and + export files with matching hostname/trust and explicit policy export opt-in + in all participating members: + + ```bash + kubectl --context "${MEMBER_CONTEXT}" --namespace store \ + apply -f origin-tls-workload.yaml -f origin-tls-policy.yaml \ + -f private-tls-service.yaml + kubectl --context "${MEMBER_CONTEXT}" --namespace store \ + rollout status deployment/store-api + kubectl --context "${MEMBER_CONTEXT}" --namespace store \ + get service/store-api serviceexport/store-api -o yaml + kubectl --context "${MEMBER_CONTEXT}" --namespace store \ + describe backendtlspolicy store-api-origin-tls + ``` + + Expect the private Service address, `Valid=True` and `Conflict=False`. + Check actual certificate presentation with the private preflight below; + Deployment availability alone does not prove a trusted TLS handshake. + Member policy events diagnose local selection/transport errors, not complete + hub convergence. Do not expect fabricated top-level policy conditions or + a member policy ancestor referencing a Gateway in another cluster. + +3. The platform operator authorizes this logical service for ingress, ensures + namespace `store` exists in the hub, inspects the generated import and applies + only the routing file. Fleet creates the hub policy automatically once the + current eligible member intents agree and excluded origins are verified + isolated; there is no hub-policy apply step: + + ```bash + kubectl --context "${HUB_CONTEXT}" --namespace store \ + get serviceimport store-api -o yaml + kubectl --context "${HUB_CONTEXT}" --namespace store \ + apply -f private-origin-tls-gateway.yaml + ``` + + Expect the intended active exporting members and compatible HTTPS port + metadata. Fleet currently puts imported port metadata in `status.ports`. + Do not add a new ServiceImport spec or patch its status to make this work. + +4. The PLS owner verifies and approves each exact AFD-to-PLS connection using + [the existing approval procedure](#4-approve-the-afd-private-endpoint-connections). + The operator performs the configuration and both-hop TLS checks below, then + supplies the observed `https:///` URL and sanitized readiness + evidence to the customer. Policy creation, CRD presence and an approval + command's success are not traffic proof. No hub credential handoff is needed. + +### Proposed verification and operational expectations + +**Actors:** Platform/network owners for hub/Azure checks; customer for curl +and member application logs + +The network owner still approves each exact AFD-to-PLS connection using the +existing manual workflow. The platform operator verifies policy acceptance, +HTTPRoute references, HTTPS listener and the observed owned TLS graph, then +separately proves client HTTPS, private HTTPS traffic/probes and both-member +delivery. Programmed does not certify a live handshake, certificate expiry, +approval or application health. + +A member's missing/deleted/invalid policy or removed export opt-in requires +explicit isolation of that member's owned origin. Eligible members may continue +serving under one unambiguous TLS contract after isolation is verified. With +no eligible origins, conflicting valid TLS intent, shared failures or unsafe +isolation, withdraw/suspend the affected route. Never restore HTTP, remove the +ServiceExport or change baseline MCS membership/EndpointSlices. +Certificates with an untrusted chain, wrong name or expired validity fail TLS; +neither disabling certificate checks nor HTTP fallback is supported. AFD can +still send requests when all origins fail health probes, so probe failure is +not a traffic-blocking guarantee. + +For same-hostname renewal, reload the new valid certificate at each workload +and verify fresh TLS connections. For an identity change, deploy certificates +covering both names everywhere before updating the policy, verify convergence +and traffic, then retire the old name. No public member endpoint, customer-issued +edge certificate, Traffic Manager deployment or hub private-key access is +required. Azure's default-domain edge certificate does not renew the member +certificates. + +See the [TLS boundaries, migration and validation gates](../design/gep-1748-https-origins-proposal.md) +and the [customer-provided AFD TLS guidance](https://learn.microsoft.com/nb-no/AZURE/frontdoor/end-to-end-tls?pivots=front-door-standard-premium). + +**Operator-only configuration checks.** Inspect configuration without assuming +that top-level policy conditions exist: +Generated hub BackendTLSPolicy acceptance is recorded under the real managed +Gateway's ancestor entry. The example generated name is derived from the target +import (`store-api-origin-tls`), not copied from an arbitrary member policy name. + +```bash +kubectl --context "${HUB_CONTEXT}" --namespace store \ + get backendtlspolicy store-api-origin-tls -o yaml +kubectl --context "${HUB_CONTEXT}" --namespace store \ + get gateway store-private-global -o yaml +kubectl --context "${HUB_CONTEXT}" --namespace store \ + get httproute store-private-api -o yaml +``` + +Expected proposed configuration signals: + +- Every authoritative source is accounted for as eligible or explicitly excluded; + eligible intent agrees and source identities/freshness are verified. The + generated policy matches that aggregate, exclusion provenance and target import. +- Excluded members have no owned origin or their exact origins are observed + administratively disabled/removed, with member/reason/degraded-capacity + diagnostics. Probe health alone does not prove isolation. +- The generated hub policy's real Gateway ancestor has `Accepted=True` for the + current generation. Its prior acceptance alone is not current source authority. +- HTTPRoute parent `Accepted=True` and `ResolvedRefs=True`. +- HTTPS/443 listener with the supported default-certificate option, current + `Programmed=True` and the observed generated AFD hostname in `status.addresses`. +- Observed owned AFD route accepts only HTTPS, links the default domain and + does not enable HTTP redirection. +- Observed owned AFD origins/routes use the intended PLS targets, TLS hostname, + HTTPS port, HTTPS-only forwarding/probes and certificate-name validation. + +The operator retrieves the actual generated hostname for the customer handoff: + +```bash +AFD_HOSTNAME=$(kubectl --context "${HUB_CONTEXT}" --namespace store \ + get gateway store-private-global -o jsonpath='{.status.addresses[0].value}') +test -n "${AFD_HOSTNAME}" || { echo "Gateway has no AFD hostname" >&2; exit 1; } +printf 'Customer URL: https://%s/\n' "${AFD_HOSTNAME}" +``` + +**Customer client check; no hub access.** Set `AFD_HOSTNAME` to the hostname the +operator supplied, without a scheme or path, then use plain `curl`: + +```bash +AFD_HOSTNAME='' +curl --verbose --fail-with-body --show-error "https://${AFD_HOSTNAME}/" +``` + +Curl must verify the edge certificate for that hostname using its normal trust +store. Do not substitute `store-origin.example.com`, override the Host header, +add `-k`/`--insecure` or rely on HTTP redirects. An edge certificate/trust error +is distinct from a successful edge handshake followed by an origin TLS error. + +For correlated delivery proof, repeat with fresh request identifiers: + +```bash +curl --verbose --fail-with-body --show-error --get \ + --data-urlencode "proof=$(date +%s)-${RANDOM}" \ + "https://${AFD_HOSTNAME}/" +``` + +Expect a `store-api member=... pod=...` response from the sample. Repeat with +fresh IDs and correlate application logs from each member: + +```bash +kubectl --context "${MEMBER_CONTEXT}" --namespace store \ + logs -l app=store-api --all-containers=true --prefix --since=10m +``` + +Confirm both intended members, the policy SNI, negotiated TLS, incoming AFD Host +and matching request IDs. Separately observe real HTTPS health probes returning +200. Different successful responses alone do not prove the private target or +TLS settings; correlate the exact PLS binding, AFD evidence and application logs. +Fewer samples need not exercise every member, so stop and investigate rather +than declaring success after an arbitrary request count. + +Curl's edge certificate verification proves the client-to-AFD TLS connection, not +the origin hop. Correlated member TLS/SNI logs and exact private bindings prove +the second connection. Both are required for an end-to-end claim. The operator +also verifies that fresh HTTP requests are not forwarded to the application; +an AFD error page is not a successful application response. + +### Proposed certificate renewal and identity changes + +**Actors:** Customer certificate/application owner in members; platform operator +for hub projection observation, not policy edits + +For renewal with the same hostname, use the approved certificate automation to +create a new AKV certificate/backing-secret version. Verify its chain, key and +hostname without exposing private contents. If using a pinned version, update +that member's SPC `objectVersion` and apply it first. With an unpinned reference, +configured CSI autorotation can refresh the mount; without autorotation a fresh +pod mount retrieves the current version. Confirm the expected mounted version +through `SecretProviderClassPodStatus` and public certificate metadata. +Reload NGINX or roll out one member at a time: + +```bash +kubectl --context "${MEMBER_CONTEXT}" --namespace store \ + rollout restart deployment/store-api +kubectl --context "${MEMBER_CONTEXT}" --namespace store \ + rollout status deployment/store-api +``` + +A rollout is one example reload method, not a zero-downtime guarantee. Never +render the mounted bundle, export private material into CI, or sync it to a +Kubernetes Secret just to trigger reload. +Verify the new certificate through direct private inspection and fresh +through-AFD TLS connections/requests before updating the next member. Keep +overlapping certificate validity and a verified rollback option. No policy edit +or hub certificate copy is needed for same-name renewal. + +For an origin hostname change, deploy certificates covering both old and new +names to every participating member first. Update `validation.hostname` in +each member's `origin-tls-policy.yaml` and apply it in every member: + +```bash +kubectl --context "${MEMBER_CONTEXT}" --namespace store \ + apply -f origin-tls-policy.yaml +``` + +Disagreement during a staggered update withdraws the affected AFD route; +coordinate a maintenance window, not a zero-downtime promise. Once all otherwise +eligible intents agree, Fleet updates the generated hub policy/AFD graph automatically. The +operator verifies the hub projection and the customer verifies member rollout, +new SNI and through-AFD responses. Only then retire old-name coverage. Do not +edit the generated hub policy, MCS schemas/status or public client DNS. +Record any excluded members; they cannot rejoin without fresh validation against +the current shared contract. + +### Proposed member lifecycle + +**Actors:** Application/placement owner and network owner + +To add a member, the customer repeats the certificate/workload/export setup in +that cluster, including its matching opted-in local policy before export, and +verifies compatible exported ports/private discovery. A newly participating export +without current matching policy is explicitly excluded until ready. Verified +absence/isolation lets healthy members continue; a conflicting otherwise-valid +TLS identity instead makes the shared contract ambiguous and withdraws the route. +The +network owner approves any newly required correlated PLS connection; operators +and the customer then prove that member's response and TLS/probes. +Joining the Fleet alone does not add a ready origin. + +To stop exporting this application from one member, delete only its export: + +```bash +kubectl --context "${MEMBER_CONTEXT}" --namespace store \ + delete serviceexport store-api +``` + +Observe that Fleet retires that member's owned origin and remaining eligible +members still serve. Do not edit `ServiceImport.status.clusters`. Removing the +last eligible origin withdraws the AFD route/origins and disables the retained +endpoint; it does not make public/HTTP origins eligible. Keep the member Service +and certificate until withdrawal is confirmed. Re-exporting must repeat +eligibility, approval and traffic verification. + +### Proposed HTTPS-origin troubleshooting + +| Symptom | Check first | Safe response | +|---|---|---| +| Member policy cannot be created | Future member TLS-capable release, pinned experimental CRD and local namespace RBAC | Platform operator corrects installation; customer uses only member permissions, never new MCS TLS fields | +| Member intent unresolved or disagrees | Exact export opt-in, policy targets/counts, member identity/freshness, exclusion reason/isolation state and eligible hostname/trust agreement | Isolate a member-local policy failure and continue verified agreeing members. Coordinate duplicate targets with their owners. Conflicting valid identities, no eligible origins or unsafe isolation withdraw the affected route; never choose by age/majority or hand-edit the hub policy | +| Generated hub policy absent/conflicted | Current internal source UIDs/generations/freshness, target import, explicit routing and verified generated ownership | Operator resolves transport/ownership/routing failures; never adopt a foreign policy or edit generated MCS state | +| Export missing/conflicted or no eligible origin | Matching Service/ServiceExport identity, complete exported port lists, active membership and ILB/PLS discovery | Fix the source/permissions or let discovery converge; never patch generated membership or substitute a public endpoint | +| Programmed is false or hostname absent | Gateway/route conditions, controller events, Azure read/write permissions and observed TLS/private configuration | Resolve the specific dependency/drift; do not manually enable an unverified ARM graph | +| Programmed is true but requests fail | Exact backend-side PLS approval, actual packet path, certificate name/chain/expiry and application logs | Treat programming as configuration only; verify approval and each TLS/network boundary independently | +| Curl rejects the edge certificate | Exact operator-provided generated hostname, client trust store/time, edge certificate chain and HTTPS route association | Platform operator investigates edge setup; never bypass validation or replace the URL with the origin hostname | +| TLS certificate failure | Policy hostname versus presented SAN, intermediates, AFD trust, expiry, server reload and actual SNI | Repair the workload certificate/configuration; never disable name checks, use insecure client probes or fall back to HTTP | +| Probes fail but direct requests work | Actual probe Host/SNI, HTTPS port, GET `/`, 200 response and firewall/application rules | Make the supported probe succeed; a local curl or Kubernetes/LB probe is not an AFD probe | +| Only one member responds | Explicit exclusion/reason/isolation state, remaining capacity, member weights/discovery, AFD probe failures and fresh correlated samples | Distinguish intentional degraded service from unobserved failure; prove excluded-origin isolation and repair/revalidate that member before re-admission. Do not claim both-member success or infer distribution from a fixed request count | +| CSI mount fails or pod cannot start | Member CSI driver/provider, SPC parameters, OIDC issuer/federated subject/audience, identity secret-read scope and AKV network access | Repair the specific prerequisite; never fall back to a node identity, public origin, printed key or disabled TLS validation | +| Failures after renewal | AKV backing-secret version, observed CSI mounted version, certificate metadata, reload/rollout completion and new TLS handshakes | Restore a known-valid version if authorized and verify recovery; old pooled connections can hide a bad reload | + +Collect sanitized resource conditions, relevant controller events and correlated +AFD/application logs for escalation. Never include private keys, tokens or +cloud-config secrets. There is no guaranteed propagation duration or automatic +certificate-expiry signal from Fleet in this proposal. + +### Proposed HTTPS-origin cleanup + +**Actors:** Platform operator first; customer application/certificate owners +in members afterward + +The customer requests retirement through the platform handoff; no customer hub +deletion commands are required. The platform operator deletes only the named +hub resources and waits for Gateway-owned finalizers/AFD cleanup; choose an +appropriate bounded wait window with `CLEANUP_TIMEOUT` (for example `45m`, not +an Azure completion guarantee): + +```bash +kubectl --context "${HUB_CONTEXT}" --namespace store \ + delete httproute store-private-api --timeout="${CLEANUP_TIMEOUT}" +kubectl --context "${HUB_CONTEXT}" --namespace store \ + delete gateway store-private-global --timeout="${CLEANUP_TIMEOUT}" +``` + +Stop if deletion fails or times out. Inspect finalizers, ownership and controller +errors; do not remove finalizers manually. Confirm owned AFD cleanup and no +application delivery. Fleet removes the generated hub policy once no authorized +route references or target export set remain, while preserving projections +still needed by other Gateways. Do not manually delete/adopt the hub projection +or remove finalizers to hide cleanup failures. + +After the operator confirms withdrawal/cleanup, the customer deletes this +example's ServiceExport, Service, local TLS policy and workload in each member +only when they are no longer needed: + +```bash +kubectl --context "${MEMBER_CONTEXT}" --namespace store \ + delete -f private-tls-service.yaml -f origin-tls-policy.yaml \ + -f origin-tls-workload.yaml --timeout="${CLEANUP_TIMEOUT}" +``` + +The workload file also deletes its SPC and ServiceAccount; confirm no other +workload uses them before deletion. Retire dedicated AKV certificate automation, +federated credentials and grants separately through their owners, only after +checking for other consumers. Never delete a shared AKV certificate or identity +as incidental Kubernetes cleanup. +Keep shared DNS, namespaces, certificate issuers and unrelated Azure assets. +Fleet does not delete customer-owned member policies or application +certificates as part of hub cleanup. + +### Customer readiness checklist + +This is the proposed acceptance checklist, not evidence that a customer has +completed it. The ingress owner should collect the listed evidence before +production onboarding. Existing HTTP prerequisites still apply; TLS does not +replace them. Unsupported requirements must be identified before deployment, +not worked around by weakening TLS or opening a public origin. + +#### Platform, access and private infrastructure + +| Requirement | Accountable owner | What must be correct / evidence to collect | +|---|---|---| +| Managed hub and membership | Fleet platform operator | Fleet has a managed hub; each intended exporting cluster is a healthy member of that Fleet. Hubless Fleet is not supported. Record explicit hub/member contexts and application namespace. | +| Controller and schema compatibility | Fleet platform operator | Select verified TLS-capable member/hub images. Install updated internal transport CRDs in the hub first and pinned experimental BackendTLSPolicy CRDs in participating members and hub before enabling TLS. A merge is not a release. Missing/old-member TLS envelopes are unknown, not authority to assume a hostname. | +| Explicit enablement and ownership | Fleet platform operator | Enable existing AFD provisioning and the experimental TLS capability deliberately. Validate the managed GatewayClass. Use the existing manager/leader election, not competing installations or manual Azure writers for its profile. | +| Kubernetes authorization | Platform and ingress owners | Customers manage member workloads, ServiceAccounts/SPCs, Service/ServiceExport and local Service-targeted TLS policies only. Member controllers read local policies and write only their reserved hub internal exports. Hub controllers own generated-policy lifecycle/status; operators authorize Gateway/HTTPRoute and hand off endpoint/evidence. No customer hub credentials, generated-policy writes, Secret-reading controller permission or shared namespace access for members. | +| Hub Azure identity | Azure resource owner | Configure and test the approved identity/cloud-config, subscription and controller AFD resource group. Grant required scoped AFD lifecycle/inventory access plus `Microsoft.Network/privateLinkServices/read` on every actual PLS. Kubernetes RBAC and credential construction alone prove neither Azure authentication nor authorization. | +| Member discovery identity | Azure resource owner | Enable private-origin discovery independently of ATM. Grant member controller `Microsoft.Network/loadBalancers/read` and `Microsoft.Network/privateLinkServices/read` at the resource groups actually containing those resources. Confirm resource-group overrides if used. | +| AKS resource provisioning | Cluster/network owner | AKS cloud-provider identity, subnet configuration and available network capacity permit the internal LB/PLS to be created. Member discovery is read-only and cannot repair provisioning. Verify the resulting Azure resources, not just Service annotations. | +| Private origin topology | Cluster/network owner | Use internal LoadBalancer plus PLS, one verified IPv4 frontend and no public frontend association. Check exact PLS-to-frontend binding, location and successful provisioning; a matching resource name is not proof. | +| Supported Private Link placement | Network and ingress owners | Confirm the selected AFD Premium/PLS regional combination, subscription/provider availability and current service quotas support the topology. Do not substitute AFD Standard, an unsupported region, public connectivity or another PLS when provisioning fails. | +| Packet path and load-balancer probes | Cluster/network owner | Validate Service selectors, ready endpoints, port/targetPort mapping, NSG/firewall/NetworkPolicy rules and ILB-to-workload reachability for the actual PLS/NAT path. Preserve AKS/LB probe reachability separately from AFD probes. If PLS proxy protocol is enabled outside this example, the workload must support it; do not assume normal TLS accepts a proxy-protocol preamble. | +| Authorized connection approval | PLS/network owner | Permit the intended AFD request, verify its exact attribution and approve each required PLS connection. Visibility/request access, approval authorization and discovery readiness are different checks. No empty pending list, request message or AFD Pending projection proves approval. Never enable broad auto-approval as a shortcut. | +| Capacity and cost | Platform owner | Budget Premium, Private Link, load balancers, certificate operations and monitoring. Respect existing per-backend and aggregate limits, including the forty-origin backend guard and PLS/port-sharing constraints. No TLS scale or SLA claim follows from a two-member demonstration. | + +Use the [hub installation guide](../../charts/hub-gateway-controller-manager/README.md#enabled-installation-prerequisites) +and [member discovery guide](../../charts/member-net-controller-manager/README.md#private-origin-discovery-for-zero-public-exposure-ingress) +for existing identity and discovery configuration. Future TLS flags/CRD +installation steps must be documented with the implementation, not guessed +from this proposal. + +#### Application, certificates and routing intent + +| Requirement | Accountable owner | What must be correct / evidence to collect | +|---|---|---| +| Compatible logical service | Application owner | Identical namespace/Service name and compatible exported port fields across members, a matching ServiceExport in each member, valid/unconflicted current export state and active aggregated membership. Do not hand-author ServiceImport or edit InternalServiceExport. | +| Explicit TLS protocol | Application and ingress owners | Exactly one exported TCP port with `appProtocol: https`; HTTPRoute selects that ServiceImport port, not targetPort. Every eligible member actually speaks TLS there. A port named https or numbered 443 is not evidence. | +| Backend policy | Customer application owner; Fleet controllers project | Each eligible member has exactly one applicable local Service-targeted policy with `networking.fleet.azure.com/export-to-fleet: "true"`, matching precise hostname/`System` trust and no unsupported fields. Duplicates, including unmarked/identical ones, exclude that member; no age/name precedence or cluster-wide admission restriction. All otherwise eligible intents must agree; valid identity conflicts withdraw the route, never majority selection. Fleet generates the hub policy automatically; policy/export alone does not authorize ingress or issue certificates. | +| DNS identity and issuance authority | Certificate/DNS owner | Control the chosen DNS name and the CA validation/renewal method. Distinguish origin identity from public application DNS and member-local Service DNS. Public certificate issuance may expose names through certificate transparency; choose an appropriate non-sensitive identity. A private endpoint is not a certificate issuer. | +| Trusted certificate and chain | Certificate/application owner | Each member presents an in-date server certificate for the configured hostname, with the correct private key and complete intermediate chain, rooted in AFD's allowed trust set. Verify SAN/name coverage, intended server use and chain compatibility; local OS trust is not proof of AFD trust. | +| TLS protocol compatibility | Application owner | Configure a TLS server compatible with AFD's documented origin TLS 1.2/1.3 negotiation and organizational policy. Do not assume a frontend cipher/minimum-version setting configures the origin hop, or require origin client certificates: AFD origin mTLS is unsupported. | +| Certificate deployment | Application/certificate owner | Prepare exportable AKV certificate/backing secret, CSI/provider and exact per-member Workload Identity federation/least-privilege secret-read access; restrict mounts, reload every serving replica and prove the presented certificate. Distinct member keys are allowed; Fleet never reads AKV or delivers private keys. | +| SNI and HTTP Host | Application owner | Select the right certificate for the policy SNI while accepting the independently preserved request Host. Confirm virtual-host/allowlist/redirect behavior; differing names must not cause wrong certificates, unexpected redirects or rejected requests. | +| AFD application health probe | Application and platform owners | HTTPS `GET /` on the selected port returns 200 with the actual AFD probe Host/SNI and no interactive authentication or HTTP redirect. Account for distributed probe load. This is separate from Kubernetes readiness and the Azure LB probe. A different mandatory path or probe protocol is a product gap for this subset. | +| Gateway/route subset | Platform operator | One HTTPS/443 listener with Terminate/default-certificate option, HTTPS-only accepted protocols, no redirect, default-domain association, same-namespace backend reference, one logical backend port and root PathPrefix. Preserve allowedRoutes authorization. Extra listeners, certificateRefs, custom domains, path expansion, filters and WAF remain unsupported here. | +| Client-facing protection | Platform operator and customer client owner | Azure provides/renews the generated hostname's edge certificate. Operator hands off the actual HTTPS URL; customer uses normal client name/chain verification. No customer client-domain DNS or edge key is required. Do not treat edge renewal as origin renewal. Default-domain TLS controls must meet client policy; stricter/custom-domain requirements are a separate product gap. | +| Client URL continuity | Platform operator and customer client owner | Agree whether the URL must survive endpoint/Gateway replacement. Normal reconciliation/member churn must retain the endpoint and URL, but replacement may require a new URL and client updates. Replacement-independent identity requires the deferred custom-domain lifecycle; do not claim this subset meets that production requirement. | + +#### Verification, change management and operations + +| Requirement | Accountable owner | What must be correct / evidence to collect | +|---|---|---| +| Configuration evidence | Platform operator; customer for local diagnostics | Account for every source: eligible intent/provenance/freshness or explicit exclusion/reason and verified origin isolation. Verify eligible agreement, generated hub policy ownership/real ancestor status, route/Gateway state and exact AFD TLS properties. Hand sanitized readiness/degraded-capacity evidence to the customer. Prior acceptance or hostname publication is not current authorization or traffic proof. | +| Both-hop/private-path TLS evidence | Platform/network owners and customer application/client owners | Client verifies the edge hostname/chain via HTTPS; fresh request identifiers obtain expected responses from both members. Operator/customer correlate AFD and member TLS/request/probe evidence, private bindings, origin SNI and preserved AFD Host/path/query. Prove HTTP is not an application path. A direct private curl is diagnostic only; client HTTPS alone does not prove origin TLS. | +| Failure acceptance | Ingress/application owners | Prove local policy failure isolates the exact origin while eligible members serve, with explicit degraded diagnostics and fresh negative delivery evidence. Prove no-eligible-origin, conflicting-valid-intent and unsafe-isolation cases withdraw/suspend the route. Separately test wrong-name/expired/untrusted/incomplete-chain handshakes. No HTTP fallback; AFD can route to all-unhealthy origins, so health checks alone are not isolation. Propagation/in-flight errors remain possible. | +| Renewal ownership | Certificate/application owner | Establish automated renewal, deployment/reload checks and expiry alerts with enough lead time for the CA/rollout process. Test same-name renewal and fresh handshakes; retaining a valid policy does not stop a workload certificate expiring. | +| Migration and rollback | Ingress/application owners | Plan the quiesce/withdrawal and member rollout order, maintenance window if needed, dual-name coverage for hostname rotation and explicit rollback. Do not switch a live HTTP route's backend into TLS in place or remove policy to recover an HTTPS outage. | +| Ongoing monitoring | Platform/application owners | Monitor AFD TLS/probe/request failures, application errors, certificate expiry, controller reconciliation and export/discovery state. Assign an on-call owner across each boundary; Programmed is configuration evidence, not a traffic-health or certificate-expiry alert. | +| Incident diagnosis | Platform/network/application owners | Separate CA/name/expiry, application Host/probe rejection, LB/PLS packet path, approval, Azure authorization and controller drift. Collect sanitized exact-resource and request correlation evidence; do not publish keys or raw credentials. Allow asynchronous propagation without promising a fixed completion time. | +| Join, leave and application replacement | Platform/application owners | Reapply certificate, local policy and port requirements for each new/repaired member. Verify source UIDs, export conflicts, PLS replacement and eligible agreement. Explicitly diagnose/isolate an unready member rather than silently omit it or unnecessarily withdraw healthy members. Re-admit only after fresh validation/private programming; conflicting valid TLS identities remain a shared failure. Membership alone is not readiness. | +| Teardown and retention | Platform/network owners and customer certificate/application owners | Customer requests retirement; operator removes hub routing and waits for owned-resource finalizers/generated-policy reference cleanup. Customer then removes member policies/resources. Retain projections needed by other Gateways, shared certificates/DNS and unrelated Azure assets. Agree retained-root costs, endpoint URL invalidation and retirement of certificate automation. | +| Test authorization | Subscription/cluster owners | Explicitly approve subscription, resource group, Kubernetes contexts and create/test/cleanup scope before live work. Use test resources, collect logs before cleanup, and do not infer authorization from a design review. | + +#### Useful private preflight, not AFD proof + +From an authorized client with private reachability to a member's ILB, the +following illustrates testing the chosen SNI and an independent application +Host. Substitute the discovered private IPv4, selected Service port, policy +hostname and expected request Host. The client must use normal trusted-CA +verification; do not add `-k`. + +```bash +# Connect privately while retaining the URL hostname for SNI/certificate checks. +# The Host header independently tests the application's expected HTTP authority. +curl --fail-with-body --show-error \ + --resolve "${ORIGIN_TLS_HOSTNAME}:${ORIGIN_PORT}:${ORIGIN_PRIVATE_IP}" \ + --header "Host: ${EXPECTED_APP_HOST}" \ + "https://${ORIGIN_TLS_HOSTNAME}:${ORIGIN_PORT}/" +``` + +This verifies only that client's trust and the direct private Service path. +Complete the through-AFD traffic/probe verification and operational checks +listed above; neither this command nor an open TCP port substitutes for them. +The diagnostic client must not require publishing an origin IP or deploying a +new ingress. + ## Configure per-cluster traffic weights **Actor:** Application or traffic-management owner diff --git a/pkg/common/origintls/observation.go b/pkg/common/origintls/observation.go new file mode 100644 index 00000000..4a3bf9da --- /dev/null +++ b/pkg/common/origintls/observation.go @@ -0,0 +1,89 @@ +/* +Copyright (c) Microsoft Corporation. +Licensed under the MIT license. +*/ + +package origintls + +import ( + "crypto/sha256" + "encoding/json" + "fmt" + "reflect" + "time" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + fleetnetv1alpha1 "go.goms.io/fleet-networking/api/v1alpha1" +) + +const observationAnnotation = "networking.fleet.azure.com/origin-tls-observation" + +type heartbeat struct { + ObservedAt metav1.Time `json:"observedAt"` + IntentDigest string `json:"intentDigest"` +} + +func intentDigest(intent *fleetnetv1alpha1.OriginTLS) (string, error) { + data, err := json.Marshal(intent) + if err != nil { + return "", err + } + return fmt.Sprintf("%x", sha256.Sum256(data)), nil +} + +// RefreshObservation binds a metadata-only heartbeat to the typed TLS snapshot. +// Unchanged intent must not increment generation and invalidate MCS conflict +// acknowledgement every minute. +func RefreshObservation(export *fleetnetv1alpha1.InternalServiceExport, intent *fleetnetv1alpha1.OriginTLS) error { + if intent == nil { + export.Spec.OriginTLS = nil + delete(export.Annotations, observationAnnotation) + return nil + } + observedAt := intent.ObservedAt + if previous := export.Spec.OriginTLS; previous != nil { + comparable := *intent + comparable.ObservedAt = previous.ObservedAt + if reflect.DeepEqual(&comparable, previous) { + intent = &comparable + } + } + digest, err := intentDigest(intent) + if err != nil { + return err + } + data, err := json.Marshal(heartbeat{ObservedAt: observedAt, IntentDigest: digest}) + if err != nil { + return err + } + if export.Annotations == nil { + export.Annotations = make(map[string]string) + } + export.Annotations[observationAnnotation] = string(data) + export.Spec.OriginTLS = intent + return nil +} + +// ObservedAt accepts only a heartbeat bound to this exact typed source snapshot. +func ObservedAt(export *fleetnetv1alpha1.InternalServiceExport) (time.Time, error) { + raw, found := export.Annotations[observationAnnotation] + if !found { + if export.Spec.OriginTLS == nil { + return time.Time{}, fmt.Errorf("TLS observation missing") + } + return export.Spec.OriginTLS.ObservedAt.Time, nil + } + var observation heartbeat + if err := json.Unmarshal([]byte(raw), &observation); err != nil { + return time.Time{}, fmt.Errorf("malformed TLS heartbeat") + } + digest, err := intentDigest(export.Spec.OriginTLS) + if err != nil { + return time.Time{}, err + } + if observation.IntentDigest != digest || observation.ObservedAt.IsZero() { + return time.Time{}, fmt.Errorf("TLS heartbeat does not match source intent") + } + return observation.ObservedAt.Time, nil +} diff --git a/pkg/common/origintls/observation_test.go b/pkg/common/origintls/observation_test.go new file mode 100644 index 00000000..64f19870 --- /dev/null +++ b/pkg/common/origintls/observation_test.go @@ -0,0 +1,45 @@ +/* +Copyright (c) Microsoft Corporation. +Licensed under the MIT license. +*/ + +package origintls + +import ( + "reflect" + "testing" + "time" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + fleetnetv1alpha1 "go.goms.io/fleet-networking/api/v1alpha1" +) + +func TestHeartbeatPreservesSpecAndRejectsReplay(t *testing.T) { + export := &fleetnetv1alpha1.InternalServiceExport{} + start := metav1.NewTime(time.Now().UTC().Truncate(time.Second)) + intent := &fleetnetv1alpha1.OriginTLS{ObservedAt: start, Ready: true, Reason: "Ready", ServiceUID: "service-one", Hostname: "origin.example.com", Trust: "System"} + if err := RefreshObservation(export, intent); err != nil { + t.Fatal(err) + } + before := export.Spec.OriginTLS.DeepCopy() + intent = intent.DeepCopy() + intent.ObservedAt = metav1.NewTime(start.Add(time.Minute)) + if err := RefreshObservation(export, intent); err != nil { + t.Fatal(err) + } + observed, err := ObservedAt(export) + if err != nil || !observed.Equal(intent.ObservedAt.Time) || !reflect.DeepEqual(before, export.Spec.OriginTLS) { + t.Fatalf("heartbeat changed spec or failed renewal: %+v %v", export, err) + } + export.Spec.OriginTLS.ServiceUID = "replacement" + if _, err := ObservedAt(export); err == nil { + t.Fatal("heartbeat replay authorized a replacement Service") + } + if err := RefreshObservation(export, nil); err != nil { + t.Fatal(err) + } + if export.Spec.OriginTLS != nil || len(export.Annotations) != 0 { + t.Fatal("disable retained TLS authority") + } +} diff --git a/pkg/common/origintls/policy.go b/pkg/common/origintls/policy.go new file mode 100644 index 00000000..c79ae641 --- /dev/null +++ b/pkg/common/origintls/policy.go @@ -0,0 +1,46 @@ +/* +Copyright (c) Microsoft Corporation. +Licensed under the MIT license. +*/ + +// Package origintls defines Fleet's deliberately restricted TLS policy contract. +package origintls + +import ( + "fmt" + "strings" + "time" + + "k8s.io/apimachinery/pkg/util/validation" + gatewayv1alpha3 "sigs.k8s.io/gateway-api/apis/v1alpha3" +) + +const ( + ExportAnnotation = "networking.fleet.azure.com/export-to-fleet" + ExportAnnotationValue = "true" + DefaultCertificateOption = "networking.fleet.azure.com/afd-default-certificate" + ProjectionLabel = "networking.fleet.azure.com/origin-tls-projection" + ProvenanceAnnotation = "networking.fleet.azure.com/origin-tls-provenance" + Heartbeat = time.Minute + MaxAge = 5 * time.Minute +) + +// Validate checks trust and exact SNI intent without reading any certificate. +func Validate(policy *gatewayv1alpha3.BackendTLSPolicy) error { + spec := policy.Spec + if policy.DeletionTimestamp != nil || len(spec.TargetRefs) != 1 || spec.TargetRefs[0].SectionName != nil || + len(spec.Options) != 0 || len(spec.Validation.CACertificateRefs) != 0 || len(spec.Validation.SubjectAltNames) != 0 || + spec.Validation.WellKnownCACertificates == nil || *spec.Validation.WellKnownCACertificates != gatewayv1alpha3.WellKnownCACertificatesSystem { + return fmt.Errorf("requires one whole-resource target, System trust and no custom CA, SAN or TLS options") + } + return ValidateHostname(string(spec.Validation.Hostname)) +} + +// ValidateHostname rejects wildcard/IP identities and non-canonical DNS names. +func ValidateHostname(host string) error { + if len(validation.IsDNS1123Subdomain(host)) != 0 || !strings.Contains(host, ".") || + strings.Contains(host, "*") || strings.Trim(host, "0123456789.") == "" { + return fmt.Errorf("requires a precise canonical DNS hostname") + } + return nil +} diff --git a/pkg/controllers/hub/gateway/controller.go b/pkg/controllers/hub/gateway/controller.go index cbcb9c33..ea6c7fe4 100644 --- a/pkg/controllers/hub/gateway/controller.go +++ b/pkg/controllers/hub/gateway/controller.go @@ -24,6 +24,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/handler" "sigs.k8s.io/controller-runtime/pkg/reconcile" gatewayv1 "sigs.k8s.io/gateway-api/apis/v1" + gatewayv1alpha3 "sigs.k8s.io/gateway-api/apis/v1alpha3" gatewayv1beta1 "sigs.k8s.io/gateway-api/apis/v1beta1" fleetnetv1alpha1 "go.goms.io/fleet-networking/api/v1alpha1" @@ -43,6 +44,7 @@ type Reconciler struct { GraphStager DisabledGraphStager HTTPProvisioner HTTPPreviewProvisioner Recorder events.EventRecorder + EnableOriginTLS bool } // DisabledGraphStager stages/prunes disabled resources or suspends an owned endpoint. @@ -75,6 +77,8 @@ type ProfileCleaner interface { // +kubebuilder:rbac:groups=gateway.networking.k8s.io,resources=gateways/status,verbs=get;patch;update // +kubebuilder:rbac:groups="",resources=events,verbs=create;patch // +kubebuilder:rbac:groups=events.k8s.io,resources=events,verbs=create;patch +// +kubebuilder:rbac:groups=gateway.networking.k8s.io,resources=backendtlspolicies,verbs=get;list;watch;create;update;patch;delete +// +kubebuilder:rbac:groups=gateway.networking.k8s.io,resources=backendtlspolicies/status,verbs=get;update;patch // Reconcile refreshes generation-aware Gateway and listener status. func (r *Reconciler) Reconcile(ctx context.Context, request ctrl.Request) (result ctrl.Result, reconcileErr error) { @@ -93,7 +97,16 @@ func (r *Reconciler) Reconcile(ctx context.Context, request ctrl.Request) (resul logger.V(2).Info("Reconciling Gateway", "deleting", current.DeletionTimestamp != nil) if current.DeletionTimestamp != nil { // Ownership cleanup must not depend on a still-valid class or resolvable backends. - return r.finalize(ctx, ¤t) + var projectionErr error + if r.EnableOriginTLS { + projectionErr = r.reconcileTLSProjections(ctx) + } + result, err := r.finalize(ctx, ¤t) + return result, errors.Join(err, projectionErr) + } + var projectionErr error + if r.EnableOriginTLS { + projectionErr = r.reconcileTLSProjections(ctx) } observation, observationErr := r.observeOrigins(ctx, ¤t) logGatewayObservation(ctx, observation, observationErr) @@ -164,29 +177,26 @@ func (r *Reconciler) Reconcile(ctx context.Context, request ctrl.Request) (resul if err == nil && observedHTTPGateway != nil { r.recordHTTPPreviewEvent(observedHTTPGateway, staging.http) } - if err := errors.Join(err, observationErr, stagingErr, evaluationErr); err != nil { + if err := errors.Join(err, observationErr, stagingErr, evaluationErr, projectionErr); err != nil { return ctrl.Result{}, err } return progressRequeue(observation != nil || staging != nil), nil } func (r *Reconciler) resolve(ctx context.Context, gateway *gatewayv1.Gateway, class *gatewayv1.GatewayClass) (*gatewaymodel.GlobalGateway, error) { - return resolveGateway(ctx, r.Client, gateway, class, true) + reader := client.Reader(r.Client) + if r.EnableOriginTLS { + reader = r.APIReader + } + return resolveGateway(ctx, reader, gateway, class, !r.EnableOriginTLS, r.EnableOriginTLS) } func resolveGateway(ctx context.Context, reader client.Reader, gateway *gatewayv1.Gateway, - class *gatewayv1.GatewayClass, indexed bool) (*gatewaymodel.GlobalGateway, error) { + class *gatewayv1.GatewayClass, indexed bool, originTLS ...bool) (*gatewaymodel.GlobalGateway, error) { + enabled := len(originTLS) != 0 && originTLS[0] + secure := enabled && len(gateway.Spec.Listeners) == 1 && gateway.Spec.Listeners[0].Protocol == gatewayv1.HTTPSProtocolType var candidate *gatewaymodel.GlobalGateway - accepted := metav1.Condition{Type: string(gatewayv1.GatewayConditionAccepted), Status: metav1.ConditionTrue, - Reason: string(gatewayv1.GatewayReasonAccepted), Message: "Private HTTP Gateway configuration accepted", ObservedGeneration: gateway.Generation} - switch { - case !gatewayClassAccepted(class): - accepted.Status, accepted.Reason, accepted.Message = metav1.ConditionFalse, string(gatewayv1.GatewayReasonInvalidParameters), "GatewayClass is not currently accepted" - case len(gateway.Spec.Addresses) != 0: - accepted.Status, accepted.Reason, accepted.Message = metav1.ConditionFalse, string(gatewayv1.GatewayReasonUnsupportedAddress), "User-supplied Gateway addresses are unsupported" - case gateway.Spec.Infrastructure != nil || gateway.Spec.BackendTLS != nil: - accepted.Status, accepted.Reason, accepted.Message = metav1.ConditionFalse, string(gatewayv1.GatewayReasonInvalidParameters), "Infrastructure and backend TLS settings are unsupported" - } + accepted := gatewayAcceptance(gateway, class) config, configErr := annotations.ParseGatewayConfig(gateway.Annotations) if configErr != nil { accepted.Status, accepted.Reason, accepted.Message = metav1.ConditionFalse, string(gatewayv1.GatewayReasonInvalidParameters), configErr.Error() @@ -195,7 +205,7 @@ func resolveGateway(ctx context.Context, reader client.Reader, gateway *gatewayv if configErr == nil { model.WAFPolicyID = config.WAFPolicyID } - resolveListeners(gateway, &model, &accepted) + resolveListeners(gateway, &model, &accepted, enabled) pending := "Awaiting observed AFD private HTTP graph convergence" if accepted.Status == metav1.ConditionTrue { var routes gatewayv1.HTTPRouteList @@ -218,7 +228,7 @@ func resolveGateway(ctx context.Context, reader client.Reader, gateway *gatewayv if err := reader.Get(ctx, client.ObjectKey{Name: route.Namespace}, &namespace); err != nil { return nil, err } - attachments, err := resolveRouteAttachments(gateway, route, namespace.Labels) + attachments, err := resolveRouteAttachments(gateway, route, namespace.Labels, enabled) if err != nil { return nil, err } @@ -229,7 +239,10 @@ func resolveGateway(ctx context.Context, reader client.Reader, gateway *gatewayv if !indexed { resolveRoute = gatewayresolver.ResolveHTTPRouteUnindexed } - resolved, err := resolveRoute(ctx, reader, route, attachments) + resolved, err := resolveRoute(ctx, reader, route, attachments, secure) + if err == nil && secure { + err = validateRouteTLSProjections(ctx, reader, resolved) + } if err != nil { var resolutionErr *gatewayresolver.ResolutionError if !errors.As(err, &resolutionErr) { @@ -268,6 +281,31 @@ func resolveGateway(ctx context.Context, reader client.Reader, gateway *gatewayv return candidate, nil } +func validateRouteTLSProjections(ctx context.Context, reader client.Reader, route gatewaymodel.Route) error { + for _, rule := range route.Rules { + for _, backend := range rule.Backends { + if err := gatewayresolver.ValidateTLSProjection(ctx, reader, backend); err != nil { + return err + } + } + } + return nil +} + +func gatewayAcceptance(gateway *gatewayv1.Gateway, class *gatewayv1.GatewayClass) metav1.Condition { + accepted := metav1.Condition{Type: string(gatewayv1.GatewayConditionAccepted), Status: metav1.ConditionTrue, + Reason: string(gatewayv1.GatewayReasonAccepted), Message: "Private Gateway configuration accepted", ObservedGeneration: gateway.Generation} + switch { + case !gatewayClassAccepted(class): + accepted.Status, accepted.Reason, accepted.Message = metav1.ConditionFalse, string(gatewayv1.GatewayReasonInvalidParameters), "GatewayClass is not currently accepted" + case len(gateway.Spec.Addresses) != 0: + accepted.Status, accepted.Reason, accepted.Message = metav1.ConditionFalse, string(gatewayv1.GatewayReasonUnsupportedAddress), "User-supplied Gateway addresses are unsupported" + case gateway.Spec.Infrastructure != nil || gateway.Spec.BackendTLS != nil: + accepted.Status, accepted.Reason, accepted.Message = metav1.ConditionFalse, string(gatewayv1.GatewayReasonInvalidParameters), "Infrastructure and backend TLS settings are unsupported" + } + return accepted +} + func gatewayClassAccepted(class *gatewayv1.GatewayClass) bool { acceptance := meta.FindStatusCondition(class.Status.Conditions, string(gatewayv1.GatewayClassConditionStatusAccepted)) return class.DeletionTimestamp == nil && class.Spec.ParametersRef == nil && acceptance != nil && @@ -291,11 +329,11 @@ func referencesGateway(route *gatewayv1.HTTPRoute, gateway client.ObjectKey) boo } func resolveRouteAttachments(gateway *gatewayv1.Gateway, route *gatewayv1.HTTPRoute, - namespaceLabels map[string]string) ([]gatewaymodel.RouteAttachment, error) { + namespaceLabels map[string]string, originTLS ...bool) ([]gatewaymodel.RouteAttachment, error) { var attachments []gatewaymodel.RouteAttachment seen := make(map[string]bool) for _, parent := range route.Spec.ParentRefs { - resolved, err := gatewayresolver.ResolveAttachments(gateway, route, parent, namespaceLabels) + resolved, err := gatewayresolver.ResolveAttachments(gateway, route, parent, namespaceLabels, originTLS...) if err != nil { var attachmentErr *gatewayresolver.AttachmentError if !errors.As(err, &attachmentErr) { @@ -328,13 +366,17 @@ func (r *Reconciler) SetupWithManager(mgr ctrl.Manager) error { if r.GraphStager != nil { return fmt.Errorf("disabled-only staging and full HTTP provisioning cannot both be configured") } - return ctrl.NewControllerManagedBy(mgr).For(&gatewayv1.Gateway{}). + builder := ctrl.NewControllerManagedBy(mgr).For(&gatewayv1.Gateway{}). Watches(&gatewayv1.GatewayClass{}, handler.EnqueueRequestsFromMapFunc(r.gatewaysForClass)). Watches(&gatewayv1.HTTPRoute{}, handler.EnqueueRequestsFromMapFunc(r.gatewaysForRoute)). Watches(&fleetnetv1alpha1.ServiceImport{}, handler.EnqueueRequestsFromMapFunc(r.gatewaysForDependency)). Watches(&fleetnetv1alpha1.InternalServiceExport{}, handler.EnqueueRequestsFromMapFunc(r.gatewaysForDependency)). Watches(&gatewayv1beta1.ReferenceGrant{}, handler.EnqueueRequestsFromMapFunc(r.gatewaysForDependency)). - Watches(&corev1.Namespace{}, handler.EnqueueRequestsFromMapFunc(r.gatewaysForDependency)).Complete(r) + Watches(&corev1.Namespace{}, handler.EnqueueRequestsFromMapFunc(r.gatewaysForDependency)) + if r.EnableOriginTLS { + builder = builder.Watches(&gatewayv1alpha3.BackendTLSPolicy{}, handler.EnqueueRequestsFromMapFunc(r.gatewaysForDependency)) + } + return builder.Complete(r) } func (r *Reconciler) gatewaysForClass(ctx context.Context, object client.Object) []reconcile.Request { diff --git a/pkg/controllers/hub/gateway/dependencies_test.go b/pkg/controllers/hub/gateway/dependencies_test.go index ef7d8264..02837f2f 100644 --- a/pkg/controllers/hub/gateway/dependencies_test.go +++ b/pkg/controllers/hub/gateway/dependencies_test.go @@ -21,6 +21,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/client/fake" gatewayv1 "sigs.k8s.io/gateway-api/apis/v1" + gatewayv1alpha3 "sigs.k8s.io/gateway-api/apis/v1alpha3" gatewayv1beta1 "sigs.k8s.io/gateway-api/apis/v1beta1" fleetnetv1alpha1 "go.goms.io/fleet-networking/api/v1alpha1" @@ -32,7 +33,7 @@ import ( func gatewayFixture(t *testing.T, members int) (client.Client, *gatewayv1.Gateway, *gatewayv1.HTTPRoute, *fleetnetv1alpha1.ServiceImport) { t.Helper() scheme := runtime.NewScheme() - for _, install := range []func(*runtime.Scheme) error{corev1.AddToScheme, gatewayv1.Install, gatewayv1beta1.Install, fleetnetv1alpha1.AddToScheme} { + for _, install := range []func(*runtime.Scheme) error{corev1.AddToScheme, gatewayv1.Install, gatewayv1beta1.Install, gatewayv1alpha3.Install, fleetnetv1alpha1.AddToScheme} { if err := install(scheme); err != nil { t.Fatal(err) } @@ -70,7 +71,7 @@ func gatewayFixture(t *testing.T, members int) (client.Client, *gatewayv1.Gatewa }) } c := fake.NewClientBuilder().WithScheme(scheme).WithObjects(objects...). - WithStatusSubresource(&gatewayv1.Gateway{}, &gatewayv1.HTTPRoute{}, &gatewayv1.GatewayClass{}, &fleetnetv1alpha1.ServiceImport{}, &fleetnetv1alpha1.InternalServiceExport{}). + WithStatusSubresource(&gatewayv1.Gateway{}, &gatewayv1.HTTPRoute{}, &gatewayv1.GatewayClass{}, &gatewayv1alpha3.BackendTLSPolicy{}, &fleetnetv1alpha1.ServiceImport{}, &fleetnetv1alpha1.InternalServiceExport{}). WithIndex(&gatewayv1.Gateway{}, gatewayresolver.GatewayClassField, func(o client.Object) []string { return []string{string(o.(*gatewayv1.Gateway).Spec.GatewayClassName)} }). WithIndex(&gatewayv1.HTTPRoute{}, gatewayresolver.HTTPRouteGatewayField, func(o client.Object) []string { route := o.(*gatewayv1.HTTPRoute) diff --git a/pkg/controllers/hub/gateway/http_provisioning.go b/pkg/controllers/hub/gateway/http_provisioning.go index a2cf370d..f8575659 100644 --- a/pkg/controllers/hub/gateway/http_provisioning.go +++ b/pkg/controllers/hub/gateway/http_provisioning.go @@ -34,9 +34,13 @@ func (r *Reconciler) applyHTTPPreviewStatus(ctx context.Context, gateway *gatewa return false, nil } result := staging.http - message := fmt.Sprintf("AFD private HTTP graph: %s", result.State) + protocol := "HTTP" + if len(model.Listeners) == 1 && model.Listeners[0].Protocol == gatewaymodel.ProtocolHTTPS { + protocol = gatewaymodel.ProtocolHTTPS + } + message := fmt.Sprintf("AFD private %s graph: %s", protocol, result.State) if staging.err != nil { - setHTTPPreviewStatus(gateway, false, "AFD private HTTP provisioning failed: "+staging.err.Error()) + setHTTPPreviewStatus(gateway, false, "AFD private "+protocol+" provisioning failed: "+staging.err.Error()) return false, staging.err } switch result.State { @@ -67,7 +71,26 @@ func (r *Reconciler) applyHTTPPreviewStatus(ctx context.Context, gateway *gatewa setHTTPPreviewStatus(gateway, false, "AFD ready evidence is no longer current: "+err.Error()) return false, err } - setHTTPPreviewStatus(gateway, true, "Observed complete enabled AFD Premium private HTTP configuration; Private Link approval, edge propagation and live application health are independent") + readyMessage := "Observed complete enabled AFD Premium private HTTP configuration; Private Link approval, edge propagation and live application health are independent" + if len(model.Listeners) == 1 && model.Listeners[0].Protocol == gatewaymodel.ProtocolHTTPS { + readyMessage = "Observed complete enabled AFD Premium private HTTPS configuration; certificate trust, edge propagation and live application health are independent" + seen := make(map[string]bool) + for _, route := range model.Routes { + for _, rule := range route.Rules { + for _, backend := range rule.Backends { + key := backend.Namespace + "/" + backend.Name + if seen[key] { + continue + } + seen[key] = true + if len(backend.ExcludedOrigins) != 0 { + readyMessage += fmt.Sprintf("; degraded %s: %d eligible origins, excluded members verified absent from owned origin inventory: %v; reduced capacity", key, len(backend.Origins), backend.ExcludedOrigins) + } + } + } + } + } + setHTTPPreviewStatus(gateway, true, readyMessage) gateway.Status.Addresses = []gatewayv1.GatewayStatusAddress{{Type: ptr.To(gatewayv1.HostnameAddressType), Value: host}} return true, nil default: @@ -151,7 +174,7 @@ func (r *Reconciler) unprogrammableOwner(ctx context.Context, gateway *gatewayv1 if !controllerutil.ContainsFinalizer(current, objectmeta.GatewayAFDCleanupFinalizer) { return frontdoor.GatewayOwner{}, errProvisioningIntentChanged } - actual, err := resolveGateway(ctx, r.APIReader, current.DeepCopy(), class, false) + actual, err := resolveGateway(ctx, r.APIReader, current.DeepCopy(), class, false, r.EnableOriginTLS) if err != nil { return frontdoor.GatewayOwner{}, err } diff --git a/pkg/controllers/hub/gateway/listeners.go b/pkg/controllers/hub/gateway/listeners.go index d960e02f..e5c3840d 100644 --- a/pkg/controllers/hub/gateway/listeners.go +++ b/pkg/controllers/hub/gateway/listeners.go @@ -20,7 +20,7 @@ import ( // resolveListeners validates listener configuration and conflicts, populates // model.Listeners, and initializes gateway.Status.Listeners with pending readiness. // Invalid, conflicting or missing listeners also mark the Gateway unaccepted. -func resolveListeners(gateway *gatewayv1.Gateway, model *gatewaymodel.GlobalGateway, accepted *metav1.Condition) { +func resolveListeners(gateway *gatewayv1.Gateway, model *gatewaymodel.GlobalGateway, accepted *metav1.Condition, originTLS ...bool) { previous := gateway.Status.Listeners gateway.Status.Listeners = nil for _, listener := range gateway.Spec.Listeners { @@ -31,7 +31,10 @@ func resolveListeners(gateway *gatewayv1.Gateway, model *gatewaymodel.GlobalGate break } } - listenerErr := gatewayresolver.ValidateListener(listener) + listenerErr := gatewayresolver.ValidateListener(listener, originTLS...) + if listener.Protocol == gatewayv1.HTTPSProtocolType && len(gateway.Spec.Listeners) != 1 { + listenerErr = &gatewayresolver.ListenerError{Reason: gatewayv1.ListenerReasonInvalid, Message: "HTTPS requires exactly one listener"} + } conflicted := false for _, other := range gateway.Spec.Listeners { if other.Name != listener.Name && other.Protocol == listener.Protocol && other.Port == listener.Port && @@ -45,7 +48,7 @@ func resolveListeners(gateway *gatewayv1.Gateway, model *gatewaymodel.GlobalGate Reason: string(gatewayv1.ListenerReasonNoConflicts), Message: "No listener conflicts", ObservedGeneration: gateway.Generation} references := metav1.Condition{Type: string(gatewayv1.ListenerConditionResolvedRefs), Status: metav1.ConditionTrue, Reason: string(gatewayv1.ListenerReasonResolvedRefs), Message: "HTTP listener has no external references", ObservedGeneration: gateway.Generation} - if listener.TLS != nil { + if listener.TLS != nil && listenerErr != nil { references.Status, references.Reason, references.Message = metav1.ConditionUnknown, string(gatewayv1.ListenerReasonPending), "TLS references are not resolved by the HTTP preview" } if listenerErr != nil { @@ -74,7 +77,7 @@ func resolveListeners(gateway *gatewayv1.Gateway, model *gatewaymodel.GlobalGate Status: metav1.ConditionFalse, Reason: string(gatewayv1.ListenerReasonPending), Message: "Awaiting observed AFD private HTTP graph convergence", ObservedGeneration: gateway.Generation}) gateway.Status.Listeners = append(gateway.Status.Listeners, status) model.Listeners = append(model.Listeners, gatewaymodel.Listener{Name: string(listener.Name), Protocol: string(listener.Protocol), - Port: int32(listener.Port), Hostname: string(ptr.Deref(listener.Hostname, ""))}) + Port: int32(listener.Port), Hostname: string(ptr.Deref(listener.Hostname, "")), DefaultCertificate: listenerErr == nil && listener.Protocol == gatewayv1.HTTPSProtocolType}) } if len(gateway.Spec.Listeners) == 0 { accepted.Status, accepted.Reason, accepted.Message = metav1.ConditionFalse, string(gatewayv1.GatewayReasonListenersNotValid), "At least one HTTP listener is required" diff --git a/pkg/controllers/hub/gateway/observability.go b/pkg/controllers/hub/gateway/observability.go index dd93f8bc..f759321c 100644 --- a/pkg/controllers/hub/gateway/observability.go +++ b/pkg/controllers/hub/gateway/observability.go @@ -287,6 +287,11 @@ func (r *Reconciler) recordHTTPPreviewEvent(gateway *gatewayv1.Gateway, result * return } if result.State == frontdoor.HTTPPreviewProgrammed { + if len(gateway.Spec.Listeners) == 1 && gateway.Spec.Listeners[0].Protocol == gatewayv1.HTTPSProtocolType { + r.Recorder.Eventf(gateway, nil, corev1.EventTypeNormal, "AFDHTTPSProgrammed", "ProgramAFDHTTPS", + "Observed enabled private HTTPS graph and published its generated hostname; certificate trust and live application health are independent. Inspect status for excluded members and reduced capacity.") + return + } r.Recorder.Eventf(gateway, nil, corev1.EventTypeNormal, "AFDHTTPProgrammed", "ProgramAFDHTTP", "Observed complete enabled AFD Premium private HTTP graph and published its Azure hostname; live application health is not implied.") } else if len(result.Staging.Route.Backends.Origins.PendingApprovals) != 0 { diff --git a/pkg/controllers/hub/gateway/origintls.go b/pkg/controllers/hub/gateway/origintls.go new file mode 100644 index 00000000..76db3560 --- /dev/null +++ b/pkg/controllers/hub/gateway/origintls.go @@ -0,0 +1,249 @@ +/* +Copyright (c) Microsoft Corporation. +Licensed under the MIT license. +*/ + +package gateway + +import ( + "context" + "errors" + "fmt" + "reflect" + "sort" + + corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/utils/ptr" + "sigs.k8s.io/controller-runtime/pkg/client" + gatewayv1 "sigs.k8s.io/gateway-api/apis/v1" + gatewayv1alpha2 "sigs.k8s.io/gateway-api/apis/v1alpha2" + gatewayv1alpha3 "sigs.k8s.io/gateway-api/apis/v1alpha3" + + "go.goms.io/fleet-networking/pkg/annotations" + "go.goms.io/fleet-networking/pkg/common/objectmeta" + "go.goms.io/fleet-networking/pkg/common/origintls" + "go.goms.io/fleet-networking/pkg/controllers/hub/gatewaymodel" + "go.goms.io/fleet-networking/pkg/controllers/hub/gatewayresolver" +) + +type tlsProjectionIntent struct { + backend gatewaymodel.Backend + ancestors map[client.ObjectKey]bool +} + +// reconcileTLSProjections uses complete current route inventory so a policy +// belongs to its ServiceImport, never to the first referencing Gateway. +func (r *Reconciler) reconcileTLSProjections(ctx context.Context) error { + if r.APIReader == nil { + return fmt.Errorf("TLS projection requires an uncached API reader") + } + var routes gatewayv1.HTTPRouteList + if err := r.APIReader.List(ctx, &routes); err != nil { + return fmt.Errorf("list TLS projection references: %w", err) + } + desired := make(map[client.ObjectKey]*tlsProjectionIntent) + gateways := make(map[client.ObjectKey]*gatewayv1.Gateway) + classes := make(map[string]*gatewayv1.GatewayClass) + var failures []error + for i := range routes.Items { + route := &routes.Items[i] + if route.DeletionTimestamp != nil || len(route.Spec.Hostnames) != 0 || gatewayresolver.ValidateHTTPRoute(route) != nil { + continue + } + ancestors, err := r.tlsProjectionAncestors(ctx, route, gateways, classes) + if err != nil { + return err + } + if len(ancestors) == 0 { + continue + } + for _, rule := range route.Spec.Rules { + rootOnly := true + for _, match := range rule.Matches { + if match.Path != nil && (ptr.Deref(match.Path.Type, gatewayv1.PathMatchPathPrefix) != gatewayv1.PathMatchPathPrefix || ptr.Deref(match.Path.Value, "/") != "/") { + rootOnly = false + } + } + if !rootOnly { + continue + } + backend, err := gatewayresolver.ResolveBackendUnindexed(ctx, r.APIReader, route.Namespace, rule.BackendRefs[0], true) + if err != nil { + var resolution *gatewayresolver.ResolutionError + if !errors.As(err, &resolution) { + return err + } + continue + } + key := client.ObjectKey{Namespace: backend.Namespace, Name: backend.Name} + intent := desired[key] + if intent == nil { + intent = &tlsProjectionIntent{backend: backend, ancestors: make(map[client.ObjectKey]bool)} + desired[key] = intent + } + if intent.backend.TLSProvenance != backend.TLSProvenance || intent.backend.TLSHostname != backend.TLSHostname { + return fmt.Errorf("TLS backend source set changed during projection inventory") + } + for _, ancestor := range ancestors { + intent.ancestors[ancestor] = true + } + } + } + // Narrow cleanup to Fleet-labelled policies, then verify target UID ownership. + var existing gatewayv1alpha3.BackendTLSPolicyList + if err := r.APIReader.List(ctx, &existing, client.MatchingLabels{origintls.ProjectionLabel: "true"}); err != nil { + return err + } + for i := range existing.Items { + policy := &existing.Items[i] + if len(policy.OwnerReferences) != 1 { + continue + } + owner := policy.OwnerReferences[0] + key := client.ObjectKey{Namespace: policy.Namespace, Name: owner.Name} + if desired[key] != nil { + continue + } + backend := gatewaymodel.Backend{Namespace: policy.Namespace, Name: owner.Name, TargetUID: string(owner.UID)} + if !gatewayresolver.OwnsTLSProjection(policy, backend) { + continue + } + if err := r.Client.Delete(ctx, policy, client.Preconditions{UID: &policy.UID, ResourceVersion: &policy.ResourceVersion}); client.IgnoreNotFound(err) != nil { + failures = append(failures, err) + } + } + keys := make([]client.ObjectKey, 0, len(desired)) + for key := range desired { + keys = append(keys, key) + } + sort.Slice(keys, func(i, j int) bool { return keys[i].String() < keys[j].String() }) + for _, key := range keys { + if err := r.ensureTLSProjection(ctx, desired[key]); err != nil { + failures = append(failures, err) + } + } + return errors.Join(failures...) +} + +func (r *Reconciler) tlsProjectionAncestors(ctx context.Context, route *gatewayv1.HTTPRoute, + gateways map[client.ObjectKey]*gatewayv1.Gateway, classes map[string]*gatewayv1.GatewayClass) ([]client.ObjectKey, error) { + ancestors := make([]client.ObjectKey, 0, len(route.Spec.ParentRefs)) + for _, parent := range route.Spec.ParentRefs { + key, recognized := gatewayresolver.GatewayParentKey(route.Namespace, parent) + if !recognized { + continue + } + gateway, seen := gateways[key] + if !seen { + gateway = &gatewayv1.Gateway{} + if err := r.APIReader.Get(ctx, key, gateway); err != nil { + if apierrors.IsNotFound(err) { + gateways[key] = nil + continue + } + return nil, err + } + gateways[key] = gateway + } + if gateway == nil || gateway.DeletionTimestamp != nil || len(gateway.Spec.Listeners) != 1 || + gateway.Spec.Listeners[0].Protocol != gatewayv1.HTTPSProtocolType || + gatewayresolver.ValidateListener(gateway.Spec.Listeners[0], true) != nil || + len(gateway.Spec.Addresses) != 0 || gateway.Spec.Infrastructure != nil || gateway.Spec.BackendTLS != nil { + continue + } + config, err := annotations.ParseGatewayConfig(gateway.Annotations) + if err != nil || config.WAFPolicyID != "" { + continue + } + classKey := string(gateway.Spec.GatewayClassName) + class, seen := classes[classKey] + if !seen { + class = &gatewayv1.GatewayClass{} + if err := r.APIReader.Get(ctx, client.ObjectKey{Name: classKey}, class); err != nil { + if apierrors.IsNotFound(err) { + classes[classKey] = nil + continue + } + return nil, err + } + classes[classKey] = class + } + if class == nil || class.Spec.ControllerName != gatewayv1.GatewayController(objectmeta.GatewayAPIControllerName) || !gatewayClassAccepted(class) { + continue + } + var namespace corev1.Namespace + if err := r.APIReader.Get(ctx, client.ObjectKey{Name: route.Namespace}, &namespace); err != nil { + return nil, err + } + attachments, err := gatewayresolver.ResolveAttachments(gateway, route, parent, namespace.Labels, true) + if err != nil || len(attachments) == 0 { + continue + } + ancestors = append(ancestors, key) + } + return ancestors, nil +} + +func (r *Reconciler) ensureTLSProjection(ctx context.Context, intent *tlsProjectionIntent) error { + expected := gatewayresolver.TLSProjection(intent.backend) + var actual gatewayv1alpha3.BackendTLSPolicy + err := r.APIReader.Get(ctx, client.ObjectKeyFromObject(expected), &actual) + if apierrors.IsNotFound(err) { + return r.Client.Create(ctx, expected) + } + if err != nil { + return err + } + if !gatewayresolver.OwnsTLSProjection(&actual, intent.backend) || actual.DeletionTimestamp != nil { + return fmt.Errorf("refusing to adopt foreign or deleting hub TLS policy %s", client.ObjectKeyFromObject(&actual)) + } + before := actual.DeepCopy() + actual.Spec = expected.Spec + if actual.Annotations == nil { + actual.Annotations = make(map[string]string) + } + actual.Annotations[origintls.ProvenanceAnnotation] = intent.backend.TLSProvenance + if !reflect.DeepEqual(before.Spec, actual.Spec) || !reflect.DeepEqual(before.Annotations, actual.Annotations) { + return r.Client.Patch(ctx, &actual, client.MergeFromWithOptions(before, client.MergeFromWithOptimisticLock{})) + } + if err := gatewayresolver.ValidateTLSProjection(ctx, r.APIReader, intent.backend); err != nil { + return err + } + before = actual.DeepCopy() + ancestors := make([]gatewayv1alpha2.PolicyAncestorStatus, 0, len(actual.Status.Ancestors)+len(intent.ancestors)) + for _, ancestor := range actual.Status.Ancestors { + if ancestor.ControllerName != gatewayv1.GatewayController(objectmeta.GatewayAPIControllerName) { + ancestors = append(ancestors, ancestor) + } + } + keys := make([]client.ObjectKey, 0, len(intent.ancestors)) + for key := range intent.ancestors { + keys = append(keys, key) + } + sort.Slice(keys, func(i, j int) bool { return keys[i].String() < keys[j].String() }) + if len(ancestors)+len(keys) > 16 { + return fmt.Errorf("hub TLS policy exceeds Gateway API ancestor capacity") + } + for _, key := range keys { + status := gatewayv1alpha2.PolicyAncestorStatus{ + AncestorRef: gatewayv1.ParentReference{Group: ptr.To(gatewayv1.Group(gatewayv1.GroupName)), Kind: ptr.To(gatewayv1.Kind("Gateway")), Namespace: ptr.To(gatewayv1.Namespace(key.Namespace)), Name: gatewayv1.ObjectName(key.Name)}, + ControllerName: gatewayv1.GatewayController(objectmeta.GatewayAPIControllerName), + } + for _, old := range actual.Status.Ancestors { + if old.ControllerName == status.ControllerName && reflect.DeepEqual(old.AncestorRef, status.AncestorRef) { + status.Conditions = old.Conditions + } + } + meta.SetStatusCondition(&status.Conditions, metav1.Condition{Type: "Accepted", Status: metav1.ConditionTrue, Reason: "Accepted", + Message: "Current member TLS intent agrees; certificate trust and traffic are verified independently", ObservedGeneration: actual.Generation}) + ancestors = append(ancestors, status) + } + actual.Status.Ancestors = ancestors + if reflect.DeepEqual(before.Status, actual.Status) { + return nil + } + return r.Client.Status().Patch(ctx, &actual, client.MergeFromWithOptions(before, client.MergeFromWithOptimisticLock{})) +} diff --git a/pkg/controllers/hub/gateway/origintls_integration_test.go b/pkg/controllers/hub/gateway/origintls_integration_test.go new file mode 100644 index 00000000..3d3986bb --- /dev/null +++ b/pkg/controllers/hub/gateway/origintls_integration_test.go @@ -0,0 +1,127 @@ +/* +Copyright (c) Microsoft Corporation. +Licensed under the MIT license. +*/ + +package gateway + +import ( + "fmt" + "time" + + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" + corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/utils/ptr" + "sigs.k8s.io/controller-runtime/pkg/client" + gatewayv1 "sigs.k8s.io/gateway-api/apis/v1" + gatewayv1alpha3 "sigs.k8s.io/gateway-api/apis/v1alpha3" + + fleetnetv1alpha1 "go.goms.io/fleet-networking/api/v1alpha1" + fleetnetv1beta1 "go.goms.io/fleet-networking/api/v1beta1" + "go.goms.io/fleet-networking/pkg/common/objectmeta" + "go.goms.io/fleet-networking/pkg/common/origintls" + "go.goms.io/fleet-networking/pkg/controllers/hub/gatewayresolver" + "go.goms.io/fleet-networking/pkg/providers/azure/frontdoor" +) + +var _ = Describe("HTTPS intent with real CRD admission and dependency watches", func() { + It("projects current intent, observes metadata heartbeats and revokes member opt-in without an HTTP fallback", func() { + ctx := integrationContext + integrationProvider.setOriginState(frontdoor.PrivateOriginReady) + namespace := &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{GenerateName: "https-integration-"}} + Expect(integrationClient.Create(ctx, namespace)).To(Succeed()) + member := &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "fleet-member-https-envtest"}} + Expect(integrationClient.Create(ctx, member)).To(Succeed()) + class := &gatewayv1.GatewayClass{ObjectMeta: metav1.ObjectMeta{GenerateName: "https-integration-"}, + Spec: gatewayv1.GatewayClassSpec{ControllerName: gatewayv1.GatewayController(objectmeta.GatewayAPIControllerName)}} + Expect(integrationClient.Create(ctx, class)).To(Succeed()) + service := &fleetnetv1alpha1.ServiceImport{ObjectMeta: metav1.ObjectMeta{Namespace: namespace.Name, Name: "api"}} + Expect(integrationClient.Create(ctx, service)).To(Succeed()) + service.Status.Ports = []fleetnetv1alpha1.ServicePort{{Name: "https", Protocol: corev1.ProtocolTCP, Port: 443, AppProtocol: ptr.To("https")}} + service.Status.Clusters = []fleetnetv1alpha1.ClusterStatus{{Cluster: "https-envtest"}} + Expect(integrationClient.Status().Update(ctx, service)).To(Succeed()) + export := &fleetnetv1alpha1.InternalServiceExport{ + ObjectMeta: metav1.ObjectMeta{Namespace: member.Name, Name: namespace.Name + "-api"}, + Spec: fleetnetv1alpha1.InternalServiceExportSpec{ + Ports: service.Status.Ports, Type: corev1.ServiceTypeLoadBalancer, IsInternalLoadBalancer: true, + ServiceReference: fleetnetv1alpha1.ExportedObjectReference{Namespace: namespace.Name, Name: "api", NamespacedName: namespace.Name + "/api", + ClusterID: "https-envtest", UID: "source-service", Kind: "Service", APIVersion: "v1"}, + PrivateLinkOrigin: &fleetnetv1alpha1.PrivateLinkOrigin{ResourceID: integrationPLS, Location: "eastus", InternalIP: "10.0.0.10", Ready: true}, + }, + } + intent := &fleetnetv1alpha1.OriginTLS{Ready: true, Reason: "Ready", ObservedAt: metav1.Now(), ServiceUID: "source-service", + Hostname: "origin.example.com", Trust: "System", + Policy: &fleetnetv1alpha1.OriginTLSPolicyReference{Namespace: namespace.Name, Name: "api-tls", UID: "source-policy", Generation: 1, ResourceVersion: "opaque", ExportToFleet: "true"}} + Expect(origintls.RefreshObservation(export, intent)).To(Succeed()) + Expect(integrationClient.Create(ctx, export)).To(Succeed()) + export.Status.Conditions = []metav1.Condition{{Type: string(fleetnetv1beta1.ServiceExportConflict), Status: metav1.ConditionFalse, + Reason: "NoConflictFound", Message: "Ports agree", ObservedGeneration: export.Generation, LastTransitionTime: metav1.Now()}} + Expect(integrationClient.Status().Update(ctx, export)).To(Succeed()) + gateway := &gatewayv1.Gateway{ObjectMeta: metav1.ObjectMeta{Namespace: namespace.Name, Name: "https"}, + Spec: gatewayv1.GatewaySpec{GatewayClassName: gatewayv1.ObjectName(class.Name), Listeners: []gatewayv1.Listener{{ + Name: "https", Protocol: gatewayv1.HTTPSProtocolType, Port: 443, + TLS: &gatewayv1.GatewayTLSConfig{Mode: ptr.To(gatewayv1.TLSModeTerminate), Options: map[gatewayv1.AnnotationKey]gatewayv1.AnnotationValue{ + gatewayv1.AnnotationKey(origintls.DefaultCertificateOption): "true", + }}, + }}}} + Expect(integrationClient.Create(ctx, gateway)).To(Succeed(), "Pinned schema must admit implementation-managed default certificate") + route := &gatewayv1.HTTPRoute{ObjectMeta: metav1.ObjectMeta{Namespace: namespace.Name, Name: "api"}, + Spec: gatewayv1.HTTPRouteSpec{CommonRouteSpec: gatewayv1.CommonRouteSpec{ParentRefs: []gatewayv1.ParentReference{{Name: "https"}}}, + Rules: []gatewayv1.HTTPRouteRule{{BackendRefs: []gatewayv1.HTTPBackendRef{{BackendRef: gatewayv1.BackendRef{BackendObjectReference: gatewayv1.BackendObjectReference{ + Group: ptr.To(gatewayv1.Group(fleetnetv1alpha1.GroupVersion.Group)), Kind: ptr.To(gatewayv1.Kind("ServiceImport")), Name: "api", Port: ptr.To(gatewayv1.PortNumber(443)), + }}}}}}, + }} + Expect(integrationClient.Create(ctx, route)).To(Succeed()) + programmed := func() error { + var current gatewayv1.Gateway + if err := integrationClient.Get(ctx, client.ObjectKeyFromObject(gateway), ¤t); err != nil { + return err + } + condition := meta.FindStatusCondition(current.Status.Conditions, "Programmed") + if condition == nil || condition.Status != metav1.ConditionTrue || len(current.Status.Addresses) != 1 { + return fmt.Errorf("waiting for admitted HTTPS projection: %+v", current.Status) + } + return nil + } + Eventually(programmed, 20*time.Second, 100*time.Millisecond).Should(Succeed()) + var policy gatewayv1alpha3.BackendTLSPolicy + key := client.ObjectKey{Namespace: namespace.Name, Name: gatewayresolver.TLSProjectionName(service.Name)} + Eventually(func(g Gomega) { + g.Expect(integrationClient.Get(ctx, key, &policy)).To(Succeed()) + g.Expect(policy.Status.Ancestors).To(HaveLen(1)) + }, 10*time.Second, 100*time.Millisecond).Should(Succeed()) + Expect(policy.OwnerReferences[0].UID).To(Equal(service.UID)) + generation := export.Generation + renewed := intent.DeepCopy() + renewed.ObservedAt = metav1.NewTime(time.Now().Add(time.Second)) + Expect(origintls.RefreshObservation(export, renewed)).To(Succeed()) + Expect(integrationClient.Update(ctx, export)).To(Succeed()) + Expect(export.Generation).To(Equal(generation), "Heartbeat must preserve MCS conflict generation") + Eventually(programmed, 10*time.Second, 100*time.Millisecond).Should(Succeed()) + renewed.Ready, renewed.Reason, renewed.Policy.ExportToFleet = false, "PolicyNotExported", "false" + Expect(origintls.RefreshObservation(export, renewed)).To(Succeed()) + Expect(integrationClient.Update(ctx, export)).To(Succeed()) + Eventually(func() error { + var current gatewayv1.Gateway + if err := integrationClient.Get(ctx, client.ObjectKeyFromObject(gateway), ¤t); err != nil { + return err + } + condition := meta.FindStatusCondition(current.Status.Conditions, "Programmed") + if condition == nil || condition.Status != metav1.ConditionFalse || len(current.Status.Addresses) != 0 { + return fmt.Errorf("stale TLS authority survived revocation") + } + err := integrationClient.Get(ctx, key, &policy) + if err == nil { + return fmt.Errorf("revoked projection retained") + } + if !apierrors.IsNotFound(err) { + return fmt.Errorf("read revoked projection: %w", err) + } + return nil + }, 10*time.Second, 100*time.Millisecond).Should(Succeed()) + }) +}) diff --git a/pkg/controllers/hub/gateway/origintls_test.go b/pkg/controllers/hub/gateway/origintls_test.go new file mode 100644 index 00000000..d61dbb32 --- /dev/null +++ b/pkg/controllers/hub/gateway/origintls_test.go @@ -0,0 +1,195 @@ +/* +Copyright (c) Microsoft Corporation. +Licensed under the MIT license. +*/ + +package gateway + +import ( + "context" + "fmt" + "strings" + "testing" + + apierrors "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/utils/ptr" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + gatewayv1 "sigs.k8s.io/gateway-api/apis/v1" + gatewayv1alpha3 "sigs.k8s.io/gateway-api/apis/v1alpha3" + + fleetnetv1alpha1 "go.goms.io/fleet-networking/api/v1alpha1" + "go.goms.io/fleet-networking/pkg/common/origintls" + "go.goms.io/fleet-networking/pkg/controllers/hub/gatewayresolver" +) + +func tlsControllerFixture(t *testing.T, members int) (client.Client, *gatewayv1.Gateway, *gatewayv1.HTTPRoute, *Reconciler, *fakeHTTPProvisioner) { + t.Helper() + ctx := context.Background() + c, gateway, route, service := gatewayFixture(t, members) + addObservationHub(t, c) + gateway.Spec.Listeners = []gatewayv1.Listener{{Name: "https", Protocol: gatewayv1.HTTPSProtocolType, Port: 443, + TLS: &gatewayv1.GatewayTLSConfig{Mode: ptr.To(gatewayv1.TLSModeTerminate), Options: map[gatewayv1.AnnotationKey]gatewayv1.AnnotationValue{ + gatewayv1.AnnotationKey(origintls.DefaultCertificateOption): "true", + }}}} + if err := c.Update(ctx, gateway); err != nil { + t.Fatal(err) + } + route.Spec.ParentRefs = []gatewayv1.ParentReference{{Name: gatewayv1.ObjectName(gateway.Name)}} + if err := c.Update(ctx, route); err != nil { + t.Fatal(err) + } + service.UID = "service-import-uid" + if err := c.Update(ctx, service); err != nil { + t.Fatal(err) + } + service.Status.Ports[0].AppProtocol = ptr.To("https") + if err := c.Status().Update(ctx, service); err != nil { + t.Fatal(err) + } + for i := 0; i < members; i++ { + var export fleetnetv1alpha1.InternalServiceExport + if err := c.Get(ctx, client.ObjectKey{Namespace: fmt.Sprintf("fleet-member-member-%d", i), Name: "store-api"}, &export); err != nil { + t.Fatal(err) + } + export.Spec.Ports = service.Status.Ports + export.Spec.OriginTLS = &fleetnetv1alpha1.OriginTLS{Ready: true, Reason: "Ready", ObservedAt: metav1.Now(), + ServiceUID: string(export.Spec.ServiceReference.UID), Hostname: "origin.example.com", Trust: "System", + Policy: &fleetnetv1alpha1.OriginTLSPolicyReference{Namespace: "store", Name: "api-tls", UID: fmt.Sprintf("policy-%d", i), Generation: 1, ResourceVersion: "observed", ExportToFleet: "true"}, + } + if err := c.Update(ctx, &export); err != nil { + t.Fatal(err) + } + } + provider := &fakeHTTPProvisioner{} + provider.progress.State, provider.progress.EndpointHostName = "Programmed", httpPreviewHostname + provider.suspension.State = "Suspended" + return c, gateway, route, &Reconciler{Client: c, APIReader: c, EnableOriginTLS: true, + ProfileCleanup: &fakeProfileCleaner{}, HTTPProvisioner: provider}, provider +} + +func TestTLSControllerProjectionSharedReferencesAndRevocation(t *testing.T) { + ctx := context.Background() + c, gateway, route, r, provider := tlsControllerFixture(t, 2) + request := ctrl.Request{NamespacedName: client.ObjectKeyFromObject(gateway)} + for i := 0; i < 2; i++ { + if _, err := r.Reconcile(ctx, request); err != nil { + t.Fatal(err) + } + } + assertHTTPGatewayReadiness(t, c, gateway, true) + var policy gatewayv1alpha3.BackendTLSPolicy + policyKey := client.ObjectKey{Namespace: "store", Name: gatewayresolver.TLSProjectionName("api")} + if err := c.Get(ctx, policyKey, &policy); err != nil { + t.Fatal(err) + } + if len(policy.OwnerReferences) != 1 || policy.OwnerReferences[0].Kind != "ServiceImport" || len(policy.Status.Ancestors) != 1 || + policy.Status.Ancestors[0].AncestorRef.Name != gatewayv1.ObjectName(gateway.Name) { + t.Fatalf("hub policy ownership/status is not target/real Gateway based: %+v", policy) + } + shared := gateway.DeepCopy() + shared.Name, shared.UID, shared.ResourceVersion, shared.Finalizers = "shared", "shared-uid", "", nil + if err := c.Create(ctx, shared); err != nil { + t.Fatal(err) + } + route.Spec.ParentRefs = append(route.Spec.ParentRefs, gatewayv1.ParentReference{Name: "shared"}) + if err := c.Update(ctx, route); err != nil { + t.Fatal(err) + } + if err := r.reconcileTLSProjections(ctx); err != nil { + t.Fatal(err) + } + if err := c.Get(ctx, policyKey, &policy); err != nil { + t.Fatal(err) + } + if len(policy.Status.Ancestors) != 2 { + t.Fatalf("shared Gateway ancestry missing: %+v", policy.Status) + } + route.Spec.ParentRefs = route.Spec.ParentRefs[1:] + if err := c.Update(ctx, route); err != nil { + t.Fatal(err) + } + if err := r.reconcileTLSProjections(ctx); err != nil { + t.Fatal(err) + } + if err := c.Get(ctx, policyKey, &policy); err != nil || len(policy.Status.Ancestors) != 1 || policy.Status.Ancestors[0].AncestorRef.Name != "shared" { + t.Fatalf("withdrawing first ref broke shared policy: %+v %v", policy.Status, err) + } + if err := c.Delete(ctx, route); err != nil { + t.Fatal(err) + } + if err := r.reconcileTLSProjections(ctx); err != nil { + t.Fatal(err) + } + if err := c.Get(ctx, policyKey, &policy); !apierrors.IsNotFound(err) { + t.Fatalf("last ref retained projection: %v", err) + } + if provider.calls == 0 { + t.Fatal("secure graph was never provisioned") + } +} + +func TestTLSControllerLocalExclusionAndGlobalConflict(t *testing.T) { + ctx := context.Background() + c, gateway, _, r, provider := tlsControllerFixture(t, 2) + request := ctrl.Request{NamespacedName: client.ObjectKeyFromObject(gateway)} + if _, err := r.Reconcile(ctx, request); err != nil { + t.Fatal(err) + } + var export fleetnetv1alpha1.InternalServiceExport + key := client.ObjectKey{Namespace: "fleet-member-member-0", Name: "store-api"} + if err := c.Get(ctx, key, &export); err != nil { + t.Fatal(err) + } + export.Spec.OriginTLS.Ready, export.Spec.OriginTLS.Reason = false, "PolicyNotExported" + if err := c.Update(ctx, &export); err != nil { + t.Fatal(err) + } + if _, err := r.Reconcile(ctx, request); err != nil { + t.Fatal(err) + } + assertHTTPGatewayReadiness(t, c, gateway, true) + backend := provider.model.Routes[0].Rules[0].Backends[0] + if len(backend.Origins) != 1 || len(backend.ExcludedOrigins) != 1 { + t.Fatalf("local failure not isolated: %+v", backend) + } + if !strings.Contains(meta.FindStatusCondition(gateway.Status.Conditions, "Programmed").Message, "reduced capacity") { + t.Fatal("degradation hidden") + } + export.Spec.OriginTLS.Ready, export.Spec.OriginTLS.Reason, export.Spec.OriginTLS.Hostname = true, "Ready", "conflict.example.com" + if err := c.Update(ctx, &export); err != nil { + t.Fatal(err) + } + calls := provider.calls + if _, err := r.Reconcile(ctx, request); err != nil { + t.Fatal(err) + } + assertHTTPGatewayReadiness(t, c, gateway, false) + if provider.calls != calls || provider.withdrawals == 0 { + t.Fatal("conflicting valid identity was programmed instead of withdrawing") + } +} + +func TestTLSControllerNeverAdoptsForeignProjection(t *testing.T) { + ctx := context.Background() + c, gateway, _, r, provider := tlsControllerFixture(t, 1) + foreign := &gatewayv1alpha3.BackendTLSPolicy{ObjectMeta: metav1.ObjectMeta{Namespace: "store", Name: gatewayresolver.TLSProjectionName("api")}} + if err := c.Create(ctx, foreign); err != nil { + t.Fatal(err) + } + if _, err := r.Reconcile(ctx, ctrl.Request{NamespacedName: client.ObjectKeyFromObject(gateway)}); err == nil { + t.Fatal("foreign policy collision hidden") + } + if provider.calls != 0 { + t.Fatal("foreign projection authorized traffic") + } + var current gatewayv1alpha3.BackendTLSPolicy + if err := c.Get(ctx, client.ObjectKeyFromObject(foreign), ¤t); err != nil { + t.Fatal(err) + } + if len(current.OwnerReferences) != 0 || len(current.Spec.TargetRefs) != 0 { + t.Fatal("foreign policy was mutated") + } +} diff --git a/pkg/controllers/hub/gateway/ownership.go b/pkg/controllers/hub/gateway/ownership.go index d03c67c9..8861508f 100644 --- a/pkg/controllers/hub/gateway/ownership.go +++ b/pkg/controllers/hub/gateway/ownership.go @@ -91,7 +91,7 @@ func (r *Reconciler) currentProvisioningIntent(ctx context.Context, expected *ga if err != nil { return nil, err } - actual, err := resolveGateway(ctx, r.APIReader, current.DeepCopy(), class, false) + actual, err := resolveGateway(ctx, r.APIReader, current.DeepCopy(), class, false, r.EnableOriginTLS) if err != nil { return nil, err } diff --git a/pkg/controllers/hub/gateway/staging.go b/pkg/controllers/hub/gateway/staging.go index d41c9048..ed31c3f0 100644 --- a/pkg/controllers/hub/gateway/staging.go +++ b/pkg/controllers/hub/gateway/staging.go @@ -7,6 +7,7 @@ package gateway import ( "context" + "errors" "fmt" "reflect" "time" @@ -15,6 +16,7 @@ import ( "k8s.io/apimachinery/pkg/types" "k8s.io/klog/v2" "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" gatewayv1 "sigs.k8s.io/gateway-api/apis/v1" "go.goms.io/fleet-networking/pkg/common/objectmeta" @@ -64,6 +66,13 @@ func (r *Reconciler) stageGraph(ctx context.Context, gateway *gatewayv1.Gateway) } model, err := r.resolve(ctx, gateway.DeepCopy(), &class) if err != nil { + if r.EnableOriginTLS && r.HTTPProvisioner != nil { + for _, listener := range gateway.Spec.Listeners { + if listener.Protocol == gatewayv1.HTTPSProtocolType { + return r.suspendUncertainTLS(ctx, gateway, err) + } + } + } return nil, err } if model == nil { @@ -97,6 +106,27 @@ func (r *Reconciler) stageGraph(ctx context.Context, gateway *gatewayv1.Gateway) return staging, staging.err } +// Loss of TLS inventory must not leave an owned endpoint serving indefinitely. +// Current UID/generation, class controller, hub identity and finalizer still gate +// suspension; uncertainty never authorizes provisioning or adopting resources. +func (r *Reconciler) suspendUncertainTLS(ctx context.Context, expected *gatewayv1.Gateway, cause error) (*gatewayStaging, error) { + hubUID, err := r.provisioningHubUID(ctx) + if err != nil { + return nil, errors.Join(cause, err) + } + current, _, err := r.currentGatewayIdentity(ctx, expected, hubUID) + if err != nil { + return nil, errors.Join(cause, err) + } + if !controllerutil.ContainsFinalizer(current, objectmeta.GatewayAFDCleanupFinalizer) { + return nil, cause + } + owner := frontdoor.GatewayOwner{HubUID: hubUID, Namespace: current.Namespace, Name: current.Name, UID: string(current.UID)} + suspension, suspendErr := r.suspendEndpoint(ctx, owner) + staging := &gatewayStaging{uid: current.UID, generation: current.Generation, invalid: true, suspension: &suspension, err: suspendErr} + return staging, errors.Join(cause, suspendErr) +} + func applyGraphStaging(gateway *gatewayv1.Gateway, model *gatewaymodel.GlobalGateway, staging *gatewayStaging) { if staging == nil || gateway.UID != staging.uid || gateway.Generation != staging.generation { return diff --git a/pkg/controllers/hub/gateway/suite_test.go b/pkg/controllers/hub/gateway/suite_test.go index e63d2d7f..c89c002a 100644 --- a/pkg/controllers/hub/gateway/suite_test.go +++ b/pkg/controllers/hub/gateway/suite_test.go @@ -29,6 +29,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/log/zap" metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server" gatewayv1 "sigs.k8s.io/gateway-api/apis/v1" + gatewayv1alpha3 "sigs.k8s.io/gateway-api/apis/v1alpha3" gatewayv1beta1 "sigs.k8s.io/gateway-api/apis/v1beta1" fleetnetv1alpha1 "go.goms.io/fleet-networking/api/v1alpha1" @@ -81,7 +82,7 @@ var _ = BeforeSuite(func() { testEnvironment := &envtest.Environment{ CRDDirectoryPaths: []string{ filepath.Join("..", "..", "..", "..", "config", "crd", "bases"), - filepath.Join(strings.TrimSpace(string(module)), "config", "crd", "standard"), + filepath.Join(strings.TrimSpace(string(module)), "config", "crd", "experimental"), }, ErrorIfCRDPathMissing: true, } @@ -96,7 +97,7 @@ var _ = BeforeSuite(func() { scheme := runtime.NewScheme() for _, install := range []func(*runtime.Scheme) error{ - corev1.AddToScheme, gatewayv1.Install, gatewayv1beta1.Install, fleetnetv1alpha1.AddToScheme, + corev1.AddToScheme, gatewayv1.Install, gatewayv1beta1.Install, gatewayv1alpha3.Install, fleetnetv1alpha1.AddToScheme, } { Expect(install(scheme)).To(Succeed()) } @@ -129,8 +130,9 @@ var _ = BeforeSuite(func() { Client: manager.GetClient(), APIReader: manager.GetAPIReader(), OriginObserver: integrationProvider, ProfileCleanup: integrationProvider, HTTPProvisioner: integrationProvider, Recorder: integrationRecorder, + EnableOriginTLS: true, }).SetupWithManager(manager)).To(Succeed()) - Expect((&httproute.Reconciler{Client: manager.GetClient()}).SetupWithManager(manager)).To(Succeed()) + Expect((&httproute.Reconciler{Client: manager.GetClient(), EnableOriginTLS: true}).SetupWithManager(manager)).To(Succeed()) done := make(chan error, 1) DeferCleanup(func() { cancel() diff --git a/pkg/controllers/hub/gatewaymodel/capacity.go b/pkg/controllers/hub/gatewaymodel/capacity.go index 98e5d7f3..1bc39f7d 100644 --- a/pkg/controllers/hub/gatewaymodel/capacity.go +++ b/pkg/controllers/hub/gatewaymodel/capacity.go @@ -38,15 +38,16 @@ func PreflightBackendCapacity(model GlobalGateway) (BackendCapacity, error) { port int32 } services := make(map[string]struct{}) - groups := make(map[backendKey][]Origin) + groups := make(map[backendKey]Backend) var capacity BackendCapacity for _, route := range normalized.Routes { for _, rule := range route.Rules { for _, backend := range rule.Backends { key := backendKey{namespace: backend.Namespace, name: backend.Name, port: backend.Port} - if origins, found := groups[key]; found { + if previous, found := groups[key]; found { // Never let traversal order choose between inconsistent copies of one backend. - if !reflect.DeepEqual(origins, backend.Origins) { + previous.RouteWeight = backend.RouteWeight + if !reflect.DeepEqual(previous, backend) { return BackendCapacity{}, fmt.Errorf("inconsistent origins for backend %s/%s:%d", key.namespace, key.name, key.port) } continue @@ -55,7 +56,7 @@ func PreflightBackendCapacity(model GlobalGateway) (BackendCapacity, error) { return BackendCapacity{}, fmt.Errorf("backend %s/%s:%d has %d origins, maximum is %d", key.namespace, key.name, key.port, len(backend.Origins), maxOriginsPerBackend) } - groups[key] = backend.Origins + groups[key] = backend services[key.namespace+"/"+key.name] = struct{}{} capacity.OriginGroups++ capacity.Origins += len(backend.Origins) diff --git a/pkg/controllers/hub/gatewaymodel/model.go b/pkg/controllers/hub/gatewaymodel/model.go index e2af9925..0a85b6f9 100644 --- a/pkg/controllers/hub/gatewaymodel/model.go +++ b/pkg/controllers/hub/gatewaymodel/model.go @@ -16,6 +16,8 @@ import ( "time" "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + + "go.goms.io/fleet-networking/pkg/common/origintls" ) const maxServiceExportWeight = 1000 @@ -23,6 +25,9 @@ const maxHTTPRouteBackendWeight = 1000000 const pathTypePrefix = "PathPrefix" const defaultHTTPPreviewHealthProbePath = "/" +// ProtocolHTTPS identifies TLS on both the listener and origin probe. +const ProtocolHTTPS = "HTTPS" + // GlobalGateway is the normalized desired state for one Gateway. type GlobalGateway struct { Namespace string @@ -35,10 +40,11 @@ type GlobalGateway struct { // Listener is a normalized Gateway listener. type Listener struct { - Name string - Protocol string - Port int32 - Hostname string + Name string + Protocol string + Port int32 + Hostname string + DefaultCertificate bool } // Route is a normalized HTTPRoute attached to a Gateway. @@ -103,6 +109,16 @@ type Backend struct { // must be verified independently before enabling the provider. OriginHostHeader string Origins []Origin + TLSHostname string + TargetUID string + TLSProvenance string + ExcludedOrigins []ExcludedOrigin +} + +// ExcludedOrigin records a member-local failure, never an identity vote. +type ExcludedOrigin struct { + Cluster string + Reason string } // HealthProbe is platform-owned; its port is the backend's selected service port. @@ -121,6 +137,13 @@ func HTTPPreviewHealthProbe() HealthProbe { return HealthProbe{Path: probePath, Method: "GET", Protocol: "HTTP", IntervalSeconds: 30} } +// HTTPSHealthProbe is independent of edge TLS and uses the selected Service port. +func HTTPSHealthProbe() HealthProbe { + probe := HTTPPreviewHealthProbe() + probe.Protocol = ProtocolHTTPS + return probe +} + // Origin represents one member-cluster endpoint behind a ServiceImport. type Origin struct { Cluster string @@ -253,6 +276,7 @@ func clone(model GlobalGateway) GlobalGateway { route.Rules[i].Backends = append([]Backend(nil), source.Rules[i].Backends...) for j := range source.Rules[i].Backends { route.Rules[i].Backends[j].Origins = append([]Origin(nil), source.Rules[i].Backends[j].Origins...) + route.Rules[i].Backends[j].ExcludedOrigins = append([]ExcludedOrigin(nil), source.Rules[i].Backends[j].ExcludedOrigins...) } } } @@ -273,7 +297,8 @@ func validate(model GlobalGateway) error { return fmt.Errorf("duplicate listener %q", listener.Name) } listeners[listener.Name] = listener - if listener.Protocol != "HTTP" || listener.Port != 80 { + if !((listener.Protocol == "HTTP" && listener.Port == 80 && !listener.DefaultCertificate) || + (listener.Protocol == ProtocolHTTPS && listener.Port == 443 && listener.DefaultCertificate && listener.Hostname == "" && len(model.Listeners) == 1)) { return fmt.Errorf("listener %q requires HTTP on edge port 80 in the initial preview", listener.Name) } if err := validateHostname(listener.Hostname); err != nil { @@ -315,6 +340,14 @@ func validateRoute(route Route, routeKey string, listeners map[string]Listener) } } for ruleIndex, rule := range route.Rules { + for _, attachment := range route.Attachments { + secure := listeners[attachment.Listener].Protocol == ProtocolHTTPS + for _, backend := range rule.Backends { + if secure != (backend.TLSHostname != "") { + return fmt.Errorf("edge and origin protocols must both use HTTP or both HTTPS") + } + } + } if err := validateRule(rule, routeKey, ruleIndex); err != nil { return err } @@ -358,7 +391,19 @@ func validateBackend(backend Backend, backendKey, routeKey string) error { if backend.RouteWeight < 1 || backend.RouteWeight > maxHTTPRouteBackendWeight { return fmt.Errorf("route %q backend %q requires a positive route weight at most %d", routeKey, backendKey, maxHTTPRouteBackendWeight) } - if backend.HealthProbe != HTTPPreviewHealthProbe() || backend.OriginHostHeader != "" { + probe := HTTPPreviewHealthProbe() + if backend.TLSHostname != "" { + probe = HTTPSHealthProbe() + if err := origintls.ValidateHostname(backend.TLSHostname); err != nil { + return err + } + if backend.TargetUID == "" || backend.TLSProvenance == "" { + return fmt.Errorf("HTTPS backend requires target UID and source provenance") + } + } else if backend.TargetUID != "" || backend.TLSProvenance != "" || len(backend.ExcludedOrigins) != 0 { + return fmt.Errorf("HTTP backend cannot carry TLS authorization") + } + if backend.HealthProbe != probe || backend.OriginHostHeader != "" { return fmt.Errorf("backend %q requires the fixed HTTP-preview probe and incoming Host policy", backendKey) } if len(backend.Origins) == 0 { diff --git a/pkg/controllers/hub/gatewayresolver/backend.go b/pkg/controllers/hub/gatewayresolver/backend.go index e3962dd4..0c84a405 100644 --- a/pkg/controllers/hub/gatewayresolver/backend.go +++ b/pkg/controllers/hub/gatewayresolver/backend.go @@ -7,9 +7,12 @@ Licensed under the MIT license. package gatewayresolver import ( + "crypto/sha256" + "encoding/json" "errors" "fmt" "sort" + "time" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/equality" @@ -22,6 +25,7 @@ import ( fleetnetv1beta1 "go.goms.io/fleet-networking/api/v1beta1" "go.goms.io/fleet-networking/pkg/annotations" "go.goms.io/fleet-networking/pkg/common/hubconfig" + "go.goms.io/fleet-networking/pkg/common/origintls" "go.goms.io/fleet-networking/pkg/controllers/hub/gatewaymodel" ) @@ -43,37 +47,25 @@ func (e *ResolutionError) Error() string { // backend on failure. The caller must enforce ReferenceGrant authorization before // invoking Resolve for a cross-namespace reference. func Resolve(routeNamespace string, ref gatewayv1.HTTPBackendRef, service *fleetnetv1alpha1.ServiceImport, - exports []fleetnetv1alpha1.InternalServiceExport) (gatewaymodel.Backend, error) { - if ptr.Deref(ref.Group, "") != gatewayv1.Group(fleetnetv1alpha1.GroupVersion.Group) || - ptr.Deref(ref.Kind, "Service") != serviceImportKind { - return resolutionFailure("InvalidKind", false, "only %s/ServiceImport backends are supported", fleetnetv1alpha1.GroupVersion.Group) - } - namespace := string(ptr.Deref(ref.Namespace, gatewayv1.Namespace(routeNamespace))) - if namespace == "" || ref.Name == "" || service == nil || service.Namespace != namespace || - service.Name != string(ref.Name) || service.DeletionTimestamp != nil { - return resolutionFailure("BackendNotFound", false, "ServiceImport %s/%s is unavailable", namespace, ref.Name) - } - weight := ptr.Deref(ref.Weight, 1) - if weight < 0 || weight > 1000000 || len(ref.Filters) != 0 { - return resolutionFailure("UnsupportedValue", false, "backend weight must be in [0, 1000000] and backend filters are not supported") - } - if err := validateHTTPPort(ref.Port, service.Status.Ports); err != nil { + exports []fleetnetv1alpha1.InternalServiceExport, originTLS ...bool) (gatewaymodel.Backend, error) { + secure := len(originTLS) != 0 && originTLS[0] + backend, err := resolveBackendReference(routeNamespace, ref, service, secure) + if err != nil { return gatewaymodel.Backend{}, err } - if err := annotations.ValidateServiceImportAnnotations(service.Annotations); err != nil { - return resolutionFailure("UnsupportedConfiguration", true, "%v", err) - } - if service.Status.Type != "" && service.Status.Type != fleetnetv1alpha1.ClusterSetIP { - return resolutionFailure("UnsupportedTopology", true, "headless ServiceImports are not supported") - } + namespace := backend.Namespace exportsByCluster, err := selectBackendExports(namespace, service, exports) if err != nil { return gatewaymodel.Backend{}, err } - backend := gatewaymodel.Backend{ - Namespace: namespace, Name: service.Name, Port: int32(*ref.Port), - RouteWeight: weight, HealthProbe: gatewaymodel.HTTPPreviewHealthProbe(), + if secure { + if err := validateTLSInventory(namespace, service, exportsByCluster, exports); err != nil { + return gatewaymodel.Backend{}, err + } + backend.TargetUID = string(service.UID) + backend.HealthProbe = gatewaymodel.HTTPSHealthProbe() } + var provenance []string clusterNames := make([]string, 0, len(exportsByCluster)) for cluster := range exportsByCluster { clusterNames = append(clusterNames, cluster) @@ -82,13 +74,29 @@ func Resolve(routeNamespace string, ref gatewayv1.HTTPBackendRef, service *fleet for _, cluster := range clusterNames { export := exportsByCluster[cluster] if export == nil { + if secure { + return resolutionFailure("IncompleteInventory", true, "cluster %q is listed but its export is absent", cluster) + } // Export deletion and ServiceImport aggregation are not atomic. continue } + if secure { + binding, eligible, err := resolveMemberTLS(&backend, export) + if err != nil { + return gatewaymodel.Backend{}, err + } + provenance = append(provenance, binding) + if !eligible { + continue + } + } origin, err := resolveExportOrigin(namespace, service, export) if err != nil { var unavailable *ResolutionError if errors.As(err, &unavailable) && unavailable.Reason == "PrivateOriginUnavailable" { + if secure { + backend.ExcludedOrigins = append(backend.ExcludedOrigins, gatewaymodel.ExcludedOrigin{Cluster: cluster, Reason: unavailable.Reason}) + } // Discovery delay must not withdraw other ready private members. continue } @@ -101,10 +109,85 @@ func Resolve(routeNamespace string, ref gatewayv1.HTTPBackendRef, service *fleet if len(backend.Origins) == 0 { return resolutionFailure("BackendUnavailable", true, "ServiceImport has no ready private origin from an active member") } + if secure { + backend.TLSProvenance = fmt.Sprintf("%x", sha256.Sum256([]byte(fmt.Sprintf("%q", provenance)))) + } return backend, nil } -func validateHTTPPort(number *gatewayv1.PortNumber, ports []fleetnetv1alpha1.ServicePort) error { +func resolveBackendReference(routeNamespace string, ref gatewayv1.HTTPBackendRef, + service *fleetnetv1alpha1.ServiceImport, secure bool) (gatewaymodel.Backend, error) { + if ptr.Deref(ref.Group, "") != gatewayv1.Group(fleetnetv1alpha1.GroupVersion.Group) || + ptr.Deref(ref.Kind, "Service") != serviceImportKind { + return resolutionFailure("InvalidKind", false, "only %s/ServiceImport backends are supported", fleetnetv1alpha1.GroupVersion.Group) + } + namespace := string(ptr.Deref(ref.Namespace, gatewayv1.Namespace(routeNamespace))) + if namespace == "" || ref.Name == "" || service == nil || service.Namespace != namespace || + service.Name != string(ref.Name) || service.DeletionTimestamp != nil { + return resolutionFailure("BackendNotFound", false, "ServiceImport %s/%s is unavailable", namespace, ref.Name) + } + weight := ptr.Deref(ref.Weight, 1) + if weight < 0 || weight > 1000000 || len(ref.Filters) != 0 { + return resolutionFailure("UnsupportedValue", false, "backend weight must be in [0, 1000000] and backend filters are not supported") + } + if err := validateHTTPPort(ref.Port, service.Status.Ports, secure); err != nil { + return gatewaymodel.Backend{}, err + } + if err := annotations.ValidateServiceImportAnnotations(service.Annotations); err != nil { + return resolutionFailure("UnsupportedConfiguration", true, "%v", err) + } + if service.Status.Type != "" && service.Status.Type != fleetnetv1alpha1.ClusterSetIP { + return resolutionFailure("UnsupportedTopology", true, "headless ServiceImports are not supported") + } + return gatewaymodel.Backend{ + Namespace: namespace, Name: service.Name, Port: int32(*ref.Port), + RouteWeight: weight, HealthProbe: gatewaymodel.HTTPPreviewHealthProbe(), + }, nil +} + +func validateTLSInventory(namespace string, service *fleetnetv1alpha1.ServiceImport, + selected map[string]*fleetnetv1alpha1.InternalServiceExport, exports []fleetnetv1alpha1.InternalServiceExport) error { + if service.UID == "" { + return newResolutionError("InvalidExport", true, "TLS backend requires ServiceImport UID") + } + for i := range exports { + source := exports[i].Spec.ServiceReference + if exports[i].DeletionTimestamp == nil && source.Namespace == namespace && source.Name == service.Name { + if _, exists := selected[source.ClusterID]; !exists { + return newResolutionError("IncompleteInventory", true, "export inventory and ServiceImport membership disagree") + } + } + } + return nil +} + +func resolveMemberTLS(backend *gatewaymodel.Backend, export *fleetnetv1alpha1.InternalServiceExport) (string, bool, error) { + source := export.Spec.ServiceReference + cluster := source.ClusterID + // Establish source identity before attributing a policy failure to a member. + if export.Namespace != fmt.Sprintf(hubconfig.HubNamespaceNameFormat, cluster) || source.UID == "" || + source.NamespacedName != backend.Namespace+"/"+backend.Name { + return "", false, newResolutionError("InvalidExport", true, "TLS inventory has unverifiable member provenance") + } + if reason := tlsExclusion(export, time.Now()); reason != "" { + backend.ExcludedOrigins = append(backend.ExcludedOrigins, gatewaymodel.ExcludedOrigin{Cluster: cluster, Reason: reason}) + return cluster + ":" + string(source.UID) + ":" + reason, false, nil + } + tls := export.Spec.OriginTLS + if backend.TLSHostname != "" && backend.TLSHostname != tls.Hostname { + return "", false, newResolutionError("ConflictingTLSIdentity", true, "valid member TLS identities disagree; no majority selection is permitted") + } + backend.TLSHostname = tls.Hostname + binding, err := json.Marshal(tls.Policy) + if err != nil { + return "", false, err + } + return cluster + ":" + string(source.UID) + ":" + tls.Hostname + ":" + string(binding), true, nil +} + +const invalidTLSObservation = "InvalidTLSObservation" + +func validateHTTPPort(number *gatewayv1.PortNumber, ports []fleetnetv1alpha1.ServicePort, originTLS ...bool) error { if number == nil || *number < 1 || *number > 65535 { return newResolutionError("PortNotFound", false, "a valid ServiceImport backend port is required") } @@ -127,12 +210,45 @@ func validateHTTPPort(number *gatewayv1.PortNumber, ports []fleetnetv1alpha1.Ser if !exists { return newResolutionError("PortNotFound", false, "ServiceImport has no port %d", *number) } - if selected == nil || (ptr.Deref(selected.AppProtocol, "") != "" && *selected.AppProtocol != "http") { + secure := len(originTLS) != 0 && originTLS[0] + if secure && (selected == nil || ptr.Deref(selected.AppProtocol, "") != "https") { + return newResolutionError("UnsupportedProtocol", false, "HTTPS requires an explicit https appProtocol on the selected TCP Service port") + } + if !secure && (selected == nil || (ptr.Deref(selected.AppProtocol, "") != "" && *selected.AppProtocol != "http")) { return newResolutionError("UnsupportedProtocol", false, "the HTTP preview requires a TCP port with absent or http appProtocol") } return nil } +func tlsExclusion(export *fleetnetv1alpha1.InternalServiceExport, now time.Time) string { + tls := export.Spec.OriginTLS + if tls == nil { + return "PolicyMissing" + } + if !tls.Ready { + switch tls.Reason { + case "PolicyMissing", "DuplicatePolicies", "PolicyNotExported", "UnsupportedPolicy", "PolicyReadFailed": + return tls.Reason + default: + return invalidTLSObservation + } + } + observedAt, err := origintls.ObservedAt(export) + if err != nil { + return invalidTLSObservation + } + if observedAt.IsZero() || now.Sub(observedAt) > origintls.MaxAge || observedAt.After(now.Add(time.Minute)) { + return "StaleTLSObservation" + } + policy := tls.Policy + if tls.ServiceUID != string(export.Spec.ServiceReference.UID) || policy == nil || policy.Namespace != export.Spec.ServiceReference.Namespace || + policy.Name == "" || policy.UID == "" || policy.ResourceVersion == "" || policy.Generation < 1 || + policy.ExportToFleet != origintls.ExportAnnotationValue || tls.Trust != "System" || origintls.ValidateHostname(tls.Hostname) != nil { + return invalidTLSObservation + } + return "" +} + func selectBackendExports(namespace string, service *fleetnetv1alpha1.ServiceImport, exports []fleetnetv1alpha1.InternalServiceExport) (map[string]*fleetnetv1alpha1.InternalServiceExport, error) { selected := make(map[string]*fleetnetv1alpha1.InternalServiceExport, len(service.Status.Clusters)) diff --git a/pkg/controllers/hub/gatewayresolver/indexes.go b/pkg/controllers/hub/gatewayresolver/indexes.go index fd6e36fc..5589d5f5 100644 --- a/pkg/controllers/hub/gatewayresolver/indexes.go +++ b/pkg/controllers/hub/gatewayresolver/indexes.go @@ -16,6 +16,7 @@ import ( "k8s.io/utils/ptr" "sigs.k8s.io/controller-runtime/pkg/client" gatewayv1 "sigs.k8s.io/gateway-api/apis/v1" + gatewayv1alpha3 "sigs.k8s.io/gateway-api/apis/v1alpha3" gatewayv1beta1 "sigs.k8s.io/gateway-api/apis/v1beta1" fleetnetv1alpha1 "go.goms.io/fleet-networking/api/v1alpha1" @@ -115,6 +116,9 @@ func DependentRoutes(ctx context.Context, reader client.Reader, object client.Ob options = append(options, client.MatchingFields{HTTPRouteServiceImportField: dependency.Spec.ServiceReference.NamespacedName}) case *gatewayv1beta1.ReferenceGrant: options = append(options, client.MatchingFields{HTTPRouteBackendNamespaceField: dependency.Namespace}) + case *gatewayv1alpha3.BackendTLSPolicy: + // Include old targets on retargeting/metadata updates: namespace-scoped. + options = append(options, client.InNamespace(dependency.Namespace)) case *corev1.Namespace: options = append(options, client.InNamespace(dependency.Name)) default: diff --git a/pkg/controllers/hub/gatewayresolver/origintls.go b/pkg/controllers/hub/gatewayresolver/origintls.go new file mode 100644 index 00000000..1686eb99 --- /dev/null +++ b/pkg/controllers/hub/gatewayresolver/origintls.go @@ -0,0 +1,95 @@ +/* +Copyright (c) Microsoft Corporation. +Licensed under the MIT license. +*/ + +package gatewayresolver + +import ( + "context" + "crypto/sha256" + "fmt" + "reflect" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + "k8s.io/utils/ptr" + "sigs.k8s.io/controller-runtime/pkg/client" + gatewayv1 "sigs.k8s.io/gateway-api/apis/v1" + gatewayv1alpha2 "sigs.k8s.io/gateway-api/apis/v1alpha2" + gatewayv1alpha3 "sigs.k8s.io/gateway-api/apis/v1alpha3" + + fleetnetv1alpha1 "go.goms.io/fleet-networking/api/v1alpha1" + "go.goms.io/fleet-networking/pkg/common/origintls" + "go.goms.io/fleet-networking/pkg/controllers/hub/gatewaymodel" +) + +// TLSProjectionName is target-derived, independent of referencing Gateway order. +func TLSProjectionName(service string) string { + name := service + "-origin-tls" + if len(name) <= 253 { + return name + } + return fmt.Sprintf("%s-%x-origin-tls", service[:160], sha256.Sum256([]byte(service))) +} + +// TLSProjection builds the exact owned hub policy, never a customer Secret. +func TLSProjection(backend gatewaymodel.Backend) *gatewayv1alpha3.BackendTLSPolicy { + return &gatewayv1alpha3.BackendTLSPolicy{ + ObjectMeta: metav1.ObjectMeta{ + Namespace: backend.Namespace, Name: TLSProjectionName(backend.Name), + Labels: map[string]string{origintls.ProjectionLabel: "true"}, + Annotations: map[string]string{origintls.ProvenanceAnnotation: backend.TLSProvenance}, + OwnerReferences: []metav1.OwnerReference{{APIVersion: fleetnetv1alpha1.GroupVersion.String(), Kind: serviceImportKind, + Name: backend.Name, UID: types.UID(backend.TargetUID), Controller: ptr.To(true)}}, + }, + Spec: gatewayv1alpha3.BackendTLSPolicySpec{ + TargetRefs: []gatewayv1alpha2.LocalPolicyTargetReferenceWithSectionName{{ + LocalPolicyTargetReference: gatewayv1alpha2.LocalPolicyTargetReference{ + Group: gatewayv1.Group(fleetnetv1alpha1.GroupVersion.Group), Kind: serviceImportKind, Name: gatewayv1.ObjectName(backend.Name)}, + }}, + Validation: gatewayv1alpha3.BackendTLSPolicyValidation{ + Hostname: gatewayv1.PreciseHostname(backend.TLSHostname), + WellKnownCACertificates: ptr.To(gatewayv1alpha3.WellKnownCACertificatesSystem), + }, + }, + } +} + +// OwnsTLSProjection requires exact target UID ownership, not a name or label alone. +func OwnsTLSProjection(policy *gatewayv1alpha3.BackendTLSPolicy, backend gatewaymodel.Backend) bool { + return policy.Namespace == backend.Namespace && policy.Name == TLSProjectionName(backend.Name) && + policy.Labels[origintls.ProjectionLabel] == "true" && + reflect.DeepEqual(policy.OwnerReferences, TLSProjection(backend).OwnerReferences) +} + +// ValidateTLSProjection ignores Accepted status and checks current spec/provenance. +func ValidateTLSProjection(ctx context.Context, reader client.Reader, backend gatewaymodel.Backend) error { + var policies gatewayv1alpha3.BackendTLSPolicyList + if err := reader.List(ctx, &policies, client.InNamespace(backend.Namespace)); err != nil { + return err + } + expected := TLSProjection(backend) + found := false + for i := range policies.Items { + policy := &policies.Items[i] + targets := policy.Name == expected.Name + for _, ref := range policy.Spec.TargetRefs { + if string(ref.Group) == fleetnetv1alpha1.GroupVersion.Group && ref.Kind == serviceImportKind && string(ref.Name) == backend.Name { + targets = true + } + } + if !targets { + continue + } + if found || policy.DeletionTimestamp != nil || !OwnsTLSProjection(policy, backend) || + !reflect.DeepEqual(policy.Spec, expected.Spec) || policy.Annotations[origintls.ProvenanceAnnotation] != backend.TLSProvenance { + return newResolutionError("InvalidTLSProjection", true, "hub TLS policy is foreign, competing, stale or differs from current member intent") + } + found = true + } + if !found { + return newResolutionError("TLSProjectionPending", true, "owned hub TLS policy has not been observed") + } + return nil +} diff --git a/pkg/controllers/hub/gatewayresolver/origintls_test.go b/pkg/controllers/hub/gatewayresolver/origintls_test.go new file mode 100644 index 00000000..3a2471a6 --- /dev/null +++ b/pkg/controllers/hub/gatewayresolver/origintls_test.go @@ -0,0 +1,202 @@ +/* +Copyright (c) Microsoft Corporation. +Licensed under the MIT license. +*/ + +package gatewayresolver + +import ( + "context" + "errors" + "reflect" + "strings" + "testing" + "time" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/utils/ptr" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + gatewayv1 "sigs.k8s.io/gateway-api/apis/v1" + gatewayv1alpha3 "sigs.k8s.io/gateway-api/apis/v1alpha3" + + fleetnetv1alpha1 "go.goms.io/fleet-networking/api/v1alpha1" + "go.goms.io/fleet-networking/pkg/common/origintls" +) + +func tlsBackendFixture() backendFixture { + f := newBackendFixture() + f.service.UID = "service-import-uid" + f.service.Status.Ports[0].AppProtocol = ptr.To("https") + for i := range f.exports { + export := &f.exports[i] + export.Spec.Ports = append([]fleetnetv1alpha1.ServicePort(nil), f.service.Status.Ports...) + export.Spec.OriginTLS = &fleetnetv1alpha1.OriginTLS{Ready: true, Reason: "Ready", ObservedAt: metav1.Now(), + ServiceUID: string(export.Spec.ServiceReference.UID), Hostname: "origin.example.com", Trust: "System", + Policy: &fleetnetv1alpha1.OriginTLSPolicyReference{Namespace: "store", Name: "api-tls", UID: "policy-" + export.Spec.ServiceReference.ClusterID, + Generation: 1, ResourceVersion: "opaque", ExportToFleet: "true"}, + } + } + return f +} + +func TestTLSBackendEligibilityAndAgreement(t *testing.T) { + const conflictingHostname = "different.example.com" + tests := []struct { + name string + change func(*backendFixture) + origins int + reason string + }{ + {"agree", nil, 2, ""}, + {"one missing", func(f *backendFixture) { f.exports[0].Spec.OriginTLS = nil }, 1, ""}, + {"one invalid", func(f *backendFixture) { + f.exports[0].Spec.OriginTLS.Ready = false + f.exports[0].Spec.OriginTLS.Reason = "DuplicatePolicies" + }, 1, ""}, + {"invalid empty reason cannot authorize", func(f *backendFixture) { + f.exports[0].Spec.OriginTLS.Ready = false + f.exports[0].Spec.OriginTLS.Reason = "" + }, 1, ""}, + {"expired", func(f *backendFixture) { + f.exports[0].Spec.OriginTLS.ObservedAt = metav1.NewTime(time.Now().Add(-origintls.MaxAge - time.Second)) + }, 1, ""}, + {"future timestamp", func(f *backendFixture) { + f.exports[0].Spec.OriginTLS.ObservedAt = metav1.NewTime(time.Now().Add(2 * time.Minute)) + }, 1, ""}, + {"source replay", func(f *backendFixture) { f.exports[0].Spec.OriginTLS.ServiceUID = "recreated" }, 1, ""}, + {"member policy namespace replay", func(f *backendFixture) { f.exports[0].Spec.OriginTLS.Policy.Namespace = "other" }, 1, ""}, + {"opt-out observation", func(f *backendFixture) { f.exports[0].Spec.OriginTLS.Policy.ExportToFleet = "false" }, 1, ""}, + {"private discovery unavailable", func(f *backendFixture) { f.exports[0].Spec.PrivateLinkOrigin.Ready = false }, 1, ""}, + {"valid identities conflict", func(f *backendFixture) { f.exports[0].Spec.OriginTLS.Hostname = conflictingHostname }, 0, "ConflictingTLSIdentity"}, + {"unready origin cannot hide valid identity conflict", func(f *backendFixture) { + f.exports[0].Spec.OriginTLS.Hostname = conflictingHostname + f.exports[0].Spec.PrivateLinkOrigin.Ready = false + }, 0, "ConflictingTLSIdentity"}, + {"zero weight cannot hide valid identity conflict", func(f *backendFixture) { + f.exports[0].Spec.OriginTLS.Hostname = conflictingHostname + f.exports[0].Spec.Weight = ptr.To[int64](0) + }, 0, "ConflictingTLSIdentity"}, + {"none eligible", func(f *backendFixture) { + for i := range f.exports { + f.exports[i].Spec.OriginTLS = nil + } + }, 0, "BackendUnavailable"}, + {"missing inventory", func(f *backendFixture) { f.exports = f.exports[:1] }, 0, "IncompleteInventory"}, + {"unaggregated source", func(f *backendFixture) { f.service.Status.Clusters = f.service.Status.Clusters[:1] }, 0, "IncompleteInventory"}, + {"foreign source namespace", func(f *backendFixture) { f.exports[0].Namespace = "not-a-member" }, 0, "InvalidExport"}, + {"explicit HTTPS protocol required", func(f *backendFixture) { f.service.Status.Ports[0].AppProtocol = nil }, 0, "UnsupportedProtocol"}, + {"port set mismatch", func(f *backendFixture) { f.exports[0].Spec.Ports[0].TargetPort.IntVal++ }, 0, "InvalidExport"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + f := tlsBackendFixture() + if tt.change != nil { + tt.change(&f) + } + got, err := Resolve("store", f.ref, f.service, f.exports, true) + if tt.reason != "" { + var resolution *ResolutionError + if !errors.As(err, &resolution) || resolution.Reason != tt.reason || len(got.Origins) != 0 { + t.Fatalf("backend=%+v error=%v want %s", got, err, tt.reason) + } + return + } + if err != nil || len(got.Origins) != tt.origins || got.TLSHostname != "origin.example.com" || got.TLSProvenance == "" || got.HealthProbe.Protocol != "HTTPS" { + t.Fatalf("backend=%+v error=%v", got, err) + } + if tt.origins == 1 && len(got.ExcludedOrigins) != 1 { + t.Fatalf("member exclusion hidden: %+v", got) + } + }) + } + f := tlsBackendFixture() + if _, err := Resolve("store", f.ref, f.service, f.exports); err == nil { + t.Fatal("default HTTP resolution silently accepted TLS-only Service") + } +} + +func TestTLSProjectionCurrentOwnershipAndContents(t *testing.T) { + f := tlsBackendFixture() + backend, err := Resolve("store", f.ref, f.service, f.exports, true) + if err != nil { + t.Fatal(err) + } + tests := []struct { + name string + change func(*gatewayv1alpha3.BackendTLSPolicy) + duplicate bool + }{ + {"valid", nil, false}, + {"foreign owner", func(p *gatewayv1alpha3.BackendTLSPolicy) { p.OwnerReferences[0].UID = "recreated-target" }, false}, + {"stale provenance", func(p *gatewayv1alpha3.BackendTLSPolicy) { p.Annotations[origintls.ProvenanceAnnotation] = "old" }, false}, + {"stale hostname with Accepted true", func(p *gatewayv1alpha3.BackendTLSPolicy) { p.Spec.Validation.Hostname = "old.example.com" }, false}, + {"manual competing policy", nil, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + policy := TLSProjection(backend) + if tt.change != nil { + tt.change(policy) + } + scheme := runtime.NewScheme() + if err := gatewayv1alpha3.Install(scheme); err != nil { + t.Fatal(err) + } + objects := []client.Object{policy} + if tt.duplicate { + other := policy.DeepCopy() + other.Name = "manual" + other.Labels = nil + other.OwnerReferences = nil + objects = append(objects, other) + } + c := fake.NewClientBuilder().WithScheme(scheme).WithObjects(objects...).Build() + err := ValidateTLSProjection(context.Background(), c, backend) + if (err == nil) != (tt.name == "valid") { + t.Fatalf("unexpected projection validation: %v", err) + } + }) + } + if name := TLSProjectionName(strings.Repeat("a", 253)); len(name) > 253 { + t.Fatalf("projection name too long: %d", len(name)) + } + renewed := f.exports[0].Spec.OriginTLS.DeepCopy() + renewed.ObservedAt = metav1.NewTime(time.Now().Add(time.Second)) + if err := origintls.RefreshObservation(&f.exports[0], renewed); err != nil { + t.Fatal(err) + } + again, err := Resolve("store", f.ref, f.service, f.exports, true) + if err != nil || !reflect.DeepEqual(backend, again) { + t.Fatalf("heartbeat destabilized backend: %+v %v", again, err) + } +} + +func TestHTTPSListenerRequiresExplicitBothHopCapability(t *testing.T) { + valid := gatewayv1.Listener{Name: "https", Protocol: gatewayv1.HTTPSProtocolType, Port: 443, + TLS: &gatewayv1.GatewayTLSConfig{Mode: ptr.To(gatewayv1.TLSModeTerminate), + Options: map[gatewayv1.AnnotationKey]gatewayv1.AnnotationValue{gatewayv1.AnnotationKey(origintls.DefaultCertificateOption): "true"}}} + if err := ValidateListener(valid); err == nil { + t.Fatal("TLS enabled by default") + } + for _, change := range []func(*gatewayv1.Listener){ + func(l *gatewayv1.Listener) { l.TLS = nil }, + func(l *gatewayv1.Listener) { l.Port = 80 }, + func(l *gatewayv1.Listener) { l.Hostname = ptr.To(gatewayv1.Hostname("custom.example.com")) }, + func(l *gatewayv1.Listener) { + l.TLS.Options[gatewayv1.AnnotationKey(origintls.DefaultCertificateOption)] = "false" + }, + func(l *gatewayv1.Listener) { l.TLS.Mode = ptr.To(gatewayv1.TLSModePassthrough) }, + func(l *gatewayv1.Listener) { l.TLS.CertificateRefs = []gatewayv1.SecretObjectReference{{Name: "cert"}} }, + } { + listener := *valid.DeepCopy() + change(&listener) + if err := ValidateListener(listener, true); err == nil { + t.Fatalf("unsupported listener accepted: %+v", listener) + } + } + if err := ValidateListener(valid, true); err != nil { + t.Fatal(err) + } +} diff --git a/pkg/controllers/hub/gatewayresolver/route.go b/pkg/controllers/hub/gatewayresolver/route.go index 1e967b19..f6927033 100644 --- a/pkg/controllers/hub/gatewayresolver/route.go +++ b/pkg/controllers/hub/gatewayresolver/route.go @@ -21,6 +21,7 @@ import ( fleetnetv1alpha1 "go.goms.io/fleet-networking/api/v1alpha1" "go.goms.io/fleet-networking/pkg/common/hubconfig" + "go.goms.io/fleet-networking/pkg/common/origintls" "go.goms.io/fleet-networking/pkg/controllers/hub/gatewaymodel" ) @@ -50,12 +51,18 @@ func GatewayParentKey(namespace string, parent gatewayv1.ParentReference) (types } // ValidateListener checks the initial private HTTP-preview listener subset. -func ValidateListener(listener gatewayv1.Listener) error { - // HTTPS endpoint listeners and certificate lifecycle are deferred to the HTTPS follow-up. - if listener.Protocol != gatewayv1.HTTPProtocolType || listener.Port != 80 { +func ValidateListener(listener gatewayv1.Listener, originTLS ...bool) error { + secure := len(originTLS) != 0 && originTLS[0] && listener.Protocol == gatewayv1.HTTPSProtocolType + if secure { + tls := listener.TLS + if listener.Port != 443 || listener.Hostname != nil || tls == nil || ptr.Deref(tls.Mode, gatewayv1.TLSModeTerminate) != gatewayv1.TLSModeTerminate || + len(tls.CertificateRefs) != 0 || len(tls.Options) != 1 || tls.Options[gatewayv1.AnnotationKey(origintls.DefaultCertificateOption)] != "true" { + return &ListenerError{Reason: gatewayv1.ListenerReasonInvalidCertificateRef, Message: "HTTPS requires port 443, termination with exactly the Fleet default-certificate option, no certificateRefs or hostname"} + } + } else if listener.Protocol != gatewayv1.HTTPProtocolType || listener.Port != 80 { return &ListenerError{Reason: gatewayv1.ListenerReasonUnsupportedProtocol, Message: fmt.Sprintf("listener %q requires HTTP on port 80", listener.Name)} } - if listener.TLS != nil { + if !secure && listener.TLS != nil { return &ListenerError{Reason: gatewayv1.ListenerReasonInvalidCertificateRef, Message: "TLS configuration is unsupported in the HTTP preview"} } if _, _, err := gatewaymodel.IntersectHostnames(string(ptr.Deref(listener.Hostname, "")), nil); err != nil { @@ -93,7 +100,7 @@ func ValidateListener(listener gatewayv1.Listener) error { // ResolveAttachments enforces parent selection, namespace policy and hostname // intersection. Namespace labels must come from the route's Namespace object. func ResolveAttachments(gateway *gatewayv1.Gateway, route *gatewayv1.HTTPRoute, parent gatewayv1.ParentReference, - namespaceLabels map[string]string) ([]gatewaymodel.RouteAttachment, error) { + namespaceLabels map[string]string, originTLS ...bool) ([]gatewaymodel.RouteAttachment, error) { key, recognized := GatewayParentKey(route.Namespace, parent) if !recognized || key != client.ObjectKeyFromObject(gateway) || gateway.DeletionTimestamp != nil { return nil, &AttachmentError{Reason: gatewayv1.RouteReasonNoMatchingParent, Message: "parent does not identify an available Gateway"} @@ -109,7 +116,7 @@ func ResolveAttachments(gateway *gatewayv1.Gateway, route *gatewayv1.HTTPRoute, continue } selected = true - if err := ValidateListener(listener); err != nil { + if err := ValidateListener(listener, originTLS...); err != nil { continue } from := gatewayv1.NamespacesFromSame @@ -179,11 +186,20 @@ func ValidateHTTPRoute(route *gatewayv1.HTTPRoute) error { // ResolveBackend authorizes a reference before reading its target and uses the // same source-service field index as the existing hub networking controllers. -func ResolveBackend(ctx context.Context, reader client.Reader, namespace string, ref gatewayv1.HTTPBackendRef) (gatewaymodel.Backend, error) { - return resolveBackend(ctx, reader, namespace, ref, true) +func ResolveBackend(ctx context.Context, reader client.Reader, namespace string, ref gatewayv1.HTTPBackendRef, originTLS ...bool) (gatewaymodel.Backend, error) { + return resolveBackend(ctx, reader, namespace, ref, true, originTLS...) +} + +// ResolveBackendUnindexed reads complete API inventory for authorization/projection. +func ResolveBackendUnindexed(ctx context.Context, reader client.Reader, namespace string, ref gatewayv1.HTTPBackendRef, originTLS ...bool) (gatewaymodel.Backend, error) { + return resolveBackend(ctx, reader, namespace, ref, false, originTLS...) } -func resolveBackend(ctx context.Context, reader client.Reader, namespace string, ref gatewayv1.HTTPBackendRef, indexed bool) (gatewaymodel.Backend, error) { +func resolveBackend(ctx context.Context, reader client.Reader, namespace string, ref gatewayv1.HTTPBackendRef, indexed bool, originTLS ...bool) (gatewaymodel.Backend, error) { + secure := len(originTLS) != 0 && originTLS[0] + if secure { + indexed = false + } if err := AuthorizeBackendReference(namespace, ref); err != nil { return gatewaymodel.Backend{}, err } @@ -203,7 +219,7 @@ func resolveBackend(ctx context.Context, reader client.Reader, namespace string, if err := reader.List(ctx, &exports, options...); err != nil { return gatewaymodel.Backend{}, fmt.Errorf("list backend internal exports: %w", err) } - backend, err := Resolve(namespace, ref, &service, exports.Items) + backend, err := Resolve(namespace, ref, &service, exports.Items, originTLS...) if err != nil { return gatewaymodel.Backend{}, err } @@ -212,6 +228,9 @@ func resolveBackend(ctx context.Context, reader client.Reader, namespace string, var memberNamespace corev1.Namespace if err := reader.Get(ctx, types.NamespacedName{Name: fmt.Sprintf(hubconfig.HubNamespaceNameFormat, origin.Cluster)}, &memberNamespace); err != nil { if apierrors.IsNotFound(err) { + if secure { + backend.ExcludedOrigins = append(backend.ExcludedOrigins, gatewaymodel.ExcludedOrigin{Cluster: origin.Cluster, Reason: "MemberNamespaceUnavailable"}) + } continue } return gatewaymodel.Backend{}, fmt.Errorf("get exporting member namespace: %w", err) @@ -219,6 +238,8 @@ func resolveBackend(ctx context.Context, reader client.Reader, namespace string, // Namespace withdrawal can precede export garbage collection/aggregation. if memberNamespace.DeletionTimestamp == nil { origins = append(origins, origin) + } else if secure { + backend.ExcludedOrigins = append(backend.ExcludedOrigins, gatewaymodel.ExcludedOrigin{Cluster: origin.Cluster, Reason: "MemberNamespaceDeleting"}) } } backend.Origins = origins @@ -246,20 +267,20 @@ func AuthorizeBackendReference(namespace string, ref gatewayv1.HTTPBackendRef) e // ResolveHTTPRoute builds rule-scoped private intent. An unavailable origin does // not hide invalid references in subsequent rules or produce a partial route. func ResolveHTTPRoute(ctx context.Context, reader client.Reader, route *gatewayv1.HTTPRoute, - attachments []gatewaymodel.RouteAttachment) (gatewaymodel.Route, error) { - return resolveHTTPRoute(ctx, reader, route, attachments, true) + attachments []gatewaymodel.RouteAttachment, originTLS ...bool) (gatewaymodel.Route, error) { + return resolveHTTPRoute(ctx, reader, route, attachments, true, originTLS...) } // ResolveHTTPRouteUnindexed applies the same authorization and backend validation // without cache-only export selectors. Callers requiring current API observations // must supply an uncached reader; all exports are listed and filtered by identity. func ResolveHTTPRouteUnindexed(ctx context.Context, reader client.Reader, route *gatewayv1.HTTPRoute, - attachments []gatewaymodel.RouteAttachment) (gatewaymodel.Route, error) { - return resolveHTTPRoute(ctx, reader, route, attachments, false) + attachments []gatewaymodel.RouteAttachment, originTLS ...bool) (gatewaymodel.Route, error) { + return resolveHTTPRoute(ctx, reader, route, attachments, false, originTLS...) } func resolveHTTPRoute(ctx context.Context, reader client.Reader, route *gatewayv1.HTTPRoute, - attachments []gatewaymodel.RouteAttachment, indexed bool) (gatewaymodel.Route, error) { + attachments []gatewaymodel.RouteAttachment, indexed bool, originTLS ...bool) (gatewaymodel.Route, error) { if err := ValidateHTTPRoute(route); err != nil { return gatewaymodel.Route{}, err } @@ -267,7 +288,7 @@ func resolveHTTPRoute(ctx context.Context, reader client.Reader, route *gatewayv CreationTimestamp: route.CreationTimestamp.Time, Attachments: attachments} var unavailable error for _, rule := range route.Spec.Rules { - backend, err := resolveBackend(ctx, reader, route.Namespace, rule.BackendRefs[0], indexed) + backend, err := resolveBackend(ctx, reader, route.Namespace, rule.BackendRefs[0], indexed, originTLS...) if err != nil { var resolutionErr *ResolutionError if !errors.As(err, &resolutionErr) || !resolutionErr.ReferenceValid { diff --git a/pkg/controllers/hub/httproute/controller.go b/pkg/controllers/hub/httproute/controller.go index 4f494d12..b69c3fb1 100644 --- a/pkg/controllers/hub/httproute/controller.go +++ b/pkg/controllers/hub/httproute/controller.go @@ -22,6 +22,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/handler" "sigs.k8s.io/controller-runtime/pkg/reconcile" gatewayv1 "sigs.k8s.io/gateway-api/apis/v1" + gatewayv1alpha3 "sigs.k8s.io/gateway-api/apis/v1alpha3" gatewayv1beta1 "sigs.k8s.io/gateway-api/apis/v1beta1" fleetnetv1alpha1 "go.goms.io/fleet-networking/api/v1alpha1" @@ -31,7 +32,8 @@ import ( // Reconciler owns only the AFD controller's HTTPRoute parent statuses. type Reconciler struct { - Client client.Client + Client client.Client + EnableOriginTLS bool } // +kubebuilder:rbac:groups=gateway.networking.k8s.io,resources=httproutes;referencegrants,verbs=get;list;watch @@ -111,7 +113,7 @@ func (r *Reconciler) resolve(ctx context.Context, route *gatewayv1.HTTPRoute, ga if err := r.Client.Get(ctx, client.ObjectKey{Name: route.Namespace}, &namespace); err != nil { return err } - _, err := gatewayresolver.ResolveAttachments(gateway, route, status.ParentRef, namespace.Labels) + _, err := gatewayresolver.ResolveAttachments(gateway, route, status.ParentRef, namespace.Labels, r.EnableOriginTLS) if err != nil { var attachmentErr *gatewayresolver.AttachmentError if !errors.As(err, &attachmentErr) { @@ -128,7 +130,8 @@ func (r *Reconciler) resolve(ctx context.Context, route *gatewayv1.HTTPRoute, ga } } // Reference validity is independent of supported routing intent and origin readiness. - resolved, err := r.resolveReferences(ctx, route) + secure := r.EnableOriginTLS && len(gateway.Spec.Listeners) == 1 && gateway.Spec.Listeners[0].Protocol == gatewayv1.HTTPSProtocolType + resolved, err := r.resolveReferences(ctx, route, secure) if err != nil { return err } @@ -137,7 +140,7 @@ func (r *Reconciler) resolve(ctx context.Context, route *gatewayv1.HTTPRoute, ga return nil } -func (r *Reconciler) resolveReferences(ctx context.Context, route *gatewayv1.HTTPRoute) (metav1.Condition, error) { +func (r *Reconciler) resolveReferences(ctx context.Context, route *gatewayv1.HTTPRoute, originTLS ...bool) (metav1.Condition, error) { resolved := metav1.Condition{Type: string(gatewayv1.RouteConditionResolvedRefs), Status: metav1.ConditionTrue, Reason: string(gatewayv1.RouteReasonResolvedRefs), Message: "Backend references are valid; AFD programming and private traffic are verified independently", ObservedGeneration: route.Generation} for _, rule := range route.Spec.Rules { @@ -148,7 +151,7 @@ func (r *Reconciler) resolveReferences(ctx context.Context, route *gatewayv1.HTT } } for _, backend := range rule.BackendRefs { - _, err := gatewayresolver.ResolveBackend(ctx, r.Client, route.Namespace, backend) + _, err := gatewayresolver.ResolveBackend(ctx, r.Client, route.Namespace, backend, originTLS...) if err == nil { continue } @@ -171,12 +174,16 @@ func (r *Reconciler) resolveReferences(ctx context.Context, route *gatewayv1.HTT // SetupWithManager watches all dependencies that can authorize or revoke intent. func (r *Reconciler) SetupWithManager(mgr ctrl.Manager) error { - return ctrl.NewControllerManagedBy(mgr).For(&gatewayv1.HTTPRoute{}). + builder := ctrl.NewControllerManagedBy(mgr).For(&gatewayv1.HTTPRoute{}). Watches(&gatewayv1.Gateway{}, handler.EnqueueRequestsFromMapFunc(r.routesForDependency)). Watches(&fleetnetv1alpha1.ServiceImport{}, handler.EnqueueRequestsFromMapFunc(r.routesForDependency)). Watches(&fleetnetv1alpha1.InternalServiceExport{}, handler.EnqueueRequestsFromMapFunc(r.routesForDependency)). Watches(&gatewayv1beta1.ReferenceGrant{}, handler.EnqueueRequestsFromMapFunc(r.routesForDependency)). - Watches(&corev1.Namespace{}, handler.EnqueueRequestsFromMapFunc(r.routesForDependency)).Complete(r) + Watches(&corev1.Namespace{}, handler.EnqueueRequestsFromMapFunc(r.routesForDependency)) + if r.EnableOriginTLS { + builder = builder.Watches(&gatewayv1alpha3.BackendTLSPolicy{}, handler.EnqueueRequestsFromMapFunc(r.routesForDependency)) + } + return builder.Complete(r) } func (r *Reconciler) routesForDependency(ctx context.Context, object client.Object) []reconcile.Request { diff --git a/pkg/controllers/member/serviceexport/controller.go b/pkg/controllers/member/serviceexport/controller.go index 1695ddd1..426eaa7b 100644 --- a/pkg/controllers/member/serviceexport/controller.go +++ b/pkg/controllers/member/serviceexport/controller.go @@ -29,6 +29,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" "sigs.k8s.io/controller-runtime/pkg/handler" + gatewayv1alpha3 "sigs.k8s.io/gateway-api/apis/v1alpha3" "go.goms.io/fleet/pkg/utils/controller" @@ -37,6 +38,7 @@ import ( "go.goms.io/fleet-networking/pkg/common/condition" "go.goms.io/fleet-networking/pkg/common/metrics" "go.goms.io/fleet-networking/pkg/common/objectmeta" + "go.goms.io/fleet-networking/pkg/common/origintls" ) const ( @@ -52,12 +54,14 @@ const ( // ControllerName is the name of the Reconciler. ControllerName = "serviceexport-controller" + serviceKind = "Service" ) // Reconciler reconciles the export of a Service. type Reconciler struct { MemberClusterID string MemberClient client.Client + MemberAPIReader client.Reader HubClient client.Client // The namespace reserved for the current member cluster in the hub cluster. HubNamespace string @@ -67,6 +71,7 @@ type Reconciler struct { AzurePublicIPAddressClient publicipaddressclient.Interface EnableTrafficManagerFeature bool + EnableOriginTLS bool EnablePrivateLinkOriginDiscovery bool AzureLoadBalancerClient OriginLoadBalancerClient @@ -80,6 +85,8 @@ type Reconciler struct { //+kubebuilder:rbac:groups="",resources=services,verbs=get;list;watch;create;update;patch;delete //+kubebuilder:rbac:groups="",resources=events,verbs=create;patch //+kubebuilder:rbac:groups=events.k8s.io,resources=events,verbs=create;patch +//+kubebuilder:rbac:groups=gateway.networking.k8s.io,resources=backendtlspolicies,verbs=get;list;watch +//+kubebuilder:rbac:groups=apiextensions.k8s.io,resources=customresourcedefinitions,resourceNames=backendtlspolicies.gateway.networking.k8s.io;internalserviceexports.networking.fleet.azure.com,verbs=get // Reconcile exports a Service. func (r *Reconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { @@ -272,6 +279,11 @@ func (r *Reconciler) exportService(ctx context.Context, svcExport *fleetnetv1bet svcExportPorts := extractServicePorts(svc) var privateOrigin *fleetnetv1alpha1.PrivateLinkOrigin var discoveryErr error + var tlsIntent *fleetnetv1alpha1.OriginTLS + var tlsErr error + if r.EnableOriginTLS { + tlsIntent, tlsErr = r.resolveOriginTLS(ctx, svc) + } if r.EnablePrivateLinkOriginDiscovery { privateOrigin, discoveryErr = r.discoverPrivateLinkOrigin(ctx, svc) } @@ -307,6 +319,9 @@ func (r *Reconciler) exportService(ctx context.Context, svcExport *fleetnetv1bet internalSvcExport.Spec.ServiceReference.UpdateFromMetaObject(svc.ObjectMeta, metav1.NewTime(exportedSince)) // Replace even with nil/failed discovery so old private readiness cannot survive drift or disablement. internalSvcExport.Spec.PrivateLinkOrigin = privateOrigin + if err := origintls.RefreshObservation(&internalSvcExport, tlsIntent); err != nil { + return err + } if r.EnablePrivateLinkOriginDiscovery { internalSvcExport.Spec.Type = svc.Spec.Type @@ -327,7 +342,7 @@ func (r *Reconciler) exportService(ctx context.Context, svcExport *fleetnetv1bet statusErr := &apierrors.StatusError{} ok := errors.As(err, &statusErr) switch { - case apierrors.IsAlreadyExists(err) && ok && statusErr.Status().Details.Kind == "Service": + case apierrors.IsAlreadyExists(err) && ok && statusErr.Status().Details.Kind == serviceKind: // An export with the same key but different UID already exists; unexport the Service first, and // requeue a new attempt to export the Service. // Additional checks are performed here as two forms of AlreadyExists error can be returned in the CreateOrUpdate @@ -352,6 +367,10 @@ func (r *Reconciler) exportService(ctx context.Context, svcExport *fleetnetv1bet "op", createOrUpdateOp) return ctrl.Result{}, err } + if tlsErr != nil { + klog.ErrorS(tlsErr, "Origin TLS resolution failed; baseline service export was preserved", "service", svcRef) + return ctrl.Result{}, errors.Join(tlsErr, discoveryErr) + } if discoveryErr != nil { // Publish the baseline export and failed discovery before returning a retryable Azure error. klog.ErrorS(discoveryErr, "Private origin discovery failed; baseline service export was preserved", "service", svcRef) @@ -364,7 +383,11 @@ func (r *Reconciler) exportService(ctx context.Context, svcExport *fleetnetv1bet if !privateOrigin.Ready && r.Recorder != nil { r.Recorder.Eventf(svcExport, nil, corev1.EventTypeWarning, privateOrigin.Reason, "DiscoverPrivateOrigin", "Private ingress origin is not ready: %s", privateOrigin.Reason) } - return ctrl.Result{RequeueAfter: wait.Jitter(privateOriginRediscoveryInterval, 0.2)}, nil + interval := privateOriginRediscoveryInterval + if r.EnableOriginTLS { + interval = origintls.Heartbeat + } + return ctrl.Result{RequeueAfter: wait.Jitter(interval, 0.2)}, nil } return ctrl.Result{}, nil } @@ -462,12 +485,18 @@ func (r *Reconciler) lookupPublicIPResourceIDByLoadBalancerIP(ctx context.Contex // SetupWithManager builds a controller with Reconciler and sets it up with a controller manager. func (r *Reconciler) SetupWithManager(mgr ctrl.Manager) error { - return ctrl.NewControllerManagedBy(mgr). + builder := ctrl.NewControllerManagedBy(mgr). // The ServiceExport controller watches over ServiceExport objects. For(&fleetnetv1beta1.ServiceExport{}). // The ServiceExport controller watches over Service objects. - Watches(&corev1.Service{}, &handler.EnqueueRequestForObject{}). - Complete(r) + Watches(&corev1.Service{}, &handler.EnqueueRequestForObject{}) + if r.EnableOriginTLS { + if !r.EnablePrivateLinkOriginDiscovery || r.MemberAPIReader == nil { + return fmt.Errorf("origin TLS requires private origin discovery and uncached policy reads") + } + builder = builder.Watches(&gatewayv1alpha3.BackendTLSPolicy{}, handler.EnqueueRequestsFromMapFunc(r.exportsForTLSPolicy)) + } + return builder.Complete(r) } // unexportService unexports a Service, specifically, it deletes the corresponding InternalServiceExport from the diff --git a/pkg/controllers/member/serviceexport/origintls.go b/pkg/controllers/member/serviceexport/origintls.go new file mode 100644 index 00000000..006e7c20 --- /dev/null +++ b/pkg/controllers/member/serviceexport/origintls.go @@ -0,0 +1,90 @@ +/* +Copyright (c) Microsoft Corporation. +Licensed under the MIT license. +*/ + +package serviceexport + +import ( + "context" + "fmt" + "time" + + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/reconcile" + gatewayv1alpha3 "sigs.k8s.io/gateway-api/apis/v1alpha3" + + fleetnetv1alpha1 "go.goms.io/fleet-networking/api/v1alpha1" + "go.goms.io/fleet-networking/pkg/common/origintls" +) + +const originTLSReadyReason = "Ready" + +func (r *Reconciler) resolveOriginTLS(ctx context.Context, service *corev1.Service) (*fleetnetv1alpha1.OriginTLS, error) { + intent := &fleetnetv1alpha1.OriginTLS{ServiceUID: string(service.UID), Reason: "PolicyMissing", ObservedAt: metav1.NewTime(time.Now().UTC())} + reader := r.MemberAPIReader + if reader == nil { + return nil, fmt.Errorf("origin TLS requires an uncached member API reader") + } + var list gatewayv1alpha3.BackendTLSPolicyList + if err := reader.List(ctx, &list, client.InNamespace(service.Namespace)); err != nil { + intent.Reason = "PolicyReadFailed" + return intent, fmt.Errorf("read member TLS policies: %w", err) + } + var matches []*gatewayv1alpha3.BackendTLSPolicy + for i := range list.Items { + policy := &list.Items[i] + for _, target := range policy.Spec.TargetRefs { + if target.Group == "" && target.Kind == serviceKind && string(target.Name) == service.Name { + matches = append(matches, policy) + break + } + } + } + if len(matches) > 1 { + intent.Reason = "DuplicatePolicies" + } + if len(matches) != 1 { + for _, policy := range matches { + r.recordTLSPolicyFailure(policy, intent.Reason) + } + return intent, nil + } + policy := matches[0] + if policy.Annotations[origintls.ExportAnnotation] != "true" { + intent.Reason = "PolicyNotExported" + return intent, nil + } + intent.Policy = &fleetnetv1alpha1.OriginTLSPolicyReference{ + Namespace: policy.Namespace, Name: policy.Name, UID: string(policy.UID), Generation: policy.Generation, + ResourceVersion: policy.ResourceVersion, ExportToFleet: policy.Annotations[origintls.ExportAnnotation], + } + intent.Reason = "UnsupportedPolicy" + if err := origintls.Validate(policy); err != nil { + r.recordTLSPolicyFailure(policy, intent.Reason) + return intent, nil //nolint:nilerr // Publish invalid customer intent and its Event; only API failures need error retries. + } + intent.Ready, intent.Reason = true, originTLSReadyReason + intent.Hostname, intent.Trust = string(policy.Spec.Validation.Hostname), "System" + return intent, nil +} + +func (r *Reconciler) recordTLSPolicyFailure(policy *gatewayv1alpha3.BackendTLSPolicy, reason string) { + if r.Recorder != nil && policy.Annotations[origintls.ExportAnnotation] == "true" { + r.Recorder.Eventf(policy, nil, corev1.EventTypeWarning, reason, "ResolveOriginTLS", + "Fleet origin TLS intent unavailable: %s; baseline MCS export is preserved", reason) + } +} + +func (r *Reconciler) exportsForTLSPolicy(_ context.Context, object client.Object) []reconcile.Request { + policy := object.(*gatewayv1alpha3.BackendTLSPolicy) + var requests []reconcile.Request + for _, target := range policy.Spec.TargetRefs { + if target.Group == "" && target.Kind == serviceKind { + requests = append(requests, reconcile.Request{NamespacedName: client.ObjectKey{Namespace: policy.Namespace, Name: string(target.Name)}}) + } + } + return requests +} diff --git a/pkg/controllers/member/serviceexport/origintls_test.go b/pkg/controllers/member/serviceexport/origintls_test.go new file mode 100644 index 00000000..2bcf525a --- /dev/null +++ b/pkg/controllers/member/serviceexport/origintls_test.go @@ -0,0 +1,196 @@ +/* +Copyright (c) Microsoft Corporation. +Licensed under the MIT license. +*/ + +package serviceexport + +import ( + "context" + "errors" + "reflect" + "testing" + "time" + + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/client-go/tools/events" + "k8s.io/utils/ptr" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + "sigs.k8s.io/controller-runtime/pkg/client/interceptor" + gatewayv1 "sigs.k8s.io/gateway-api/apis/v1" + gatewayv1alpha2 "sigs.k8s.io/gateway-api/apis/v1alpha2" + gatewayv1alpha3 "sigs.k8s.io/gateway-api/apis/v1alpha3" + + fleetnetv1alpha1 "go.goms.io/fleet-networking/api/v1alpha1" + fleetnetv1beta1 "go.goms.io/fleet-networking/api/v1beta1" + "go.goms.io/fleet-networking/pkg/common/origintls" +) + +func memberTLSPolicy() *gatewayv1alpha3.BackendTLSPolicy { + return &gatewayv1alpha3.BackendTLSPolicy{ + ObjectMeta: metav1.ObjectMeta{Namespace: "store", Name: "api-tls", UID: "policy-uid", Generation: 1, + Annotations: map[string]string{origintls.ExportAnnotation: "true"}}, + Spec: gatewayv1alpha3.BackendTLSPolicySpec{ + TargetRefs: []gatewayv1alpha2.LocalPolicyTargetReferenceWithSectionName{{ + LocalPolicyTargetReference: gatewayv1alpha2.LocalPolicyTargetReference{Group: "", Kind: "Service", Name: "api"}, + }}, + Validation: gatewayv1alpha3.BackendTLSPolicyValidation{Hostname: "origin.example.com", + WellKnownCACertificates: ptr.To(gatewayv1alpha3.WellKnownCACertificatesSystem)}, + }, + } +} + +func memberTLSClient(t *testing.T, objects ...client.Object) client.WithWatch { + t.Helper() + scheme := runtime.NewScheme() + for _, install := range []func(*runtime.Scheme) error{corev1.AddToScheme, gatewayv1alpha3.Install, fleetnetv1alpha1.AddToScheme, fleetnetv1beta1.AddToScheme} { + if err := install(scheme); err != nil { + t.Fatal(err) + } + } + return fake.NewClientBuilder().WithScheme(scheme).WithObjects(objects...).Build() +} + +func TestResolveOriginTLSOptInAndSinglePolicy(t *testing.T) { + tests := []struct { + name string + change func(*gatewayv1alpha3.BackendTLSPolicy) []client.Object + reason string + }{ + {"valid", nil, originTLSReadyReason}, + {"unmarked belongs to another implementation", func(p *gatewayv1alpha3.BackendTLSPolicy) []client.Object { + delete(p.Annotations, origintls.ExportAnnotation) + return nil + }, "PolicyNotExported"}, + {"exact annotation value", func(p *gatewayv1alpha3.BackendTLSPolicy) []client.Object { + p.Annotations[origintls.ExportAnnotation] = "True" + return nil + }, "PolicyNotExported"}, + {"unmarked duplicate counts", func(p *gatewayv1alpha3.BackendTLSPolicy) []client.Object { + other := p.DeepCopy() + other.Name = "istio" + other.Annotations = nil + return []client.Object{other} + }, "DuplicatePolicies"}, + {"identical duplicate counts", func(p *gatewayv1alpha3.BackendTLSPolicy) []client.Object { + other := p.DeepCopy() + other.Name = "duplicate" + return []client.Object{other} + }, "DuplicatePolicies"}, + {"unrelated policy ignored", func(p *gatewayv1alpha3.BackendTLSPolicy) []client.Object { + other := p.DeepCopy() + other.Name = "unrelated-policy" + other.Spec.TargetRefs[0].Name = "unrelated-service" + return []client.Object{other} + }, originTLSReadyReason}, + {"wildcard rejected", func(p *gatewayv1alpha3.BackendTLSPolicy) []client.Object { + p.Spec.Validation.Hostname = "*.example.com" + return nil + }, "UnsupportedPolicy"}, + {"IP rejected", func(p *gatewayv1alpha3.BackendTLSPolicy) []client.Object { + p.Spec.Validation.Hostname = "10.0.0.1" + return nil + }, "UnsupportedPolicy"}, + {"custom CA rejected", func(p *gatewayv1alpha3.BackendTLSPolicy) []client.Object { + p.Spec.Validation.CACertificateRefs = []gatewayv1.LocalObjectReference{{Kind: "ConfigMap", Name: "ca"}} + return nil + }, "UnsupportedPolicy"}, + {"section rejected", func(p *gatewayv1alpha3.BackendTLSPolicy) []client.Object { + p.Spec.TargetRefs[0].SectionName = ptr.To(gatewayv1.SectionName("https")) + return nil + }, "UnsupportedPolicy"}, + {"multiple targets rejected", func(p *gatewayv1alpha3.BackendTLSPolicy) []client.Object { + p.Spec.TargetRefs = append(p.Spec.TargetRefs, p.Spec.TargetRefs[0]) + return nil + }, "UnsupportedPolicy"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + policy := memberTLSPolicy() + objects := []client.Object{} + if tt.change != nil { + objects = tt.change(policy) + } + objects = append(objects, policy) + c := memberTLSClient(t, objects...) + if err := c.Get(context.Background(), client.ObjectKeyFromObject(policy), policy); err != nil { + t.Fatal(err) + } + before := policy.DeepCopy() + service, _, _ := privateOriginFixture() + r := Reconciler{MemberAPIReader: c, Recorder: events.NewFakeRecorder(10)} + got, err := r.resolveOriginTLS(context.Background(), service) + if err != nil || got.Reason != tt.reason || got.Ready != (tt.reason == originTLSReadyReason) { + t.Fatalf("intent=%+v error=%v want reason=%s", got, err, tt.reason) + } + var after gatewayv1alpha3.BackendTLSPolicy + if err := c.Get(context.Background(), client.ObjectKeyFromObject(policy), &after); err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(before.Spec, after.Spec) || !reflect.DeepEqual(before.Status, after.Status) || !reflect.DeepEqual(before.Annotations, after.Annotations) { + t.Fatal("member policy was mutated") + } + if got.Ready && (got.Hostname != "origin.example.com" || got.Trust != "System" || got.ServiceUID != string(service.UID) || got.Policy.ResourceVersion == "") { + t.Fatalf("incomplete non-secret provenance: %+v", got) + } + }) + } +} + +func TestOriginTLSMetadataRevocationAndRetargeting(t *testing.T) { + ctx := context.Background() + policy := memberTLSPolicy() + c := memberTLSClient(t, policy) + r := Reconciler{MemberAPIReader: c} + service, _, _ := privateOriginFixture() + before, err := r.resolveOriginTLS(ctx, service) + if err != nil || !before.Ready { + t.Fatalf("initial intent: %+v %v", before, err) + } + if err := c.Get(ctx, client.ObjectKeyFromObject(policy), policy); err != nil { + t.Fatal(err) + } + generation := policy.Generation + delete(policy.Annotations, origintls.ExportAnnotation) + if err := c.Update(ctx, policy); err != nil { + t.Fatal(err) + } + after, err := r.resolveOriginTLS(ctx, service) + if err != nil || after.Ready || after.Reason != "PolicyNotExported" || policy.Generation != generation { + t.Fatalf("metadata-only opt-out survived: %+v %v", after, err) + } + policy.Spec.TargetRefs[0].Name = "other" + if got := r.exportsForTLSPolicy(ctx, policy); len(got) != 1 || got[0].Name != "other" { + t.Fatalf("retarget dependency not enqueued: %v", got) + } + // controller-runtime maps both old and new objects on update. + old := memberTLSPolicy() + if got := r.exportsForTLSPolicy(ctx, old); len(got) != 1 || got[0].Name != "api" { + t.Fatal("old target cannot be revoked") + } +} + +func TestExportOriginTLSReadFailurePreservesBaseline(t *testing.T) { + ctx := context.Background() + service, lbs, plss := privateOriginFixture() + export := &fleetnetv1beta1.ServiceExport{ObjectMeta: metav1.ObjectMeta{Namespace: service.Namespace, Name: service.Name}} + member, hub := memberTLSClient(t, export), memberTLSClient(t) + wantErr := errors.New("policy read unavailable") + reader := interceptor.NewClient(member, interceptor.Funcs{List: func(context.Context, client.WithWatch, client.ObjectList, ...client.ListOption) error { return wantErr }}) + r := Reconciler{MemberClient: member, MemberAPIReader: reader, HubClient: hub, + HubNamespace: "fleet-member-test", MemberClusterID: "test", EnableOriginTLS: true, EnablePrivateLinkOriginDiscovery: true, + ResourceGroupName: "node-rg", AzureLoadBalancerClient: lbs, AzurePrivateLinkServiceClient: plss} + if _, err := r.exportService(ctx, export, service, time.Now(), 1); !errors.Is(err, wantErr) { + t.Fatalf("read error lost: %v", err) + } + var got fleetnetv1alpha1.InternalServiceExport + if err := hub.Get(ctx, client.ObjectKey{Namespace: r.HubNamespace, Name: formatInternalServiceExportName(export)}, &got); err != nil { + t.Fatal(err) + } + if len(got.Spec.Ports) != len(service.Spec.Ports) || got.Spec.OriginTLS == nil || got.Spec.OriginTLS.Ready || got.Spec.OriginTLS.Reason != "PolicyReadFailed" || !got.Spec.PrivateLinkOrigin.Ready { + t.Fatalf("baseline export lost or failed TLS hidden: %+v", got.Spec) + } +} diff --git a/pkg/providers/azure/frontdoor/backend.go b/pkg/providers/azure/frontdoor/backend.go index dcfe5b0c..fbe6e120 100644 --- a/pkg/providers/azure/frontdoor/backend.go +++ b/pkg/providers/azure/frontdoor/backend.go @@ -51,6 +51,7 @@ type Origin struct { ServiceUID string HostName string HTTPPort int32 + HTTPSPort int32 Weight int64 Priority int32 OriginHostHeader string @@ -144,14 +145,20 @@ func PlanBackends(model gatewaymodel.GlobalGateway) (BackendPlan, error) { } for _, member := range backend.Origins { target := PrivateLinkTarget{ResourceID: member.PrivateLinkResourceID, Location: member.PrivateLinkLocation} - group.Origins = append(group.Origins, Origin{ + origin := Origin{ // Replacements change identity; weight-only updates keep the same resource. Name: resourceName("fleet-origin", group.Name, member.Cluster, member.ServiceUID, target.ResourceID, target.Location, member.Endpoint), Cluster: member.Cluster, ServiceUID: member.ServiceUID, HostName: member.Endpoint, HTTPPort: key.Port, Weight: member.Weight, Priority: 1, OriginHostHeader: backend.OriginHostHeader, EnforceCertificateNameCheck: true, PrivateLink: target, - }) + } + if backend.TLSHostname != "" { + origin.Name = resourceName("fleet-origin", origin.Name, "https", backend.TLSHostname) + origin.HostName = backend.TLSHostname + origin.HTTPSPort, origin.HTTPPort = key.Port, 0 + } + group.Origins = append(group.Origins, origin) } plan.OriginGroups = append(plan.OriginGroups, group) } @@ -173,11 +180,11 @@ func PlanBackends(model gatewaymodel.GlobalGateway) (BackendPlan, error) { for _, origin := range group.Origins { target, found := targets[origin.PrivateLink] if !found { - target = &PrivateLinkPlan{Target: origin.PrivateLink, HTTPPort: origin.HTTPPort} + target = &PrivateLinkPlan{Target: origin.PrivateLink, HTTPPort: origin.port()} targets[origin.PrivateLink] = target - } else if target.HTTPPort != origin.HTTPPort { + } else if target.HTTPPort != origin.port() { return BackendPlan{}, &PrivateLinkPortConflictError{ - Target: origin.PrivateLink, FirstPort: target.HTTPPort, SecondPort: origin.HTTPPort, + Target: origin.PrivateLink, FirstPort: target.HTTPPort, SecondPort: origin.port(), } } target.Origins = append(target.Origins, OriginReference{OriginGroup: group.Name, Origin: origin.Name}) @@ -203,6 +210,13 @@ func PlanBackends(model gatewaymodel.GlobalGateway) (BackendPlan, error) { return plan, nil } +func (origin Origin) port() int32 { + if origin.HTTPSPort != 0 { + return origin.HTTPSPort + } + return origin.HTTPPort +} + func resourceName(prefix string, parts ...string) string { hash := sha256.New() for _, part := range parts { diff --git a/pkg/providers/azure/frontdoor/backend_provision.go b/pkg/providers/azure/frontdoor/backend_provision.go index 9ba84bc0..6f95db32 100644 --- a/pkg/providers/azure/frontdoor/backend_provision.go +++ b/pkg/providers/azure/frontdoor/backend_provision.go @@ -312,7 +312,7 @@ func (p *BackendProvisioner) ensureOrigin(ctx context.Context, roots RootRequest if !matchesPrivateOrigin(desired, actual.Properties) { properties := request.Parameters.Properties parameters := armcdn.AFDOriginUpdateParameters{Properties: &armcdn.AFDOriginUpdatePropertiesParameters{ - HostName: properties.HostName, HTTPPort: properties.HTTPPort, Weight: properties.Weight, + HostName: properties.HostName, HTTPPort: properties.HTTPPort, HTTPSPort: properties.HTTPSPort, Weight: properties.Weight, Priority: properties.Priority, EnabledState: properties.EnabledState, EnforceCertificateNameCheck: properties.EnforceCertificateNameCheck, SharedPrivateLinkResource: properties.SharedPrivateLinkResource, }} diff --git a/pkg/providers/azure/frontdoor/graph.go b/pkg/providers/azure/frontdoor/graph.go index 2a11a5ca..62c6fa2d 100644 --- a/pkg/providers/azure/frontdoor/graph.go +++ b/pkg/providers/azure/frontdoor/graph.go @@ -104,6 +104,10 @@ func BuildHTTPPreviewRequests(scope ResourceScope, owner GatewayOwner, return HTTPPreviewRequests{}, fmt.Errorf("AFD HTTP graph requires one nonempty logical backend") } group := backends.OriginGroups[0] + protocol, forwarding := armcdn.AFDEndpointProtocolsHTTP, armcdn.ForwardingProtocolHTTPOnly + if model.Listeners[0].Protocol == gatewaymodel.ProtocolHTTPS { + protocol, forwarding = armcdn.AFDEndpointProtocolsHTTPS, armcdn.ForwardingProtocolHTTPSOnly + } return HTTPPreviewRequests{ Roots: roots, Backends: backends, RouteName: resourceName("fleet-route", owner.UID), // Omit cache, origin path, rule sets and custom domains: preserve path/query/Host. @@ -112,10 +116,9 @@ func BuildHTTPPreviewRequests(scope ResourceScope, owner GatewayOwner, OriginGroup: &armcdn.ResourceReference{ ID: ptr.To(roots.ProfileID + "/originGroups/" + group.Name), }, - PatternsToMatch: []*string{ptr.To(httpPreviewPattern)}, - SupportedProtocols: []*armcdn.AFDEndpointProtocols{ptr.To(armcdn.AFDEndpointProtocolsHTTP)}, - // HTTPS origin forwarding and certificate validation are deferred to the HTTPS follow-up. - ForwardingProtocol: ptr.To(armcdn.ForwardingProtocolHTTPOnly), + PatternsToMatch: []*string{ptr.To(httpPreviewPattern)}, + SupportedProtocols: []*armcdn.AFDEndpointProtocols{ptr.To(protocol)}, + ForwardingProtocol: ptr.To(forwarding), HTTPSRedirect: ptr.To(armcdn.HTTPSRedirectDisabled), LinkToDefaultDomain: ptr.To(armcdn.LinkToDefaultDomainEnabled), }}, diff --git a/pkg/providers/azure/frontdoor/http_provision.go b/pkg/providers/azure/frontdoor/http_provision.go index 587ee23a..4166f802 100644 --- a/pkg/providers/azure/frontdoor/http_provision.go +++ b/pkg/providers/azure/frontdoor/http_provision.go @@ -59,7 +59,7 @@ func graphMismatch(format string, args ...interface{}) error { // Sequential ARM reads do not exclude concurrent writers; the owned profile must // be exclusively controller-managed. func (p *RouteProvisioner) ReconcileHTTPPreview(ctx context.Context, owner GatewayOwner, - model gatewaymodel.GlobalGateway) (HTTPPreviewProvisioningResult, error) { + model gatewaymodel.GlobalGateway) (result HTTPPreviewProvisioningResult, reconcileErr error) { if err := ctx.Err(); err != nil { return HTTPPreviewProvisioningResult{}, err } @@ -72,6 +72,7 @@ func (p *RouteProvisioner) ReconcileHTTPPreview(ctx context.Context, owner Gatew } ctx, cancel := context.WithTimeout(ctx, 30*time.Second) defer cancel() + defer p.suspendUnverifiedTLS(ctx, owner, model.Listeners[0].Protocol == gatewaymodel.ProtocolHTTPS, &result, &reconcileErr) _, endpoint, found, err := p.backends.observeRoots(ctx, owner, graph.Roots) if err != nil { return HTTPPreviewProvisioningResult{}, err @@ -158,6 +159,16 @@ func (p *RouteProvisioner) ReconcileHTTPPreview(ctx context.Context, owner Gatew EndpointHostName: *endpoint.Properties.HostName}, nil } +func (p *RouteProvisioner) suspendUnverifiedTLS(ctx context.Context, owner GatewayOwner, secure bool, + result *HTTPPreviewProvisioningResult, reconcileErr *error) { + if !secure || *reconcileErr == nil { + return + } + suspension, err := p.SuspendEndpoint(ctx, owner) + *result = HTTPPreviewProvisioningResult{State: HTTPPreviewSuspending, Suspension: suspension, Diagnostic: "TLS isolation/configuration could not be verified"} + *reconcileErr = errors.Join(*reconcileErr, err) +} + func httpInventoryProgress(ctx context.Context, err error) (HTTPPreviewProvisioningResult, error) { if errors.Is(err, errInventoryPending) { return HTTPPreviewProvisioningResult{State: HTTPPreviewPending, Diagnostic: err.Error()}, ctx.Err() @@ -277,6 +288,12 @@ func (p *RouteProvisioner) enableHTTPRoute(ctx context.Context, graph HTTPPrevie func (p *RouteProvisioner) reconcileOriginTopology(ctx context.Context, owner GatewayOwner, model gatewaymodel.GlobalGateway, graph HTTPPreviewRequests, state armcdn.EnabledState, change *originTopologyChange) (HTTPPreviewProvisioningResult, error) { + if model.Listeners[0].Protocol == gatewaymodel.ProtocolHTTPS && len(change.stale) != 0 { + if err := p.pruneStaleOriginUnderState(ctx, owner, graph, change.stale, state); err != nil { + return HTTPPreviewProvisioningResult{}, err + } + return HTTPPreviewProvisioningResult{State: HTTPPreviewPending, Diagnostic: "TLS member isolation pending observed origin absence; " + change.Error()}, ctx.Err() + } if len(change.missing) != 0 { _, endpoint, found, err := p.backends.observeRoots(ctx, owner, graph.Roots) if err != nil { diff --git a/pkg/providers/azure/frontdoor/https_test.go b/pkg/providers/azure/frontdoor/https_test.go new file mode 100644 index 00000000..0dc77238 --- /dev/null +++ b/pkg/providers/azure/frontdoor/https_test.go @@ -0,0 +1,191 @@ +/* +Copyright (c) Microsoft Corporation. +Licensed under the MIT license. +*/ + +package frontdoor + +import ( + "context" + "net/http" + "reflect" + "strings" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/cdn/armcdn/v2" + "k8s.io/utils/ptr" + + "go.goms.io/fleet-networking/pkg/controllers/hub/gatewaymodel" +) + +func httpsModel() gatewaymodel.GlobalGateway { + model := backendModel() + model.Listeners[0].Protocol, model.Listeners[0].Port, model.Listeners[0].DefaultCertificate = "HTTPS", 443, true + backend := &model.Routes[0].Rules[0].Backends[0] + backend.TLSHostname, backend.TargetUID, backend.TLSProvenance = "origin.example.com", "service-import-uid", "source-digest" + backend.HealthProbe = gatewaymodel.HTTPSHealthProbe() + return model +} + +func httpsFixture(t *testing.T) (backendProvisioningFixture, armcdn.Route) { + t.Helper() + f, _ := routeFixture(t) + snapshot := originSnapshot(t, httpsModel()) + f.snapshot.model, f.snapshot.origins, f.snapshot.first = snapshot.model, snapshot.origins, snapshot.first + var err error + f.graph, err = BuildHTTPPreviewRequests(f.snapshot.scope, f.snapshot.owner, f.snapshot.model) + if err != nil { + t.Fatal(err) + } + observed, err := BuildHTTPPreviewRequests(f.snapshot.scope, f.snapshot.owner, f.snapshot.model) + if err != nil { + t.Fatal(err) + } + f.group.Properties.HealthProbeSettings = observed.Backends.OriginGroups[0].Parameters.Properties.HealthProbeSettings + route := observed.Route + route.ID, route.Name = ptr.To(f.graph.Roots.ProfileID+routeSuffix(f)), ptr.To(f.graph.RouteName) + route.Properties.EndpointName = ptr.To(f.graph.Roots.EndpointName) + route.Properties.ProvisioningState, route.Properties.DeploymentStatus = ptr.To(armcdn.AfdProvisioningStateSucceeded), ptr.To(armcdn.DeploymentStatusSucceeded) + return f, route +} + +func TestHTTPSRequestsEnforceIndependentTLSHops(t *testing.T) { + model := httpsModel() + scope, owner := ownershipFixture() + graph, err := BuildHTTPPreviewRequests(scope, owner, model) + if err != nil { + t.Fatal(err) + } + props := requestProperties(t, graph.Route) + requireJSON(t, props, "supportedProtocols", []string{"Https"}) + requireJSON(t, props, "forwardingProtocol", "HttpsOnly") + requireJSON(t, props, "httpsRedirect", "Disabled") + requireJSON(t, props, "linkToDefaultDomain", "Enabled") + group := graph.Backends.OriginGroups[0] + requireJSON(t, requestProperties(t, group.Parameters), "healthProbeSettings", map[string]any{ + "probeIntervalInSeconds": 30, "probePath": "/", "probeProtocol": "Https", "probeRequestType": "GET", + }) + for _, origin := range group.Origins { + props := requestProperties(t, origin.Parameters) + requireJSON(t, props, "hostName", "origin.example.com") + requireJSON(t, props, "httpsPort", 8080) + requireJSON(t, props, "enforceCertificateNameCheck", true) + if _, exists := props["httpPort"]; exists { + t.Fatal("TLS request includes an HTTP origin port") + } + if _, exists := props["originHostHeader"]; exists { + t.Fatal("Host override must be omitted, not empty") + } + if origin.Parameters.Properties.SharedPrivateLinkResource == nil { + t.Fatal("TLS origin lost private target") + } + } + for _, change := range []func(*gatewaymodel.GlobalGateway){ + func(m *gatewaymodel.GlobalGateway) { + m.Listeners[0].Protocol = "HTTP" + m.Listeners[0].Port = 80 + m.Listeners[0].DefaultCertificate = false + }, + func(m *gatewaymodel.GlobalGateway) { + b := &m.Routes[0].Rules[0].Backends[0] + b.TLSHostname = "" + b.TargetUID = "" + b.TLSProvenance = "" + b.HealthProbe = gatewaymodel.HTTPPreviewHealthProbe() + }, + func(m *gatewaymodel.GlobalGateway) { m.Listeners[0].DefaultCertificate = false }, + func(m *gatewaymodel.GlobalGateway) { m.Routes[0].Rules[0].Backends[0].HealthProbe.Protocol = "HTTP" }, + func(m *gatewaymodel.GlobalGateway) { + m.Routes[0].Rules[0].Backends[0].OriginHostHeader = "override.example.com" + }, + } { + model := httpsModel() + change(&model) + if got, err := BuildHTTPPreviewRequests(scope, owner, model); err == nil || !reflect.DeepEqual(got, HTTPPreviewRequests{}) { + t.Fatalf("mixed/unsupported TLS graph accepted: %+v %v", got, err) + } + } +} + +func TestHTTPSObservationChecksNamePortAndValidation(t *testing.T) { + for _, change := range []func(*armcdn.AFDOrigin){ + func(o *armcdn.AFDOrigin) { o.Properties.HostName = ptr.To("different.example.com") }, + func(o *armcdn.AFDOrigin) { o.Properties.HTTPSPort = ptr.To[int32](8443) }, + func(o *armcdn.AFDOrigin) { o.Properties.EnforceCertificateNameCheck = ptr.To(false) }, + func(o *armcdn.AFDOrigin) { o.Properties.OriginHostHeader = ptr.To("stale.example.com") }, + } { + snapshot := originSnapshot(t, httpsModel()) + origin := snapshot.origins[snapshot.first] + change(&origin) + snapshot.origins[snapshot.first] = origin + observed, err := snapshot.observe() + if err != nil || observed.OriginsConverged { + t.Fatalf("TLS drift accepted: %+v %v", observed, err) + } + } +} + +func TestHTTPSProviderReadbackAndWithdrawal(t *testing.T) { + f, route := httpsFixture(t) + f.endpoint.Properties.EnabledState = ptr.To(armcdn.EnabledStateEnabled) + route.Properties.EnabledState = ptr.To(armcdn.EnabledStateEnabled) + steps := append(httpPreviewReads(f, route), httpPreviewInventory(f, route)...) + provider, calls := disabledGraphClient(t, f, steps, nil) + got, err := provider.ReconcileHTTPPreview(context.Background(), f.snapshot.owner, f.snapshot.model) + if err != nil || got.State != HTTPPreviewProgrammed || got.EndpointHostName == "" || *calls != len(steps) { + t.Fatalf("HTTPS readback not programmed: %+v %v (%d/%d)", got, err, *calls, len(steps)) + } + if err := verifyWithdrawalRoute(f.graph, route); err != nil { + t.Fatalf("TLS route cannot be withdrawn: %v", err) + } +} + +func TestHTTPSIsolationPrunesBeforeAddingAndRequiresAbsence(t *testing.T) { + f, route := httpsFixture(t) + f.endpoint.Properties.EnabledState, route.Properties.EnabledState = ptr.To(armcdn.EnabledStateEnabled), ptr.To(armcdn.EnabledStateEnabled) + inventory := httpPreviewInventory(f, route) + stale := f.originRead(0).body.(armcdn.AFDOrigin) + stale.Name = ptr.To(resourceName("fleet-origin", "excluded-source")) + stale.ID = ptr.To(f.graph.Roots.ProfileID + "/originGroups/" + f.graph.Backends.OriginGroups[0].Name + "/origins/" + *stale.Name) + at := len(f.roots()) + 3 + inventory[at].body.(map[string]interface{})[inventoryValueField] = []interface{}{f.originRead(1).body, stale} + steps := append(httpPreviewReads(f, route), inventory...) + suffix := "/originGroups/" + f.graph.Backends.OriginGroups[0].Name + "/origins/" + *stale.Name + steps = append(steps, backendStep{method: http.MethodGet, suffix: suffix, status: http.StatusOK, body: stale}) + steps = append(steps, f.roots()...) + steps = append(steps, backendStep{method: http.MethodDelete, suffix: suffix, status: http.StatusNoContent}) + provider, calls := disabledGraphClient(t, f, steps, nil) + got, err := provider.ReconcileHTTPPreview(context.Background(), f.snapshot.owner, f.snapshot.model) + if err != nil || got.State != HTTPPreviewPending || got.EndpointHostName != "" || *calls != len(steps) { + t.Fatalf("TLS isolation reported prematurely: %+v %v (%d/%d)", got, err, *calls, len(steps)) + } +} + +func TestHTTPSInventoryFailureAttemptsSuspensionAndSurfacesDeniedEnforcement(t *testing.T) { + for _, denied := range []bool{false, true} { + t.Run(map[bool]string{false: "suspension submitted", true: "suspension denied"}[denied], func(t *testing.T) { + f, route := httpsFixture(t) + f.endpoint.Properties.EnabledState, route.Properties.EnabledState = ptr.To(armcdn.EnabledStateEnabled), ptr.To(armcdn.EnabledStateEnabled) + steps := append(httpPreviewReads(f, route), httpPreviewInventory(f, route)...) + steps[len(steps)-1].status = http.StatusForbidden + suspension := suspendEndpointSteps(f) + if denied { + suspension[len(suspension)-1].status = http.StatusForbidden + } + steps = append(steps, suspension...) + provider, calls := disabledGraphClient(t, f, steps, nil) + got, err := provider.ReconcileHTTPPreview(context.Background(), f.snapshot.owner, f.snapshot.model) + if err == nil || !strings.Contains(err.Error(), "list unsupported AFD secrets inventory") || got.State != HTTPPreviewSuspending || + got.EndpointHostName != "" || *calls != len(steps) { + t.Fatalf("inventory uncertainty was hidden: %+v %v (%d/%d)", got, err, *calls, len(steps)) + } + if denied { + if got.Suspension.State != "" || !strings.Contains(err.Error(), "suspend owned AFD endpoint") { + t.Fatalf("denied enforcement reported as successful: %+v %v", got, err) + } + } else if got.Suspension.State != EndpointSuspensionPending { + t.Fatalf("submission reported as observed suspension: %+v", got) + } + }) + } +} diff --git a/pkg/providers/azure/frontdoor/observation.go b/pkg/providers/azure/frontdoor/observation.go index 4068e81d..1ea341d8 100644 --- a/pkg/providers/azure/frontdoor/observation.go +++ b/pkg/providers/azure/frontdoor/observation.go @@ -168,8 +168,12 @@ func matchesPrivateOrigin(desired Origin, actual *armcdn.AFDOriginProperties) bo if !matchesPrivateLinkTarget(desired.PrivateLink, actual) { return false } + portMatches := ptr.Deref(actual.HTTPPort, 0) == desired.HTTPPort + if desired.HTTPSPort != 0 { + portMatches = ptr.Deref(actual.HTTPSPort, 0) == desired.HTTPSPort + } return ptr.Deref(actual.HostName, "") == desired.HostName && - ptr.Deref(actual.HTTPPort, 0) == desired.HTTPPort && + portMatches && int64(ptr.Deref(actual.Weight, 0)) == desired.Weight && ptr.Deref(actual.Priority, 0) == desired.Priority && ptr.Deref(actual.EnabledState, "") == armcdn.EnabledStateEnabled && diff --git a/pkg/providers/azure/frontdoor/origin_cleanup.go b/pkg/providers/azure/frontdoor/origin_cleanup.go index d4ca3ed9..dd92c979 100644 --- a/pkg/providers/azure/frontdoor/origin_cleanup.go +++ b/pkg/providers/azure/frontdoor/origin_cleanup.go @@ -18,6 +18,7 @@ import ( "k8s.io/utils/ptr" "go.goms.io/fleet-networking/pkg/common/azureerrors" + "go.goms.io/fleet-networking/pkg/common/origintls" ) func verifyStaleOrigin(roots RootRequests, group OriginGroupRequest, origin armcdn.AFDOrigin) error { @@ -42,12 +43,19 @@ func verifyStaleOrigin(roots RootRequests, group OriginGroupRequest, origin armc return fmt.Errorf("extra AFD origin %q lacks a valid PLS identity/location", name) } address, err := netip.ParseAddr(ptr.Deref(properties.HostName, "")) - if err != nil || !address.Is4() || !address.IsPrivate() || + privateIP := err == nil && address.Is4() && address.IsPrivate() + tlsDNS := origintls.ValidateHostname(ptr.Deref(properties.HostName, "")) == nil && ptr.Deref(properties.HTTPSPort, 0) > 0 + if (!privateIP && !tlsDNS) || ptr.Deref(properties.Weight, 0) < 1 || ptr.Deref(properties.Weight, 0) > 1000 { return fmt.Errorf("extra AFD origin %q lacks a supported private endpoint/weight", name) } desired := staleOriginConfiguration(origin) - if len(group.Origins) != 0 { + if tlsDNS { + desired.HTTPPort = 0 + if desired.HTTPSPort < 1 || desired.HTTPSPort > 65535 { + return fmt.Errorf("retired TLS origin has an invalid HTTPS port") + } + } else if len(group.Origins) != 0 && group.Origins[0].Parameters.Properties.HTTPPort != nil { desired.HTTPPort = *group.Origins[0].Parameters.Properties.HTTPPort } else if desired.HTTPPort < 1 || desired.HTTPPort > 65535 { return fmt.Errorf("retired AFD origin %q has an invalid HTTP port", name) @@ -71,12 +79,16 @@ func fleetGeneratedName(name, prefix string) bool { func staleOriginConfiguration(origin armcdn.AFDOrigin) Origin { properties := origin.Properties link := properties.SharedPrivateLinkResource - return Origin{ + result := Origin{ HostName: ptr.Deref(properties.HostName, ""), HTTPPort: ptr.Deref(properties.HTTPPort, 0), Weight: int64(ptr.Deref(properties.Weight, 0)), Priority: ptr.Deref(properties.Priority, 0), OriginHostHeader: ptr.Deref(properties.OriginHostHeader, ""), EnforceCertificateNameCheck: ptr.Deref(properties.EnforceCertificateNameCheck, false), PrivateLink: PrivateLinkTarget{ResourceID: ptr.Deref(link.PrivateLink.ID, ""), Location: ptr.Deref(link.PrivateLinkLocation, "")}, } + if origintls.ValidateHostname(result.HostName) == nil { + result.HTTPSPort, result.HTTPPort = ptr.Deref(properties.HTTPSPort, 0), 0 + } + return result } func verifyStaleOriginState(properties *armcdn.AFDOriginProperties) error { diff --git a/pkg/providers/azure/frontdoor/requests.go b/pkg/providers/azure/frontdoor/requests.go index 7a81da5a..254c3302 100644 --- a/pkg/providers/azure/frontdoor/requests.go +++ b/pkg/providers/azure/frontdoor/requests.go @@ -57,12 +57,12 @@ func BuildBackendRequests(model gatewaymodel.GlobalGateway) (BackendRequests, er if origin.Weight < 1 || origin.Weight > 1000 { return BackendRequests{}, fmt.Errorf("origin %q weight must be in [1, 1000]", origin.Name) } - request.Origins = append(request.Origins, OriginRequest{ + originRequest := OriginRequest{ Name: origin.Name, Parameters: armcdn.AFDOrigin{Properties: &armcdn.AFDOriginProperties{ // Omit OriginHostHeader to preserve incoming Host; ARM rejects an explicit empty string. - HostName: ptr.To(origin.HostName), HTTPPort: ptr.To(origin.HTTPPort), - Weight: ptr.To(int32(origin.Weight)), Priority: ptr.To(origin.Priority), + HostName: ptr.To(origin.HostName), + Weight: ptr.To(int32(origin.Weight)), Priority: ptr.To(origin.Priority), EnabledState: ptr.To(armcdn.EnabledStateEnabled), EnforceCertificateNameCheck: ptr.To(origin.EnforceCertificateNameCheck), SharedPrivateLinkResource: &armcdn.SharedPrivateLinkResourceProperties{ // Custom PLS has no group ID. Approval status is observed, never requested. @@ -71,7 +71,13 @@ func BuildBackendRequests(model gatewaymodel.GlobalGateway) (BackendRequests, er RequestMessage: ptr.To("Fleet AFD private origin for " + plan.ProfileName), }, }}, - }) + } + if origin.HTTPSPort != 0 { + originRequest.Parameters.Properties.HTTPSPort = ptr.To(origin.HTTPSPort) + } else { + originRequest.Parameters.Properties.HTTPPort = ptr.To(origin.HTTPPort) + } + request.Origins = append(request.Origins, originRequest) } requests.OriginGroups = append(requests.OriginGroups, request) } @@ -79,6 +85,10 @@ func BuildBackendRequests(model gatewaymodel.GlobalGateway) (BackendRequests, er } func privateHTTPGroupProperties(probe gatewaymodel.HealthProbe) *armcdn.AFDOriginGroupProperties { + protocol := armcdn.ProbeProtocolHTTP + if probe.Protocol == gatewaymodel.ProtocolHTTPS { + protocol = armcdn.ProbeProtocolHTTPS + } return &armcdn.AFDOriginGroupProperties{ LoadBalancingSettings: &armcdn.LoadBalancingSettingsParameters{ SampleSize: ptr.To(int32(4)), SuccessfulSamplesRequired: ptr.To(int32(3)), @@ -86,7 +96,7 @@ func privateHTTPGroupProperties(probe gatewaymodel.HealthProbe) *armcdn.AFDOrigi }, HealthProbeSettings: &armcdn.HealthProbeParameters{ ProbePath: ptr.To(probe.Path), ProbeIntervalInSeconds: ptr.To(probe.IntervalSeconds), - ProbeProtocol: ptr.To(armcdn.ProbeProtocolHTTP), ProbeRequestType: ptr.To(armcdn.HealthProbeRequestTypeGET), + ProbeProtocol: ptr.To(protocol), ProbeRequestType: ptr.To(armcdn.HealthProbeRequestTypeGET), }, SessionAffinityState: ptr.To(armcdn.EnabledStateDisabled), } diff --git a/pkg/providers/azure/frontdoor/withdrawal.go b/pkg/providers/azure/frontdoor/withdrawal.go index 87c5ab5d..630f8767 100644 --- a/pkg/providers/azure/frontdoor/withdrawal.go +++ b/pkg/providers/azure/frontdoor/withdrawal.go @@ -170,6 +170,10 @@ func (p *RouteProvisioner) observeWithdrawalInventory(ctx context.Context, graph group = OriginGroupRequest{Name: *actual.Name, Parameters: armcdn.AFDOriginGroup{ Properties: privateHTTPGroupProperties(gatewaymodel.HTTPPreviewHealthProbe()), }} + if actual.Properties != nil && actual.Properties.HealthProbeSettings != nil && + ptr.Deref(actual.Properties.HealthProbeSettings.ProbeProtocol, "") == armcdn.ProbeProtocolHTTPS { + group.Parameters.Properties = privateHTTPGroupProperties(gatewaymodel.HTTPSHealthProbe()) + } if err := verifyGroupIdentity(roots, group.Name, *actual); err != nil { return nil, group, nil, err } @@ -221,6 +225,10 @@ func verifyWithdrawalRoute(graph HTTPPreviewRequests, route armcdn.Route) error ForwardingProtocol: ptr.To(armcdn.ForwardingProtocolHTTPOnly), HTTPSRedirect: ptr.To(armcdn.HTTPSRedirectDisabled), LinkToDefaultDomain: ptr.To(armcdn.LinkToDefaultDomainEnabled), } + if ptr.Deref(route.Properties.ForwardingProtocol, "") == armcdn.ForwardingProtocolHTTPSOnly { + expected.SupportedProtocols = []*armcdn.AFDEndpointProtocols{ptr.To(armcdn.AFDEndpointProtocolsHTTPS)} + expected.ForwardingProtocol = ptr.To(armcdn.ForwardingProtocolHTTPSOnly) + } state := ptr.Deref(route.Properties.EnabledState, "") if !matchesHTTPPreviewRoute(expected, route.Properties) || (state != armcdn.EnabledStateEnabled && state != armcdn.EnabledStateDisabled) { diff --git a/test/README.md b/test/README.md index 2f5ec947..7dc8dbac 100644 --- a/test/README.md +++ b/test/README.md @@ -71,6 +71,15 @@ flags required by `test/e2e/traffic_manager_test.go`. Tests in that file skip wh ### Azure Front Door and Gateway API +For the proposed end-to-end HTTPS follow-up, first-party test owners should +review the separate [origin hostname/certificate fixture guide](https-origins-certificates.md). +It covers approved DNS identity, conditional OneCert/public-CA enrollment, +private-key custody, member Service-targeted policies/automatic hub projection, +preflight, rotation and negative fixtures. This is +preparation only; no TLS E2E opt-in/command exists yet. The implementation and +required live scenarios remain in the +[HTTPS proposal](../docs/design/gep-1748-https-origins-proposal.md#e2e-testing-requirements). + The separate Gateway manager has an opt-in local image build target. It requires make, Docker/buildx and a Linux container builder: @@ -430,6 +439,17 @@ exercise these ARM operations. The separately opted-in private HTTP scenario below prepares actual deployment/identity, approval, SDK, traffic and cleanup assertions. Its live execution remains deferred. +#### Installed-controller private HTTPS proof (prepared, not live-verified) + +HTTPS has a separate `ENABLE_AFD_PRIVATE_HTTPS_PROOF=true` opt-in and +`afd-private-https-proof` label; ordinary HTTP runs do not select it. +See the [certificate fixture interface](https-origins-certificates.md#executable-fixture-interface) +for AKV/Workload Identity identifier inputs, member CSI prerequisites, required +candidate images, CRD-first setup and +explicit live-scope approval. The scenario checks both TLS hops, real probes, +member-local metadata revocation, provider-verified isolation, no HTTP fallback, +all-ineligible withdrawal and cleanup. It is compiled offline, not live-verified. + #### Installed-controller private HTTP proof (prepared, not live-verified) `gateway_private_http_test.go` adds one serial scenario labeled diff --git a/test/e2e/e2e_test.go b/test/e2e/e2e_test.go index 103f8fa6..a929d107 100644 --- a/test/e2e/e2e_test.go +++ b/test/e2e/e2e_test.go @@ -24,6 +24,7 @@ import ( clientgoscheme "k8s.io/client-go/kubernetes/scheme" "sigs.k8s.io/cloud-provider-azure/pkg/azclient/publicipaddressclient" gatewayv1 "sigs.k8s.io/gateway-api/apis/v1" + gatewayv1alpha3 "sigs.k8s.io/gateway-api/apis/v1alpha3" gatewayv1beta1 "sigs.k8s.io/gateway-api/apis/v1beta1" fleetv1beta1 "go.goms.io/fleet/apis/cluster/v1beta1" @@ -77,6 +78,7 @@ func init() { utilruntime.Must(gatewayv1.Install(scheme)) // ReferenceGrant remains v1beta1 in Gateway API v1.2.1. utilruntime.Must(gatewayv1beta1.Install(scheme)) + utilruntime.Must(gatewayv1alpha3.Install(scheme)) } func TestE2E(t *testing.T) { diff --git a/test/e2e/fixtures/https_server.py b/test/e2e/fixtures/https_server.py new file mode 100644 index 00000000..bfa445a0 --- /dev/null +++ b/test/e2e/fixtures/https_server.py @@ -0,0 +1,79 @@ +import http.server +import json +import os +import ssl +import time +import urllib.parse + + +class Handler(http.server.BaseHTTPRequestHandler): + def do_GET(self): + parsed = urllib.parse.urlparse(self.path) + nonce = urllib.parse.parse_qs(parsed.query).get("proof", [""])[0] + result = { + "proof_id": os.environ["FLEET_PROOF_ID"], + "cluster_id": os.environ["MEMBER_CLUSTER_ID"], + "request_id": nonce, + "host": self.headers.get("Host", ""), + "sni": getattr(self.connection, "fleet_sni", ""), + "protocol": self.connection.version(), + } + print(json.dumps({"event": "tls_request", "path": parsed.path, + "probe": "Health Probe" in self.headers.get("User-Agent", ""), + **result}), flush=True) + data = json.dumps(result).encode("utf-8") + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(data))) + self.send_header("Cache-Control", "no-store") + self.end_headers() + self.wfile.write(data) + + +def observe_sni(connection, name, _context): + connection.fleet_sni = name or "" + + +def validated_context(bundle, hostname, client_context=None): + if os.stat(bundle).st_size > 1024 * 1024: + raise ValueError("CSI certificate bundle exceeds 1 MiB") + context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + context.minimum_version = ssl.TLSVersion.TLSv1_2 + context.load_cert_chain(bundle, password=lambda: "") + client_context = client_context or ssl.create_default_context() + client_context.hostname_checks_common_name = False + server_in, server_out, client_in, client_out = (ssl.MemoryBIO() for _ in range(4)) + server = context.wrap_bio(server_in, server_out, server_side=True) + client = client_context.wrap_bio(client_in, client_out, server_hostname=hostname) + peers = [(client, client_out, server_in), (server, server_out, client_in)] + done = set() + # Validate exactly the loaded chain/key with an in-memory, verified handshake. + for _ in range(16): + for peer, outgoing, incoming in peers: + if peer not in done: + try: + peer.do_handshake() + done.add(peer) + except ssl.SSLWantReadError: + pass + incoming.write(outgoing.read()) + if len(done) == 2: + break + else: + raise ValueError("certificate validation handshake did not finish") + expires = ssl.cert_time_to_seconds(client.getpeercert()["notAfter"]) + if expires - time.time() < 7 * 24 * 60 * 60: + raise ValueError("serving certificate requires at least seven days remaining") + return context + + +def main(): + context = validated_context("/tls/serving.pem", os.environ["ORIGIN_TLS_HOSTNAME"]) + context.set_servername_callback(observe_sni) + server = http.server.ThreadingHTTPServer(("0.0.0.0", 8443), Handler) + server.socket = context.wrap_socket(server.socket, server_side=True) + server.serve_forever() + + +if __name__ == "__main__": + main() diff --git a/test/e2e/fixtures/test_https_server.py b/test/e2e/fixtures/test_https_server.py new file mode 100644 index 00000000..033d3c09 --- /dev/null +++ b/test/e2e/fixtures/test_https_server.py @@ -0,0 +1,131 @@ +from pathlib import Path +import ssl +import subprocess +import tempfile +import unittest +from unittest import mock + +from https_server import validated_context + + +class CertificateTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.temporary = tempfile.TemporaryDirectory() + cls.addClassCleanup(cls.temporary.cleanup) + cls.directory = Path(cls.temporary.name) + cls.run_openssl("req", "-x509", "-newkey", "ec", + "-pkeyopt", "ec_paramgen_curve:prime256v1", "-nodes", + "-keyout", "ca.key", "-out", "ca.pem", "-days", "30", + "-subj", "/CN=Disposable fixture test CA", + "-addext", "basicConstraints=critical,CA:TRUE", + "-addext", "keyUsage=critical,keyCertSign,cRLSign") + cls.run_openssl("req", "-new", "-newkey", "ec", + "-pkeyopt", "ec_paramgen_curve:prime256v1", "-nodes", + "-keyout", "intermediate.key", "-out", "intermediate.csr", + "-subj", "/CN=Disposable fixture intermediate") + (cls.directory / "intermediate.ext").write_text( + "basicConstraints=critical,CA:TRUE,pathlen:0\n" + "keyUsage=critical,keyCertSign,cRLSign\n", encoding="ascii") + cls.run_openssl("x509", "-req", "-in", "intermediate.csr", + "-CA", "ca.pem", "-CAkey", "ca.key", "-CAcreateserial", + "-out", "intermediate.pem", "-days", "30", + "-extfile", "intermediate.ext") + for name, days, usage in (("valid", 14, "serverAuth"), + ("short", 2, "serverAuth"), + ("client", 14, "clientAuth")): + cls.run_openssl("req", "-new", "-newkey", "ec", + "-pkeyopt", "ec_paramgen_curve:prime256v1", "-nodes", + "-keyout", name + ".key", "-out", name + ".csr", + "-subj", "/CN=origin.example.com") + extensions = cls.directory / (name + ".ext") + extensions.write_text( + "basicConstraints=critical,CA:FALSE\n" + "keyUsage=critical,digitalSignature\n" + "extendedKeyUsage=" + usage + "\n" + "subjectAltName=DNS:origin.example.com\n", encoding="ascii") + cls.run_openssl("x509", "-req", "-in", name + ".csr", + "-CA", "intermediate.pem", "-CAkey", "intermediate.key", "-CAcreateserial", + "-out", name + ".pem", "-days", str(days), + "-extfile", name + ".ext") + (cls.directory / (name + ".bundle")).write_bytes( + (cls.directory / (name + ".pem")).read_bytes() + + (cls.directory / "intermediate.pem").read_bytes() + + (cls.directory / (name + ".key")).read_bytes()) + + @classmethod + def run_openssl(cls, *args): + subprocess.run(["openssl", *args], cwd=cls.directory, + check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + + def validate(self, name, hostname="origin.example.com", trusted=True): + client = ssl.create_default_context( + cafile=str(self.directory / "ca.pem") if trusted else None) + return validated_context(self.directory / (name + ".bundle"), hostname, client) + + def test_valid_bundle_requires_no_external_listener(self): + with mock.patch("socket.socket", side_effect=AssertionError("network access")): + self.assertIsInstance(self.validate("valid"), ssl.SSLContext) + + def test_wrong_name(self): + with self.assertRaises(ssl.SSLCertVerificationError): + self.validate("valid", hostname="other.example.com") + + def test_untrusted_issuer(self): + with self.assertRaises(ssl.SSLCertVerificationError): + self.validate("valid", trusted=False) + + def test_server_usage(self): + with self.assertRaises(ssl.SSLCertVerificationError): + self.validate("client") + + def test_incomplete_chain(self): + (self.directory / "incomplete.bundle").write_bytes( + (self.directory / "valid.pem").read_bytes() + + (self.directory / "valid.key").read_bytes()) + with self.assertRaises(ssl.SSLCertVerificationError): + self.validate("incomplete") + + def test_lifetime_margin(self): + with self.assertRaisesRegex(ValueError, "seven days"): + self.validate("short") + + def test_expired_leaf(self): + # Backdate only a disposable local unit-test certificate, never public issuance. + config = self.directory / "ca.conf" + config.write_text( + "[ca]\ndefault_ca=issuer\n[issuer]\n" + "database=index\nnew_certs_dir=.\ncertificate=ca.pem\n" + "private_key=ca.key\nserial=serial\n" + "default_md=sha256\npolicy=policy\nx509_extensions=server\n" + "[policy]\ncommonName=supplied\n[server]\n" + "basicConstraints=critical,CA:FALSE\n" + "keyUsage=critical,digitalSignature\nextendedKeyUsage=serverAuth\n" + "subjectAltName=DNS:origin.example.com\n", encoding="ascii") + (self.directory / "index").touch() + (self.directory / "serial").write_text("01\n", encoding="ascii") + self.run_openssl("ca", "-batch", "-config", "ca.conf", "-in", "valid.csr", + "-out", "expired.pem", "-notext", + "-startdate", "20000101000000Z", "-enddate", "20010101000000Z") + (self.directory / "expired.bundle").write_bytes( + (self.directory / "expired.pem").read_bytes() + + (self.directory / "valid.key").read_bytes()) + with self.assertRaises(ssl.SSLCertVerificationError): + self.validate("expired") + + def test_mismatched_private_key(self): + path = self.directory / "mismatch.bundle" + path.write_bytes((self.directory / "valid.pem").read_bytes() + + (self.directory / "short.key").read_bytes()) + with self.assertRaises(ssl.SSLError): + self.validate("mismatch") + + def test_public_certificate_is_not_a_serving_bundle(self): + path = self.directory / "public.bundle" + path.write_bytes((self.directory / "valid.pem").read_bytes()) + with self.assertRaises(ssl.SSLError): + self.validate("public") + + +if __name__ == "__main__": + unittest.main() diff --git a/test/e2e/gateway_private_http_test.go b/test/e2e/gateway_private_http_test.go index ee98e0dc..dded6bb7 100644 --- a/test/e2e/gateway_private_http_test.go +++ b/test/e2e/gateway_private_http_test.go @@ -416,15 +416,15 @@ func createPrivateHTTPWorkload(ctx context.Context) corev1.Service { } func waitPrivateHTTPModel(ctx context.Context, gateway *gatewayv1.Gateway, route *gatewayv1.HTTPRoute, - serviceName string, credential azcore.TokenCredential) gatewaymodel.GlobalGateway { + serviceName string, credential azcore.TokenCredential, originTLS ...bool) gatewaymodel.GlobalGateway { GinkgoHelper() var model gatewaymodel.GlobalGateway Eventually(ctx, func() error { - attachments, err := gatewayresolver.ResolveAttachments(gateway, route, route.Spec.ParentRefs[0], nil) + attachments, err := gatewayresolver.ResolveAttachments(gateway, route, route.Spec.ParentRefs[0], nil, originTLS...) if err != nil { return err } - resolved, err := gatewayresolver.ResolveHTTPRouteUnindexed(ctx, hubCluster.Client(), route, attachments) + resolved, err := gatewayresolver.ResolveHTTPRouteUnindexed(ctx, hubCluster.Client(), route, attachments, originTLS...) if err != nil { return err } @@ -453,6 +453,9 @@ func waitPrivateHTTPModel(ctx context.Context, gateway *gatewayv1.Gateway, route model = gatewaymodel.GlobalGateway{Namespace: gateway.Namespace, Name: gateway.Name, UID: string(gateway.UID), Listeners: []gatewaymodel.Listener{{Name: privateHTTPListener, Protocol: "HTTP", Port: 80}}, Routes: []gatewaymodel.Route{resolved}} + if len(originTLS) != 0 && originTLS[0] { + model.Listeners = []gatewaymodel.Listener{{Name: string(gateway.Spec.Listeners[0].Name), Protocol: "HTTPS", Port: 443, DefaultCertificate: true}} + } return nil }, privateHTTPTimeout, privateHTTPPoll).Should(Succeed()) return model diff --git a/test/e2e/gateway_private_https_test.go b/test/e2e/gateway_private_https_test.go new file mode 100644 index 00000000..e97dc09b --- /dev/null +++ b/test/e2e/gateway_private_https_test.go @@ -0,0 +1,335 @@ +//go:build e2e + +/* +Copyright (c) Microsoft Corporation. +Licensed under the MIT license. +*/ + +package e2e + +import ( + "context" + _ "embed" + "encoding/json" + "fmt" + "os" + "strings" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azidentity" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/cdn/armcdn/v2" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v9" + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" + corev1 "k8s.io/api/core/v1" + storagev1 "k8s.io/api/storage/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/util/intstr" + "k8s.io/utils/ptr" + "sigs.k8s.io/controller-runtime/pkg/client" + gatewayv1 "sigs.k8s.io/gateway-api/apis/v1" + gatewayv1alpha2 "sigs.k8s.io/gateway-api/apis/v1alpha2" + gatewayv1alpha3 "sigs.k8s.io/gateway-api/apis/v1alpha3" + + "go.goms.io/fleet-networking/pkg/common/objectmeta" + "go.goms.io/fleet-networking/pkg/common/origintls" + "go.goms.io/fleet-networking/pkg/common/uniquename" + "go.goms.io/fleet-networking/pkg/controllers/hub/gatewaymodel" + "go.goms.io/fleet-networking/pkg/controllers/hub/gatewayresolver" + "go.goms.io/fleet-networking/pkg/providers/azure/frontdoor" + "go.goms.io/fleet-networking/test/e2e/framework" + tlsfixture "go.goms.io/fleet-networking/test/fixtures/origintls" +) + +//go:embed fixtures/https_server.py +var privateHTTPSServer string + +var _ = Describe("Gateway private HTTPS proof", Serial, Label("afd-private-https-proof"), func() { + It("proves both TLS hops, probes, member-local revocation, no HTTP fallback and cleanup using installed controllers", func(ctx SpecContext) { + if os.Getenv("ENABLE_AFD_PRIVATE_HTTPS_PROOF") != "true" { + Skip("Explicit live authorization and ENABLE_AFD_PRIVATE_HTTPS_PROOF=true are required") + } + Expect(os.Getenv("ENABLE_ORIGIN_TLS")).To(Equal("true")) + Expect(os.Getenv("ENABLE_AZURE_FRONT_DOOR")).To(Equal("true")) + Expect(retainedAFDSetup).To(BeFalse(), "TLS proof does not support retained resources or secret fixtures") + fixture, err := tlsfixture.FromEnv(os.Getenv) + Expect(err).NotTo(HaveOccurred(), "AKV CSI fixture inputs must be explicitly configured") + hostname := fixture.Hostname + preflightPrivateHTTPSCSI(ctx, fixture.Namespace) + waitPrivateHTTPController(ctx) + credential, err := azidentity.NewDefaultAzureCredential(nil) + Expect(err).NotTo(HaveOccurred()) + scope := frontdoor.ResourceScope{SubscriptionID: subscriptionID, ResourceGroup: atmResourceGroup} + verifier, err := frontdoor.NewRouteProvisioner(scope, credential, nil) + Expect(err).NotTo(HaveOccurred()) + profiles, err := armcdn.NewProfilesClient(scope.SubscriptionID, credential, nil) + Expect(err).NotTo(HaveOccurred()) + services, err := armnetwork.NewPrivateLinkServicesClient(scope.SubscriptionID, credential, nil) + Expect(err).NotTo(HaveOccurred()) + service := createPrivateHTTPSWorkload(ctx, fixture) + class := framework.GatewayClass("https-proof-"+service.Namespace, gatewayControllerName) + Expect(hubCluster.Client().Create(ctx, class)).To(Succeed()) + DeferCleanup(func(ctx SpecContext) { + Expect(client.IgnoreNotFound(hubCluster.Client().Delete(ctx, class))).To(Succeed()) + }, NodeTimeout(time.Minute)) + gateway := framework.Gateway(service.Namespace, "private-https", class.Name, "", nil) + gateway.Spec.Listeners = []gatewayv1.Listener{{Name: "https", Protocol: gatewayv1.HTTPSProtocolType, Port: 443, + TLS: &gatewayv1.GatewayTLSConfig{Mode: ptr.To(gatewayv1.TLSModeTerminate), Options: map[gatewayv1.AnnotationKey]gatewayv1.AnnotationValue{ + gatewayv1.AnnotationKey(origintls.DefaultCertificateOption): "true", + }}}} + Expect(hubCluster.Client().Create(ctx, gateway)).To(Succeed()) + var identity corev1.Namespace + Expect(hubCluster.Client().Get(ctx, client.ObjectKey{Name: metav1.NamespaceSystem}, &identity)).To(Succeed()) + owner := frontdoor.GatewayOwner{HubUID: string(identity.UID), Namespace: gateway.Namespace, Name: gateway.Name, UID: string(gateway.UID)} + roots, err := frontdoor.BuildRootRequests(scope, owner) + Expect(err).NotTo(HaveOccurred()) + DeferCleanup(func(ctx SpecContext) { cleanupPrivateHTTPGateway(ctx, gateway, scope, owner, roots, profiles) }, NodeTimeout(privateHTTPCleanupNodeTimeout)) + route := framework.HTTPRouteToFleetServiceImport(service.Namespace, "private-https", gateway.Name, "", service.Name, 443, 1) + route.Spec.Rules[0].Matches = []gatewayv1.HTTPRouteMatch{{Path: &gatewayv1.HTTPPathMatch{Type: ptr.To(gatewayv1.PathMatchPathPrefix), Value: ptr.To("/")}}} + Expect(hubCluster.Client().Create(ctx, route)).To(Succeed()) + model := waitPrivateHTTPModel(ctx, gateway, route, service.Name, credential, true) + plan, err := frontdoor.PlanBackends(model) + Expect(err).NotTo(HaveOccurred()) + DeferCleanup(func(ctx SpecContext) { + if CurrentSpecReport().Failed() { + reportPrivateHTTPDiagnostics(ctx, "HTTPS proof failure", scope, owner, plan, credential, gateway) + } + }, NodeTimeout(privateHTTPDiagnosticTimeout+time.Minute)) + waitPrivateHTTPPhase(ctx, "HTTPS exact private-link approvals", func(ctx context.Context) error { + requests, err := collectPrivateHTTPApprovalRequests(ctx, services, scope, roots, service.Namespace, plan.PrivateLinks) + if err != nil { + return err + } + if err := privateHTTPApprovalsComplete(requests); err != nil { + if os.Getenv("ENABLE_AFD_PRIVATE_LINK_AUTO_APPROVAL") == "true" { + return approvePrivateHTTPRequests(ctx, services, scope, roots, service.Namespace, plan.PrivateLinks, requests) + } + return err + } + return nil + }) + var published string + waitPrivateHTTPPhase(ctx, "HTTPS enabled graph", func(ctx context.Context) error { + var current gatewayv1.Gateway + if err := hubCluster.Client().Get(ctx, client.ObjectKeyFromObject(gateway), ¤t); err != nil { + return err + } + host, err := privateHTTPGatewayState(¤t, true, 1) + if err != nil { + return err + } + observed, err := verifier.VerifyEnabledHTTPPreview(ctx, owner, model) + if err != nil { + return err + } + if observed != host { + return fmt.Errorf("published hostname differs from the observed owned endpoint") + } + published = host + return nil + }) + members := make(map[string]bool) + for _, member := range memberClusters { + members[member.Name()] = true + } + httpClient := privateHTTPClient() + checkTraffic := func(expected map[string]bool) error { + nonce := uniquename.RandomLowerCaseAlphabeticString(24) + reply, err := requestPrivateHTTP(ctx, httpClient, "https://"+published+"/", nonce) + if err != nil { + return err + } + if _, err := validatePrivateHTTPResponse(reply, service.Namespace, nonce, published, expected); err != nil { + return err + } + var tls struct{ SNI, Protocol string } + if err := json.Unmarshal(reply.Body, &tls); err != nil { + return err + } + if tls.SNI != hostname || (tls.Protocol != "TLSv1.2" && tls.Protocol != "TLSv1.3") { + return fmt.Errorf("application did not observe the selected SNI over TLS") + } + return nil + } + waitPrivateHTTPPhase(ctx, "verified end-to-end TLS traffic", func(context.Context) error { return checkTraffic(members) }) + for _, member := range memberClusters { + waitPrivateHTTPSProbe(ctx, member, service, hostname) + } + Eventually(ctx, func() error { + reply, err := requestPrivateHTTP(ctx, httpClient, "http://"+published+"/", uniquename.RandomLowerCaseAlphabeticString(24)) + if err != nil { + return err + } + return validatePrivateHTTPBlocked(reply, service.Namespace) + }, privateHTTPTrafficTimeout, privateHTTPPoll).Should(Succeed(), "HTTP must neither deliver the application nor redirect") + + By("revoking only one member's export marker without changing policy generation") + excluded := memberClusters[0] + var policy gatewayv1alpha3.BackendTLSPolicy + policyKey := client.ObjectKey{Namespace: service.Namespace, Name: service.Name + "-tls"} + Expect(excluded.Client().Get(ctx, policyKey, &policy)).To(Succeed()) + generation := policy.Generation + delete(policy.Annotations, origintls.ExportAnnotation) + Expect(excluded.Client().Update(ctx, &policy)).To(Succeed()) + Expect(policy.Generation).To(Equal(generation)) + delete(members, excluded.Name()) + waitPrivateHTTPPhase(ctx, "HTTPS isolated member absence", func(ctx context.Context) error { + updated, err := resolvePrivateHTTPSModel(ctx, gateway, route) + if err != nil { + return err + } + backend := updated.Routes[0].Rules[0].Backends[0] + if len(backend.Origins) != len(memberClusters)-1 || len(backend.ExcludedOrigins) != 1 { + return fmt.Errorf("member-local TLS revocation is not observed") + } + if _, err := verifier.VerifyEnabledHTTPPreview(ctx, owner, updated); err != nil { + return err + } + return checkTraffic(members) + }) + Consistently(ctx, func() error { return checkTraffic(members) }, time.Minute, privateHTTPPoll).Should(Succeed()) + By("requiring global withdrawal once every member is ineligible") + for _, member := range memberClusters[1:] { + var policy gatewayv1alpha3.BackendTLSPolicy + Expect(member.Client().Get(ctx, policyKey, &policy)).To(Succeed()) + delete(policy.Annotations, origintls.ExportAnnotation) + Expect(member.Client().Update(ctx, &policy)).To(Succeed()) + } + var blocked privateHTTPBlockWindow + waitPrivateHTTPPhase(ctx, "HTTPS withdrawal", func(ctx context.Context) error { + var current gatewayv1.Gateway + if err := hubCluster.Client().Get(ctx, client.ObjectKeyFromObject(gateway), ¤t); err != nil { + return err + } + if _, err := privateHTTPGatewayState(¤t, false, 1); err != nil { + return err + } + reply, err := requestPrivateHTTP(ctx, httpClient, "https://"+published+"/", uniquename.RandomLowerCaseAlphabeticString(24)) + if err == nil { + err = validatePrivateHTTPBlocked(reply, service.Namespace) + } + return blocked.observe(time.Now(), err) + }) + cleanupPrivateHTTPGateway(ctx, gateway, scope, owner, roots, profiles) + }, SpecTimeout(privateHTTPSpecTimeout)) +}) + +func preflightPrivateHTTPSCSI(ctx context.Context, namespace string) { + GinkgoHelper() + for _, cluster := range fleet.Clusters() { + err := cluster.Client().Get(ctx, client.ObjectKey{Name: namespace}, &corev1.Namespace{}) + Expect(apierrors.IsNotFound(err)).To(BeTrue(), "HTTPS proof refuses an existing namespace or an unverifiable namespace inventory") + } + for _, member := range memberClusters { + var driver storagev1.CSIDriver + Expect(member.Client().Get(ctx, client.ObjectKey{Name: tlsfixture.CSIDriver}, &driver)).To(Succeed(), "Install Secrets Store CSI and the Azure provider before running the proof") + tokenRequest := false + for _, request := range driver.Spec.TokenRequests { + tokenRequest = tokenRequest || request.Audience == tlsfixture.WorkloadIdentityAudience + } + Expect(tokenRequest).To(BeTrue(), "CSI must request tokens for the preauthorized member ServiceAccount") + providers := &unstructured.UnstructuredList{} + providers.SetAPIVersion(tlsfixture.CSIGroupVersion) + providers.SetKind("SecretProviderClassList") + Expect(member.Client().List(ctx, providers, client.InNamespace(namespace), client.Limit(1))).To(Succeed(), "Install the SecretProviderClass CRD before running the proof") + } +} + +func createPrivateHTTPSWorkload(ctx context.Context, fixture tlsfixture.Config) corev1.Service { + GinkgoHelper() + workload := framework.NewWorkloadManager(fleet) + service := workload.Service() + service.Namespace = fixture.Namespace + service.Annotations = map[string]string{objectmeta.ServiceAnnotationAzureLoadBalancerInternal: "true", + objectmeta.ServiceAnnotationPLSName: service.Namespace, "service.beta.kubernetes.io/azure-pls-create": "true"} + service.Spec.Ports = []corev1.ServicePort{{Name: "https", Protocol: corev1.ProtocolTCP, Port: 443, TargetPort: intstr.FromInt32(8443), AppProtocol: ptr.To("https")}} + for _, cluster := range fleet.Clusters() { + cluster := cluster + namespace := framework.Namespace(service.Namespace) + Expect(cluster.Client().Create(ctx, namespace)).To(Succeed()) + DeferCleanup(func(ctx SpecContext) { + Expect(client.IgnoreNotFound(cluster.Client().Delete(ctx, namespace, client.Preconditions{UID: &namespace.UID}))).To(Succeed()) + Eventually(ctx, func() bool { + return apierrors.IsNotFound(cluster.Client().Get(ctx, client.ObjectKeyFromObject(namespace), &corev1.Namespace{})) + }, + privateHTTPCleanupTimeout, privateHTTPConvergencePoll).Should(BeTrue()) + }, NodeTimeout(privateHTTPCleanupNodeTimeout)) + } + for _, member := range memberClusters { + account, provider, err := fixture.Resources() + Expect(err).NotTo(HaveOccurred()) + Expect(member.Client().Create(ctx, account)).To(Succeed()) + Expect(member.Client().Create(ctx, provider)).To(Succeed()) + config := &corev1.ConfigMap{ObjectMeta: metav1.ObjectMeta{Namespace: service.Namespace, Name: "https-server"}, Data: map[string]string{"server.py": privateHTTPSServer}} + Expect(member.Client().Create(ctx, config)).To(Succeed()) + deployment := workload.Deployment(member.Name()).DeepCopy() + container := &deployment.Spec.Template.Spec.Containers[0] + container.Command, container.Args = []string{"python", "-u", "/fixture/server.py"}, nil + container.Env = append(container.Env, corev1.EnvVar{Name: "FLEET_PROOF_ID", Value: service.Namespace}) + container.VolumeMounts = []corev1.VolumeMount{{Name: "fixture", MountPath: "/fixture", ReadOnly: true}} + deployment.Spec.Template.Spec.Volumes = []corev1.Volume{ + {Name: "fixture", VolumeSource: corev1.VolumeSource{ConfigMap: &corev1.ConfigMapVolumeSource{LocalObjectReference: corev1.LocalObjectReference{Name: config.Name}}}}, + } + Expect(fixture.Configure(deployment)).To(Succeed()) + Expect(member.Client().Create(ctx, deployment)).To(Succeed()) + Expect(member.Client().Create(ctx, service.DeepCopy())).To(Succeed()) + policy := &gatewayv1alpha3.BackendTLSPolicy{ObjectMeta: metav1.ObjectMeta{Namespace: service.Namespace, Name: service.Name + "-tls", + Annotations: map[string]string{origintls.ExportAnnotation: "true"}}, + Spec: gatewayv1alpha3.BackendTLSPolicySpec{ + TargetRefs: []gatewayv1alpha2.LocalPolicyTargetReferenceWithSectionName{{LocalPolicyTargetReference: gatewayv1alpha2.LocalPolicyTargetReference{Group: "", Kind: "Service", Name: gatewayv1.ObjectName(service.Name)}}}, + Validation: gatewayv1alpha3.BackendTLSPolicyValidation{Hostname: gatewayv1.PreciseHostname(fixture.Hostname), WellKnownCACertificates: ptr.To(gatewayv1alpha3.WellKnownCACertificatesSystem)}, + }} + Expect(member.Client().Create(ctx, policy)).To(Succeed()) + Expect(member.Client().Create(ctx, framework.ServiceExport(service.Namespace, service.Name))).To(Succeed()) + } + return service +} + +func resolvePrivateHTTPSModel(ctx context.Context, gateway *gatewayv1.Gateway, route *gatewayv1.HTTPRoute) (gatewaymodel.GlobalGateway, error) { + attachments, err := gatewayresolver.ResolveAttachments(gateway, route, route.Spec.ParentRefs[0], nil, true) + if err != nil { + return gatewaymodel.GlobalGateway{}, err + } + resolved, err := gatewayresolver.ResolveHTTPRouteUnindexed(ctx, hubCluster.Client(), route, attachments, true) + if err != nil { + return gatewaymodel.GlobalGateway{}, err + } + return gatewaymodel.Normalize(gatewaymodel.GlobalGateway{Namespace: gateway.Namespace, Name: gateway.Name, UID: string(gateway.UID), + Listeners: []gatewaymodel.Listener{{Name: "https", Protocol: "HTTPS", Port: 443, DefaultCertificate: true}}, Routes: []gatewaymodel.Route{resolved}}) +} + +func waitPrivateHTTPSProbe(ctx context.Context, member *framework.Cluster, service corev1.Service, hostname string) { + GinkgoHelper() + Eventually(ctx, func() error { + var pods corev1.PodList + if err := member.Client().List(ctx, &pods, client.InNamespace(service.Namespace), client.MatchingLabels(service.Spec.Selector)); err != nil { + return err + } + for _, pod := range pods.Items { + text, err := member.PodLogs(ctx, service.Namespace, pod.Name, &corev1.PodLogOptions{Container: "python", TailLines: ptr.To[int64](1000), LimitBytes: ptr.To[int64](privateHTTPMaxBody)}) + if err != nil { + return err + } + for _, line := range strings.Split(text, "\n") { + if !strings.HasPrefix(line, "{") { + continue + } + var record struct { + Event, SNI, Host, Protocol, Path string + Probe bool + } + if err := json.Unmarshal([]byte(line), &record); err != nil { + return err + } + if record.Event == "tls_request" && record.Probe && record.Path == "/" && record.SNI == hostname && record.Host != "" && + (record.Protocol == "TLSv1.2" || record.Protocol == "TLSv1.3") { + AddReportEntry("HTTPS probe Host "+member.Name(), record.Host) + return nil + } + } + } + return fmt.Errorf("waiting for real HTTPS probe with expected SNI") + }, privateHTTPTrafficTimeout, privateHTTPPoll).Should(Succeed()) +} diff --git a/test/fixtures/origintls/csi.go b/test/fixtures/origintls/csi.go new file mode 100644 index 00000000..2fed9e39 --- /dev/null +++ b/test/fixtures/origintls/csi.go @@ -0,0 +1,121 @@ +/* +Copyright (c) Microsoft Corporation. +Licensed under the MIT license. +*/ + +// Package origintls configures application-only AKV CSI fixtures, never secret contents. +package origintls + +import ( + "fmt" + "regexp" + "strings" + + appsv1 "k8s.io/api/apps/v1" + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/util/validation" + "k8s.io/utils/ptr" + + "go.goms.io/fleet-networking/pkg/common/origintls" +) + +const ( + ServingAccount = "origin-serving" + CSIGroupVersion = "secrets-store.csi.x-k8s.io/v1" + CSIDriver = "secrets-store.csi.k8s.io" + WorkloadIdentityAudience = "api://AzureADTokenExchange" +) + +var ( + uuid = regexp.MustCompile(`^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$`) + vaultName = regexp.MustCompile(`^[a-zA-Z][a-zA-Z0-9-]{1,22}[a-zA-Z0-9]$`) + objectName = regexp.MustCompile(`^[a-zA-Z0-9-]{1,127}$`) + objectVersion = regexp.MustCompile(`^[0-9a-fA-F]{32}$`) +) + +// Config contains identifiers supplied by the owner of the approved test environment. +type Config struct { + Namespace, Hostname, VaultName, CertificateName, CertificateVersion, TenantID, ClientID string +} + +// FromEnv rejects legacy runner-key inputs rather than silently falling back to them. +func FromEnv(getenv func(string) string) (Config, error) { + if getenv("ORIGIN_CERT_CHAIN_FILE") != "" || getenv("ORIGIN_KEY_FILE") != "" { + return Config{}, fmt.Errorf("runner-local certificate inputs are unsupported; use the AKV CSI fixture") + } + config := Config{ + Namespace: getenv("ORIGIN_TLS_NAMESPACE"), Hostname: getenv("ORIGIN_TLS_HOSTNAME"), + VaultName: getenv("ORIGIN_AKV_NAME"), CertificateName: getenv("ORIGIN_AKV_CERT_NAME"), + CertificateVersion: getenv("ORIGIN_AKV_CERT_VERSION"), + TenantID: getenv("ORIGIN_AKV_TENANT_ID"), ClientID: getenv("ORIGIN_AKV_CLIENT_ID"), + } + if err := config.validate(); err != nil { + return Config{}, err + } + return config, nil +} + +func (c Config) validate() error { + if !strings.HasPrefix(c.Namespace, "https-proof-") || c.Namespace == "https-proof-" || + len(validation.IsDNS1123Label(c.Namespace)) != 0 { + return fmt.Errorf("ORIGIN_TLS_NAMESPACE must be a fresh https-proof-* namespace") + } + if origintls.ValidateHostname(c.Hostname) != nil { + return fmt.Errorf("ORIGIN_TLS_HOSTNAME must be a precise DNS identity") + } + if !vaultName.MatchString(c.VaultName) || strings.Contains(c.VaultName, "--") { + return fmt.Errorf("ORIGIN_AKV_NAME must be a valid Key Vault name") + } + if !objectName.MatchString(c.CertificateName) { + return fmt.Errorf("ORIGIN_AKV_CERT_NAME must name the certificate's backing secret") + } + if c.CertificateVersion != "" && !objectVersion.MatchString(c.CertificateVersion) { + return fmt.Errorf("ORIGIN_AKV_CERT_VERSION must be empty or a 32-digit hexadecimal secret version") + } + if !uuid.MatchString(c.TenantID) || !uuid.MatchString(c.ClientID) { + return fmt.Errorf("ORIGIN_AKV_TENANT_ID and ORIGIN_AKV_CLIENT_ID must be UUIDs") + } + return nil +} + +// Resources creates member-only identity/reference objects, with no Secret sync. +func (c Config) Resources() (*corev1.ServiceAccount, *unstructured.Unstructured, error) { + if err := c.validate(); err != nil { + return nil, nil, err + } + account := &corev1.ServiceAccount{ObjectMeta: metav1.ObjectMeta{Namespace: c.Namespace, Name: ServingAccount}, + AutomountServiceAccountToken: ptr.To(false)} + objects := fmt.Sprintf("array:\n - |\n objectName: %s\n objectType: secret\n objectFormat: pem\n objectAlias: serving.pem\n objectVersion: %q\n filePermission: \"0400\"\n", + c.CertificateName, c.CertificateVersion) + provider := &unstructured.Unstructured{Object: map[string]interface{}{ + "apiVersion": CSIGroupVersion, "kind": "SecretProviderClass", + "metadata": map[string]interface{}{"namespace": c.Namespace, "name": ServingAccount}, + "spec": map[string]interface{}{"provider": "azure", "parameters": map[string]interface{}{ + "usePodIdentity": "false", "useVMManagedIdentity": "false", "clientID": c.ClientID, + "keyvaultName": c.VaultName, "tenantId": c.TenantID, "objects": objects, + }}, + }} + return account, provider, nil +} + +// Configure mounts the CSI bundle directly, without exposing Azure tokens to the app. +func (c Config) Configure(deployment *appsv1.Deployment) error { + if err := c.validate(); err != nil { + return err + } + if len(deployment.Spec.Template.Spec.Containers) != 1 { + return fmt.Errorf("TLS fixture requires exactly one application container") + } + deployment.Namespace = c.Namespace + pod := &deployment.Spec.Template.Spec + pod.ServiceAccountName, pod.AutomountServiceAccountToken = ServingAccount, ptr.To(false) + pod.Volumes = append(pod.Volumes, corev1.Volume{Name: "tls", VolumeSource: corev1.VolumeSource{ + CSI: &corev1.CSIVolumeSource{Driver: CSIDriver, ReadOnly: ptr.To(true), + VolumeAttributes: map[string]string{"secretProviderClass": ServingAccount}}, + }}) + pod.Containers[0].VolumeMounts = append(pod.Containers[0].VolumeMounts, corev1.VolumeMount{Name: "tls", MountPath: "/tls", ReadOnly: true}) + pod.Containers[0].Env = append(pod.Containers[0].Env, corev1.EnvVar{Name: "ORIGIN_TLS_HOSTNAME", Value: c.Hostname}) + return nil +} diff --git a/test/fixtures/origintls/csi_test.go b/test/fixtures/origintls/csi_test.go new file mode 100644 index 00000000..82b76b66 --- /dev/null +++ b/test/fixtures/origintls/csi_test.go @@ -0,0 +1,114 @@ +/* +Copyright (c) Microsoft Corporation. +Licensed under the MIT license. +*/ + +package origintls + +import ( + "testing" + + appsv1 "k8s.io/api/apps/v1" + corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/utils/ptr" + "sigs.k8s.io/yaml" +) + +func fixtureEnvironment() map[string]string { + return map[string]string{ + "ORIGIN_TLS_NAMESPACE": "https-proof-csi", "ORIGIN_TLS_HOSTNAME": "origin.example.com", + "ORIGIN_AKV_NAME": "fixture-vault", "ORIGIN_AKV_CERT_NAME": "serving-certificate", + "ORIGIN_AKV_TENANT_ID": "11111111-1111-1111-1111-111111111111", + "ORIGIN_AKV_CLIENT_ID": "22222222-2222-2222-2222-222222222222", + } +} + +func TestCSIEnvironmentRejectsMissingAndUnsafeReferences(t *testing.T) { + for name := range fixtureEnvironment() { + t.Run("missing "+name, func(t *testing.T) { + env := fixtureEnvironment() + delete(env, name) + if _, err := FromEnv(func(key string) string { return env[key] }); err == nil { + t.Fatal("missing input accepted") + } + }) + } + for _, tt := range []struct{ name, value string }{ + {"ORIGIN_TLS_NAMESPACE", "kube-system"}, {"ORIGIN_TLS_NAMESPACE", "https-proof-"}, + {"ORIGIN_TLS_HOSTNAME", "*.example.com"}, {"ORIGIN_AKV_NAME", "https://vault.example"}, + {"ORIGIN_AKV_CERT_NAME", "cert\nobjectType: cert"}, {"ORIGIN_AKV_CERT_VERSION", "latest"}, + {"ORIGIN_AKV_TENANT_ID", "tenant"}, {"ORIGIN_AKV_CLIENT_ID", "client-secret"}, + {"ORIGIN_KEY_FILE", "/tmp/key.pem"}, {"ORIGIN_CERT_CHAIN_FILE", "/tmp/chain.pem"}, + } { + t.Run(tt.name+"="+tt.value, func(t *testing.T) { + env := fixtureEnvironment() + env[tt.name] = tt.value + if _, err := FromEnv(func(key string) string { return env[key] }); err == nil { + t.Fatal("unsafe or legacy input accepted") + } + }) + } +} + +func TestCSIMountBindsWorkloadIdentityAndPrivateBundleWithoutSecretSync(t *testing.T) { + env := fixtureEnvironment() + env["ORIGIN_AKV_CERT_VERSION"] = "0123456789abcdef0123456789abcdef" + config, err := FromEnv(func(key string) string { return env[key] }) + if err != nil { + t.Fatal(err) + } + account, provider, err := config.Resources() + if err != nil { + t.Fatal(err) + } + parameters, found, err := unstructured.NestedStringMap(provider.Object, "spec", "parameters") + if err != nil || !found { + t.Fatalf("invalid CSI parameters: %v", err) + } + if parameters["clientID"] != config.ClientID || parameters["tenantId"] != config.TenantID || + parameters["keyvaultName"] != config.VaultName || parameters["useVMManagedIdentity"] != "false" { + t.Fatalf("wrong identity/reference configuration: %+v", parameters) + } + var objects struct { + Array []string `json:"array"` + } + if err := yaml.UnmarshalStrict([]byte(parameters["objects"]), &objects); err != nil { + t.Fatal(err) + } + if len(objects.Array) != 1 { + t.Fatalf("expected one certificate bundle: %+v", objects) + } + var object map[string]string + if err := yaml.UnmarshalStrict([]byte(objects.Array[0]), &object); err != nil { + t.Fatal(err) + } + if object["objectType"] != "secret" || object["objectFormat"] != "pem" || object["objectAlias"] != "serving.pem" || + object["objectName"] != config.CertificateName || object["objectVersion"] != config.CertificateVersion || object["filePermission"] != "0400" { + t.Fatalf("bundle could lose private key, full chain or permissions: %+v", object) + } + if _, found, _ := unstructured.NestedFieldNoCopy(provider.Object, "spec", "secretObjects"); found { + t.Fatal("CSI must not sync secret contents to the API server") + } + deployment := &appsv1.Deployment{} + deployment.Spec.Template.Spec.Containers = []corev1.Container{{Name: "app"}} + if err := config.Configure(deployment); err != nil { + t.Fatal(err) + } + assertCSIApplicationMount(t, config, account, provider, deployment) +} + +func assertCSIApplicationMount(t *testing.T, config Config, account *corev1.ServiceAccount, provider *unstructured.Unstructured, deployment *appsv1.Deployment) { + t.Helper() + pod := deployment.Spec.Template.Spec + if account.Namespace != config.Namespace || deployment.Namespace != config.Namespace || pod.ServiceAccountName != account.Name || + ptr.Deref(account.AutomountServiceAccountToken, true) || ptr.Deref(pod.AutomountServiceAccountToken, true) { + t.Fatal("workload identity subject or token isolation changed") + } + mount, volume := pod.Containers[0].VolumeMounts[0], pod.Volumes[0] + if mount.Name != volume.Name || !mount.ReadOnly || mount.SubPath != "" || volume.Secret != nil || + volume.CSI == nil || volume.CSI.Driver != CSIDriver || !ptr.Deref(volume.CSI.ReadOnly, false) || + volume.CSI.VolumeAttributes["secretProviderClass"] != provider.GetName() { + t.Fatal("application does not directly mount the expected read-only CSI bundle") + } +} diff --git a/test/helm/gateway_chart_test.go b/test/helm/gateway_chart_test.go index 2e72580a..e09931e9 100644 --- a/test/helm/gateway_chart_test.go +++ b/test/helm/gateway_chart_test.go @@ -62,7 +62,7 @@ func TestGatewayChartDisabled(t *testing.T) { deployment.Spec.Template.Spec.ServiceAccountName != got.account.Name { t.Fatal("Deployment and ServiceAccount do not share the release namespace/identity") } - wantArgs := []string{"--enable-afd=false", "--leader-elect=true", "--leader-election-namespace=" + chartNamespace, + wantArgs := []string{"--enable-afd=false", "--enable-origin-tls=false", "--leader-elect=true", "--leader-election-namespace=" + chartNamespace, "--metrics-bind-address=:8082", "--health-probe-bind-address=:8083", "--v=2"} if container.Image != chartImage || !reflect.DeepEqual(container.Args, wantArgs) { t.Fatalf("image/args = %q/%v, want %q/%v", container.Image, container.Args, chartImage, wantArgs) @@ -194,6 +194,8 @@ func TestGatewayChartRejectsInvalidConfiguration(t *testing.T) { {"missing class name", true, []string{helmSetStringFlag, "gatewayClass.name="}, "gatewayClass.name"}, {"missing existing account", false, []string{helmSetFlag, "serviceAccount.create=false"}, "serviceAccount.name"}, {"string feature flag", false, []string{helmSetStringFlag, "afd.enabled=false"}, "afd.enabled"}, + {"origin TLS without provisioning", false, []string{helmSetFlag, "enableOriginTLS=true"}, "enableOriginTLS requires afd.enabled"}, + {"string origin TLS flag", false, []string{helmSetStringFlag, "enableOriginTLS=false"}, "enableOriginTLS"}, {"string leader flag", false, []string{helmSetStringFlag, "leaderElection=false"}, "leaderElection"}, {"string class flag", false, []string{helmSetStringFlag, "gatewayClass.create=false"}, "gatewayClass.create"}, {"string account flag", false, []string{helmSetStringFlag, "serviceAccount.create=false"}, "serviceAccount.create"}, diff --git a/test/helm/origin_tls_chart_test.go b/test/helm/origin_tls_chart_test.go new file mode 100644 index 00000000..425fd776 --- /dev/null +++ b/test/helm/origin_tls_chart_test.go @@ -0,0 +1,145 @@ +//go:build helm + +/* +Copyright (c) Microsoft Corporation. +Licensed under the MIT license. +*/ + +package helm + +import ( + "bytes" + "errors" + "io" + "path/filepath" + "reflect" + "slices" + "strings" + "testing" + + appsv1 "k8s.io/api/apps/v1" + rbacv1 "k8s.io/api/rbac/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/util/yaml" + clientgoscheme "k8s.io/client-go/kubernetes/scheme" +) + +func TestGatewayChartOriginTLS(t *testing.T) { + got := renderChart(t, helmSetFlag, enabledConfiguration+",enableOriginTLS=true") + if !slices.Contains(got.deployment.Spec.Template.Spec.Containers[0].Args, "--enable-origin-tls=true") { + t.Fatal("enabled origin TLS flag is missing") + } + var policies []rbacv1.PolicyRule + foundCRDRead := false + for _, rule := range got.clusterRole.Rules { + if slices.Contains(rule.Resources, "backendtlspolicies") || slices.Contains(rule.Resources, "backendtlspolicies/status") { + policies = append(policies, rule) + } + if slices.Contains(rule.Resources, "customresourcedefinitions") { + foundCRDRead = true + if !reflect.DeepEqual(rule.Verbs, []string{verbGet}) || !reflect.DeepEqual(rule.ResourceNames, + []string{"backendtlspolicies.gateway.networking.k8s.io", "internalserviceexports.networking.fleet.azure.com"}) { + t.Fatalf("startup CRD read is not scoped: %#v", rule) + } + } + for _, resource := range rule.Resources { + if strings.Contains(resource, "secret") { + t.Fatalf("origin TLS granted Secret permissions: %#v", rule) + } + } + } + if !foundCRDRead { + t.Fatal("origin TLS startup cannot read required CRDs") + } + assertRules(t, policies, map[string][]string{ + "gateway.networking.k8s.io/backendtlspolicies": {verbGet, verbList, verbWatch, verbCreate, verbUpdate, verbPatch, "delete"}, + "gateway.networking.k8s.io/backendtlspolicies/status": {verbGet, verbUpdate, verbPatch}, + }) +} + +func TestMemberChartOriginTLS(t *testing.T) { + for _, enabled := range []bool{false, true} { + t.Run(map[bool]string{false: "disabled", true: "enabled"}[enabled], func(t *testing.T) { + flags := []string{} + if enabled { + flags = append(flags, helmSetFlag, "enableOriginTLS=true,enablePrivateLinkOriginDiscovery=true") + } + args := append(memberTemplateArgs(), flags...) + output, err := runHelm(t, args...) + if err != nil { + t.Fatalf("helm template: %v\n%s", err, output) + } + deployment, role := decodeMemberOriginTLSResources(t, output) + wantFlag := "--enable-origin-tls=false" + if enabled { + wantFlag = "--enable-origin-tls=true" + } + if deployment == nil || role == nil || !slices.Contains(deployment.Spec.Template.Spec.Containers[0].Args, wantFlag) { + t.Fatal("member resources or TLS flag are missing") + } + var policies []rbacv1.PolicyRule + for _, rule := range role.Rules { + for _, resource := range rule.Resources { + if strings.HasPrefix(resource, "backendtlspolicies") { + policies = append(policies, rule) + } + } + } + if enabled { + assertRules(t, policies, map[string][]string{ + "gateway.networking.k8s.io/backendtlspolicies": {verbGet, verbList, verbWatch}, + }) + } else if len(policies) != 0 { + t.Fatalf("disabled member has BackendTLSPolicy permissions: %#v", policies) + } + }) + } +} + +func TestMemberChartRejectsInvalidOriginTLS(t *testing.T) { + for _, flags := range [][]string{ + {helmSetFlag, "enableOriginTLS=true"}, + {helmSetStringFlag, "enableOriginTLS=false"}, + } { + output, err := runHelm(t, append(memberTemplateArgs(), flags...)...) + if err == nil || !strings.Contains(string(output), "enableOriginTLS") { + t.Fatalf("helm accepted invalid origin TLS settings: %v\n%s", err, output) + } + } +} + +func memberTemplateArgs() []string { + return []string{"template", "member", filepath.Join("..", "..", "charts", "member-net-controller-manager"), + "--namespace", chartNamespace, "--show-only", "templates/deployment.yaml", "--show-only", "templates/rbac.yaml"} +} + +func decodeMemberOriginTLSResources(t *testing.T, output []byte) (*appsv1.Deployment, *rbacv1.ClusterRole) { + t.Helper() + decoder := clientgoscheme.Codecs.UniversalDeserializer() + documents := yaml.NewYAMLOrJSONDecoder(bytes.NewReader(output), 4096) + var deployment *appsv1.Deployment + var role *rbacv1.ClusterRole + for { + var raw runtime.RawExtension + if err := documents.Decode(&raw); err != nil { + if errors.Is(err, io.EOF) { + break + } + t.Fatal(err) + } + if len(raw.Raw) == 0 || string(raw.Raw) == "null" { + continue + } + object, _, err := decoder.Decode(raw.Raw, nil, nil) + if err != nil { + t.Fatal(err) + } + switch object := object.(type) { + case *appsv1.Deployment: + deployment = object + case *rbacv1.ClusterRole: + role = object + } + } + return deployment, role +} diff --git a/test/https-origins-certificates.md b/test/https-origins-certificates.md new file mode 100644 index 00000000..e2db8eb8 --- /dev/null +++ b/test/https-origins-certificates.md @@ -0,0 +1,276 @@ +# First-party certificate fixtures for end-to-end AFD TLS + +**Status: experimental fixture implemented; live Azure validation not run.** +Use this guide with the [engineering scenario matrix](../docs/design/gep-1748-https-origins-proposal.md#e2e-testing-requirements) +and [E2E environment guide](README.md). Obtain explicit authorization for the +subscription, resource group, Kubernetes contexts, certificate/DNS operations +and create/test/cleanup scope before provisioning anything. No live operations +are authorized by this document. + +The installed-controller fixture has its own explicit +`ENABLE_AFD_PRIVATE_HTTPS_PROOF=true` opt-in and `afd-private-https-proof` label. +It is not enabled by ordinary AFD/HTTP testing. It exercises system-verified edge +HTTPS, member TLS/SNI and real probe logs, exact Private Link approvals, no HTTP +fallback/redirect, metadata-only single-member opt-out, observed origin isolation, +healthy-member delivery, all-ineligible withdrawal and owned cleanup. This is not +a claim that the entire engineering scenario matrix has been proven live. + +## Executable fixture interface + +After obtaining scope approval, use the existing E2E environment with candidate +images. Supply `ENABLE_AZURE_FRONT_DOOR=true`, +`ENABLE_AFD_PRIVATE_HTTPS_PROOF=true`, `AZURE_SUBSCRIPTION_ID`, +`AZURE_RESOURCE_GROUP` and the normal verified hub/member contexts. +`ENABLE_ORIGIN_TLS` defaults to the explicit HTTPS proof selection. The existing +install script upgrades the internal hub CRD first, installs the pinned +experimental policy CRD and grants members scoped hub-schema reads before +enabling TLS in the existing managers. It grants no AKV/Secret access to them. + +Supply these environment variables; **all values are identifiers, not secrets**: + +| Variable | Required value | +|---|---| +| `ORIGIN_TLS_HOSTNAME` | Approved precise DNS SAN shared by the members | +| `ORIGIN_TLS_NAMESPACE` | Fresh, preauthorized `https-proof-*` namespace, absent from hub and both members | +| `ORIGIN_AKV_NAME` | Existing Azure Key Vault name, not its URL | +| `ORIGIN_AKV_CERT_NAME` | Certificate's backing-secret name containing the exportable private key and full chain | +| `ORIGIN_AKV_TENANT_ID` | Entra tenant UUID containing the vault/identity | +| `ORIGIN_AKV_CLIENT_ID` | Workload Identity application or user-assigned managed identity client UUID, not a credential | +| `ORIGIN_AKV_CERT_VERSION` | Optional 32-hex-digit **backing-secret** version; empty means latest | + +`ORIGIN_CERT_CHAIN_FILE` and `ORIGIN_KEY_FILE` are no longer supported and are +rejected. No PEM, PFX password, client secret or token belongs in environment +variables, command arguments, logs or the checkout. The runner neither reads +private-key files nor downloads AKV secret contents. + +Before the run, the approved platform/certificate owner must prepare the CSI +driver, Azure provider and OIDC issuer in **each member**, AKV network access, +and least-privilege secret-read permissions for the chosen identity (for +example, appropriately scoped Key Vault Secrets User with Azure RBAC, or +secret `get` under access policies). No certificate/key write access is needed. +Preconfigure one federated credential per member issuer, with audience +`api://AzureADTokenExchange` and exact subject: + +```text +system:serviceaccount::origin-serving +``` + +The namespace may be authorized before it exists. The fixture refuses existing +namespaces, creates the ServiceAccount/SPC itself in each member, and never +creates identities, role assignments, federated credentials, vaults or +certificates. Changing the namespace requires matching federation first. +It checks the CSI driver token-request audience and SPC CRD before creation; +a missing provider, failed mount, AKV denial or certificate failure is a failed +proof, never an identity/protocol/trust fallback. See the +[CSI Workload Identity prerequisites](https://azure.github.io/secrets-store-csi-driver-provider-azure/docs/configurations/identity-access-modes/workload-identity-mode/). +CSI requests ServiceAccount tokens natively; no application token injection or +Workload Identity pod label/ServiceAccount annotation is needed for CSI alone. + +Run `bash test/scripts/run-e2e.sh` only in the explicitly approved environment. +It selects the HTTPS label rather than relabelling or replacing the HTTP proof. +The workload has only an HTTPS listener and internal LB/PLS Service. Certificate +bytes are mounted read-only as `/tls/serving.pem` in member application pods, +using `objectType: secret`, `objectFormat: pem`, alias `serving.pem` and file +mode `0400`. This fixture's Python process runs as root; a non-root application +needs deliberately configured file ownership/access. There is no `secretObjects` +sync and no serving TLS Secret in any cluster. The hub receives no AKV identity +or CSI resource. The fixture never renders private material or changes/deletes +the AKV certificate. Retention mode is rejected; cleanup removes only the +namespaces created by this run and the owned Gateway/profile. + +Compile without live operations using +`go test -tags=e2e ./test/e2e -run '^$'`. This does **not** run the proof. +Offline configuration/mount tests are +`go test ./test/fixtures/origintls ./test/scripts`. Certificate validation tests +are `python3 -m unittest discover -s test/e2e/fixtures -p 'test_*.py' -v` +(Python 3 and OpenSSL required); generated local CA/certificates are disposable +unit-test data, never positive live fixtures. + +## What the first-party test owner must obtain + +| Fixture | Owner and required result | +|---|---| +| Client-facing hostname/certificate | Platform operator supplies the observed generated AFD HTTPS URL. Azure provides/renews its edge certificate; do not request an origin certificate for an `azurefd.net` name. | +| Origin SNI hostname | Test/DNS owner reserves a precise DNS name under an approved, controlled domain. `store-origin.example.com` is documentation only, not a name you can enroll. | +| Member 1 serving certificate/key | Approved certificate owner supplies a publicly trusted server certificate with that DNS SAN and its matching application-usable private key. | +| Member 2 serving certificate/key | This disposable fixture uses one approved AKV reference/identity with federation for each member issuer. Production applications should prefer separate member keys/identities for the same DNS identity. | +| Renewal and negative fixtures | Certificate/test owners plan permitted issuance, reload, rotation and isolated failure cases before the run. | + +Keep the public repository free of real tenant/subscription/service identifiers, +internal enrollment instructions, internal DNS names, certificate request +records, private keys, PFX files, rendered Secrets and credentials. Use the +authorized internal run record for actual identities, enrollment references, +owners and custody evidence; never record key material there either. + +## 1. Reserve an origin name, not a public application endpoint + +1. Ask the first-party service's DNS/certificate owner for a dedicated, + non-sensitive test name in an approved domain for the target cloud. Record + the owning service, authorized requester, renewal contact and retirement + date in the internal run record. +2. Obtain authorization to enroll that exact DNS SAN and to perform the + issuer's domain-control validation. Domain ownership, issuer authorization + and access to a member namespace are different permissions. +3. Use a publicly certifiable DNS name, not a Kubernetes `.svc` name, private + IP address, invented suffix or the generated AFD endpoint name. Public + certificate issuance can disclose the name through certificate transparency. +4. Arrange the approved domain-control validation method, such as DNS-based + validation where the issuer supports it. A public validation record does + not require exposing the application. Do not publish a public member + LoadBalancer or add a public origin to complete issuance. +5. Declare this same origin identity in a Service-targeted BackendTLSPolicy in + each member, with the proposed + `networking.fleet.azure.com/export-to-fleet: "true"` annotation. This opts into + Fleet export, not exclusive ownership by Fleet. Fleet transports validated + non-secret intent and generates the hub policy from current eligible-member + agreement and explicit verified exclusions. + The application actor touches + only members; no manual hub-policy apply or identity-change handoff is needed. + Platform Gateway/HTTPRoute still explicitly authorizes ingress. + +AFD's exact Private Link/PLS association supplies private connectivity. The +origin hostname supplies TLS SNI/name validation; neither a DNS record nor +domain enrollment alone proves that private path. Verify the supported +DNS/Private Link combination in the live test. + +## 2. Obtain an approved publicly trusted certificate + +### Can first-party testers use OneCert? + +**Only through an authorized enrollment path that issues an AFD-trusted public +server certificate.** Do not assume a certificate is suitable because it was +obtained through OneCert or is trusted on a corporate workstation. An internal +enterprise-CA chain is not a valid positive fixture for this proposal. + +The first-party certificate owner must use the current internal OneCert/domain +registration and enrollment runbooks to: + +1. Verify/register the controlled domain and authorize the owning service and + requesting identity for that namespace. +2. Select an approved public-CA server-TLS enrollment profile, not an internal + CA or client-authentication-only profile. Confirm the resulting root is + allowed by AFD's current trust requirements, not merely by local policy. +3. Request the exact DNS SAN, server-authentication use and an approved key + algorithm/size. For identity-rotation tests, prearrange certificates covering + both the old and new names in every participating member. +4. Choose approved key custody and workload delivery before enrollment. This + example application needs access to a usable certificate/private-key pair; + a downloadable public `.cer` file alone cannot configure its TLS server. +5. Complete issuer validation, retrieve the leaf/intermediate chain and arrange + authorized private-key delivery to the application. Record issuance, + expiry/renewal, delivery/reload and teardown owners. + +OneCert-specific portal URLs, issuer/profile identifiers and internal access +procedures are deliberately not reproduced in this public repository. Resolve +them with the service's certificate owner using the authoritative internal +runbook. If that path cannot supply a public chain or approved key delivery, +record the fixture as blocked; do not select an internal issuer or bypass +certificate checks just to make the test run. + +### Key Vault/CSR and key delivery considerations + +Use the organization's supported enrollment integration where available. For +an approved external-signing workflow, [Key Vault CSR creation and merge](https://learn.microsoft.com/azure/key-vault/certificates/create-certificate-signing-request) +supports generating a key/CSR, having the authorized CA sign it and merging +the signed chain back with the original key. A CSR/public certificate contains +no private key; sending a CSR to the approved issuer does not mean sending +the private key. A non-integrated issuer does not provide automatic renewal +merely because the certificate is stored in Key Vault. + +If policy permits export for this disposable fixture, authorize the member +Workload Identity to read the certificate's **backing secret**, not just the +public certificate. [Key Vault certificate export](https://learn.microsoft.com/azure/key-vault/certificates/how-to-export-certificate) +requires an exportable key and authorized secret access. The Azure CSI provider +retrieves and mounts the application-usable PEM private key and complete chain +inside each member; the E2E runner does not retrieve or convert it. +`objectType: cert` and `objectType: key` provide public components, not a usable +serving key pair. See [certificate components](https://azure.github.io/secrets-store-csi-driver-provider-azure/docs/configurations/getting-certs-and-keys/). +Non-exportable/HSM-backed keys cannot be made exportable by CSI. If export is +prohibited, mark this fixture blocked rather than weakening key policy or +giving Fleet controllers Key Vault/private-key access. + +## 3. Validate before deploying + +Before the run, the certificate owner verifies issuance, DNS SAN, server usage, +expiry and full chain against AFD's current allowed roots through the approved +certificate-management process. Do not export the key into the runner to do so. + +After CSI mounting, but **before binding its serving listener**, the Python +application loads the bundle and performs an in-memory server/client TLS +handshake using its system trust store, hostname verification with SAN rather +than CN fallback, and server-authentication checks. This verifies the actual +loaded key/chain without an external listener or copying it out of the pod. +It requires at least seven days remaining validity. Wrong name, bad trust, +missing/mismatched key, expired/near-expiry certificate or unsuitable server +usage prevents startup. There is no production custom-trust/verification bypass. +Pod-local trust is still a preflight, not proof of AFD trust; the real AFD +traffic/probe assertions remain required. + +This server loads the certificate only at startup. CSI autorotation can update +files but does not reload this process. Do not renew/change the selected version +during the basic proof; use an approved pinned version if repeatability is +required. Renewal/hot reload and the full negative matrix remain separate, +explicitly authorized exercises. + +## 4. Deploy and prove both TLS connections + +Prepare each member's application-only AKV CSI delivery, then +follow the [proposed customer setup](../docs/howtos/gateway-api-afd-configuration.md#proposed-setup-order). +The application actor needs only member credentials, including local policy +permissions. Fleet owns the generated hub BackendTLSPolicy; the platform operator +owns Gateway/HTTPRoute authorization and endpoint handoff. Require matching +current explicitly opted-in member policies and inspect source +provenance/projection ownership, complete source inventory and explicit exclusion +reasons/isolation evidence. Require exactly one applicable policy per eligible +member Service. Unmarked policies for other implementations must not be +implicitly exported but still count toward duplicate-target detection. +Test duplicate appearance/removal and opt-in removal separately from +certificate failures; Fleet must not choose a winner or delete extra policies. +Prove exact administrative origin isolation and healthy-member continuation +for local policy failures. No eligible members, conflicting otherwise-valid TLS +identities or unverifiable isolation require affected-route withdrawal. AFD +runtime certificate failures remain separate from controller-observed policy +errors; health-probe failure alone does not isolate an origin. +Do not copy the member key into the hub, AFD or public MCS fields. + +Before going through AFD, use the [private preflight](../docs/howtos/gateway-api-afd-configuration.md#useful-private-preflight-not-afd-proof) +from an authorized private client to check actual certificate presentation, +selected Service port and SNI/Host behavior. Then use the operator-supplied +generated hostname with normal verification: + +```bash +# AFD_HOSTNAME is supplied by the platform operator; no hub access is needed. +curl --verbose --fail-with-body --show-error --get \ + --data-urlencode "proof=$(date +%s)-${RANDOM}" \ + "https://${AFD_HOSTNAME}/" +``` + +Require edge certificate/name/chain verification plus correlated member +TLS/SNI/request logs, exact private bindings, HTTPS probes and both-member +responses. Client HTTPS alone does not prove origin TLS. Fresh HTTP requests +must not forward to the application. Do not use `-k`, replace AFD trust, +override client SNI/Host or manually repair an ARM graph to obtain a pass. +Record only sanitized public certificate metadata/fingerprints in evidence. + +## 5. Prepare rotation, failures and retirement + +| Fixture or operation | Preparation and guardrail | +|---|---| +| Same-name renewal | Obtain a second trusted AKV issuance/backing-secret version before expiry; update a pinned SPC or confirm CSI autorotation's mounted version, then reload/replace the application. Prove fresh AFD handshakes, not only pooled connections. | +| Origin-name rotation | Reserve/enroll the new name and deploy dual-name coverage everywhere, then update each member policy. Conflicting otherwise-valid identities withdraw the AFD route; after eligible agreement Fleet updates the hub projection automatically. Record exclusions and require fresh agreement before re-admission. Verify new SNI/traffic before retiring old coverage. | +| Wrong-name failure | Use a certificate for another authorized test name in an isolated fixture. Do not request someone else's identity. | +| Untrusted chain | Use a disposable local test CA only for the negative case; never add it as AFD trust or call it a positive fixture. | +| Expired certificate | Arrange an authorized retained expired test certificate/key or wait for an approved short-lived fixture to expire. Do not change clocks or attempt to backdate a public-CA issuance. | +| Incomplete chain | Use an isolated chain that demonstrably fails at AFD; cached/fetched intermediates can invalidate a naive negative test. | +| Cleanup | Collect sanitized evidence, have the operator withdraw hub routing, confirm no delivery and generated-policy reference cleanup, then retire member policies/workloads/SPCs/ServiceAccounts. The fixture deletes no AKV objects or external federation; owners retire dedicated grants/certificates separately within approved scope. Do not delete shared DNS, identities or issuers. | + +If a negative certificate cannot be obtained safely or a case is not executed, +report it as blocked/skipped rather than manufacturing a pass. Certificate +issuance and validation records remain in the approved internal run record, +not the public evidence bundle. + +## Public references + +- [AFD end-to-end TLS and certificate requirements](https://learn.microsoft.com/azure/frontdoor/end-to-end-tls?pivots=front-door-standard-premium) +- [AFD Private Link ILB identity and SNI](https://learn.microsoft.com/azure/frontdoor/standard-premium/how-to-enable-private-link-internal-load-balancer) +- [Key Vault certificate composition and exportability](https://learn.microsoft.com/azure/key-vault/certificates/about-certificates) diff --git a/test/scripts/afd_commands_test.go b/test/scripts/afd_commands_test.go index b58699f3..ff3933f0 100644 --- a/test/scripts/afd_commands_test.go +++ b/test/scripts/afd_commands_test.go @@ -25,6 +25,8 @@ import ( "k8s.io/apimachinery/pkg/util/yaml" ) +const enabled = "true" + func TestAFDCommandFailureStopsWork(t *testing.T) { tests := []struct { name, script, command, forbidden string @@ -57,6 +59,28 @@ func TestAFDCommandFailureStopsWork(t *testing.T) { } } +func TestHTTPSInstallationGrantsSchemaReadBeforeMemberUpgrade(t *testing.T) { + afdTestEnvironment(t) + log := installAFDCommandStubs(t) + t.Setenv("ENABLE_ORIGIN_TLS", enabled) + output, err := runAFDScript(t, "./install-afd.sh") + if err != nil { + t.Fatalf("TLS installation failed: %s: %v\n%s", output, err, readAFDFile(t, log)) + } + commands := readAFDFile(t, log) + for _, member := range []string{"member-1", "member-2"} { + binding := strings.Index(commands, "create clusterrolebinding fleet-origin-tls-schema-reader-"+member) + upgrade := strings.Index(commands, "helm upgrade member-net-controller-manager ./charts/member-net-controller-manager --kube-context "+member+"-admin") + if binding < 0 || upgrade < binding { + t.Fatalf("member enabled without hub schema read: %s", commands) + } + } + if strings.Count(commands, "--set enableOriginTLS=true") != 3 || + strings.Count(commands, "apply --server-side -f ") != 4 { + t.Fatalf("TLS prerequisites or capability flags missing: %s", commands) + } +} + func TestAFDBootstrapStopsBeforeAzureOnPreflightFailure(t *testing.T) { afdTestEnvironment(t) log := installAFDCommandStubs(t) @@ -93,7 +117,7 @@ func TestAFDRetainedSetupSignals(t *testing.T) { for _, signal := range []string{"INT", "TERM"} { t.Run(signal, func(t *testing.T) { afdTestEnvironment(t) - t.Setenv("RETAIN_AFD_E2E_SETUP", "true") + t.Setenv("RETAIN_AFD_E2E_SETUP", enabled) script := "cleanup() { echo 'unexpected deletion'; }\n" + start + block + "\nfi\nkill -s " + signal + " $$\necho 'unexpected continuation'\n" output, err := runAFDScript(t, "-ec", script) @@ -243,7 +267,7 @@ func TestAFDRenderedInstallation(t *testing.T) { // This optional, offline check consults installed command help; it never invokes Azure operations. func TestAFDInstalledAzureCLIOptions(t *testing.T) { - if os.Getenv("AFD_VALIDATE_LOCAL_TOOLS") != "true" { + if os.Getenv("AFD_VALIDATE_LOCAL_TOOLS") != enabled { t.Skip("Set AFD_VALIDATE_LOCAL_TOOLS=true to check installed Azure CLI command/option metadata") } afdTestEnvironment(t) @@ -292,7 +316,7 @@ func TestAFDInstalledAzureCLIOptions(t *testing.T) { func installAFDCommandStubs(t *testing.T) string { t.Helper() - t.Setenv("ENABLE_AZURE_FRONT_DOOR", "true") + t.Setenv("ENABLE_AZURE_FRONT_DOOR", enabled) t.Setenv("AFD_TEST_MANAGED_BY", "member-1") log := filepath.Join(t.TempDir(), "commands") t.Setenv("AFD_TEST_COMMAND_LOG", log) @@ -409,7 +433,8 @@ fi const afdKubectlStub = `#!/bin/bash set -euo pipefail printf 'kubectl %s\n' "$*" >>"$AFD_TEST_COMMAND_LOG" -[[ "$1" == --context && "$2" == hub-admin ]]; shift 2 +[[ "$1" == --context && "$2" =~ ^(hub|member-[12])-admin$ ]] +context="$2"; shift 2 namespace="" if [[ "$1" == --namespace ]]; then namespace="$2"; shift 2; fi verb="$1" @@ -417,11 +442,25 @@ if [[ "${AFD_TEST_FAIL_COMMAND:-}" == "kubectl $verb" ]]; then echo "injected CLI failure: kubectl $verb" >&2; exit 23 fi case "$*" in + "apply --server-side -f "*gateway.networking.k8s.io_backendtlspolicies.yaml) + [[ -z "$namespace" && -f "$4" ]] ;; + "apply --server-side -f ./config/crd/bases/networking.fleet.azure.com_internalserviceexports.yaml") + [[ "$context" == hub-admin && -f "../../${4#./}" ]] ;; + "wait --for=condition=Established --timeout=60s crd/backendtlspolicies.gateway.networking.k8s.io") + [[ -z "$namespace" ]] ;; + "wait --for=condition=Established --timeout=60s crd/internalserviceexports.networking.fleet.azure.com") + [[ "$context" == hub-admin ]] ;; + "create clusterrole fleet-origin-tls-schema-reader --verb=get --resource=customresourcedefinitions.apiextensions.k8s.io --resource-name=internalserviceexports.networking.fleet.azure.com --dry-run=client -o yaml") + [[ "$context" == hub-admin ]] + printf '{"kind":"ClusterRole","metadata":{"name":"fleet-origin-tls-schema-reader"}}\n' ;; + "create clusterrolebinding fleet-origin-tls-schema-reader-member-"*) + [[ "$context" == hub-admin && "$*" == *"--clusterrole=fleet-origin-tls-schema-reader --user=member-"*"-principal --dry-run=client -o yaml" ]] + printf '{"kind":"ClusterRoleBinding","metadata":{"name":"tls-schema-reader-fixture"}}\n' ;; "create namespace fleet-system --dry-run=client -o yaml") [[ -z "$namespace" ]] printf '{"apiVersion":"v1","kind":"Namespace","metadata":{"name":"fleet-system"}}\n' ;; "apply -f -") - jq -e '(.kind == "Namespace" or .kind == "Secret") and .metadata.name != null' >/dev/null ;; + jq -e '(.kind == "Namespace" or .kind == "Secret" or .kind == "ClusterRole" or .kind == "ClusterRoleBinding") and .metadata.name != null' >/dev/null ;; *) [[ "$namespace" == fleet-system && $# == 8 && "$1 $2 $3 $4" == "create secret generic afd-cloud-config" && diff --git a/test/scripts/afd_test.go b/test/scripts/afd_test.go index e0c4ee23..1b0b881a 100644 --- a/test/scripts/afd_test.go +++ b/test/scripts/afd_test.go @@ -176,6 +176,85 @@ func TestAFDStandardTestCommand(t *testing.T) { } } +func TestHTTPSProofRequiresSeparateOptIn(t *testing.T) { + tests := []struct { + name, proof, capability, retention, afd string + fails bool + }{ + {"default stays off", "", "", "", "true", false}, + {"explicit HTTPS", "true", "", "", "true", false}, + {"cannot disable required capability", "true", "false", "", "true", true}, + {"cannot retain key fixtures", "true", "", "true", "true", true}, + {"requires AFD", "true", "", "", "false", true}, + {"invalid opt-in", "yes", "", "", "true", true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + afdTestEnvironment(t) + t.Setenv("ENABLE_AZURE_FRONT_DOOR", tt.afd) + t.Setenv("ENABLE_AFD_PRIVATE_HTTPS_PROOF", tt.proof) + t.Setenv("ENABLE_ORIGIN_TLS", tt.capability) + t.Setenv("RETAIN_AFD_E2E_SETUP", tt.retention) + for key, value := range httpsCSIEnvironment() { + t.Setenv(key, value) + } + bin := t.TempDir() + writeAFDCommand(t, filepath.Join(bin, "go"), "#!/bin/bash\nprintf 'go %s\\n' \"$*\"\n") + t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH")) + output, err := runAFDScript(t, "./run-e2e.sh") + if (err != nil) != tt.fails { + t.Fatalf("HTTPS selection failed: %s %v", output, err) + } + + if tt.fails { + return + } + httpsSelected := strings.Contains(output, "-ginkgo.label-filter=afd-private-https-proof") + if httpsSelected != (tt.proof == "true") { + t.Fatalf("HTTP and HTTPS proof selection mixed: %s", output) + } + }) + } +} + +func httpsCSIEnvironment() map[string]string { + return map[string]string{ + "ORIGIN_TLS_NAMESPACE": "https-proof-script", "ORIGIN_TLS_HOSTNAME": "origin.example.com", + "ORIGIN_AKV_NAME": "fixture-vault", "ORIGIN_AKV_CERT_NAME": "serving-certificate", + "ORIGIN_AKV_TENANT_ID": "11111111-1111-1111-1111-111111111111", + "ORIGIN_AKV_CLIENT_ID": "22222222-2222-2222-2222-222222222222", + } +} + +func TestHTTPSProofRequiresCSIReferencesBeforeRunningCommands(t *testing.T) { + type testCase struct{ name, key, value string } + tests := make([]testCase, 0, len(httpsCSIEnvironment())+2) + for key := range httpsCSIEnvironment() { + tests = append(tests, testCase{"missing " + key, key, ""}) + } + tests = append(tests, + testCase{"reject runner key", "ORIGIN_KEY_FILE", "/tmp/key.pem"}, + testCase{"reject runner chain", "ORIGIN_CERT_CHAIN_FILE", "/tmp/chain.pem"}) + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + afdTestEnvironment(t) + t.Setenv("ENABLE_AZURE_FRONT_DOOR", "true") + t.Setenv("ENABLE_AFD_PRIVATE_HTTPS_PROOF", "true") + for key, value := range httpsCSIEnvironment() { + t.Setenv(key, value) + } + t.Setenv(tt.key, tt.value) + bin := t.TempDir() + writeAFDCommand(t, filepath.Join(bin, "go"), "#!/bin/bash\necho unexpected-go-command\n") + t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH")) + output, err := runAFDScript(t, "./run-e2e.sh") + if err == nil || !strings.Contains(output, "error:") || strings.Contains(output, "unexpected-go-command") { + t.Fatalf("invalid CSI inputs reached the runner: %v %s", err, output) + } + }) + } +} + func TestAFDRetainedDiagnostic(t *testing.T) { tests := []struct { name, retention, enabled, script, want string @@ -371,6 +450,10 @@ func afdTestEnvironment(t *testing.T) { "ENABLE_TRAFFIC_MANAGER", "ENABLE_AZURE_FRONT_DOOR", "ENABLE_GATEWAY_API", "ENABLE_AFD_PRIVATE_HTTP_PROOF", "AFD_PROOF_CONTROLLER_IMAGE", "REGISTRY", "ENABLE_AFD_PRIVATE_LINK_AUTO_APPROVAL", + "ENABLE_AFD_PRIVATE_HTTPS_PROOF", "ENABLE_ORIGIN_TLS", + "ORIGIN_TLS_NAMESPACE", "ORIGIN_TLS_HOSTNAME", "ORIGIN_AKV_NAME", "ORIGIN_AKV_CERT_NAME", + "ORIGIN_AKV_CERT_VERSION", "ORIGIN_AKV_TENANT_ID", "ORIGIN_AKV_CLIENT_ID", + "ORIGIN_CERT_CHAIN_FILE", "ORIGIN_KEY_FILE", "RETAIN_AFD_E2E_SETUP", "HUB_CLUSTER", "MEMBER_CLUSTER_1", "MEMBER_CLUSTER_2", "HUB_GATEWAY_CONTROLLER_MANAGER_IMAGE_NAME", "HUB_GATEWAY_CONTROLLER_MANAGER_IMAGE_VERSION", diff --git a/test/scripts/e2e-config.sh b/test/scripts/e2e-config.sh index 5394ee0a..816948f1 100644 --- a/test/scripts/e2e-config.sh +++ b/test/scripts/e2e-config.sh @@ -2,9 +2,40 @@ export ENABLE_TRAFFIC_MANAGER="${ENABLE_TRAFFIC_MANAGER:-false}" export ENABLE_AZURE_FRONT_DOOR="${ENABLE_AZURE_FRONT_DOOR:-false}" +export ENABLE_AFD_PRIVATE_HTTPS_PROOF="${ENABLE_AFD_PRIVATE_HTTPS_PROOF:-false}" +export ENABLE_ORIGIN_TLS="${ENABLE_ORIGIN_TLS:-$ENABLE_AFD_PRIVATE_HTTPS_PROOF}" export RETAIN_AFD_E2E_SETUP="${RETAIN_AFD_E2E_SETUP:-false}" export AZURE_NETWORK_SETTING="${AZURE_NETWORK_SETTING:-shared-vnet}" +for flag in "$ENABLE_ORIGIN_TLS" "$ENABLE_AFD_PRIVATE_HTTPS_PROOF"; do + if [[ "$flag" != true && "$flag" != false ]]; then + echo "error: TLS capability and proof opt-ins must be true or false" >&2 + return 1 + fi +done +if [[ "$ENABLE_ORIGIN_TLS" == true && "$ENABLE_AZURE_FRONT_DOOR" != true ]]; then + echo "error: ENABLE_ORIGIN_TLS requires ENABLE_AZURE_FRONT_DOOR=true" >&2 + return 1 +fi +if [[ "$ENABLE_AFD_PRIVATE_HTTPS_PROOF" == true && + ( "$ENABLE_ORIGIN_TLS" != true || "$RETAIN_AFD_E2E_SETUP" == true ) ]]; then + echo "error: HTTPS proof requires TLS capability and does not support retained secret fixtures" >&2 + return 1 +fi +if [[ "$ENABLE_AFD_PRIVATE_HTTPS_PROOF" == true ]]; then + for required in ORIGIN_TLS_NAMESPACE ORIGIN_TLS_HOSTNAME ORIGIN_AKV_NAME \ + ORIGIN_AKV_CERT_NAME ORIGIN_AKV_TENANT_ID ORIGIN_AKV_CLIENT_ID; do + if [[ -z "${!required:-}" ]]; then + echo "error: HTTPS CSI proof requires ${required}" >&2 + return 1 + fi + done + if [[ -n "${ORIGIN_CERT_CHAIN_FILE:-}" || -n "${ORIGIN_KEY_FILE:-}" ]]; then + echo "error: runner-local certificate inputs are unsupported; use the AKV CSI fixture" >&2 + return 1 + fi +fi + if [[ "$ENABLE_AZURE_FRONT_DOOR" != true && "$ENABLE_AZURE_FRONT_DOOR" != false ]]; then echo "error: ENABLE_AZURE_FRONT_DOOR must be true or false" >&2 return 1 diff --git a/test/scripts/install-afd.sh b/test/scripts/install-afd.sh index 35b43101..58036d51 100644 --- a/test/scripts/install-afd.sh +++ b/test/scripts/install-afd.sh @@ -8,6 +8,26 @@ source "$(dirname "${BASH_SOURCE[0]}")/e2e-config.sh" if [[ "$ENABLE_AZURE_FRONT_DOOR" != true ]]; then exit 0 fi +if [[ "$ENABLE_ORIGIN_TLS" == true ]]; then + kubectl --context hub-admin apply --server-side \ + -f ./config/crd/bases/networking.fleet.azure.com_internalserviceexports.yaml + kubectl --context hub-admin wait --for=condition=Established --timeout=60s \ + crd/internalserviceexports.networking.fleet.azure.com + policy_crd="$(go list -m -f '{{.Dir}}' sigs.k8s.io/gateway-api)/config/crd/experimental/gateway.networking.k8s.io_backendtlspolicies.yaml" + if [[ ! -f "$policy_crd" ]]; then + echo "error: pinned experimental BackendTLSPolicy CRD is missing" >&2 + exit 1 + fi + for context in hub-admin member-1-admin member-2-admin; do + kubectl --context "$context" apply --server-side -f "$policy_crd" + kubectl --context "$context" wait --for=condition=Established --timeout=60s \ + crd/backendtlspolicies.gateway.networking.k8s.io + done + kubectl --context hub-admin create clusterrole fleet-origin-tls-schema-reader \ + --verb=get --resource=customresourcedefinitions.apiextensions.k8s.io \ + --resource-name=internalserviceexports.networking.fleet.azure.com --dry-run=client -o yaml | + kubectl --context hub-admin apply -f - +fi tenant="$(az account show --subscription "$AZURE_SUBSCRIPTION_ID" --query tenantId -o tsv)" cloud_config() { @@ -67,9 +87,14 @@ for member in member-1 member-2; do --assignee-object-id "$principal" --assignee-principal-type ServicePrincipal \ --scope "/subscriptions/$AZURE_SUBSCRIPTION_ID/resourceGroups/$node_group" >/dev/null config="$(cloud_config "$client" "$node_group" "$location")" + if [[ "$ENABLE_ORIGIN_TLS" == true ]]; then + kubectl --context hub-admin create clusterrolebinding "fleet-origin-tls-schema-reader-$member" \ + --clusterrole=fleet-origin-tls-schema-reader --user="$principal" --dry-run=client -o yaml | + kubectl --context hub-admin apply -f - + fi helm upgrade member-net-controller-manager ./charts/member-net-controller-manager \ --kube-context "$member-admin" --namespace default --reuse-values \ - --set enablePrivateLinkOriginDiscovery=true --set-json "azureCloudConfig=$config" \ + --set enablePrivateLinkOriginDiscovery=true --set "enableOriginTLS=$ENABLE_ORIGIN_TLS" --set-json "azureCloudConfig=$config" \ --wait --timeout 10m done @@ -90,5 +115,5 @@ helm install hub-gateway-controller-manager ./charts/hub-gateway-controller-mana --set-string "serviceAccount.name=$AFD_PROOF_CONTROLLER_DEPLOYMENT" \ --set-string "image.repository=${AFD_PROOF_CONTROLLER_IMAGE%:*}" \ --set-string "image.tag=${AFD_PROOF_CONTROLLER_IMAGE##*:}" \ - --set afd.enabled=true --set-string "afd.resourceGroup=$AZURE_RESOURCE_GROUP" \ + --set afd.enabled=true --set "enableOriginTLS=$ENABLE_ORIGIN_TLS" --set-string "afd.resourceGroup=$AZURE_RESOURCE_GROUP" \ --set afd.cloudConfigSecret.name=afd-cloud-config --wait --timeout 10m diff --git a/test/scripts/run-e2e.sh b/test/scripts/run-e2e.sh index 9ed2bdb6..d30ee482 100644 --- a/test/scripts/run-e2e.sh +++ b/test/scripts/run-e2e.sh @@ -7,6 +7,9 @@ set -o pipefail source "$(dirname "${BASH_SOURCE[0]}")/e2e-config.sh" if [[ "$ENABLE_AZURE_FRONT_DOOR" == true ]]; then + if [[ "$ENABLE_AFD_PRIVATE_HTTPS_PROOF" == true ]]; then + exec go test -count=1 -timeout 10h -tags=e2e -v ./test/e2e -args -ginkgo.v -ginkgo.timeout=9h30m -ginkgo.label-filter=afd-private-https-proof + fi if [[ "$RETAIN_AFD_E2E_SETUP" == true ]]; then echo "AFD retained diagnostic: withdrawal and cleanup are not run; resources require explicit later cleanup." exec go test -count=1 -timeout 10h -tags=e2e -v ./test/e2e -args -ginkgo.v -ginkgo.timeout=9h30m -ginkgo.label-filter=afd-private-http-proof