Karyo
Documentation/ Operations

Identity principal upgrade

Karyo 2.1.1rendered at build time
On this page

This is the maintenance-window runbook for moving an existing installation from bare Keycloak subjects and usernames to Karyo-owned principal UUIDs and exact OIDC issuer/subject bindings. New installations with an external provider use the same path. A new managed-Keycloak installation instead creates System, the setup account, which records the cutover marker itself (deploying). Do not enable traffic after structural migrations until the cutover marker exists.

The reviewed manifest contains identity and access metadata. Keep it outside the repository with mode 0600, transfer it through the installation's protected maintenance channel, and retain it with the coordinated backup. It contains no password, client secret or whole token.

Stop conditions

Stop rather than infer when any of these is true:

  • discovery metadata and a legitimately issued access token do not prove the exact issuer, subject, RS256 signature, time validity and karyo-api audience;
  • a subject's historical issuer is unknown, aliases overlap, a custom subject mapper changes the directory id-to-sub relationship, or whitespace/case normalization would collapse identities;
  • an access grant, personal layout or completed provisioning operation cannot be assigned to one exact provider identity;
  • a live claim or work-group member name has zero or multiple attested directory matches;
  • any legacy provisioning operation is not COMPLETE;
  • the first active Company administrator, affiliation, compatibility roles, backup or rollback point is not explicitly approved;
  • the source database identity, schema version, counts or reviewed manifest digest changed.

Historical journal names may remain unresolved because they do not authorize access. Record them in historicalUnresolvedActors; never rewrite them from a same-named current account.

1. Prepare and collect evidence

  1. Fence identity, grant and administration writes. Record the old application image, provider configuration, maintenance start and rollback point.
  2. Back up and rehearse restoration of both the Karyo PostgreSQL database and provider state. For Keycloak, retain the database backup and an administrative realm export. Confirm the legacy provisioning fingerprint HMAC key is available without putting its value in the manifest.
  3. Read the provider's discovery document through both browser/public and backend network paths. Archive the response and claims from legitimately issued browser and service access tokens. Confirm the signed iss, opaque sub, aud containing karyo-api, algorithm and current realm mappers. A backchannel URL is not an issuer unless tokens actually carry it.
  4. Export the complete provider directory with stable ids, disabled users, service identities, pagination evidence, usernames, profiles and roles. For Keycloak, its user id is accepted as sub only after the real token and mapper evidence proves that relationship.
  5. Identify the first active Company administrator explicitly. First login never enrolls or elevates an account.

2. Apply structures, then export and review the manifest

With traffic still fenced, start the new image in migration mode and let Flyway apply all additive structural migrations. Do not admit authenticated traffic. Preflight records that resulting schema version, so running it against the old schema and then migrating would correctly be treated as source drift.

Set a PostgreSQL URL accepted by psql, then export a review-required skeleton:

KARYO_DATABASE_URL='postgresql://...' \
  scripts/identity_migration.py preflight \
  --directory /protected/keycloak-users.json \
  --issuer https://wms.example.com/auth/realms/karyo \
  --provider-key primary --adapter-type KEYCLOAK \
  --output /protected/karyo-identity-manifest.json

For an external provider, use its directory evidence format (users array or an array, with id or subject, username, enabled/profile fields), its exact signed issuer, and EXTERNAL. Preflight is read-only. It stops on ambiguous live names and records deterministic mapping choices in the output file. Deleted subjects become review-required retired principals with unlinked bindings; they are never dropped merely because the provider no longer lists them.

Review every REVIEW_REQUIRED value. Approve:

  • provider UUID, canonical issuer, explicitly attested aliases and evidence reference;
  • each retained principal UUID, HUMAN/SERVICE/SYSTEM account type, ACTIVE/SUSPENDED/RETIRED state, OPS/BUSINESS_UNIT_USER affiliation, Business Unit and local compatibility roles;
  • every exact binding and deleted-identity provenance;
  • access-grant, personal-layout and completed-provisioning row assignments;
  • every live work/member assignment and its unchanged display snapshot;
  • backup, freeze, audience, first-administrator and rollback attestations.

