Skip to content

add support for signout all users in project level - #14647

Merged
Meldiron merged 6 commits into
appwrite:mainfrom
imtia33:feat/force-signout-all-users
Oct 26, 2026
Merged

Meldiron merged 6 commits into
appwrite:mainfrom
imtia33:feat/force-signout-all-users

Conversation

@imtia33

@imtia33 imtia33 commented Oct 19, 2026

Copy link
Copy Markdown
Contributor

What does this PR do?

Adds a new API endpoint DELETE /v1/project/sessions that allows a project developer (via API key with sessions.write + users.write scope, or a privileged console user) to immediately invalidate every active session across the entire project — without touching a single session document at request time.

The problem

Previously there was no way to force-sign-out all users in a project in one shot. The naive approach — iterating over every user's sessions and deleting them — is O(N) at request time (N = number of active sessions), which for a large project means seconds of latency, potential timeouts, and a heavy write storm on the database.

The approach: epoch bump (O(1) at request time)

Instead of deleting documents, the endpoint writes a single timestamp (sessionsValidAfter) into the project's existing auths JSON attribute:

projects/{projectId}.auths.sessionsValidAfter = "2026-10-19T05:15:00.000Z"

Every auth path that verifies a session then compares the session's immutable $createdAt against this epoch. If the session was created at or before the epoch, it is treated as invalid — the user is effectively signed out — without any document being modified or deleted.

Cleanup of the now-dead session documents happens asynchronously in the background via the existing Deletes worker, reusing the DELETE_TYPE_SESSIONS queue type, which already runs during maintenance. The worker now accepts an optional validAfter cutoff: when supplied (force sign-out), it deletes sessions created before that timestamp; when absent (routine maintenance), it uses the project's session duration as before.


Approach & Time Complexity

Phase Operation Complexity
Request Write one field to projects doc (auths.sessionsValidAfter) O(1)
Request Enqueue one DeleteMessage to the Deletes queue O(1)
Each auth check Read sessionsValidAfter from already-loaded $project doc; compare to $createdAt O(1) per request
Async cleanup Worker deletes all sessions with $createdAt <= cutoff in batches O(N) — off the hot path

The epoch is checked inside User::sessionVerify() and User::sessionActive(), which are called in every auth path. The $project document is already loaded in the request context — no extra DB queries are added to the hot path.


Workflow

sequenceDiagram
    participant Dev as Developer (API Key)
    participant API as DELETE /v1/project/sessions
    participant DB as Platform DB (projects collection)
    participant Queue as Deletes Queue
    participant Worker as Deletes Worker

    Dev->>API: DELETE /v1/project/sessions
    API->>DB: updateDocument('projects', id,\n{ auths.sessionsValidAfter: now() })
    API->>Queue: enqueue(DELETE_TYPE_SESSIONS, datetime=now())
    API-->>Dev: 204 No Content

    Note over DB,Worker: Hot path — every subsequent request
    Dev->>API: Any authenticated request
    API->>DB: load $project (already cached)
    API->>API: sessionVerify(secret, proof, validAfter)
    API->>API: session.$createdAt <= validAfter? → reject
    API-->>Dev: 401 Unauthorized

    Note over Queue,Worker: Async — off hot path
    Queue->>Worker: consume DELETE_TYPE_SESSIONS message
    Worker->>DB: deleteByGroup('sessions',\n  createdAt <= validAfter, batch)
    Worker-->>Queue: done
Loading
flowchart TD
    A[DELETE /v1/project/sessions received] --> B{Auth check:\nsessions.write + users.write\nor privileged user?}
    B -- No --> C[403 Forbidden]
    B -- Yes --> D[Write auths.sessionsValidAfter = now\nto projects doc — O1]
    D --> E[Enqueue DELETE_TYPE_SESSIONS\nwith datetime = now — O1]
    E --> F[204 No Content]

    F --> G{Next user request\nto any endpoint}
    G --> H[Load user + sessions\nfrom DB]
    H --> I{session.createdAt\n<= sessionsValidAfter?}
    I -- Yes --> J[Reject session\n→ 401]
    I -- No --> K[Session is valid\n→ continue]

    E --> L[Deletes Worker picks up message]
    L --> M[deleteByGroup sessions\nwhere createdAt <= cutoff\nin batches — ON async]
    M --> N[Dead session docs removed\nfrom DB]
