Skip to content

fix: scope OAuth2 password grant user resolution to a realm (default master) - #3175

Merged
tada5hi merged 9 commits into
masterfrom
fix/password-grant-realm-scoping
Jul 2, 2026
Merged

tada5hi merged 9 commits into
masterfrom
fix/password-grant-realm-scoping

Conversation

@tada5hi

@tada5hi tada5hi commented Jul 2, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

The OAuth2 password grant did not scope user resolution to a realm. With no realm hint and a name-based username, the lookup ran with no realm predicate and no ordering, returning a non-deterministic cross-realm row in multi-realm deployments with same-named users — a legitimate user could be denied login (password verified against another realm's row), and it was a latent cross-realm auth-confusion surface.

Change

  • The grant resolves the user realm once from realm_id ?? realm_name (each accepts a realm UUID or name; the hint is trimmed/lowercased per the canonical-identifier convention; realm_name was previously silently dropped and is now honored) via IRealmRepository.resolve(hint, true), defaulting to the master realm when no hint is supplied. The resolved realm.id feeds both the client and user authenticators, so name-based resolution is deterministic and the LDAP provider lookup is realm-scoped.
  • resolve(hint, true) now throws InternalError when the master realm row is missing, instead of returning null at runtime despite the non-null overload (previously a TypeError 500 on /token for unprovisioned deployments).
  • findByProtocol skips the redundant realm re-resolve for UUID keys (and fails closed on unknown UUIDs).
  • client-web-kit: store.login() gated the realm on the wrong ref, and LoginForm submitted a stale form.realm_id while the SSR /authorize page supplies the realm via codeRequest.realm_id (picker hidden) — the picked realm was never transmitted. form.realm_id is now seeded from codeRequest.realm_id (single source) and forwarded end-to-end.

Behavior changes (release-note worthy)

  • Realm-less password grants now match master-realm users only. Non-master users must pass realm_id or realm_name (UUID or name). Single-realm deployments and the provisioned master admin are unaffected.
  • An LDAP identity provider registered in a non-master realm is no longer tried on realm-less grants — send a realm hint.
  • A name-identified confidential client on this grant must live in the user's realm (UUID-identified clients are unaffected).
  • An unknown realm hint falls back to master (consistent with registration / password-recovery).
  • On the SSR /authorize page, login is pinned to the client's realm — that page authenticates that realm's users only.
  • HTTP Basic auth, authorization_code, refresh_token, client_credentials, and robot_credentials are intentionally untouched (see plan 037 non-goals in .agents/architecture.md).

Testing

  • New HTTP-level cases in grant-password.spec.ts: same-name-in-two-realms determinism guard, realm selection via realm_id (UUID and name) and realm_name (incl. mixed-case/whitespace canonicalization), realm-less rejection of non-master users, unknown-hint master fallback.
  • Full server-core suite: 95 files / 959 tests green (includes LDAP password grant, Basic-auth-authenticated suite, all other grants, SSR UI pages).
  • Reviewed by a multi-agent adversarial pass; all confirmed findings addressed or documented (deferred: regression test for the interactive-login realm plumbing — client-web-kit has no test infra; realm lookup on /token is uncached — one indexed SELECT per login).

Summary by CodeRabbit

  • New Features

    • Password-based login now deterministically resolves the realm from the provided realm hint (realm_id/realm_name) and scopes credential + token issuance to the resolved realm, falling back to the master realm.
    • Login form now reactively synchronizes the realm field from an existing code request.
  • Bug Fixes

    • Improved realm/client/user/robot/policy lookups by normalizing names (trim + lowercase) for non-UUID matching.
    • Added clearer handling for missing master realm during fallback resolution.
  • Documentation

    • Updated OAuth2 password-flow documentation and authentication realm-resolution rules.
  • Tests

    • Added unit coverage for realm selection, realm-scoped user routing case-insensitivity, and canonicalization behavior.

Follow-up review pass

A second review pass over the branch produced three more commits:

  • server-core: username/password are now extracted as non-empty strings and rejected with invalid_request when missing (no raw non-string values reach the SQL layer); the realm hint is trimmed per field, so a whitespace-only realm_id no longer masks a valid realm_name; findByProtocol fails closed for unknown realm names (symmetric with unknown UUIDs). Regression coverage added for the name-identified confidential-client realm scoping.
  • client-web-kit: LoginForm tracks codeRequest.realm_id through an immediate watch instead of a one-shot setup seed, so a late-arriving or replaced codeRequest prop in downstream consumers cannot strand the form realm-less.
  • docs: the OAuth2 guide notes that an unknown realm value also falls back to master.

Full server-core suite after the pass: 95 files / 960 tests green.

Canonical name lookups (auth surface)

Two follow-up items were pulled in after review discussion:

  • Repository-level lookup canonicalization: name-based lookups on the authentication surface (trim().toLowerCase() on the lookup key) in the user/client/robot identity repositories, OAuth2ClientRepository (/authorize client resolution), and RealmRepositoryAdapter.findOneByName. Mixed-case Basic usernames, token-body credentials, and /realms/<key> path segments now resolve identically on MySQL and PostgreSQL (names are stored canonically; previously PostgreSQL missed where MySQL's ci collation matched). LDAP binds still receive the raw credential. Tests: mixed-case password-grant username, client-by-name, robot-by-name, /realms/MASTER path + Basic ADMIN username.
  • Provisioning canonical persistence: the file-source entity validators run group-less, so core-kit validator transforms never apply — file-provisioned names could persist raw, and the scoped lookups above would then lock those identities out on PostgreSQL. Every entity synchronizer now canonicalizes attributes.name, and relation-name references (entity resolver, permission→policy names) are canonicalized before lookup. Covered by new synchronizer unit tests.

Full server-core suite: 95 files / 966 tests green.

tada5hi added 3 commits July 2, 2026 09:50
…fault master)

The OAuth2 password grant resolves the user realm once from
realm_id ?? realm_name (each accepts a realm UUID or name; the hint is
canonicalized via trim/toLowerCase and realm_name is now honored instead
of silently dropped) through IRealmRepository.resolve(hint, true),
defaulting to the master realm when no hint is supplied. The resolved
realm id is passed to both the client and user authenticators, making
name-based login deterministic instead of matching an arbitrary
cross-realm row.

resolve(hint, true) now throws InternalError when the master realm row
is missing (violated provisioning invariant) instead of returning null
at runtime despite the non-null overload. findByProtocol skips the
redundant realm re-resolve for UUID keys and fails closed on unknown
UUIDs.
store.login() gated the realm_id parameter on the store's realmId ref
(unset before login) instead of the login context, so the realm picked
in LoginForm was never transmitted. LoginForm additionally kept two
competing realm sources (form.realm_id vs a codeRequest-preferring
computed) and submitted the stale form value — on the SSR /authorize
page the picker is hidden and the realm arrives via codeRequest, so the
grant went realm-less. form.realm_id is now seeded from
codeRequest.realm_id in setup (single source) and submit/store both
forward it.
Copilot AI review requested due to automatic review settings July 2, 2026 07:50
@coderabbitai

coderabbitai Bot commented Jul 2, 2026 •

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@tada5hi, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 41 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 9e30f320-9681-489c-b031-bba1220c6e1c

📥 Commits

Reviewing files that changed from the base of the PR and between eafe9d7 and c8f11d7.

📒 Files selected for processing (2)
  • apps/server-core/src/core/provisioning/synchronizer/policy/module.ts
  • apps/server-core/test/unit/core/provisioning/synchronizer/policy.spec.ts
📝 Walkthrough

Walkthrough

This PR adds password-grant realm resolution via realm_id/realm_name, wires realmRepository through token handling, normalizes name-based repository and provisioning lookups, updates client login realm selection, and refreshes related tests and documentation.

Changes

Canonical realm and name resolution

Layer / File(s) Summary
Realm and identity lookup
apps/server-core/src/app/modules/database/repositories/realm/repository.ts, .../identity-provider/repository.ts, apps/server-core/src/core/entities/realm/types.ts
Realm fallback resolution throws when master lookup fails, realm names are normalized before lookup, identity-provider lookup adds a UUID branch, and repository interface docs describe the fallback overload.
Password grant realm resolution
apps/server-core/src/adapters/http/adapters/oauth2/grant-types/password.ts, .../grant-types/types.ts, .../grant-types/utils/credentials.ts, apps/server-core/src/adapters/http/controllers/workflows/token/module.ts, .../types.ts, apps/server-core/src/app/modules/http/modules/controller.ts
Password grant request handling now reads required credentials, derives a canonical realm hint, resolves it through realmRepository, and uses the resolved realm for client and user authentication; the grant context and controller wiring carry the new repository dependency.
Repository and resolver normalization
apps/server-core/src/app/modules/identity/repositories/client.ts, .../robot.ts, .../user.ts, apps/server-core/src/app/modules/oauth2/repositories/client/repository.ts, apps/server-core/src/core/provisioning/synchronizer/...
Client, robot, user, OAuth2 client, and provisioning entity resolvers normalize non-UUID names before querying; provisioning synchronizers canonicalize incoming names before merge and relationship updates; policy resolution normalizes policy names before lookup.
Client login realm selection
packages/client-web-kit/src/components/workflows/login/LoginForm.vue, packages/client-web-kit/src/core/store/create.ts
LoginForm.vue watches incoming code-request realm changes and keeps form.realm_id in sync, while the store login flow sends ctx.realmId in the password login payload.
Tests and documentation
apps/server-core/test/unit/..., .agents/architecture.md, docs/src/guide/development/api-oauth2.md
Password-grant tests cover master-realm fallback, realm hint variants, client scoping, and mixed-case usernames; additional tests cover realm-scoped controller access and robot credential login; architecture and API docs describe the updated realm-resolution behavior.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant TokenController
  participant HTTPPasswordGrant
  participant IRealmRepository
  participant CredentialsAuthenticator

  Client->>TokenController: POST /token
  TokenController->>HTTPPasswordGrant: runWithRequest(...)
  HTTPPasswordGrant->>HTTPPasswordGrant: read username/password and realmHint
  HTTPPasswordGrant->>IRealmRepository: resolve(realmHint, true)
  IRealmRepository-->>HTTPPasswordGrant: realm.id
  HTTPPasswordGrant->>CredentialsAuthenticator: authenticate(username, password, realm.id)
  CredentialsAuthenticator-->>HTTPPasswordGrant: user
  HTTPPasswordGrant-->>Client: token response
Loading

Possibly related PRs

  • authup/authup#2880: Both PRs touch the realm repository abstraction/adapter layer (IRealmRepository/RealmRepositoryAdapter) that the main PR then uses to implement canonical realm resolution in the OAuth2 password grant.
  • authup/authup#3020: Both PRs modify the OAuth2 password grant implementation—HTTPPasswordGrant/token-controller wiring now incorporates client authentication-related context, and the main PR extends that same password-grant path with canonical realm resolution for how client/user authentication is scoped.
  • authup/authup#3024: Both PRs implement canonical identifier normalization via trim().toLowerCase() and tighten name/realm lookup semantics—main PR extends this specifically to OAuth2 password-grant realm hints and RealmRepositoryAdapter.findOneByName canonical input, while retrieved PR makes the broader “lowercase canonical identifier” rule consistent across the system.
🚥 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 clearly summarizes the main change: scoping OAuth2 password-grant user resolution to a realm with master fallback.
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.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/password-grant-realm-scoping

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.

@pkg-pr-new

pkg-pr-new Bot commented Jul 2, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

authup

npm i https://pkg.pr.new/authup@3175

@authup/client-web

npm i https://pkg.pr.new/@authup/client-web@3175

@authup/server-core

npm i https://pkg.pr.new/@authup/server-core@3175

@authup/access

npm i https://pkg.pr.new/@authup/access@3175

@authup/client-web-kit

npm i https://pkg.pr.new/@authup/client-web-kit@3175

@authup/client-web-kit-theme

npm i https://pkg.pr.new/@authup/client-web-kit-theme@3175

@authup/client-web-nuxt

npm i https://pkg.pr.new/@authup/client-web-nuxt@3175

@authup/client-web-theme

npm i https://pkg.pr.new/@authup/client-web-theme@3175

@authup/core-http-kit

npm i https://pkg.pr.new/@authup/core-http-kit@3175

@authup/core-kit

npm i https://pkg.pr.new/@authup/core-kit@3175

@authup/core-realtime-kit

npm i https://pkg.pr.new/@authup/core-realtime-kit@3175

@authup/errors

npm i https://pkg.pr.new/@authup/errors@3175

@authup/i18n

npm i https://pkg.pr.new/@authup/i18n@3175

@authup/kit

npm i https://pkg.pr.new/@authup/kit@3175

@authup/server-adapter-kit

npm i https://pkg.pr.new/@authup/server-adapter-kit@3175

@authup/server-adapter-node

npm i https://pkg.pr.new/@authup/server-adapter-node@3175

@authup/server-adapter-socket-io

npm i https://pkg.pr.new/@authup/server-adapter-socket-io@3175

@authup/server-adapter-web

npm i https://pkg.pr.new/@authup/server-adapter-web@3175

@authup/server-kit

npm i https://pkg.pr.new/@authup/server-kit@3175

@authup/server-test-kit

npm i https://pkg.pr.new/@authup/server-test-kit@3175

@authup/specs

npm i https://pkg.pr.new/@authup/specs@3175

commit: eafe9d7

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 fixes a security/correctness issue in the OAuth2 password grant where user (and LDAP provider) resolution could be non-deterministic across realms when usernames collide. It introduces deterministic realm-scoped resolution (defaulting to master when no hint is provided), hardens realm lookup behavior, and fixes the client-web SSR authorize/login realm plumbing so the selected realm is actually transmitted.

Changes:

  • Server-core: Resolve the user realm once (realm_id ?? realm_name, canonicalized), default to master, and pass the resolved realm.id into both client and user authentication for the password grant.
  • Server-core: Make IRealmRepository.resolve(hint, true) throw an InternalError when the master realm is missing; optimize identity provider lookup to avoid re-resolving realm UUIDs and fail closed for unknown UUIDs.
  • Client-web-kit + docs + tests: Fix realm propagation in login/store, document the realm behavior, and add HTTP-level tests covering realm selection and same-name cross-realm determinism.

Reviewed changes

Copilot reviewed 14 out of 14 changed files in this pull request and generated no comments.

Show a summary per file
File Description
packages/client-web-kit/src/core/store/create.ts Fixes realm_id inclusion logic so the realm hint is actually sent during login when provided.
packages/client-web-kit/src/components/workflows/login/LoginForm.vue Seeds form.realm_id from codeRequest.realm_id to ensure SSR /authorize login is pinned to the intended realm and the value is forwarded.
docs/src/guide/development/api-oauth2.md Documents password-grant realm scoping, default-to-master behavior, and client-by-name realm constraint.
apps/server-core/test/unit/http/controllers/workflows/token/grant-password.spec.ts Adds HTTP-level tests for master defaulting, realm hints (realm_id/realm_name), canonicalization, and unknown-hint fallback.
apps/server-core/src/core/entities/realm/types.ts Documents resolve(..., true) throwing behavior when the provisioning invariant (master realm exists) is violated.
apps/server-core/src/app/modules/http/modules/controller.ts Wires realmRepository into the token controller context.
apps/server-core/src/app/modules/database/repositories/realm/repository.ts Enforces InternalError if master realm cannot be resolved when fallback is requested.
apps/server-core/src/app/modules/database/repositories/identity-provider/repository.ts Optimizes findByProtocol realm scoping: UUID realm keys filter directly; non-UUID keys resolve via realm repository.
apps/server-core/src/adapters/http/controllers/workflows/token/types.ts Extends token controller context with realmRepository.
apps/server-core/src/adapters/http/controllers/workflows/token/module.ts Passes realmRepository into the HTTP password grant instance.
apps/server-core/src/adapters/http/adapters/oauth2/grant-types/utils/credentials.ts Exports readStringField for shared safe string extraction from token request bodies.
apps/server-core/src/adapters/http/adapters/oauth2/grant-types/types.ts Extends password grant context with realmRepository.
apps/server-core/src/adapters/http/adapters/oauth2/grant-types/password.ts Implements canonicalized realm hint resolution with master fallback and scopes both client/user auth to the resolved realm id.
.agents/architecture.md Updates architectural documentation for password-grant realm resolution semantics and explicitly scopes the change.

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

@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

🧹 Nitpick comments (1)
apps/server-core/test/unit/http/controllers/workflows/token/grant-password.spec.ts (1)

15-20: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Solid coverage of the new realm-resolution paths; consider adding a test for the client-realm scoping change.

The new tests correctly exercise master-realm default, realm_id/realm_name/casing hints, and unknown-hint fallback. However, the architecture doc (see .agents/architecture.md "Password grant realm resolution" section) also documents a behavior change where a name-identified confidential client must now live in the same realm as the resolved user, else it fails with invalid_client. That scenario isn't covered here — it's a security-relevant behavior change (previously an unscoped name lookup could match a client in a different realm) and would benefit from a regression test.

Also applies to: 138-236

🤖 Prompt for 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.

In
`@apps/server-core/test/unit/http/controllers/workflows/token/grant-password.spec.ts`
around lines 15 - 20, Add a regression test in grant-password.spec for the
client-realm scoping change in the password grant flow. Extend the existing
realm-resolution coverage around the grant handling path to verify that a
confidential client identified by name is only accepted when it belongs to the
same realm as the resolved user, and that a mismatched realm returns
invalid_client. Use the existing helpers createFakeClient, createFakeRealm,
createFakeUser, and expectClientError, and target the password grant test cases
around the grant-password controller behavior.
🤖 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/app/modules/database/repositories/identity-provider/repository.ts`:
- Around line 165-174: The realm scoping logic in repository.ts currently fails
open for name-based lookups because the `realmRepository.resolve` path skips
`qb.andWhere` when `realm` is null. Update the `realmKey` handling in the
repository method so unresolved names behave like the UUID branch and return no
rows, not all realms; use the existing `isUUID`, `realmRepository.resolve`, and
`qb.andWhere('provider.realm_id = :realmId', ...)` flow to locate and adjust the
fallback behavior.

---

Nitpick comments:
In
`@apps/server-core/test/unit/http/controllers/workflows/token/grant-password.spec.ts`:
- Around line 15-20: Add a regression test in grant-password.spec for the
client-realm scoping change in the password grant flow. Extend the existing
realm-resolution coverage around the grant handling path to verify that a
confidential client identified by name is only accepted when it belongs to the
same realm as the resolved user, and that a mismatched realm returns
invalid_client. Use the existing helpers createFakeClient, createFakeRealm,
createFakeUser, and expectClientError, and target the password grant test cases
around the grant-password controller behavior.
🪄 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: 51fc05c4-ba2b-4c5b-8272-3363d64184f4

📥 Commits

Reviewing files that changed from the base of the PR and between c244de2 and 6ced4cf.

📒 Files selected for processing (14)
  • .agents/architecture.md
  • apps/server-core/src/adapters/http/adapters/oauth2/grant-types/password.ts
  • apps/server-core/src/adapters/http/adapters/oauth2/grant-types/types.ts
  • apps/server-core/src/adapters/http/adapters/oauth2/grant-types/utils/credentials.ts
  • apps/server-core/src/adapters/http/controllers/workflows/token/module.ts
  • apps/server-core/src/adapters/http/controllers/workflows/token/types.ts
  • apps/server-core/src/app/modules/database/repositories/identity-provider/repository.ts
  • apps/server-core/src/app/modules/database/repositories/realm/repository.ts
  • apps/server-core/src/app/modules/http/modules/controller.ts
  • apps/server-core/src/core/entities/realm/types.ts
  • apps/server-core/test/unit/http/controllers/workflows/token/grant-password.spec.ts
  • docs/src/guide/development/api-oauth2.md
  • packages/client-web-kit/src/components/workflows/login/LoginForm.vue
  • packages/client-web-kit/src/core/store/create.ts

tada5hi added 5 commits July 2, 2026 10:34
…y filtering

username/password are extracted via readStringField and rejected with
invalid_request when absent or non-string; the realm hint is trimmed per
field before selection so a whitespace-only realm_id no longer masks a
valid realm_name. findByProtocol now fails closed for an unknown realm
name (symmetric with the unknown-UUID branch). Adds regression coverage
for the name-identified confidential client realm scoping (same-realm
success, realm-less invalid_client).
…ogin form

The one-shot setup seed missed a codeRequest prop that arrives or
changes after mount, stranding the form realm-less while the realm
picker stays hidden. The realm now flows through an immediate watch
into updateRealmId, so the identity-provider query follows as well.
…ned names

Name-based lookups on the authentication surface canonicalize the lookup
key (trim/lowercase) before binding it: the user/client/robot identity
repositories (name and realm-name filter), OAuth2ClientRepository
(/authorize client resolution), and RealmRepositoryAdapter.findOneByName.
Mixed-case Basic usernames, token-body credentials, and /realms/<key>
path segments now resolve identically on MySQL and PostgreSQL. The LDAP
bind still receives the raw credential.

Because lookups now assume canonical storage, provisioning upholds it:
the file-source entity validators run group-less (core-kit validators
mount fields under the CREATE/UPDATE groups), so their canonicalizing
transforms never apply — every entity synchronizer therefore
canonicalizes attributes.name, and relation-name references (entity
resolver, permission->policy names) are canonicalized before lookup.
Without this, mixed-case file-provisioned identities would be locked out
on PostgreSQL by the scoped lookups.

@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/core/provisioning/synchronizer/user/module.ts (1)

132-149: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Normalize client keys before lookup clientRepository.findOneBy({ name: clientKey, ... }) compares the raw relation key against canonically stored client names, so mixed-case or padded keys will silently skip client permission/role assignment. Normalize clientKey in both loops.

🤖 Prompt for 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.

In `@apps/server-core/src/core/provisioning/synchronizer/user/module.ts` around
lines 132 - 149, Normalize the client relation keys before performing the lookup
in the user provisioning path, since the current `clientRepository.findOneBy`
call in the client permissions loop compares the raw `clientKey` and can miss
canonically stored names. Update the handling in the `module.ts` logic that
iterates over `input.relations.clientPermissions` so `clientKey` is normalized
consistently before both the `findOneBy` lookup and any subsequent permission
resolution, ensuring mixed-case or padded keys still match the intended client.
apps/server-core/src/core/provisioning/synchronizer/role/module.ts (1)

85-124: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Normalize permission-name lists before matching

globalPermissionsExclude and globalPermissionsRealmScopeOverrides are compared against canonical permission.name values, but the input lists are used raw here. Case or whitespace mismatches will silently miss, leaving permissions included or falling back to defaultScope. Normalize these names the same way as the resolver.

🤖 Prompt for 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.

In `@apps/server-core/src/core/provisioning/synchronizer/role/module.ts` around
lines 85 - 124, The permission matching in the role synchronizer is using raw
input values for `globalPermissionsExclude` and the realm-scope override map, so
name comparisons can miss when casing or whitespace differs. Update `module.ts`
in the role synchronizer path to normalize those input permission names the same
way `permissionResolver.resolveGlobal`, `permissionResolver.resolveRealm`, and
`buildRealmScopeOverrides` expect canonical `permission.name` values before
filtering or looking up overrides. Keep the existing synchronization flow, but
ensure `globalPermissionsExclude` and `globalPermissionsRealmScopeOverrides` are
compared against normalized names so exclusions and per-permission scopes are
applied consistently.
🧹 Nitpick comments (1)
apps/server-core/src/app/modules/identity/repositories/client.ts (1)

38-73: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Duplicate query-normalization logic across repositories.

The same trim().toLowerCase() name/realm-name lookup pattern is now duplicated verbatim in client.ts, robot.ts, user.ts, and apps/server-core/src/app/modules/oauth2/repositories/client/repository.ts. Consider extracting a shared helper (e.g. a query-builder utility that accepts the alias, key, and realmKey) to avoid four copies drifting out of sync if the canonicalization rule ever changes.

♻️ Example shared helper sketch
// e.g. packages/kit or a shared repository util
export function applyNameRealmFilter<T extends ObjectLiteral>(
    query: SelectQueryBuilder<T>,
    entityAlias: string,
    key: string,
    realmKey?: string,
): void {
    query.where(`${entityAlias}.name = :name`, { name: key.trim().toLowerCase() });
    if (realmKey) {
        if (isUUID(realmKey)) {
            query.andWhere(`${entityAlias}.realm_id = :realmId`, { realmId: realmKey });
        } else {
            query.andWhere('realm.name = :realmName', { realmName: realmKey.trim().toLowerCase() });
        }
    }
}
🤖 Prompt for 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.

In `@apps/server-core/src/app/modules/identity/repositories/client.ts` around
lines 38 - 73, The name/realm lookup normalization logic is duplicated in this
repository’s find path, so extract the shared trim-and-lowercase filtering into
a reusable helper and have this method call it instead of inlining the same
branching. Update the client repository’s find(key, realmKey) flow to use a
common utility that handles the entity alias, key, and realmKey, and then reuse
that same helper from the corresponding robot, user, and OAuth2 client
repository query builders to keep canonicalization consistent.
🤖 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/core/provisioning/synchronizer/policy/module.ts`:
- Around line 39-41: The stale-child cleanup in synchronizeChildren is using
declaredNames captured before synchronize(child) mutates each child’s
attributes.name, so non-canonical source names can be treated as stale and
detached/deleted. Update synchronizeChildren in module.ts to derive the declared
child names after the child synchronization/canonicalization step, following the
same pattern as synchronizeMany, and keep cleanupStaleChildren comparing
canonical names from the synchronized children against existingChildren.

---

Outside diff comments:
In `@apps/server-core/src/core/provisioning/synchronizer/role/module.ts`:
- Around line 85-124: The permission matching in the role synchronizer is using
raw input values for `globalPermissionsExclude` and the realm-scope override
map, so name comparisons can miss when casing or whitespace differs. Update
`module.ts` in the role synchronizer path to normalize those input permission
names the same way `permissionResolver.resolveGlobal`,
`permissionResolver.resolveRealm`, and `buildRealmScopeOverrides` expect
canonical `permission.name` values before filtering or looking up overrides.
Keep the existing synchronization flow, but ensure `globalPermissionsExclude`
and `globalPermissionsRealmScopeOverrides` are compared against normalized names
so exclusions and per-permission scopes are applied consistently.

In `@apps/server-core/src/core/provisioning/synchronizer/user/module.ts`:
- Around line 132-149: Normalize the client relation keys before performing the
lookup in the user provisioning path, since the current
`clientRepository.findOneBy` call in the client permissions loop compares the
raw `clientKey` and can miss canonically stored names. Update the handling in
the `module.ts` logic that iterates over `input.relations.clientPermissions` so
`clientKey` is normalized consistently before both the `findOneBy` lookup and
any subsequent permission resolution, ensuring mixed-case or padded keys still
match the intended client.

---

Nitpick comments:
In `@apps/server-core/src/app/modules/identity/repositories/client.ts`:
- Around line 38-73: The name/realm lookup normalization logic is duplicated in
this repository’s find path, so extract the shared trim-and-lowercase filtering
into a reusable helper and have this method call it instead of inlining the same
branching. Update the client repository’s find(key, realmKey) flow to use a
common utility that handles the entity alias, key, and realmKey, and then reuse
that same helper from the corresponding robot, user, and OAuth2 client
repository query builders to keep canonicalization consistent.
🪄 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: 59f48359-5f03-4f1e-aaed-84334cf1412e

📥 Commits

Reviewing files that changed from the base of the PR and between 6ced4cf and eafe9d7.

📒 Files selected for processing (24)
  • .agents/architecture.md
  • apps/server-core/src/adapters/http/adapters/oauth2/grant-types/password.ts
  • apps/server-core/src/app/modules/database/repositories/identity-provider/repository.ts
  • apps/server-core/src/app/modules/database/repositories/realm/repository.ts
  • apps/server-core/src/app/modules/identity/repositories/client.ts
  • apps/server-core/src/app/modules/identity/repositories/robot.ts
  • apps/server-core/src/app/modules/identity/repositories/user.ts
  • apps/server-core/src/app/modules/oauth2/repositories/client/repository.ts
  • apps/server-core/src/core/provisioning/synchronizer/base.ts
  • apps/server-core/src/core/provisioning/synchronizer/client/module.ts
  • apps/server-core/src/core/provisioning/synchronizer/entity-resolver.ts
  • apps/server-core/src/core/provisioning/synchronizer/permission/module.ts
  • apps/server-core/src/core/provisioning/synchronizer/policy/module.ts
  • apps/server-core/src/core/provisioning/synchronizer/realm/module.ts
  • apps/server-core/src/core/provisioning/synchronizer/robot/module.ts
  • apps/server-core/src/core/provisioning/synchronizer/role/module.ts
  • apps/server-core/src/core/provisioning/synchronizer/scope/module.ts
  • apps/server-core/src/core/provisioning/synchronizer/user/module.ts
  • apps/server-core/test/unit/core/provisioning/synchronizer/canonicalization.spec.ts
  • apps/server-core/test/unit/http/controllers/entities/realm-scoped.spec.ts
  • apps/server-core/test/unit/http/controllers/workflows/token/grant-password.spec.ts
  • apps/server-core/test/unit/http/controllers/workflows/token/grant-robot-credentials.spec.ts
  • docs/src/guide/development/api-oauth2.md
  • packages/client-web-kit/src/components/workflows/login/LoginForm.vue
✅ Files skipped from review due to trivial changes (3)
  • apps/server-core/test/unit/http/controllers/entities/realm-scoped.spec.ts
  • apps/server-core/test/unit/core/provisioning/synchronizer/canonicalization.spec.ts
  • .agents/architecture.md
🚧 Files skipped from review as they are similar to previous changes (5)
  • docs/src/guide/development/api-oauth2.md
  • apps/server-core/src/app/modules/database/repositories/realm/repository.ts
  • packages/client-web-kit/src/components/workflows/login/LoginForm.vue
  • apps/server-core/src/app/modules/database/repositories/identity-provider/repository.ts
  • apps/server-core/src/adapters/http/adapters/oauth2/grant-types/password.ts

…zation

synchronizeChildren snapshotted child names before synchronize()
canonicalized them in place, so cleanupStaleChildren compared raw
declared names against canonical stored names and would delete or
detach a mixed-case declared child right after syncing it. The names
are now derived after the sync loop, matching synchronizeMany.
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