Studio Step 2: N sign-in chooser entries and an egress-guarded issuer probe (epic &119)

Status: Done (2026-09-27) — !1519
Issues: #568, #570 (epic &119)
Branches: feat/119-studio-step2 (carries this page)

This is a Design + Scope plan. GitLab owns tracking. The plan freezes when U-A starts. It ships as one MR with one battery, because both units restructure the same Step-2 form and template.

Erratum (2026-09-27): D4 as built renders Remove only when there is more than one entry and Add only below MAX_IDP_ENTRIES (a hint replaces it at the limit); the handler still guards both bounds.

Erratum (2026-09-27): D9’s always-refused metadata endpoints also include GCP’s IPv6 metadata address fd20:ce::254 (IPv6-only instances; GCP documentation, retrieved 2026-09-27), and the RFC 8215 local-use NAT64 prefix 64:ff9b:1::/48 is classified private, because its embedded IPv4 follows an operator-chosen layout.

Context

  • Step 2 authors one chooser entry.

    • WizardDraft (services/canopy-web/src/studio/wizard.rs ~57-88) holds idp_slug, idp_label, idp_chip_color, idp_chip_icon, idp_domain_match and idp_authorize_params. It is stored only in the tower-sessions session (SESSION_KEY, ~91-110).

    • The form is parsed as Form<HashMap<String, String>> (~327), so repeated keys collapse. Step 4 already uses indexed names (programs_{slug}).

    • bundle.rs render_idp_toml passes idps: vec![idp_entry] (~311-329), and the round-trip test asserts one entry (~836).

  • Studio is stricter than the runtime, and loses input.

    • validate_idp_domain_match requires at least one suffix (validation.rs ~250-271). The runtime allows an empty list: a chooser-only entry (crates/canopy-composition/src/idp.rs ~101-104).

    • A 422 re-renders the domain and authorize-param textareas from the parsed draft. Input that failed to parse is therefore wiped (wizard.rs ~510-518, ~638-654).

  • The runtime rules for many entries: slugs are unique (SlugDuplicate); domain_match is first match in declaration order; a single entry skips the chooser (single_idp()); zero entries refuse canopy-web’s boot (IdpRuntimeError::NoIdpEntries).

  • No probe is possible today.

    • Discovery fetches go through a process-global cache keyed by the raw input, with no eviction and no body cap (crates/canopy-auth/src/discovery.rs ~195-325). OidcDiscovery is #[serde(default)], so {} parses.

    • canopy-web’s shared client follows redirects and has no destination policy (services/canopy-web/src/main.rs ~265-269).

    • cargo xtask identity verify does not check the issuer binding or the exchange-grant advertisement, and its code is private to xtask.

    • htmx 2 swaps no 4xx response unless the target carries data-swap-errors or the response is a marked denial (services/canopy-web/static/js/canopy-web.js ~66-86).

Rulings in force:

  • This must work in every jurisdiction without code changes.

  • Pre-1.0 has no compatibility shims.

  • ADR-048: one trusted issuer, deployment-configured.

  • Startup-guard doctrine (security-operations.adoc ~146): default-refuse outside CANOPY_ENV=development; an environment-only override accepting the literal true (canopy_common::env::override_flag_is_true); a WARN whenever the override is exercised.

Scope

In scope: D1–D10.

Out of scope (GitLab follow-ups, linked from the closing comment):

  • chain-auditing Studio actions (the bundle download and the probe);

  • cargo xtask identity verify adopting the probe’s checks, which would add its missing issuer-binding and exchange-grant rows;

  • a streaming body cap for introspection and the token exchanger, which today buffer a chunked body before comparing;

  • the wizard collecting [identity].validation and [identity.introspection].

Pre-existing defects, each filed as a fix: issue:

  • every step’s first submit button is Cancel, so Enter in any field cancels the wizard (the new probe_* fields inherit it);

  • a failed resubmit of an earlier step still saves, and the bundle is then built from the invalid draft.

Design

Decisions

# Decision

D1

