Skip to content

fix(contexts): delete the applications of a deleted user - #3196

Open
rubenvdlinde wants to merge 4 commits into
mainfrom
fix/noid/delete-applications-of-deleted-user
Open

rubenvdlinde wants to merge 4 commits into
mainfrom
fix/noid/delete-applications-of-deleted-user

Conversation

@rubenvdlinde

@rubenvdlinde rubenvdlinde commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

When a user was deleted, Tables removed their tables but not their applications. The application stayed in the database with its pages, its shares and the navigation entries of the people it was shared with, owned by a user who no longer exists.

Size: 195 lines: 38 code and 157 tests.

What changes

  • UserDeletedListener now deletes the applications the user owns before it deletes their tables. Applications the user only received through a share are left alone, and so are applications owned by a group. Each application goes through ContextService::delete(), the same path as deleting it in the UI, so its node relations, pages, page content, shares and navigation entries go with it. Applications go first, so deleting the tables doesn't have to detach them from applications that are removed anyway.
  • One application that fails to delete is logged and skipped. The other applications and the tables are still deleted.
  • ShareMapper::findAllSharesForNode() accepts a null sender. The parameter isn't used in the query, but ShareService::deleteAllForContext() passes the session user, which is null when there's no session: occ user:delete, or a user backend removing users in the background. Without this, deleting an application there threw a TypeError that aborted the whole user deletion.

Because the listener goes through ContextService::delete(), anything that method learns to clean up later is also cleaned up when a user is deleted. The widgets and menu items from #3132 and #3135 are both removed in that method, so they need no change here.

How it was tested

  • New tests/unit/Listener/UserDeletedListenerTest.php: only applications the user owns are deleted, applications are deleted before tables, a failing application doesn't stop the rest, and other events are ignored.
  • New test in ShareServiceTest: deleteAllForContext() works without a session user. Without the fix it fails with the TypeError above.
