Skip to content

Commit

Permalink
Merge pull request #40026 from lhsazevedo/auth-token-commands
Browse files Browse the repository at this point in the history
feat: Add auth token list and delete commands
  • Loading branch information
nickvergessen authored Aug 29, 2023
2 parents 2220620 + 79bc6ba commit 6f520f2
Show file tree
Hide file tree
Showing 14 changed files with 471 additions and 12 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OC\Core\Command\User;
namespace OC\Core\Command\User\AuthTokens;

use OC\Authentication\Events\AppPasswordCreatedEvent;
use OC\Authentication\Token\IProvider;
Expand All @@ -40,7 +40,7 @@
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\Question;

class AddAppPassword extends Command {
class Add extends Command {
public function __construct(
protected IUserManager $userManager,
protected IProvider $tokenProvider,
Expand All @@ -52,7 +52,8 @@ public function __construct(

protected function configure() {
$this
->setName('user:add-app-password')
->setName('user:auth-tokens:add')
->setAliases(['user:add-app-password'])
->setDescription('Add app password for the named user')
->addArgument(
'user',
Expand Down
120 changes: 120 additions & 0 deletions core/Command/User/AuthTokens/Delete.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
<?php
/**
* @copyright Copyright (c) 2023 Lucas Azevedo <lhs_azevedo@hotmail.com>
*
* @author Lucas Azevedo <lhs_azevedo@hotmail.com>
*
* @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 <http://www.gnu.org/licenses/>.
*
*/
namespace OC\Core\Command\User\AuthTokens;

use DateTimeImmutable;
use OC\Core\Command\Base;
use OC\Authentication\Token\IProvider;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Exception\RuntimeException;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class Delete extends Base {
public function __construct(
protected IProvider $tokenProvider,
) {
parent::__construct();
}

protected function configure(): void {
$this
->setName('user:auth-tokens:delete')
->setDescription('Deletes an authentication token')
->addArgument(
'uid',
InputArgument::REQUIRED,
'ID of the user to delete tokens for'
)
->addArgument(
'id',
InputArgument::OPTIONAL,
'ID of the auth token to delete'
)
->addOption(
'last-used-before',
null,
InputOption::VALUE_REQUIRED,
'Delete tokens last used before a given date.'
);
}

protected function execute(InputInterface $input, OutputInterface $output): int {
$uid = $input->getArgument('uid');
$id = (int) $input->getArgument('id');
$before = $input->getOption('last-used-before');

if ($before) {
if ($id) {
throw new RuntimeException('Option --last-used-before cannot be used with [<id>]');
}

return $this->deleteLastUsedBefore($uid, $before);
}

if (!$id) {
throw new RuntimeException('Not enough arguments. Specify the token <id> or use the --last-used-before option.');
}
return $this->deleteById($uid, $id);
}

protected function deleteById(string $uid, int $id): int {
$this->tokenProvider->invalidateTokenById($uid, $id);

return Command::SUCCESS;
}

protected function deleteLastUsedBefore(string $uid, string $before): int {
$date = $this->parseDateOption($before);
if (!$date) {
throw new RuntimeException('Invalid date format. Acceptable formats are: ISO8601 (w/o fractions), "YYYY-MM-DD" and Unix time in seconds.');
}

$this->tokenProvider->invalidateLastUsedBefore($uid, $date->getTimestamp());

return Command::SUCCESS;
}

/**
* @return \DateTimeImmutable|false
*/
protected function parseDateOption(string $input) {
$date = false;

// Handle Unix timestamp
if (filter_var($input, FILTER_VALIDATE_INT)) {
return new DateTimeImmutable('@' . $input);
}

// ISO8601
$date = DateTimeImmutable::createFromFormat(DateTimeImmutable::ATOM, $input);
if ($date) {
return $date;
}

// YYYY-MM-DD
return DateTimeImmutable::createFromFormat('!Y-m-d', $input);
}
}
100 changes: 100 additions & 0 deletions core/Command/User/AuthTokens/ListCommand.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
<?php
/**
* @copyright Copyright (c) 2023 Lucas Azevedo <lhs_azevedo@hotmail.com>
*
* @author Lucas Azevedo <lhs_azevedo@hotmail.com>
*
* @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 <http://www.gnu.org/licenses/>.
*
*/
namespace OC\Core\Command\User\AuthTokens;

use OC\Core\Command\Base;
use OC\Authentication\Token\IProvider;
use OC\Authentication\Token\IToken;
use OCP\IUserManager;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class ListCommand extends Base {
public function __construct(
protected IUserManager $userManager,
protected IProvider $tokenProvider,
) {
parent::__construct();
}

protected function configure(): void {
parent::configure();

$this
->setName('user:auth-tokens:list')
->setDescription('List authentication tokens of an user')
->addArgument(
'user',
InputArgument::REQUIRED,
'User to list auth tokens for'
);
}

protected function execute(InputInterface $input, OutputInterface $output): int {
$user = $this->userManager->get($input->getArgument('user'));

if (is_null($user)) {
$output->writeln('<error>user not found</error>');
return 1;
}

$tokens = $this->tokenProvider->getTokenByUser($user->getUID());

$tokens = array_map(function (IToken $token) use ($input): mixed {
$sensitive = [
'password',
'password_hash',
'token',
'public_key',
'private_key',
];
$data = array_diff_key($token->jsonSerialize(), array_flip($sensitive));

if ($input->getOption('output') === self::OUTPUT_FORMAT_PLAIN) {
$data = $this->formatTokenForPlainOutput($data);
}

return $data;
}, $tokens);

$this->writeTableInOutputFormat($input, $output, $tokens);

return 0;
}

public function formatTokenForPlainOutput(array $token): array {
$token['scope'] = implode(', ', array_keys(array_filter($token['scope'] ?? [])));

$token['lastActivity'] = date(DATE_ATOM, $token['lastActivity']);

$token['type'] = match ($token['type']) {
IToken::TEMPORARY_TOKEN => 'temporary',
IToken::PERMANENT_TOKEN => 'permanent',
IToken::WIPE_TOKEN => 'wipe',
default => $token['type'],
};

return $token;
}
}
4 changes: 3 additions & 1 deletion core/register_command.php
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,9 @@
$application->add(new OC\Core\Command\User\ListCommand(\OC::$server->getUserManager(), \OC::$server->getGroupManager()));
$application->add(new OC\Core\Command\User\Info(\OC::$server->getUserManager(), \OC::$server->getGroupManager()));
$application->add(new OC\Core\Command\User\SyncAccountDataCommand(\OC::$server->getUserManager(), \OC::$server->get(\OCP\Accounts\IAccountManager::class)));
$application->add(new OC\Core\Command\User\AddAppPassword(\OC::$server->get(\OCP\IUserManager::class), \OC::$server->get(\OC\Authentication\Token\IProvider::class), \OC::$server->get(\OCP\Security\ISecureRandom::class), \OC::$server->get(\OCP\EventDispatcher\IEventDispatcher::class)));
$application->add(\OC::$server->get(\OC\Core\Command\User\AuthTokens\Add::class));
$application->add(\OC::$server->get(\OC\Core\Command\User\AuthTokens\ListCommand::class));
$application->add(\OC::$server->get(\OC\Core\Command\User\AuthTokens\Delete::class));

$application->add(new OC\Core\Command\Group\Add(\OC::$server->getGroupManager()));
$application->add(new OC\Core\Command\Group\Delete(\OC::$server->getGroupManager()));
Expand Down
4 changes: 3 additions & 1 deletion lib/composer/composer/autoload_classmap.php
Original file line number Diff line number Diff line change
Expand Up @@ -1042,7 +1042,9 @@
'OC\\Core\\Command\\TwoFactorAuth\\State' => $baseDir . '/core/Command/TwoFactorAuth/State.php',
'OC\\Core\\Command\\Upgrade' => $baseDir . '/core/Command/Upgrade.php',
'OC\\Core\\Command\\User\\Add' => $baseDir . '/core/Command/User/Add.php',
'OC\\Core\\Command\\User\\AddAppPassword' => $baseDir . '/core/Command/User/AddAppPassword.php',
'OC\\Core\\Command\\User\\AuthTokens\\Add' => $baseDir . '/core/Command/User/AuthTokens/Add.php',
'OC\\Core\\Command\\User\\AuthTokens\\Delete' => $baseDir . '/core/Command/User/AuthTokens/Delete.php',
'OC\\Core\\Command\\User\\AuthTokens\\ListCommand' => $baseDir . '/core/Command/User/AuthTokens/ListCommand.php',
'OC\\Core\\Command\\User\\Delete' => $baseDir . '/core/Command/User/Delete.php',
'OC\\Core\\Command\\User\\Disable' => $baseDir . '/core/Command/User/Disable.php',
'OC\\Core\\Command\\User\\Enable' => $baseDir . '/core/Command/User/Enable.php',
Expand Down
4 changes: 3 additions & 1 deletion lib/composer/composer/autoload_static.php
Original file line number Diff line number Diff line change
Expand Up @@ -1075,7 +1075,9 @@ class ComposerStaticInit749170dad3f5e7f9ca158f5a9f04f6a2
'OC\\Core\\Command\\TwoFactorAuth\\State' => __DIR__ . '/../../..' . '/core/Command/TwoFactorAuth/State.php',
'OC\\Core\\Command\\Upgrade' => __DIR__ . '/../../..' . '/core/Command/Upgrade.php',
'OC\\Core\\Command\\User\\Add' => __DIR__ . '/../../..' . '/core/Command/User/Add.php',
'OC\\Core\\Command\\User\\AddAppPassword' => __DIR__ . '/../../..' . '/core/Command/User/AddAppPassword.php',
'OC\\Core\\Command\\User\\AuthTokens\\Add' => __DIR__ . '/../../..' . '/core/Command/User/AuthTokens/Add.php',
'OC\\Core\\Command\\User\\AuthTokens\\Delete' => __DIR__ . '/../../..' . '/core/Command/User/AuthTokens/Delete.php',
'OC\\Core\\Command\\User\\AuthTokens\\ListCommand' => __DIR__ . '/../../..' . '/core/Command/User/AuthTokens/ListCommand.php',
'OC\\Core\\Command\\User\\Delete' => __DIR__ . '/../../..' . '/core/Command/User/Delete.php',
'OC\\Core\\Command\\User\\Disable' => __DIR__ . '/../../..' . '/core/Command/User/Disable.php',
'OC\\Core\\Command\\User\\Enable' => __DIR__ . '/../../..' . '/core/Command/User/Enable.php',
Expand Down
5 changes: 5 additions & 0 deletions lib/private/Authentication/Token/IProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,11 @@ public function invalidateTokenById(string $uid, int $id);
*/
public function invalidateOldTokens();

/**
* Invalidate (delete) tokens last used before a given date
*/
public function invalidateLastUsedBefore(string $uid, int $before): void;

/**
* Save the updated token
*
Expand Down
4 changes: 4 additions & 0 deletions lib/private/Authentication/Token/Manager.php
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,10 @@ public function invalidateOldTokens() {
$this->publicKeyTokenProvider->invalidateOldTokens();
}

public function invalidateLastUsedBefore(string $uid, int $before): void {
$this->publicKeyTokenProvider->invalidateLastUsedBefore($uid, $before);
}

/**
* @param IToken $token
* @param string $oldTokenId
Expand Down
9 changes: 9 additions & 0 deletions lib/private/Authentication/Token/PublicKeyTokenMapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,15 @@ public function invalidateOld(int $olderThan, int $remember = IToken::DO_NOT_REM
->execute();
}

public function invalidateLastUsedBefore(string $uid, int $before): int {
$qb = $this->db->getQueryBuilder();
$qb->delete($this->tableName)
->where($qb->expr()->eq('uid', $qb->createNamedParameter($uid)))
->andWhere($qb->expr()->lt('last_activity', $qb->createNamedParameter($before, IQueryBuilder::PARAM_INT)))
->andWhere($qb->expr()->eq('version', $qb->createNamedParameter(PublicKeyToken::VERSION, IQueryBuilder::PARAM_INT)));
return $qb->executeStatement();
}

/**
* Get the user UID for the given token
*
Expand Down
6 changes: 6 additions & 0 deletions lib/private/Authentication/Token/PublicKeyTokenProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,12 @@ public function invalidateOldTokens() {
$this->mapper->invalidateOld($rememberThreshold, IToken::REMEMBER);
}

public function invalidateLastUsedBefore(string $uid, int $before): void {
$this->cache->clear();

$this->mapper->invalidateLastUsedBefore($uid, $before);
}

public function updateToken(IToken $token) {
$this->cache->clear();

Expand Down
Loading

0 comments on commit 6f520f2

Please sign in to comment.