Skip to content

refactor!: drop user.client_id, backfill canonical identifier columns - #3066

Merged
tada5hi merged 3 commits into
masterfrom
refactor/drop-user-client-id
May 20, 2026
Merged

tada5hi merged 3 commits into
masterfrom
refactor/drop-user-client-id

Conversation

@tada5hi

@tada5hi tada5hi commented May 20, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

  • Drops the unused client_id / client columns and relation from User / UserEntity. The column has been functionally dead since migration 1766830857009 deleted every row where it was non-null ("user client_id referenced wrong table"). The provisioning synchronizer drops the now-redundant client_id lookup key.
  • Adds paired postgres + mysql migration 1779267068441-Default that bundles:
    • Canonical-name backfill (consolidates plan 008): collision pre-check that aborts on any duplicate group after LOWER(TRIM(name)), then UPDATE … = LOWER(TRIM(…)) across nine name tables (auth_clients, auth_robots, auth_users, auth_realms, auth_roles, auth_scopes, auth_permissions, auth_policies, auth_identity_providers) and auth_users.email. Pre-check GROUP BY mirrors each entity's @Unique([...]) declaration.
    • Column drop: auto-generated DDL dropping the auth_users.client_id FK, index, and column.
  • down() restores the column / index / FK only; canonical UPDATEs are not reversed (lossy by definition — original casing is not recoverable).

Breaking change

User.client_id and User.client are removed from @authup/core-kit. Note the [key: string]: any escape hatch on the User interface means any consumer reading these fields still typechecks but returns undefined at runtime.

Test plan

  • npm run build --workspace=apps/server-core — clean
  • npm run test --workspace=apps/server-core — 799/799 passed
  • npx eslint --fix on all changed files — clean
  • Smoke-tested migration up / down / re-up against fresh Postgres + MySQL containers — see below
  • Verified canonical UPDATE rewrites mixed-case rows correctly on both DBs
  • Verified collision pre-check aborts cleanly on a deliberately seeded duplicate

Smoke-test details

  • Postgres: fresh DB → migration run (8/8 applied) → auth_users.client_id confirmed dropped → revert → column restored with correct FK target (auth_clients, not the originally-buggy auth_realms) → re-apply → column dropped again. ✅
  • MySQL: same cycle. ✅
  • Canonical UPDATE on Postgres: seeded 'TestRealm' + '[email protected]', ran migration → names and emails canonicalized to lowercase. ✅
  • Collision detection on Postgres: seeded 'CollideMe' + 'collideme' (Postgres is case-sensitive, both rows persist) → migration aborted with actionable error: Canonical-name migration aborted: "auth_realms" has 1 collision group(s) on LOWER(TRIM(name)). ✅
  • Bug caught during MySQL smoke test (fixed in ec8972dfa): MySQL's default utf8mb4_0900_ai_ci collation treats 'TestRealm' = 'testrealm', so the original WHERE name <> LOWER(TRIM(name)) predicate was always false on mixed-case rows and the UPDATE silently no-op'd. Switched the WHERE clause to WHERE BINARY name <> LOWER(TRIM(name)) (and same for email) to force byte-level comparison. Re-verified end-to-end. ✅

Notes

  • Migration bundles two unrelated changes (column drop + canonical backfill). Considered splitting; kept bundled because the canonical backfill was already ledger'd in plan 008 awaiting consolidation, and shipping both in one timestamp avoids a second migration run for operators.
  • down() for canonical backfill is intentionally a no-op (cannot recover original casing); subsequent writes continue to canonicalize, so the schema stays consistent.
  • ⚠️ CI does not exercise migration files — the test runner uses dataSource.synchronize() instead. The MySQL BINARY bug above was only caught by manual smoke testing. Opened CI: migrations are not exercised against MySQL or PostgreSQL #3067 to add a dedicated CI job that runs migrations end-to-end. Until that lands, every migration PR should be smoke-tested manually against both DBs.

Summary by CodeRabbit

  • Bug Fixes

    • User names and email addresses are now automatically normalized (converted to lowercase with whitespace trimmed) for improved data consistency.
  • Refactor

    • Simplified user record structure by removing client associations.

Review Change Stack

