Skip to content

feat: restrict entity names to lowercase characters - #3024

Merged
tada5hi merged 7 commits into
masterfrom
feat/canonical-name-normalization
Apr 29, 2026
Merged

tada5hi merged 7 commits into
masterfrom
feat/canonical-name-normalization

Conversation

@tada5hi

@tada5hi tada5hi commented Apr 28, 2026 •

Copy link
Copy Markdown
Collaborator

Tighten isNameValid to /^[a-z0-9-_.]+$/ so identifier-style names across all entities (client, robot, user, role, scope, permission, policy, realm, identity-provider) are stored in canonical form.

Eliminates the cross-DB inconsistency where MySQL with the default *_ci collation treats 'foo' and 'Foo' as duplicates while PostgreSQL allows both rows to coexist under its case-sensitive collation.

Side effects:

  • Existing test fixtures using mixed-case names ('TestA', 'TestB') updated to lowercase variants
  • Pre-existing isNameValid test for uppercase input flipped from expecting valid to expecting invalid

Production data migration to canonicalize existing rows is tracked in plan 008 (migration ledger).

Summary by CodeRabbit

Release Notes

  • Identifier Normalization

    • User, client, policy, role, scope, permission, realm, and robot names are now automatically normalized to lowercase with whitespace trimmed for consistency.
    • Email addresses are now normalized to lowercase.
    • Identifier lookups now use exact matching instead of pattern matching for improved precision.
  • Documentation

    • Updated architecture and conventions documentation with canonicalization rules and implementation guidance.

Tighten isNameValid to /^[a-z0-9-_.]+$/ so identifier-style names
across all entities (client, robot, user, role, scope, permission,
policy, realm, identity-provider) are stored in canonical form.

Eliminates the cross-DB inconsistency where MySQL with the default
*_ci collation treats 'foo' and 'Foo' as duplicates while PostgreSQL
allows both rows to coexist under its case-sensitive collation.

Side effects:
- Existing test fixtures using mixed-case names ('TestA', 'TestB')
  updated to lowercase variants
- Pre-existing isNameValid test for uppercase input flipped from
  expecting valid to expecting invalid

Production data migration to canonicalize existing rows is tracked
in plan 008 (migration ledger).
Copilot AI review requested due to automatic review settings April 28, 2026 21:08
@coderabbitai

coderabbitai Bot commented Apr 28, 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 19 minutes and 25 seconds before requesting another review.

To keep reviews running without waiting, you can enable usage-based add-on for your organization. This allows additional reviews beyond the hourly cap. Account admins can enable it under billing.

⌛ 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: f1ed3c91-582a-4358-a307-fd3a8b69e8e5

📥 Commits

Reviewing files that changed from the base of the PR and between 63935ec and b6ef521.

📒 Files selected for processing (13)
  • apps/server-core/src/app/modules/database/repositories/client/repository.ts
  • apps/server-core/src/app/modules/database/repositories/permission/repository.ts
  • apps/server-core/src/app/modules/database/repositories/policy/repository.ts
  • apps/server-core/src/app/modules/database/repositories/realm/repository.ts
  • apps/server-core/src/app/modules/database/repositories/robot/repository.ts
  • apps/server-core/src/app/modules/database/repositories/role/repository.ts
  • apps/server-core/src/app/modules/database/repositories/scope/repository.ts
  • apps/server-core/src/app/modules/database/repositories/user/repository.ts
  • apps/server-core/test/unit/http/controllers/entities/identity-provider/module.spec.ts
  • apps/server-core/test/unit/http/controllers/entities/user.spec.ts
  • packages/client-web-kit/src/core/translator/de/vuelidate.ts
  • packages/client-web-kit/src/core/translator/en/vuelidate.ts
  • packages/client-web-kit/src/core/vuelidate.ts
📝 Walkthrough

Walkthrough

Implements systematic canonicalization of identifier fields (name, user.email) across the codebase by normalizing all inputs to LOWER(TRIM(value)). Updates validators to normalize before validation, repositories to use exact equality instead of pattern matching, and adds architectural documentation defining canonicalization enforcement strategy.

Changes