Loading

What was changed

New endpoint

  • src/Appwrite/Platform/Modules/Project/Http/Project/Sessions/Delete.php — DELETE /v1/project/sessions, scoped to sessions.write + users.write. Writes the epoch and enqueues cleanup.
  • src/Appwrite/Platform/Modules/Project/Services/Http.php — Registers the new action.

Epoch check — session verification

  • src/Appwrite/Utopia/Database/Documents/User.php — sessionVerify() and sessionActive() accept an optional ?string $validAfter. If set and session.$createdAt <= $validAfter, the session is rejected before any secret comparison.

Epoch threaded into all auth paths

File Change
app/init/resources/request.php HTTP cookie + JWT paths (4 call sites)
app/init/realtime/connection.php Realtime WebSocket auth (4 call sites)
app/init/mqtt/connection.php MQTT auth (2 call sites)
app/realtime.php PubSub revoked-connection check
app/controllers/api/account.php OAuth2 session upgrade + JWT mint
src/.../Account/Sessions/IdToken/Create.php ID token session upgrade
src/.../Realtime/Message/Handlers/Authentication.php Realtime re-authentication handler

Async cleanup

  • src/Appwrite/Platform/Workers/Deletes.php — deleteExpiredSessions() accepts optional ?string $validAfter. The DELETE_TYPE_SESSIONS switch case now passes $datetime (the epoch from the queue message). Routine maintenance (DELETE_TYPE_MAINTENANCE) still passes null, preserving the original duration-based behaviour.

Tests

  • tests/unit/Utopia/Database/Documents/UserTest.php — 8 new data-driven assertions covering the epoch matrix for both sessionVerify and sessionActive (before/at/after epoch, and null passthrough).
  • tests/e2e/Services/Project/SessionsDeleteIntegrationTest.php — Integration test: creates a session, calls the endpoint, confirms the session is rejected on next use.
  • tests/e2e/Security/baseline.json — Registers DELETE /v1/project/sessions so the security baseline test doesn't flag it as an undocumented route.

Test Plan

  1. Unit tests (already green):

    docker compose exec appwrite vendor/bin/phpunit tests/unit/Utopia/Database/Documents/UserTest.php
    # 20 tests, 102 assertions — OK
    
  2. Integration test:

    docker compose exec appwrite test tests/e2e/Services/Project/SessionsDeleteIntegrationTest
    

    OK (3 tests, 43 assertions)
    Time: 00:06.878, Memory: 30.00 MB

  3. Manual smoke test:

    • Create a project, create a user, start a session.
    • Call DELETE /v1/project/sessions with a project API key (sessions.write + users.write).
    • Confirm GET /v1/account returns 401 on the old session token.
    • Create a new session — confirm it works normally.

Related PRs and Issues

N/A


Checklist

  • Have you read the Contributing Guidelines on issues?
  • If the PR includes a change to an API's metadata (desc, label, params, etc.), does it also include updated API specs and example docs? — N/A for this PR: no SDK regen or docs markdown in scope; to be handled in a follow-up.

@ghost

ghost commented Oct 19, 2026 •

Copy link
Copy Markdown

🔵 Tier A · Mergeable after minor fixes

The unresolved realtime finding still applies: project session invalidation can close admin-mode connections.

This pull request adds project-wide session invalidation by recording a cutoff in project auth settings, checking that cutoff across HTTP, realtime, MQTT, JWT, and account-authentication paths, and queuing asynchronous session cleanup. It also adds the project API endpoint and Console control, documentation, and coverage for the invalidation behavior; the latest update refreshes the Console package snapshot and converts the session test data providers to generators.

Latest changes: The newest commits update the Console package snapshot (including its MQTT dependency) and change the two session-invalidation data providers to yield cases from \Iterator generators.

Verdict New comments Fixed Still open
💬 Commented 0 0 1

