Repository navigation
feat(server-core): mount entity controllers under /realms/:realmId - #3049
Conversation
Dual-mount six realm-aware controllers (client, robot, user, permission, policy, identity-provider) via @routup/decorators array paths at both `/<entity>` and `/realms/:realmId/<entity>`. RealmResolverMiddleware (registered at `/realms/:realmId`) accepts the path segment as UUID or realm name, resolves via IRealmRepository, and stashes the canonical UUID on event.store. Controllers read it through `getRequestRealmID(event)` — falling back to `event.params.realmId` for non-nested routes — because the decorator-mounted route re-extracts the raw URL segment into params after the middleware runs. Writes call `applyRouteRealmIDToBody(event, data)` at the top of add/edit/put handlers so the route realm wins silently over body realm. system.realm-match still gates cross-realm writes; the prefix is a routing convenience, not an authorization shortcut. Bumps @routup/decorators to ^4.2.0 for the `DController(url: string | string[])` overload. Closes #3031
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (2)
✅ Files skipped from review due to trivial changes (1)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughThis PR adds realm-scoped HTTP routing to entity controllers. It introduces request helpers to manage realm ID context, a new ChangesRealm-Scoped HTTP Endpoints
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ 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 |
There was a problem hiding this comment.
Pull request overview
This PR adds nested realm-scoped routing for key entity controllers in apps/server-core by dual-mounting them at both flat paths (e.g. /users) and nested paths (e.g. /realms/:realmId/users). It introduces a realm-resolver middleware + request helpers so controllers can consistently treat the route realm as authoritative (especially for writes) while keeping existing permission semantics intact.
Changes:
- Dual-mount six realm-aware controllers under both
/<entity>and/realms/:realmId/<entity>and update controller read/write paths to usegetRequestRealmID()/applyRouteRealmIDToBody(). - Add
RealmResolverMiddlewaremounted at/realms/:realmIdto resolve realm name/UUID to a canonical UUID stored onevent.store. - Add unit tests for nested-route availability and “route realm overrides body realm_id” on create, plus bump
@routup/decoratorsto support array controller paths.
Reviewed changes
Copilot reviewed 17 out of 18 changed files in this pull request and generated 8 comments.
Show a summary per file
| File | Description |
|---|---|
| package-lock.json | Updates routup-related dependency versions and lockfile entries for the new decorators capability. |
| apps/server-core/package.json | Bumps @routup/decorators to ^4.2.0 (array path overload). |
| apps/server-core/src/app/modules/http/modules/middleware.ts | Mounts the new realm resolver middleware at /realms/:realmId. |
| apps/server-core/src/adapters/http/request/helpers/realm-id.ts | Adds request helpers to read/store resolved realm UUID and to force route realm onto write payloads. |
| apps/server-core/src/adapters/http/request/helpers/index.ts | Exports the new realm-id helpers. |
| apps/server-core/src/adapters/http/middleware/built-in/realm-resolver/types.ts | Defines the realm-resolver middleware context type. |
| apps/server-core/src/adapters/http/middleware/built-in/realm-resolver/module.ts | Implements realm key resolution and stashing of the canonical realm UUID. |
| apps/server-core/src/adapters/http/middleware/built-in/realm-resolver/factory.ts | Adds factory to expose the resolver as a Routup handler. |
| apps/server-core/src/adapters/http/middleware/built-in/realm-resolver/index.ts | Barrel export for realm-resolver middleware module/factory/types. |
| apps/server-core/src/adapters/http/middleware/built-in/index.ts | Re-exports realm-resolver middleware from built-in middleware index. |
| apps/server-core/src/adapters/http/controllers/entities/user/module.ts | Dual-mounts under /realms/:realmId/users and applies route realm to reads/writes. |
| apps/server-core/src/adapters/http/controllers/entities/robot/module.ts | Dual-mounts under /realms/:realmId/robots and applies route realm to reads/writes. |
| apps/server-core/src/adapters/http/controllers/entities/policy/module.ts | Dual-mounts under /realms/:realmId/policies and applies route realm to reads/writes. |
| apps/server-core/src/adapters/http/controllers/entities/permission/module.ts | Dual-mounts under /realms/:realmId/permissions and applies route realm to reads/writes. |
| apps/server-core/src/adapters/http/controllers/entities/identity-provider/module.ts | Dual-mounts under /realms/:realmId/identity-providers and applies route realm precedence in lookups/writes. |
| apps/server-core/src/adapters/http/controllers/entities/client/module.ts | Dual-mounts under /realms/:realmId/clients and applies route realm to reads/writes. |
| apps/server-core/test/unit/http/controllers/entities/realm-scoped.spec.ts | Adds unit tests for nested route reachability and route-realm precedence on create. |
| .agents/architecture.md | Documents the nested route mounting model and the “route realm wins” convention. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| if (isUUID(value)) { | ||
| setRequestRealmID(event, value); | ||
| return; | ||
| } | ||
|
|
||
| const realm = await this.realmRepository.resolve(value); |
| @DTags('oauth2') | ||
| @DController('/clients') | ||
| @DController(['/clients', '/realms/:realmId/clients']) | ||
| export class ClientController { |
| @DTags('user') | ||
| @DController('/users') | ||
| @DController(['/users', '/realms/:realmId/users']) | ||
| export class UserController { |
| @DTags('robot') | ||
| @DController('/robots') | ||
| @DController(['/robots', '/realms/:realmId/robots']) | ||
| export class RobotController { |
| @DTags('permission') | ||
| @DController('/permissions') | ||
| @DController(['/permissions', '/realms/:realmId/permissions']) | ||
| export class PermissionController { |
| @DTags('policy') | ||
| @DController('/policies') | ||
| @DController(['/policies', '/realms/:realmId/policies']) | ||
| export class PolicyController { |
| @DTags('identity') | ||
| @DController('/identity-providers') | ||
| @DController(['/identity-providers', '/realms/:realmId/identity-providers']) | ||
| export class IdentityProviderController { |
| describe('user', () => { | ||
| it('should list users via /realms/<name>/users', async () => { | ||
| const response = await httpRequest(suite, 'GET', '/realms/master/users', { headers: { Authorization: basicAuth } }); | ||
|
|
||
| expect(response.status).toEqual(200); | ||
| const body = await response.json(); | ||
| expect(body.data).toBeDefined(); | ||
| expect(Array.isArray(body.data)).toBe(true); | ||
| }); | ||
|
|
||
| it('should list users via /realms/<uuid>/users', async () => { | ||
| const response = await httpRequest(suite, 'GET', `/realms/${masterRealm.id}/users`, { headers: { Authorization: basicAuth } }); | ||
|
|
||
| expect(response.status).toEqual(200); | ||
| }); | ||
|
|
||
| it('should 404 on unknown realm key in path', async () => { | ||
| const response = await httpRequest(suite, 'GET', '/realms/this-realm-does-not-exist/users', { headers: { Authorization: basicAuth } }); | ||
|
|
||
| expect(response.status).toEqual(404); | ||
| }); | ||
|
|
||
| it('should create user under route realm, overriding body realm_id', async () => { | ||
| // body points at scopedRealm (a realm the admin can't write to); | ||
| // route says master. If the override works, the user lands in | ||
| // master and the permission check passes (admin is in master). | ||
| // If body won instead, the request would 403. | ||
| const payload = { ...createFakeUser(), realm_id: scopedRealm.id }; | ||
|
|
||
| const response = await httpRequest(suite, 'POST', `/realms/${masterRealm.id}/users`, { | ||
| headers: { Authorization: basicAuth, 'Content-Type': 'application/json' }, | ||
| body: JSON.stringify(payload), | ||
| }); | ||
|
|
||
| expect(response.status).toEqual(201); | ||
| const body = await response.json(); | ||
| expect(body.realm_id).toEqual(masterRealm.id); | ||
| expect(body.realm_id).not.toEqual(scopedRealm.id); | ||
| }); |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (2)
apps/server-core/src/app/modules/http/modules/middleware.ts (1)
119-124: ⚖️ Poor tradeoffConsider mounting position relative to RealmController.
The documentation notes (architecture.md lines 532-533) that
RealmControlleris mounted at/realmswith routes like/realms/:id, and this realm-resolver middleware also fires on those URLs (prefix match), causing one extrarealmRepository.resolve()call per realm-CRUD request.While the docs acknowledge this as acceptable, consider whether mounting the resolver more specifically (e.g., only on the entity paths that need it:
/realms/:realmId/users,/realms/:realmId/clients, etc.) would be more efficient. This would avoid the unnecessary resolution forRealmControllerendpoints.🤖 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/http/modules/middleware.ts` around lines 119 - 124, The mountRealmResolver middleware is currently mounted broadly with router.use('/realms/:realmId', middleware) in mountRealmResolver and thus runs for RealmController endpoints too; change its mounting to only the specific subpaths that actually need a resolved realm (for example mount under '/realms/:realmId/users', '/realms/:realmId/clients', '/realms/:realmId/roles', etc.) by replacing the single router.use('/realms/:realmId', middleware) with explicit router.use calls for those entity routes (or call middleware when registering those routers), keeping createRealmResolverMiddleware and RealmRepositoryAdapter usage the same so you avoid extra realmRepository.resolve() calls on plain /realms CRUD endpoints.apps/server-core/test/unit/http/controllers/entities/realm-scoped.spec.ts (1)
62-78: ⚡ Quick winConsider adding a conflict detection test.
The current test validates that route realm overrides body realm, but consider adding a test case that explicitly validates the conflict scenario: when route and body specify different realms, does the system detect and handle this appropriately? The PR objectives mention "If route and body realm_id conflict, return a BadRequest."
However, based on the implementation in
applyRouteRealmIDToBody, it appears the route realm silently wins rather than detecting conflicts. This may be intentional per the PR description ("route realm silently wins"), but the test suite should clarify this behavior.🤖 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/entities/realm-scoped.spec.ts` around lines 62 - 78, Add a unit test in realm-scoped.spec.ts that explicitly asserts the conflict behavior when route and body realm_id differ: craft a POST to /realms/{routeRealm.id}/users with a payload containing a different realm_id and assert the API returns a 400 Bad Request (per the PR objective that conflicts should fail), referencing the existing test pattern (use httpRequest, basicAuth, createFakeUser) and the function applyRouteRealmIDToBody to locate the logic under test; if the implementation intentionally lets the route silently win, instead add a clarifying test that asserts the route-wins behavior and update the test name/comment to document which behavior is intended.
🤖 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/package.json`:
- Line 82: The PR claims "@routup/decorators": "^4.2.0" was bumped to enable
DController(url: string | string[]) array paths support, but the package docs
show only single-string controllers; verify the actual changelog/commit history
or source of `@routup/decorators` v4.2.0 to confirm if DController supports
string[] paths, and then either (a) update the PR description to state the true
reason for the upgrade (cite the exact feature/bugfix from the changelog) or (b)
if array-path support is not present, remove that claim and/or revert the
version bump and instead adopt the correct version that adds the feature;
reference the dependency line "@routup/decorators": "^4.2.0" and the
DController(url: string | string[]) mention when making the correction.
---
Nitpick comments:
In `@apps/server-core/src/app/modules/http/modules/middleware.ts`:
- Around line 119-124: The mountRealmResolver middleware is currently mounted
broadly with router.use('/realms/:realmId', middleware) in mountRealmResolver
and thus runs for RealmController endpoints too; change its mounting to only the
specific subpaths that actually need a resolved realm (for example mount under
'/realms/:realmId/users', '/realms/:realmId/clients', '/realms/:realmId/roles',
etc.) by replacing the single router.use('/realms/:realmId', middleware) with
explicit router.use calls for those entity routes (or call middleware when
registering those routers), keeping createRealmResolverMiddleware and
RealmRepositoryAdapter usage the same so you avoid extra
realmRepository.resolve() calls on plain /realms CRUD endpoints.
In `@apps/server-core/test/unit/http/controllers/entities/realm-scoped.spec.ts`:
- Around line 62-78: Add a unit test in realm-scoped.spec.ts that explicitly
asserts the conflict behavior when route and body realm_id differ: craft a POST
to /realms/{routeRealm.id}/users with a payload containing a different realm_id
and assert the API returns a 400 Bad Request (per the PR objective that
conflicts should fail), referencing the existing test pattern (use httpRequest,
basicAuth, createFakeUser) and the function applyRouteRealmIDToBody to locate
the logic under test; if the implementation intentionally lets the route
silently win, instead add a clarifying test that asserts the route-wins behavior
and update the test name/comment to document which behavior is intended.
🪄 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: 3f9afac9-d6fc-4dac-aa76-120f20829174
⛔ Files ignored due to path filters (1)
package-lock.jsonis excluded by!**/package-lock.json
📒 Files selected for processing (17)
.agents/architecture.mdapps/server-core/package.jsonapps/server-core/src/adapters/http/controllers/entities/client/module.tsapps/server-core/src/adapters/http/controllers/entities/identity-provider/module.tsapps/server-core/src/adapters/http/controllers/entities/permission/module.tsapps/server-core/src/adapters/http/controllers/entities/policy/module.tsapps/server-core/src/adapters/http/controllers/entities/robot/module.tsapps/server-core/src/adapters/http/controllers/entities/user/module.tsapps/server-core/src/adapters/http/middleware/built-in/index.tsapps/server-core/src/adapters/http/middleware/built-in/realm-resolver/factory.tsapps/server-core/src/adapters/http/middleware/built-in/realm-resolver/index.tsapps/server-core/src/adapters/http/middleware/built-in/realm-resolver/module.tsapps/server-core/src/adapters/http/middleware/built-in/realm-resolver/types.tsapps/server-core/src/adapters/http/request/helpers/index.tsapps/server-core/src/adapters/http/request/helpers/realm-id.tsapps/server-core/src/app/modules/http/modules/middleware.tsapps/server-core/test/unit/http/controllers/entities/realm-scoped.spec.ts
| "@routup/basic": "^2.1.0", | ||
| "@routup/cors": "^1.0.1", | ||
| "@routup/decorators": "^4.1.0", | ||
| "@routup/decorators": "^4.2.0", |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Description: Verify `@routup/decorators` version 4.2.0 exists and check for security advisories
# Check if version 4.2.0 exists on npm
echo "Checking `@routup/decorators` version 4.2.0 on npm..."
curl -s https://registry.npmjs.org/@routup/decorators/4.2.0 | jq -r '.version // "Version not found"'
# Get all available versions
echo -e "\nAvailable versions:"
curl -s https://registry.npmjs.org/@routup/decorators | jq -r '.versions | keys[]' | tail -10
# Check for security advisories
echo -e "\nChecking for security advisories..."
gh api graphql -f query='
{
securityVulnerabilities(first: 5, ecosystem: NPM, package: "@routup/decorators") {
nodes {
advisory {
summary
severity
publishedAt
}
vulnerableVersionRange
firstPatchedVersion {
identifier
}
}
}
}'Repository: authup/authup
Length of output: 1946
🌐 Web query:
@routup/decorators 4.2.0 DController array paths support
💡 Result:
Summary: The published @routup/decorators docs (including the examples shown for the decorators package) do not indicate that DController accepts an array of path strings (e.g., @DController(['/a','/b'])). The example shown uses a single string path in @DController('/users'), not an array. There is therefore no evidence from the authoritative package documentation that “array paths” are supported in version 4.2.0 (or at all), and the best-supported usage is a single string path per DController. What the sources show 1) The @routup/decorators package example defines a controller with a single string path: @DController('/users'). [1] 2) The same documentation snippet shows a method decorator with a second argument for DDelete('/:id',[]) (i.e., an array is used as an argument for that specific decorator invocation), but this is not presented as “array paths” for DController. [1] 3) The example also shows how the decorators plugin is mounted, via decorators({controllers:[UserController],...}). This again implies controllers are registered as classes and their base route comes from the single path argument given to @DController. [1] Answer to the query - Does @routup/decorators 4.2.0 DController support array paths? Based on the available authoritative documentation, there is no stated/ documented support for passing an array of paths to @DController; only a single string path is shown. [1] Suggested workaround (if you need multiple base paths) - Create multiple controllers (or multiple decorated classes) each with its own @DController('') base path, and register them in the decorators plugin’s controllers list. This is consistent with the way controllers are passed to decorators({ controllers: [...] }). [1]
Citations:
Clarify the purpose of the @routup/decorators version bump.
The PR states this version is required for DController(url: string | string[]) array paths support, but official package documentation shows only single string paths are supported (@DController('/users')). Confirm whether version 4.2.0 actually provides this feature or update the PR description to reflect the actual reason for the upgrade.
🤖 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/package.json` at line 82, The PR claims
"@routup/decorators": "^4.2.0" was bumped to enable DController(url: string |
string[]) array paths support, but the package docs show only single-string
controllers; verify the actual changelog/commit history or source of
`@routup/decorators` v4.2.0 to confirm if DController supports string[] paths, and
then either (a) update the PR description to state the true reason for the
upgrade (cite the exact feature/bugfix from the changelog) or (b) if array-path
support is not present, remove that claim and/or revert the version bump and
instead adopt the correct version that adds the feature; reference the
dependency line "@routup/decorators": "^4.2.0" and the DController(url: string |
string[]) mention when making the correction.
|
@coderabbitai review |
✅ Actions performedReview triggered.
|
Previously the middleware was mounted at `/realms/:realmId`, which also intercepted bare RealmController routes including `PUT /realms/:id` (the upsert path). On a create-via-PUT, the realm doesn't exist yet, so the middleware threw EntityNotFoundError before the controller could create it — breaking the existing `realm.spec.ts > should create and update resource with put` test. Mount at `/realms/:realmId/:nested` so the middleware only fires when there is at least one path segment after `:realmId`. Nested-entity URLs (`/realms/master/users/...`) still match; RealmController's own routes (CRUD, openid-config, jwks) are no longer intercepted.
Summary
@routup/decoratorsarray paths at both/<entity>and/realms/:realmId/<entity>. Bumps@routup/decoratorsto^4.2.0for theDController(url: string | string[])overload.RealmResolverMiddlewaremounted at/realms/:realmIdresolves the path segment (UUID or realm name) to a canonical UUID viaIRealmRepositoryand stashes it onevent.store. Two helpers inadapters/http/request/helpers/realm-id.ts(getRequestRealmID,applyRouteRealmIDToBody) let controllers read the realm and overridedata.realm_idon write — route realm wins silently over body realm.system.realm-matchstill gates cross-realm writes; the route prefix is a routing convenience, not an authorization shortcut.Resolves the long-standing precedence bug originally flagged on
IdentityProviderController.write()in PR #3030 review: lookups and creates no longer ignore the route's:realmIdin favour of body or actor-identity realm.Closes #3031
Test plan
npm run build -w apps/server-corecleannpm run test -w apps/server-core -- test/unit/http/controllers/entities/realm-scoped.spec.ts— 9/9 pass (user list by name/UUID/404, route-wins-over-body create, smoke GET for the other 5 nested entities)npm run test -w apps/server-core— full HTTP suite green (existing tests should be unaffected — non-nested routes get a no-op middleware path)GET /realms/master/usersandGET /realms/<unknown>/usersagainst a dev serverSummary by CodeRabbit
New Features
Documentation
Chores
Tests