-
-
Notifications
You must be signed in to change notification settings - Fork 4.6k
feat: add occ command to scan and delete orphaned keys #55556
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
hamza221
wants to merge
1
commit into
master
Choose a base branch
from
feat/occ/orphaned-keys
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+205
−0
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,202 @@ | ||
| <?php | ||
|
|
||
| declare(strict_types=1); | ||
|
|
||
| /** | ||
| * SPDX-FileCopyrightText: 2025 Nextcloud GmbH and Nextcloud contributors | ||
| * SPDX-License-Identifier: AGPL-3.0-or-later | ||
| */ | ||
| namespace OCA\Encryption\Command; | ||
|
|
||
| use OC\Encryption\Util; | ||
| use OC\Files\SetupManager; | ||
| use OCA\Encryption\Crypto\Encryption; | ||
| use OCP\Files\File; | ||
| use OCP\Files\Folder; | ||
| use OCP\Files\IRootFolder; | ||
| use OCP\Files\NotFoundException; | ||
| use OCP\IConfig; | ||
| use OCP\IUser; | ||
| use OCP\IUserManager; | ||
| use Psr\Log\LoggerInterface; | ||
| use Symfony\Component\Console\Command\Command; | ||
| use Symfony\Component\Console\Helper\ProgressBar; | ||
| use Symfony\Component\Console\Helper\QuestionHelper; | ||
| use Symfony\Component\Console\Input\InputInterface; | ||
| use Symfony\Component\Console\Output\OutputInterface; | ||
| use Symfony\Component\Console\Question\ConfirmationQuestion; | ||
| use Symfony\Component\Console\Question\Question; | ||
|
|
||
| class CleanOrphanedKeys extends Command { | ||
|
|
||
| public function __construct( | ||
| protected IConfig $config, | ||
| protected QuestionHelper $questionHelper, | ||
| private IUserManager $userManager, | ||
| private Util $encryptionUtil, | ||
| private SetupManager $setupManager, | ||
| private IRootFolder $rootFolder, | ||
| private LoggerInterface $logger, | ||
| ) { | ||
| parent::__construct(); | ||
|
|
||
| } | ||
|
|
||
| protected function configure(): void { | ||
| $this | ||
| ->setName('encryption:clean-orphaned-keys') | ||
| ->setDescription('Scan the keys storage for orphaned keys and remove them'); | ||
| } | ||
|
|
||
| protected function execute(InputInterface $input, OutputInterface $output): int { | ||
| $orphanedKeys = []; | ||
| $headline = 'Scanning all keys for file parity'; | ||
| $output->writeln($headline); | ||
| $output->writeln(str_pad('', strlen($headline), '=')); | ||
| $output->writeln("\n"); | ||
| $progress = new ProgressBar($output); | ||
| $progress->setFormat(" %message% \n [%bar%]"); | ||
|
|
||
| foreach ($this->userManager->getSeenUsers() as $user) { | ||
| $uid = $user->getUID(); | ||
| $progress->setMessage('Scanning all keys for: ' . $uid); | ||
| $progress->advance(); | ||
| $this->setupUserFileSystem($user); | ||
| $root = $this->encryptionUtil->getKeyStorageRoot() . '/' . $uid . '/files_encryption/keys'; | ||
| $userOrphanedKeys = $this->scanFolder($output, $root, $uid); | ||
| $orphanedKeys = array_merge($orphanedKeys, $userOrphanedKeys); | ||
| } | ||
| $progress->setMessage('Scanned orphaned keys for all users'); | ||
| $progress->finish(); | ||
| $output->writeln("\n"); | ||
| foreach ($orphanedKeys as $keyPath) { | ||
| $output->writeln('Orphaned key found: ' . $keyPath); | ||
| } | ||
| if (count($orphanedKeys) == 0) { | ||
| return self::SUCCESS; | ||
| } | ||
| $question = new ConfirmationQuestion('Do you want to delete all orphaned keys? (y/n) ', false); | ||
| if ($this->questionHelper->ask($input, $output, $question)) { | ||
| $this->deleteAll($orphanedKeys, $output); | ||
| } else { | ||
|
|
||
| $question = new ConfirmationQuestion('Do you want to delete specific keys? (y/n) ', false); | ||
| if ($this->questionHelper->ask($input, $output, $question)) { | ||
| $this->deleteSpecific($input, $output, $orphanedKeys); | ||
| } | ||
| } | ||
|
|
||
| return self::SUCCESS; | ||
| } | ||
|
|
||
| private function scanFolder(OutputInterface $output, string $folderPath, string $user) : array { | ||
| $orphanedKeys = []; | ||
| try { | ||
| $folder = $this->rootFolder->get($folderPath); | ||
| } catch (NotFoundException $e) { | ||
| // Happens when user doesn't have encrypted files | ||
| $this->logger->error('Error when accessing folder ' . $folderPath . ' for user ' . $user, ['exception' => $e]); | ||
| return []; | ||
| } | ||
|
|
||
| if (!($folder instanceof Folder)) { | ||
| $this->logger->error('Invalid folder'); | ||
| return []; | ||
| } | ||
|
|
||
| foreach ($folder->getDirectoryListing() as $item) { | ||
| $path = $folderPath . '/' . $item->getName(); | ||
| $stopValue = $this->stopCondition($path); | ||
| if ($stopValue === null) { | ||
| $this->logger->error('Reached unexpected state when scanning user\'s filesystem for orphaned encryption keys' . $path); | ||
| } elseif ($stopValue) { | ||
| $filePath = str_replace('files_encryption/keys/', '', $path); | ||
| try { | ||
| $this->rootFolder->get($filePath); | ||
| } catch (NotFoundException $e) { | ||
| // We found an orphaned key | ||
| $orphanedKeys[] = $path; | ||
| continue; | ||
| } | ||
| } else { | ||
| $orphanedKeys = array_merge($orphanedKeys, $this->scanFolder($output, $path, $user)); | ||
| } | ||
| } | ||
| return $orphanedKeys; | ||
| } | ||
| /** | ||
| * Checks the stop considition for the recursion | ||
| * following the logic that keys are stored in files_encryption/keys/<user>/<path>/<fileName>/OC_DEFAULT_MODULE/<key>.sharekey | ||
| * @param string $path path of the current folder | ||
| * @return bool|null true if we should stop and found a key, false if we should continue, null if we shouldn't end up here | ||
| */ | ||
| private function stopCondition(string $path) : ?bool { | ||
| $folder = $this->rootFolder->get($path); | ||
| if ($folder instanceof Folder) { | ||
| $content = $folder->getDirectoryListing(); | ||
| $subfolder = $content[0]; | ||
| if (count($content) === 1 && $subfolder->getName() === Encryption::ID) { | ||
| if ($subfolder instanceof Folder) { | ||
| $content = $subfolder->getDirectoryListing(); | ||
| if (count($content) === 1 && $content[0] instanceof File) { | ||
| return strtolower($content[0]->getExtension()) === 'sharekey' ; | ||
| } | ||
| } | ||
| } | ||
| return false; | ||
| } | ||
hamza221 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| // We shouldn't end up here, because we return true when reaching the folder named after the file containing OC_DEFAULT_MODULE | ||
| return null; | ||
| } | ||
| private function deleteAll(array $keys, OutputInterface $output) { | ||
| foreach ($keys as $key) { | ||
| $file = $this->rootFolder->get($key); | ||
| try { | ||
| $file->delete(); | ||
| $output->writeln('Key deleted: ' . $key); | ||
| } catch (\Exception $e) { | ||
| $output->writeln('Failed to delete ' . $key); | ||
| $this->logger->error('Error when deleting orphaned key ' . $key . '. ' . $e->getMessage()); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| private function deleteSpecific(InputInterface $input, OutputInterface $output, array $orphanedKeys) { | ||
| $question = new Question('Please enter path for key to delete: '); | ||
| $path = $this->questionHelper->ask($input, $output, $question); | ||
| if (!in_array(trim($path), $orphanedKeys)) { | ||
| $output->writeln('Wrong key path'); | ||
| } else { | ||
| try { | ||
| $this->rootFolder->get(trim($path))->delete(); | ||
| $output->writeln('Key deleted: ' . $path); | ||
| } catch (\Exception $e) { | ||
| $output->writeln('Failed to delete ' . $path); | ||
| $this->logger->error('Error when deleting orphaned key ' . $path . '. ' . $e->getMessage()); | ||
| } | ||
| $orphanedKeys = array_filter($orphanedKeys, function ($k) use ($path) { | ||
| return $k !== trim($path); | ||
| }); | ||
| } | ||
| if (count($orphanedKeys) == 0) { | ||
| return; | ||
| } | ||
| $output->writeln('Remaining orphaned keys: '); | ||
| foreach ($orphanedKeys as $keyPath) { | ||
| $output->writeln($keyPath); | ||
| } | ||
| $question = new ConfirmationQuestion('Do you want to delete more orphaned keys? (y/n) ', false); | ||
| if ($this->questionHelper->ask($input, $output, $question)) { | ||
| $this->deleteSpecific($input, $output, $orphanedKeys); | ||
| } | ||
|
|
||
| } | ||
|
|
||
| /** | ||
| * setup user file system | ||
| */ | ||
| protected function setupUserFileSystem(IUser $user): void { | ||
| $this->setupManager->tearDown(); | ||
| $this->setupManager->setupForUser($user); | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.