Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

✨ Add admin API routes to get deleted users and to update login time #669

Merged
merged 7 commits into from
Nov 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions .env
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,14 @@ MAILER_DELIVERY_ADDRESS="[email protected]"
DATABASE_URL="mysql://mail:[email protected]:3306/mail?charset=utf8mb4"
###< doctrine/doctrine-bundle ###

### Enable retention API ###
# Set to `true` to enable retention API
RETENTION_API_ENABLED=false
# Access is restricted to these IPs (supports subnets like `10.0.0.1/24`)
RETENTION_API_IP_ALLOWLIST="127.0.0.1, ::1"
# Warning: set a secure access token
RETENTION_API_ACCESS_TOKEN="insecure"

### Enable keycloak API ###
# Set to `true` to enable keycloak API
KEYCLOAK_API_ENABLED=false
Expand All @@ -72,8 +80,8 @@ POSTFIX_API_IP_ALLOWLIST="127.0.0.1, ::1"
# Warning: set a secure access token
POSTFIX_API_ACCESS_TOKEN="insecure"

### Enable DOVECOT API ###
# Set to `true` to enable DOVECOT API
### Enable dovecot API ###
# Set to `true` to enable dovecot API
DOVECOT_API_ENABLED=false
# Access is restricted to these IPs (supports subnets like `10.0.0.1/24`)
DOVECOT_API_IP_ALLOWLIST="127.0.0.1, ::1"
Expand Down
10 changes: 7 additions & 3 deletions .env.test
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,18 @@ DOVECOT_MAIL_GID="5000"
WEBMAIL_URL="https://webmail.example.org"
WKD_DIRECTORY="/tmp/.well-known/openpgpkey"
WKD_FORMAT="advanced"
RETENTION_API_ENABLED=true
RETENTION_API_ACCESS_TOKEN="insecure"
RETENTION_API_IP_ALLOWLIST="127.0.0.1, ::1"
KEYCLOAK_API_ENABLED=true
KEYCLOAK_API_IP_ALLOWLIST="127.0.0.1, ::1"
KEYCLOAK_API_ACCESS_TOKEN="insecure"
KEYCLOAK_API_IP_ALLOWLIST="127.0.0.1, ::1"
POSTFIX_API_ENABLED=true
POSTFIX_API_IP_ALLOWLIST="127.0.0.1, ::1"
POSTFIX_API_ACCESS_TOKEN="insecure"
POSTFIX_API_IP_ALLOWLIST="127.0.0.1, ::1"
ROUNDCUBE_API_ENABLED=true
ROUNDCUBE_API_ACCESS_TOKEN="insecure"
ROUNDCUBE_API_IP_ALLOWLIST="127.0.0.1, ::1"
DOVECOT_API_ENABLED=true
DOVECOT_API_IP_ALLOWLIST="127.0.0.1, ::1"
DOVECOT_API_ACCESS_TOKEN="insecure"
DOVECOT_API_IP_ALLOWLIST="127.0.0.1, ::1"
17 changes: 17 additions & 0 deletions config/packages/security.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,11 @@ security:
# Custom UserProvider to allow login via email and localpart (without domain)
user:
id: App\Security\UserProvider
retention:
memory:
users:
- identifier: retention
roles: ['ROLE_RETENTION']
keycloak:
memory:
users:
Expand Down Expand Up @@ -120,6 +125,12 @@ security:
dev:
pattern: ^/(_(profiler|error|wdt)|css|images|js)/
security: false
retention:
pattern: ^/api/retention
stateless: true
provider: retention
access_token:
token_handler: App\Security\RetentionAccessTokenHandler
keycloak:
pattern: ^/api/keycloak
stateless: true
Expand Down Expand Up @@ -185,6 +196,12 @@ security:
- { path: "^/account", roles: ROLE_USER, allow_if: "!is_granted('ROLE_SPAM')" }
- { path: "^/openpgp", roles: ROLE_USER, allow_if: "!is_granted('ROLE_SPAM')" }
- { path: "^/admin", roles: ROLE_DOMAIN_ADMIN }
- {
path: "^/api/retention",
ips: "%env(RETENTION_API_IP_ALLOWLIST)%",
allow_if: "'%env(RETENTION_API_ENABLED)%' == 'true' and is_granted('ROLE_RETENTION')",
}
- { path: "^/api/retention", roles: ROLE_NO_ACCESS }
- {
path: "^/api/keycloak",
ips: "%env(KEYCLOAK_API_IP_ALLOWLIST)%",
Expand Down
4 changes: 4 additions & 0 deletions config/services.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,10 @@ services:
- '@Doctrine\ORM\EntityManagerInterface'
public: true

App\Security\RetentionAccessTokenHandler:
arguments:
$retentionAccessToken: "%env(RETENTION_API_ACCESS_TOKEN)%"

App\Security\KeycloakAccessTokenHandler:
arguments:
$keycloakApiAccessToken: "%env(KEYCLOAK_API_ACCESS_TOKEN)%"
Expand Down
63 changes: 63 additions & 0 deletions src/Controller/RetentionController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
<?php

namespace App\Controller;

use App\Dto\RetentionTouchUserDto;
use App\Entity\Domain;
use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bridge\Doctrine\Attribute\MapEntity;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Attribute\MapRequestPayload;
use Symfony\Component\Routing\Annotation\Route;

class RetentionController extends AbstractController
{
const MESSAGE_TIMESTAMP_IN_FUTURE = 'timestamp in future';

public function __construct(
private readonly EntityManagerInterface $manager,
) {
}

#[Route(path: '/api/retention/{email}/touch', name: 'retention_touch', methods: ['PUT'], stateless: true)]
public function putTouchUser(
#[MapEntity(mapping: ['email' => 'email'])] User $user,
#[MapRequestPayload] RetentionTouchUserDto $requestData,
): Response
{
$now = new \DateTime;
$time = $requestData->getTimestamp()
? new \DateTime('@' . $requestData->getTimestamp())
: $now;

// Check that timestamp is not in future
if ($time > $now) {
return $this->json([
'message' => self::MESSAGE_TIMESTAMP_IN_FUTURE,
], Response::HTTP_BAD_REQUEST);
}

if ($time > $user->getLastLoginTime()) {
$user->setLastLoginTime($time);
$this->manager->persist($user);
$this->manager->flush();
}

return $this->json([]);
}

/**
* List deleted users
*/
#[Route(path: '/api/retention/{domainUrl}/users', name: 'retention_users', methods: ['GET'], stateless: true)]
public function getDeletedUsers(
#[MapEntity(mapping: ['domainUrl' => 'name'])] Domain $domain,
): Response
{
$deletedUsers = $this->manager->getRepository(User::class)->findDeletedUsers($domain);
$deletedUsernames = array_map(static function ($user) { return $user->getEmail(); }, $deletedUsers);
return $this->json($deletedUsernames);
}
}
5 changes: 5 additions & 0 deletions src/DataFixtures/LoadUserData.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ class LoadUserData extends AbstractUserData implements DependentFixtureInterface
['email' => '[email protected]', 'roles' => [Roles::MULTIPLIER], 'totp' => false, 'mailcrypt' => false],
['email' => '[email protected]', 'roles' => [Roles::SUSPICIOUS], 'totp' => false, 'mailcrypt' => false],
['email' => '[email protected]', 'roles' => [Roles::DOMAIN_ADMIN], 'totp' => false, 'mailcrypt' => false],
['email' => '[email protected]', 'roles' => [Roles::USER], 'totp' => false, 'mailcrypt' => false, 'deleted' => true],
];

