Skip to content
Open
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
4 changes: 4 additions & 0 deletions lib/Contracts/IInternalAddressService.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,14 @@
namespace OCA\Mail\Contracts;

use OCA\Mail\Db\InternalAddress;
use OCA\Mail\Exception\InvalidAddressException;

interface IInternalAddressService {
public function isInternal(string $uid, string $address): bool;

/**
* @throws InvalidAddressException if the $address to add or its $type is invalid
*/
public function add(string $uid, string $address, string $type, ?bool $trust = true);

/**
Expand Down
4 changes: 4 additions & 0 deletions lib/Contracts/ITrustedSenderService.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,14 @@
namespace OCA\Mail\Contracts;

use OCA\Mail\Db\TrustedSender;
use OCA\Mail\Exception\InvalidAddressException;

interface ITrustedSenderService {
public function isTrusted(string $uid, string $email): bool;

/**
* @throws InvalidAddressException if the $email to trust or its $type is invalid
*/
public function trust(string $uid, string $email, string $type, ?bool $trust = true);

/**
Expand Down
19 changes: 19 additions & 0 deletions lib/Exception/InvalidAddressException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?php

declare(strict_types=1);

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

namespace OCA\Mail\Exception;

use OCP\AppFramework\Http;

class InvalidAddressException extends ClientException {
#[\Override]
public function getHttpCode(): int {
return Http::STATUS_UNPROCESSABLE_ENTITY;
}
}
128 changes: 128 additions & 0 deletions lib/Service/AddressOrDomainNormalizer.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
<?php

declare(strict_types=1);

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

namespace OCA\Mail\Service;

use Horde_Mail_Exception;
use Horde_Mail_Rfc822;
use Horde_Mail_Rfc822_Address;
use OCA\Mail\Exception\InvalidAddressException;

class AddressOrDomainNormalizer {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rename it after what it produces, not what it accepts, such as TrustedEntryNormalizer, or something that matches the individual/domain type values.

private const TYPE_INDIVIDUAL = 'individual';
private const TYPE_DOMAIN = 'domain';

/** RFC 5321, section 4.5.3.1.3: a path has at most 256 octets, including the angle brackets */
private const MAX_LENGTH = 254;

/** Stricter than RFC 5322 and 6532, but some writing systems need the joiners U+200C and U+200D */
private const DISALLOWED_CHARACTERS = '/(?![\x{200C}\x{200D}])[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u';

private const IDNA_OPTIONS = IDNA_NONTRANSITIONAL_TO_ASCII | IDNA_USE_STD3_RULES | IDNA_CHECK_BIDI | IDNA_CHECK_CONTEXTJ;

/**
* @throws InvalidAddressException
*/
public function normalize(string $value, string $type): string {
$normalized = match ($type) {
self::TYPE_INDIVIDUAL => $this->normalizeAddress($value),
self::TYPE_DOMAIN => $this->normalizeDomain($value),
default => throw new InvalidAddressException('Invalid type'),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

throws InvalidAddressException('Invalid type'), which reports a programming mistake as bad user input. An enum, or reusing the constants the mappers already have, would make that case impossible.

};

// IDN decoding can lengthen the value, and Oracle's columns count bytes
if (strlen($normalized) > self::MAX_LENGTH) {
throw new InvalidAddressException('Email address or domain too long');
}

return $normalized;
}

/**
* @throws InvalidAddressException
*/
private function normalizeAddress(string $value): string {
if (strlen($value) > self::MAX_LENGTH
|| !mb_check_encoding($value, 'UTF-8')
|| preg_match(self::DISALLOWED_CHARACTERS, $value) === 1) {
throw new InvalidAddressException('Invalid email address');
}

try {
// RFC 5322, with the UTF-8 addresses of RFC 6532
$addresses = (new Horde_Mail_Rfc822())->parseAddressList($value, ['validate' => 'eai']);
} catch (Horde_Mail_Exception) {
throw new InvalidAddressException('Invalid email address');
}

$address = $addresses->first();
$separator = strrpos($value, '@');
// Horde accepts a trailing dot, over-long labels and any address literal
$host = $separator === false ? null : $this->toAsciiHost(substr($value, $separator + 1));
if (count($addresses) !== 1
|| !($address instanceof Horde_Mail_Rfc822_Address)
|| $host === null) {
throw new InvalidAddressException('Invalid email address');
}

$address->host = $host;
return $address->bare_address;
}

/**
* @throws InvalidAddressException
*/
private function normalizeDomain(string $domain): string {
$host = $this->toAsciiHost($domain);
if ($host === null) {
throw new InvalidAddressException('Invalid domain');
}

// Same form as the host of a parsed sender: IDN-decoded and lowercased by Horde
$address = new Horde_Mail_Rfc822_Address();
$address->host = $host;
return $address->host;
}

private function toAsciiHost(string $domain): ?string {
if (str_starts_with($domain, '[') && str_ends_with($domain, ']')) {
$literal = substr($domain, 1, -1);
return $this->isValidAddressLiteral($literal) ? $literal : null;
}

if ($domain === '') {
return null;
}

$asciiDomain = idn_to_ascii($domain, self::IDNA_OPTIONS, INTL_IDNA_VARIANT_UTS46);
// UTS #46 accepts a trailing dot, RFC 5322 doesn't
if ($asciiDomain === false || str_ends_with($asciiDomain, '.')) {
return null;
}

// RFC 3696, section 2: only an IPv4 address ends with an all-numeric label
if (preg_match('/(^|\.)[0-9]+$/', $asciiDomain) === 1
&& filter_var($asciiDomain, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false) {
return null;
}

return $asciiDomain;
}

/**
* RFC 5321, section 4.1.3
*/
private function isValidAddressLiteral(string $literal): bool {
if (stripos($literal, 'IPv6:') === 0) {
return filter_var(substr($literal, 5), FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) !== false;
}

return filter_var($literal, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false;
}
}
36 changes: 26 additions & 10 deletions lib/Service/InternalAddressService.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,13 @@
use OCA\Mail\Contracts\IInternalAddressService;
use OCA\Mail\Db\InternalAddress;
use OCA\Mail\Db\InternalAddressMapper;
use OCA\Mail\Exception\InvalidAddressException;
use OCP\DB\Exception;

class InternalAddressService implements IInternalAddressService {
public function __construct(
private InternalAddressMapper $mapper,
private AddressOrDomainNormalizer $normalizer,
) {
}

Expand All @@ -27,19 +30,32 @@ public function isInternal(string $uid, string $address): bool {
);
}

/**
* @throws InvalidAddressException
*/
#[\Override]
public function add(string $uid, string $address, string $type, ?bool $trust = true): ?InternalAddress {
if ($trust && $this->isInternal($uid, $address)) {
// Nothing to do
return null;
}

if ($trust) {
$this->mapper->create(
$uid,
$address,
$type
);
$address = $this->normalizer->normalize($address, $type);
if ($this->isInternal($uid, $address)) {
// Nothing to do
return null;
}

try {
$this->mapper->create(
$uid,
$address,
$type
);
} catch (Exception $exception) {
if ($exception->getReason() !== Exception::REASON_UNIQUE_CONSTRAINT_VIOLATION) {
throw $exception;
}

// isInternal() doesn't match a domain itself, and requests can race
return null;
}
return $this->getInternalAddress($uid, $address);
} else {
$this->mapper->remove(
Expand Down
35 changes: 25 additions & 10 deletions lib/Service/TrustedSenderService.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,13 @@
use OCA\Mail\Contracts\ITrustedSenderService;
use OCA\Mail\Db\Message;
use OCA\Mail\Db\TrustedSenderMapper;
use OCA\Mail\Exception\InvalidAddressException;
use OCP\DB\Exception;

class TrustedSenderService implements ITrustedSenderService {
public function __construct(
private TrustedSenderMapper $mapper,
private AddressOrDomainNormalizer $normalizer,
) {
}

Expand Down Expand Up @@ -44,19 +47,31 @@ public function isSenderTrusted(string $uid, Message $message): bool {
);
}

/**
* @throws InvalidAddressException
*/
#[\Override]
public function trust(string $uid, string $email, string $type, ?bool $trust = true): void {
if ($trust && $this->isTrusted($uid, $email)) {
// Nothing to do
return;
}

if ($trust) {
$this->mapper->create(
$uid,
$email,
$type
);
$email = $this->normalizer->normalize($email, $type);
if ($this->isTrusted($uid, $email)) {
// Nothing to do
return;
}

try {
$this->mapper->create(
$uid,
$email,
$type
);
} catch (Exception $exception) {
if ($exception->getReason() !== Exception::REASON_UNIQUE_CONSTRAINT_VIOLATION) {
throw $exception;
}

// isTrusted() doesn't match a domain itself, and requests can race
}
} else {
$this->mapper->remove(
$uid,
Expand Down
23 changes: 16 additions & 7 deletions lib/UserMigration/Service/InternalAddressesMigrationService.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

use JsonException;
use OCA\Mail\Contracts\IInternalAddressService;
use OCA\Mail\Exception\InvalidAddressException;
use OCA\Mail\UserMigration\MailAccountMigrator;
use OCP\IL10N;
use OCP\IUser;
Expand Down Expand Up @@ -106,20 +107,28 @@ public function importInternalAddresses(IUser $user, IImportSource $importSource

foreach ($internalAddresses as $internalAddress) {
if (!$this->isWellFormedInternalAddress($internalAddress)) {
$output->writeln(
$this->l10n->t(
'An internal address of %s is invalid and will be skipped. Continue …',
[$user->getUID()]
)
);
$this->reportInvalidInternalAddress($user, $output);

continue;
}

$this->internalAddressService->add($user->getUID(), $internalAddress['address'], $internalAddress['type']);
try {
$this->internalAddressService->add($user->getUID(), $internalAddress['address'], $internalAddress['type']);
} catch (InvalidAddressException) {
$this->reportInvalidInternalAddress($user, $output);
}
}
}

private function reportInvalidInternalAddress(IUser $user, OutputInterface $output): void {
$output->writeln(
$this->l10n->t(
'An internal address of %s is invalid and will be skipped. Continue …',
[$user->getUID()]
)
);
}

/**
* Validate that the parsed internal addresses are a list.
*
Expand Down
23 changes: 16 additions & 7 deletions lib/UserMigration/Service/TrustedSendersMigrationService.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

use JsonException;
use OCA\Mail\Contracts\ITrustedSenderService;
use OCA\Mail\Exception\InvalidAddressException;
use OCA\Mail\UserMigration\MailAccountMigrator;
use OCP\IL10N;
use OCP\IUser;
Expand Down Expand Up @@ -100,12 +101,7 @@ public function importTrustedSenders(IUser $user, IImportSource $importSource, O

foreach ($trustedSenders as $trustedSender) {
if (!$this->isWellFormedTrustedSender($trustedSender)) {
$output->writeln(
$this->l10n->t(
'A trusted sender of %s is invalid and will be skipped. Continue …',
[$user->getUID()]
)
);
$this->reportInvalidTrustedSender($user, $output);

continue;
}
Expand All @@ -117,10 +113,23 @@ public function importTrustedSenders(IUser $user, IImportSource $importSource, O
), OutputInterface::VERBOSITY_VERBOSE
);

$this->trustedSenderService->trust($user->getUID(), $trustedSender['email'], $trustedSender['type']);
try {
$this->trustedSenderService->trust($user->getUID(), $trustedSender['email'], $trustedSender['type']);
} catch (InvalidAddressException) {
$this->reportInvalidTrustedSender($user, $output);
}
}
}

private function reportInvalidTrustedSender(IUser $user, OutputInterface $output): void {
$output->writeln(
$this->l10n->t(
'A trusted sender of %s is invalid and will be skipped. Continue …',
[$user->getUID()]
)
);
}

/**
* Validate that the parsed trusted senders are a list.
*
Expand Down
Loading
Loading