The epic, restated after &118.

  • #568 becomes N chooser entries at the one issuer.

  • #570 becomes a probe of a candidate issuer against the drafted [identity]: "will this pack boot against that issuer?" It runs the checks boot runs, plus JWKS readiness.

  • The probed URL is never written to the draft or the bundle, because the issuer stays deployment configuration (ADR-048).

  • The probe is per issuer, not per entry. It lives in the identity fieldset.

D2

Draft model.

  • WizardDraft replaces the six idp_* fields with idps: Vec<IdpDraftEntry>.

  • IdpDraftEntry holds slug, label, chip_color, chip_icon, domain_match: Vec<String> and authorize_params: BTreeMap<String, String>.

  • MAX_IDP_ENTRIES = 16. The chooser is a list of chips, and the bound caps form size.

  • A session draft in the old shape fails to deserialize, and load falls back to an empty draft (the existing warning path). There is no migration.

  • Step 2 over an empty idps renders one blank entry with idp_count=1.

  • The dead Step2Form struct, whose shape this changes, is deleted.

D3

Form encoding.

  • Entries are indexed: idp_{i}_slug, idp_{i}_label, idp_{i}_chip_color, idp_{i}_chip_icon, idp_{i}_domain_match, idp_{i}_authorize_params.

  • A hidden idp_count field must lie in 1..=MAX_IDP_ENTRIES, and every index below it must be present. A missing index is a field error, never a silently dropped entry.

  • Field errors are keyed by the indexed name.

  • The parser adds no unwrap_or_default call (quality budget B5 can only fall): a missing key is matched explicitly.

D4

Add and remove without a new default button.

  • Each entry has a "Remove" control, and the list ends with "Add a sign-in choice". Both are type="button", so they never become the form’s default (implicit-submission) button.

  • Each control carries hx-post="/studio/onboarding/step/2/entries", hx-include="closest form", hx-vals naming the op (add | remove) and index, hx-target on the entries container, and hx-swap="outerHTML".

  • The handler takes StudioAdminOnly and no State<AppState>. It parses the submitted entries leniently: raw strings, no validation, nothing written to the session. It applies the op (add appends an empty entry up to the maximum; remove never drops below one) and renders the entries partial, re-indexed, with 200. A malformed op or out-of-range index is 400; the page never sends one.

  • No edit is lost to a pending swap. Every entries control carries hx-sync="closest form:drop" (a second add or remove in flight is dropped) and hx-disabled-elt naming the entries fieldset and the Next button (nothing is editable or submittable while a replacement is pending).

    • The implementer confirms in htmx 2.0.8’s source that request parameters are collected before hx-disabled-elt disables anything. Disabled inputs are not submitted, so if collection comes second, the disable moves to an htmx:beforeSend listener in services/canopy-web/static/js/canopy-web.js.

  • CSRF rides in the form’s _csrf field, which hx-include carries (csrf_middleware reads it).

  • This is CSP-clean: no inline script, and htmx is already loaded by base.html. Without JavaScript the one-entry path still works; adding an entry needs htmx.

D5

Validation across entries, and input kept on error.

  • Each entry keeps today’s validators. domain_match may now be empty, meaning a chooser-only entry, as the runtime allows; the template drops required.

  • Across entries:

    • slugs are unique;

    • the same domain suffix may not appear on two entries, because the later entry could never match it;

    • there is at least one entry and at most MAX_IDP_ENTRIES.

  • A 422 re-renders every entry from the operator’s submitted text, textareas included.

D6

Bundle and review.

  • render_idp_toml emits every entry, in order.

  • Its header comment says that entries are chooser entries at the one issuer, that the first matching domain_match routes email discovery, and that a single entry skips the chooser.

  • Step 5 lists every entry.

D7

The probe surface.

  • The identity fieldset gains a "Test an issuer" group: probe_issuer (required to probe), probe_internal_url (optional; discovery is fetched from it, and the document must still name probe_issuer, as fetch_trusted_issuer does), a type="button" control that hx-posts to POST /studio/onboarding/step/2/probe with hx-include="closest form", and a result region.

  • The handler takes StudioAdminOnly, Extension<IssuerProbeClient> and Extension<ProbeLimiter> (D10), and no State<AppState>. It builds the drafted IdentityConfig through validation::validate_identity. An invalid draft reports "fix the identity table first" and makes no network call.

  • Statuses: every executed probe renders its result with 200 (passed, failed, or identity invalid). Only the throttle answers 429. The result region carries data-swap-errors so the 429 fragment is swapped in.

  • apply_step2 never reads probe_*. WizardDraft has no probe field.

