Repository navigation
feat: security hardening quick wins - #3227
Conversation
…dMany adapters A client fields projection (e.g. ?fields[user]=id,name) stripped realm_id from the SQL SELECT, so the per-row realm_scope gate evaluated against a missing resource realm: ownOrNull-scoped readers received every realm's rows (cross-realm disclosure - for clients including a plaintext-secret gate misfire), while own-scoped readers were wrongly denied their own rows. The shared applyRealmScopeSelect helper now re-adds realm_id plus the other gate-read columns after applyQuery in the user, robot, client, role-attribute and user-attribute adapters (session migrated onto the same helper). Role/scope/permission/policy list reads carry no per-row realm gate and are unaffected.
The prometheus middleware skip() excluded /authorize and /token, leaving the generic per-route histogram blind to the security-critical endpoints. Only the /metrics self-scrape and the root status endpoint stay excluded; both metered paths are fixed strings, so there is no label-cardinality risk.
The UserValidator accepted 3-character passwords and the password-reset flow enforced an inconsistent minimum of 5. The floor is now a validator option defaulting to 10 (NIST 800-63B posture: length only, no composition rules), driven by the new passwordMinLength config key (env PASSWORD_MIN_LENGTH) and threaded to every password-write site: user create/update, registration and password reset. Applies to new writes only - existing password hashes keep verifying.
Client.grant_types existed end-to-end but was never read by an enforcement path. A non-null (space- or comma-delimited) list is now an opt-in allowlist checked after client resolution in the authorization_code, refresh_token (incl. the bound-client-from-token path), client_credentials and password grants, and in the /authorize code-request verifier (authorization_code membership, denied before the consent UI renders). Violations fail with the new unauthorized_client error code (RFC 6749 §5.2). A null column keeps allow-all semantics, so upgrades are backward compatible; deployments that stored decorative grant_types values should review them before upgrading.
📝 WalkthroughWalkthroughThe changes add configurable password length enforcement, OAuth2 client grant allowlisting, realm-safe field projections, and Prometheus middleware coverage. Related configuration, service wiring, error contracts, repository helpers, tests, and documentation are updated. ChangesPassword policy configuration
OAuth2 grant allowlisting
Realm-scoped projections
Prometheus path coverage
Estimated code review effort: 4 (Complex) | ~60 minutes Sequence Diagram(s)sequenceDiagram
participant OAuthClient
participant TokenOrAuthorizeEndpoint
participant GrantVerifier
participant ErrorResponse
OAuthClient->>TokenOrAuthorizeEndpoint: submit grant request
TokenOrAuthorizeEndpoint->>GrantVerifier: resolve client and requested grant
GrantVerifier->>ErrorResponse: reject unauthorized grant
GrantVerifier-->>TokenOrAuthorizeEndpoint: continue allowed flow
Possibly related PRs
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (3 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Warning There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure. 🔧 ESLint
apps/server-core/src/adapters/http/adapters/oauth2/grant-types/authorize.tsOops! Something went wrong! :( ESLint: 10.6.0 ConfigError: Config (unnamed): Unexpected key "0" found. apps/server-core/src/adapters/http/adapters/oauth2/grant-types/client-credentials.tsOops! Something went wrong! :( ESLint: 10.6.0 ConfigError: Config (unnamed): Unexpected key "0" found. apps/server-core/src/adapters/http/adapters/oauth2/grant-types/password.tsOops! Something went wrong! :( ESLint: 10.6.0 ConfigError: Config (unnamed): Unexpected key "0" found.
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: |
|
@coderabbitai review |
✅ Action performedReview finished.
|
|
@coderabbitai full review |
✅ Action performedFull review finished. Your plan includes PR reviews subject to rate limits. More reviews will be available in 19 minutes. |
|
@coderabbitai full review |
✅ Action performedFull review finished. |
There was a problem hiding this comment.
🧹 Nitpick comments (3)
packages/specs/src/oauth2/error/client-unauthorized.ts (1)
30-32: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueConsider including the rejected grant type in
datafor programmatic access.The
grantTypefactory embeds the rejected grant type only in the message string. Callers or middleware that need to inspect which grant was rejected must parse the message. Addingdata: { grant_type: grantType }would allow structured access without message parsing, and the constructor already mergesoptions.datainto the final payload.♻️ Optional: add grant_type to error data
static grantType(grantType: string) { - return new OAuth2ClientUnauthorizedError({ message: `The client is not authorized to use the '${grantType}' grant type` }); + return new OAuth2ClientUnauthorizedError({ + message: `The client is not authorized to use the '${grantType}' grant type`, + data: { grant_type: grantType }, + }); }🤖 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 `@packages/specs/src/oauth2/error/client-unauthorized.ts` around lines 30 - 32, Update the OAuth2ClientUnauthorizedError.grantType factory to include the rejected grant type in the structured error data as grant_type, while preserving the existing message and constructor flow.apps/server-core/test/unit/core/oauth2/client/grant-type.spec.ts (1)
44-48: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueConsider strengthening the "inert" test to also verify known values still work alongside unknown ones.
The current test verifies that
grant_types: 'foo bar'rejectsPASSWORD, which shows unknown values don't grant blanket access. However, it doesn't verify that a known value coexisting with unknown values still passes — e.g.,'foo authorization_code'should still allowAUTHORIZATION_CODE. Adding that assertion would make the "inert" semantics fully bidirectional.♻️ Optional: add bidirectional inertness assertion
it('should treat unknown values in the list as inert', () => { const client = buildClient('foo bar'); expect(() => assertClientGrantAllowed(client, OAuth2TokenGrant.PASSWORD)) .toThrow(expect.objectContaining({ code: ErrorCode.OAUTH_CLIENT_UNAUTHORIZED })); + + // Unknown values don't break known values either + const clientWithKnown = buildClient('foo authorization_code'); + expect(() => assertClientGrantAllowed(clientWithKnown, OAuth2TokenGrant.AUTHORIZATION_CODE)).not.toThrow(); });🤖 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/core/oauth2/client/grant-type.spec.ts` around lines 44 - 48, Strengthen the test “should treat unknown values in the list as inert” by also building a client with unknown and known grants, such as “foo authorization_code”, and asserting assertClientGrantAllowed permits OAuth2TokenGrant.AUTHORIZATION_CODE. Preserve the existing rejection assertion proving unknown-only values do not authorize PASSWORD.packages/core-kit/src/domains/user/validator.ts (1)
127-131: 🔒 Security & Privacy | 🔵 Trivial | ⚡ Quick winConsider adding bounds validation for
passwordMinLengthas defense-in-depth.The
passwordMinLengthoption has no runtime bounds check in the validator. If a caller passes0, negative, or a value exceedingUSER_PASSWORD_MAX_LENGTH, the Zod schema would either allow empty passwords or reject all passwords. The config layer should validate this, but sinceUserValidatoris a public class that can be instantiated directly (as shown in tests), a simple clamp or guard would prevent silent security weakening.🛡️ Proposed defense-in-depth clamp
createValidator( z.string() - .min(this.options.passwordMinLength ?? USER_PASSWORD_MIN_LENGTH) + .min( + Math.max( + 1, + Math.min( + this.options.passwordMinLength ?? USER_PASSWORD_MIN_LENGTH, + USER_PASSWORD_MAX_LENGTH, + ), + ), + ) .max(USER_PASSWORD_MAX_LENGTH), ),🤖 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 `@packages/core-kit/src/domains/user/validator.ts` around lines 127 - 131, Validate the password minimum length used in UserValidator’s password schema before passing it to z.string().min(): clamp or guard the resolved passwordMinLength to remain within the valid range of 1 through USER_PASSWORD_MAX_LENGTH. Preserve USER_PASSWORD_MAX_LENGTH as the upper bound and ensure direct UserValidator construction cannot permit empty passwords or make every password invalid.
🤖 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/test/unit/core/oauth2/client/grant-type.spec.ts`:
- Around line 44-48: Strengthen the test “should treat unknown values in the
list as inert” by also building a client with unknown and known grants, such as
“foo authorization_code”, and asserting assertClientGrantAllowed permits
OAuth2TokenGrant.AUTHORIZATION_CODE. Preserve the existing rejection assertion
proving unknown-only values do not authorize PASSWORD.
In `@packages/core-kit/src/domains/user/validator.ts`:
- Around line 127-131: Validate the password minimum length used in
UserValidator’s password schema before passing it to z.string().min(): clamp or
guard the resolved passwordMinLength to remain within the valid range of 1
through USER_PASSWORD_MAX_LENGTH. Preserve USER_PASSWORD_MAX_LENGTH as the upper
bound and ensure direct UserValidator construction cannot permit empty passwords
or make every password invalid.
In `@packages/specs/src/oauth2/error/client-unauthorized.ts`:
- Around line 30-32: Update the OAuth2ClientUnauthorizedError.grantType factory
to include the rejected grant type in the structured error data as grant_type,
while preserving the existing message and constructor flow.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: c6d69f59-9c1e-450a-87a5-e1905ed8331b
📒 Files selected for processing (51)
.agents/architecture.mdapps/server-core/src/adapters/http/adapters/oauth2/grant-types/authorize.tsapps/server-core/src/adapters/http/adapters/oauth2/grant-types/client-credentials.tsapps/server-core/src/adapters/http/adapters/oauth2/grant-types/password.tsapps/server-core/src/adapters/http/adapters/oauth2/grant-types/refresh_token.tsapps/server-core/src/adapters/http/middleware/built-in/prometheus.tsapps/server-core/src/app/modules/authentication/repositories/session.tsapps/server-core/src/app/modules/config/constants.tsapps/server-core/src/app/modules/config/normalize.tsapps/server-core/src/app/modules/config/read/env.tsapps/server-core/src/app/modules/config/types.tsapps/server-core/src/app/modules/config/validator.tsapps/server-core/src/app/modules/database/repositories/client/repository.tsapps/server-core/src/app/modules/database/repositories/helpers.tsapps/server-core/src/app/modules/database/repositories/robot/repository.tsapps/server-core/src/app/modules/database/repositories/role-attribute/repository.tsapps/server-core/src/app/modules/database/repositories/user-attribute/repository.tsapps/server-core/src/app/modules/database/repositories/user/repository.tsapps/server-core/src/app/modules/http/modules/controller.tsapps/server-core/src/core/entities/client/web-client.tsapps/server-core/src/core/entities/user/service.tsapps/server-core/src/core/identity/password-recovery/service.tsapps/server-core/src/core/identity/password-recovery/types.tsapps/server-core/src/core/identity/registration/service.tsapps/server-core/src/core/identity/registration/types.tsapps/server-core/src/core/oauth2/authorization/code-request/verifier/module.tsapps/server-core/src/core/oauth2/client/grant-type.tsapps/server-core/src/core/oauth2/client/index.tsapps/server-core/test/unit/config/index.spec.tsapps/server-core/test/unit/core/entities/user/service.spec.tsapps/server-core/test/unit/core/identity/password-recovery/service.spec.tsapps/server-core/test/unit/core/identity/registration/service.spec.tsapps/server-core/test/unit/core/oauth2/authorization/code-request/verifier/module.spec.tsapps/server-core/test/unit/core/oauth2/client/grant-type.spec.tsapps/server-core/test/unit/http/controllers/entities/realm-isolation-field-projection.spec.tsapps/server-core/test/unit/http/controllers/workflows/token/grant-types-enforcement.spec.tsapps/server-core/test/unit/http/middleware/prometheus.spec.tsdocs/src/guide/deployment/configuration-server-core.mdpackages/core-kit/src/domains/user/constants.tspackages/core-kit/src/domains/user/index.tspackages/core-kit/src/domains/user/types.tspackages/core-kit/src/domains/user/validator.tspackages/core-kit/test/unit/domains/user.spec.tspackages/errors/src/constants.tspackages/i18n/src/catalogs/de/error.tspackages/i18n/src/catalogs/en/error.tspackages/i18n/src/catalogs/es/error.tspackages/i18n/src/catalogs/fr/error.tspackages/specs/src/oauth2/check.tspackages/specs/src/oauth2/error/client-unauthorized.tspackages/specs/src/oauth2/error/index.ts
Overview
First batch ("wave 0") of the roadmap quick wins — four independent, migration-free hardening items. One commit per item.
1. Cross-realm disclosure via
fieldsprojection (security fix)rapiq honors a client
fieldsprojection over the repository default, soGET /<entity>?fields[<entity>]=id,namestrippedrealm_idfrom the SQL SELECT and the per-rowrealm_scopegate evaluated against a missing resource realm:ownOrNull-scoped reader received every realm's rows (cross-realm disclosure; for clients,fields[client]=id,secretcould disclose foreign-realm plaintext client secrets),own-scoped reader was wrongly denied its own rows.Fix: shared
applyRealmScopeSelecthelper force-selects the gate-read columns afterapplyQueryin the user, robot, client, role-attribute and user-attribute adapters; the session adapter (fixed in #3187) is migrated onto the same helper. The regression spec pins all four exploitable directions and was verified to fail without the fix.Audit note: role/scope/permission/policy list reads carry no per-row realm gate at all (their
resourceRealmMatchusages are write paths), so there was nothing to bypass there — but their ungated list reads are a pre-existing gap worth a separate follow-up decision.2. Meter
/authorize+/tokenThe prometheus middleware
skip()excluded exactly the security-critical endpoints. Only the/metricsself-scrape and root status excludes remain; both metered paths are fixed strings (no label-cardinality risk).3. Configurable minimum password length
UserValidatoraccepted 3-character passwords and the reset flow enforced an inconsistentmin(5). NewpasswordMinLengthconfig (envPASSWORD_MIN_LENGTH, default 10) threads into user create/update, registration and password reset. Length-only, no composition rules (NIST 800-63B). New writes only — existing hashes keep verifying.4. Enforce
Client.grant_typesThe column existed end-to-end but was documented "metadata only". A non-null (space/comma-delimited) list is now an opt-in allowlist enforced after client resolution in the
authorization_code/refresh_token(incl. the bound-client-from-token path) /client_credentials/passwordgrants and in the/authorizecode-request verifier (deny before the consent UI). Violations fail with the newunauthorized_clienterror code (RFC 6749 §5.2, i18n entries in all four locales).null= allow-all, so upgrades are backward compatible.Upgrade notes (for the next release)
PASSWORD_MIN_LENGTHis lowered; file-provisioned users with shorter passwords now fail provisioning validation at startup.grant_typesvalues will see those clients restricted to the listed grants (e.g. a client listing onlyauthorization_codefails refresh withunauthorized_client). The provisioned per-realmwebclient already listsauthorization_code refresh_token.Verification
check:types(tsconfig.test.json) and eslint clean.Summary by CodeRabbit
New Features
Bug Fixes
Documentation