Removes `client_id` / `client` from the User domain interface and
UserEntity. The column has been effectively unused since migration
1766830857009 deleted all rows where it was non-null ("user client_id
referenced wrong table"). The user provisioning synchronizer drops the
now-redundant `client_id` lookup key.

Adds paired postgres + mysql migration `1779267068441-Default`:

- canonical-name backfill: collision pre-check (aborts on duplicate
  after `LOWER(TRIM(name))`) + `UPDATE` to canonical form across nine
  name tables (clients, robots, users, realms, roles, scopes,
  permissions, policies, identity-providers) and `auth_users.email`.
  Pre-check group-by mirrors each entity's `@Unique([...])` declaration.
- DDL: drops `auth_users.client_id` FK, index, column.

`down()` restores the column / index / FK; the canonical UPDATEs are
not reversed (lossy).

BREAKING CHANGE: `User.client_id` and `User.client` are removed from
`@authup/core-kit`.
Copilot AI review requested due to automatic review settings May 20, 2026 09:12
@coderabbitai

coderabbitai Bot commented May 20, 2026 •

Copy link
Copy Markdown

Warning

Rate limit exceeded

@tada5hi has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 27 minutes and 20 seconds before requesting another review.

You’ve run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: ceb9aa56-edd3-4853-af27-7b38b13975ec

📥 Commits

Reviewing files that changed from the base of the PR and between ec8972d and 02b3f86.

📒 Files selected for processing (2)
  • apps/server-core/src/adapters/database/migrations/mysql/1779267068441-Default.ts
  • apps/server-core/src/adapters/database/migrations/postgres/1779267068441-Default.ts
📝 Walkthrough

Walkthrough

This PR removes the optional client relationship and client_id field from the User entity across the entire codebase. Changes span the public type contract in core-kit, the database entity mapping in server-core, two database migrations (MySQL and Postgres) that normalize existing data and drop the column, and the user provisioning synchronizer logic that no longer looks up users by client association.

Changes

Client association removal from User

Layer / File(s) Summary
User type contract removal
packages/core-kit/src/domains/user/entity.ts
Client type import and client_id and client properties are removed from the exported User interface.
UserEntity ORM mapping update
apps/server-core/src/adapters/database/domains/user/entity.ts
Client type import is removed and the client_id column plus the nullable client ManyToOne relationship block are deleted from UserEntity.
Database schema migration
apps/server-core/src/adapters/database/migrations/mysql/1779267068441-Default.ts, apps/server-core/src/adapters/database/migrations/postgres/1779267068441-Default.ts
MySQL and Postgres migrations validate no canonical-name collisions exist, normalize name and email fields via LOWER(TRIM(...)) across auth tables, drop the client_id column and its foreign key constraint and index; down() restores the column and constraints but not the canonicalization.
Synchronizer user lookup update
apps/server-core/src/core/provisioning/synchronizer/user/module.ts
client_id is removed from the userRepository.findOneBy criteria, so user lookup now matches only on name and realm_id.

🎯 3 (Moderate) | ⏱️ ~20 minutes


A client once clung to every User,
But now they part with grace,
Realm and name are all that matter,
In this cleaner, lighter place. 🐰✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately reflects the main changes: removing user.client_id and backfilling canonical identifier columns. It is concise, specific, and clearly communicates the primary refactoring effort.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch refactor/drop-user-client-id

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR removes the deprecated User.client_id/User.client fields and corresponding DB mapping, and introduces a data+schema migration that (1) canonicalizes name (and auth_users.email) values via LOWER(TRIM(...)) with a collision pre-check, then (2) drops the auth_users.client_id FK/index/column for both Postgres and MySQL.

Changes:

  • Remove client_id / client from the @authup/core-kit User interface and the server-core UserEntity mapping.
  • Update user provisioning synchronization lookup to stop using the removed client_id key.
  • Add Postgres + MySQL migrations to pre-check for canonical-name collisions, backfill canonical values, and drop the auth_users.client_id column (with a partial down migration restoring only the dropped column/index/FK).

Reviewed changes

Copilot reviewed 5 out of 5 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
packages/core-kit/src/domains/user/entity.ts Drops client_id/client from the shared User domain interface (breaking API).
apps/server-core/src/core/provisioning/synchronizer/user/module.ts Removes client_id from the provisioning lookup key when resolving existing users.
apps/server-core/src/adapters/database/migrations/postgres/1779267068441-Default.ts Adds Postgres migration to collision-check + canonicalize names/emails and drop auth_users.client_id.
apps/server-core/src/adapters/database/migrations/mysql/1779267068441-Default.ts Adds MySQL migration to collision-check + canonicalize names/emails and drop auth_users.client_id.
apps/server-core/src/adapters/database/domains/user/entity.ts Removes the client_id column and client relation from the TypeORM UserEntity.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +42 to +47
for (const table of NAME_TABLES) {
await queryRunner.query(`
UPDATE "${table}"
SET "name" = LOWER(TRIM("name"))
WHERE "name" <> LOWER(TRIM("name"))
`);
Comment on lines +42 to +47
for (const table of NAME_TABLES) {
await queryRunner.query(`
UPDATE \`${table}\`
SET \`name\` = LOWER(TRIM(\`name\`))
WHERE \`name\` <> LOWER(TRIM(\`name\`))
`);
…HERE

MySQL's default `utf8mb4_0900_ai_ci` collation is case-insensitive, so
`name <> LOWER(TRIM(name))` evaluated `'TestRealm' = 'testrealm'` and the
UPDATE silently skipped every mixed-case row. The migration was a no-op
on MySQL deployments.

Forcing `BINARY` on the LHS of the comparison switches the predicate to
byte-by-byte equality so the WHERE clause matches mixed-case storage
correctly. The `LOWER(TRIM(...))` SET expression is unaffected (those
functions return the canonical bytes regardless of collation).

Caught by smoke-testing the migration end-to-end against a real MySQL
container before merge.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In
`@apps/server-core/src/adapters/database/migrations/mysql/1779267068441-Default.ts`:
- Around line 8-18: The pre-check in the migration (driven by
NAME_COLLISION_CHECKS) is too strict because nullable client_id values get
grouped together; update the collision pre-check SQL for the auth_roles and
auth_permissions entries so they exclude NULL client_id values by adding a WHERE
client_id IS NOT NULL before the GROUP BY in the pre-check generation logic for
both MySQL and Postgres migrations; specifically modify the pre-check for the
entries referencing 'auth_roles' and 'auth_permissions' so the generated query
includes the client_id IS NOT NULL predicate to match the database UNIQUE
semantics.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 6e44aeee-2edc-4ca1-9bb9-03cd00cecf1e

📥 Commits

Reviewing files that changed from the base of the PR and between 6068d68 and ec8972d.

📒 Files selected for processing (5)
  • apps/server-core/src/adapters/database/domains/user/entity.ts
  • apps/server-core/src/adapters/database/migrations/mysql/1779267068441-Default.ts
  • apps/server-core/src/adapters/database/migrations/postgres/1779267068441-Default.ts
  • apps/server-core/src/core/provisioning/synchronizer/user/module.ts
  • packages/core-kit/src/domains/user/entity.ts
💤 Files with no reviewable changes (2)
  • apps/server-core/src/core/provisioning/synchronizer/user/module.ts
  • packages/core-kit/src/domains/user/entity.ts

…antics

SQL GROUP BY collapses NULL values into a single group, but UNIQUE
constraints treat NULL as distinct. The pre-check was therefore stricter
than UNIQUE: two rows with the same canonical name + NULL in a keyed
column (e.g. two global scopes with realm_id=NULL, or two global
permissions with client_id=NULL and realm_id=NULL) would abort the
migration even though they are valid under the actual unique constraint.

For tables with nullable columns in the unique key, filter NULL rows out
of the pre-check so the predicate matches UNIQUE semantics:

- auth_roles, auth_permissions: WHERE client_id IS NOT NULL AND realm_id IS NOT NULL
- auth_scopes, auth_policies: WHERE realm_id IS NOT NULL

The canonical UPDATE itself is unchanged — it rewrites all rows
regardless of NULLs, which is safe because NULL-distinct rows can never
collide post-UPDATE.

Caught by CodeRabbit review and confirmed by seeded smoke test: two
global scopes (NULL realm_id) with the same canonical name now coexist
through the migration (instead of aborting), while a realm-bound
collision still triggers the abort correctly.
@tada5hi

tada5hi commented May 20, 2026

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented May 20, 2026

Copy link
Copy Markdown
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@tada5hi
tada5hi merged commit ba68a60 into master May 20, 2026
8 checks passed
@tada5hi
tada5hi deleted the refactor/drop-user-client-id branch May 20, 2026 12:15
@github-actions github-actions Bot mentioned this pull request May 20, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants