From 040e740f0f6f3aa06158e337f9ca997077cc74d5 Mon Sep 17 00:00:00 2001 From: memurats Date: Thu, 12 Nov 2026 14:47:13 +0100 Subject: [PATCH 1/7] harden user deletion --- lib/Db/UserQueries.php | 150 ++++-- lib/Event/UserAccountChangeListener.php | 53 +- lib/Rules/DisplaynameRules.php | 53 +- lib/Rules/TariffRules.php | 97 +--- lib/Rules/UserAccountRules.php | 464 +++++++++++------ lib/User/NmcUserService.php | 180 ++++++- lib/User/UserAccountDeletionJob.php | 231 ++++++-- tests/unit/UserAccounctDeletionJobTest.php | 205 ++++++-- tests/unit/UserAccountChangeListenerTest.php | 520 ++++++++----------- tests/unit/UserWithdrawTest.php | 225 ++++---- 10 files changed, 1321 insertions(+), 857 deletions(-) diff --git a/lib/Db/UserQueries.php b/lib/Db/UserQueries.php index a19b87e..dbc2935 100644 --- a/lib/Db/UserQueries.php +++ b/lib/Db/UserQueries.php @@ -1,37 +1,20 @@ - * - * @author Bernd Rederlechner - * - * @license GNU AGPL version 3 or any later version - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - * - */ namespace OCA\NextMagentaCloudProvisioning\Db; use OCA\NextMagentaCloudProvisioning\AppInfo\Application; - use OCP\DB\QueryBuilder\IQueryBuilder; - use OCP\IDBConnection; class UserQueries { + private const DELETION_KEYS = [ + 'deletion', + 'withdrawal', + 'deletion_marked_at', + ]; + /** @var IDBConnection */ private $db; @@ -40,10 +23,11 @@ public function __construct(IDBConnection $db) { } /** - * Find all users marked for deletion with a deletion date - * before $refDate. + * Find the oldest users whose deletion date has been reached. + * + * @return string[] */ - public function findDeletions(\DateTime $refDate, ?int $limit = null): array { + public function findDeletions(\DateTimeInterface $refDate, ?int $limit = null): array { $refTs = $refDate->getTimestamp(); $qb = $this->db->getQueryBuilder(); @@ -51,8 +35,9 @@ public function findDeletions(\DateTime $refDate, ?int $limit = null): array { ->from('preferences') ->where($qb->expr()->eq('appid', $qb->createNamedParameter(Application::APP_ID))) ->andWhere($qb->expr()->eq('configkey', $qb->createNamedParameter('deletion'))) - ->andWhere($qb->expr()->lt('configvalue', $qb->createNamedParameter($refTs, IQueryBuilder::PARAM_INT))) - ->orderBy('configvalue', 'ASC'); + ->andWhere($qb->expr()->lte('configvalue', $qb->createNamedParameter($refTs, IQueryBuilder::PARAM_INT))) + ->orderBy('configvalue', 'ASC') + ->addOrderBy('userid', 'ASC'); if ($limit !== null) { $qb->setMaxResults($limit); @@ -70,55 +55,124 @@ public function findDeletions(\DateTime $refDate, ?int $limit = null): array { return $uids; } - public function getDeletionDateTime(string $userId): ?\DateTime { + public function getDeletionDateTime(string $userId): ?\DateTimeImmutable { + return $this->getPreferenceDateTime($userId, 'deletion'); + } + + /** + * Return all metadata needed to validate a deletion decision. + * + * @return array{ + * deletion: \DateTimeImmutable, + * withdrawal: ?\DateTimeImmutable, + * markedAt: ?\DateTimeImmutable, + * lastAccountChange: ?\DateTimeImmutable + * }|null + */ + public function getDeletionState(string $userId): ?array { + $deletion = $this->getPreferenceDateTime($userId, 'deletion'); + if ($deletion === null) { + return null; + } + + return [ + 'deletion' => $deletion, + 'withdrawal' => $this->getPreferenceDateTime($userId, 'withdrawal'), + 'markedAt' => $this->getPreferenceDateTime($userId, 'deletion_marked_at'), + 'lastAccountChange' => $this->getPreferenceDateTime($userId, 'last_account_change'), + ]; + } + + /** + * Remove only deletion-related provisioning state. + * + * last_account_change is intentionally retained so delayed events cannot + * overwrite a newer state after deletion has been cancelled. + */ + public function deleteDeletionPreferencesById(string $userId): bool { $qb = $this->db->getQueryBuilder(); - $qb->select('configvalue') - ->from('preferences') + $keyExpression = $qb->expr()->orX( + $qb->expr()->eq('configkey', $qb->createNamedParameter(self::DELETION_KEYS[0])), + $qb->expr()->eq('configkey', $qb->createNamedParameter(self::DELETION_KEYS[1])), + $qb->expr()->eq('configkey', $qb->createNamedParameter(self::DELETION_KEYS[2])) + ); + + $qb->delete('preferences') ->where($qb->expr()->eq('userid', $qb->createNamedParameter($userId))) ->andWhere($qb->expr()->eq('appid', $qb->createNamedParameter(Application::APP_ID))) - ->andWhere($qb->expr()->eq('configkey', $qb->createNamedParameter('deletion'))) - ->setMaxResults(1); + ->andWhere($keyExpression) + ->execute(); - $result = $qb->execute(); - $value = $result->fetchOne(); - $result->closeCursor(); + return true; + } - if ($value === false || $value === null || $value === '') { - return null; - } + /** + * Move a failed deletion attempt out of the current batch. + */ + public function postponeDeletion(string $userId, \DateTimeInterface $retryAt): bool { + $qb = $this->db->getQueryBuilder(); - $deletionDate = new \DateTime(); - $deletionDate->setTimestamp((int)$value); + $qb->update('preferences') + ->set('configvalue', $qb->createNamedParameter($retryAt->getTimestamp(), IQueryBuilder::PARAM_INT)) + ->where($qb->expr()->eq('userid', $qb->createNamedParameter($userId))) + ->andWhere($qb->expr()->eq('appid', $qb->createNamedParameter(Application::APP_ID))) + ->andWhere($qb->expr()->eq('configkey', $qb->createNamedParameter('deletion'))) + ->execute(); - return $deletionDate; + return true; } public function countMigrated(): int { $qb = $this->db->getQueryBuilder(); $qb->select($qb->func()->count('*')) - ->from("preferences") + ->from('preferences') ->where($qb->expr()->eq('appid', $qb->createNamedParameter('nmcuser_oidc'))) ->andWhere($qb->expr()->eq('configkey', $qb->createNamedParameter('migrated'))); + $result = $qb->execute(); $column = (int)$result->fetchOne(); $result->closeCursor(); + return $column; } /** - * Delete a user preference by their user ID - * - * @param string $userId - * @return bool True if deletion was successful, false otherwise + * Delete all user preferences after the user itself has disappeared. */ public function deleteUserPreferenceById(string $userId): bool { $qb = $this->db->getQueryBuilder(); - + $qb->delete('preferences') ->where($qb->expr()->eq('userid', $qb->createNamedParameter($userId))) ->execute(); return true; // Return true to indicate successful deletion } + + private function getPreferenceDateTime(string $userId, string $key): ?\DateTimeImmutable { + $qb = $this->db->getQueryBuilder(); + + $qb->select('configvalue') + ->from('preferences') + ->where($qb->expr()->eq('userid', $qb->createNamedParameter($userId))) + ->andWhere($qb->expr()->eq('appid', $qb->createNamedParameter(Application::APP_ID))) + ->andWhere($qb->expr()->eq('configkey', $qb->createNamedParameter($key))) + ->setMaxResults(1); + + $result = $qb->execute(); + $value = $result->fetchOne(); + $result->closeCursor(); + + if ($value === false || $value === null || $value === '' || !is_numeric($value)) { + return null; + } + + $timestamp = (int)$value; + if ($timestamp <= 0) { + return null; + } + + return (new \DateTimeImmutable())->setTimestamp($timestamp); + } } diff --git a/lib/Event/UserAccountChangeListener.php b/lib/Event/UserAccountChangeListener.php index d62f36c..1bcb6a9 100644 --- a/lib/Event/UserAccountChangeListener.php +++ b/lib/Event/UserAccountChangeListener.php @@ -10,41 +10,44 @@ class UserAccountChangeListener implements IEventListener { - /** @var LoggerInterface */ - private $logger; + private LoggerInterface $logger; + private UserAccountRules $accountRules; - /** @var UserAccountRules */ - private $accountRules; - - - public function __construct(LoggerInterface $logger, - UserAccountRules $accountRules) { + public function __construct(LoggerInterface $logger, UserAccountRules $accountRules) { $this->logger = $logger; $this->accountRules = $accountRules; } public function handle(Event $event): void { - if ($event instanceof UserAccountChangeEvent) { - $this->logger->debug("{$event->getUID()}: UserAccountChangeEvent received."); - $this->onChangeAccount($event); + if (!$event instanceof UserAccountChangeEvent) { + return; } + + $this->logger->debug("{$event->getUID()}: UserAccountChangeEvent received."); + $this->onChangeAccount($event); } - /** - * NextMagentaCloud wants to have shorter displaynames, but SAM3 only delivers displaynames - * with mail domain, so we remove the domain to get consistent with SLUP `alia` attribute - */ - protected function onChangeAccount(UserAccountChangeEvent $event) { + protected function onChangeAccount(UserAccountChangeEvent $event): void { $claims = $event->getClaims(); - $this->logger->debug("Account change event: " . json_encode(get_object_vars($claims))); - - $evalResult = $this->accountRules->deriveAccountState($event->getUid(), $event->getDisplayName(), - $event->getMainEmail(), $event->getQuota(), $claims); - if (!array_key_exists('redirect', $evalResult)) { - $event->setResult($evalResult['allowed'], $evalResult['reason']); - } else { - $event->setResult($evalResult['allowed'], $evalResult['reason'], $evalResult['redirect']); + + // Log claim names only, never the complete token contents. + $this->logger->debug("{$event->getUID()}: Account change claims received.", [ + 'claimKeys' => array_keys(get_object_vars($claims)), + ]); + + $result = $this->accountRules->deriveAccountState( + $event->getUID(), + $event->getDisplayName(), + $event->getMainEmail(), + $event->getQuota(), + $claims + ); + + if (array_key_exists('redirect', $result)) { + $event->setResult($result['allowed'], $result['reason'], $result['redirect']); + return; } - } + $event->setResult($result['allowed'], $result['reason']); + } } diff --git a/lib/Rules/DisplaynameRules.php b/lib/Rules/DisplaynameRules.php index 6b60c3e..247769d 100644 --- a/lib/Rules/DisplaynameRules.php +++ b/lib/Rules/DisplaynameRules.php @@ -4,45 +4,48 @@ use OCA\NextMagentaCloudProvisioning\Logger\ProvisioningLogger; -/** - * The generic tariff rules evaluator - */ class DisplaynameRules { private GroupTariffMapping $groupTariffMapping; - - /** @var ProvisioningLogger */ private ProvisioningLogger $provisioningLogger; - public function __construct(GroupTariffMapping $groupTariffMapping, ProvisioningLogger $provisioningLogger) { $this->groupTariffMapping = $groupTariffMapping; $this->provisioningLogger = $provisioningLogger; } - /** - * Central rule to derive displayname - * consistently from SAM/SLUP fields - */ - public function deriveDisplayname(object $claims) { - $displayname = ""; - $this->provisioningLogger->debug("test"); + public function deriveDisplayname(object $claims): string { foreach ($this->groupTariffMapping->getDisplaynameSearch() as $search) { - // check if all attributes match - $searchAttrs = array_map(function ($field) { return 'urn:telekom.com:' . $field; }, $search); - $allFieldsMatch = array_reduce($searchAttrs, function ($carry, $field) use ($claims) { - return !property_exists($claims, $field) ? false : $carry; + if (empty($search)) { + continue; + } + + $fields = array_map(static fn(string $field): string => 'urn:telekom.com:' . $field, $search); + + $allFieldsMatch = array_reduce($fields, static function (bool $carry, string $field) use ($claims): bool { + return $carry && property_exists($claims, $field); }, true); - // the displayname is only complete if all match - if ($allFieldsMatch) { - return implode(' ', array_map(function ($id) use ($claims) { - return $claims->{$id}; - }, $searchAttrs)); + + if (!$allFieldsMatch) { + continue; } + + $displayName = implode(' ', array_map( + static fn(string $field): string => (string)$claims->{$field}, + $fields + )); + + $this->provisioningLogger->debug('Derived displayname from configured claims', [ + 'fields' => $fields, + ]); + + return $displayName; } - $this->provisioningLogger->warning('Could not derive displayname from claims', ['claims' => $claims]); - return "-anon-"; - } + $this->provisioningLogger->warning('Could not derive displayname from claims', [ + 'claimKeys' => array_keys(get_object_vars($claims)), + ]); + return '-anon-'; + } } diff --git a/lib/Rules/TariffRules.php b/lib/Rules/TariffRules.php index def1007..4e84852 100644 --- a/lib/Rules/TariffRules.php +++ b/lib/Rules/TariffRules.php @@ -4,101 +4,60 @@ use OCA\NextMagentaCloudProvisioning\Logger\ProvisioningLogger; -/** - * The generic tariff rules evaluator - */ class TariffRules { private GroupTariffMapping $groupTariffMapping; - - /** @var ProvisioningLogger */ private ProvisioningLogger $provisioningLogger; - public function __construct(GroupTariffMapping $groupTariffMapping, ProvisioningLogger $provisioningLogger) { $this->groupTariffMapping = $groupTariffMapping; $this->provisioningLogger = $provisioningLogger; } - /** - * Quota computation helper function to check - * claims contain none of the configured flags - * - * For random combinations of tariffs where even one of - * the flaged tariffs can be 0, the case must be explixitly checked - * and cannot be used as default. - */ - private function quotaNoFlags(object $claims, $tariffs) { - $anyFlagSet = array_reduce($tariffs, function ($carry, $tariff) use ($claims) { - if (array_key_exists('flag', $tariff) && ($carry == false)) { - return $this->isQuotaFlagSet($claims, $tariff); - } else { + private function quotaNoFlags(object $claims, array $tariffs): string { + $anyFlagSet = array_reduce($tariffs, function (bool $carry, array $tariff) use ($claims): bool { + if ($carry || !array_key_exists('flag', $tariff)) { return $carry; } + return $this->isQuotaFlagSet($claims, $tariff); }, false); - if (!$anyFlagSet) { - // make sure that a quota >0 is only delivered - // for the NOFLAGS case if actually no flags are set - // Otherwise, all quotas < the NOFLAGS quota will not apply - return $tariffs['NOFLAGS']['space_limit']; - } else { - return "0 B"; - } + return $anyFlagSet ? '0 B' : $tariffs['NOFLAGS']['space_limit']; } - - /** - * Get the quota if a flag is set - * The function does assume that the flag field exists - */ - private function isQuotaFlagSet(object $claims, $tariff) { - $flagname = $tariff['flag']; - if (property_exists($claims, $flagname) && - $claims->{$flagname} === "1") { - return true; - } else { - return false; - } + private function isQuotaFlagSet(object $claims, array $tariff): bool { + $flagName = $tariff['flag']; + return property_exists($claims, $flagName) && (string)$claims->{$flagName} === '1'; } - /** - * Compute the maximum of two quotas given - * Nextcloud human readable storage sizes - */ - private function maxQuota(string $left, string $right) { - $leftBytes = \OCP\Util::computerFileSize($left); - $rightBytes = \OCP\Util::computerFileSize($right); - if ($leftBytes > $rightBytes) { - return $left; - } else { - return $right; - } + private function maxQuota(string $left, string $right): string { + return \OCP\Util::computerFileSize($left) > \OCP\Util::computerFileSize($right) ? $left : $right; } - /** - * Central rule to derive quota - * consistently from SAM/SLUP fields - */ - public function deriveQuota(object $claims) { + public function deriveQuota(object $claims): string { $tariffs = $this->groupTariffMapping->getGroupMapping(); - // for each flag that is set: add the quota limit - $quotaCandidates = array_map(function ($tariff) use ($claims, $tariffs) { - if (array_key_exists('flag', $tariff)) { - return $this->isQuotaFlagSet($claims, $tariff) ? $tariff['space_limit'] : "0 B"; - } else { - // skip the "no flags" case - // it is the deafult value of reduce - return "0 B"; + $quotaCandidates = array_map(function (array $tariff) use ($claims): string { + if (!array_key_exists('flag', $tariff)) { + return '0 B'; } + return $this->isQuotaFlagSet($claims, $tariff) ? $tariff['space_limit'] : '0 B'; }, $tariffs); - $noflagsQuota = $this->quotaNoFlags($claims, $tariffs); - $maxQuota = array_reduce($quotaCandidates, array($this, 'maxQuota'), $noflagsQuota); + $maxQuota = array_reduce($quotaCandidates, [$this, 'maxQuota'], $this->quotaNoFlags($claims, $tariffs)); + + $activeFlagCount = 0; + foreach ($tariffs as $tariff) { + if (array_key_exists('flag', $tariff) && $this->isQuotaFlagSet($claims, $tariff)) { + $activeFlagCount++; + } + } + + $this->provisioningLogger->debug('Derived quota from tariff claims', [ + 'activeFlagCount' => $activeFlagCount, + 'quota' => $maxQuota, + ]); - // Return the max quota limit as human readable unit - // as it is standard in Nextcloud return $maxQuota; } } diff --git a/lib/Rules/UserAccountRules.php b/lib/Rules/UserAccountRules.php index cdc9359..7dba36b 100644 --- a/lib/Rules/UserAccountRules.php +++ b/lib/Rules/UserAccountRules.php @@ -12,26 +12,25 @@ class UserAccountRules { - /** @var LoggerInterface */ - private $logger; + private const BOOKING_CLAIM = 'urn:telekom.com:f556'; + private const LOCK_CLAIM = 'urn:telekom.com:s556'; + private const PRESERVE_CLAIM = 'urn:telekom.com:f734'; + private const USTA_CLAIM = 'urn:telekom.com:usta'; + private const CHANGE_TIME_CLAIM = 'changeTime'; - /** @var IConfig */ - private $config; + private IConfig $config; + private LoggerInterface $logger; + private NmcUserService $nmcUserService; + private IUserManager $userManager; + private ProviderMapper $oidcProviderMapper; - /** @var NmcUserService */ - private $nmcUserService; - - /** @var IUserManager */ - private $userManager; - - /** @var ProviderMapper */ - private $oidcProviderMapper; - - public function __construct(IConfig $config, + public function __construct( + IConfig $config, LoggerInterface $logger, NmcUserService $nmcUserService, - IUserManager $userManager, - ProviderMapper $oidcProviderMapper) { + IUserManager $userManager, + ProviderMapper $oidcProviderMapper + ) { $this->config = $config; $this->logger = $logger; $this->nmcUserService = $nmcUserService; @@ -39,202 +38,335 @@ public function __construct(IConfig $config, $this->oidcProviderMapper = $oidcProviderMapper; } - /** - * Check whether NextMagentaCloud product is booked on customer. - */ - public function isBooked($claims) { - if (property_exists($claims, 'urn:telekom.com:f556') && ($claims->{'urn:telekom.com:f556'} == "1")) { - return true; + // true = booked, false = withdrawn, null = claim missing. + public function getBookingState(object $claims): ?bool { + if (!property_exists($claims, self::BOOKING_CLAIM)) { + return null; } - return false; + return (string)$claims->{self::BOOKING_CLAIM} === '1'; } - /** - * Check whether NextMagentaCloud product is booked on customer. - */ - public function isTelekomPreserveProcess($claims) { - if (property_exists($claims, 'urn:telekom.com:f734') && ($claims->{'urn:telekom.com:f734'} == "1")) { - return true; - } - return false; + public function isBooked(object $claims): bool { + return $this->getBookingState($claims) === true; } - /** - * Check whether NextMagentaCloud product is requested - * by an Over The Top customer - */ - public function isOTTCustomer($claims) { - if (property_exists($claims, 'urn:telekom.com:usta') && ($claims->{'urn:telekom.com:usta'} == "1")) { - return true; - } - return false; + public function isTelekomPreserveProcess(object $claims): bool { + return property_exists($claims, self::PRESERVE_CLAIM) && (string)$claims->{self::PRESERVE_CLAIM} === '1'; } - /** - * Check whether NextMagentaCloud product is requested - * by an Access Customer - */ - public function isAccessCustomer($claims) { - if (property_exists($claims, 'urn:telekom.com:usta') && ($claims->{'urn:telekom.com:usta'} == "3")) { - return true; - } - return false; + public function isOTTCustomer(object $claims): bool { + return property_exists($claims, self::USTA_CLAIM) && (string)$claims->{self::USTA_CLAIM} === '1'; } + public function isAccessCustomer(object $claims): bool { + return property_exists($claims, self::USTA_CLAIM) && (string)$claims->{self::USTA_CLAIM} === '3'; + } - /** - * Check whether NextMagentaCloud product is blocked - */ - public function isLocked($claims) { - if (property_exists($claims, 'urn:telekom.com:s556') && (strcmp($claims->{'urn:telekom.com:s556'}, "1") == 0)) { - return true; - } - return false; + public function isLocked(object $claims): bool { + return property_exists($claims, self::LOCK_CLAIM) && (string)$claims->{self::LOCK_CLAIM} === '1'; } - /** - * Derive withdraw date from token claims - */ - public function withdrawDate($claims) : \DateTime { - if (property_exists($claims, 'changeTime')) { - return \DateTime::createFromFormat(\DateTimeInterface::ISO8601, $claims->changeTime); - } elseif (property_exists($claims, 'auth_time')) { - $withdrawTime = new \DateTime(); - $withdrawTime->setTimestamp(intval($claims->auth_time)); - return $withdrawTime; - } else { - return new \DateTime(); // now + // changeTime is authoritative. Never use auth_time for retention. + public function withdrawDate(object $claims): ?\DateTimeImmutable { + if (!property_exists($claims, self::CHANGE_TIME_CLAIM)) { + return null; + } + + $value = trim((string)$claims->{self::CHANGE_TIME_CLAIM}); + if ($value === '') { + return null; } + + $formats = [ + 'Y-m-d\TH:i:s.vP', + 'Y-m-d\TH:i:s.uP', + \DateTimeInterface::ATOM, + \DateTimeInterface::ISO8601, + 'Y-m-d\TH:i:s.v\Z', + 'Y-m-d\TH:i:s\Z', + ]; + + foreach ($formats as $format) { + $date = \DateTimeImmutable::createFromFormat($format, $value); + $errors = \DateTimeImmutable::getLastErrors(); + + if ($date !== false && ($errors === false || ($errors['warning_count'] === 0 && $errors['error_count'] === 0))) { + return $date; + } + } + + return null; } - /** - * @param string $displayname - * @param string $testParam - * @return bool - */ - public function isTestAccount(string $displayname, string $testParam = "-test", string $explodeParam = "@"): bool { - $explode = (str_contains($explodeParam, $displayname)) ? explode($explodeParam, $displayname) : $displayname; - if (is_array($explode)) { - return str_contains($explode[0], $testParam); - } else { - return str_contains($explode, $testParam); + public function isTestAccount(string $displayname, string $testParam = '-test', string $explodeParam = '@'): bool { + if ($testParam === '') { + return false; } + + $name = $displayname; + if ($explodeParam !== '' && str_contains($displayname, $explodeParam)) { + $name = explode($explodeParam, $displayname, 2)[0]; + } + + return str_contains($name, $testParam); } - /** - * - * You can adopt the redirect URLs for "Telekom erhalten" with: - * `sudo -u www-data php /var/www/nextcloud/occ config:app:set nmcprovisioning userpreserveurl --value 'https://telekom.example.com/' - * - * and the redirect for general decommissioned accounts with: - * `sudo -u www-data php /var/www/nextcloud/occ config:app:set nmcprovisioning userratesurl --value "https://cloud.telekom-dienste.de/tarife"` - */ - public function deriveAccountState(string $uid, ?string $displayname, ?string $mainEmail, - string $quota, object $claims, bool $create = true, $providerName = 'Telekom'): array { + public function deriveAccountState( + string $uid, + ?string $displayname, + ?string $mainEmail, + string $quota, + object $claims, + bool $create = true, + string $providerName = 'Telekom' + ): array { $this->logger->info("PROV {$uid}: Check user existence"); - $this->logger->debug("Account change event: " . json_encode(get_object_vars($claims))); - $this->logger->debug("Provider {$uid}: " . $providerName); - $config = $this->config->getSystemValue('nmc_provisioning', [ + $this->logger->debug("PROV {$uid}: Provider", ['provider' => $providerName]); + + $defaults = [ 'slup_test_account_check' => true, 'slup_test_account_name' => '-test', - 'slup_test_account_explode' => '@' - ]); - if ($user = $this->nmcUserService->userExists($providerName, $uid, true)) { + 'slup_test_account_explode' => '@', + ]; + + $config = $this->config->getSystemValue('nmc_provisioning', $defaults); + $config = is_array($config) ? array_replace($defaults, $config) : $defaults; + + $user = $this->nmcUserService->userExists($providerName, $uid, true); + if ($user) { $this->logger->info("PROV {$uid}: Modify existing"); return $this->deriveExistingAccountState($user, $displayname, $mainEmail, $quota, $claims, $providerName); - } elseif ($create || $config['slup_test_account_check'] && - $this->isTestAccount($displayname, $config['slup_test_account_name'], $config['slup_test_account_explode'])) { + } + + $isTestAccount = (bool)$config['slup_test_account_check'] + && $displayname !== null + && $this->isTestAccount( + $displayname, + (string)$config['slup_test_account_name'], + (string)$config['slup_test_account_explode'] + ); + + if ($create || $isTestAccount) { $this->logger->info("PROV {$uid}: Create"); return $this->deriveNewAccountState($uid, $displayname, $mainEmail, $quota, $claims, $providerName); - } else { - $this->logger->info("PROV {$uid}: No create"); - return array('allowed' => true, 'reason' => 'No create - please login with the user', 'changed' => true); } + + $this->logger->info("PROV {$uid}: No create"); + + return [ + 'allowed' => true, + 'reason' => 'No create - please login with the user', + 'changed' => true, + ]; } - /** - * The flag evaluation behaves different if a user does not exist and has to be created. - * - * In many negative cases, no user account is created at all. - */ - protected function deriveNewAccountState(string $uid, ?string $displayname, ?string $mainEmail, - string $quota, object $claims, $providerName) : array { - if (is_null($displayname)) { + protected function deriveNewAccountState( + string $uid, + ?string $displayname, + ?string $mainEmail, + string $quota, + object $claims, + string $providerName + ): array { + if ($displayname === null) { $this->logger->error("{$uid}: New user without displayName"); - return array('allowed' => false, 'reason' => 'No displayname no new account', 'changed' => false); + + return [ + 'allowed' => false, + 'reason' => 'No displayname no new account', + 'changed' => false, + ]; } if ($this->isLocked($claims)) { - // user is locked due to abuse - $this->logger->info("{$uid}: New user with lock state, no user created"); - return array('allowed' => false, 'reason' => 'Locked no new account', 'changed' => false); + $this->logger->info("{$uid}: New user locked, no user created"); + + return [ + 'allowed' => false, + 'reason' => 'Locked no new account', + 'changed' => false, + ]; } - if (!$this->isBooked($claims)) { - $this->logger->info("{$uid}: New user without MagentaCloud tariff, no user created"); - $withdrawUrl = $this->config->getAppValue('nmcprovisioning', 'userwithdrawurl', - "https://cloud.telekom-dienste.de/tarife"); - return array('allowed' => false, 'reason' => 'No tariff no new account', 'changed' => false, 'redirect' => $withdrawUrl); + $bookingState = $this->getBookingState($claims); + if ($bookingState !== true) { + $this->logger->info( + $bookingState === null + ? "{$uid}: New user without tariff claim, no user created" + : "{$uid}: New user without MagentaCloud tariff, no user created" + ); + + return [ + 'allowed' => false, + 'reason' => $bookingState === null ? 'Missing tariff claim no new account' : 'No tariff no new account', + 'changed' => false, + 'redirect' => $this->config->getAppValue( + 'nmcprovisioning', + 'userwithdrawurl', + 'https://cloud.telekom-dienste.de/tarife' + ), + ]; } $this->nmcUserService->create($providerName, $uid, $displayname, $mainEmail, $quota); + + $changeTime = $this->withdrawDate($claims); + if ($changeTime !== null) { + $this->nmcUserService->recordAccountChangeTime($uid, $changeTime); + } + $this->logger->info("{$uid}: New user created"); - return array('allowed' => true, 'reason' => 'Created', 'changed' => true); + + return [ + 'allowed' => true, + 'reason' => 'Created', + 'changed' => true, + ]; } - /** - * The flag evaluation behaves different if a user does not exist and has to be created. - * - * Many negative cases impact account only on update. - */ - public function deriveExistingAccountState(User|IUser $user, ?string $displayname, ?string $mainEmail, - string $quota, object $claims, $providerName = 'Telekom') : array { - if ($this->isLocked($claims)) { - // user is locked due to abuse - $this->nmcUserService->update($user, $displayname, $mainEmail, $quota, false); - $this->logger->info("{$user->getUID()}: User locked"); - return array('allowed' => false, 'reason' => 'Locked', 'changed' => true); - } - - if ($this->isBooked($claims)) { - // user may has been marked for deletion before re-vitalizing account - $this->nmcUserService->unmarkDeletion($user->getUID()); - $deletionMark = $this->nmcUserService->getDeletionDateTime($user->getUID()); - // check deletion mark and log error in case - if ($deletionMark == null) { - $this->logger->info("{$user->getUID()}: Deletion mark removed."); - } else { - $this->logger->error("{$user->getUID()}: Deletion active after reactivation for " . $deletionMark->format(\DateTimeInterface::ISO8601)); + public function deriveExistingAccountState( + User|IUser $user, + ?string $displayname, + ?string $mainEmail, + string $quota, + object $claims, + string $providerName = 'Telekom' + ): array { + $uid = $user->getUID(); + $bookingState = $this->getBookingState($claims); + $changeTime = $this->withdrawDate($claims); + + if ($bookingState === true) { + if ($changeTime !== null && $this->nmcUserService->isStaleAccountChange($uid, $changeTime)) { + $this->logger->warning("{$uid}: Stale booked event ignored."); + + return [ + 'allowed' => $user->isEnabled(), + 'reason' => 'Stale booked event ignored', + 'changed' => false, + ]; + } + + $this->nmcUserService->unmarkDeletion($uid); + + if ($changeTime !== null) { + $this->nmcUserService->recordAccountChangeTime($uid, $changeTime); + } + + if ($this->isLocked($claims)) { + $this->nmcUserService->update($user, $displayname, $mainEmail, $quota, false); + $this->logger->info("{$uid}: User booked but locked; deletion cancelled."); + + return [ + 'allowed' => false, + 'reason' => 'Locked', + 'changed' => true, + ]; } - // update case - // user is active and gets update - //TODO Check is update required???? $this->nmcUserService->update($user, $displayname, $mainEmail, $quota, true); - return array('allowed' => true, 'reason' => 'Updated', 'changed' => true); - } else { - $withdrawDate = $this->withdrawDate($claims); - $deletionDate = $this->nmcUserService->markDeletion($user->getUID(), $withdrawDate); - $this->logger->info("{$user->getUID()}: Withdrawn at " . $withdrawDate->format(\DateTimeInterface::ISO8601) . - ", deletion=" . $deletionDate->format(\DateTimeInterface::ISO8601)); - // lock and latest update of user data + + return [ + 'allowed' => true, + 'reason' => 'Updated', + 'changed' => true, + ]; + } + + // Locking alone must never schedule deletion. + if ($this->isLocked($claims)) { $this->nmcUserService->update($user, $displayname, $mainEmail, $quota, false); + $this->logger->info("{$uid}: User locked"); - if ($this->isTelekomPreserveProcess($claims)) { - $redirect = $this->config->getAppValue('nmcprovisioning', 'userpreserveurl', - 'https://telekom.example.com/'); - } elseif ($this->isOTTCustomer($claims)) { - $redirect = $this->config->getAppValue('nmcprovisioning', 'userotturl', - 'https://telekom.example.com/'); - } elseif ($this->isAccessCustomer($claims)) { - $redirect = $this->config->getAppValue('nmcprovisioning', 'useraccessurl', - 'https://telekom.example.com/'); - } else { - $redirect = $this->config->getAppValue('nmcprovisioning', 'userwithdrawurl', - 'https://cloud.telekom-dienste.de/tarife'); - } + return [ + 'allowed' => false, + 'reason' => 'Locked', + 'changed' => true, + ]; + } + + // Missing tariff state is not a confirmed withdrawal. + if ($bookingState === null) { + $this->nmcUserService->unmarkDeletion($uid); + $this->nmcUserService->update($user, $displayname, $mainEmail, $quota, false); + + $this->logger->warning("{$uid}: f556 missing. Deletion not scheduled."); + + return $this->withdrawResult('Missing tariff claim - deletion not scheduled', $claims, true); + } + + // Withdrawal needs a valid authoritative timestamp. + if ($changeTime === null) { + $this->nmcUserService->unmarkDeletion($uid); + $this->nmcUserService->update($user, $displayname, $mainEmail, $quota, false); - return array('allowed' => false, 'reason' => 'Withdrawn', 'changed' => true, 'redirect' => $redirect); + $this->logger->error("{$uid}: Withdrawal without valid changeTime. Deletion not scheduled."); + + return $this->withdrawResult('Withdrawn without valid changeTime - deletion not scheduled', $claims, true); + } + + if ($this->nmcUserService->isStaleAccountChange($uid, $changeTime)) { + $this->logger->warning("{$uid}: Stale withdrawal ignored at " . $changeTime->format(\DateTimeInterface::ATOM)); + + return [ + 'allowed' => $user->isEnabled(), + 'reason' => 'Stale withdrawal event ignored', + 'changed' => false, + ]; + } + + try { + $deletionDate = $this->nmcUserService->markDeletion($uid, $changeTime); + } catch (\Throwable $e) { + $this->nmcUserService->unmarkDeletion($uid); + $this->nmcUserService->update($user, $displayname, $mainEmail, $quota, false); + + $this->logger->critical("{$uid}: Failed to schedule deletion safely.", [ + 'exception' => $e, + ]); + + return $this->withdrawResult('Deletion scheduling failed safely', $claims, true); + } + + if ($deletionDate === null) { + $this->logger->warning("{$uid}: Withdrawal lost race with newer state."); + + return [ + 'allowed' => $user->isEnabled(), + 'reason' => 'Stale withdrawal event ignored', + 'changed' => false, + ]; + } + + $this->logger->info( + "{$uid}: Withdrawn at {$changeTime->format(\DateTimeInterface::ATOM)}, deletion={$deletionDate->format(\DateTimeInterface::ATOM)}" + ); + + $this->nmcUserService->update($user, $displayname, $mainEmail, $quota, false); + + return $this->withdrawResult('Withdrawn', $claims, true); + } + + private function withdrawResult(string $reason, object $claims, bool $changed): array { + if ($this->isTelekomPreserveProcess($claims)) { + $redirect = $this->config->getAppValue('nmcprovisioning', 'userpreserveurl', 'https://telekom.example.com/'); + } elseif ($this->isOTTCustomer($claims)) { + $redirect = $this->config->getAppValue('nmcprovisioning', 'userotturl', 'https://telekom.example.com/'); + } elseif ($this->isAccessCustomer($claims)) { + $redirect = $this->config->getAppValue('nmcprovisioning', 'useraccessurl', 'https://telekom.example.com/'); + } else { + $redirect = $this->config->getAppValue( + 'nmcprovisioning', + 'userwithdrawurl', + 'https://cloud.telekom-dienste.de/tarife' + ); } + + return [ + 'allowed' => false, + 'reason' => $reason, + 'changed' => $changed, + 'redirect' => $redirect, + ]; } } diff --git a/lib/User/NmcUserService.php b/lib/User/NmcUserService.php index 85e9037..859b032 100644 --- a/lib/User/NmcUserService.php +++ b/lib/User/NmcUserService.php @@ -21,6 +21,14 @@ // classes from user_oidc app class NmcUserService { + private const KEY_DELETION = 'deletion'; + private const KEY_WITHDRAWAL = 'withdrawal'; + private const KEY_DELETION_MARKED_AT = 'deletion_marked_at'; + private const KEY_LAST_ACCOUNT_CHANGE = 'last_account_change'; + + private const DEFAULT_RETENTION = 'P60D'; + private const DEFAULT_SAFETY_DELAY = 'P1D'; + /** @var IUserManager */ private $userManager; @@ -152,50 +160,169 @@ public function getMigrationFlag($userId) { } /** - * Set deletion timestamp for delayed deletion - * It is computed as withdrawDate + userretention (atm withdrawDate + 60D) - * `userretention` appvalue is taken as the retention period if set, - * given as ISO8601/PHP DateInterval formatted string, with a default of "P60D" - * It can be set with: - * `sudo -u www-data php /var/www/nextcloud/occ config:app:set nmcprovisioning userretention --value P60DT1H` - * @return the computed deletion date + * Return the newest account-state change timestamp accepted for this user. + * + * This timestamp is deliberately kept when a deletion is cancelled. It is + * used to reject delayed/out-of-order withdrawal events later on. + */ + public function getLastAccountChangeTime(string $userId): ?\DateTimeImmutable { + return $this->getUserTimestamp($userId, self::KEY_LAST_ACCOUNT_CHANGE); + } + + /** + * Record an account-state change without allowing an older timestamp to + * replace a newer one. + */ + public function recordAccountChangeTime(string $userId, \DateTimeInterface $changeTime): bool { + $incomingTimestamp = $changeTime->getTimestamp(); + $current = $this->getLastAccountChangeTime($userId); + + if ($current !== null && $incomingTimestamp < $current->getTimestamp()) { + return false; + } + + if ($current === null || $incomingTimestamp > $current->getTimestamp()) { + $this->config->setUserValue($userId, Application::APP_ID, self::KEY_LAST_ACCOUNT_CHANGE, $incomingTimestamp); + } + + return true; + } + + public function isStaleAccountChange(string $userId, \DateTimeInterface $changeTime): bool { + $current = $this->getLastAccountChangeTime($userId); + + return $current !== null && $changeTime->getTimestamp() < $current->getTimestamp(); + } + + /** + * Mark a user for delayed deletion. + * + * The effective deletion date is the later of: + * - authoritative withdrawal time + configured retention period + * - first local observation of this withdrawal + safety delay + * + * The second condition prevents an old/replayed event from becoming + * immediately destructive when it reaches this system for the first time. + * + * @return \DateTimeImmutable|null Null if the withdrawal event is stale. */ - public function markDeletion(string $userId, \DateTime $withdrawTime): \DateTime { - $deletionDate = clone $withdrawTime; - $retention = new \DateInterval($this->config->getAppValue('nmcprovisioning', 'userretention', "P60D")); - $deletionDate->add($retention); + public function markDeletion(string $userId, \DateTimeInterface $withdrawTime): ?\DateTimeImmutable { + if ($this->isStaleAccountChange($userId, $withdrawTime)) { + $this->logger->warning('Refusing stale withdrawal event', [ + 'userId' => $userId, + 'withdrawTime' => $withdrawTime->format(\DateTimeInterface::ATOM), + 'lastAccountChange' => $this->getLastAccountChangeTime($userId)?->format(\DateTimeInterface::ATOM), + ]); + return null; + } + + $withdrawal = \DateTimeImmutable::createFromInterface($withdrawTime); + $existingWithdrawal = $this->getUserTimestamp($userId, self::KEY_WITHDRAWAL); + $existingMarkedAt = $this->getUserTimestamp($userId, self::KEY_DELETION_MARKED_AT); + + /* + * Repeated delivery of the same event must not keep moving the local + * safety window. For a genuinely newer withdrawal event, start a new + * observation window. + */ + if ($existingWithdrawal !== null && $existingMarkedAt !== null && $existingWithdrawal->getTimestamp() === $withdrawal->getTimestamp()) { + $markedAt = $existingMarkedAt; + } else { + $markedAt = new \DateTimeImmutable(); + } + + $retention = $this->getConfiguredInterval('userretention', self::DEFAULT_RETENTION); + $safetyDelay = $this->getConfiguredInterval('userdeletionsafetydelay', self::DEFAULT_SAFETY_DELAY); + + $retentionDate = $withdrawal->add($retention); + $safetyDate = $markedAt->add($safetyDelay); + $deletionDate = $retentionDate > $safetyDate ? $retentionDate : $safetyDate; + + if (!$this->recordAccountChangeTime($userId, $withdrawal)) { + $this->logger->warning('Withdrawal became stale before it could be stored', [ + 'userId' => $userId, + 'withdrawTime' => $withdrawal->format(\DateTimeInterface::ATOM), + ]); + return null; + } $this->logger->info('Marking user for delayed deletion', [ 'userId' => $userId, - 'withdrawTime' => $withdrawTime->format(\DateTimeInterface::ATOM), + 'withdrawTime' => $withdrawal->format(\DateTimeInterface::ATOM), + 'markedAt' => $markedAt->format(\DateTimeInterface::ATOM), 'deletionDate' => $deletionDate->format(\DateTimeInterface::ATOM), - 'retention' => $this->config->getAppValue('nmcprovisioning', 'userretention', "P60D"), + 'retention' => $this->config->getAppValue('nmcprovisioning', 'userretention', self::DEFAULT_RETENTION), + 'safetyDelay' => $this->config->getAppValue('nmcprovisioning', 'userdeletionsafetydelay', self::DEFAULT_SAFETY_DELAY), ]); - $this->config->setUserValue($userId, Application::APP_ID, 'deletion', $deletionDate->getTimestamp()); + /* + * Write supporting metadata first and the actual deletion marker last. + * A partially written state therefore cannot become eligible for the + * deletion query. + */ + $this->config->setUserValue($userId, Application::APP_ID, self::KEY_WITHDRAWAL, $withdrawal->getTimestamp()); + $this->config->setUserValue($userId, Application::APP_ID, self::KEY_DELETION_MARKED_AT, $markedAt->getTimestamp()); + $this->config->setUserValue($userId, Application::APP_ID, self::KEY_DELETION, $deletionDate->getTimestamp()); + + /* + * Narrow the race window with a concurrent reactivation/newer event. + * If a newer state appeared while this method was writing, disarm the + * deletion immediately. The deletion job performs the same check again. + */ + if ($this->isStaleAccountChange($userId, $withdrawal)) { + $this->logger->warning('Newer account state detected while marking deletion', [ + 'userId' => $userId, + ]); + $this->unmarkDeletion($userId); + return null; + } return $deletionDate; } /** - * Set withdraw timestamp for delayed deletion + * Cancel a pending deletion. + * + * The actual deletion marker is removed first. This makes an interrupted + * cleanup fail safe: the background job no longer sees the user as a + * deletion candidate. */ - public function unmarkDeletion(string $userId) { - $this->config->deleteUserValue($userId, Application::APP_ID, 'deletion'); + public function unmarkDeletion(string $userId): void { + $this->config->deleteUserValue($userId, Application::APP_ID, self::KEY_DELETION); + $this->config->deleteUserValue($userId, Application::APP_ID, self::KEY_WITHDRAWAL); + $this->config->deleteUserValue($userId, Application::APP_ID, self::KEY_DELETION_MARKED_AT); } /** - * Get planned deletion date, or null if none. + * Get planned deletion date, or null if none. */ - public function getDeletionDateTime(string $userId): ?\DateTime { - $delTs = $this->config->getUserValue($userId, Application::APP_ID, 'deletion', null); - if ($delTs != null) { - $delDate = new \DateTime(); - $delDate->setTimestamp($delTs); - return $delDate; - } else { + public function getDeletionDateTime(string $userId): ?\DateTimeImmutable { + return $this->getUserTimestamp($userId, self::KEY_DELETION); + } + + private function getUserTimestamp(string $userId, string $key): ?\DateTimeImmutable { + $value = $this->config->getUserValue($userId, Application::APP_ID, $key, null); + + if ($value === null || $value === '' || !is_numeric($value)) { return null; } + + $timestamp = (int)$value; + if ($timestamp <= 0) { + return null; + } + + return (new \DateTimeImmutable())->setTimestamp($timestamp); + } + + private function getConfiguredInterval(string $key, string $default): \DateInterval { + $value = $this->config->getAppValue('nmcprovisioning', $key, $default); + + try { + return new \DateInterval($value); + } catch (\Throwable $e) { + throw new \RuntimeException("Invalid nmcprovisioning configuration {$key}={$value}", 0, $e); + } } /** @@ -314,8 +441,7 @@ protected function updateUserSettings(IUser $user, string|null $email, string|nu } //Its enough to check the string value from quota, the group mapping is matching with exact quota string - if (!is_null($quota) && - $quota !== $user->getQuota()) { + if (!is_null($quota) && $quota !== $user->getQuota()) { $this->logger->debug("PROV quota {$user->getUID()} old: {$user->getQuota()} new: {$quota}"); $user->setQuota($quota); $this->autoGroupMatch($user, $quota); diff --git a/lib/User/UserAccountDeletionJob.php b/lib/User/UserAccountDeletionJob.php index 81eafd4..ee90020 100644 --- a/lib/User/UserAccountDeletionJob.php +++ b/lib/User/UserAccountDeletionJob.php @@ -11,6 +11,11 @@ class UserAccountDeletionJob extends TimedJob { public const CIRCUIT_BOOT_DELAY = 300; + private const MAX_EXECUTION_TIME = 10800; + private const SLOW_DELETION_WARNING = 1800; + private const RETRY_DELAY = 3600; + private const BATCH_SIZE = 10; + /** @var LoggerInterface */ private $logger; @@ -20,13 +25,12 @@ class UserAccountDeletionJob extends TimedJob { /** @var IUserManager */ private $userManager; - public function __construct( - ITimeFactory $timeFactory, - LoggerInterface $logger, - UserQueries $userQueries, - IUserManager $userManager - ) { + /** @var ITimeFactory */ + private $timeFactory; + + public function __construct(ITimeFactory $timeFactory, LoggerInterface $logger, UserQueries $userQueries, IUserManager $userManager) { parent::__construct($timeFactory); + $this->timeFactory = $timeFactory; $this->logger = $logger; $this->userQueries = $userQueries; $this->userManager = $userManager; @@ -36,20 +40,16 @@ public function getInterval(): int { return $this->interval; } - public function run($arguments) { + public function run($arguments): void { $this->logger->info('User account deletion job started'); - $startTime = time(); - $maxExecutionTime = 10800; // 3 hours - $maxDeletionTimePerUser = 1800; // 30 minutes - - $limit = 10; + $startTime = $this->timeFactory->getTime(); - while (time() - $startTime < $maxExecutionTime) { - $refTime = new \DateTime(); - $expiredUids = $this->userQueries->findDeletions($refTime, $limit); + while ($this->timeFactory->getTime() - $startTime < self::MAX_EXECUTION_TIME) { + $refTime = $this->now(); + $expiredUids = $this->userQueries->findDeletions($refTime, self::BATCH_SIZE); - if (empty($expiredUids)) { + if ($expiredUids === []) { $this->logger->info('No more users to delete, exiting job.'); break; } @@ -57,59 +57,186 @@ public function run($arguments) { $this->logger->info(\count($expiredUids) . ' users found for deletion in this batch.'); foreach ($expiredUids as $uid) { - if (time() - $startTime > $maxExecutionTime) { + if ($this->timeFactory->getTime() - $startTime >= self::MAX_EXECUTION_TIME) { $this->logger->info('User account deletion job stopped after 3 hours.'); return; } - try { - $deletionDate = $this->userQueries->getDeletionDateTime($uid); + $this->processUser($uid); + } + } - if ($deletionDate === null) { - $this->logger->warning("Skipping $uid, deletion entry no longer exists."); - continue; - } + $this->logger->info('User account deletion job ended'); + } - $now = new \DateTime(); - if ($deletionDate > $now) { - $this->logger->warning( - "Skipping $uid, deletion not due yet: " . $deletionDate->format(\DateTimeInterface::ATOM) - ); - continue; - } + private function processUser(string $uid): void { + try { + $state = $this->userQueries->getDeletionState($uid); - $user = $this->userManager->get($uid); - if (!$user) { - $this->logger->warning("User $uid not found, removing user preferences and cleaning up."); - $this->userQueries->deleteUserPreferenceById($uid); - continue; - } + if ($state === null) { + $this->logger->warning("Skipping {$uid}, deletion entry no longer exists."); + return; + } - $this->logger->info("Deleting $uid, deletion due since " . $deletionDate->format(\DateTimeInterface::ATOM)); + if ($state['deletion'] > $this->now()) { + $this->logger->warning("Skipping {$uid}, deletion not due yet: " . $state['deletion']->format(\DateTimeInterface::ATOM)); + return; + } - $startDeletionTime = time(); + /* + * Old/partial deletion markers are deliberately not trusted. + * Supporting metadata is required before irreversible deletion. + */ + if ($state['withdrawal'] === null || $state['markedAt'] === null) { + $this->logger->critical("Skipping {$uid}: incomplete deletion metadata. " . 'Deletion marker will be disarmed.'); + $this->userQueries->deleteDeletionPreferencesById($uid); + return; + } - $user->delete(); + if ($state['lastAccountChange'] !== null && $state['lastAccountChange']->getTimestamp() > $state['withdrawal']->getTimestamp()) { + $this->logger->critical("Skipping {$uid}: newer account state exists. " . 'Deletion marker will be disarmed.'); + $this->userQueries->deleteDeletionPreferencesById($uid); + return; + } - if (time() - $startDeletionTime > $maxDeletionTimePerUser) { - $this->logger->warning("User $uid deletion took longer than 30 minutes, skipping."); - continue; - } + $user = $this->userManager->get($uid); - $this->userQueries->deleteUserPreferenceById($uid); + if ($user === null) { + $this->logger->warning("User {$uid} not found, removing orphaned preferences."); + $this->userQueries->deleteUserPreferenceById($uid); + return; + } - $this->logger->info("User $uid deleted successfully and preferences cleaned up."); - } catch (\Throwable $e) { - $this->logger->error("Deletion failed for $uid: " . $e->getMessage(), [ - 'exception' => $e, - 'app' => 'nmcprovisioning', - ]); + /* + * Reactivation is authoritative in the safe direction. An enabled + * user must never be deleted by this background job. + */ + if ($user->isEnabled()) { + $this->logger->critical("Skipping {$uid}: user is enabled while marked for deletion. " . 'Deletion marker will be disarmed.'); + $this->userQueries->deleteDeletionPreferencesById($uid); + return; + } + + $initialFingerprint = $this->fingerprint($state); + + /* + * Re-read deletion metadata after resolving the user and immediately + * before delete(). This preserves the current recheck behaviour and + * extends it to all deletion metadata. + */ + $currentState = $this->userQueries->getDeletionState($uid); - continue; + if ($currentState === null) { + $this->logger->warning("Skipping {$uid}: deletion was cancelled before delete()."); + return; + } + + if (!hash_equals($initialFingerprint, $this->fingerprint($currentState))) { + $this->logger->warning("Skipping {$uid}: deletion state changed before delete()."); + return; + } + + if ( + $currentState['deletion'] > $this->now() + || $currentState['withdrawal'] === null + || $currentState['markedAt'] === null + || ($currentState['lastAccountChange'] !== null && $currentState['lastAccountChange']->getTimestamp() > $currentState['withdrawal']->getTimestamp()) + ) { + $this->logger->warning("Skipping {$uid}: final deletion validation failed."); + return; + } + + /* + * Re-fetch the user too. A reactivation may have happened while the + * deletion state was being checked. + */ + $user = $this->userManager->get($uid); + + if ($user === null) { + $this->logger->warning("User {$uid} disappeared before delete(), cleaning preferences."); + $this->userQueries->deleteUserPreferenceById($uid); + return; + } + + if ($user->isEnabled()) { + $this->logger->critical("Skipping {$uid}: user was re-enabled before delete(). " . 'Deletion marker will be disarmed.'); + $this->userQueries->deleteDeletionPreferencesById($uid); + return; + } + + /* + * One final metadata read after the final user-state read also protects + * booked-but-locked reactivations: those may stay disabled while still + * cancelling the deletion marker. + */ + $finalState = $this->userQueries->getDeletionState($uid); + + if ($finalState === null || !hash_equals($initialFingerprint, $this->fingerprint($finalState))) { + $this->logger->warning("Skipping {$uid}: deletion state changed during final validation."); + return; + } + + $this->logger->info("Deleting {$uid}, deletion due since " . $currentState['deletion']->format(\DateTimeInterface::ATOM)); + + $startDeletionTime = $this->timeFactory->getTime(); + + $user->delete(); + + $duration = $this->timeFactory->getTime() - $startDeletionTime; + + /* + * The old code said "skipping" here even though delete() had already + * happened, which also skipped preference cleanup. A slow deletion + * is now only a warning; cleanup still runs. + */ + if ($duration > self::SLOW_DELETION_WARNING) { + $this->logger->warning("User {$uid} deletion took longer than 30 minutes " . "({$duration} seconds)."); + } + + $this->userQueries->deleteUserPreferenceById($uid); + + $this->logger->info("User {$uid} deleted successfully and preferences cleaned up."); + } catch (\Throwable $e) { + $this->logger->error( + "Deletion failed for {$uid}: " . $e->getMessage(), + [ + 'exception' => $e, + 'app' => 'nmcprovisioning', + ] + ); + + /* + * Avoid selecting the same broken account over and over during the + * same three-hour run. If it still has a deletion marker, retry it + * later. + */ + try { + $currentState = $this->userQueries->getDeletionState($uid); + if ($currentState !== null) { + $this->userQueries->postponeDeletion($uid, $this->now()->modify('+' . self::RETRY_DELAY . ' seconds')); } + } catch (\Throwable $retryException) { + $this->logger->error( + "Failed to postpone deletion for {$uid}: " . $retryException->getMessage(), + [ + 'exception' => $retryException, + 'app' => 'nmcprovisioning', + ] + ); } } + } - $this->logger->info('User account deletion job ended'); + private function now(): \DateTimeImmutable { + return (new \DateTimeImmutable())->setTimestamp($this->timeFactory->getTime()); + } + + private function fingerprint(array $state): string { + return implode(':', [ + (string)$state['deletion']->getTimestamp(), + $state['withdrawal'] instanceof \DateTimeInterface ? (string)$state['withdrawal']->getTimestamp() : '-', + $state['markedAt'] instanceof \DateTimeInterface ? (string)$state['markedAt']->getTimestamp() : '-', + $state['lastAccountChange'] instanceof \DateTimeInterface ? (string)$state['lastAccountChange']->getTimestamp() : '-', + ]); } } diff --git a/tests/unit/UserAccounctDeletionJobTest.php b/tests/unit/UserAccounctDeletionJobTest.php index 8e78cbb..4ef7658 100644 --- a/tests/unit/UserAccounctDeletionJobTest.php +++ b/tests/unit/UserAccounctDeletionJobTest.php @@ -14,72 +14,185 @@ use Psr\Log\LoggerInterface; class UserAccountDeletionJobTest extends TestCase { + private const UID = '120042010000000004200001'; + + private $app; + private $timeFactory; + private $userQueries; + private $userManager; + private $job; + public function setUp(): void { parent::setUp(); + $this->app = new \OCP\AppFramework\App(Application::APP_ID); + $this->timeFactory = $this->createMock(ITimeFactory::class); + $this->timeFactory->method('getTime')->willReturn(2_000_000_000); + $this->userQueries = $this->createMock(UserQueries::class); $this->userManager = $this->getMockForAbstractClass(IUserManager::class); - $this->job = new UserAccountDeletionJob($this->app->getContainer()->get(ITimeFactory::class), - $this->app->getContainer()->get(LoggerInterface::class), - $this->userQueries, - $this->userManager); + + $this->job = new UserAccountDeletionJob($this->timeFactory, $this->app->getContainer()->get(LoggerInterface::class), $this->userQueries, $this->userManager); } - public function testJobRunNone() { + public function testJobRunNone(): void { $this->userQueries->expects($this->once()) - ->method("findDeletions") - ->willReturn([]); // Keine Benutzer zum Löschen - - // Mock für den Benutzer, der nie gelöscht wird + ->method('findDeletions') + ->willReturn([]); + + $this->userManager->expects($this->never()) + ->method('get'); + + $this->job->run(null); + } + + public function testValidDisabledUserIsDeleted(): void { + $state = $this->validState(); + + $this->userQueries->expects($this->exactly(2)) + ->method('findDeletions') + ->willReturnOnConsecutiveCalls([self::UID], []); + + $this->userQueries->expects($this->exactly(3)) + ->method('getDeletionState') + ->with(self::UID) + ->willReturn($state); + $user = $this->getMockForAbstractClass(IUser::class); - $user->expects($this->never())->method("delete"); // delete wird niemals aufgerufen - $this->userManager->expects($this->never())->method("get"); // get wird auch nie aufgerufen - + $user->method('isEnabled')->willReturn(false); + $user->expects($this->once())->method('delete'); + + $this->userManager->expects($this->exactly(2)) + ->method('get') + ->with(self::UID) + ->willReturn($user); + + $this->userQueries->expects($this->once()) + ->method('deleteUserPreferenceById') + ->with(self::UID); + $this->job->run(null); } - public function testJobRunMultiple() { - // Simuliere mehrere Aufrufe von findDeletions, um Benutzer in verschiedenen Batches zu finden - $this->userQueries->expects($this->exactly(3)) // findDeletions wird dreimal aufgerufen - ->method("findDeletions") - ->willReturnOnConsecutiveCalls( - ['120042010000000004200001', '120042010000000004200002'], // Erstes Batch - ['120042010000000004200003'], // Zweites Batch - [] // Drittens Batch, keine Benutzer mehr zu löschen - ); - - // Mock des Benutzers, der gelöscht werden soll + public function testEnabledUserIsNeverDeleted(): void { + $this->userQueries->expects($this->exactly(2)) + ->method('findDeletions') + ->willReturnOnConsecutiveCalls([self::UID], []); + + $this->userQueries->expects($this->once()) + ->method('getDeletionState') + ->willReturn($this->validState()); + $user = $this->getMockForAbstractClass(IUser::class); - $user->expects($this->exactly(3))->method("delete"); // delete wird für jeden Benutzer genau einmal aufgerufen - $this->userManager->expects($this->exactly(3)) // get wird für jeden Benutzer aufgerufen - ->method("get") - ->withConsecutive( - [$this->equalTo('120042010000000004200001')], - [$this->equalTo('120042010000000004200002')], - [$this->equalTo('120042010000000004200003')] - ) + $user->method('isEnabled')->willReturn(true); + $user->expects($this->never())->method('delete'); + + $this->userManager->expects($this->once()) + ->method('get') ->willReturn($user); - + + $this->userQueries->expects($this->once()) + ->method('deleteDeletionPreferencesById') + ->with(self::UID); + $this->job->run(null); } - public function testJobRunOne() { - // Simuliere findDeletions mit nur einem Benutzer + public function testLegacyDeletionMarkerWithoutMetadataIsDisarmed(): void { + $state = $this->validState(); + $state['withdrawal'] = null; + $state['markedAt'] = null; + $this->userQueries->expects($this->exactly(2)) - ->method("findDeletions") - ->willReturnOnConsecutiveCalls( - ['120042010000000004200001'], // Erstes Batch - [] // Zweites Batch, keine Benutzer mehr zu löschen - ); - - // Mock des Benutzers, der gelöscht werden soll + ->method('findDeletions') + ->willReturnOnConsecutiveCalls([self::UID], []); + + $this->userQueries->expects($this->once()) + ->method('getDeletionState') + ->willReturn($state); + + $this->userManager->expects($this->never()) + ->method('get'); + + $this->userQueries->expects($this->once()) + ->method('deleteDeletionPreferencesById') + ->with(self::UID); + + $this->job->run(null); + } + + public function testNewerAccountStateDisarmsDeletion(): void { + $state = $this->validState(); + $state['lastAccountChange'] = new \DateTimeImmutable('2033-05-18T02:00:00+00:00'); + + $this->userQueries->expects($this->exactly(2)) + ->method('findDeletions') + ->willReturnOnConsecutiveCalls([self::UID], []); + + $this->userQueries->expects($this->once()) + ->method('getDeletionState') + ->willReturn($state); + + $this->userManager->expects($this->never()) + ->method('get'); + + $this->userQueries->expects($this->once()) + ->method('deleteDeletionPreferencesById') + ->with(self::UID); + + $this->job->run(null); + } + + public function testChangedDeletionStatePreventsDelete(): void { + $first = $this->validState(); + $second = $this->validState(); + $second['deletion'] = new \DateTimeImmutable('2033-05-18T01:00:01+00:00'); + + $this->userQueries->expects($this->exactly(2)) + ->method('findDeletions') + ->willReturnOnConsecutiveCalls([self::UID], []); + + $this->userQueries->expects($this->exactly(2)) + ->method('getDeletionState') + ->willReturnOnConsecutiveCalls($first, $second); + $user = $this->getMockForAbstractClass(IUser::class); - $user->expects($this->once())->method("delete"); // delete wird genau einmal aufgerufen - $this->userManager->expects($this->once()) // get wird genau einmal aufgerufen - ->method("get") - ->with($this->equalTo('120042010000000004200001')) + $user->method('isEnabled')->willReturn(false); + $user->expects($this->never())->method('delete'); + + $this->userManager->expects($this->once()) + ->method('get') ->willReturn($user); - + + $this->job->run(null); + } + + public function testMissingUserCleansOrphanedPreferences(): void { + $this->userQueries->expects($this->exactly(2)) + ->method('findDeletions') + ->willReturnOnConsecutiveCalls([self::UID], []); + + $this->userQueries->expects($this->once()) + ->method('getDeletionState') + ->willReturn($this->validState()); + + $this->userManager->expects($this->once()) + ->method('get') + ->willReturn(null); + + $this->userQueries->expects($this->once()) + ->method('deleteUserPreferenceById') + ->with(self::UID); + $this->job->run(null); } + + private function validState(): array { + return [ + 'deletion' => new \DateTimeImmutable('2033-05-18T01:00:00+00:00'), + 'withdrawal' => new \DateTimeImmutable('2033-03-19T01:00:00+00:00'), + 'markedAt' => new \DateTimeImmutable('2033-03-19T01:00:00+00:00'), + 'lastAccountChange' => new \DateTimeImmutable('2033-03-19T01:00:00+00:00'), + ]; + } } diff --git a/tests/unit/UserAccountChangeListenerTest.php b/tests/unit/UserAccountChangeListenerTest.php index cbc8c20..844927d 100644 --- a/tests/unit/UserAccountChangeListenerTest.php +++ b/tests/unit/UserAccountChangeListenerTest.php @@ -14,373 +14,313 @@ use OCP\Accounts\IAccountManager; use OCP\IConfig; use OCP\IGroupManager; +use OCP\IUser; use OCP\IUserManager; use PHPUnit\Framework\TestCase; use Psr\Log\LoggerInterface; class UserAccountChangeListenerTest extends TestCase { + private const UID = '12004901000000000XXXXXXX'; + + private $app; + private $config; + private $logger; + private $userManager; + private $oidcProviderMapper; + private $userService; + private $accountRules; + private $listener; + public function setUp(): void { parent::setUp(); + $this->app = new \OCP\AppFramework\App(Application::APP_ID); $this->config = $this->getMockForAbstractClass(IConfig::class); $this->logger = $this->app->getContainer()->get(LoggerInterface::class); $this->userManager = $this->getMockForAbstractClass(IUserManager::class); - $this->oidcProviderMapper = $this->app->getContainer()->get(ProviderMapper::class); + $this->oidcProviderMapper = $this->app + ->getContainer() + ->get(ProviderMapper::class); + $this->userService = $this->getMockBuilder(NmcUserService::class) - ->setConstructorArgs([ $this->app->getContainer()->get(IUserManager::class), - $this->app->getContainer()->get(IAccountManager::class), - $this->logger, - $this->config, - $this->app->getContainer()->get(UserMapper::class), - $this->app->getContainer()->get(ProviderMapper::class), - $this->app->getContainer()->get(IGroupManager::class)]) - ->onlyMethods(['create', 'update', 'userExists']) - ->getMock(); - $this->accountRules = new UserAccountRules($this->config, - $this->logger, - $this->userService, - $this->userManager, - $this->oidcProviderMapper); + ->setConstructorArgs([ + $this->app->getContainer()->get(IUserManager::class), + $this->app->getContainer()->get(IAccountManager::class), + $this->logger, + $this->config, + $this->app->getContainer()->get(UserMapper::class), + $this->app->getContainer()->get(ProviderMapper::class), + $this->app->getContainer()->get(IGroupManager::class), + ]) + ->onlyMethods([ + 'create', + 'update', + 'userExists', + 'markDeletion', + 'unmarkDeletion', + 'isStaleAccountChange', + 'recordAccountChangeTime', + ]) + ->getMock(); + + $this->accountRules = new UserAccountRules($this->config, $this->logger, $this->userService, $this->userManager, $this->oidcProviderMapper); $this->listener = new UserAccountChangeListener($this->logger, $this->accountRules); - $this->config->expects($this->any()) - ->method("getAppValue") - ->with($this->equalTo('nmcprovisioning'), - $this->logicalOr($this->equalTo('userretention'), - $this->equalTo('useraccessurl'), - $this->equalTo('userwithdrawurl'), - $this->equalTo('userpreserveurl'), - $this->equalTo('userotturl'))) - ->willReturn($this->returnCallback(function ($app, $key) { - $values = [ - 'userwithdrawurl' => "https://cloud.telekom-dienste.de", - 'userpreserveurl' => "https://telekom.example.com/", - 'useraccessurl' => "https://cloud.telekom-dienste.de/tarife", - 'userotturl' => "https://cloud.telekom-dienste.de/ott", - 'userretention' => "P60D", - - ]; - - return $values[$key]; - })); + $this->config->method('getSystemValue') + ->willReturn([ + 'slup_test_account_check' => true, + 'slup_test_account_name' => '-test', + 'slup_test_account_explode' => '@', + ]); + + $this->config->method('getAppValue') + ->willReturnCallback( + static function ($app, $key, $default = '') { + $values = [ + 'userwithdrawurl' => 'https://cloud.telekom-dienste.de', + 'userpreserveurl' => 'https://telekom.example.com/', + 'useraccessurl' => 'https://cloud.telekom-dienste.de/tarife', + 'userotturl' => 'https://cloud.telekom-dienste.de/ott', + ]; + + return $values[$key] ?? $default; + } + ); } - public function testWithdrawNonExisting() { - $oidcClaims = json_decode(<<userService->expects($this->once()) - ->method('userExists') - ->with($this->equalTo('Telekom'), $this->equalTo("12004901000000000XXXXXXX")) - ->willReturn(false); - - $event = new UserAccountChangeEvent("12004901000000000XXXXXXX", "jonny.gyros", - "jonny.gyros@ver.sul.t-online.de", "3GB", $oidcClaims); + ->method('userExists') + ->willReturn(null); + + $event = $this->event( + $this->claims([ + 'urn:telekom.com:f556' => '0', + ]) + ); + $this->listener->handle($event); + $this->assertFalse($event->getResult()->isAccessAllowed()); - $this->assertEquals('No tariff no new account', $event->getResult()->getReason()); - $this->assertNotNull($event->getResult()->getRedirectUrl()); - $this->assertEquals("https://cloud.telekom-dienste.de", $event->getResult()->getRedirectUrl()); + $this->assertSame('No tariff no new account', $event->getResult()->getReason()); } - public function testWithdrawNoUsta() { - $oidcClaims = json_decode(<<existingUser(false); + + $this->userService->method('userExists') + ->willReturn($user); + $this->userService->method('isStaleAccountChange') + ->willReturn(false); + + $expectedDeletion = new \DateTimeImmutable('2030-03-02T00:00:00+00:00'); $this->userService->expects($this->once()) - ->method('userExists') - ->with($this->equalTo('Telekom'), $this->equalTo("12004901000000000XXXXXXX")) - ->willReturn(true); - $this->config->expects($this->once()) - ->method("setUserValue") - ->with($this->equalTo('12004901000000000XXXXXXX'), Application::APP_ID, $this->equalTo("deletion")); + ->method('markDeletion') + ->willReturn($expectedDeletion); + $this->userService->expects($this->once()) - ->method('update') - ->with($this->equalTo('Telekom'), $this->equalTo("12004901000000000XXXXXXX"), - $this->equalTo("jonny.gyros"), $this->equalTo("jonny.gyros@ver.sul.t-online.de"), - $this->isNull(), $this->equalTo("3 GB"), $this->isFalse(), $this->isFalse()) - ->willReturn(false); + ->method('update') + ->with($user, 'jonny.gyros', 'jonny.gyros@ver.sul.t-online.de', '3 GB', false); - $event = new UserAccountChangeEvent("12004901000000000XXXXXXX", "jonny.gyros", - "jonny.gyros@ver.sul.t-online.de", "3 GB", $oidcClaims); + $event = $this->event( + $this->claims([ + 'urn:telekom.com:f556' => '0', + 'changeTime' => '2030-01-01T00:00:00Z', + ]) + ); $this->listener->handle($event); + $this->assertFalse($event->getResult()->isAccessAllowed()); - $this->assertEquals('Withdrawn', $event->getResult()->getReason()); - $this->assertNotNull($event->getResult()->getRedirectUrl()); - $this->assertEquals("https://cloud.telekom-dienste.de", $event->getResult()->getRedirectUrl()); + $this->assertSame('Withdrawn', $event->getResult()->getReason()); } - public function testPreserveOtherUsta() { - $oidcClaims = json_decode(<<existingUser(false); + + $this->userService->method('userExists') + ->willReturn($user); + + $this->userService->expects($this->never()) + ->method('markDeletion'); $this->userService->expects($this->once()) - ->method('userExists') - ->with($this->equalTo('Telekom'), $this->equalTo("12004901000000000XXXXXXX")) - ->willReturn(true); - $this->config->expects($this->once()) - ->method("setUserValue") - ->with($this->equalTo('12004901000000000XXXXXXX'), Application::APP_ID, $this->equalTo("deletion")); + ->method('unmarkDeletion') + ->with(self::UID); + $this->userService->expects($this->once()) - ->method('update') - ->with($this->equalTo('Telekom'), $this->equalTo("12004901000000000XXXXXXX"), - $this->equalTo("jonny.gyros"), $this->equalTo("jonny.gyros@ver.sul.t-online.de"), - $this->isNull(), $this->equalTo("3 GB"), $this->isFalse(), $this->isFalse()) - ->willReturn(false); + ->method('update') + ->with($user, 'jonny.gyros', 'jonny.gyros@ver.sul.t-online.de', '3 GB', false); - $event = new UserAccountChangeEvent("12004901000000000XXXXXXX", "jonny.gyros", - "jonny.gyros@ver.sul.t-online.de", "3 GB", $oidcClaims); + $event = $this->event( + $this->claims([ + 'urn:telekom.com:f556' => '0', + 'auth_time' => 1637683330, + ]) + ); $this->listener->handle($event); - $this->assertFalse($event->getResult()->isAccessAllowed()); - $this->assertEquals('Withdrawn', $event->getResult()->getReason()); - $this->assertNotNull($event->getResult()->getRedirectUrl()); - $this->assertEquals('https://telekom.example.com/', $event->getResult()->getRedirectUrl()); + + $this->assertSame('Withdrawn without valid changeTime - deletion not scheduled', $event->getResult()->getReason()); } + public function testMissingBookingClaimNeverSchedulesDeletion(): void { + $user = $this->existingUser(false); - public function testWithdrawPreserve() { - $oidcClaims = json_decode(<<userService->expects($this->once()) - ->method('userExists') - ->with($this->equalTo('Telekom'), $this->equalTo("12004901000000000XXXXXXX")) - ->willReturn(true); - $this->config->expects($this->once()) - ->method("setUserValue") - ->with($this->equalTo('12004901000000000XXXXXXX'), Application::APP_ID, $this->equalTo("deletion")); - $this->userService->expects($this->once()) - ->method('update') - ->with($this->equalTo('Telekom'), $this->equalTo("12004901000000000XXXXXXX"), - $this->equalTo("jonny.gyros"), $this->equalTo("jonny.gyros@ver.sul.t-online.de"), - $this->isNull(), $this->equalTo("3 GB"), $this->isFalse(), $this->isFalse()) - ->willReturn(false); + $this->userService->method('userExists') + ->willReturn($user); - $event = new UserAccountChangeEvent("12004901000000000XXXXXXX", "jonny.gyros", - "jonny.gyros@ver.sul.t-online.de", "3 GB", $oidcClaims); + $this->userService->expects($this->never()) + ->method('markDeletion'); - $this->listener->handle($event); - $this->assertFalse($event->getResult()->isAccessAllowed()); - $this->assertEquals('Withdrawn', $event->getResult()->getReason()); - $this->assertNotNull($event->getResult()->getRedirectUrl()); - $this->assertEquals('https://telekom.example.com/', $event->getResult()->getRedirectUrl()); - } - - public function testWithdrawOTT() { - $oidcClaims = json_decode(<<userService->expects($this->once()) - ->method('userExists') - ->with($this->equalTo('Telekom'), $this->equalTo("12004901000000000XXXXXXX")) - ->willReturn(true); - $this->config->expects($this->once()) - ->method("setUserValue") - ->with($this->equalTo('12004901000000000XXXXXXX'), Application::APP_ID, $this->equalTo("deletion")); $this->userService->expects($this->once()) - ->method('update') - ->with($this->equalTo('Telekom'), $this->equalTo("12004901000000000XXXXXXX"), - $this->equalTo("jonny.gyros"), $this->equalTo("jonny.gyros@ver.sul.t-online.de"), - $this->isNull(), $this->equalTo("3 GB"), $this->isFalse(), $this->isFalse()) - ->willReturn(false); + ->method('unmarkDeletion') + ->with(self::UID); - $event = new UserAccountChangeEvent("12004901000000000XXXXXXX", "jonny.gyros", - "jonny.gyros@ver.sul.t-online.de", "3 GB", $oidcClaims); + $event = $this->event( + $this->claims([ + 'changeTime' => '2030-01-01T00:00:00Z', + ]) + ); $this->listener->handle($event); + $this->assertFalse($event->getResult()->isAccessAllowed()); - $this->assertEquals('Withdrawn', $event->getResult()->getReason()); - $this->assertNotNull($event->getResult()->getRedirectUrl()); - $this->assertEquals("https://cloud.telekom-dienste.de/ott", $event->getResult()->getRedirectUrl()); + $this->assertSame('Missing tariff claim - deletion not scheduled', $event->getResult()->getReason()); } - public function testWithdrawAccess() { - $oidcClaims = json_decode(<<userService->expects($this->once()) - ->method('userExists') - ->with($this->equalTo('Telekom'), $this->equalTo("12004901000000000XXXXXXX")) - ->willReturn(true); - $this->config->expects($this->once()) - ->method("setUserValue") - ->with($this->equalTo('12004901000000000XXXXXXX'), Application::APP_ID, $this->equalTo("deletion")); - $this->userService->expects($this->once()) - ->method('update') - ->with($this->equalTo('Telekom'), $this->equalTo("12004901000000000XXXXXXX"), - $this->equalTo("jonny.gyros"), $this->equalTo("jonny.gyros@ver.sul.t-online.de"), - $this->isNull(), $this->equalTo("3 GB"), $this->isFalse(), $this->isFalse()) - ->willReturn(false); + public function testStaleWithdrawalIsIgnored(): void { + $user = $this->existingUser(true); - $event = new UserAccountChangeEvent("12004901000000000XXXXXXX", "jonny.gyros", - "jonny.gyros@ver.sul.t-online.de", "3 GB", $oidcClaims); + $this->userService->method('userExists') + ->willReturn($user); + $this->userService->method('isStaleAccountChange') + ->willReturn(true); + + $this->userService->expects($this->never()) + ->method('markDeletion'); + $this->userService->expects($this->never()) + ->method('update'); + + $event = $this->event( + $this->claims([ + 'urn:telekom.com:f556' => '0', + 'changeTime' => '2030-01-01T00:00:00Z', + ]) + ); $this->listener->handle($event); - $this->assertFalse($event->getResult()->isAccessAllowed()); - $this->assertEquals('Withdrawn', $event->getResult()->getReason()); - $this->assertNotNull($event->getResult()->getRedirectUrl()); - $this->assertEquals("https://cloud.telekom-dienste.de/tarife", $event->getResult()->getRedirectUrl()); + + $this->assertTrue($event->getResult()->isAccessAllowed()); + $this->assertSame('Stale withdrawal event ignored', $event->getResult()->getReason()); } - public function testUnWithdraw() { - $oidcClaims = json_decode(<<existingUser(false); + + $this->userService->method('userExists') + ->willReturn($user); + $this->userService->method('isStaleAccountChange') + ->willReturn(false); $this->userService->expects($this->once()) - ->method('userExists') - ->with($this->equalTo('Telekom'), $this->equalTo("12004901000000000XXXXXXX")) - ->willReturn(true); - $this->config->expects($this->once()) - ->method("deleteUserValue") - ->with($this->equalTo('12004901000000000XXXXXXX'), Application::APP_ID, $this->equalTo("deletion")); + ->method('unmarkDeletion') + ->with(self::UID); + $this->userService->expects($this->once()) ->method('update') - ->with($this->equalTo('Telekom'), $this->equalTo("12004901000000000XXXXXXX"), - $this->equalTo("jonny.gyros"), $this->equalTo("jonny.gyros@ver.sul.t-online.de"), - $this->isNull(), $this->equalTo("3 GB"), $this->isFalse(), $this->isTrue()) - ->willReturn(true); + ->with($user, 'jonny.gyros', 'jonny.gyros@ver.sul.t-online.de', '3 GB', true); - $event = new UserAccountChangeEvent("12004901000000000XXXXXXX", "jonny.gyros", - "jonny.gyros@ver.sul.t-online.de", "3 GB", $oidcClaims); + $event = $this->event( + $this->claims([ + 'urn:telekom.com:f556' => '1', + 'changeTime' => '2030-01-02T00:00:00Z', + ]) + ); $this->listener->handle($event); + $this->assertTrue($event->getResult()->isAccessAllowed()); - $this->assertEquals('Updated', $event->getResult()->getReason()); - $this->assertNull($event->getResult()->getRedirectUrl()); + $this->assertSame('Updated', $event->getResult()->getReason()); } - public function testLock() { - $oidcClaims = json_decode(<<existingUser(false); + + $this->userService->method('userExists') + ->willReturn($user); + $this->userService->method('isStaleAccountChange') + ->willReturn(false); $this->userService->expects($this->once()) - ->method('userExists') - ->with($this->equalTo('Telekom'), $this->equalTo("12004901000000000XXXXXXX")) - ->willReturn(true); + ->method('unmarkDeletion') + ->with(self::UID); + $this->userService->expects($this->once()) ->method('update') - ->with($this->equalTo('Telekom'), $this->equalTo("12004901000000000XXXXXXX"), - $this->equalTo("jonny.gyros"), $this->equalTo("jonny.gyros@ver.sul.t-online.de"), - $this->isNull(), $this->equalTo("3 GB"), $this->isFalse(), $this->isFalse()) - ->willReturn(true); + ->with($user, 'jonny.gyros', 'jonny.gyros@ver.sul.t-online.de', '3 GB', false); - $event = new UserAccountChangeEvent("12004901000000000XXXXXXX", "jonny.gyros", - "jonny.gyros@ver.sul.t-online.de", "3 GB", $oidcClaims); + $event = $this->event( + $this->claims([ + 'urn:telekom.com:f556' => '1', + 'urn:telekom.com:s556' => '1', + 'changeTime' => '2030-01-02T00:00:00Z', + ]) + ); $this->listener->handle($event); + $this->assertFalse($event->getResult()->isAccessAllowed()); - $this->assertEquals('Locked', $event->getResult()->getReason()); - $this->assertNull($event->getResult()->getRedirectUrl()); + $this->assertSame('Locked', $event->getResult()->getReason()); } - public function testLockNonExisting() { - $oidcClaims = json_decode(<<existingUser(false); - $this->userService->expects($this->once()) - ->method('userExists') - ->with($this->equalTo('Telekom'), $this->equalTo("12004901000000000XXXXXXX")) + $this->userService->method('userExists') + ->willReturn($user); + $this->userService->method('isStaleAccountChange') ->willReturn(false); + $this->userService->method('markDeletion') + ->willReturn(new \DateTimeImmutable('2030-03-02T00:00:00+00:00')); - $event = new UserAccountChangeEvent("12004901000000000XXXXXXX", "jonny.gyros", - "jonny.gyros@ver.sul.t-online.de", "3 GB", $oidcClaims); + $event = $this->event( + $this->claims([ + 'urn:telekom.com:f556' => '0', + 'urn:telekom.com:f734' => '1', + 'changeTime' => '2030-01-01T00:00:00Z', + ]) + ); $this->listener->handle($event); - $this->assertFalse($event->getResult()->isAccessAllowed()); - $this->assertEquals('Locked no new account', $event->getResult()->getReason()); - $this->assertNull($event->getResult()->getRedirectUrl()); + + $this->assertSame( + 'https://telekom.example.com/', + $event->getResult()->getRedirectUrl() + ); + } + + private function existingUser(bool $enabled): IUser { + $user = $this->getMockForAbstractClass(IUser::class); + $user->method('getUID')->willReturn(self::UID); + $user->method('isEnabled')->willReturn($enabled); + + return $user; + } + + private function event(object $claims): UserAccountChangeEvent { + return new UserAccountChangeEvent(self::UID, 'jonny.gyros', 'jonny.gyros@ver.sul.t-online.de', '3 GB', $claims); + } + + private function claims(array $overrides = []): object { + return (object)array_merge( + [ + 'urn:telekom.com:s556' => '0', + 'urn:telekom.com:usta' => '1', + 'urn:telekom.com:f734' => '0', + ], + $overrides + ); } } diff --git a/tests/unit/UserWithdrawTest.php b/tests/unit/UserWithdrawTest.php index b1840cf..29ce087 100644 --- a/tests/unit/UserWithdrawTest.php +++ b/tests/unit/UserWithdrawTest.php @@ -17,132 +17,139 @@ use Psr\Log\LoggerInterface; class UserWithdrawTest extends TestCase { + private $app; + private $config; + private $logger; + private $userManager; + private $oidcProviderMapper; + private $userService; + private $accountService; + private array $userValues = []; + private array $appValues = []; + public function setUp(): void { parent::setUp(); + $this->app = new \OCP\AppFramework\App(Application::APP_ID); $this->config = $this->getMockForAbstractClass(IConfig::class); $this->logger = $this->app->getContainer()->get(LoggerInterface::class); $this->userManager = $this->getMockForAbstractClass(IUserManager::class); $this->oidcProviderMapper = $this->app->getContainer()->get(ProviderMapper::class); - $this->userServiceMock = $this->getMockBuilder(NmcUserService::class) - ->setConstructorArgs([ $this->app->getContainer()->get(IUserManager::class), - $this->app->getContainer()->get(IAccountManager::class), - $this->logger, - $this->config, - $this->app->getContainer()->get(UserMapper::class), - $this->app->getContainer()->get(ProviderMapper::class), - $this->app->getContainer()->get(IGroupManager::class)]) - ->onlyMethods(['create', 'update']) - ->getMock(); - $this->accountService = new UserAccountRules($this->config, - $this->logger, - $this->userServiceMock, - $this->userManager, - $this->oidcProviderMapper); + + $this->configureInMemoryUserValues(); + + $this->appValues = [ + 'userretention' => 'P60D', + 'userdeletionsafetydelay' => 'PT0S', + ]; + + $this->config->method('getAppValue') + ->willReturnCallback(function ($app, $key, $default = '') { return $this->appValues[$key] ?? $default; }); + + $this->userService = $this->getMockBuilder(NmcUserService::class) + ->setConstructorArgs([ + $this->app->getContainer()->get(IUserManager::class), + $this->app->getContainer()->get(IAccountManager::class), + $this->logger, + $this->config, + $this->app->getContainer()->get(UserMapper::class), + $this->app->getContainer()->get(ProviderMapper::class), + $this->app->getContainer()->get(IGroupManager::class), + ]) + ->onlyMethods(['create', 'update']) + ->getMock(); + + $this->accountService = new UserAccountRules($this->config, $this->logger, $this->userService, $this->userManager, $this->oidcProviderMapper); + } + + public function testWithdrawalDateUsesChangeTime(): void { + $claims = new \stdClass(); + $claims->changeTime = '2021-11-18T08:11:09Z'; + + $withdrawalTime = $this->accountService->withdrawDate($claims); + + $this->assertNotNull($withdrawalTime); + $this->assertSame('2021-11-18T08:11:09+00:00', $withdrawalTime->format(\DateTimeInterface::ATOM)); + } + + public function testWithdrawalDateDoesNotFallbackToAuthTime(): void { + $claims = new \stdClass(); + $claims->auth_time = 1637683330; + + $this->assertNull($this->accountService->withdrawDate($claims)); } - public function testDeletionDateOidcClaims() { - $oidcClaims = json_decode(<<accountService->withdrawDate($oidcClaims); - $this->assertEquals('2021-11-23T16:02:10+0000', $deletionTime-> format(\DateTimeInterface::ISO8601)); + public function testWithdrawalDateWithoutTimestampIsNull(): void { + $this->assertNull($this->accountService->withdrawDate(new \stdClass())); } - - public function testDeletionDateSlupClaims() { - $slupTestClaims = new \stdClass(); - $slupTestClaims->request = "UTS"; - $slupTestClaims->changeTime = "2021-11-18T08:11:09Z"; - $slupTestClaims->token = "847841948"; - $slupTestClaims->oldfields = new \stdClass(); - $slupTestClaims->newfields = new \stdClass(); - $deletionTime = $this->accountService->withdrawDate($slupTestClaims); - $this->assertEquals('2021-11-18T08:11:09+0000', $deletionTime-> format(\DateTimeInterface::ISO8601)); + + public function testMarkDeletionDefaultRetention(): void { + $userId = '12004901000000000XXXXXXX'; + $withdrawal = new \DateTimeImmutable('2030-08-03T16:05:06+00:00'); + $expected = $withdrawal->add(new \DateInterval('P60D')); + + $deletionDate = $this->userService->markDeletion($userId, $withdrawal); + + $this->assertNotNull($deletionDate); + $this->assertSame($expected->getTimestamp(), $deletionDate->getTimestamp()); + + $this->assertSame($withdrawal->getTimestamp(), (int)$this->userValues[$userId]['withdrawal']); + $this->assertSame($expected->getTimestamp(), (int)$this->userValues[$userId]['deletion']); + $this->assertSame($withdrawal->getTimestamp(), (int)$this->userValues[$userId]['last_account_change']); } - public function testDeletionDateDefault() { - $now = new \DateTime(); - $deletionTime = $this->accountService->withdrawDate(new \stdClass()); - $this->assertGreaterThanOrEqual($now->getTimestamp(), $deletionTime->getTimestamp()); - $this->assertLessThan($now->getTimestamp() + 3, $deletionTime->getTimestamp()); + public function testOldWithdrawalGetsLocalSafetyDelay(): void { + $userId = '12004901000000000XXXXXXX'; + $withdrawal = new \DateTimeImmutable('2021-08-03T16:05:06+00:00'); + + $this->appValues['userdeletionsafetydelay'] = 'P1D'; + + $before = time(); + $deletionDate = $this->userService->markDeletion($userId, $withdrawal); + $after = time(); + + $this->assertNotNull($deletionDate); + $this->assertGreaterThanOrEqual($before + 86400, $deletionDate->getTimestamp()); + $this->assertLessThanOrEqual($after + 86401, $deletionDate->getTimestamp()); } - public function testMarkDeletionDefault() { - $withdrawDate = new \DateTime("2021-08-03T16:05:06+0000"); - $expectedDeletionDate = new \DateTime(); - $expectedDeletionDate->setTimestamp($withdrawDate->getTimestamp() + 60 * 24 * 60 * 60); - - - $this->config->expects($this->once()) - ->method("getAppValue") - ->with($this->equalTo('nmcprovisioning'), $this->equalTo('userretention'), $this->equalTo("P60D")) - ->willReturn("P60D"); - $this->config->expects($this->once()) - ->method("setUserValue") - ->with($this->equalTo('12004901000000000XXXXXXX'), Application::APP_ID, $this->equalTo("deletion"), - $this->equalTo($expectedDeletionDate->getTimestamp())); - $this->config->expects($this->once()) - ->method("getUserValue") - ->with($this->equalTo('12004901000000000XXXXXXX'), Application::APP_ID, $this->equalTo("deletion"), - $this->equalTo(null)) - ->willReturn($expectedDeletionDate->getTimestamp()); - - $deletionDate = $this->userServiceMock->markDeletion('12004901000000000XXXXXXX', $withdrawDate); - $this->assertEquals($expectedDeletionDate, $deletionDate); - - $readDeletionDate = $this->userServiceMock->getDeletionDateTime('12004901000000000XXXXXXX'); - $this->assertNotNull($readDeletionDate); - $this->assertEquals($expectedDeletionDate, $readDeletionDate); + public function testStaleWithdrawalIsRejected(): void { + $userId = '12004901000000000XXXXXXX'; + + $this->userValues[$userId]['last_account_change'] = (new \DateTimeImmutable('2030-08-04T00:00:00+00:00')) + ->getTimestamp(); + + $result = $this->userService->markDeletion($userId, new \DateTimeImmutable('2030-08-03T00:00:00+00:00')); + + $this->assertNull($result); + $this->assertArrayNotHasKey('deletion', $this->userValues[$userId]); } - public function testMarkDeletionConfig() { - $withdrawDate = new \DateTime("2021-08-03T16:05:06+0000"); - $expectedDeletionDate = new \DateTime(); - $expectedDeletionDate->setTimestamp($withdrawDate->getTimestamp() + 60 * 60); - - $this->config->expects($this->once()) - ->method("getAppValue") - ->with($this->equalTo('nmcprovisioning'), $this->equalTo('userretention'), $this->equalTo("P60D")) - ->willReturn("PT1H"); - $this->config->expects($this->once()) - ->method("setUserValue") - ->with($this->equalTo('12004901000000000XXXXXXX'), Application::APP_ID, $this->equalTo("deletion"), - $this->equalTo($expectedDeletionDate->getTimestamp())); - $this->config->expects($this->once()) - ->method("getUserValue") - ->with($this->equalTo('12004901000000000XXXXXXX'), Application::APP_ID, $this->equalTo("deletion"), - $this->equalTo(null)) - ->willReturn($expectedDeletionDate->getTimestamp()); - - $deletionDate = $this->userServiceMock->markDeletion('12004901000000000XXXXXXX', $withdrawDate); - $this->assertEquals($expectedDeletionDate, $deletionDate); - - $readDeletionDate = $this->userServiceMock->getDeletionDateTime('12004901000000000XXXXXXX'); - $this->assertNotNull($readDeletionDate); - $this->assertEquals($expectedDeletionDate, $readDeletionDate); + public function testUnmarkDeletionRemovesDeletionMetadataButKeepsOrdering(): void { + $userId = '12004901000000000XXXXXXX'; + $this->userValues[$userId] = [ + 'deletion' => 10, + 'withdrawal' => 9, + 'deletion_marked_at' => 8, + 'last_account_change' => 9, + ]; + + $this->userService->unmarkDeletion($userId); + + $this->assertArrayNotHasKey('deletion', $this->userValues[$userId]); + $this->assertArrayNotHasKey('withdrawal', $this->userValues[$userId]); + $this->assertArrayNotHasKey('deletion_marked_at', $this->userValues[$userId]); + $this->assertSame(9, $this->userValues[$userId]['last_account_change']); } - public function testUnmarkDeletionDefault() { - $this->config->expects($this->once()) - ->method("deleteUserValue") - ->with($this->equalTo('12004901000000000XXXXXXX'), Application::APP_ID, $this->equalTo("deletion")); - $this->config->expects($this->once()) - ->method("getUserValue") - ->with($this->equalTo('12004901000000000XXXXXXX'), Application::APP_ID, $this->equalTo("deletion"), - $this->equalTo(null)) - ->willReturn(null); - - $deletionDate = $this->userServiceMock->unmarkDeletion('12004901000000000XXXXXXX'); - $this->assertNull($this->userServiceMock->getDeletionDateTime('12004901000000000XXXXXXX')); + private function configureInMemoryUserValues(): void { + $this->config->method('getUserValue') + ->willReturnCallback(function ($userId, $appId, $key, $default = null) { return $this->userValues[$userId][$key] ?? $default; }); + + $this->config->method('setUserValue') + ->willReturnCallback(function ($userId, $appId, $key, $value): void { $this->userValues[$userId][$key] = $value; }); + + $this->config->method('deleteUserValue') + ->willReturnCallback(function ($userId, $appId, $key): void { unset($this->userValues[$userId][$key]); }); } } From 0924726e0bc86cecb648937f782069723c5d22c1 Mon Sep 17 00:00:00 2001 From: memurats Date: Fri, 13 Nov 2026 10:02:18 +0100 Subject: [PATCH 2/7] fix cs --- lib/Rules/DisplaynameRules.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/Rules/DisplaynameRules.php b/lib/Rules/DisplaynameRules.php index 247769d..7954644 100644 --- a/lib/Rules/DisplaynameRules.php +++ b/lib/Rules/DisplaynameRules.php @@ -20,7 +20,7 @@ public function deriveDisplayname(object $claims): string { continue; } - $fields = array_map(static fn(string $field): string => 'urn:telekom.com:' . $field, $search); + $fields = array_map(static fn (string $field): string => 'urn:telekom.com:' . $field, $search); $allFieldsMatch = array_reduce($fields, static function (bool $carry, string $field) use ($claims): bool { return $carry && property_exists($claims, $field); @@ -31,7 +31,7 @@ public function deriveDisplayname(object $claims): string { } $displayName = implode(' ', array_map( - static fn(string $field): string => (string)$claims->{$field}, + static fn (string $field): string => (string)$claims->{$field}, $fields )); From a08aa35ea19b79fa4a29fc633bfe4a742d9240c5 Mon Sep 17 00:00:00 2001 From: memurats Date: Mon, 16 Nov 2026 17:07:09 +0100 Subject: [PATCH 3/7] Move unrelated rule changes out of user deletion PR --- lib/Rules/DisplaynameRules.php | 53 +++++++++---------- lib/Rules/TariffRules.php | 97 ++++++++++++++++++++++++---------- 2 files changed, 94 insertions(+), 56 deletions(-) diff --git a/lib/Rules/DisplaynameRules.php b/lib/Rules/DisplaynameRules.php index 7954644..6b60c3e 100644 --- a/lib/Rules/DisplaynameRules.php +++ b/lib/Rules/DisplaynameRules.php @@ -4,48 +4,45 @@ use OCA\NextMagentaCloudProvisioning\Logger\ProvisioningLogger; +/** + * The generic tariff rules evaluator + */ class DisplaynameRules { private GroupTariffMapping $groupTariffMapping; + + /** @var ProvisioningLogger */ private ProvisioningLogger $provisioningLogger; + public function __construct(GroupTariffMapping $groupTariffMapping, ProvisioningLogger $provisioningLogger) { $this->groupTariffMapping = $groupTariffMapping; $this->provisioningLogger = $provisioningLogger; } - public function deriveDisplayname(object $claims): string { + /** + * Central rule to derive displayname + * consistently from SAM/SLUP fields + */ + public function deriveDisplayname(object $claims) { + $displayname = ""; + $this->provisioningLogger->debug("test"); foreach ($this->groupTariffMapping->getDisplaynameSearch() as $search) { - if (empty($search)) { - continue; - } - - $fields = array_map(static fn (string $field): string => 'urn:telekom.com:' . $field, $search); - - $allFieldsMatch = array_reduce($fields, static function (bool $carry, string $field) use ($claims): bool { - return $carry && property_exists($claims, $field); + // check if all attributes match + $searchAttrs = array_map(function ($field) { return 'urn:telekom.com:' . $field; }, $search); + $allFieldsMatch = array_reduce($searchAttrs, function ($carry, $field) use ($claims) { + return !property_exists($claims, $field) ? false : $carry; }, true); - - if (!$allFieldsMatch) { - continue; + // the displayname is only complete if all match + if ($allFieldsMatch) { + return implode(' ', array_map(function ($id) use ($claims) { + return $claims->{$id}; + }, $searchAttrs)); } - - $displayName = implode(' ', array_map( - static fn (string $field): string => (string)$claims->{$field}, - $fields - )); - - $this->provisioningLogger->debug('Derived displayname from configured claims', [ - 'fields' => $fields, - ]); - - return $displayName; } - $this->provisioningLogger->warning('Could not derive displayname from claims', [ - 'claimKeys' => array_keys(get_object_vars($claims)), - ]); - - return '-anon-'; + $this->provisioningLogger->warning('Could not derive displayname from claims', ['claims' => $claims]); + return "-anon-"; } + } diff --git a/lib/Rules/TariffRules.php b/lib/Rules/TariffRules.php index 4e84852..def1007 100644 --- a/lib/Rules/TariffRules.php +++ b/lib/Rules/TariffRules.php @@ -4,60 +4,101 @@ use OCA\NextMagentaCloudProvisioning\Logger\ProvisioningLogger; +/** + * The generic tariff rules evaluator + */ class TariffRules { private GroupTariffMapping $groupTariffMapping; + + /** @var ProvisioningLogger */ private ProvisioningLogger $provisioningLogger; + public function __construct(GroupTariffMapping $groupTariffMapping, ProvisioningLogger $provisioningLogger) { $this->groupTariffMapping = $groupTariffMapping; $this->provisioningLogger = $provisioningLogger; } - private function quotaNoFlags(object $claims, array $tariffs): string { - $anyFlagSet = array_reduce($tariffs, function (bool $carry, array $tariff) use ($claims): bool { - if ($carry || !array_key_exists('flag', $tariff)) { + /** + * Quota computation helper function to check + * claims contain none of the configured flags + * + * For random combinations of tariffs where even one of + * the flaged tariffs can be 0, the case must be explixitly checked + * and cannot be used as default. + */ + private function quotaNoFlags(object $claims, $tariffs) { + $anyFlagSet = array_reduce($tariffs, function ($carry, $tariff) use ($claims) { + if (array_key_exists('flag', $tariff) && ($carry == false)) { + return $this->isQuotaFlagSet($claims, $tariff); + } else { return $carry; } - return $this->isQuotaFlagSet($claims, $tariff); }, false); - return $anyFlagSet ? '0 B' : $tariffs['NOFLAGS']['space_limit']; + if (!$anyFlagSet) { + // make sure that a quota >0 is only delivered + // for the NOFLAGS case if actually no flags are set + // Otherwise, all quotas < the NOFLAGS quota will not apply + return $tariffs['NOFLAGS']['space_limit']; + } else { + return "0 B"; + } } - private function isQuotaFlagSet(object $claims, array $tariff): bool { - $flagName = $tariff['flag']; - return property_exists($claims, $flagName) && (string)$claims->{$flagName} === '1'; + + /** + * Get the quota if a flag is set + * The function does assume that the flag field exists + */ + private function isQuotaFlagSet(object $claims, $tariff) { + $flagname = $tariff['flag']; + if (property_exists($claims, $flagname) && + $claims->{$flagname} === "1") { + return true; + } else { + return false; + } } - private function maxQuota(string $left, string $right): string { - return \OCP\Util::computerFileSize($left) > \OCP\Util::computerFileSize($right) ? $left : $right; + /** + * Compute the maximum of two quotas given + * Nextcloud human readable storage sizes + */ + private function maxQuota(string $left, string $right) { + $leftBytes = \OCP\Util::computerFileSize($left); + $rightBytes = \OCP\Util::computerFileSize($right); + if ($leftBytes > $rightBytes) { + return $left; + } else { + return $right; + } } - public function deriveQuota(object $claims): string { + /** + * Central rule to derive quota + * consistently from SAM/SLUP fields + */ + public function deriveQuota(object $claims) { $tariffs = $this->groupTariffMapping->getGroupMapping(); - $quotaCandidates = array_map(function (array $tariff) use ($claims): string { - if (!array_key_exists('flag', $tariff)) { - return '0 B'; + // for each flag that is set: add the quota limit + $quotaCandidates = array_map(function ($tariff) use ($claims, $tariffs) { + if (array_key_exists('flag', $tariff)) { + return $this->isQuotaFlagSet($claims, $tariff) ? $tariff['space_limit'] : "0 B"; + } else { + // skip the "no flags" case + // it is the deafult value of reduce + return "0 B"; } - return $this->isQuotaFlagSet($claims, $tariff) ? $tariff['space_limit'] : '0 B'; }, $tariffs); - $maxQuota = array_reduce($quotaCandidates, [$this, 'maxQuota'], $this->quotaNoFlags($claims, $tariffs)); - - $activeFlagCount = 0; - foreach ($tariffs as $tariff) { - if (array_key_exists('flag', $tariff) && $this->isQuotaFlagSet($claims, $tariff)) { - $activeFlagCount++; - } - } - - $this->provisioningLogger->debug('Derived quota from tariff claims', [ - 'activeFlagCount' => $activeFlagCount, - 'quota' => $maxQuota, - ]); + $noflagsQuota = $this->quotaNoFlags($claims, $tariffs); + $maxQuota = array_reduce($quotaCandidates, array($this, 'maxQuota'), $noflagsQuota); + // Return the max quota limit as human readable unit + // as it is standard in Nextcloud return $maxQuota; } } From 8679e974e1aa405b4a8b097929882205786f74c5 Mon Sep 17 00:00:00 2001 From: memurats Date: Tue, 17 Nov 2026 10:33:37 +0100 Subject: [PATCH 4/7] Harden user deletion retention and state validation --- lib/Db/UserQueries.php | 50 +++++++++--- lib/Rules/UserAccountRules.php | 13 ++- lib/User/NmcUserService.php | 99 +++++++++++----------- lib/User/UserAccountDeletionJob.php | 122 ++++++++-------------------- 4 files changed, 131 insertions(+), 153 deletions(-) diff --git a/lib/Db/UserQueries.php b/lib/Db/UserQueries.php index dbc2935..bcf16fc 100644 --- a/lib/Db/UserQueries.php +++ b/lib/Db/UserQueries.php @@ -29,7 +29,6 @@ public function __construct(IDBConnection $db) { */ public function findDeletions(\DateTimeInterface $refDate, ?int $limit = null): array { $refTs = $refDate->getTimestamp(); - $qb = $this->db->getQueryBuilder(); $qb->select('userid') ->from('preferences') @@ -60,26 +59,47 @@ public function getDeletionDateTime(string $userId): ?\DateTimeImmutable { } /** - * Return all metadata needed to validate a deletion decision. + * Return the deletion state in one database query so the background job can + * validate the decision immediately before the irreversible delete(). * * @return array{ * deletion: \DateTimeImmutable, * withdrawal: ?\DateTimeImmutable, - * markedAt: ?\DateTimeImmutable, * lastAccountChange: ?\DateTimeImmutable * }|null */ public function getDeletionState(string $userId): ?array { - $deletion = $this->getPreferenceDateTime($userId, 'deletion'); + $qb = $this->db->getQueryBuilder(); + $keyExpression = $qb->expr()->orX( + $qb->expr()->eq('configkey', $qb->createNamedParameter('deletion')), + $qb->expr()->eq('configkey', $qb->createNamedParameter('withdrawal')), + $qb->expr()->eq('configkey', $qb->createNamedParameter('last_account_change')) + ); + + $qb->select('configkey', 'configvalue') + ->from('preferences') + ->where($qb->expr()->eq('userid', $qb->createNamedParameter($userId))) + ->andWhere($qb->expr()->eq('appid', $qb->createNamedParameter(Application::APP_ID))) + ->andWhere($keyExpression); + + $result = $qb->execute(); + + $values = []; + while ($row = $result->fetch()) { + $values[(string)$row['configkey']] = $row['configvalue']; + } + + $result->closeCursor(); + + $deletion = $this->dateTimeFromPreferenceValue($values['deletion'] ?? null); if ($deletion === null) { return null; } return [ 'deletion' => $deletion, - 'withdrawal' => $this->getPreferenceDateTime($userId, 'withdrawal'), - 'markedAt' => $this->getPreferenceDateTime($userId, 'deletion_marked_at'), - 'lastAccountChange' => $this->getPreferenceDateTime($userId, 'last_account_change'), + 'withdrawal' => $this->dateTimeFromPreferenceValue($values['withdrawal'] ?? null), + 'lastAccountChange' => $this->dateTimeFromPreferenceValue($values['last_account_change'] ?? null), ]; } @@ -88,10 +108,12 @@ public function getDeletionState(string $userId): ?array { * * last_account_change is intentionally retained so delayed events cannot * overwrite a newer state after deletion has been cancelled. + * + * deletion_marked_at is included for cleanup of values written by earlier + * revisions of the hardening PR. */ public function deleteDeletionPreferencesById(string $userId): bool { $qb = $this->db->getQueryBuilder(); - $keyExpression = $qb->expr()->orX( $qb->expr()->eq('configkey', $qb->createNamedParameter(self::DELETION_KEYS[0])), $qb->expr()->eq('configkey', $qb->createNamedParameter(self::DELETION_KEYS[1])), @@ -112,7 +134,6 @@ public function deleteDeletionPreferencesById(string $userId): bool { */ public function postponeDeletion(string $userId, \DateTimeInterface $retryAt): bool { $qb = $this->db->getQueryBuilder(); - $qb->update('preferences') ->set('configvalue', $qb->createNamedParameter($retryAt->getTimestamp(), IQueryBuilder::PARAM_INT)) ->where($qb->expr()->eq('userid', $qb->createNamedParameter($userId))) @@ -144,15 +165,14 @@ public function deleteUserPreferenceById(string $userId): bool { $qb = $this->db->getQueryBuilder(); $qb->delete('preferences') - ->where($qb->expr()->eq('userid', $qb->createNamedParameter($userId))) - ->execute(); + ->where($qb->expr()->eq('userid', $qb->createNamedParameter($userId))) + ->execute(); - return true; // Return true to indicate successful deletion + return true; } private function getPreferenceDateTime(string $userId, string $key): ?\DateTimeImmutable { $qb = $this->db->getQueryBuilder(); - $qb->select('configvalue') ->from('preferences') ->where($qb->expr()->eq('userid', $qb->createNamedParameter($userId))) @@ -164,6 +184,10 @@ private function getPreferenceDateTime(string $userId, string $key): ?\DateTimeI $value = $result->fetchOne(); $result->closeCursor(); + return $this->dateTimeFromPreferenceValue($value); + } + + private function dateTimeFromPreferenceValue(mixed $value): ?\DateTimeImmutable { if ($value === false || $value === null || $value === '' || !is_numeric($value)) { return null; } diff --git a/lib/Rules/UserAccountRules.php b/lib/Rules/UserAccountRules.php index 7dba36b..3543c83 100644 --- a/lib/Rules/UserAccountRules.php +++ b/lib/Rules/UserAccountRules.php @@ -91,6 +91,16 @@ public function withdrawDate(object $claims): ?\DateTimeImmutable { $errors = \DateTimeImmutable::getLastErrors(); if ($date !== false && ($errors === false || ($errors['warning_count'] === 0 && $errors['error_count'] === 0))) { + $now = new \DateTimeImmutable(); + + if ($date > $now) { + $this->logger->warning('Future changeTime received, clamping to current time', [ + 'changeTime' => $date->format(\DateTimeInterface::ATOM), + 'now' => $now->format(\DateTimeInterface::ATOM), + ]); + return $now; + } + return $date; } } @@ -287,7 +297,6 @@ public function deriveExistingAccountState( // Missing tariff state is not a confirmed withdrawal. if ($bookingState === null) { - $this->nmcUserService->unmarkDeletion($uid); $this->nmcUserService->update($user, $displayname, $mainEmail, $quota, false); $this->logger->warning("{$uid}: f556 missing. Deletion not scheduled."); @@ -297,7 +306,6 @@ public function deriveExistingAccountState( // Withdrawal needs a valid authoritative timestamp. if ($changeTime === null) { - $this->nmcUserService->unmarkDeletion($uid); $this->nmcUserService->update($user, $displayname, $mainEmail, $quota, false); $this->logger->error("{$uid}: Withdrawal without valid changeTime. Deletion not scheduled."); @@ -318,7 +326,6 @@ public function deriveExistingAccountState( try { $deletionDate = $this->nmcUserService->markDeletion($uid, $changeTime); } catch (\Throwable $e) { - $this->nmcUserService->unmarkDeletion($uid); $this->nmcUserService->update($user, $displayname, $mainEmail, $quota, false); $this->logger->critical("{$uid}: Failed to schedule deletion safely.", [ diff --git a/lib/User/NmcUserService.php b/lib/User/NmcUserService.php index 859b032..88b677b 100644 --- a/lib/User/NmcUserService.php +++ b/lib/User/NmcUserService.php @@ -23,12 +23,9 @@ class NmcUserService { private const KEY_DELETION = 'deletion'; private const KEY_WITHDRAWAL = 'withdrawal'; - private const KEY_DELETION_MARKED_AT = 'deletion_marked_at'; private const KEY_LAST_ACCOUNT_CHANGE = 'last_account_change'; private const DEFAULT_RETENTION = 'P60D'; - private const DEFAULT_SAFETY_DELAY = 'P1D'; - /** @var IUserManager */ private $userManager; @@ -174,7 +171,19 @@ public function getLastAccountChangeTime(string $userId): ?\DateTimeImmutable { * replace a newer one. */ public function recordAccountChangeTime(string $userId, \DateTimeInterface $changeTime): bool { - $incomingTimestamp = $changeTime->getTimestamp(); + $incoming = \DateTimeImmutable::createFromInterface($changeTime); + $now = new \DateTimeImmutable(); + + if ($incoming > $now) { + $this->logger->warning('Clamping future account change time to current time', [ + 'userId' => $userId, + 'changeTime' => $incoming->format(\DateTimeInterface::ATOM), + 'now' => $now->format(\DateTimeInterface::ATOM), + ]); + $incoming = $now; + } + + $incomingTimestamp = $incoming->getTimestamp(); $current = $this->getLastAccountChangeTime($userId); if ($current !== null && $incomingTimestamp < $current->getTimestamp()) { @@ -197,46 +206,52 @@ public function isStaleAccountChange(string $userId, \DateTimeInterface $changeT /** * Mark a user for delayed deletion. * - * The effective deletion date is the later of: - * - authoritative withdrawal time + configured retention period - * - first local observation of this withdrawal + safety delay + * The deletion date is calculated from the later of the authoritative + * withdrawal timestamp and the local observation time, plus the configured + * retention period. This guarantees the full retention period even when an + * old withdrawal event reaches this system late. * - * The second condition prevents an old/replayed event from becoming - * immediately destructive when it reaches this system for the first time. + * Repeated delivery of the same withdrawal event is idempotent and keeps the + * already scheduled deletion date. * * @return \DateTimeImmutable|null Null if the withdrawal event is stale. */ public function markDeletion(string $userId, \DateTimeInterface $withdrawTime): ?\DateTimeImmutable { - if ($this->isStaleAccountChange($userId, $withdrawTime)) { + $withdrawal = \DateTimeImmutable::createFromInterface($withdrawTime); + $now = new \DateTimeImmutable(); + + if ($withdrawal > $now) { + $this->logger->warning('Clamping future withdrawal time to current time', [ + 'userId' => $userId, + 'withdrawTime' => $withdrawal->format(\DateTimeInterface::ATOM), + 'now' => $now->format(\DateTimeInterface::ATOM), + ]); + $withdrawal = $now; + } + + if ($this->isStaleAccountChange($userId, $withdrawal)) { $this->logger->warning('Refusing stale withdrawal event', [ 'userId' => $userId, - 'withdrawTime' => $withdrawTime->format(\DateTimeInterface::ATOM), + 'withdrawTime' => $withdrawal->format(\DateTimeInterface::ATOM), 'lastAccountChange' => $this->getLastAccountChangeTime($userId)?->format(\DateTimeInterface::ATOM), ]); return null; } - $withdrawal = \DateTimeImmutable::createFromInterface($withdrawTime); $existingWithdrawal = $this->getUserTimestamp($userId, self::KEY_WITHDRAWAL); - $existingMarkedAt = $this->getUserTimestamp($userId, self::KEY_DELETION_MARKED_AT); - - /* - * Repeated delivery of the same event must not keep moving the local - * safety window. For a genuinely newer withdrawal event, start a new - * observation window. - */ - if ($existingWithdrawal !== null && $existingMarkedAt !== null && $existingWithdrawal->getTimestamp() === $withdrawal->getTimestamp()) { - $markedAt = $existingMarkedAt; - } else { - $markedAt = new \DateTimeImmutable(); + $existingDeletion = $this->getDeletionDateTime($userId); + + if ( + $existingWithdrawal !== null + && $existingDeletion !== null + && $existingWithdrawal->getTimestamp() === $withdrawal->getTimestamp() + ) { + return $existingDeletion; } $retention = $this->getConfiguredInterval('userretention', self::DEFAULT_RETENTION); - $safetyDelay = $this->getConfiguredInterval('userdeletionsafetydelay', self::DEFAULT_SAFETY_DELAY); - - $retentionDate = $withdrawal->add($retention); - $safetyDate = $markedAt->add($safetyDelay); - $deletionDate = $retentionDate > $safetyDate ? $retentionDate : $safetyDate; + $deletionBase = $withdrawal > $now ? $withdrawal : $now; + $deletionDate = $deletionBase->add($retention); if (!$this->recordAccountChangeTime($userId, $withdrawal)) { $this->logger->warning('Withdrawal became stale before it could be stored', [ @@ -249,33 +264,21 @@ public function markDeletion(string $userId, \DateTimeInterface $withdrawTime): $this->logger->info('Marking user for delayed deletion', [ 'userId' => $userId, 'withdrawTime' => $withdrawal->format(\DateTimeInterface::ATOM), - 'markedAt' => $markedAt->format(\DateTimeInterface::ATOM), 'deletionDate' => $deletionDate->format(\DateTimeInterface::ATOM), 'retention' => $this->config->getAppValue('nmcprovisioning', 'userretention', self::DEFAULT_RETENTION), - 'safetyDelay' => $this->config->getAppValue('nmcprovisioning', 'userdeletionsafetydelay', self::DEFAULT_SAFETY_DELAY), ]); /* - * Write supporting metadata first and the actual deletion marker last. - * A partially written state therefore cannot become eligible for the - * deletion query. + * Write the destructive marker before the supporting withdrawal metadata. + * If the second write fails, last_account_change lets the deletion job + * distinguish this incomplete new state from a legacy pre-PR marker and + * fail safely. */ - $this->config->setUserValue($userId, Application::APP_ID, self::KEY_WITHDRAWAL, $withdrawal->getTimestamp()); - $this->config->setUserValue($userId, Application::APP_ID, self::KEY_DELETION_MARKED_AT, $markedAt->getTimestamp()); $this->config->setUserValue($userId, Application::APP_ID, self::KEY_DELETION, $deletionDate->getTimestamp()); + $this->config->setUserValue($userId, Application::APP_ID, self::KEY_WITHDRAWAL, $withdrawal->getTimestamp()); - /* - * Narrow the race window with a concurrent reactivation/newer event. - * If a newer state appeared while this method was writing, disarm the - * deletion immediately. The deletion job performs the same check again. - */ - if ($this->isStaleAccountChange($userId, $withdrawal)) { - $this->logger->warning('Newer account state detected while marking deletion', [ - 'userId' => $userId, - ]); - $this->unmarkDeletion($userId); - return null; - } + // Clean up metadata written by earlier revisions of this hardening PR. + $this->config->deleteUserValue($userId, Application::APP_ID, 'deletion_marked_at'); return $deletionDate; } @@ -290,7 +293,7 @@ public function markDeletion(string $userId, \DateTimeInterface $withdrawTime): public function unmarkDeletion(string $userId): void { $this->config->deleteUserValue($userId, Application::APP_ID, self::KEY_DELETION); $this->config->deleteUserValue($userId, Application::APP_ID, self::KEY_WITHDRAWAL); - $this->config->deleteUserValue($userId, Application::APP_ID, self::KEY_DELETION_MARKED_AT); + $this->config->deleteUserValue($userId, Application::APP_ID, 'deletion_marked_at'); } /** diff --git a/lib/User/UserAccountDeletionJob.php b/lib/User/UserAccountDeletionJob.php index ee90020..22d9f91 100644 --- a/lib/User/UserAccountDeletionJob.php +++ b/lib/User/UserAccountDeletionJob.php @@ -71,34 +71,6 @@ public function run($arguments): void { private function processUser(string $uid): void { try { - $state = $this->userQueries->getDeletionState($uid); - - if ($state === null) { - $this->logger->warning("Skipping {$uid}, deletion entry no longer exists."); - return; - } - - if ($state['deletion'] > $this->now()) { - $this->logger->warning("Skipping {$uid}, deletion not due yet: " . $state['deletion']->format(\DateTimeInterface::ATOM)); - return; - } - - /* - * Old/partial deletion markers are deliberately not trusted. - * Supporting metadata is required before irreversible deletion. - */ - if ($state['withdrawal'] === null || $state['markedAt'] === null) { - $this->logger->critical("Skipping {$uid}: incomplete deletion metadata. " . 'Deletion marker will be disarmed.'); - $this->userQueries->deleteDeletionPreferencesById($uid); - return; - } - - if ($state['lastAccountChange'] !== null && $state['lastAccountChange']->getTimestamp() > $state['withdrawal']->getTimestamp()) { - $this->logger->critical("Skipping {$uid}: newer account state exists. " . 'Deletion marker will be disarmed.'); - $this->userQueries->deleteDeletionPreferencesById($uid); - return; - } - $user = $this->userManager->get($uid); if ($user === null) { @@ -108,8 +80,9 @@ private function processUser(string $uid): void { } /* - * Reactivation is authoritative in the safe direction. An enabled - * user must never be deleted by this background job. + * Reactivation is authoritative in the safe direction. This is not a + * concurrency guarantee because IUserManager may cache in-process, but it + * still protects against an already enabled account. */ if ($user->isEnabled()) { $this->logger->critical("Skipping {$uid}: user is enabled while marked for deletion. " . 'Deletion marker will be disarmed.'); @@ -117,78 +90,57 @@ private function processUser(string $uid): void { return; } - $initialFingerprint = $this->fingerprint($state); - /* - * Re-read deletion metadata after resolving the user and immediately - * before delete(). This preserves the current recheck behaviour and - * extends it to all deletion metadata. + * Validate the deletion decision once directly against the preferences DB + * immediately before delete(). getDeletionState() performs a single query. */ - $currentState = $this->userQueries->getDeletionState($uid); + $state = $this->userQueries->getDeletionState($uid); - if ($currentState === null) { + if ($state === null) { $this->logger->warning("Skipping {$uid}: deletion was cancelled before delete()."); return; } - if (!hash_equals($initialFingerprint, $this->fingerprint($currentState))) { - $this->logger->warning("Skipping {$uid}: deletion state changed before delete()."); - return; - } - - if ( - $currentState['deletion'] > $this->now() - || $currentState['withdrawal'] === null - || $currentState['markedAt'] === null - || ($currentState['lastAccountChange'] !== null && $currentState['lastAccountChange']->getTimestamp() > $currentState['withdrawal']->getTimestamp()) - ) { - $this->logger->warning("Skipping {$uid}: final deletion validation failed."); + if ($state['deletion'] > $this->now()) { + $this->logger->warning("Skipping {$uid}, deletion not due yet: " . $state['deletion']->format(\DateTimeInterface::ATOM)); return; } - /* - * Re-fetch the user too. A reactivation may have happened while the - * deletion state was being checked. - */ - $user = $this->userManager->get($uid); - - if ($user === null) { - $this->logger->warning("User {$uid} disappeared before delete(), cleaning preferences."); - $this->userQueries->deleteUserPreferenceById($uid); - return; - } + if ($state['withdrawal'] === null) { + /* + * Deletion markers created before this hardening PR contain only the + * deletion timestamp. Keep processing those markers with the previous + * semantics instead of disarming all pending production deletions. + * + * If last_account_change exists, however, this is an incomplete state + * written by the new code and must fail safe. + */ + if ($state['lastAccountChange'] !== null) { + $this->logger->critical("Skipping {$uid}: incomplete deletion metadata. " . 'Deletion marker will be disarmed.'); + $this->userQueries->deleteDeletionPreferencesById($uid); + return; + } - if ($user->isEnabled()) { - $this->logger->critical("Skipping {$uid}: user was re-enabled before delete(). " . 'Deletion marker will be disarmed.'); + $this->logger->warning("Processing {$uid} with a legacy deletion marker without withdrawal metadata."); + } elseif ( + $state['lastAccountChange'] !== null + && $state['lastAccountChange']->getTimestamp() > $state['withdrawal']->getTimestamp() + ) { + $this->logger->critical("Skipping {$uid}: newer account state exists. " . 'Deletion marker will be disarmed.'); $this->userQueries->deleteDeletionPreferencesById($uid); return; } - /* - * One final metadata read after the final user-state read also protects - * booked-but-locked reactivations: those may stay disabled while still - * cancelling the deletion marker. - */ - $finalState = $this->userQueries->getDeletionState($uid); - - if ($finalState === null || !hash_equals($initialFingerprint, $this->fingerprint($finalState))) { - $this->logger->warning("Skipping {$uid}: deletion state changed during final validation."); - return; - } - - $this->logger->info("Deleting {$uid}, deletion due since " . $currentState['deletion']->format(\DateTimeInterface::ATOM)); + $this->logger->info("Deleting {$uid}, deletion due since " . $state['deletion']->format(\DateTimeInterface::ATOM)); $startDeletionTime = $this->timeFactory->getTime(); - $user->delete(); + if (!$user->delete()) { + throw new \RuntimeException("User deletion returned false for {$uid}"); + } $duration = $this->timeFactory->getTime() - $startDeletionTime; - /* - * The old code said "skipping" here even though delete() had already - * happened, which also skipped preference cleanup. A slow deletion - * is now only a warning; cleanup still runs. - */ if ($duration > self::SLOW_DELETION_WARNING) { $this->logger->warning("User {$uid} deletion took longer than 30 minutes " . "({$duration} seconds)."); } @@ -231,12 +183,4 @@ private function now(): \DateTimeImmutable { return (new \DateTimeImmutable())->setTimestamp($this->timeFactory->getTime()); } - private function fingerprint(array $state): string { - return implode(':', [ - (string)$state['deletion']->getTimestamp(), - $state['withdrawal'] instanceof \DateTimeInterface ? (string)$state['withdrawal']->getTimestamp() : '-', - $state['markedAt'] instanceof \DateTimeInterface ? (string)$state['markedAt']->getTimestamp() : '-', - $state['lastAccountChange'] instanceof \DateTimeInterface ? (string)$state['lastAccountChange']->getTimestamp() : '-', - ]); - } } From 155ca7d0fc76b9b3eff1805bebe9b52d01e7136e Mon Sep 17 00:00:00 2001 From: memurats Date: Tue, 17 Nov 2026 10:33:55 +0100 Subject: [PATCH 5/7] Add regression tests for hardened user deletion handling --- tests/unit/UserAccounctDeletionJobTest.php | 132 +++++++++++++++---- tests/unit/UserAccountChangeListenerTest.php | 49 ++++++- tests/unit/UserWithdrawTest.php | 64 ++++++--- 3 files changed, 201 insertions(+), 44 deletions(-) diff --git a/tests/unit/UserAccounctDeletionJobTest.php b/tests/unit/UserAccounctDeletionJobTest.php index 4ef7658..8b7259a 100644 --- a/tests/unit/UserAccounctDeletionJobTest.php +++ b/tests/unit/UserAccounctDeletionJobTest.php @@ -53,16 +53,18 @@ public function testValidDisabledUserIsDeleted(): void { ->method('findDeletions') ->willReturnOnConsecutiveCalls([self::UID], []); - $this->userQueries->expects($this->exactly(3)) + $this->userQueries->expects($this->once()) ->method('getDeletionState') ->with(self::UID) ->willReturn($state); $user = $this->getMockForAbstractClass(IUser::class); $user->method('isEnabled')->willReturn(false); - $user->expects($this->once())->method('delete'); + $user->expects($this->once()) + ->method('delete') + ->willReturn(true); - $this->userManager->expects($this->exactly(2)) + $this->userManager->expects($this->once()) ->method('get') ->with(self::UID) ->willReturn($user); @@ -79,9 +81,8 @@ public function testEnabledUserIsNeverDeleted(): void { ->method('findDeletions') ->willReturnOnConsecutiveCalls([self::UID], []); - $this->userQueries->expects($this->once()) - ->method('getDeletionState') - ->willReturn($this->validState()); + $this->userQueries->expects($this->never()) + ->method('getDeletionState'); $user = $this->getMockForAbstractClass(IUser::class); $user->method('isEnabled')->willReturn(true); @@ -89,6 +90,7 @@ public function testEnabledUserIsNeverDeleted(): void { $this->userManager->expects($this->once()) ->method('get') + ->with(self::UID) ->willReturn($user); $this->userQueries->expects($this->once()) @@ -98,10 +100,10 @@ public function testEnabledUserIsNeverDeleted(): void { $this->job->run(null); } - public function testLegacyDeletionMarkerWithoutMetadataIsDisarmed(): void { + public function testLegacyDeletionMarkerWithoutMetadataIsProcessed(): void { $state = $this->validState(); $state['withdrawal'] = null; - $state['markedAt'] = null; + $state['lastAccountChange'] = null; $this->userQueries->expects($this->exactly(2)) ->method('findDeletions') @@ -109,10 +111,51 @@ public function testLegacyDeletionMarkerWithoutMetadataIsDisarmed(): void { $this->userQueries->expects($this->once()) ->method('getDeletionState') + ->with(self::UID) ->willReturn($state); - $this->userManager->expects($this->never()) - ->method('get'); + $user = $this->getMockForAbstractClass(IUser::class); + $user->method('isEnabled')->willReturn(false); + $user->expects($this->once()) + ->method('delete') + ->willReturn(true); + + $this->userManager->expects($this->once()) + ->method('get') + ->with(self::UID) + ->willReturn($user); + + $this->userQueries->expects($this->never()) + ->method('deleteDeletionPreferencesById'); + + $this->userQueries->expects($this->once()) + ->method('deleteUserPreferenceById') + ->with(self::UID); + + $this->job->run(null); + } + + public function testIncompleteNewDeletionMarkerIsDisarmed(): void { + $state = $this->validState(); + $state['withdrawal'] = null; + + $this->userQueries->expects($this->exactly(2)) + ->method('findDeletions') + ->willReturnOnConsecutiveCalls([self::UID], []); + + $this->userQueries->expects($this->once()) + ->method('getDeletionState') + ->with(self::UID) + ->willReturn($state); + + $user = $this->getMockForAbstractClass(IUser::class); + $user->method('isEnabled')->willReturn(false); + $user->expects($this->never())->method('delete'); + + $this->userManager->expects($this->once()) + ->method('get') + ->with(self::UID) + ->willReturn($user); $this->userQueries->expects($this->once()) ->method('deleteDeletionPreferencesById') @@ -131,10 +174,17 @@ public function testNewerAccountStateDisarmsDeletion(): void { $this->userQueries->expects($this->once()) ->method('getDeletionState') + ->with(self::UID) ->willReturn($state); - $this->userManager->expects($this->never()) - ->method('get'); + $user = $this->getMockForAbstractClass(IUser::class); + $user->method('isEnabled')->willReturn(false); + $user->expects($this->never())->method('delete'); + + $this->userManager->expects($this->once()) + ->method('get') + ->with(self::UID) + ->willReturn($user); $this->userQueries->expects($this->once()) ->method('deleteDeletionPreferencesById') @@ -143,10 +193,33 @@ public function testNewerAccountStateDisarmsDeletion(): void { $this->job->run(null); } - public function testChangedDeletionStatePreventsDelete(): void { - $first = $this->validState(); - $second = $this->validState(); - $second['deletion'] = new \DateTimeImmutable('2033-05-18T01:00:01+00:00'); + public function testDeletionCancelledBeforeDeleteIsSkipped(): void { + $this->userQueries->expects($this->exactly(2)) + ->method('findDeletions') + ->willReturnOnConsecutiveCalls([self::UID], []); + + $this->userQueries->expects($this->once()) + ->method('getDeletionState') + ->with(self::UID) + ->willReturn(null); + + $user = $this->getMockForAbstractClass(IUser::class); + $user->method('isEnabled')->willReturn(false); + $user->expects($this->never())->method('delete'); + + $this->userManager->expects($this->once()) + ->method('get') + ->with(self::UID) + ->willReturn($user); + + $this->userQueries->expects($this->never()) + ->method('deleteUserPreferenceById'); + + $this->job->run(null); + } + + public function testDeleteFailureIsPostponedAndPreferencesAreKept(): void { + $state = $this->validState(); $this->userQueries->expects($this->exactly(2)) ->method('findDeletions') @@ -154,16 +227,32 @@ public function testChangedDeletionStatePreventsDelete(): void { $this->userQueries->expects($this->exactly(2)) ->method('getDeletionState') - ->willReturnOnConsecutiveCalls($first, $second); + ->with(self::UID) + ->willReturn($state); $user = $this->getMockForAbstractClass(IUser::class); $user->method('isEnabled')->willReturn(false); - $user->expects($this->never())->method('delete'); + $user->expects($this->once()) + ->method('delete') + ->willReturn(false); $this->userManager->expects($this->once()) ->method('get') + ->with(self::UID) ->willReturn($user); + $this->userQueries->expects($this->never()) + ->method('deleteUserPreferenceById'); + + $this->userQueries->expects($this->once()) + ->method('postponeDeletion') + ->with( + self::UID, + $this->callback(static function (\DateTimeInterface $retryAt): bool { + return $retryAt->getTimestamp() === 2_000_003_600; + }) + ); + $this->job->run(null); } @@ -172,12 +261,12 @@ public function testMissingUserCleansOrphanedPreferences(): void { ->method('findDeletions') ->willReturnOnConsecutiveCalls([self::UID], []); - $this->userQueries->expects($this->once()) - ->method('getDeletionState') - ->willReturn($this->validState()); + $this->userQueries->expects($this->never()) + ->method('getDeletionState'); $this->userManager->expects($this->once()) ->method('get') + ->with(self::UID) ->willReturn(null); $this->userQueries->expects($this->once()) @@ -191,7 +280,6 @@ private function validState(): array { return [ 'deletion' => new \DateTimeImmutable('2033-05-18T01:00:00+00:00'), 'withdrawal' => new \DateTimeImmutable('2033-03-19T01:00:00+00:00'), - 'markedAt' => new \DateTimeImmutable('2033-03-19T01:00:00+00:00'), 'lastAccountChange' => new \DateTimeImmutable('2033-03-19T01:00:00+00:00'), ]; } diff --git a/tests/unit/UserAccountChangeListenerTest.php b/tests/unit/UserAccountChangeListenerTest.php index 844927d..6227c77 100644 --- a/tests/unit/UserAccountChangeListenerTest.php +++ b/tests/unit/UserAccountChangeListenerTest.php @@ -136,7 +136,7 @@ public function testExistingWithdrawalWithChangeTimeSchedulesDeletion(): void { $this->assertSame('Withdrawn', $event->getResult()->getReason()); } - public function testWithdrawalWithoutChangeTimeNeverSchedulesDeletion(): void { + public function testWithdrawalWithoutChangeTimePreservesExistingDeletion(): void { $user = $this->existingUser(false); $this->userService->method('userExists') @@ -145,9 +145,8 @@ public function testWithdrawalWithoutChangeTimeNeverSchedulesDeletion(): void { $this->userService->expects($this->never()) ->method('markDeletion'); - $this->userService->expects($this->once()) - ->method('unmarkDeletion') - ->with(self::UID); + $this->userService->expects($this->never()) + ->method('unmarkDeletion'); $this->userService->expects($this->once()) ->method('update') @@ -165,7 +164,7 @@ public function testWithdrawalWithoutChangeTimeNeverSchedulesDeletion(): void { $this->assertSame('Withdrawn without valid changeTime - deletion not scheduled', $event->getResult()->getReason()); } - public function testMissingBookingClaimNeverSchedulesDeletion(): void { + public function testMissingBookingClaimPreservesExistingDeletion(): void { $user = $this->existingUser(false); $this->userService->method('userExists') @@ -174,9 +173,12 @@ public function testMissingBookingClaimNeverSchedulesDeletion(): void { $this->userService->expects($this->never()) ->method('markDeletion'); + $this->userService->expects($this->never()) + ->method('unmarkDeletion'); + $this->userService->expects($this->once()) - ->method('unmarkDeletion') - ->with(self::UID); + ->method('update') + ->with($user, 'jonny.gyros', 'jonny.gyros@ver.sul.t-online.de', '3 GB', false); $event = $this->event( $this->claims([ @@ -190,6 +192,39 @@ public function testMissingBookingClaimNeverSchedulesDeletion(): void { $this->assertSame('Missing tariff claim - deletion not scheduled', $event->getResult()->getReason()); } + + public function testDeletionSchedulingFailurePreservesExistingDeletion(): void { + $user = $this->existingUser(false); + + $this->userService->method('userExists') + ->willReturn($user); + $this->userService->method('isStaleAccountChange') + ->willReturn(false); + + $this->userService->expects($this->once()) + ->method('markDeletion') + ->willThrowException(new \RuntimeException('write failed')); + + $this->userService->expects($this->never()) + ->method('unmarkDeletion'); + + $this->userService->expects($this->once()) + ->method('update') + ->with($user, 'jonny.gyros', 'jonny.gyros@ver.sul.t-online.de', '3 GB', false); + + $event = $this->event( + $this->claims([ + 'urn:telekom.com:f556' => '0', + 'changeTime' => '2030-01-01T00:00:00Z', + ]) + ); + + $this->listener->handle($event); + + $this->assertFalse($event->getResult()->isAccessAllowed()); + $this->assertSame('Deletion scheduling failed safely', $event->getResult()->getReason()); + } + public function testStaleWithdrawalIsIgnored(): void { $user = $this->existingUser(true); diff --git a/tests/unit/UserWithdrawTest.php b/tests/unit/UserWithdrawTest.php index 29ce087..a1d3471 100644 --- a/tests/unit/UserWithdrawTest.php +++ b/tests/unit/UserWithdrawTest.php @@ -40,7 +40,6 @@ public function setUp(): void { $this->appValues = [ 'userretention' => 'P60D', - 'userdeletionsafetydelay' => 'PT0S', ]; $this->config->method('getAppValue') @@ -83,43 +82,78 @@ public function testWithdrawalDateWithoutTimestampIsNull(): void { $this->assertNull($this->accountService->withdrawDate(new \stdClass())); } - public function testMarkDeletionDefaultRetention(): void { + public function testOldWithdrawalGetsFullRetentionFromLocalObservation(): void { $userId = '12004901000000000XXXXXXX'; - $withdrawal = new \DateTimeImmutable('2030-08-03T16:05:06+00:00'); - $expected = $withdrawal->add(new \DateInterval('P60D')); + $withdrawal = new \DateTimeImmutable('2021-08-03T16:05:06+00:00'); + $retention = new \DateInterval('P60D'); + $before = new \DateTimeImmutable(); $deletionDate = $this->userService->markDeletion($userId, $withdrawal); + $after = new \DateTimeImmutable(); $this->assertNotNull($deletionDate); - $this->assertSame($expected->getTimestamp(), $deletionDate->getTimestamp()); + $this->assertGreaterThanOrEqual($before->add($retention)->getTimestamp(), $deletionDate->getTimestamp()); + $this->assertLessThanOrEqual($after->add($retention)->getTimestamp(), $deletionDate->getTimestamp()); $this->assertSame($withdrawal->getTimestamp(), (int)$this->userValues[$userId]['withdrawal']); - $this->assertSame($expected->getTimestamp(), (int)$this->userValues[$userId]['deletion']); $this->assertSame($withdrawal->getTimestamp(), (int)$this->userValues[$userId]['last_account_change']); + $this->assertArrayNotHasKey('deletion_marked_at', $this->userValues[$userId]); } - public function testOldWithdrawalGetsLocalSafetyDelay(): void { + public function testRepeatedWithdrawalKeepsExistingDeletionDate(): void { $userId = '12004901000000000XXXXXXX'; $withdrawal = new \DateTimeImmutable('2021-08-03T16:05:06+00:00'); - $this->appValues['userdeletionsafetydelay'] = 'P1D'; + $firstDeletionDate = $this->userService->markDeletion($userId, $withdrawal); + $secondDeletionDate = $this->userService->markDeletion($userId, $withdrawal); - $before = time(); - $deletionDate = $this->userService->markDeletion($userId, $withdrawal); - $after = time(); + $this->assertNotNull($firstDeletionDate); + $this->assertNotNull($secondDeletionDate); + $this->assertSame($firstDeletionDate->getTimestamp(), $secondDeletionDate->getTimestamp()); + $this->assertSame($firstDeletionDate->getTimestamp(), (int)$this->userValues[$userId]['deletion']); + } + + public function testFutureWithdrawalIsClampedToCurrentTime(): void { + $userId = '12004901000000000XXXXXXX'; + $futureWithdrawal = (new \DateTimeImmutable())->add(new \DateInterval('P1D')); + $retention = new \DateInterval('P60D'); + + $before = new \DateTimeImmutable(); + $deletionDate = $this->userService->markDeletion($userId, $futureWithdrawal); + $after = new \DateTimeImmutable(); $this->assertNotNull($deletionDate); - $this->assertGreaterThanOrEqual($before + 86400, $deletionDate->getTimestamp()); - $this->assertLessThanOrEqual($after + 86401, $deletionDate->getTimestamp()); + + $storedWithdrawal = (int)$this->userValues[$userId]['withdrawal']; + $this->assertGreaterThanOrEqual($before->getTimestamp(), $storedWithdrawal); + $this->assertLessThanOrEqual($after->getTimestamp(), $storedWithdrawal); + $this->assertSame($storedWithdrawal, (int)$this->userValues[$userId]['last_account_change']); + + $this->assertGreaterThanOrEqual($before->add($retention)->getTimestamp(), $deletionDate->getTimestamp()); + $this->assertLessThanOrEqual($after->add($retention)->getTimestamp(), $deletionDate->getTimestamp()); + } + + public function testRecordAccountChangeTimeClampsFutureTimestamp(): void { + $userId = '12004901000000000XXXXXXX'; + $futureChange = (new \DateTimeImmutable())->add(new \DateInterval('P1D')); + + $before = new \DateTimeImmutable(); + $result = $this->userService->recordAccountChangeTime($userId, $futureChange); + $after = new \DateTimeImmutable(); + + $this->assertTrue($result); + $stored = (int)$this->userValues[$userId]['last_account_change']; + $this->assertGreaterThanOrEqual($before->getTimestamp(), $stored); + $this->assertLessThanOrEqual($after->getTimestamp(), $stored); } public function testStaleWithdrawalIsRejected(): void { $userId = '12004901000000000XXXXXXX'; - $this->userValues[$userId]['last_account_change'] = (new \DateTimeImmutable('2030-08-04T00:00:00+00:00')) + $this->userValues[$userId]['last_account_change'] = (new \DateTimeImmutable('2025-08-04T00:00:00+00:00')) ->getTimestamp(); - $result = $this->userService->markDeletion($userId, new \DateTimeImmutable('2030-08-03T00:00:00+00:00')); + $result = $this->userService->markDeletion($userId, new \DateTimeImmutable('2025-08-03T00:00:00+00:00')); $this->assertNull($result); $this->assertArrayNotHasKey('deletion', $this->userValues[$userId]); From 969b59f203b2f1196868baece41a46e9ca30214d Mon Sep 17 00:00:00 2001 From: Mauro Mura Date: Tue, 17 Nov 2026 12:06:20 +0100 Subject: [PATCH 6/7] Add copyright and author comments to UserQueries.php Added copyright and author information to UserQueries.php --- lib/Db/UserQueries.php | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/lib/Db/UserQueries.php b/lib/Db/UserQueries.php index bcf16fc..684120f 100644 --- a/lib/Db/UserQueries.php +++ b/lib/Db/UserQueries.php @@ -1,4 +1,11 @@ + * @author Mauro Mura + * + * SPDX-License-Identifier: AGPL-3.0-or-later + */ declare(strict_types=1); From 6dd57a3290ed495772b6931d4df8ad8e4e4d21ad Mon Sep 17 00:00:00 2001 From: Mauro Mura Date: Tue, 17 Nov 2026 12:06:53 +0100 Subject: [PATCH 7/7] Add strict types declaration to UserQueries.php --- lib/Db/UserQueries.php | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/lib/Db/UserQueries.php b/lib/Db/UserQueries.php index 684120f..1d40347 100644 --- a/lib/Db/UserQueries.php +++ b/lib/Db/UserQueries.php @@ -1,4 +1,7 @@ @@ -7,8 +10,6 @@ * SPDX-License-Identifier: AGPL-3.0-or-later */ -declare(strict_types=1); - namespace OCA\NextMagentaCloudProvisioning\Db; use OCA\NextMagentaCloudProvisioning\AppInfo\Application;