Repository navigation
feat: authorize access policy + persisted per-scope consent - #3246
Conversation
|
Note Reviews pausedUse the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughAdds OAuth2 application access policies and persisted per-scope consent. Policies are evaluated during authorization, federated callbacks, and token redemption. Consent records gain database persistence, APIs, permission-aware management, authorization-flow recording, covering probes, silent-login handling, and settings-page revocation UI. ChangesOAuth2 access policy and consent
Estimated code review effort: 5 (Critical) | ~120 minutes Sequence Diagram(s)sequenceDiagram
participant Browser
participant AuthorizePage
participant AuthorizeController
participant OAuth2Authorization
participant AccessPolicyEvaluator
participant ConsentService
participant TokenEndpoint
Browser->>AuthorizePage: Submit authorization request
AuthorizePage->>AuthorizeController: Confirm request
AuthorizeController->>OAuth2Authorization: Authorize verified request
OAuth2Authorization->>AccessPolicyEvaluator: Evaluate client policy
AccessPolicyEvaluator-->>OAuth2Authorization: Allow or deny
OAuth2Authorization->>ConsentService: Record granted scopes
OAuth2Authorization-->>AuthorizeController: Authorization code or access_denied
Browser->>TokenEndpoint: Redeem authorization code
TokenEndpoint->>AccessPolicyEvaluator: Re-evaluate client policy
AccessPolicyEvaluator-->>TokenEndpoint: Allow or invalid_grant
Possibly related PRs
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches🧪 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: |
|
@coderabbitai full review |
✅ Action performedFull review finished. |
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (1)
apps/server-core/src/core/entities/consent/service.ts (1)
177-183: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winEnsure date comparison is robust against driver-level date hydration.
If the underlying database driver (MySQL vs Postgres) hydrates
expires_atas aDateobject instead of a string,row.expires_at > now(wherenowis an ISO string) evaluates asDate > string, which results innumber > NaN(alwaysfalse). Converting to a timestamp guarantees correctness regardless of how the database driver returns the value.♻️ Proposed refactor for robust date comparison
- const now = new Date().toISOString(); + const now = Date.now(); return tokens.every((token) => rows.some( (row) => row.scope === token && - (row.expires_at === null || row.expires_at > now), + (row.expires_at === null || new Date(row.expires_at).getTime() > now), ));🤖 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/consent/service.ts` around lines 177 - 183, Update the expiry check in the token validation logic around findAllBySubjectClient so row.expires_at is normalized to a numeric timestamp before comparison, supporting both Date and string values. Compare it against the current time’s numeric timestamp while preserving the null-as-unexpired 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/client-web/pages/settings/index/applications.vue`:
- Around line 1-22: Import VCTimeago from `@vuecs/timeago` and register it in the
defineComponent components option alongside VCButton and VCIcon, ensuring the
existing connected-since template usage resolves correctly.
- Around line 64-87: Update the consent grouping and revoke-all flow around
groupByClient and revokeAll so each client group represents all of that client’s
consents, not only the current page’s props.data. Ensure revoke-all deletes
every consent for the selected client and connected-since uses the earliest
created_at across the complete dataset; obtain the full records through the
existing data-loading mechanism rather than relying solely on the active page.
In `@packages/client-web-kit/test/unit/components/entities/client/form.spec.ts`:
- Around line 177-179: Update the assertion in the client form update-request
test to verify that the request body explicitly contains the access_policy_id
property and that its value is null; do not use nullish coalescing, which also
accepts an omitted property. Keep the existing findUpdateRequest flow unchanged.
---
Nitpick comments:
In `@apps/server-core/src/core/entities/consent/service.ts`:
- Around line 177-183: Update the expiry check in the token validation logic
around findAllBySubjectClient so row.expires_at is normalized to a numeric
timestamp before comparison, supporting both Date and string values. Compare it
against the current time’s numeric timestamp while preserving the
null-as-unexpired 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: 580daab3-bfd6-4085-8d2d-570f0d621669
📒 Files selected for processing (114)
.agents/architecture.mdapps/client-web/pages/settings/index.vueapps/client-web/pages/settings/index/applications.vueapps/server-core/src/adapters/database/data-source/options/module.tsapps/server-core/src/adapters/database/domains/client/entity.tsapps/server-core/src/adapters/database/domains/consent/entity.tsapps/server-core/src/adapters/database/domains/consent/index.tsapps/server-core/src/adapters/database/domains/consent/subscriber.tsapps/server-core/src/adapters/database/domains/constants.tsapps/server-core/src/adapters/database/domains/index.tsapps/server-core/src/adapters/database/domains/policy/repository.tsapps/server-core/src/adapters/database/migrations/mysql/1783942684249-Default.tsapps/server-core/src/adapters/database/migrations/mysql/1783946622534-Default.tsapps/server-core/src/adapters/database/migrations/postgres/1783942684249-Default.tsapps/server-core/src/adapters/database/migrations/postgres/1783946622534-Default.tsapps/server-core/src/adapters/http/adapters/oauth2/authorization/module.tsapps/server-core/src/adapters/http/adapters/oauth2/authorization/types.tsapps/server-core/src/adapters/http/adapters/oauth2/grant-types/authorize.tsapps/server-core/src/adapters/http/adapters/oauth2/grant-types/types.tsapps/server-core/src/adapters/http/controllers/entities/consent/index.tsapps/server-core/src/adapters/http/controllers/entities/consent/module.tsapps/server-core/src/adapters/http/controllers/entities/identity-provider/module.tsapps/server-core/src/adapters/http/controllers/entities/identity-provider/types.tsapps/server-core/src/adapters/http/controllers/entities/index.tsapps/server-core/src/adapters/http/controllers/workflows/authorize/module.tsapps/server-core/src/adapters/http/controllers/workflows/authorize/types.tsapps/server-core/src/adapters/http/controllers/workflows/token/module.tsapps/server-core/src/adapters/http/controllers/workflows/token/types.tsapps/server-core/src/app/modules/database/repositories/client/repository.tsapps/server-core/src/app/modules/http/modules/controller.tsapps/server-core/src/app/modules/oauth2/constants.tsapps/server-core/src/app/modules/oauth2/module.tsapps/server-core/src/app/modules/oauth2/repositories/consent/index.tsapps/server-core/src/app/modules/oauth2/repositories/consent/repository.tsapps/server-core/src/app/modules/oauth2/repositories/index.tsapps/server-core/src/app/modules/provisioning/sources/default/module.tsapps/server-core/src/core/entities/consent/index.tsapps/server-core/src/core/entities/consent/service.tsapps/server-core/src/core/entities/consent/types.tsapps/server-core/src/core/entities/index.tsapps/server-core/src/core/identity/permission/index.tsapps/server-core/src/core/identity/policy/checker/service.tsapps/server-core/src/core/oauth2/access-policy/index.tsapps/server-core/src/core/oauth2/access-policy/module.tsapps/server-core/src/core/oauth2/access-policy/types.tsapps/server-core/src/core/oauth2/authorization/module.tsapps/server-core/src/core/oauth2/authorization/types.tsapps/server-core/src/core/oauth2/index.tsapps/server-core/test/unit/core/entities/consent/fake-repository.tsapps/server-core/test/unit/core/entities/consent/service.spec.tsapps/server-core/test/unit/core/identity/policy/checker.spec.tsapps/server-core/test/unit/core/oauth2/access-policy/evaluator.spec.tsapps/server-core/test/unit/core/oauth2/authorization/code-request/verifier/module.spec.tsapps/server-core/test/unit/core/oauth2/authorization/module.spec.tsapps/server-core/test/unit/core/oauth2/end-session/service.spec.tsapps/server-core/test/unit/http/controllers/entities/client-self-manage.spec.tsapps/server-core/test/unit/http/controllers/entities/client.spec.tsapps/server-core/test/unit/http/controllers/entities/consent.spec.tsapps/server-core/test/unit/http/controllers/workflows/authorize-access-policy.spec.tsapps/server-core/test/unit/http/controllers/workflows/token/grant-authorize-access-policy.spec.tsapps/server-core/test/unit/http/controllers/workflows/token/grant-idp-authorize.spec.tsapps/server-core/test/unit/http/controllers/workflows/ui-pages.spec.tspackages/client-web-kit/src/components/entities/client/AClientForm.vuepackages/client-web-kit/src/components/entities/consent/AConsents.tspackages/client-web-kit/src/components/entities/consent/index.tspackages/client-web-kit/src/components/entities/index.tspackages/client-web-kit/src/components/workflows/authorize/Authorize.vuepackages/client-web-kit/src/components/workflows/authorize/AuthorizeForm.vuepackages/client-web-kit/test/unit/components/entities/client/form.spec.tspackages/client-web-kit/test/unit/components/workflows/authorize-form.spec.tspackages/client-web-kit/test/unit/components/workflows/authorize.spec.tspackages/core-http-kit/src/client/module.tspackages/core-http-kit/src/client/type.tspackages/core-http-kit/src/domains/entities/client/types.tspackages/core-http-kit/src/domains/entities/consent/index.tspackages/core-http-kit/src/domains/entities/consent/module.tspackages/core-http-kit/src/domains/entities/consent/types.tspackages/core-http-kit/src/domains/entities/index.tspackages/core-kit/src/domains/client/entity.tspackages/core-kit/src/domains/client/validator.tspackages/core-kit/src/domains/consent/entity.tspackages/core-kit/src/domains/consent/index.tspackages/core-kit/src/domains/contstants.tspackages/core-kit/src/domains/event/constants.tspackages/core-kit/src/domains/index.tspackages/core-kit/src/domains/permission/constants.tspackages/core-kit/src/domains/types.tspackages/errors/src/constants.tspackages/i18n/src/catalogs/de/app.tspackages/i18n/src/catalogs/de/client.tspackages/i18n/src/catalogs/de/entity.tspackages/i18n/src/catalogs/de/error.tspackages/i18n/src/catalogs/de/field.tspackages/i18n/src/catalogs/en/app.tspackages/i18n/src/catalogs/en/client.tspackages/i18n/src/catalogs/en/entity.tspackages/i18n/src/catalogs/en/error.tspackages/i18n/src/catalogs/en/field.tspackages/i18n/src/catalogs/es/app.tspackages/i18n/src/catalogs/es/client.tspackages/i18n/src/catalogs/es/entity.tspackages/i18n/src/catalogs/es/error.tspackages/i18n/src/catalogs/es/field.tspackages/i18n/src/catalogs/fr/app.tspackages/i18n/src/catalogs/fr/client.tspackages/i18n/src/catalogs/fr/entity.tspackages/i18n/src/catalogs/fr/error.tspackages/i18n/src/catalogs/fr/field.tspackages/i18n/src/constants.tspackages/specs/src/oauth2/check.tspackages/specs/src/oauth2/constants.tspackages/specs/src/oauth2/error/access-denied.tspackages/specs/src/oauth2/error/index.tspackages/specs/test/unit/oauth2/scope.spec.ts
The code-request verifier already computes redirectUriVerified but the HTTP authorizer discarded it. Carry it on OAuth2AuthorizationOptions (alongside the already-threaded client) so authorize-time denials can decide between an error redirect (RFC 6749 §4.1.2.1) and an interactive error. Shared prerequisite of plans 052 and 055.
Optional Client.access_policy_id (FK auth_policies, ON DELETE SET NULL,
null = default-allow) gating who may obtain a token for a client,
evaluated fail-closed by the new OAuth2AccessPolicyEvaluator
(core/oauth2/access-policy) with IDENTITY policy data at three legs:
- OAuth2Authorization.authorizeInner — last gate before code issuance
(after realm/MFA/freshness); denial throws OAuth2AccessDeniedError
carrying redirectUri/state as non-enumerable fields iff the
redirect_uri was pattern-verified
- the federated-IdP callback — redirects back to the hosted authorize
page with error=access_denied (serve() maps the recognized query
param onto a neutral hydration error)
- /token code redemption backstop — denial surfaces as invalid_grant
AuthorizeController.confirm answers a verified denial as a 200 { url }
error redirect (RFC 6749 §4.1.2.1); unverified denials render the kit's
localized terminal denial card. access_policy_id joins the client
self-manage denylist, stays out of the anonymous ClientSummary DTO, is
admin-editable via APolicyPicker in AClientForm, and denials record
EventName.AUTHORIZE_FAILED plus the now-live authorize denied metric.
Migration pair 1783942684249 (both dialects, round-trip verified).
…service management auth_consents stores one row per (client_id, sub, sub_kind, scope token) (4-col unique, CASCADE FKs, dormant expires_at honored by the covering check). Recorded exclusively at POST /authorize approval — after the access-policy gate, never for built_in clients, never on the federated callback or /token — with union/keep semantics: re-approval only inserts missing tokens via subscriber-preserving per-row saves. A stored grant covering the requested tokens (strict lowercase-token superset via unwrapOAuth2Scope on both sides) lets the kit skip the consent prompt: Authorize.vue probes the self-scoped consent list alongside the MFA status fetch, AuthorizeForm auto-submits on covering consent unless prompt=consent, and the silent branch redirects consent_required only when no covering consent exists — making prompt=none meaningful for non-built_in clients. The covering lookup rides a 60s query cache (CachePrefix.CONSENT_COVERING) invalidated by the new ConsentEntitySubscriber (realtime + audit for free). Self-service API mirrors sessions: CONSENT_READ/CONSENT_DELETE, read+delete only, own rows ungated, per-row realm-match for admins, plan-039 force-selects. New settings Applications tab groups per-scope rows by client with chip-level revoke and per-app revoke-all. i18n x4, typed client.consent API, migration pair 1783946622534 (round-trip verified on mysql + postgres).
- Consent covering probe (Authorize.vue): scope the probe to the resolved user subject (sub + sub_kind) and re-check row.sub in the covering match. The server only force-scopes permissionless callers, so an actor holding CONSENT_READ (admin/realm_admin) previously received other subjects' rows and auto-consented off a stranger's grant. Drive the probe off the resolved user id (loggedIn flips before userInfo resolves) and drop any in-flight response whose subject is no longer current (logout / account switch mid-probe). - Consent list endpoint: expose only a client summary (id/name/display_name/ built_in) via a fixed join; drop 'client' from relations.allowed so a raw ?include=client cannot leak the full ClientEntity (redirect_uri patterns, grant_types, secret-storage flags, access_policy_id) to a self-service user without CLIENT_READ. - Scope-token normalization: drop empty tokens client-side (matching the server) so a comma/space-padded scope can still read as covered, and drop tokens exceeding CONSENT_SCOPE_MAX_LENGTH (shared entity/service constant) so an over-long token can't overflow the column and abort the write loop. - Docs: scope the access-policy denial event/metric claim to the /authorize leg (IdP + token legs are an uninstrumented audit-coverage gap), document the refresh-grant admission-control boundary, and record the consent Stage-1 orphan-row / summary-join behaviors. Regression tests: probe subject filter + foreign-subject non-coverage (kit), client-summary-only leak guard (http), over-long token drop (service).
- Explicitly import + register VCTimeago (convention: new code declares its VC* deps rather than relying on the app's global registration). - Revoke-all now fetches the client's complete consent set before deleting, instead of only the current page's rows — per-scope rows can span pages, so a page-local revoke-all could leave scopes granted. - Strengthen the cleared-picker test to assert an explicit access_policy_id: null in the body (the nullish-coalescing check also passed on omission).
ad133b6 to
dc0ff6a
Compare
|
@coderabbitai pause |
✅ Action performedReviews paused. |
|
@coderabbitai full review |
✅ Action performedFull review finished. Your plan includes PR reviews subject to rate limits. More reviews will be available in 36 minutes. |
…e driver-error guard - Fold the access_policy_id (052) and auth_consents (055) schema changes into the unreleased migration 1783856507391 (both dialects, per the fold-per-release convention); drop the two standalone Wave 4 migration pairs. Round-trip verified on mysql + postgres. - auth_consents gains a nullable user_id FK (ON DELETE CASCADE), populated when the subject is a user, so deleting a user cascade-drops its consent rows (non-user subjects rely on the client/realm cascade). Resolves the orphaned-consent-rows limitation from review. - Relocate the inline duplicate-key check to a reusable adapters/database/errors/driver.ts: getDatabaseDriverErrorCode unwraps the vendor code from a QueryFailedError (top-level or nested driverError.code), isUniqueConstraintDatabaseError matches it across mysql/postgres/sqlite. Tests: consent user_id population + user-deletion cascade (http), driver guard unit matrix.
9721921 to
ae0a781
Compare
Roadmap Wave 4 — the authorize-path product pair (Authentik-parity plans 052 + 055). Stacked on #3245 (the two policy-evaluation fixes it depends on); rebase onto
masteronce #3245 merges, or merge #3245 first.Four commits: prerequisite threading → application access policy (052) → persisted per-scope consent (055) → adversarial-review hardening.
052 — application access policy
Optional
Client.access_policy_id(FK →auth_policies,ON DELETE SET NULL,null= default-allow) gating who may obtain a token for a client, evaluated fail-closed at three legs:/authorizeissuance — the last gate before code issuance (after realm → MFA → freshness); denial throwsOAuth2AccessDeniedError.authorize(); denial redirects back to the hosted authorize page witherror=access_denied./tokencode-redemption backstop — catches pre-policy codes / missed mint sites; denial =invalid_grant.Fail-closed everywhere (unresolvable/dangling policy id, load/eval failure, and a policy-carrying client with no wired evaluator). A verified
redirect_urigets anerror=access_deniedredirect (RFC 6749 §4.1.2.1); an unverified one renders the kit's interactive denial card (redirectUri/stateride non-enumerable class fields so they never reach the wire body).access_policy_idjoins the client self-manage denylist, stays out of the anonymousClientSummary, and is admin-editable viaAPolicyPicker. Denials recordEventName.AUTHORIZE_FAILED+ the now-liveauthup_authorize_total{outcome="denied"}metric.Documented boundary: this is admission control — it is not evaluated on the
refresh_tokengrant, so evict an already-admitted identity via session revocation. The gate feeds IDENTITY policy data only (anATTRIBUTES-type access policy fails closed).055 — persisted consent (per-scope)
auth_consentsstores one row per(client_id, sub, sub_kind, scope token)(4-col unique index, CASCADE FKs, dormantexpires_athonored by the covering check) — a deliberate deviation from the plan's merged-string draft that enables partial (per-scope) revoke.POST /authorizeapproval (after the 052 gate — a denied identity writes nothing), skippingbuilt_inclients, with union/keep semantics (insert missing tokens only; subscriber-preserving per-row saves).CachePrefix.CONSENT_COVERING) and invalidated by the newConsentEntitySubscriber(realtime + audit for free). This makesprompt=nonemeaningful for non-built_inclients.CONSENT_READ/CONSENT_DELETEAPI mirrors sessions (read + delete only), plus a new settings Applications tab with per-scope revoke chips and per-app revoke-all.Adversarial review hardening (final commit)
A 57-agent review pass fixed before merge:
CONSENT_READ(admin/realm_admin) opening an authorize flow could auto-consent off another user's stored grant. Now filtered + re-checked bysub/sub_kind, driven off the resolved user (not the token-derivedloggedIn), and drops stale in-flight responses across logout/account-switch.GET /consents?include=clientleaked the fullClientEntity(redirect_uri patterns, grant_types, secret-storage flags,access_policy_id) to self-service users withoutCLIENT_READ— now a fixed client-summary join.CONSENT_SCOPE_MAX_LENGTH).Each fix has a regression test.
Schema
Two fresh migration pairs —
1783942684249(access_policy_id) and1783946622534(auth_consents) — both round-trip-verified (run → revert-all → re-run) on MySQL and PostgreSQL locally.Verification
apps/server-corefull suite 1543 green;client-web-kit129 green; specs/core-kit/i18n (locale-parity) green.check:typesclean; eslint clean.Docs:
.agents/architecture.mdgains "Application Access Policy" and "OAuth2 Consent" sections and the plan-043 pointer now resolves to the implemented feature.Summary by CodeRabbit
New Features
consent_requiredfor silent requests without consent.Bug Fixes