Skip to content
Draft
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
2 changes: 1 addition & 1 deletion lib/Controller/AccountsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ public function index(): JSONResponse {
$json = [];
foreach ($mailAccounts as $mailAccount) {
$conf = $mailAccount->jsonSerialize();
$conf['aliases'] = $this->aliasesService->findAll($conf['accountId'], $this->currentUserId);
$conf['aliases'] = $this->aliasesService->findAllWithDeletable($conf['accountId'], $this->currentUserId);
$json[] = $conf;
}
return new JSONResponse($json);
Expand Down
4 changes: 3 additions & 1 deletion lib/Controller/AliasesController.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,9 @@ public function __construct(string $appName,
*/
#[TrapError]
public function index(int $accountId): JSONResponse {
return new JSONResponse($this->aliasService->findAll($accountId, $this->currentUserId));
return new JSONResponse(
$this->aliasService->findAllWithDeletable($accountId, $this->currentUserId)
);
}

/**
Expand Down
2 changes: 1 addition & 1 deletion lib/Controller/PageController.php
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ public function index(): TemplateResponse {
$accountsJson = [];
foreach ($mailAccounts as $mailAccount) {
$json = $mailAccount->jsonSerialize();
$json['aliases'] = $this->aliasesService->findAll($mailAccount->getId(),
$json['aliases'] = $this->aliasesService->findAllWithDeletable($mailAccount->getId(),
$this->currentUserId);
try {
$mailboxes = $this->mailManager->getMailboxes($mailAccount);
Expand Down
19 changes: 19 additions & 0 deletions lib/Db/AliasMapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,25 @@ public function findByAlias(string $alias, string $currentUserId): Alias {
return $this->findEntity($qb);
}

/**
* @throws DoesNotExistException
*/
public function findByAliasAndName(string $alias, string $name, string $currentUserId): Alias {
$qb = $this->db->getQueryBuilder();
$qb->select('aliases.*', 'accounts.provisioning_id')
->from($this->getTableName(), 'aliases')
->join('aliases', 'mail_accounts', 'accounts', $qb->expr()->eq('aliases.account_id', 'accounts.id'))
->where(
$qb->expr()->andX(
$qb->expr()->eq('accounts.user_id', $qb->createNamedParameter($currentUserId)),
$qb->expr()->eq('aliases.alias', $qb->createNamedParameter($alias)),
$qb->expr()->eq('aliases.name', $qb->createNamedParameter($name))
)
);

return $this->findEntity($qb);
}

/**
* @param int $accountId
* @param string $currentUserId
Expand Down
25 changes: 25 additions & 0 deletions lib/Db/Provisioning.php
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,8 @@
* @method void setLdapAliasesProvisioning(bool $ldapAliasesProvisioning)
* @method string|null getLdapAliasesAttribute()
* @method void setLdapAliasesAttribute(?string $ldapAliasesAttribute)
* @method string|null getNameTemplates()
* @method void setNameTemplates(?string $nameTemplates)
*/
class Provisioning extends Entity implements JsonSerializable {
public const WILDCARD = '*';
Expand All @@ -80,6 +82,7 @@
protected $aliases = [];
protected $ldapAliasesProvisioning;
protected $ldapAliasesAttribute;
protected $nameTemplates;

public function __construct() {
$this->addType('imapPort', 'integer');
Expand Down Expand Up @@ -116,6 +119,7 @@
'aliases' => $this->getAliases(),
'ldapAliasesProvisioning' => $this->getLdapAliasesProvisioning(),
'ldapAliasesAttribute' => $this->getLdapAliasesAttribute(),
'nameTemplates' => json_decode($this->getNameTemplates() ?? '[]', true),
];
}

Expand Down Expand Up @@ -175,4 +179,25 @@
}
return $this->buildEmail($user);
}