UserDeletedListenerTest without the fix: Tests: 4, Errors: 4 (the listener doesn't take a ContextService)
UserDeletedListenerTest with the fix:    OK (4 tests, 7 assertions)
ShareServiceTest without the mapper fix: TypeError: findAllSharesForNode(): Argument #3 ($sender) must be of type string, null given
ShareServiceTest with the fix:           OK (17 tests, 31 assertions)
Full unit suite, PostgreSQL (Nextcloud 34): OK (427 tests, 843 assertions)
Full unit suite, SQLite (Nextcloud 35):     OK (427 tests, 843 assertions)
composer cs:check: no files to fix
psalm: No errors found!
rector: OK

On a local instance, a user with one table and one application on it. The application is shared with another user, who has it in their navigation. Then the user is deleted. Rows left for that application afterwards, on main and with this change:

Deleted through Application Node relations Pages Page content Shares Navigation Table
provisioning API DELETE /cloud/users/{id} main 1 0 1 0 1 1 0
this change 0 0 0 0 0 0 0
occ user:delete main 1 0 1 0 1 1 0
this change 0 0 0 0 0 0 0

With only the listener change, occ user:delete failed with the TypeError and the user wasn't deleted at all. That is what the ShareMapper change fixes.

🖼️ Screenshots

Backend only, no visual change.

🏁 Checklist

  • ⛑️ Tests (unit and/or integration) are included or not needed
  • 🔙 Backport requests are created or not needed: /backport to stableX.X
  • 📅 Milestone is set
  • 🌸 PR title is meaningful (if it should be in the changelog: is it meaningful to users?)

🤖 AI (if applicable)

  • The content of this PR was partly or fully generated using AI

@rubenvdlinde
rubenvdlinde force-pushed the fix/noid/delete-applications-of-deleted-user branch from 7ec3770 to 11c8005 Compare November 3, 2026 14:51
@rubenvdlinde
rubenvdlinde marked this pull request as ready for review November 6, 2026 08:25

@AndyScherzinger AndyScherzinger left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Review focused on performance, security, clean code and architecture (backend only). The checks ran on a dev instance (MariaDB) with this PR on main, deleting throwaway users with occ user:delete and the provisioning API.

On the normal path this works: after deleting a user who owns an application shared with bob, nothing of that application is left (node relations, pages, page contents, shares, navigation entries including bob's own override), and the PR's tests pass. The main problem is the event the deletion runs on (comment on line 41).

Not commented inline (lines this PR doesn't change):

  • The table loop in the same handle() has no per-item isolation. The first InternalError from TableService::delete() leaves the single try { ... } catch (InternalError) {}, so every later table of the user is skipped silently while the user deletion completes. TableService::delete() has no transaction, so the failing table is left half-deleted (rows, views, columns and shares gone, the table itself kept). A try/catch per table with an error log, like the new application loop, would match what this PR does for applications.
    Validated: reproduced on a deployed instance (MariaDB, S-main restored and this PR at 11c80057, throwaway users deleted with occ user:delete: the user owned tables 14, 15 and 16 (16 shared with bob), a second session held table 15's row; occ user:delete exited 0 after the lock wait, table 15 was half-deleted, and table 16 was never attempted and still visible to bob).
  • A failed share deletion is swallowed in ContextService::delete(). ShareService::deleteAllForContext() (ShareService.php line 877) runs in a nested atomic() that rolls back only to its savepoint, and its catch logs without the exception. The outer transaction then deletes the relations, pages and the application and commits, so this listener's "could not delete application" branch never runs, and the share and navigation rows outlive the application (share review keeps listing "Application 63"). This is older (the UI path does the same), but the PR now relies on it for unattended user deletion, and the description says shares and navigation entries go with the application.
    Validated: reproduced on a deployed instance (MariaDB, S-main restored and this PR at 11c80057, throwaway users deleted with occ user:delete: the user's application 63 shared with bob, bob's navigation row locked by a second session; occ user:delete exited 0, the application and its pages were gone, the share row and the navigation row remained, and the log had only "something went wrong while deleting shares for context: 63").

CI: green.

Comment thread lib/Listener/UserDeletedListener.php Outdated
$this->logger->info('event "user deleted" was triggered, will try to delete all data for the user: ' . $event->getUser()->getUID() . ' (' . $event->getUser()->getDisplayName() . ')');

// applications first, so deleting the tables does not detach them from applications that go anyway
$this->deleteApplications($event->getUser()->getUID());

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Applications are deleted on BeforeUserDeletedEvent, each committed in its own atomic(), before the server knows the account will really go. User::delete() dispatches the event and only then asks the backend, which can refuse: user_ldap refuses accounts that still exist in LDAP, so the admin gets error 101 or exit 1 while every application the user owns, with its shares, pages and the recipients' navigation entries, is already gone. The account stays and works without them. Tables already behaved this way; the PR extends it to applications other people use. Moving the whole cleanup, applications first and then tables, to UserDeletedEvent (which ReceiverCleanupListener already uses; the server's dav and files cleanups record on Before and delete on After), with a \Throwable catch per item there, fixes this and the comment on line 71. The owner match by uid still works once the account is gone.

Validated: reproduced on a deployed instance (MariaDB, S-main restored and this PR at 11c80057, throwaway users deleted with occ user:delete: the backend's own DELETE made to fail with a lock on the oc_users row; occ user:delete exited 255, the account still exists and logs in, and its application and bob's share of it are gone).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

You are right, deleting on the before event meant a refused deletion left the account without its applications. The listener now runs on UserDeletedEvent, next to ReceiverCleanupListener, and still deletes applications first and then tables, each in its own \Throwable catch with an error log. I checked it against the real database with a uid that has no account and no session user: the table, its column, row and view, the application, its node relation and its share were all gone afterwards.

cc @blizzz

Comment thread lib/Listener/UserDeletedListener.php Outdated
foreach ($contexts as $context) {
try {
$this->contextService->delete($context->getId(), $userId);
} catch (NotFoundError|Exception $e) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The per-application isolation covers only NotFoundError and OCP\DB\Exception (the imported Exception). Any other Throwable from ContextService::delete() leaves handle() and aborts the user deletion after the applications before it are already deleted and committed. Nothing on today's delete path throws anything else, but the null-sender TypeError this PR fixes was exactly such a case and would still abort half-way with this catch; so would a throwing CriticalActionPerformedEvent listener. On BeforeUserDeletedEvent, swallowing \Throwable isn't right either, because the deletion would then complete with the application left in place; on UserDeletedEvent (comment on line 41) catching \Throwable per item is.

Validated: code check only.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Agreed. Every application and every table now has its own catch (\Throwable $e) with an error log, and there is a test where the first application throws a plain RuntimeException and the second one and the tables are still deleted.

cc @blizzz

$this->assertSame(['application', 'table'], $calls);
}

public function testAFailingApplicationDoesNotStopTheRest(): void {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The isolation test only throws NotFoundError, which in practice needs a race between findAll() and findById(). No test makes ContextService::findAll() or delete() throw OCP\DB\Exception, none covers the table phase failing, and the logger mock has no expectations. With line 62 narrowed to catch (InternalError $e) and line 71 to catch (NotFoundError $e), all four listener tests still pass, although a database error in one application would then abort the whole user deletion again, which is the failure this PR fixes.

Validated: code check only, plus the four tests run in the dev container with the narrowed catches (PHPUnit 11).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks, the tests now fail when the catches are narrowed. I added cases where finding the applications or the tables throws a database error, where one application throws a runtime exception and where the first of two tables throws a PermissionError, each with an expectation on the logger. Narrowing the catches back to NotFoundError|Exception turns two of them red, and putting the listener back on the before event turns seven red.

cc @blizzz

Comment thread lib/Db/ShareMapper.php Outdated
* @throws Exception
*/
public function findAllSharesForNode(string $nodeType, int $nodeId, string $sender = '', array $excluded = []): array {
public function findAllSharesForNode(string $nodeType, int $nodeId, ?string $sender = '', array $excluded = []): array {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The TypeError fix widens a parameter the query never reads ($sender has been unused since 5def698) instead of dropping the dead argument at its only nullable caller, ShareService::deleteAllForContext() (line 871). The public mapper signature and docblock now advertise a nullable sender filter that does nothing, and deleteAllForContext() still reads the session user (null under occ, the deleting admin over OCS) for no reason. findAllSharesForNode('context', $context->getId()), as hasLinkShare() already calls it (line 218), is a one-line change, the PR's new test passes unchanged, and ShareMapper.php stays untouched.

Validated: code check only.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Good point, the sender filter was never read. I reverted the ShareMapper change and deleteAllForContext() now calls findAllSharesForNode('context', $id) without the session user, like hasLinkShare() does.

cc @blizzz

Comment thread lib/Listener/UserDeletedListener.php Outdated

private function deleteApplications(string $userId): void {
try {
$contexts = array_filter(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Owned applications are found through the UI read model: ContextService::findAll() resolves the user's groups, joins shares, navigation, pages, page contents and node relations for every owned and received application, resolves a display name per share row and regroups them, only for the closure to filter ownership in PHP; ContextService::delete() then reads each application again through the same join. That is a third copy of the ownership rule (this closure, PermissionsService line 542, and SQL without owner_type), and the InternalError arm of the catch can't be reached for a real uid. An owner-keyed SELECT id FROM tables_contexts_context WHERE owner_type = 0 AND owner_id = ? (a new ContextMapper method) is shorter, is paid only when there is something to delete, and also works on UserDeletedEvent.

Validated: reproduced on a deployed instance (MariaDB, S-main restored and this PR at 11c80057, throwaway users deleted with occ user:delete: deleting a user with 50 owned applications cost 152 more SELECTs, 350 more DELETEs and 0.3 s more than a user without any; most of it is the per-application deletes themselves).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Agreed. ContextMapper::findIdsOwnedByUser() selects only the ids where owner_type is user and owner_id is the uid, and the listener deletes those. This query matches on the uid string only, so it also works once the account is gone. The tables to delete now come from TableMapper::findAll() as well, which matches on ownership: TableService::findAll() also returned tables the user only reached through an application shared with them, and those are not the user's to delete.

cc @blizzz

Comment thread lib/Listener/UserDeletedListener.php Outdated
$this->logger->error('could not delete application ' . $context->getId() . ' of the deleted user ' . $userId, ['exception' => $e]);
}
}
$this->logger->debug('applications for the deleted user removed');

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

"applications for the deleted user removed" is logged after the loop even when every ContextService::delete() failed, unlike the table block, where the matching line is only reached when nothing threw. Lines 67 and 72 already say what happened; dropping this line avoids the contradiction. Smaller: handle() now spells $event->getUser()->getUID() four times (lines 38, 41, 44 and 49); one $userId after the instanceof guard serves all of them.

Validated: code check only.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Right, that line could contradict the errors above it, so it is gone. The uid is read once into $userId right after the event check.

cc @blizzz

Comment thread tests/unit/Service/ShareServiceTest.php Outdated
}

public function testDeleteAllForContextWorksWithoutASessionUser(): void {
$shareService = new ShareService(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The new test copies setUp()'s 17-argument new ShareService(...) to change one argument ('admin' to null). Every future constructor change then has to be made twice in this file, and AGENTS.md tells contributors to add new mocks "in every setUp() method that instantiates that service", so this copy in a test method is the one that gets missed. A createShareService(?string $userId) factory used by setUp() and this test (as ImportServiceAuditLogTest::createService() does) keeps one construction site. With the change suggested on ShareMapper.php line 127, the test may not be needed at all.

Validated: code check only.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I kept the test, because it now checks that deleteAllForContext() calls the mapper without a sender when there is no session user, and it fails with a TypeError against the old call. Both setUp() and this test build the service through one createShareService() factory.

cc @blizzz

@github-actions

Copy link
Copy Markdown
Contributor

Hello there,
Thank you so much for taking the time and effort to create a pull request to our Nextcloud project.

We hope that the review process is going smooth and is helpful for you. We want to ensure your pull request is reviewed to your satisfaction. If you have a moment, our community management team would very much appreciate your feedback on your experience with this PR review process.

Your feedback is valuable to us as we continuously strive to improve our community developer experience. Please take a moment to complete our short survey by clicking on the following link: https://cloud.nextcloud.com/apps/forms/s/i9Ago4EQRZ7TWxjfmeEpPkf6

Thank you for contributing to Nextcloud and we hope to hear from you soon!

(If you believe you should not receive this message, you can add yourself to the blocklist.)

@rubenvdlinde

Copy link
Copy Markdown
Contributor Author

On the two points from the review summary: each table now has its own \Throwable catch with an error log, so one table that fails no longer skips the others or leaves them half deleted, and there is a test where the first of two tables throws a PermissionError. Whether a failed share deletion should roll back the whole application delete is a bigger change to ShareService::deleteAllForContext(), so I'll open a separate issue for it rather than grow this fix.

cc @blizzz

Deleting a user removed their tables but left their applications behind,
with pages, shares and navigation entries, owned by nobody. The user
deleted listener now deletes the applications the user owns through
ContextService::delete(), before their tables. Applications only shared
with the user, or owned by a group, stay.

ShareMapper::findAllSharesForNode() accepts a null sender: it is not
used in the query, but deleting an application without a session user,
as occ user:delete does, passed null and the TypeError aborted the user
deletion.

Assisted-by: ClaudeCode:claude-opus-5-5
Signed-off-by: Ruben van der Linde <ruben@conduction.nl>
…ilter

findAllSharesForNode() never reads its sender argument, so
deleteAllForContext() no longer passes the session user, which is null
when a user is deleted from the CLI. ShareMapper keeps its signature and
the test builds its service through one factory.

Assisted-by: ClaudeCode:claude-opus-5-5
Signed-off-by: Ruben van der Linde <ruben@conduction.nl>
UserDeletedListener now runs on UserDeletedEvent, so a deletion the
backend refuses keeps the account's applications and tables. It finds
the user's applications with an owner-keyed id query in ContextMapper
and deletes each application and each table in its own catch, so one
failing item no longer skips the rest.

Assisted-by: ClaudeCode:claude-opus-5-5
Signed-off-by: Ruben van der Linde <ruben@conduction.nl>
UserDeletedListener takes the tables to delete from
TableMapper::findAll(), which matches on ownership, instead of
TableService::findAll(), which also returns tables the user only
reaches through an application.

Assisted-by: ClaudeCode:claude-opus-5-5
Signed-off-by: Ruben van der Linde <ruben@conduction.nl>
@rubenvdlinde
rubenvdlinde force-pushed the fix/noid/delete-applications-of-deleted-user branch from ebbf65a to 985db28 Compare November 21, 2026 10:54
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants