Connect the CRM from the integrations settings page
C# · ASP.NET Core · intermediate · modification
Adds the connect / reconnect endpoint behind the Pipewell card on the integrations settings page. `CrmClient.cs` (new) holds the `CrmConnection` record (tenant, region and key) that the controller hands to the client, the `CrmVerification` outcome and a typed `CrmClient` that calls `GET /v1/account` on the region's host with the key as a bearer token: 200 is `Valid`, 401 or 403 is `Rejected`, any other status, a network error or a timeout is `Unavailable`. `Program.cs` registers the typed client through `AddHttpClient` with a 10-second timeout. `CrmIntegrationController` gains `PUT`: it validates the region and the key format, verifies the key, then protects it with `IKeyProtector` and writes the region, the protected key and the connection time to the tenant's row in one update; a refused key answers 422 and an unavailable Pipewell 503, both as problem details; the refused and unavailable branches and a saved connect each write the support line the requirements ask for. `CrmConnectTests.cs` covers the new endpoint with a fake Pipewell handler on the existing `HelpdeskApiFactory`.
ASP.NET Core 10 Web API on .NET 10 (C# 14, nullable reference types enabled), controllers with `[ApiController]`. Unchanged and declared: `AddHelpdeskAuth` validates JWT bearer tokens from the company's identity provider; every token carries `tenant_id` (a GUID, read by `User.GetTenantId()`) and `tenant_role` (`admin` or `agent`), and the `TenantAdmin` policy (`HelpdeskAuth.TenantAdmin`) requires a signed-in user with `tenant_role` = `admin`. EF Core 10 with Npgsql in production: `HelpdeskDbContext.CrmIntegrations` has one `CrmIntegration` row per tenant, keyed by `TenantId` and created when the tenant is provisioned, with nullable `Region`, `ProtectedApiKey` and `ConnectedAt` (all null until the first connect). `IKeyProtector` (`Helpdesk.Api.Security`, registered by `AddHelpdeskDataProtection`) wraps ASP.NET Core Data Protection; the key ring is shared only with the integration worker (a separate service, unchanged), which reads `ProtectedApiKey` and unprotects it. Logging: `AddJsonConsole` writes each entry as one JSON line with the formatted message and every template argument as text; a collector ships the container output to the company log platform, where every support agent and the log vendor can read it, retained 30 days. Minimum level is Information (`Microsoft.AspNetCore` at Warning) from the unchanged appsettings; the app has no HTTP request or body logging. `UseExceptionHandler` with `AddProblemDetails` turns an unhandled exception into a generic 500. Pipewell: hosts `api.pipewell.example` (us) and `api.eu.pipewell.example` (eu); `GET /v1/account` with `Authorization: Bearer <key>` answers 200 for an active key and 401 for an unknown or revoked one; keys are `pw_` followed by 40 ASCII letters or digits. The settings page sends the region in lower case and ships separately. Tests use xUnit and the existing `HelpdeskApiFactory` (`WebApplicationFactory<Program>` over in-memory SQLite): `CreateClientFor(tenantId, role)` signs requests in, `SeedTenantAsync` inserts a tenant's disconnected row, `GetIntegrationAsync` reads it back, and `WithTestServices` returns a factory with extra test services.
Requirements
- `PUT /api/integrations/crm` (new) lets a tenant admin connect Pipewell, the tenant's CRM, or reconnect it with a new key. The body is `{ "region": "us" | "eu", "apiKey": "..." }`; surrounding whitespace in the pasted key is ignored. An unknown region, or a key that is not `pw_` followed by 40 letters or digits, answers 400 without calling Pipewell.
- Before anything is saved, the endpoint checks the key once against Pipewell (`GET /v1/account` on the region's host) with a 10-second request timeout on the HTTP client. A key Pipewell refuses answers 422; Pipewell failing, timing out or unreachable answers 503. In both cases nothing is saved and the tenant's previous connection stays as it was.
- A verified key is stored encrypted at rest with the existing `IKeyProtector`, together with the region and the connection time, and the response is the same status object `GET` returns (`connected`, `region`, `connectedAt`). When two admins connect at the same time, the last successful connect wins.
- The Pipewell API key is a secret that only the integration worker may read: it is never shown back in the UI (no response, success or error, contains it) and it must not appear anywhere support staff can see.
- Support gets one line when Pipewell refuses the key or is unavailable (`CRM verification failed`, Warning, with the outcome) and one when a verified key is saved (`CRM connected`, Information), each naming the tenant and the region so support can find the attempt when a customer writes in.
- Only tenant admins may connect the CRM: the controller keeps the existing `TenantAdmin` policy (401 when signed out, 403 for agents). Unchanged: `GET /api/integrations/crm` returns the status.
Files touched
- src/Helpdesk.Api/Program.cs
- src/Helpdesk.Api/Integrations/CrmClient.cs
- src/Helpdesk.Api/Integrations/CrmIntegrationController.cs
- tests/Helpdesk.Api.Tests/CrmConnectTests.cs