/**
* Build account names from the name templates.
*
* Supports placeholders: %USERID%, %DISPLAYNAME%
* @return string[]

Check failure on line 187 in lib/Db/Provisioning.php

View workflow job for this annotation

GitHub Actions / static-psalm-analysis dev-master

InvalidReturnType

lib/Db/Provisioning.php:187:13: InvalidReturnType: The declared return type 'array<array-key, string>' for OCA\Mail\Db\Provisioning::buildNames is incorrect, got 'array<array-key, array<array-key, string>|string>' (see https://psalm.dev/011)

Check failure on line 187 in lib/Db/Provisioning.php

View workflow job for this annotation

GitHub Actions / static-psalm-analysis dev-stable32

InvalidReturnType

lib/Db/Provisioning.php:187:13: InvalidReturnType: The declared return type 'array<array-key, string>' for OCA\Mail\Db\Provisioning::buildNames is incorrect, got 'array<array-key, array<array-key, string>|string>' (see https://psalm.dev/011)

Check failure on line 187 in lib/Db/Provisioning.php

View workflow job for this annotation

GitHub Actions / static-psalm-analysis dev-stable31

InvalidReturnType

lib/Db/Provisioning.php:187:13: InvalidReturnType: The declared return type 'array<array-key, string>' for OCA\Mail\Db\Provisioning::buildNames is incorrect, got 'array<array-key, array<array-key, string>|string>' (see https://psalm.dev/011)
*/
public function buildNames(IUser $user): array {
$displayName = $user->getDisplayName() ?? '';
$templates = json_decode($this->getNameTemplates() ?? '[]', true);
if (empty($templates)) {
return [$displayName];
}

return array_map(function ($template) use ($user, $displayName) {

Check failure on line 196 in lib/Db/Provisioning.php

View workflow job for this annotation

GitHub Actions / static-psalm-analysis dev-master

InvalidReturnStatement

lib/Db/Provisioning.php:196:10: InvalidReturnStatement: The inferred type 'array<array-key, array<array-key, string>|string>' does not match the declared return type 'array<array-key, string>' for OCA\Mail\Db\Provisioning::buildNames (see https://psalm.dev/128)

Check failure on line 196 in lib/Db/Provisioning.php

View workflow job for this annotation

GitHub Actions / static-psalm-analysis dev-stable32

InvalidReturnStatement

lib/Db/Provisioning.php:196:10: InvalidReturnStatement: The inferred type 'array<array-key, array<array-key, string>|string>' does not match the declared return type 'array<array-key, string>' for OCA\Mail\Db\Provisioning::buildNames (see https://psalm.dev/128)

Check failure on line 196 in lib/Db/Provisioning.php

View workflow job for this annotation

GitHub Actions / static-psalm-analysis dev-stable31

InvalidReturnStatement

lib/Db/Provisioning.php:196:10: InvalidReturnStatement: The inferred type 'array<array-key, array<array-key, string>|string>' does not match the declared return type 'array<array-key, string>' for OCA\Mail\Db\Provisioning::buildNames (see https://psalm.dev/128)
if ($user->getUID() !== null) {
$template = str_replace('%USERID%', $user->getUID(), $template);
}
return str_replace('%DISPLAYNAME%', $displayName, $template);
}, $templates);
}
}
2 changes: 2 additions & 0 deletions lib/Db/ProvisioningMapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,8 @@ public function validate(array $data): Provisioning {

$provisioning->setLdapAliasesProvisioning($ldapAliasesProvisioning);
$provisioning->setLdapAliasesAttribute($ldapAliasesAttribute);
$nameTemplates = $data['nameTemplates'] ?? [];
$provisioning->setNameTemplates(!empty($nameTemplates) ? json_encode($nameTemplates) : null);

return $provisioning;
}
Expand Down
35 changes: 35 additions & 0 deletions lib/Migration/Version5007Date20260114100548.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<?php

declare(strict_types=1);

/**
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

namespace OCA\Mail\Migration;

use Closure;
use OCP\DB\ISchemaWrapper;
use OCP\DB\Types;
use OCP\Migration\IOutput;
use OCP\Migration\SimpleMigrationStep;

class Version5007Date20260114100548 extends SimpleMigrationStep {
#[\Override]
public function changeSchema(IOutput $output, Closure $schemaClosure, array $options): ?ISchemaWrapper {
/** @var ISchemaWrapper $schema */
$schema = $schemaClosure();

$provisioningTable = $schema->getTable('mail_provisionings');

if (!$provisioningTable->hasColumn('name_templates')) {
$provisioningTable->addColumn('name_templates', Types::TEXT, [
'notnull' => false,
'default' => '["%DISPLAYNAME%"]',
]);
}

return $schema;
}
}
67 changes: 65 additions & 2 deletions lib/Service/AliasesService.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,10 @@
use OCA\Mail\Db\Alias;
use OCA\Mail\Db\AliasMapper;
use OCA\Mail\Db\MailAccountMapper;
use OCA\Mail\Db\ProvisioningMapper;
use OCA\Mail\Exception\ClientException;
use OCP\AppFramework\Db\DoesNotExistException;
use OCP\IUserManager;