D8

The probe’s checks, in a new crates/canopy-auth/src/issuer_probe.rs.

  • probe(client: &GuardedClient, issuer, internal_url, contract) → IssuerProbeReport. It runs in order and stops at the first failure:

    1. the inputs: issuer and internal_url are trimmed of surrounding whitespace, parsed as url::Url, and refused (InvalidUrl) with a query, a fragment or userinfo;

    2. discovery: the fetch base is internal_url, else issuer. The discovery URL appends the segments with path_segments_mut().pop_if_empty().extend([".well-known", "openid-configuration"]), so an issuer with a path (the devstack’s …/realms/canopy) keeps it. Never Url::join, never concatenation. The fetch is uncached, and the document is parsed as OidcDiscovery;

    3. the advertised issuer equals the trimmed input string exactly, not the parsed Url (which would add a / to a bare host). The comparison reuses require_issuer, made pub(crate);

    4. the RFC 8693 grant is advertised (require_token_exchange);

    5. authorization_endpoint, token_endpoint and jwks_uri are absolute URLs with a host and the https scheme; http is accepted in development only. Anything else (ftp:, mailto:, empty) is UnusableEndpoint(name);

    6. the JWKS is fetched through the same GuardedClient (so the document-supplied jwks_uri passes the same checks) and parsed as a JwkSet. At least one key must be usable, meaning all three hold, as runtime validation requires (jwks.rs ~646):

      • it carries a kid;

      • DecodingKey::from_jwk builds it;

      • jwks::bind_algorithm binds it under some algorithm in contract.algorithms().

  • IssuerProbeReport carries the outcome (Passed or Failed(ProbeFailure)) and the facts gathered so far: the advertised issuer, jwks_uri, whether the grant and an introspection_endpoint are advertised, the key count and the usable-key count.

  • ProbeFailure is typed:

    • input: InvalidUrl;

    • transport: the GuardedClient's EgressFetchError (D9), tagged with the hop (discovery or JWKS), plus NotJson;

    • document: IssuerMismatch { advertised }, NoTokenExchange, UnusableEndpoint(name), NoUsableKey.

  • Raw error text and response bodies never reach the report.

  • The page renders each failure as an actionable sentence, escaped by Askama. This covers #570’s four states (success, discovery 404, TLS error, iss mismatch) and more.

D9

