# Hosted Plant Finder release notes

This runbook is for a future authorized staging deployment. The C# lab runs against four synthetic records on localhost. The hosted commands and database adapter design below were reviewed against official documentation. The Lab evidence covers the local fixture and HTTP app. Record Azure, Copilot Studio, private networking and Aurora evidence separately before claiming those integrations.

## 1. Separate the catalog, action and metered entry point

Use ordinary Gardenality filtering as the default user path. It can still incur infrastructure costs, but it uses no Copilot credits. For the connected pilot, allow only approved accounts. Use an end-user connector connection and derive the caller from a validated principal. In the fixture, a unique random key resolves to a server-controlled subject. For an Entra deployment, validate the bearer token issuer, signing key, audience, expiry, allowed tenant, delegated scope and approved connector application, then enforce the pilot allowlist and subject key using `tid` plus `oid`. A shared connection obscures individual identity and is incompatible with per-user quota enforcement.

Apply one gate before a metered operation your own backend dispatches. A Plant Finder gate controls calls to that adapter. A Studio agent turn can start incurring usage before it invokes the connector. To enforce an application-level limit on that turn, restricted users must enter through the controlled backend entry point with the same authenticated identity, and that backend must acquire a permit before submitting the turn. A directly reachable Studio channel is a separate path. Environment billing and cost alerts are monitoring and administrative controls. Review their separately documented behavior and measure any metered units before adopting a spend claim. [Copilot Studio billing and licensing](https://learn.microsoft.com/en-us/microsoft-copilot-studio/billing-licensing)

### Optional server-only Studio companion

This is a design for a future staging harness. The offline fixture has no Microsoft client or metered calls. Keep the native connector test separate from the companion gateway test. Have the channel owner verify that the chosen Copilot Studio standard-harness channel supports the required user authentication and connection-card flow, including the application's end-user authorization. Use ordinary search if those prerequisites or a bounded charge model cannot be verified.

| Proposed application operation | Direct Line v3 operation, invoked by the backend |
|---|---|
| `POST /v1/assistant/conversations` | Reserve and claim admission before `POST /v3/directline/conversations`. Opening a conversation can trigger agent initialization. Store the returned conversation ID and credentials server-side. |
| `POST /v1/assistant/conversations/{handle}/turns` | Authenticate the caller, check handle ownership, and require an idempotency key. Reserve and claim a permit before `POST /v3/directline/conversations/{conversationId}/activities`. Send a single bounded `message` activity, with `from.id` supplied by the server. Store the returned provider activity ID on the receipt. |
| `GET /v1/assistant/conversations/{handle}/turns/{receipt}` | Verify the same caller/handle/receipt ownership. Poll with deadlines and a stored watermark using `GET /v3/directline/conversations/{conversationId}/activities?watermark=…`. Keep access to unneeded activities and tokens inside the companion. A status read never submits another activity. |

Use the documented Direct Line base URL for the agent region. Enable **Settings → Security → Web channel security → Require secured access**. Send Bearer credentials server-to-server. Store the Direct Line secret in the vault and wait for the setting to take effect, then verify an unauthorized request fails. If using conversation-scoped tokens, use `POST /v3/directline/tokens/generate` and `POST /v3/directline/tokens/refresh` from the backend. Use a random `dl_` channel identity per conversation and map it to the application's authenticated subject in your store. Keep the channel secret, conversation credentials and WebSocket stream URL server-side. The channel credential and user ID have separate jobs from end-user sign-in. Do not accept a browser-supplied Microsoft conversation ID, user ID or target URL. Disable or restrict direct channels the pilot audience could use to bypass admission and verify that they cannot start a turn outside the companion. [Direct Line v3 reference](https://learn.microsoft.com/en-us/azure/bot-service/rest-api/bot-framework-rest-direct-line-3-0-api-reference) · [Copilot Studio channel security](https://learn.microsoft.com/en-us/microsoft-copilot-studio/configure-web-security) · [Direct Line token parameters](https://learn.microsoft.com/en-us/azure/bot-service/rest-api/bot-framework-rest-direct-line-3-0-authentication) · [Agent user authentication](https://learn.microsoft.com/en-us/microsoft-copilot-studio/configuration-end-user-authentication)

Route any operation that can trigger agent work through the same admission and outcome protocol, including application-driven custom events. A Direct Line activity identifier is a receipt, not evidence of end-to-end idempotency or final billing. On a lost reply, timeout, or uncertain response, keep the reservation, put the receipt in an unknown state and offer ordinary Plant Finder. Reconcile it with provider activity and approved usage evidence. Automated resubmissions stay disabled. Set and verify allowlist, per-user and global admission, bounded message sizes and polling, and a kill switch before trial turns. Track provider billing separately from exact application admission counts.

## 2. Keep Aurora private and read only

1. Ask the database owner to record the actual Aurora engine and version, private reader endpoint, port, server CA, current published-record predicate and canonical Gardenality URL contract. The PostgreSQL example below is conditional on an Aurora PostgreSQL target. An Aurora MySQL target needs an engine-specific adapter, privilege script and execution evidence.
2. Give the connector a reviewed HTTPS ingress for the bounded API. Confirm the correct Power Platform datacenter and apply the documented regional connector egress rules at the API ingress. Regional App Service VNet integration handles outbound traffic. Separately, use an approved routed private link between the Azure VNet and AWS VPC, such as a compatible site-to-site IPsec connection. The network owner must verify non-overlapping CIDRs, return routes, failover, firewall rules and DNS resolution from the running app. Allow only the app's expected source range and catalog port at Aurora. Prefer the real Aurora DNS hostname for TLS name verification. Leave the RDS instance private. [Connector egress ranges](https://learn.microsoft.com/en-us/connectors/common/outbound-ip-addresses) · [App Service access restrictions](https://learn.microsoft.com/en-us/azure/app-service/app-service-ip-restrictions) · [App Service VNet integration](https://learn.microsoft.com/en-us/azure/app-service/overview-vnet-integration) · [AWS Site-to-Site VPN](https://docs.aws.amazon.com/vpn/latest/s2svpn/VPC_VPN.html) · [Azure site-to-site setup](https://learn.microsoft.com/en-us/azure/vpn-gateway/tutorial-site-to-site-portal)
3. Create a dedicated login with no base-table rights, elevated memberships, ownership or write grants. Give it schema `USAGE` and `SELECT` on one owner-approved view. Use the Aurora reader endpoint where appropriate. It can route to the writer when no replicas exist, so the database grants remain the permission boundary. Require TLS and Npgsql `SSL Mode=VerifyFull` with the AWS CA bundle. Set connection, statement and request timeouts. [Aurora PostgreSQL permissions and TLS](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/AuroraPostgreSQL.Security.html) · [Aurora reader endpoints](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/Aurora.Endpoints.Reader.html) · [Npgsql TLS](https://www.npgsql.org/doc/security.html)
4. Map only reviewed fields: catalog ID, public display name, zone minimum and maximum, normalized light and soil, known mature height, approved geography-qualified native tag, fall-interest tag and canonical public URL. Treat missing values as unknown. Return up to three matching records with grounded reasons, including a size tradeoff when relevant. Select columns explicitly and validate every returned URL against the owner-approved host and path. Keep free-form notes, user accounts, contact details, provenance internals and unpublished entries outside the projection. Match legacy ASPX filter names, combination rules, sorts, pagination, empty states and public links independently before claiming parity. The fixture covers one narrow matching contract.

### Conditional PostgreSQL example

The schema, role and column names are placeholders. The two SQL blocks passed a local PostgreSQL 19.0 check in PGlite 0.6.1 against synthetic records. Ranked order, no match, exact projected fields, unpublished record exclusion, denied base reads and denied view updates passed under `SET ROLE`. A real login and Aurora network/TLS remain release checks. The view owner needs appropriate base-table access. Audit rights inherited via `PUBLIC` or other role memberships. Keep this login out of unrelated databases or schemas with public access. The catalog role is separate from the writable quota store.

```sql
CREATE ROLE plant_finder_view_owner NOLOGIN;
CREATE ROLE plant_finder_catalog LOGIN;
CREATE SCHEMA lab_api AUTHORIZATION plant_finder_view_owner;
REVOKE ALL ON SCHEMA lab_api FROM PUBLIC;

GRANT USAGE ON SCHEMA approved_source TO plant_finder_view_owner;
GRANT SELECT (catalog_id, display_name, zone_min, zone_max, light_code,
              soil_code, mature_height_ft, native_region_tag, fall_interest,
              canonical_public_url, is_published)
ON approved_source.plants TO plant_finder_view_owner;

SET ROLE plant_finder_view_owner;
CREATE VIEW lab_api.public_plants WITH (security_barrier = true) AS
SELECT catalog_id, display_name, zone_min, zone_max, light_code,
       soil_code, mature_height_ft, native_region_tag, fall_interest,
       canonical_public_url
FROM approved_source.plants
WHERE is_published IS TRUE;
REVOKE ALL ON lab_api.public_plants FROM PUBLIC;
RESET ROLE;

GRANT USAGE ON SCHEMA lab_api TO plant_finder_catalog;
GRANT SELECT ON lab_api.public_plants TO plant_finder_catalog;
ALTER ROLE plant_finder_catalog SET default_transaction_read_only = on;
ALTER ROLE plant_finder_catalog SET statement_timeout = '2s';
```

Set the login's secret outside SQL history or use already approved short-lived identity. The following query uses typed parameters in this order: required zone, light and soil, then optional preferred height, qualifying native-region tag and fall interest. Use the ranking rule only after verifying the approved native tag's meaning. The SQL returns facts for the app to validate and serialize. It leaves provenance and reasons to the app.

```sql
PREPARE find_plants(integer, text, text, numeric, text, boolean) AS
SELECT catalog_id, display_name, zone_min, zone_max, light_code, soil_code,
       mature_height_ft, native_region_tag, fall_interest, canonical_public_url
FROM lab_api.public_plants
WHERE $1 BETWEEN zone_min AND zone_max
  AND light_code = $2
  AND soil_code = $3
  AND mature_height_ft IS NOT NULL
  AND canonical_public_url IS NOT NULL
ORDER BY (
    CASE WHEN native_region_tag = $5 THEN 2 ELSE 0 END
  + CASE WHEN $6 IS TRUE AND fall_interest IS TRUE THEN 2 ELSE 0 END
  + CASE WHEN mature_height_ft <= $4 THEN 1 ELSE 0 END
) DESC, catalog_id::text COLLATE "C" ASC
LIMIT 3;
```

As the real login, verify one fixture-safe `SELECT` succeeds, forbidden base access and a write attempted in a rollback-only transaction fail, and an unpublished sentinel cannot be returned. Inspect query plans and the public JSON response before accepting the adapter. [PostgreSQL view security](https://www.postgresql.org/docs/current/sql-createview.html) · [PostgreSQL GRANT](https://www.postgresql.org/docs/current/sql-grant.html) · [PostgreSQL PREPARE](https://www.postgresql.org/docs/current/sql-prepare.html)

## 3. Make paid-call reservations durable before scaling

The local lab serializes a process-local admission decision. Its counters and receipt history reset when that process restarts. Keep paid paths disabled during a single-process synthetic staging exercise. For connected usage or multiple replicas, use a transactional writable store separate from Gardenality. Implement the following sequence with a short PostgreSQL transaction or an equivalent primitive. Use UTC windows from the authoritative server clock and a singleton gate-control row per operation. All callers, workers and control writes share the lock order below. [PostgreSQL row locks](https://www.postgresql.org/docs/current/explicit-locking.html) · [PostgreSQL transaction isolation](https://www.postgresql.org/docs/current/transaction-iso.html)

| Store record | Key and contents |
|---|---|
| Control | Operation. Enabled state, positive limits, version and approval reference. |
| Bucket | Operation, UTC window and kind, stable opaque user ID or reserved global identifier. Used units. |
| Receipt | Operation, authenticated subject, idempotency key. Canonical payload hash, captured window, reserved units, dispatch state, bounded response and safe correlation ID. |

1. Authenticate and validate first. Apply request rate limits per user at ingress, including replay traffic, so retries cannot flood the store. Use bounded, expiring rate counters and edge rate limits in addition to authenticated limits. Begin a transaction. Lock the control row with `SELECT ... FOR UPDATE`. Stop with unavailable if control is disabled, unreadable or unreachable. Check the same subject's idempotency receipt and hash. Replay a completed matching receipt and reject a conflicting hash. A pending receipt must never create a second outbound attempt.
2. Initialize and lock that UTC day's global bucket followed by the user's bucket. Reject if either would exceed its configured positive limit. If an operation can bill variable units, reserve a measured worst-case bound and enforce corresponding upstream bounds. Increment both counters and insert the unique receipt in the same transaction. Return a permit only after commit succeeds. A lost commit acknowledgement must be resolved by looking up the receipt. A renewed key is not a safe recovery from an unknown commit.
3. The single egress path takes the control lock, rechecks the kill switch, and conditionally moves one receipt from `reserved` to `dispatch_claimed`. Commit before attempting the bounded provider call. Disable automatic paid-call retries unless the provider supplies an enforceable idempotency contract and the reserved units cover every charge. Keep the same key inside the provider request when supported. A crash or timeout after a claim is an unknown outcome. Keep the reservation, reconcile against provider evidence, and never resend automatically. Complete or record failure with a conditional state change on that receipt. Do not hold a database transaction open across a remote call.
4. Disable by updating the locked control row. Unclaimed reservations cannot dispatch after the committed switch. A claim that committed before the switch may still be in flight or between claim and send. For a strict blackout, disable the application gate and block new egress at the dispatch gateway, then drain in-flight operations. A managed agent channel that can bypass that gateway must also be disabled for the blackout to cover it. Reconcile claimed receipts before re-enabling.
5. Keep receipts for an explicit retry horizon that crosses day rollover. A request retried after the horizon can consume a new allowance, so reject expired reused keys or make the horizon visible to clients. Delete terminal receipts by bounded retention job and retain unknown outcomes until reconciled. Verify raced duplicates, the last global permit from two replicas, UTC rollover, store outage, worker crash after claim, and kill-switch behavior with a fake dispatch target before exposing any paid path.

## 4. Stage, verify and roll back

1. In an approved non-production Azure subscription, select the existing web app and slot reserved for the exercise. Confirm the supported runtime matches `net10.0` before packaging. Use only the synthetic catalog for this pilot. Turn off paid provider dispatch and keep the production site outside the pilot route. Record the version, slot, connector operation ID, scenario run and intended team before starting. [App Service .NET configuration](https://learn.microsoft.com/en-us/azure/app-service/configure-language-dotnetcore)
2. From the source pack root, create a compiled ZIP with the publish directory contents at its root. The local publish and ZIP commands ran with .NET SDK 10.0.400. The extracted portable DLL started on loopback. It returned `200` from `/healthz`, `401` for a request without credentials, and `200` with G-103 then G-104 for the authenticated match. A repeated key returned an identical `200` response and the replay header. The commands targeting Azure were documentation-checked. They reference pre-existing named resources via environment variables and require an authorized tenant session.

```powershell
dotnet publish ./PlantFinder.Api/PlantFinder.Api.csproj -c Release `
  --no-self-contained -p:UseAppHost=false -o ./publish
Compress-Archive -Path ./publish/* -DestinationPath ./PlantFinder.Api.zip -Force
Get-FileHash ./PlantFinder.Api.zip -Algorithm SHA256
az webapp list-runtimes --os linux --output table
az webapp deploy --resource-group $env:PLANT_LAB_RESOURCE_GROUP `
  --name $env:PLANT_LAB_WEB_APP --slot staging `
  --src-path ./PlantFinder.Api.zip --type zip
```

3. Enforce HTTPS at the hosting edge. On Linux, start with `dotnet PlantFinder.Api.dll` if the app needs an explicit startup command. Under the staging slot's environment variables, use slot-sticky `PlantFinder__Enabled`, `PlantFinder__SimulateCatalogUnavailable`, `PlantFinder__PerUserRequestsPerMinute`, `PlantFinder__PerUserDailyQuota`, `PlantFinder__GlobalDailyQuota`, and one `PlantFinder__Callers__0__Subject` plus `PlantFinder__Callers__0__KeySha256` mapping per key with successive indexes. Set the fixture enabled only for controlled scenario runs. Use a Key Vault reference for each stored caller digest. Leave `PlantFinder__AllowRemoteHttp` false unless you have verified that the edge terminates HTTPS and clients cannot reach the HTTP backend directly. App Service forwards HTTPS state to ASP.NET Core on supported hosting paths. Configure no database or paid provider in the fixture deployment. Use slot-sticky Key Vault references with the slot's managed identity granted only secret retrieval, plus separate role assignments and credentials for each environment. App Service resolves unversioned references to the latest version and may cache them for up to 24 hours. Force a reference refresh or a planned restart when rotation must take effect immediately, then verify without printing values. [App Service .NET configuration](https://learn.microsoft.com/en-us/azure/app-service/configure-language-dotnetcore) · [ZIP deployment](https://learn.microsoft.com/en-us/azure/app-service/deploy-zip) · [Key Vault references](https://learn.microsoft.com/en-us/azure/app-service/app-service-key-vault-references)
4. Rotate with overlap. Issue a new key for the same synthetic caller and add its digest as a second mapping. Reconnect the user's Power Platform connection with the new key. Verify the same limits apply across both keys and a successful action uses the new connection. Remove the old mapping, refresh or roll the app as needed, and verify the old key is rejected. The lab counter is process-local, so a restart during this pilot resets its counts. For Entra or database secrets, separately rotate the relevant credential and verify a fresh connection before retiring the old version. Keep credentials out of exported solutions, logs, screenshots and ZIP files.
5. Test stage HTTPS `/healthz` and `/v1/plants/find` with synthetic credentials and the provided expected scenarios. From the approved Power Platform environment, test the connector operation and a fresh Studio agent conversation separately. Record the return code, scenario output and correlation ID. Check that nonmembers fail, the action enforces both limits, replay creates no new downstream call, unsupported input gives a clear message and an outage returns the fallback. Stay in staging for this review.
6. During a later approved release, record the production preimage (application ZIP/hash, settings keys, solution exports, connection-reference bindings and channel status). Verify the target routes, environment identity, quotas and kill-switch state. Use App Service slot-swap only if the hosting owner approved that path and the current build is valid with the target slot settings. A successful swap places the old build in staging. Leave it available until verification is complete. Then import the approved connector and agent solutions in dependency order, bind the target connections, and publish only the approved channel. Run fresh end-to-end checks on the published version. [App Service slots](https://learn.microsoft.com/en-us/azure/app-service/deploy-staging-slots) · [Copilot Studio solution import and export](https://learn.microsoft.com/en-us/microsoft-copilot-studio/authoring-solutions-import-export)
7. On rollback, turn the action/dispatch switch off and confirm the ordinary search link works. Keep the incident evidence. If the app was swapped, swap the same two slots again to restore the earlier build, with sticky environment settings intact. If production was never swapped, restore the last verified staging ZIP. Restore or remove the changed tool/topic and publish the earlier reviewed configuration to the approved channel. Verify a fresh session and normal search, then re-enable only after the release owner clears the fault. Restore app/agent behavior without erasing the cap ledger or replay receipts.

The CLI command for a later approved forward swap and for its immediate reversal is the same. Verify that `staging` still contains the correct release before using it. The command was documentation-checked. The lab made no swap.

```powershell
az webapp deployment slot swap --resource-group $env:PLANT_LAB_RESOURCE_GROUP `
  --name $env:PLANT_LAB_WEB_APP --slot staging --target-slot production
```