class AliasesService {
/** @var AliasMapper */
Expand All @@ -23,9 +25,19 @@ class AliasesService {
/** @var MailAccountMapper */
private $mailAccountMapper;

public function __construct(AliasMapper $aliasMapper, MailAccountMapper $mailAccountMapper) {
private ProvisioningMapper $provisioningMapper;
private IUserManager $userManager;

public function __construct(
AliasMapper $aliasMapper,
MailAccountMapper $mailAccountMapper,
ProvisioningMapper $provisioningMapper,
IUserManager $userManager,
) {
$this->aliasMapper = $aliasMapper;
$this->mailAccountMapper = $mailAccountMapper;
$this->provisioningMapper = $provisioningMapper;
$this->userManager = $userManager;
}

/**
Expand All @@ -37,6 +49,20 @@ public function findAll(int $accountId, string $currentUserId): array {
return $this->aliasMapper->findAll($accountId, $currentUserId);
}

/**
* Get all aliases with deletable flag included.
*
* @return list<array>
*/
public function findAllWithDeletable(int $accountId, string $currentUserId): array {
$aliases = $this->findAll($accountId, $currentUserId);
return array_map(function ($alias) use ($currentUserId) {
$data = $alias->jsonSerialize();
$data['deletable'] = $this->isAliasDeletable($alias, $currentUserId);
return $data;
}, $aliases);
}

/**
* @param int $aliasId
* @param string $currentUserId
Expand Down Expand Up @@ -84,13 +110,50 @@ public function create(string $userId, int $accountId, string $alias, string $al
public function delete(string $userId, int $aliasId): Alias {
$entity = $this->aliasMapper->find($aliasId, $userId);

if ($entity->isProvisioned()) {
if ($entity->isProvisioned() && !$this->isAliasDeletable($entity, $userId)) {
throw new ClientException('Deleting a provisioned alias is not allowed.');
}

return $this->aliasMapper->delete($entity);
}

/**
* Check if a provisioned alias can be deleted.
*
* A provisioned alias is deletable if its name is no longer in the
* current provisioning name templates. This allows users to clean up
* aliases after an admin removes a name template.
*/
public function isAliasDeletable(Alias $alias, string $userId): bool {
// Non-provisioned aliases are always deletable
if (!$alias->isProvisioned()) {
return true;
}

$account = $this->mailAccountMapper->find($userId, $alias->getAccountId());
$provisioningId = $account->getProvisioningId();

// No provisioning config means alias shouldn't exist as provisioned - allow deletion
if ($provisioningId === null) {
return true;
}

$provisioning = $this->provisioningMapper->get($provisioningId);
if ($provisioning === null) {
return true;
}

$user = $this->userManager->get($userId);
if ($user === null) {
return false;
}

$validNames = $provisioning->buildNames($user);

// If alias name is NOT in valid names, it's deletable
return !in_array($alias->getName(), $validNames, true);
}

/**
* Deletes all aliases of an account.
*
Expand Down
55 changes: 35 additions & 20 deletions lib/Service/Provisioning/Manager.php
Original file line number Diff line number Diff line change
Expand Up @@ -122,15 +122,19 @@ public function provision(): int {
/**
* Delete orphaned aliases for the given account.
*
* A alias is orphaned if not listed in newAliases anymore
* An alias is orphaned if its email is no longer in the valid emails list.
* (=> the provisioning configuration does contain it anymore)
*
* @throws \OCP\DB\Exception
*/
private function deleteOrphanedAliases(string $userId, int $accountId, array $newAliases): void {
private function deleteOrphanedAliases(string $userId, int $accountId, array $validEmails): void {
$existingAliases = $this->aliasMapper->findAll($accountId, $userId);
foreach ($existingAliases as $existingAlias) {
if (!in_array($existingAlias->getAlias(), $newAliases, true)) {
if ($existingAlias->getProvisioningId() === null) {
continue;
}

if (!in_array($existingAlias->getAlias(), $validEmails, true)) {
$this->aliasMapper->delete($existingAlias);
}
}
Expand All @@ -141,20 +145,26 @@ private function deleteOrphanedAliases(string $userId, int $accountId, array $ne
*
* @throws \OCP\DB\Exception
*/
private function createNewAliases(string $userId, int $accountId, array $newAliases, string $displayName, string $accountEmail): void {
foreach ($newAliases as $newAlias) {
if ($newAlias === $accountEmail) {
continue; // skip alias when identical to account email
}

try {
$this->aliasMapper->findByAlias($newAlias, $userId);
} catch (DoesNotExistException $e) {
$alias = new Alias();
$alias->setAccountId($accountId);
$alias->setName($displayName);
$alias->setAlias($newAlias);
$this->aliasMapper->insert($alias);
private function createNewAliases(string $userId, int $accountId, array $aliasEmails, array $names, string $accountEmail): void {
// Include account email for secondary name templates
$allEmails = array_unique(array_merge([$accountEmail], $aliasEmails));

foreach ($allEmails as $email) {
foreach ($names as $index => $name) {
// Skip first name for account email (already set on account)
if ($email === $accountEmail && $index === 0) {
continue;
}

try {
$this->aliasMapper->findByAliasAndName($email, $name, $userId);
} catch (DoesNotExistException $e) {
$alias = new Alias();
$alias->setAccountId($accountId);
$alias->setName($name);
$alias->setAlias($email);
$this->aliasMapper->insert($alias);
}
}
}
}
Expand Down Expand Up @@ -227,14 +237,19 @@ public function provisionSingleUser(array $provisionings, IUser $user): bool {
return true;
}

// Include account email to preserve aliases created via name templates
$aliasEmails = array_unique(array_merge([$mailAccount->getEmail()], $provisioning->getAliases()));

$names = $provisioning->buildNames($user);

try {
$this->deleteOrphanedAliases($user->getUID(), $mailAccount->getId(), $provisioning->getAliases());
$this->deleteOrphanedAliases($user->getUID(), $mailAccount->getId(), $aliasEmails);
} catch (\Throwable $e) {
$this->logger->warning('Deleting orphaned aliases failed', ['exception' => $e]);
}

try {
$this->createNewAliases($user->getUID(), $mailAccount->getId(), $provisioning->getAliases(), $this->userManager->getDisplayName($user->getUID()), $mailAccount->getEmail());
$this->createNewAliases($user->getUID(), $mailAccount->getId(), $provisioning->getAliases(), $names, $mailAccount->getEmail());
} catch (\Throwable $e) {
$this->logger->warning('Creating new aliases failed', ['exception' => $e]);
}
Expand Down Expand Up @@ -274,7 +289,7 @@ private function updateAccount(IUser $user, MailAccount $account, Provisioning $
$account->setProvisioningId($config->getId());

$account->setEmail($config->buildEmail($user));
$account->setName($this->userManager->getDisplayName($user->getUID()));
$account->setName($config->buildNames($user)[0] ?? '');
$account->setInboundUser($config->buildImapUser($user));
$account->setInboundHost($config->getImapHost());
$account->setInboundPort($config->getImapPort());
Expand Down
2 changes: 1 addition & 1 deletion src/components/AliasForm.vue
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@
</template>
</NcButton>
<NcButton
v-if="enableDelete && !alias.provisioned"
v-if="enableDelete && alias.deletable"
variant="tertiary-no-background"
:aria-label="t('mail', 'Delete alias')"
:name="t('mail', 'Delete alias')"
Expand Down Expand Up @@ -87,7 +87,7 @@
},

props: {
account: {

Check warning on line 90 in src/components/AliasForm.vue

View workflow job for this annotation

GitHub Actions / NPM lint

'account' of property found, but never used
type: Object,
required: true,
},
Expand All @@ -99,12 +99,12 @@

enableUpdate: {
type: Boolean,
default: true,

Check warning on line 102 in src/components/AliasForm.vue

View workflow job for this annotation

GitHub Actions / NPM lint

Boolean prop should only be defaulted to false
},

enableDelete: {
type: Boolean,
default: true,

Check warning on line 107 in src/components/AliasForm.vue

View workflow job for this annotation

GitHub Actions / NPM lint

Boolean prop should only be defaulted to false
},

onUpdateAlias: {
Expand Down
12 changes: 12 additions & 0 deletions src/components/settings/ProvisionPreview.vue
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
{{ t('mail', 'Domain Match: {provisioningDomain}', { provisioningDomain }) }}
<br>
{{ t('mail', 'Email: {email}', { email }) }}<br>
{{ t('mail', 'Names: {names}', { names }) }}<br>
{{
t('mail', 'IMAP: {user} on {host}:{port} ({ssl} encryption)', {
user: imapUser,
Expand Down Expand Up @@ -62,6 +63,17 @@
return this.templates.email.replace('%USERID%', this.data.uid).replace('%EMAIL%', this.data.email)
},

names() {
const templates = this.templates.nameTemplates || []
if (!templates.length) {
return this.data.displayName || 'Display Name'
}
return templates.map(t => t

Check failure on line 71 in src/components/settings/ProvisionPreview.vue

View workflow job for this annotation

GitHub Actions / NPM lint

Expected parentheses around arrow function argument
.replace('%USERID%', this.data.uid)
.replace('%DISPLAYNAME%', this.data.displayName || '')

Check failure on line 73 in src/components/settings/ProvisionPreview.vue

View workflow job for this annotation

GitHub Actions / NPM lint

Missing trailing comma
).join(', ')

Check failure on line 74 in src/components/settings/ProvisionPreview.vue

View workflow job for this annotation

GitHub Actions / NPM lint

Unexpected newline before ')'
},

provisioningDomain() {
return this.templates.provisioningDomain
},
Expand Down
Loading
Loading