/**
Expand All @@ -37,6 +38,7 @@ public function load(ObjectManager $manager): void
$splitted = explode('@', (string)$email);
$roles = $user['roles'];
$domain = $manager->getRepository(Domain::class)->findOneBy(['name' => $splitted[1]]);
$deleted = array_key_exists('deleted', $user) && $user['deleted'];

$totpEnabled = $user['totp'];
$mailcryptEnabled = $user['mailcrypt'];
Expand All @@ -50,6 +52,9 @@ public function load(ObjectManager $manager): void
$this->mailCryptKeyHandler->create($user, self::PASSWORD);
$user->setMailCrypt(true);
}
if ($deleted) {
$user->setDeleted(true);
}
$manager->persist($user);
}

Expand Down
18 changes: 18 additions & 0 deletions src/Dto/RetentionTouchUserDto.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php

namespace App\Dto;

class RetentionTouchUserDto
{
private int $timestamp = 0;

public function getTimestamp(): int
{
return $this->timestamp;
}

public function setTimestamp(int $timestamp): void
{
$this->timestamp = $timestamp;
}
}
6 changes: 4 additions & 2 deletions src/Repository/UserRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -78,9 +78,11 @@ public function findInactiveUsers(int $days)
return $this->matching(new Criteria($expression));
}

public function findDeletedUsers(): array
public function findDeletedUsers(?Domain $domain = null): array
{
return $this->findBy(['deleted' => true]);
return $domain
? $this->findBy(['domain' => $domain, 'deleted' => true])
: $this->findBy(['deleted' => true]);
}

public function countUsers(): int
Expand Down
23 changes: 23 additions & 0 deletions src/Security/RetentionAccessTokenHandler.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php

namespace App\Security;

use Symfony\Component\Security\Core\Exception\BadCredentialsException;
use Symfony\Component\Security\Http\AccessToken\AccessTokenHandlerInterface;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;

class RetentionAccessTokenHandler implements AccessTokenHandlerInterface
{
public function __construct(private string $retentionAccessToken)
{
}

public function getUserBadgeFrom(#[\SensitiveParameter] string $accessToken): UserBadge
{
if ($accessToken !== $this->retentionAccessToken) {
throw new BadCredentialsException('Invalid access token');
}

return new UserBadge('retention');
}
}
70 changes: 70 additions & 0 deletions tests/Controller/RetentionControllerTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
<?php

namespace App\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class RetentionControllerTest extends WebTestCase
{
public function testPutTouchUserWrongApiToken(): void
{
$client = static::createClient([], [
'HTTP_Authorization' => 'Bearer wrong',
]);
$client->request('PUT', '/api/retention/[email protected]/touch');

self::assertResponseStatusCodeSame(401);
}

public function testPutTouchUserUnknownUser(): void
{
$client = static::createClient([], [
'HTTP_Authorization' => 'Bearer insecure',
]);

$client->request('PUT', '/api/retention/[email protected]/touch');
self::assertResponseStatusCodeSame(404);
}

public function testPutTouchUserTimestampInFuture(): void
{
$client = static::createClient([], [
'HTTP_Authorization' => 'Bearer insecure',
]);

$client->request('PUT', '/api/retention/[email protected]/touch', ['timestamp' => 999999999999]);
self::assertResponseStatusCodeSame(400);
}

public function testPutTouchUser(): void
{
$client = static::createClient([], [
'HTTP_Authorization' => 'Bearer insecure',
]);

$client->request('PUT', '/api/retention/[email protected]/touch', ['timestamp' => 0]);
self::assertResponseIsSuccessful();
self::assertJsonStringEqualsJsonString('[]', $client->getResponse()->getContent());
}

public function testGetDeletedUsersNonexistantDomain(): void
{
$client = static::createClient([], [
'HTTP_Authorization' => 'Bearer insecure',
]);

$client->request('GET', '/api/retention/nonexistant.org/users');
self::assertResponseStatusCodeSame(404);
}

public function testGetDeletedUsers(): void
{
$client = static::createClient([], [
'HTTP_Authorization' => 'Bearer insecure',
]);

$client->request('GET', '/api/retention/example.org/users');
self::assertResponseIsSuccessful();
self::assertJsonStringEqualsJsonString('["[email protected]"]', $client->getResponse()->getContent());
}
}