Compatibility roles are review evidence only. At runtime they grant nothing: Karyo authorizes every call from stored grants (ADR 0048), and the roles only bound which actions the access manifest may propose. Administrative provider service accounts receive no warehouse compatibility roles or grants. Never copy claims unchecked, merge two principals, link by email/name, clear a claim, or fabricate a grant to make validation pass.

Validate offline:

scripts/identity_migration.py validate /protected/karyo-identity-manifest.json

Record the printed SHA-256 digest. If the file changes, review and record the new digest.

3. Rehearse on a restored copy

  1. Restore both database and provider evidence in an isolated environment and apply the same additive structural migrations used before preflight.
  2. Apply the reviewed manifest:
KARYO_DATABASE_URL='postgresql://...' \
  scripts/identity_migration.py apply --yes-reviewed \
  /protected/karyo-identity-manifest.json

The command uses one serializable PostgreSQL transaction and an advisory lock. It verifies source counts, refuses nonterminal operations, inserts exact providers/principals/bindings idempotently, re-keys grants/layouts/completed operations, verifies each live reference's old snapshot, validates the staged constraints, writes identity change facts, and writes the cutover marker last. A second apply of the identical manifest is a no-op reconciliation. A different digest after completion is refused.

Verify these SQL invariants before testing traffic:

SELECT count(*) FROM karyo.access_grants WHERE principal_id IS NULL;              -- 0
SELECT count(*) FROM karyo.home_layouts WHERE NOT is_default AND principal_id IS NULL; -- 0
SELECT count(*) FROM karyo.access_provisioning_operations
 WHERE state = 'COMPLETE' AND (principal_id IS NULL OR binding_id IS NULL);         -- 0
SELECT migration_version, manifest_digest, source_principal_count
 FROM karyo.identity_migration_runs WHERE migration_version = 1;                   -- exactly 1
SELECT provider_id, subject, count(*) FROM karyo.external_identities
 GROUP BY provider_id, subject HAVING count(*) <> 1;                               -- no rows

Compare active/revoked grant counts and row ids, default/personal layout totals, completed provisioning fingerprints/version, live claim/member totals and old display snapshots with the preflight report. Marker 1 switches no authority on: every principal is authorized from its stored grants from the moment it is enrolled, so a principal without a grant holds no action and is refused action-not-granted. Marker 2 records the reviewed access activation below; identity cutover alone must not write it.

4. Production cutover

  1. Reconfirm the maintenance fence, fresh coordinated backups and unchanged source snapshot.
  2. Apply structural migrations and the exact rehearsed manifest as above.
  3. Configure OIDC_URL, exact OIDC_ISSUER, OIDC_API_AUDIENCE=karyo-api, RS256, browser authority/client id and KARYO_IDENTITY_PROVIDER_TYPE.
  4. For managed Keycloak, follow the maintenance-isolation procedure and run scripts/migrate_keycloak_realm.py through its loopback maintenance endpoint so installed browser and backend clients receive the API audience mapper. Realm JSON edits alone do not update an existing realm. For EXTERNAL, do not run that adapter command and do not start embedded Keycloak.
  5. Start the new runtime. Exercise real signed access tokens for the imported Company administrator, OPS, BUSINESS_UNIT_USER, disabled user and service identities. Verify backend, console and floor login; same subject at another issuer; missing/wrong audience; suspension; unlinking; personal layout; work ownership; provider capability display; and provider outage behavior.
  6. Remove temporary provider sessions and credentials. Release traffic only after all checks pass.

5. Activate reviewed Company and Business Unit grants

Identity cutover version 1 preserves principal UUIDs and exact issuer/subject bindings. Access activation is a second reviewed manifest and writes cutover version 2. It writes the reviewed grants, which are the only authority for operational and administration calls alike. Rehearse it in full on the isolated restored copy before production.

Activation never enrolls an identity, matches a username, treats a first login as authority, or turns a provider claim into a grant.

For managed Keycloak, use changing an existing Keycloak realm for the backup, isolation and live Admin API update. Keep the application and nginx stopped for access activation, and export the directory evidence below before that procedure retires the temporary administrator and closes its maintenance endpoint. Defer its final deploy until the reviewed access manifest has been applied; retain the traffic fence for the verification below. That runbook owns the command and temporary maintenance endpoint; the managed realm fixtures own the transition claim mapping. Inspect freshly issued browser and backend access tokens: both must contain the expected API audience, exact iss/sub, and the translated Business Unit value.

