Files
HealthAppRepository/src/AUTHENTICATION.md
T

12 KiB
Raw Blame History

US-13 prototype authentication

The API gateway authenticates pre-created externally configured accounts. Login is POST /api/authentication/login with accountId and password. A successful JSON response contains accessToken, tokenType: Bearer, expiresIn, accountId and trusted role; it contains no patient data or refresh token. Send the access token as Authorization: Bearer <token> on subsequent patient-data requests. Invalid credentials return the same 401 response for unknown accounts and wrong passwords. Login responses cannot be cached. General measurement guidance remains public.

Mechanism and configuration

Use ASP.NET Core's built-in bearer authentication and ticket protection, with Data Protection's application name HealthApp.ApiGateway and the bearer purpose. Tokens are opaque protected authentication tickets, not JWTs. The configured key ring and framework purpose enforce the gateway trust boundary; only account ID, role and authentication properties are protected inside a token. Do not share the key ring with other applications/services. No custom cryptography, identity microservice, account database or refresh-token mechanism is introduced.

The gateway verifies passwords with ASP.NET Core PasswordHasher against Authentication:Accounts:<index>:{AccountId,Role,PasswordHash}. Roles are Patient or HealthcareProfessional, from trusted configuration. IDs support ASCII letters, digits, hyphen and underscore, up to 128 characters. This keeps the internal account lookup contract unambiguous. Provision credentials externally; no registration or administration API is exposed. For provisioning, tools/PasswordHash reads a password from standard input and emits its ASP.NET Core hash. Supply input securely (e.g. redirect a permission-restricted temporary file), and protect the resulting hash/configuration; neither belongs in Git. The tool needs no NuGet dependency.

Authentication:TokenLifetimeMinutes defaults to 30; supported range is 1–1440. Authentication:KeyDirectory is required. Keep its contents persistent through restart/deployment and readable only by the gateway service account. The systemd unit provides a mode-0700 state directory; example configuration points into it. Keys are protected by filesystem permissions in this Linux prototype. Removing keys invalidates tokens; preserve them for restart continuity. Accounts and configuration are loaded at startup; after disabling accounts or changing roles, old tokens can remain valid until their expiry. Immediate revocation is outside this story. Missing/invalid/expired tokens return 401; authenticate again after expiry. Credential validation is not repeated for each operation.

Before thesis measurement, record the lifetime, account/role mix, key persistence, login frequency and expiry handling. Normally obtain tokens during workload setup and reuse them; state explicitly whether login is measured. If tokens expire, re-authentication is required. Keep these choices identical across variants. The automated test helper logs in using real password verification and caches tokens; its account-per-resource setup is not a prescribed measurement workload.

Ownership and profile creation

The patient service owns the account association as patient.account_id with a unique index. It remains application access data, outside tokens. The gateway queries its protected GET /api/patients/by-account/{accountId} service API on each request; that API is not forwarded as a public account-lookup route. An account without a profile may log in and create one; its other own-data requests return 404. Patient operations are subject to the standard Patient authorization policy.

GET /api/patients/me retrieves the caller’s own associated profile without needing to know its generated identifier, including after a creation response was lost. It returns 404 before profile creation.

Profile creation derives X-Account-Id from the authenticated principal. The gateway overwrites client input; the service accepts it only behind its gateway credential. The profile and association are inserted in one atomic database save, so failure rolls both back. The unique index arbitrates concurrent creation. A completed creation, a retry after a lost response and a competing request cannot create another profile; later attempts receive 409. A retry after a failed transaction may create the first profile. Profile identity remains persistent through restarts. US-01's authenticated creation is included because US-13 depends on a persistent, recoverable association.

Apply the new patient migration before startup. Existing profiles retain a null account association rather than being assigned to an arbitrary account. They are not accessible to patient accounts until a trusted deployment operator explicitly associates them with pre-created accounts. For synthetic experiments, provision a fresh database via the authenticated creation flow. Do not infer ownership from caller-supplied IDs or automatically assign historical profiles.

For observation-ID requests, the gateway reads the observation through its service API to obtain the actual patient, then compares that owner with the account's profile. Requests for another patient's information receive an empty 404, the same as missing data, without forwarding writes or revealing existence. Failed ownership lookups fail closed with 502/504. Tokens do not cache ownership. Healthcare-professional logins establish a trusted role. US-14 now permits reads of assigned patients and the caller’s own assignment list; all professional writes are rejected before forwarding. Trend/overview endpoints remain unimplemented; the gateway's default authentication policy also protects future patient endpoints, which must retain ownership checks when added.

Service and transport protection

