Implement US-13 patient authentication and persistent ownership

This commit is contained in:
Steffen committed 2026-10-05 11:10:22 +02:00
1 parent ebf50827d6
commit 0ce9b2b168
36 files changed
+1203 -28

No files matched your search

+130
View File
@@ -0,0 +1,130 @@
# 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, but their access is denied
by default until US-14's assigned-patient read policies are implemented; US-14 is
not completed by this change. 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