The egress guard (the SSRF decision): canopy_common::http::egress, added as pub mod egress; in crates/canopy-common/src/http.rs with the body in http/egress.rs (the crates/canopy-common/src/chain_verify.rs + crates/canopy-common/src/chain_verify/ layout).

  • Address classes, decided in this order:

    1. :: is always refused and ::1 is loopback, both decided before any extraction (so ::1 is never read as the compatible form of 0.0.0.1);

    2. the metadata endpoints 169.254.169.254, fd00:ec2::254 (AWS IPv6) and 100.100.100.200 (Alibaba) are always refused, decided before the private ranges that would otherwise admit the last two;

    3. the embedded IPv4 address of ::ffff:0:0/96 (mapped), ::/96 (compatible), 64:ff9b::/96 (NAT64) and 2002::/16 (6to4) is extracted and classified as IPv4;

    4. the table below.

      class ranges admitted when

      always refused

      the metadata endpoints above, 0.0.0.0/8, 169.254.0.0/16 (link-local), 224.0.0.0/4, 240.0.0.0/4 (reserved, including broadcast), 192.0.2.0/24, 198.51.100.0/24, 203.0.113.0/24, ::, fe80::/10, ff00::/8, 2001:db8::/32

      never: no issuer is served from them, and link-local is where metadata services live

      loopback

      127.0.0.0/8, ::1

      development only

      private

      10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, 100.64.0.0/10 (shared CGNAT), 198.18.0.0/15, fc00::/7

      development, or under the override

      public

      everything else

      always

  • Policy. EgressPolicy { development: bool, allow_private: bool }, with admits(scheme, class) deciding each address for the request’s scheme:

    • development (canopy_common::env::is_development): every class except "always refused", over http or https. The devstack issuer is http://host.docker.internal:<port>;, an RFC 1918 address.

    • outside development: public addresses over https only;

    • CANOPY_WEB__ALLOW_PRIVATE_ISSUER_PROBE=true (a RESERVED_KEYS entry, read by override_flag_is_true) adds private addresses over http or https. An in-cluster internal URL (http://keycloak:8080/…) is private, while plain http to a public address stays refused. The deployment owns that risk; each probe that reaches a private address under the override logs WARN naming the class.

  • Resolve, vet, pin. A reqwest resolver sees only the host, not the scheme, so it cannot apply a scheme-dependent rule. The guard therefore resolves and vets addresses itself, per request, and pins the connection to them.

    GuardedClient { policy, lookup, connect_timeout, total_timeout } in canopy_common::http::egress. get_capped(&Url, limit) → Result<Bytes, EgressFetchError>: .. checks the scheme (http or https only); .. takes the host’s addresses: an IP-literal host is its own single address; a name is resolved through lookup. lookup is the system resolver (tokio::net::lookup_host) in production and a fixed-answer lookup in tests; .. classifies every address and calls admits(scheme, class). Any refused answer refuses the fetch, so mixed public and private answers never connect; .. sends the request on a one-shot client built with resolve_to_addrs(host, vetted), a deny-all dns_resolver (no other name can resolve), redirect::Policy::none(), no_proxy() and the timeouts. The connection can reach only the vetted addresses, which closes DNS rebinding, while TLS still verifies the hostname; .. streams the body with a running total, so a chunked body is refused at the cap rather than buffered.

    + The timeouts are constructor parameters (the build_data_path_client precedent), so tests need not wait 5 s. A client per probe is cheap at the throttled rate.

  • EgressFetchError is typed: Refused { class } and Dns, both decided before any request; then Tls, Timeout, Connect, Redirect(status), Status(status) and TooLarge. A reqwest error is classified as TLS (a rustls::Error reached through std::io::Error::get_ref, since io::Error::source skips it), then timeout, then connect. canopy-common gains a direct rustls dependency (version = "0.23", default-features = false, added to the workspace) for that downcast.

  • The discovery and JWKS hops both run through get_capped with a 64 KiB cap. That is the house cap (introspection.rs RESPONSE_BODY_CAP), which fits dozens of RSA keys.

  • canopy-web builds IssuerProbeClient(GuardedClient) at boot (connect 2 s, total 5 s) and layers it as its own Extension, so it cannot displace the shared OIDC client.

D10

Throttle and log.

  • The quota holds across replicas: 6 probes per studio admin per 60 s fixed window, keyed studio-probe:{subject}.

    • canopy_api::ratelimit gains a public keyed check, SharedKeyedLimiter: the module’s ADR-026 atomic fixed window over the BFF’s rate-limit Redis (RATE_LIMIT_REDIS_URL), with the module’s unavailability posture (a process-local governor fallback, never unlimited, never blocked; bounded by CHECK_BUDGET; keyed state swept). The per-IP layer is unchanged.

    • It is built at boot and layered as Extension<ProbeLimiter>. Over the limit, a 429 fragment asks the admin to wait.

  • Each probe logs info with the admin’s subject, the target host and port, and the outcome category. The URL path and response content are never logged.

Invariants

  • No probed URL reaches the draft, the bundle or idp.toml.

  • The probe never fetches an "always refused" address. Outside development it fetches no loopback address, no private address unless the accountable override is set, and no public address over plain http.

  • The probe connects only to addresses it vetted for that request’s scheme, and never follows a redirect.

  • A probe’s usable key is one runtime validation could use.

  • No response body or raw transport error reaches the page or the log.

  • The bundle’s idp.toml round-trips through IdpDocument::parse for any 1..=16 entries.

Units — U-A → U-C, one MR

Commit 1 is docs(plans): plan the Studio Step 2 entries and issuer probe (&119). The last is docs(plans): close the Studio Step 2 plan (&119).

U-A (w5) — feat(web): author N sign-in chooser entries in Studio (#568)

Files:

  • services/canopy-web/src/studio/{wizard,validation,bundle}.rs (the new handler is pub(crate) in wizard.rs, registered in its routes());

  • templates/studio/_wizard_body_step2.html, a new _wizard_step2_entries.html partial, and _wizard_body_step5.html;

  • a new services/canopy-web/src/studio/step2_route_tests.rs (#[cfg(test)]);

  • xtask/src/cmd/route_authz.rs:

    • EXPECTED_MUTATING_TOTAL goes from 83 to 84, and its canary comment’s Studio count from 2 to 3;

    • a SCOPE_POLICY row NotProgramScoped(STUDIO_REASON) for the handler;

    • policy_for is unchanged, since it keys on the registering file (studio/wizard.rs, already StudioAdminOnly);

  • tests/e2e/specs/studio-onboarding.spec.ts.

Tests:

  • Indexed parsing: count bounds, a missing index, and re-indexing after a remove.

  • A proptest: the parser never panics on arbitrary form maps, and entries → form → entries is the identity.

  • Cross-entry uniqueness of slugs and of domain suffixes.

  • An empty domain_match is accepted. This legitimately rewrites domain_match_requires_at_prefix's empty-list assertion; the commit says why.

  • A 422 keeps the raw textarea input.

  • Routed tests in step2_route_tests.rs, following auth/validation_error_tests.rs: a Router with the handler, the session and CSRF layers, and a seeded studio-admin session. They cover add and remove at the bounds, and a 403 for a non-admin.

  • A proptest: render_idp_toml over 1..=16 generated valid entries round-trips through IdpDocument::parse, with order and fields kept.

  • Fixtures that move to idps: wizard_draft_serializes_roundtrip, bundle.rs make_draft, and the e2e spec’s flat idp_* posts.

  • e2e: add two entries with the control, fill them, and see the review list three and the bundle’s idp.toml hold three . A duplicate slug gives 422 through postStep.

  • e2e, delayed response: page.route holds the entries response. While it is pending, the entries fieldset and Next are disabled and a second control’s click sends nothing. After release, a field edited before the click keeps its value.

U-B (w5) — feat(web,auth): probe a candidate issuer from Studio (#570)

Files:

  • crates/canopy-common/src/http.rs (pub mod egress;) and http/egress.rs (new); the workspace and canopy-common Cargo.toml (rustls);

  • crates/canopy-auth/src/issuer_probe.rs (new) and discovery.rs (require_issuer becomes pub(crate));

  • canopy-web:

    • studio/wizard.rs (the probe handler, pub(crate), registered in routes()),

    • a new studio/probe.rs (the limiter and result rendering),

    • main.rs (IssuerProbeClient, ProbeLimiter),

    • config.rs (RESERVED_KEYS),

    • the Step-2 template and a _wizard_step2_probe.html partial,

    • bundle.rs (the README gains an identity section: probe the issuer, then run cargo xtask identity verify before deploying);

  • crates/canopy-api/src/ratelimit.rs (SharedKeyedLimiter);

  • crates/canopy-test-lib/tests/issuer_probe_test.rs (new; canopy-auth has no canopy-test-lib dev-dependency);

  • xtask/src/cmd/route_authz.rs: EXPECTED_MUTATING_TOTAL goes from 84 to 85 and the Studio count from 3 to 4, plus a NotProgramScoped(STUDIO_REASON) row for the probe handler.

Tests:

  • EgressPolicy:

    • every row of the address table, and the classification order: [::1] is loopback and admitted in development; ::ffff:127.0.0.1 is loopback; the NAT64 form of 169.254.169.254 is refused;

    • fd00:ec2::254 and 100.100.100.200 are refused in development and under the override, as literals and as DNS answers;

    • the scheme rule per class: under the override, http to a private answer is admitted, while http to a public answer, or to mixed public and private answers, is refused.

  • GuardedClient, with short timeouts and a fixed-answer lookup:

    • http://169.254.169.254/ is refused with no network;

    • a name whose answer is refused never connects (a counting listener stays at zero);

    • a 302 is refused, not followed;

    • a chunked body over the cap is TooLarge;

    • a delay past the total is Timeout;

    • an https URL at a plain-HTTP listener is Tls.

  • issuer_probe_test.rs against the canopy-test-lib MockIssuer, plus small axum stand-ins for the shapes the mock cannot serve. One case per ProbeFailure:

    • input with a query, a fragment or userinfo;

    • 404; not JSON;

    • an issuer with a path, found at …/realms/x/.well-known/openid-configuration;

    • issuer mismatch; no exchange grant;

    • an unusable endpoint (ftp: and mailto: authorization or token endpoints; http outside development);

    • a document whose jwks_uri is an always-refused IP literal;

    • an empty JWKS; no usable key, with a fixture for each reason (an EC key under RS256, an RSA key whose n is malformed, a key without kid).

  • Pass, with its facts.

  • Routed tests in step2_route_tests.rs: 200 for pass, fail and identity-invalid; the throttle’s 429; a probe followed by Next and a bundle download leaves no probe_* value anywhere in the bundle.

  • SharedKeyedLimiter: the window admits 6 and refuses the 7th per key; keys are independent; with Redis unreachable it falls back to the process-local limiter, never unlimited. Follow the module’s existing test pattern.

  • e2e against the devstack (development policy). The probe cases run serially in the studio-admin project only, three probes within one window’s quota of 6, and the spec states its quota budget. Both Studio projects share jane.studio.

    • success at the issuer canopy-web’s own configuration names;

    • IssuerMismatch at http://keycloak:8080/realms/canopy (Keycloak names itself by KC_HOSTNAME);

    • 404 at a nonexistent realm.

      Connect and the other transport failures are covered offline.

U-C (w2) — docs: document Studio’s chooser entries and issuer probe (#570)

Files:

  • docs/modules/ROOT/pages/api/canopy-web.adoc (the two routes);

  • authorization-inventory.adoc (the canary count);

  • security.adoc (the egress guard);

  • security-operations.adoc (the override’s inventory row);

  • configuration-reference.adoc (CANOPY_WEB__ALLOW_PRIVATE_ISSUER_PROBE);

  • idp-integration.adoc (Studio authors N chooser entries; the probe beside identity verify);

  • guide/administrator.adoc (Step 2);

  • CHANGELOG.

Verification

  1. Per unit: fmt, clippy, non-live nextest and quality-budgets in isolated worktrees, with no live-devstack tests.

  2. CANOPY_CARGO_FEATURES=canopy-api/test-clock cargo xtask dev reload, then git push. The battery is the gate: the Studio e2e projects run the new specs against the devstack.

Documentation Updates

  • The pages in U-C.

  • GitLab: file the out-of-scope follow-ups and the two pre-existing fix: issues. Rewrite epic &119’s description, which copied cluster-1 text, with this plan’s link.

Review log

round vendor resolved model verdict

1 (2026-09-26)

Anthropic

claude-opus-5-5

no-ship — seven blockers fixed:

* a policy-carrying GuardedClient, so the URL check guards the JWKS hop and tests can build it; * issuer-path-preserving discovery URLs, compared as strings; * htmx swaps no 4xx, so statuses are stated and the result region takes data-swap-errors; * an explicit address-class table, including the embedded-IPv4 forms; * typed TLS and DNS classification (a direct rustls dependency, io::Error::get_ref); * the route-authz facts (policy_for keys on the registering file) and a Studio routed-test home; * proptests for the indexed parser and the bundle round-trip.

2 (2026-09-26)

OpenAI

gpt-6-astra

no-ship — eight findings fixed in revision 3:

* resolve, vet and pin per request, since a reqwest resolver cannot see the scheme (mixed answers refused); * the IPv6 and Alibaba metadata endpoints always refused, ahead of the private ranges; * :: and ::1 classified before compatible-address extraction; * a usable key needs a kid and a decodable key, as runtime validation does; * authorization, token and JWKS endpoints must be https (http in development only); * entries controls synchronized and the fieldset disabled while a swap is pending, with a delayed-response browser test; * the e2e probe cases fit one window’s quota in one project; * the probe quota held across replicas through the BFF’s shared Redis window.

No round 3.

Edit this page · default