Use HTTPS for client and service traffic. Outside Development, gateway and service requests over HTTP are rejected and outgoing service endpoints must be HTTPS. Certificates use ordinary Kestrel configuration and normal platform validation; no insecure certificate handler is provided. Configure DNS names/certificates for separate machines. Development permits plain HTTP for local automated tests only. Use network firewall rules to restrict service ports to trusted hosts as an additional deployment control; the application credential checks still enforce protection if a client reaches a service directly.

Each service requires InternalAccess:GatewayKey, a random credential of at least 32 characters, matched by the gateway's Services:<service>:Key. Services reject missing/wrong keys and client bearer tokens. Use distinct per-service gateway keys in deployment. The gateway forwards only its own configured key; arbitrary client identity headers are not propagated. Do not log these headers or tokens.

Observation and Insights each have a separate Services:ApiGateway:Key, matched by the gateway's InternalAccess:Observation:Key or InternalAccess:Insights:Key. Their X-Service-Key authenticates an internal principal using an ASP.NET Core handler. The Observation principal can only GET a patient profile by patient ID; the Insights principal can only GET observation history by patient ID. Neither can create/update/delete profiles or observations, query account associations or call other protected routes. Both internal read paths still pass through the gateway. Service credentials are separate from patient tokens and token keys. Use independent random values, restrictive configuration-file permissions and HTTPS; placeholder values in deployment examples deliberately fail validation.

Verification

The acceptance suite exercises real HTTP hosts and PostgreSQL migrations. It covers US-13's login, own access, missing/invalid/expired tokens, no-profile behaviour, cross-patient reads/writes and observation ownership. Additional checks cover caller-supplied account spoofing, persistent tokens/associations after restart, duplicate/concurrent creation, unavailable-service recovery, direct service bypass, internal-credential route restrictions, professional creation rejection and public US-15 guidance. Existing functional assertions run through real token login rather than a production authentication bypass.

Framework reference: https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.authentication.bearertoken.bearertokenoptions?view=aspnetcore-10.0

US-14 professional assignments

Predefine assignments in the gateway's external Access:ProfessionalAssignments configuration, keyed by the stable professional account identifier. For example:

{
  "Access": {
    "ProfessionalAssignments": {
      "example_professional": [
        "00000000-0000-0000-0000-000000000001",
        "00000000-0000-0000-0000-000000000002"
      ]
    }
  }
}

Use actual patient identifiers returned by authenticated profile creation. The example UUIDs are placeholders. A professional can have several patients, and several professionals can share a patient. Duplicate identifiers are treated as one assignment. Empty identifiers are rejected at startup. An omitted account entry means no assignments. Configure that account's role and password hash separately under Authentication:Accounts; assignments never grant a role.

GET /api/professionals/me/patients requires the HealthcareProfessional policy and returns an array of { "patientId": "..." } entries, in deterministic identifier order. It lists only the caller's configured assignments, without fetching patient records. No assignments returns []. Missing profiles remain assigned identifiers; retrieving their data follows the existing missing-resource behaviour. Caller query parameters or identity headers cannot select another professional's list. Patient accounts cannot use this endpoint.

Professional GET requests to existing patient profiles, observations (including recorded legacy context), history, latest observations and numerical insight require membership in the caller's assignment set. Observation-ID requests resolve the actual owning patient via the protected Observation API; a supplied patient ID is not evidence of assignment. Unassigned reads return an empty 404, preserving the same non-disclosure convention as patient access. Assigned missing data follows the existing retrieval contracts. All professional POST/PUT/PATCH/DELETE requests are rejected with 403 before ownership lookups or forwarding. There is no assignment-management API or additional database/service.

Assignments are loaded at gateway startup, outside tokens and credential validation. Restart the gateway after changing its external configuration. Existing valid tokens then use the new assignment data. Empty lists need no upstream service; observation-owner lookup failures fail closed with 502/504.

The US-14 tests exercise actual login, multiple and shared assignments, empty lists, assigned/unassigned reads, preserved context, missing resources, every existing write route, invalid and expired credentials, patient-role rejection, assignment changes across restart and unavailable ownership lookup. Trend and overview endpoints now have equivalent owner/assignment routing and integration tests under US-11/US-12. Structured observation context is included in authorized reads.

US-12 Overview service access

The gateway requires Services:HealthOverview:BaseUrl and Services:HealthOverview:Key. The latter matches Overview's InternalAccess:GatewayKey and protects direct access. Overview's outgoing Services:ApiGateway:Key matches InternalAccess:HealthOverview:Key on the gateway. Use distinct randomly generated credentials of at least 32 characters for each direction and service; load them externally. Production endpoints use HTTPS.

The HealthOverview service identity is restricted to GET patient profiles, GET latest overall observations and GET numerical insights. It cannot retrieve history, trends or another overview, or perform writes. It establishes no client identity. The gateway checks client ownership/professional assignment before forwarding the outer request. Internal credentials are trusted service credentials and must remain inaccessible to clients. Overview adds no authentication framework, shared runtime library or persistence.