Cohort / File(s) Summary
Documentation
.agents/architecture.md, .agents/conventions.md
Adds canonical identifier normalization rules and implementation guidance defining LOWER(TRIM(value)) for name columns and user.email.
Core Validators
packages/core-kit/src/domains/*/validator.ts (client, identity-provider, permission, policy, realm, robot, role, scope)
Updates all entity name validators to normalize input via .trim().toLowerCase() before length constraints and custom validation checks.
User Validator & Helper
packages/core-kit/src/domains/user/validator.ts, packages/core-kit/src/helpers/name-valid.ts
User name normalizes via .trim().toLowerCase(); email adds lowercase-only regex validation; name validation regex restricts to lowercase letters only (^[a-z0-9-_.]+$).
Server Validators
apps/server-core/src/adapters/http/controllers/entities/policy/utils/validation.ts, apps/server-core/src/core/identity/password-recovery/service.ts
PolicyValidator and PasswordRecoveryService normalize name/email fields via .trim().toLowerCase() before validation.
Repository Lookups
apps/server-core/src/app/modules/database/repositories/*/repository.ts (client, permission, policy, realm, robot, role, scope, user)
Switches name-based lookup queries from SQL LIKE pattern matching to exact equality (=) across all findOneByName() and conditional findOne() methods.
Identity Provider Account Module
apps/server-core/src/core/identity/provider/account/module.ts
Normalizes user.name and candidate names to lowercase during saveUser flow and fallback NanoID generation.
Test Fixtures & Data Generators
apps/server-core/test/utils/domains/*.ts (client, policy, role-attribute, user-attribute, user)
Updates fake data creation functions to generate lowercase names and emails.
Unit Tests
apps/server-core/test/unit/... (permission, role, scope modules; password-recovery, account, registration services)
Adjusts test inputs and assertions to use lowercase names/emails; normalizes dynamically generated faker values before test execution.
Name Validation Unit Test
packages/core-kit/test/unit/helpers/name.spec.ts
Updates test expectation for uppercase name input to assert invalid instead of valid.

Possibly related PRs

Poem

🐰 Canonicalization hops true,
Trimming spaces, lowercasing through,
Names and emails unified,
Exact matches justified,
Order from chaos, queries renewed! 🎉


🎯 3 (Moderate) | ⏱️ ~20 minutes

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The pull request title 'restrict entity names to lowercase characters' accurately and concisely summarizes the primary change across the changeset: enforcing lowercase normalization for identifier-style names across all entities.
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 feat/canonical-name-normalization

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
Review rate limit: 0/1 reviews remaining, refill in 19 minutes and 25 seconds.

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 tightens the core “entity name” validator to enforce lowercase-only identifier names, aiming to remove cross-database inconsistencies (e.g., MySQL case-insensitive collations treating Foo/foo as duplicates while PostgreSQL allows both).

Changes:

  • Update isNameValid to restrict names to lowercase characters.
  • Update unit tests to expect uppercase input to be invalid.
  • Adjust several server-core entity controller tests to use lowercase fixture names.

Reviewed changes

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

Show a summary per file
File Description
packages/core-kit/src/helpers/name-valid.ts Tightens the name validation regex + updates the thrown error message.
packages/core-kit/test/unit/helpers/name.spec.ts Updates unit test expectation for uppercase input to be invalid.
apps/server-core/test/unit/http/controllers/entities/scope.spec.ts Updates scope update tests to use lowercase names.
apps/server-core/test/unit/http/controllers/entities/role.spec.ts Updates role update tests to use lowercase names.
apps/server-core/test/unit/http/controllers/entities/permission/module.spec.ts Updates permission update tests to use lowercase names.

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

Comment on lines +22 to 28
if (/^[a-z0-9-_.]+$/.test(input)) {
return true;
}

if (options.throwOnFailure) {
throw new AuthupError('Only the characters [A-Za-z0-9-_.]+ are allowed.');
throw new AuthupError('Only the characters [a-z0-9-_.]+ are allowed.');
}
Comment on lines +22 to 24
if (/^[a-z0-9-_.]+$/.test(input)) {
return true;
}
tada5hi added 3 commits April 28, 2026 23:42
Mirror the lowercase-only restriction from name to email and to the
random fallback used when an external identity provider's claimed name
fails validation.

- UserValidator: email field gains a regex check rejecting any
  uppercase letter (kept the underlying z.email() format check)
- PasswordRecoveryService: forgotPassword's email lookup applies the
  same regex via the validup chain (.matches(/^[^A-Z]+$/))
- IdentityProviderAccountManager: random username fallback's nanoid
  alphabet narrowed to lowercase + digits + '-_'
- Test fixtures (createFakeUser/createFakeClient/createFakePolicy/
  createFakeUserAttribute/createFakeRoleAttribute) lowercase faker
  outputs that flow into name/email columns

External identity providers may still return mixed-case attribute
candidates; that boundary (canonicalize on ingress) is tracked as a
follow-up in plan 007.
Add .trim().toLowerCase() before the lowercase-only regex on every
identifier-style validator so callers can submit mixed-case input
that gets silently canonicalized; the regex stays as a defense-in-
depth assertion that the post-transform value is canonical.

Validators updated (Zod / @validup/adapter-zod):
  client, robot, user, role, scope, permission, policy, realm,
  identity-provider — name field gains .trim().toLowerCase()
  user.email — same treatment

Validators updated (@validup/adapter-validator chain):
  password-recovery forgotPassword/resetPassword — email and name
  fields gain .trim().toLowerCase() (and the email path keeps the
  .matches(/^[^A-Z]+$/) defense-in-depth check)
  policy HTTP-layer validator — name field same

External boundary canonicalization (IdentityProviderAccountManager):
  attributeCandidates.name entries are lowercased before validation
  so a real upstream username like 'John.Doe' becomes 'john.doe'
  instead of falling through to the random nanoid fallback. The
  initial output.name (from attributesSelf) is also canonicalized
  for the create path.

Tests updated: account.spec.ts now exercises the canonicalization
explicitly (input 'fooBarBaz' → output 'foobarbaz').

576/576 core tests green; lint clean.
Add a "Canonical Identifier Form" section to architecture.md
describing what's canonicalized (name on every entity, user.email),
why (cross-DB collation divergence between MySQL ci and Postgres
default), and the three enforcement layers (validator transform,
validator regex defense-in-depth, external boundary canonicalization
at IdP ingress).

Update conventions.md with a one-line rule plus pointer to the
detailed section, so adding a new identifier column has a clear
checklist (validator transform, repository = lookup, migration entry).

@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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
apps/server-core/src/app/modules/database/repositories/role/repository.ts (1)

77-88: ⚠️ Potential issue | 🟠 Major

Guard this exact-match lookup behind the canonicalization backfill.

Switching from LIKE to = is correct for normalized names, but it will strand any existing mixed-case role.name rows until the data migration has completed. Please gate the rollout or keep a temporary fallback until the backfill is guaranteed in production.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server-core/src/app/modules/database/repositories/role/repository.ts`
around lines 77 - 88, The exact-match change in findOneByName should be guarded
so pre-backfill mixed-case rows are still found: add a check for the
canonicalization backfill/rollout flag (e.g., a config/feature toggle like
isCanonicalBackfillDone) inside the findOneByName method and, if the backfill is
not confirmed, fall back to the previous behavior (use the LIKE-based lookup or
a case-insensitive LIKE) in addition to the new '=' lookup; keep the realm
scoping via realmRepository.resolve(realmKey) and ensure the query only returns
one result (deduplicate or prefer the normalized '=' match when both could
match).
apps/server-core/src/app/modules/database/repositories/user/repository.ts (1)

97-105: ⚠️ Potential issue | 🟠 Major

This change will break lookups for non-lowercase names without normalization at call sites.

The identity resolver (apps/server-core/src/core/identity/resolver/module.ts) passes user/client/robot names directly to findOneByName() without lowercasing or normalization (lines 64, 86, 108). The same issue applies to the OAuth2 code request verifier (line 52). Both now perform exact-match queries against database names.

Some paths do normalize (account provisioning at line 135, password recovery at lines 146+), but the primary identity resolution path does not. Existing lookups for names with uppercase characters will silently fail unless the database names are already lowercase. The referenced migration ("plan 008") and canonical-name infrastructure do not appear in the codebase.

Either normalize input at all call sites (especially identity resolver) or add a rollout guard to preserve backward compatibility during migration.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server-core/src/app/modules/database/repositories/user/repository.ts`
around lines 97 - 105, findOneByName currently does an exact-match on user.name
which breaks lookups for names with uppercase characters because callers like
the identity resolver pass raw names; change findOneByName to perform a
case-insensitive lookup by normalizing the input and DB side comparison (e.g.
use LOWER(user.name) = :name and pass name.toLowerCase()) and keep realm
filtering via realmRepository.resolve as-is; alternatively add an explicit flag
param (e.g., caseSensitive = false) to findOneByName so callers can opt into
legacy exact-match during rollout and update identity resolver to call it with
caseSensitive=false until migration completes.
♻️ Duplicate comments (1)
apps/server-core/src/app/modules/database/repositories/policy/repository.ts (1)

90-105: ⚠️ Potential issue | 🟠 Major

Same backfill dependency applies here.

policy.name = :name has the same legacy-row failure mode, so this only works safely if the canonicalization migration is already complete.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server-core/src/app/modules/database/repositories/policy/repository.ts`
around lines 90 - 105, The query in findOneByName currently only matches
policy.name which breaks when rows still use legacy vs canonicalized names;
update findOneByName to compute the canonical form (using the same
canonicalization utility used elsewhere) and change the QueryBuilder predicate
to match either the raw name or the canonical column (e.g., WHERE (policy.name =
:name OR policy.canonical_name = :canonicalName)) and pass both parameters,
while preserving the realm filter and calling
this.repository.extendOneWithEA(entity) as before; reference findOneByName,
this.repository.createQueryBuilder, realmRepository.resolve, and
this.repository.extendOneWithEA to locate where to make the change.
🧹 Nitpick comments (4)
apps/server-core/src/core/identity/password-recovery/service.ts (1)

140-150: Drop the lowercase regex or move it ahead of the sanitizer.

Because both validators call .trim().toLowerCase() before matches(/^[^A-Z]+$/), mixed-case emails are normalized and the custom "Email must be lowercase." message never fires. If canonicalization is the intent, the regex is redundant; if rejection is the intent, validate before lowercasing.

♻️ Suggested cleanup
                 return chain
                     .exists()
                     .notEmpty()
                     .trim()
                     .toLowerCase()
-                    .isEmail()
-                    .matches(/^[^A-Z]+$/)
-                    .withMessage('Email must be lowercase.');
+                    .isEmail();

Apply the same cleanup to the second email validator block as well.

Also applies to: 185-197

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server-core/src/core/identity/password-recovery/service.ts` around lines
140 - 150, The email validator currently lowercases inputs via
.trim().toLowerCase() before applying .matches(/^[^A-Z]+$/) so the "Email must
be lowercase." message never triggers; either remove the redundant matches()
check if canonicalizing emails, or move the matches() call before the
.toLowerCase() sanitizer to enforce rejection of mixed-case addresses. Update
the oneOfContainer.mount('email', createValidator(...)) blocks (both the first
block and the second block around the other email validator) accordingly so the
intent is consistent: drop the regex when normalizing, or validate for uppercase
before calling .toLowerCase() to preserve the error message.
packages/core-kit/src/domains/user/validator.ts (1)

83-88: Remove the lowercase regex here.

Because the value is already lowercased before regex(...), mixed-case emails will still be accepted and the custom "Email must be lowercase." message can never fire. If canonicalization is the goal, the regex is redundant; if rejection is the goal, validate before lowercasing.

♻️ Suggested cleanup
                 z.email()
                     .trim()
                     .toLowerCase()
-                    .regex(/^[^A-Z]+$/, 'Email must be lowercase.'),
+                    ,
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/core-kit/src/domains/user/validator.ts` around lines 83 - 88, The
current emailValidator chains .toLowerCase() then .regex(/^[^A-Z]+$/, 'Email
must be lowercase.'), so the lowercase check never triggers; remove the
redundant lowercase regex from the createValidator call (the chain on
z.email().trim().toLowerCase()) so canonicalization is the only behavior, or if
you intend to reject mixed-case input instead, move the regex check before
.toLowerCase() (i.e., apply the regex on the raw z.email().trim() before calling
.toLowerCase()). Ensure the change is made in the emailValidator definition that
calls createValidator.
apps/server-core/src/app/modules/database/repositories/permission/repository.ts (1)

62-68: Gate this exact-match lookup on the canonicalization backfill.

Switching from LIKE to = is correct only after every existing permission name has been normalized; otherwise legacy rows become unreachable during rollout. Please make sure plan 008 is enforced before this ships.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@apps/server-core/src/app/modules/database/repositories/permission/repository.ts`
around lines 62 - 68, The equality lookup was switched from LIKE to =
prematurely; gate the exact-match operator on the canonicalization backfill
(plan 008). In the permission repository method that builds the query (where
qb.where('permission.name = :name'...) and the realm branch that uses
qb.andWhere), introduce a check such as isPlan008Complete() or a
config/feature-flag (e.g., isCanonicalizationBackfillComplete()) and choose the
operator accordingly (use '=' only when the backfill is complete, otherwise use
'LIKE' or the previous behavior), applying the same conditional operator for the
realm-scoped andWhere clause so legacy rows remain reachable until plan 008 is
enforced.
apps/server-core/src/app/modules/database/repositories/robot/repository.ts (1)

92-116: Same rollout gate applies here.

The exact-match predicate is fine post-migration, but it will miss any legacy mixed-case robot names until the canonicalization backfill completes. Please make sure the deployment is gated on that migration.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server-core/src/app/modules/database/repositories/robot/repository.ts`
around lines 92 - 116, The exact-match logic in findOne (and the caller
findOneByIdOrName) will miss legacy mixed-case robot names until the
canonicalization backfill runs; add a rollout gate that checks the migration
completion flag (e.g., isRobotCanonicalizationBackfillComplete or similar
feature flag) and, if the backfill is not complete, use a case-insensitive
lookup (ILIKE or lower(name) = lower(...)) as a fallback in findOne (and ensure
findOneByIdOrName still delegates correctly), otherwise keep the strict
exact-match behavior; ensure the gate is read from a shared
feature-flag/migration-status provider so deployment can be gated until the
backfill finishes.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@apps/server-core/src/app/modules/database/repositories/client/repository.ts`:
- Around line 95-97: The exact-match change in findOneByName breaks lookups for
pre-backfill mixed-case names; revert to a case-insensitive lookup until plan
008 is applied by changing the query builder to compare names case-insensitively
(e.g. use LOWER(client.name) = LOWER(:name) or Postgres ILIKE) in the
findOneByName method and the other name-based query block around lines 109-115
so existing mixed-case rows are still found, and add a TODO comment to switch to
exact match after the backfill/migration completes.

---

Outside diff comments:
In `@apps/server-core/src/app/modules/database/repositories/role/repository.ts`:
- Around line 77-88: The exact-match change in findOneByName should be guarded
so pre-backfill mixed-case rows are still found: add a check for the
canonicalization backfill/rollout flag (e.g., a config/feature toggle like
isCanonicalBackfillDone) inside the findOneByName method and, if the backfill is
not confirmed, fall back to the previous behavior (use the LIKE-based lookup or
a case-insensitive LIKE) in addition to the new '=' lookup; keep the realm
scoping via realmRepository.resolve(realmKey) and ensure the query only returns
one result (deduplicate or prefer the normalized '=' match when both could
match).

In `@apps/server-core/src/app/modules/database/repositories/user/repository.ts`:
- Around line 97-105: findOneByName currently does an exact-match on user.name
which breaks lookups for names with uppercase characters because callers like
the identity resolver pass raw names; change findOneByName to perform a
case-insensitive lookup by normalizing the input and DB side comparison (e.g.
use LOWER(user.name) = :name and pass name.toLowerCase()) and keep realm
filtering via realmRepository.resolve as-is; alternatively add an explicit flag
param (e.g., caseSensitive = false) to findOneByName so callers can opt into
legacy exact-match during rollout and update identity resolver to call it with
caseSensitive=false until migration completes.

---

Duplicate comments:
In `@apps/server-core/src/app/modules/database/repositories/policy/repository.ts`:
- Around line 90-105: The query in findOneByName currently only matches
policy.name which breaks when rows still use legacy vs canonicalized names;
update findOneByName to compute the canonical form (using the same
canonicalization utility used elsewhere) and change the QueryBuilder predicate
to match either the raw name or the canonical column (e.g., WHERE (policy.name =
:name OR policy.canonical_name = :canonicalName)) and pass both parameters,
while preserving the realm filter and calling
this.repository.extendOneWithEA(entity) as before; reference findOneByName,
this.repository.createQueryBuilder, realmRepository.resolve, and
this.repository.extendOneWithEA to locate where to make the change.

---

Nitpick comments:
In
`@apps/server-core/src/app/modules/database/repositories/permission/repository.ts`:
- Around line 62-68: The equality lookup was switched from LIKE to =
prematurely; gate the exact-match operator on the canonicalization backfill
(plan 008). In the permission repository method that builds the query (where
qb.where('permission.name = :name'...) and the realm branch that uses
qb.andWhere), introduce a check such as isPlan008Complete() or a
config/feature-flag (e.g., isCanonicalizationBackfillComplete()) and choose the
operator accordingly (use '=' only when the backfill is complete, otherwise use
'LIKE' or the previous behavior), applying the same conditional operator for the
realm-scoped andWhere clause so legacy rows remain reachable until plan 008 is
enforced.

In `@apps/server-core/src/app/modules/database/repositories/robot/repository.ts`:
- Around line 92-116: The exact-match logic in findOne (and the caller
findOneByIdOrName) will miss legacy mixed-case robot names until the
canonicalization backfill runs; add a rollout gate that checks the migration
completion flag (e.g., isRobotCanonicalizationBackfillComplete or similar
feature flag) and, if the backfill is not complete, use a case-insensitive
lookup (ILIKE or lower(name) = lower(...)) as a fallback in findOne (and ensure
findOneByIdOrName still delegates correctly), otherwise keep the strict
exact-match behavior; ensure the gate is read from a shared
feature-flag/migration-status provider so deployment can be gated until the
backfill finishes.

In `@apps/server-core/src/core/identity/password-recovery/service.ts`:
- Around line 140-150: The email validator currently lowercases inputs via
.trim().toLowerCase() before applying .matches(/^[^A-Z]+$/) so the "Email must
be lowercase." message never triggers; either remove the redundant matches()
check if canonicalizing emails, or move the matches() call before the
.toLowerCase() sanitizer to enforce rejection of mixed-case addresses. Update
the oneOfContainer.mount('email', createValidator(...)) blocks (both the first
block and the second block around the other email validator) accordingly so the
intent is consistent: drop the regex when normalizing, or validate for uppercase
before calling .toLowerCase() to preserve the error message.

In `@packages/core-kit/src/domains/user/validator.ts`:
- Around line 83-88: The current emailValidator chains .toLowerCase() then
.regex(/^[^A-Z]+$/, 'Email must be lowercase.'), so the lowercase check never
triggers; remove the redundant lowercase regex from the createValidator call
(the chain on z.email().trim().toLowerCase()) so canonicalization is the only
behavior, or if you intend to reject mixed-case input instead, move the regex
check before .toLowerCase() (i.e., apply the regex on the raw z.email().trim()
before calling .toLowerCase()). Ensure the change is made in the emailValidator
definition that calls createValidator.
🪄 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: d6aefe0d-6404-4a91-ac05-36e892f6dcda

📥 Commits

Reviewing files that changed from the base of the PR and between cc789a9 and 63935ec.

📒 Files selected for processing (35)
  • .agents/architecture.md
  • .agents/conventions.md
  • apps/server-core/src/adapters/http/controllers/entities/policy/utils/validation.ts
  • apps/server-core/src/app/modules/database/repositories/client/repository.ts
  • apps/server-core/src/app/modules/database/repositories/permission/repository.ts
  • apps/server-core/src/app/modules/database/repositories/policy/repository.ts
  • apps/server-core/src/app/modules/database/repositories/realm/repository.ts
  • apps/server-core/src/app/modules/database/repositories/robot/repository.ts
  • apps/server-core/src/app/modules/database/repositories/role/repository.ts
  • apps/server-core/src/app/modules/database/repositories/scope/repository.ts
  • apps/server-core/src/app/modules/database/repositories/user/repository.ts
  • apps/server-core/src/core/identity/password-recovery/service.ts
  • apps/server-core/src/core/identity/provider/account/module.ts
  • apps/server-core/test/unit/core/identity/password-recovery/service.spec.ts
  • apps/server-core/test/unit/core/identity/provider/account.spec.ts
  • apps/server-core/test/unit/core/identity/registration/service.spec.ts
  • apps/server-core/test/unit/http/controllers/entities/permission/module.spec.ts
  • apps/server-core/test/unit/http/controllers/entities/role.spec.ts
  • apps/server-core/test/unit/http/controllers/entities/scope.spec.ts
  • apps/server-core/test/utils/domains/client.ts
  • apps/server-core/test/utils/domains/policy.ts
  • apps/server-core/test/utils/domains/role-attribute.ts
  • apps/server-core/test/utils/domains/user-attribute.ts
  • apps/server-core/test/utils/domains/user.ts
  • packages/core-kit/src/domains/client/validator.ts
  • packages/core-kit/src/domains/identity-provider/validator.ts
  • packages/core-kit/src/domains/permission/validator.ts
  • packages/core-kit/src/domains/policy/validator.ts
  • packages/core-kit/src/domains/realm/validator.ts
  • packages/core-kit/src/domains/robot/validator.ts
  • packages/core-kit/src/domains/role/validator.ts
  • packages/core-kit/src/domains/scope/validator.ts
  • packages/core-kit/src/domains/user/validator.ts
  • packages/core-kit/src/helpers/name-valid.ts
  • packages/core-kit/test/unit/helpers/name.spec.ts

Comment on lines 95 to +97
async findOneByName(name: string, realmKey?: string): Promise<Client | null> {
const qb = this.repository.createQueryBuilder('client');
qb.where('client.name LIKE :name', { name });
qb.where('client.name = :name', { name });

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Hold the exact-match lookup change until the backfill is guaranteed.

Both branches now require already-canonical names. If plan 008 has not been applied yet, any pre-existing mixed-case client rows will no longer be found, which is a user-visible regression for client reads.

Also applies to: 109-115

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server-core/src/app/modules/database/repositories/client/repository.ts`
around lines 95 - 97, The exact-match change in findOneByName breaks lookups for
pre-backfill mixed-case names; revert to a case-insensitive lookup until plan
008 is applied by changing the query builder to compare names case-insensitively
(e.g. use LOWER(client.name) = LOWER(:name) or Postgres ILIKE) in the
findOneByName method and the other name-based query block around lines 109-115
so existing mixed-case rows are still found, and add a TODO comment to switch to
exact match after the backfill/migration completes.

tada5hi added 3 commits April 29, 2026 10:54
LIKE :name with no wildcards in the bound value behaves identically to
= :name on both supported databases:
- MySQL with utf8mb4_*_ci collation: both case-insensitive
- PostgreSQL: both case-sensitive
The LIKE form was misleading (reads as "pattern match" but the binding
contains no patterns) and exposed a wildcard hole if input ever bypassed
canonicalization. Switching to = closes that hole and aligns the SQL
with what the code actually means.

Files: realm, role, scope, permission, policy, client, robot, user
repositories — findOneByName / findOne methods.

This commit is NOT a deploy-blocker for the canonical-name data
migration (plan 008). Behavior on existing deployments:
- MySQL: zero change. Mixed-case rows remain findable case-insensitively.
- PostgreSQL: zero case-sensitivity change. Mixed-case rows remain
  findable by their original casing; the validator transform on new
  writes will canonicalize names going forward, so old rows stay in
  their original case until next update. The data migration is
  eventual cleanup — running it later (or never) won't break this
  commit.
Two HTTP integration tests still set name='TestA' on update and assert
the response equals the original input. With the validator transform,
the response now contains the canonical 'testa', so the assertions
fired (only on Postgres, since MySQL's *_ci collation didn't surface
the mismatch the same way through the API client roundtrip).

Updated to 'testa' in both. 773/773 Postgres + 773/773 MySQL tests
green.
…rule

The ALPHA_UPPER_NUM_HYPHEN_UNDERSCORE_DOT vuelidate rule still permitted
uppercase via /^[a-zA-Z0-9-_.]*$/, while the server-side validators
restrict to /^[a-z0-9-_.]+$/ (with .trim().toLowerCase() transform).
The UI's pre-submit validator was looser than the API contract.

Tighten the rule's regex to /^[a-z0-9-_.]*$/ and update the en/de i18n
strings to reflect the actual allowed character set. Enum key name kept
as-is (ALPHA_UPPER_NUM_HYPHEN_UNDERSCORE_DOT) to avoid a breaking enum
rename for downstream consumers; renaming is a separate concern.
@tada5hi
tada5hi force-pushed the feat/canonical-name-normalization branch from 63935ec to b6ef521 Compare April 29, 2026 09:12
@tada5hi
tada5hi merged commit 6b6be70 into master Apr 29, 2026
8 checks passed
@tada5hi
tada5hi deleted the feat/canonical-name-normalization branch April 29, 2026 09:18
@github-actions github-actions Bot mentioned this pull request Apr 29, 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