Note

Not approving while a bug finding is open: Avoid closing admin sockets during project session cleanup

Fix with agent prompt
### Issue 1
app/realtime.php:775-777
**Avoid closing admin sockets during project session cleanup**

An admin-mode connection's session belongs to a console user, but this sweep loads that user from the target project's database and marks the connection revoked when the document is absent. A project signout therefore closes admin sockets attached to that project even though their console sessions were not invalidated; validate these connections against the console user store or exclude them.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.
📂 Walkthrough · 27
File Change
app/config/sdks/parameters.lock.json Locks the API parameter contract for project-wide session deletion.
app/controllers/api/account.php Applies session cutoff checks to OAuth session upgrades and JWT creation, including console-session handling for admin-mode JWTs.
app/controllers/general.php Validates preview JWT sessions against session cutoffs, required factors, and project team membership.
app/init/mqtt/connection.php Adds session cutoff and factor checks to MQTT authentication and carries session recheck metadata.
app/init/realtime/connection.php Applies cutoff and factor checks to realtime cookie and JWT authentication.
app/init/resources/request.php Applies project or console session cutoffs to HTTP cookie and JWT authentication.
app/realtime.php Revalidates realtime sessions and factors after permission changes and updates the project cleanup comment.
apps/console/package.json Updates the Console package dependency to the newer PR snapshot.
apps/console/bun.lock Locks the newer Console snapshot and its MQTT dependency update.
apps/console/src/components/pages/projects/$projectId/auth/Settings.tsx Adds the project force-signout control to authentication settings.
apps/console/src/components/pages/projects/$projectId/auth/_components/ForceSignOutCard.tsx Implements the confirmation UI and mutation for project-wide signout.
apps/console/src/content/docs-partials/auth-security.md Documents project-wide session signout in the authentication security guide.
apps/console/src/lib/i18n/dictionaries/he/auth-storage.ts Adds Hebrew translations for the force-signout control.
apps/console/src/lib/i18n/dictionaries/ja/auth-storage.ts Adds Japanese translations for the force-signout control.
apps/console/src/lib/react-query/hooks/auth.ts Adds the Console mutation for deleting project sessions.
src/Appwrite/Messaging/Adapter/Realtime.php Publishes project-wide session invalidation as a realtime permission-changing event.
src/Appwrite/Platform/Modules/Account/Http/Account/Sessions/IdToken/Create.php Checks the session cutoff when upgrading a session for ID-token creation.
src/Appwrite/Platform/Modules/Project/Http/Project/Sessions/Delete.php Adds the endpoint that records the invalidation cutoff and queues cleanup.
src/Appwrite/Platform/Modules/Project/Services/Http.php Registers the project sessions deletion endpoint.
src/Appwrite/Platform/Workers/Deletes.php Adds cutoff-based session cleanup and purges affected user caches.
src/Appwrite/Realtime/Message/Handlers/Authentication.php Checks session invalidation and required factors during realtime reauthentication.
src/Appwrite/Utopia/Database/Documents/User.php Adds session cutoff, expiry, and required-factor checks to user session verification.
tests/e2e/Security/baseline.json Registers the new project sessions route in the security baseline.
tests/e2e/Services/Project/SessionsDeleteBase.php Covers signout success, authorization failures, project isolation, and console sessions.
tests/e2e/Services/Project/SessionsDeleteConsoleClientTest.php Adds the Console-client E2E suite for project-wide session deletion.
tests/e2e/Services/Project/SessionsDeleteCustomServerTest.php Adds the custom-server E2E suite for project-wide session deletion.
tests/unit/Utopia/Database/Documents/UserTest.php Tests session cutoff, expiry, and factor-completion behavior; the latest update expresses invalidation matrices as generator providers.
⏳ Still open from earlier reviews · 1

Reviewed the commits since 72189c4 · Details · Comment @hansi-codes review to re-run, or mention @hansi-codes with a question.

ghost
ghost previously requested changes Oct 19, 2026

@ghost ghost 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.

🟡 Tier B · 2 blocking findings to address. Summary