Export the complete live Keycloak directory through the Admin API, including stable user ids, effective realm roles, disabled/service accounts and these attributes: principal_kind, business_unit_id, and warehouse_id. For an external provider, skip the Keycloak command and export equivalent evidence. The access directory must be an object with the exact canonical issuer and a users array. Each user carries opaque subject (or attested id), realmRoles as an array of effective role names, and attributes with array-valued claims. Keep pagination evidence and do not replace subjects with usernames. Then create the access review skeleton:

KARYO_DATABASE_URL='postgresql://...' \
  scripts/identity_migration.py access-preflight \
  --directory /protected/keycloak-users-with-effective-roles.json \
  --issuer https://wms.example.com/auth/realms/karyo \
  --output /protected/karyo-access-manifest.json

Every grant-review entry is joined through the already enrolled exact issuer/subject binding and carries the existing Karyo principal UUID. Directory identities without an enrolled binding, including provider administration service accounts, are listed separately in providerOnlyIdentities as evidence only. They require no enrollment for access activation and receive no grants or principal review writes. The exporter proposes only catalogue actions that both the exported effective roles and the locally approved compatibility roles translate to, through the ACTION_ROLES table of the shipped role gates (scripts/identity_migration.py, ACTION_ROLES). It creates no grants. Missing or unknown kind, missing/zero/foreign Business Unit and a binding absent from the directory are reconciliation findings. They receive no proposed actions for new grants. Fix the source evidence and re-export rather than clearing a finding in the JSON. One case is not a finding: an operations identity with no Business Unit claim (absent or 0) whose principal is OPS and unaffiliated, such as the first Company administrator, carries the observation unaffiliated operations identity and no proposed actions. The reviewer may give it an explicit COMPANY grant, bounded by the actions its compatibility roles translate to; any other node is refused. BUSINESS_UNIT_USER principals, principals incorrectly affiliated with zero and identities with any reconciliation finding never qualify. Legacy warehouse_id text is archived evidence only: it can never select a node, confer authority or invalidate independently authorized, explicitly reviewed grants.

Review the node and finite action list for every grant. Every existing binding needs a review entry (combine exports for each exact issuer if the installation uses multiple providers). Explicitly list existing active grants approved for retention in each entry's retainedGrantIds; revoked rows stay revoked. Retention validates each stored grant's exact principal, permission profile, state, node and the actions its compatibility roles translate to against the reviewed snapshot, independently of directory claims and new-grant eligibility. Reviewed grants for suspended principals, unlinked bindings or absent-directory identities remain stored unchanged; retention never activates a principal or binding or restores access. New grants still require active principals and bindings plus reconciled claims, and stay within the actions both the exported and the approved roles translate to. Unsafe or unreviewed active grants stop activation: reconcile them through the existing grant administration path and re-export, never delete audit history or edit a reconciliation finding away. Principal cutover version 1 must already be complete. Record backup/freeze/session evidence, then validate and rehearse twice on the isolated restored copy:

scripts/identity_migration.py access-validate /protected/karyo-access-manifest.json
KARYO_DATABASE_URL='postgresql://...' \
  scripts/identity_migration.py access-apply --yes-reviewed \
  /protected/karyo-access-manifest.json

Apply verifies the complete database snapshot under a serializable advisory lock, creates digest-named profiles, writes grants against principal UUIDs while retaining the external subject as provenance, and writes migration marker 2 last. The initial apply refuses a changed source snapshot. After activation, reapplying the identical digest is a no-op without rechecking that snapshot; a different manifest digest is refused. Verify marker 2, active/revoked grant counts and GET /api/v1/me/access before reopening.

Do not reopen traffic until the linked realm procedure has completed its token drain and temporary administrator retirement. Require browser/floor users to sign in again so their tokens contain the new mapper output; a refresh does not mutate an already issued JWT. Identity and tenancy owns the grant-backed authorization boundary. Each endpoint declares one catalogue action, and a request is scoped to the Business Units and Facilities where that action is granted. A principal with no matching grant is refused; neither OPS kind, key 0 nor a provider role supplies fallback authority.

