diff --git a/lib/Db/UserQueries.php b/lib/Db/UserQueries.php index a19b87e..1d40347 100644 --- a/lib/Db/UserQueries.php +++ b/lib/Db/UserQueries.php @@ -1,37 +1,28 @@ - * + * @copyright Copyright (c) 2026, T-Systems International GmbH * @author Bernd Rederlechner + * @author Mauro Mura * - * @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 . - * + * SPDX-License-Identifier: AGPL-3.0-or-later */ 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,19 +31,20 @@ 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(); $qb->select('userid') ->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 +62,149 @@ 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 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, + * lastAccountChange: ?\DateTimeImmutable + * }|null + */ + public function getDeletionState(string $userId): ?array { $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('configvalue') + $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($qb->expr()->eq('configkey', $qb->createNamedParameter('deletion'))) - ->setMaxResults(1); + ->andWhere($keyExpression); $result = $qb->execute(); - $value = $result->fetchOne(); + + $values = []; + while ($row = $result->fetch()) { + $values[(string)$row['configkey']] = $row['configvalue']; + } + $result->closeCursor(); - if ($value === false || $value === null || $value === '') { + $deletion = $this->dateTimeFromPreferenceValue($values['deletion'] ?? null); + if ($deletion === null) { return null; } - $deletionDate = new \DateTime(); - $deletionDate->setTimestamp((int)$value); + return [ + 'deletion' => $deletion, + 'withdrawal' => $this->dateTimeFromPreferenceValue($values['withdrawal'] ?? null), + 'lastAccountChange' => $this->dateTimeFromPreferenceValue($values['last_account_change'] ?? null), + ]; + } + + /** + * 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. + * + * 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])), + $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($keyExpression) + ->execute(); - return $deletionDate; + return true; + } + + /** + * Move a failed deletion attempt out of the current batch. + */ + 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))) + ->andWhere($qb->expr()->eq('appid', $qb->createNamedParameter(Application::APP_ID))) + ->andWhere($qb->expr()->eq('configkey', $qb->createNamedParameter('deletion'))) + ->execute(); + + 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(); + ->where($qb->expr()->eq('userid', $qb->createNamedParameter($userId))) + ->execute(); + + 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))) + ->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(); + + return $this->dateTimeFromPreferenceValue($value); + } + + private function dateTimeFromPreferenceValue(mixed $value): ?\DateTimeImmutable { + if ($value === false || $value === null || $value === '' || !is_numeric($value)) { + return null; + } + + $timestamp = (int)$value; + if ($timestamp <= 0) { + return null; + } - return true; // Return true to indicate successful deletion + 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/UserAccountRules.php b/lib/Rules/UserAccountRules.php index cdc9359..3543c83 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,342 @@ 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))) { + $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; + } + } + + 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->update($user, $displayname, $mainEmail, $quota, false); - return array('allowed' => false, 'reason' => 'Withdrawn', 'changed' => true, 'redirect' => $redirect); + $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->update($user, $displayname, $mainEmail, $quota, false); + + $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->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..88b677b 100644 --- a/lib/User/NmcUserService.php +++ b/lib/User/NmcUserService.php @@ -21,6 +21,11 @@ // classes from user_oidc app class NmcUserService { + private const KEY_DELETION = 'deletion'; + private const KEY_WITHDRAWAL = 'withdrawal'; + private const KEY_LAST_ACCOUNT_CHANGE = 'last_account_change'; + + private const DEFAULT_RETENTION = 'P60D'; /** @var IUserManager */ private $userManager; @@ -152,50 +157,175 @@ 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 { + $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()) { + 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 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. + * + * 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, \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 { + $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' => $withdrawal->format(\DateTimeInterface::ATOM), + 'lastAccountChange' => $this->getLastAccountChangeTime($userId)?->format(\DateTimeInterface::ATOM), + ]); + return null; + } + + $existingWithdrawal = $this->getUserTimestamp($userId, self::KEY_WITHDRAWAL); + $existingDeletion = $this->getDeletionDateTime($userId); + + if ( + $existingWithdrawal !== null + && $existingDeletion !== null + && $existingWithdrawal->getTimestamp() === $withdrawal->getTimestamp() + ) { + return $existingDeletion; + } + + $retention = $this->getConfiguredInterval('userretention', self::DEFAULT_RETENTION); + $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', [ + '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), 'deletionDate' => $deletionDate->format(\DateTimeInterface::ATOM), - 'retention' => $this->config->getAppValue('nmcprovisioning', 'userretention', "P60D"), + 'retention' => $this->config->getAppValue('nmcprovisioning', 'userretention', self::DEFAULT_RETENTION), ]); - $this->config->setUserValue($userId, Application::APP_ID, 'deletion', $deletionDate->getTimestamp()); + /* + * 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_DELETION, $deletionDate->getTimestamp()); + $this->config->setUserValue($userId, Application::APP_ID, self::KEY_WITHDRAWAL, $withdrawal->getTimestamp()); + + // Clean up metadata written by earlier revisions of this hardening PR. + $this->config->deleteUserValue($userId, Application::APP_ID, 'deletion_marked_at'); 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, '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 +444,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..22d9f91 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 + $startTime = $this->timeFactory->getTime(); - $limit = 10; + while ($this->timeFactory->getTime() - $startTime < self::MAX_EXECUTION_TIME) { + $refTime = $this->now(); + $expiredUids = $this->userQueries->findDeletions($refTime, self::BATCH_SIZE); - while (time() - $startTime < $maxExecutionTime) { - $refTime = new \DateTime(); - $expiredUids = $this->userQueries->findDeletions($refTime, $limit); - - if (empty($expiredUids)) { + if ($expiredUids === []) { $this->logger->info('No more users to delete, exiting job.'); break; } @@ -57,59 +57,130 @@ 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); + } + } + + $this->logger->info('User account deletion job ended'); + } + + private function processUser(string $uid): void { + try { + $user = $this->userManager->get($uid); + + if ($user === null) { + $this->logger->warning("User {$uid} not found, removing orphaned preferences."); + $this->userQueries->deleteUserPreferenceById($uid); + return; + } + + /* + * 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.'); + $this->userQueries->deleteDeletionPreferencesById($uid); + return; + } + + /* + * Validate the deletion decision once directly against the preferences DB + * immediately before delete(). getDeletionState() performs a single query. + */ + $state = $this->userQueries->getDeletionState($uid); - if ($deletionDate === null) { - $this->logger->warning("Skipping $uid, deletion entry no longer exists."); - continue; - } + if ($state === null) { + $this->logger->warning("Skipping {$uid}: deletion was cancelled before delete()."); + return; + } - $now = new \DateTime(); - if ($deletionDate > $now) { - $this->logger->warning( - "Skipping $uid, deletion not due yet: " . $deletionDate->format(\DateTimeInterface::ATOM) - ); - continue; - } + if ($state['deletion'] > $this->now()) { + $this->logger->warning("Skipping {$uid}, deletion not due yet: " . $state['deletion']->format(\DateTimeInterface::ATOM)); + return; + } - $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['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; + } - $this->logger->info("Deleting $uid, deletion due since " . $deletionDate->format(\DateTimeInterface::ATOM)); + $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; + } - $startDeletionTime = time(); + $this->logger->info("Deleting {$uid}, deletion due since " . $state['deletion']->format(\DateTimeInterface::ATOM)); - $user->delete(); + $startDeletionTime = $this->timeFactory->getTime(); - if (time() - $startDeletionTime > $maxDeletionTimePerUser) { - $this->logger->warning("User $uid deletion took longer than 30 minutes, skipping."); - continue; - } + if (!$user->delete()) { + throw new \RuntimeException("User deletion returned false for {$uid}"); + } - $this->userQueries->deleteUserPreferenceById($uid); + $duration = $this->timeFactory->getTime() - $startDeletionTime; - $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', - ]); + if ($duration > self::SLOW_DELETION_WARNING) { + $this->logger->warning("User {$uid} deletion took longer than 30 minutes " . "({$duration} seconds)."); + } - continue; + $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()); } + } diff --git a/tests/unit/UserAccounctDeletionJobTest.php b/tests/unit/UserAccounctDeletionJobTest.php index 8e78cbb..8b7259a 100644 --- a/tests/unit/UserAccounctDeletionJobTest.php +++ b/tests/unit/UserAccounctDeletionJobTest.php @@ -14,72 +14,273 @@ 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(): void { + $this->userQueries->expects($this->once()) + ->method('findDeletions') + ->willReturn([]); + + $this->userManager->expects($this->never()) + ->method('get'); + + $this->job->run(null); } - public function testJobRunNone() { + public function testValidDisabledUserIsDeleted(): void { + $state = $this->validState(); + + $this->userQueries->expects($this->exactly(2)) + ->method('findDeletions') + ->willReturnOnConsecutiveCalls([self::UID], []); + $this->userQueries->expects($this->once()) - ->method("findDeletions") - ->willReturn([]); // Keine Benutzer zum Löschen - - // Mock für den Benutzer, der nie gelöscht wird + ->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') + ->willReturn(true); + + $this->userManager->expects($this->once()) + ->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->never()) + ->method('getDeletionState'); + $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') + ->with(self::UID) ->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 testLegacyDeletionMarkerWithoutMetadataIsProcessed(): void { + $state = $this->validState(); + $state['withdrawal'] = null; + $state['lastAccountChange'] = 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') + ->with(self::UID) + ->willReturn($state); + + $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->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') + ->with(self::UID) ->willReturn($user); - + + $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') + ->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') + ->with(self::UID); + + $this->job->run(null); + } + + 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') + ->willReturnOnConsecutiveCalls([self::UID], []); + + $this->userQueries->expects($this->exactly(2)) + ->method('getDeletionState') + ->with(self::UID) + ->willReturn($state); + + $user = $this->getMockForAbstractClass(IUser::class); + $user->method('isEnabled')->willReturn(false); + $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); + } + + public function testMissingUserCleansOrphanedPreferences(): void { + $this->userQueries->expects($this->exactly(2)) + ->method('findDeletions') + ->willReturnOnConsecutiveCalls([self::UID], []); + + $this->userQueries->expects($this->never()) + ->method('getDeletionState'); + + $this->userManager->expects($this->once()) + ->method('get') + ->with(self::UID) + ->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'), + 'lastAccountChange' => new \DateTimeImmutable('2033-03-19T01:00:00+00:00'), + ]; + } } diff --git a/tests/unit/UserAccountChangeListenerTest.php b/tests/unit/UserAccountChangeListenerTest.php index cbc8c20..6227c77 100644 --- a/tests/unit/UserAccountChangeListenerTest.php +++ b/tests/unit/UserAccountChangeListenerTest.php @@ -14,373 +14,348 @@ 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->never()) + ->method('unmarkDeletion'); $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")); - $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 testMissingBookingClaimPreservesExistingDeletion(): void { + $user = $this->existingUser(false); + + $this->userService->method('userExists') + ->willReturn($user); + + $this->userService->expects($this->never()) + ->method('markDeletion'); + + $this->userService->expects($this->never()) + ->method('unmarkDeletion'); - 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); + ->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([ + '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://telekom.example.com/', $event->getResult()->getRedirectUrl()); + $this->assertSame('Missing tariff claim - deletion not scheduled', $event->getResult()->getReason()); } - public function testWithdrawOTT() { - $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("setUserValue") - ->with($this->equalTo('12004901000000000XXXXXXX'), Application::APP_ID, $this->equalTo("deletion")); + ->method('markDeletion') + ->willThrowException(new \RuntimeException('write failed')); + + $this->userService->expects($this->never()) + ->method('unmarkDeletion'); + $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/ott", $event->getResult()->getRedirectUrl()); + $this->assertSame('Deletion scheduling failed safely', $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); + + $this->userService->method('userExists') + ->willReturn($user); + $this->userService->method('isStaleAccountChange') + ->willReturn(true); - $event = new UserAccountChangeEvent("12004901000000000XXXXXXX", "jonny.gyros", - "jonny.gyros@ver.sul.t-online.de", "3 GB", $oidcClaims); + $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..a1d3471 100644 --- a/tests/unit/UserWithdrawTest.php +++ b/tests/unit/UserWithdrawTest.php @@ -17,132 +17,173 @@ 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', + ]; + + $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 testDeletionDateOidcClaims() { - $oidcClaims = json_decode(<<accountService->withdrawDate($oidcClaims); - $this->assertEquals('2021-11-23T16:02:10+0000', $deletionTime-> format(\DateTimeInterface::ISO8601)); + 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 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 testWithdrawalDateDoesNotFallbackToAuthTime(): void { + $claims = new \stdClass(); + $claims->auth_time = 1637683330; + + $this->assertNull($this->accountService->withdrawDate($claims)); } - 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 testWithdrawalDateWithoutTimestampIsNull(): void { + $this->assertNull($this->accountService->withdrawDate(new \stdClass())); } - 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 testOldWithdrawalGetsFullRetentionFromLocalObservation(): void { + $userId = '12004901000000000XXXXXXX'; + $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->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($withdrawal->getTimestamp(), (int)$this->userValues[$userId]['last_account_change']); + $this->assertArrayNotHasKey('deletion_marked_at', $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 testRepeatedWithdrawalKeepsExistingDeletionDate(): void { + $userId = '12004901000000000XXXXXXX'; + $withdrawal = new \DateTimeImmutable('2021-08-03T16:05:06+00:00'); + + $firstDeletionDate = $this->userService->markDeletion($userId, $withdrawal); + $secondDeletionDate = $this->userService->markDeletion($userId, $withdrawal); + + $this->assertNotNull($firstDeletionDate); + $this->assertNotNull($secondDeletionDate); + $this->assertSame($firstDeletionDate->getTimestamp(), $secondDeletionDate->getTimestamp()); + $this->assertSame($firstDeletionDate->getTimestamp(), (int)$this->userValues[$userId]['deletion']); } - 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')); + 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); + + $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('2025-08-04T00:00:00+00:00')) + ->getTimestamp(); + + $result = $this->userService->markDeletion($userId, new \DateTimeImmutable('2025-08-03T00:00:00+00:00')); + + $this->assertNull($result); + $this->assertArrayNotHasKey('deletion', $this->userValues[$userId]); + } + + 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']); + } + + 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]); }); } }