Comment thread app/init/realtime/connection.php Resolved
Comment thread app/init/realtime/connection.php Resolved
Comment thread app/init/mqtt/connection.php Resolved
Comment thread app/init/resources/request.php Resolved
Comment thread app/controllers/api/account.php Resolved
…en realtime connections, rename to sessionsInvalidatedAt, require users.write scope, worker user-cache purge, restructure e2e tests, add console force sign out card
@imtia33
imtia33 force-pushed the feat/force-signout-all-users branch from d79c029 to bfa23de Compare October 22, 2026 16:56
@appwrite

appwrite Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

New Console

Project ID: new-console

Sites (1)
Site Status Logs Preview QR
 New Console
new-console
Queued Queued Authorize Preview URL QR Code

Tip

Teams feature lets you group users with membership management and role permissions

@ghost ghost 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.

🔵 Tier A · See the inline comments. Summary

Comment thread app/controllers/api/account.php Resolved
Comment thread app/realtime.php
Comment on lines +775 to +777
$user->isEmpty()
|| $user->getAttribute('status') === false
|| !$user->sessionActive($sessionId, $invalidatedAt)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Avoid closing admin sockets during project session cleanup

An admin-mode connection's session belongs to a console user, but this sweep loads that user from the target project's database and marks the connection revoked when the document is absent. A project signout therefore closes admin sockets attached to that project even though their console sessions were not invalidated; validate these connections against the console user store or exclude them.

Prompt To Fix With AI
This is a comment left during a code review.
Path: app/realtime.php
Line: 775-777

Comment:
**Avoid closing admin sockets during project session cleanup**

An admin-mode connection's session belongs to a console user, but this sweep loads that user from the target project's database and marks the connection revoked when the document is absent. A project signout therefore closes admin sockets attached to that project even though their console sessions were not invalidated; validate these connections against the console user store or exclude them.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

🟡 Minor · bug · Reply if this doesn't apply.

@ghost
ghost dismissed their stale review October 22, 2026 17:42

The findings that requested changes are resolved. See the summary comment for what is still open.

@Meldiron

Copy link
Copy Markdown
Contributor

Note from Luke, to investigate and maybe consider: how delete by group is working? i'd assume you can do it in one update/delete query right?

@imtia33

imtia33 commented Oct 23, 2026

Copy link
Copy Markdown
Contributor Author

Note from Luke, to investigate and maybe consider: how delete by group is working? i'd assume you can do it in one update/delete query right?

Dug into it in the repo it's not per-doc SQL: deleteByGroup -> Database::deleteDocuments batches at 1,000 docs, and each batch is one bulk DELETE … WHERE _sequence IN (…) AND createdAt <= cutoff (filter re-applied in the statement for race safety). A true one-query delete would bypass the parts that need the rows: user-cache purging (session lists are read from cached user docs, that was one of the review bugs), usage metrics, and cache-invalidation scope. It also keeps lock footprint per batch bounded instead of one giant transaction. And since the invalidateAt check already invalidates everything instantly, the worker deletion is just cleanup, I thinkspeed isn't critical.
But If its required IMO, the right place is a filter-driven bulk-delete API in utopia-php/database.

# Conflicts:
#	app/init/mqtt/connection.php
#	app/init/realtime/connection.php
#	app/realtime.php
ghost
ghost previously requested changes Oct 26, 2026

@ghost ghost 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.

🟡 Tier B · 1 blocking finding to address. Summary

Comment thread app/controllers/general.php Resolved
@ghost
ghost dismissed their stale review October 26, 2026 11:04

The findings that requested changes are resolved. See the summary comment for what is still open.

@pkg-pr-new

pkg-pr-new Bot commented Oct 26, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

npm i https://pkg.pr.new/appwrite/appwrite/@appwrite.io/console@14647

commit: fb552b1

@Meldiron

Copy link
Copy Markdown
Contributor
CleanShot 2026-10-26 at 12 26 50@2x CleanShot 2026-10-26 at 12 26 54@2x

@Meldiron
Meldiron merged commit c532ce1 into appwrite:main Oct 26, 2026
70 of 71 checks passed
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