Repository navigation
fix: provision client scopes into the client_scope junction - #3354
Conversation
The per-realm `web` client declared `global openid` in the dead `auth_clients.scope` column and created no `auth_client_scopes` rows, but `/authorize` resolves scopes exclusively through that junction (`OAuth2ScopeRepository.findByClientId`). The declared intent was therefore never enforced: a standard OIDC `scope=openid` authorization request failed with `insufficient_scope`, and only requests carrying `global` passed, via the verifier's bypass. Authup's own clients always send `global openid`, so the gap only surfaced for a non-kit RP. `WebClientProvisioner.ensureForRealm` now binds the built-in `global` and `openid` scopes as junction rows, driven by a shared `WEB_CLIENT_SCOPE_NAMES` so the descriptive column cannot drift from what is actually granted. The binding runs even when the client attributes are already current, since an instance provisioned before the rows existed carries an up-to-date client with no scopes at all. It is additive like the attribute merge, so a scope an admin bound by hand survives. There was no provisioning path to `auth_client_scopes` for any client, not just `web`, so `ClientProvisioningRelations` gains `globalScopes` / `realmScopes`. Realm-level scopes are now synchronized before the realm's clients, otherwise a `realmScopes` entry could not reference a scope declared in the same realm block. `ProvisioningEntityResolver` takes a `clientScoped` option because `auth_scopes` has no `clientId` column and the pinned predicate would not compile against it. An existing client named `web` is now taken over rather than skipped. The name is reserved (`CLIENT_RESERVED_NAMES`), so a non-built-in row predates the reservation and must not shadow the realm's login client.
|
Warning Review limit reached
Next review available in: 43 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the 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 configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (4)
📝 WalkthroughWalkthroughClient provisioning now supports global and realm scopes through ChangesClient scope provisioning
Estimated code review effort: 4 (Complex) | ~45 minutes Sequence Diagram(s)sequenceDiagram
participant ProvisioningInput
participant ClientProvisioningSynchronizer
participant ScopeRepository
participant ClientScopeRepository
participant Authorization
ProvisioningInput->>ClientProvisioningSynchronizer: provide client scope relations
ClientProvisioningSynchronizer->>ScopeRepository: resolve global and realm scopes
ClientProvisioningSynchronizer->>ClientScopeRepository: persist client-scope junction rows
Authorization->>ClientScopeRepository: read scopes for client
ClientScopeRepository-->>Authorization: return granted scopes
Possibly related PRs
Suggested reviewers: 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
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. Comment |
authup
@authup/client-web
@authup/server-core
@authup/access
@authup/client-web-kit
@authup/client-web-kit-theme
@authup/client-web-nuxt
@authup/client-web-theme
@authup/core-http-kit
@authup/core-kit
@authup/core-realtime-kit
@authup/errors
@authup/i18n
@authup/kit
@authup/server-adapter-kit
@authup/server-adapter-node
@authup/server-adapter-socket-io
@authup/server-adapter-web
@authup/server-kit
@authup/server-test-kit
@authup/specs
commit: |
Self-review follow-up. The takeover makes the client public (`authMethod: none`), so a secret it carried as a confidential client can never authenticate it again. It was left in the column, plaintext, as dead sensitive material. Clearing it needs the row re-read WITH the secret: `secret` is a `select: false` column, so the loaded entity carries no value for it and typeorm's changed-column diff never emits the null. The re-read is confined to the takeover branch, and the secret stays out of `buildWebClientAttributes` because an undefined-vs-null compare would mark every web client dirty on every boot. Proven against a real datasource in `provisioning.spec.ts`, which is what caught the first attempt: the repository fake merges by `Object.assign`, so the unit test passed while the column kept its value. Also consolidate the provisioning spec from four full provisioning passes to two. The suite shares one sqlite file across parallel spec files, so extra write pressure shows up as flakes elsewhere.
Self-review notesTwo things came out of auditing the branch, plus three observations worth recording. Fixed: the takeover left a plaintext secret at restThe takeover switches the client to The first attempt at this silently did nothing: Corrected: the "no
|
There was a problem hiding this comment.
🧹 Nitpick comments (2)
apps/server-core/src/core/entities/client/web-client.ts (1)
154-186: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win
ensureScopesreimplements the insert-only junction pattern instead of reusingProvisioningJunctionSynchronizer, and does N sequential scope lookups.This hand-rolled find-then-create loop duplicates logic already centralized in
ProvisioningJunctionSynchronizer(used for the identical purpose inclient/module.ts'sscopeJunction), and looks up each scope name with a separate query instead of one batchedfindManyBy.♻️ Batch the scope lookup
- for (const name of WEB_CLIENT_SCOPE_NAMES) { - const scope = await this.scopeRepository.findOneBy({ - name, - realmId: null, - }); - - if (!scope) { - ... - continue; - } - - const existing = await this.clientScopeRepository.findOneBy({ - clientId: client.id, - scopeId: scope.id, - }); - - if (existing) { - continue; - } - - await this.clientScopeRepository.save(this.clientScopeRepository.create({ ... })); - } + const scopes = await this.scopeRepository.findManyBy({ realmId: null, name: WEB_CLIENT_SCOPE_NAMES }); + const missing = WEB_CLIENT_SCOPE_NAMES.filter((n) => !scopes.some((s) => s.name === n)); + missing.forEach((n) => this.logger?.warn(`Skipping scope '${n}' ...`)); + // then delegate the insert-only part to ProvisioningJunctionSynchronizer if layering allows it🤖 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/entities/client/web-client.ts` around lines 154 - 186, Update ensureScopes to reuse ProvisioningJunctionSynchronizer, matching the scopeJunction setup in client/module.ts, instead of manually checking and inserting client-scope rows. Batch-load WEB_CLIENT_SCOPE_NAMES with a single findManyBy lookup, preserve the warning for unprovisioned scopes, and retain insert-only synchronization for the web client.apps/server-core/src/core/provisioning/synchronizer/client/module.ts (1)
116-182: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winExtract the repeated global+realm resolve/junction-sync pattern.
The new scopes block (Lines 160-182) is now the third copy of the same shape used for permissions (Lines 116-136) and roles (Lines 138-158): resolve global + realm entities, guard on non-empty, sync junction with two key names. Consider a small private helper to consolidate this and prevent future divergence.
♻️ Example helper consolidating the three blocks
+ private async syncScopedJunction<T extends ObjectLiteral>( + attributes: Client, + resolver: ProvisioningEntityResolver<T>, + junction: ProvisioningJunctionSynchronizer<any>, + globalNames: string[] | undefined, + realmNames: string[] | undefined, + targetKey: string, + targetRealmKey: string, + ): Promise<void> { + const targets = [ + ...await resolver.resolveGlobal(globalNames), + ...(attributes.realmId ? await resolver.resolveRealm(realmNames, attributes.realmId) : []), + ]; + if (targets.length > 0) { + await junction.synchronize(attributes, targets, targetKey, targetRealmKey); + } + }🤖 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/client/module.ts` around lines 116 - 182, Extract the duplicated global-and-realm resolution and conditional junction synchronization from the provisioning synchronizer into a small private helper, then update the permission, role, and scope flows to call it with their resolver results, junction instances, and entity key names. Preserve realmId handling and skip synchronization when the resolved collection is empty.
🤖 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.
Nitpick comments:
In `@apps/server-core/src/core/entities/client/web-client.ts`:
- Around line 154-186: Update ensureScopes to reuse
ProvisioningJunctionSynchronizer, matching the scopeJunction setup in
client/module.ts, instead of manually checking and inserting client-scope rows.
Batch-load WEB_CLIENT_SCOPE_NAMES with a single findManyBy lookup, preserve the
warning for unprovisioned scopes, and retain insert-only synchronization for the
web client.
In `@apps/server-core/src/core/provisioning/synchronizer/client/module.ts`:
- Around line 116-182: Extract the duplicated global-and-realm resolution and
conditional junction synchronization from the provisioning synchronizer into a
small private helper, then update the permission, role, and scope flows to call
it with their resolver results, junction instances, and entity key names.
Preserve realmId handling and skip synchronization when the resolved collection
is empty.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro Plus
Run ID: 0f3b3007-dd15-400b-8af0-226d6009c61e
📒 Files selected for processing (19)
.agents/architecture.mdapps/server-core/src/app/modules/http/modules/controller.tsapps/server-core/src/app/modules/provisioning/module.tsapps/server-core/src/core/entities/client/web-client.tsapps/server-core/src/core/provisioning/entities/client/relations-validator.tsapps/server-core/src/core/provisioning/entities/client/types.tsapps/server-core/src/core/provisioning/synchronizer/client/module.tsapps/server-core/src/core/provisioning/synchronizer/client/types.tsapps/server-core/src/core/provisioning/synchronizer/entity-resolver.tsapps/server-core/src/core/provisioning/synchronizer/index.tsapps/server-core/src/core/provisioning/synchronizer/realm/module.tsapps/server-core/src/core/provisioning/synchronizer/types.tsapps/server-core/test/data/sources/file.mtsapps/server-core/test/unit/core/entities/client/web-client.spec.tsapps/server-core/test/unit/core/entities/scope/fake-repository.tsapps/server-core/test/unit/core/entities/scope/service.spec.tsapps/server-core/test/unit/http/controllers/workflows/authorize.spec.tsapps/server-core/test/unit/modules/provisioning.spec.tsdocs/src/guide/deployment/provisioning.md
The `clientScoped` option refactored `resolveGlobal` / `resolveRealm` / `resolveClient` onto one shared path, and none of the three had direct coverage. `resolveClient` in particular is reachable only through a user's `clientPermissions` / `clientRoles`, which no fixture exercises. The spec asserts the emitted where clause per method, for named lookups and the `*` wildcard, plus name canonicalization and the empty short-circuit. Every client-scoped case also passes against the pre-refactor implementation, which is what makes the refactor provably behaviour-preserving for permissions and roles.
Closes #3347 (provisioning half; the dead-column removal is deliberately out of scope, see below).
The bug
buildWebClientAttributeswrote the per-realmwebclient's intended scopes intoauth_clients.scope, but/authorizeresolves scopes exclusively through theauth_client_scopesjunction (OAuth2ScopeRepository.findByClientId). No junction rows were ever created, so the declaredglobal openidwas never enforced.With an empty granted set the code-request verifier behaves like this:
scope=global openidglobalbypassscope=openidinsufficient_scopescopeparamscope=''Authup's own clients always send
global openid, so the gap only surfaced for a non-kit RP performing a standard OIDCscope=openidrequest against a realm's built-inwebclient.Changes
WebClientProvisioner.ensureForRealmbindsglobal+openidasauth_client_scopesrows, driven by a sharedWEB_CLIENT_SCOPE_NAMESso the descriptive column cannot drift from what is actually granted. The binding runs outside the attribute dirty-check: an instance provisioned before the rows existed carries an up-to-date client with no scopes at all, and must be backfilled on the next boot. Additive like the attribute merge, so a scope an admin bound by hand survives.ClientProvisioningRelationsgainsglobalScopes/realmScopes. There was no provisioning path toauth_client_scopesfor any client, not justweb(the contributing factor named in the issue).realmScopesentry could not reference a scope declared in the same realm block. Scopes are leaf entities with no relations of their own, so moving them first is safe.ProvisioningEntityResolvertakes aclientScopedoption.auth_scopeshas noclientIdcolumn, so the always-pinned client predicate would not compile against it.webis taken over rather than skipped. The name is reserved (CLIENT_RESERVED_NAMES), so a non-built-in row predates the reservation and must not shadow the realm's login client. Note the consequence: such a client is converted to public /builtInwith the trusted-origin redirect patterns, so an integration still using it with a secret stops working.Verification
authorize.spec.tsgains the issue's exact reproduction (scope=openidalone against the master realm'swebclient). Confirmed red with the scope binding disabled, green with it.provisioning.spec.tscovers both file-declared client scopes and thewebclient end to end.check:typesand eslint.Out of scope
The dead columns (
Client.scope,baseUrl,rootUrl) are untouched. Dropping them needs a generated migration on top of #3352, and the decision applies to all three at once.Client.scopeis now documented in code and in.agents/architecture.mdas descriptive only, with the junction named as the authorization source.Summary by CodeRabbit
New Features
Bug Fixes
Documentation