Test with freshly issued tokens for an approved Company operator, a Business Unit administrator, a missing/unknown-claim identity and an identity carrying a legacy location hint. Confirm sibling Business Units remain outside the grant, a visible-but-unmanageable user stays in Users without Edit/Suspend controls, and direct mutation is refused. Check X-Karyo-Business-Unit-Id selection, sibling record URLs, forged headers and conflicting body businessUnitId fields. /me.businessUnitId continues to show affiliation, not selection. Drain floor queues before upgrading the client; IndexedDB version 2 marks old unbound entries for reconciliation, never for automatic replay. Archive only the reviewed manifest and evidence references, never credentials or whole tokens.

Auth migration V1214 deletes the profiles standard-operations-read, standard-operations-write, standard-user-admin and standard-integrations, every grant that names one, and the actions operations.read, operations.write and reports.export (services/karyo-app/src/main/resources/db/migration/auth/V1214__action_catalogue.sql, V1214__action_catalogue). A principal that held only such a grant holds nothing after the migration; grant it one of the seven standard profiles again, including the demo users.

Enroll a principal after cutover

Karyo never enrolls at first login, and authentication-only external mode has no runtime create or bind route. A principal that must exist after cutover version 1, such as a new administrator or an external-provider user, is enrolled by a reviewed enrollment manifest:

{
  "enrollmentManifestVersion": 1,
  "issuer": "https://wms.example.com/auth/realms/karyo",
  "evidence": "change ticket and directory export reference",
  "principals": [{
    "id": "<new principal UUID>", "bindingId": "<new binding UUID>",
    "subject": "<exact provider subject>", "accountType": "HUMAN", "principalKind": "OPS",
    "businessUnitId": null, "roles": ["MANAGER"],
    "username": "j.doe", "displayName": "J. Doe", "email": "j.doe@example.com",
    "evidence": "provider export line for this subject"
  }]
}
scripts/identity_migration.py enroll-validate /protected/karyo-enrollment.json
KARYO_DATABASE_URL='postgresql://...' \
  scripts/identity_migration.py enroll --yes-reviewed /protected/karyo-enrollment.json

The command runs in one serializable transaction under the identity advisory lock. It refuses the manifest unless cutover version 1 is complete and the issuer resolves through an active alias and provider. It also refuses an existing principal id, a subject already bound or tombstoned at that provider, and a missing Business Unit. A BUSINESS_UNIT_USER principal needs a positive Business Unit; a SYSTEM principal has none. Each principal starts ACTIVE with its compatibility roles recorded as evidence, one exact binding and an ENROLLED change fact. Replaying the identical manifest is a no-op. Enrollment writes no grants: give authority afterwards through the Users page grant section or POST /api/v1/principals/{id}/grants.

HMAC v1 compatibility

Completed legacy provisioning operations retain their original fingerprint, provider subject and fingerprint_version=1. That hash includes transient inputs, including the original password and actor external subject, and cannot be recomputed from database state. A legacy retry may only verify the exact original request and exact legacy issuer/subject, then return the existing result. It must never create, regrant, enable or restore. A retry through another newly linked binding is a conflict. Keep the old HMAC key for the documented compatibility period; rotation is separate.

Suspension, unlinking and provider switching

Suspension is local and denies the next API request; it does not promise to disable the provider account. Unlinking tombstones the exact pair permanently. The last active binding can only be unlinked after suspension. Existing organization grants remain stored but inert while a principal is suspended or has no active binding.

A provider switch adds reviewed exact bindings to the same Karyo principal UUIDs. Keep the old provider available until the new tokens pass all checks. Selecting the old login frontend again is safe only while those verified bindings remain active; it is authentication routing, not database rollback.

Rollback boundary

Before manifest/provider writes, abandon the attempt and run the old deployment. After additive backfill but before traffic or provider changes, prefer the rehearsed coordinated snapshot restore. After any new principal write, link, suspension or provisioning operation, do not run the old subject/name-authorizing binary: it can ignore local denial and misattribute ownership. Fix forward, or restore application database, provider state/configuration and deployment together to the recorded pre-cutover point, accepting loss of all later work.