Skip to content

Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.

Add test for full encryption/decryption flow (#117)

Leendert de Borst1609562499cd
diff --git a/.env.example b/.env.example
index 6f97da333..23265bf74 100644
--- a/.env.example
+++ b/.env.example
@@ -1,3 +1,4 @@
+API_URL=
JWT_KEY=
-SMTP_ALLOWED_DOMAINS=example.tld
+SMTP_ALLOWED_DOMAINS=
SMTP_TLS_ENABLED=false
diff --git a/README.md b/README.md
index b69c2ca49..662f0de40 100644
--- a/README.md
+++ b/README.md
@@ -15,7 +15,8 @@ AliasVault is an open-source password and identity manager built with C# ASP.NET
### What makes AliasVault unique:
- **Zero-knowledge architecture**: All data is end-to-end encrypted on the client and stored in encrypted state on the server. Your master password never leaves your device and the server never has access to your data.
-- **Virtual identities**: Generate virtual identities with virtual (working) email addresses that are assigned to one or more passwords.
+- **Built-in email server**: AliasVault includes its own email server that allows you to generate virtual email addresses for each identity. Emails sent to these addresses are instantly visible in the AliasVault app.
+- **Virtual identities**: Generate virtual identities and assign them to a website, allowing you to use different email addresses and usernames for each website. Keeping your online identities separate and secure, making it harder for attackers to link your accounts.
- **Open-source**: The source code is available on GitHub and can be self-hosted on your own server.
> Note: AliasVault is currently in development and not yet ready for production use. The project is still in the early stages and many features are not yet implemented. You are welcome to contribute to the project by submitting pull requests or opening issues.
@@ -41,7 +42,7 @@ $ git clone https://github.com/lanedirt/AliasVault.git
```
### 2. Run the install script.
-The script checks and creates a .env file with a JWT secret, generates an admin password, and manages Docker image building and container initiation. It ensures necessary configurations and services are ready for the application's operation.
+The script checks and creates a .env file with a JWT secret, generates an admin password and manages Docker image building and container initiation. It ensures necessary configurations and services are ready for the application's operation.
```bash
# Go to the project directory
diff --git a/docker-compose.yml b/docker-compose.yml
index fe43c0106..14926e584 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -7,8 +7,8 @@ services:
ports:
- "8080:8082"
volumes:
- - ./database:/database
- - ./logs:/logs
+ - ./database:/database:rw
+ - ./logs:/logs:rw
restart: always
env_file:
- .env
@@ -20,8 +20,8 @@ services:
ports:
- "80:8080"
restart: always
- environment:
- - API_URL=http://localhost:81
+ env_file:
+ - .env
api:
image: aliasvault-api
@@ -31,8 +31,8 @@ services:
ports:
- "81:8081"
volumes:
- - ./database:/database
- - ./logs:/logs
+ - ./database:/database:rw
+ - ./logs:/logs:rw
env_file:
- .env
restart: always
@@ -46,8 +46,8 @@ services:
- "25:25"
- "587:587"
volumes:
- - ./database:/database
- - ./logs:/logs
+ - ./database:/database:rw
+ - ./logs:/logs:rw
env_file:
- .env
restart: always
diff --git a/install.sh b/install.sh
index 8ac16a5f1..7a497a7b1 100755
--- a/install.sh
+++ b/install.sh
@@ -135,6 +135,25 @@ create_env_file() {
fi
}
+# Function to check and populate the .env file with API_URL
+populate_api_url() {
+ printf "${CYAN}> Checking API_URL...${NC}\n"
+ if ! grep -q "^API_URL=" "$ENV_FILE" || [ -z "$(grep "^API_URL=" "$ENV_FILE" | cut -d '=' -f2)" ]; then
+ DEFAULT_API_URL="http://localhost:81"
+ read -p "Enter the base URL where the API will be hosted (press Enter for default: $DEFAULT_API_URL): " USER_API_URL
+ API_URL=${USER_API_URL:-$DEFAULT_API_URL}
+ if grep -q "^API_URL=" "$ENV_FILE"; then
+ awk -v url="$API_URL" '/^API_URL=/ {$0="API_URL="url} 1' "$ENV_FILE" > "$ENV_FILE.tmp" && mv "$ENV_FILE.tmp" "$ENV_FILE"
+ else
+ echo "API_URL=${API_URL}" >> "$ENV_FILE"
+ fi
+ printf "${GREEN}> API_URL has been set to $API_URL in $ENV_FILE.${NC}\n"
+ else
+ API_URL=$(grep "^API_URL=" "$ENV_FILE" | cut -d '=' -f2)
+ printf "${GREEN}> API_URL already exists in $ENV_FILE with value: $API_URL${NC}\n"
+ fi
+}
+
# Function to check and populate the .env file with JWT_KEY
populate_jwt_key() {
printf "${CYAN}> Checking JWT_KEY...${NC}\n"
@@ -155,16 +174,30 @@ populate_jwt_key() {
set_smtp_allowed_domains() {
printf "${CYAN}> Setting SMTP_ALLOWED_DOMAINS...${NC}\n"
if ! grep -q "^SMTP_ALLOWED_DOMAINS=" "$ENV_FILE" || [ -z "$(grep "^SMTP_ALLOWED_DOMAINS=" "$ENV_FILE" | cut -d '=' -f2)" ]; then
- printf "Please enter the domains that should be allowed to send email, separated by commas: "
+ printf "Please enter the domains that should be allowed to receive email, separated by commas (press Enter to disable email support): "
read -r smtp_allowed_domains
+
+ # Set default value if user input is empty
+ smtp_allowed_domains=${smtp_allowed_domains:-"DISABLED.TLD"}
+
if grep -q "^SMTP_ALLOWED_DOMAINS=" "$ENV_FILE"; then
awk -v domains="$smtp_allowed_domains" '/^SMTP_ALLOWED_DOMAINS=/ {$0="SMTP_ALLOWED_DOMAINS="domains} 1' "$ENV_FILE" > "$ENV_FILE.tmp" && mv "$ENV_FILE.tmp" "$ENV_FILE"
else
echo "SMTP_ALLOWED_DOMAINS=${smtp_allowed_domains}" >> "$ENV_FILE"
fi
- printf "${GREEN}> SMTP_ALLOWED_DOMAINS has been set in $ENV_FILE.${NC}\n"
+
+ if [ "$smtp_allowed_domains" = "DISABLED.TLD" ]; then
+ printf "${GREEN}> SMTP_ALLOWED_DOMAINS has been set to 'DISABLED.TLD' in $ENV_FILE.${NC} ${RED}SMTP is disabled.${NC}\n"
+ else
+ printf "${GREEN}> SMTP_ALLOWED_DOMAINS has been set to '${smtp_allowed_domains}' in $ENV_FILE.${NC}\n"
+ fi
else
- printf "${GREEN}> SMTP_ALLOWED_DOMAINS already exists and has a value in $ENV_FILE.${NC}\n"
+ smtp_allowed_domains=$(grep "^SMTP_ALLOWED_DOMAINS=" "$ENV_FILE" | cut -d '=' -f2)
+ if [ "$smtp_allowed_domains" = "DISABLED.TLD" ]; then
+ printf "${GREEN}> SMTP_ALLOWED_DOMAINS already exists in $ENV_FILE.${NC} ${RED}SMTP is disabled.${NC}\n"
+ else
+ printf "${GREEN}> SMTP_ALLOWED_DOMAINS already exists in $ENV_FILE with value: ${smtp_allowed_domains}${NC}\n"
+ fi
fi
}
@@ -281,6 +314,7 @@ main() {
printf "${YELLOW}+++ Initializing .env file +++${NC}\n"
printf "\n"
create_env_file || exit $?
+ populate_api_url || exit $?
populate_jwt_key || exit $?
set_smtp_allowed_domains || exit $?
set_smtp_tls_enabled || exit $?
diff --git a/src/AliasVault.Client/Main/Components/Email/RecentEmails.razor b/src/AliasVault.Client/Main/Components/Email/RecentEmails.razor
index 6e71f6c29..fb3ff8182 100644
--- a/src/AliasVault.Client/Main/Components/Email/RecentEmails.razor
+++ b/src/AliasVault.Client/Main/Components/Email/RecentEmails.razor
@@ -16,7 +16,7 @@
<div class="p-4 mb-4 bg-white border border-gray-200 rounded-lg shadow-sm 2xl:col-span-2 dark:border-gray-700 sm:p-6 dark:bg-gray-800">
<div class="flex justify-between">
<h3 class="mb-4 text-xl font-semibold dark:text-white">Email</h3>
- <button @onclick="LoadRecentEmailsAsync" type="button" class="text-blue-700 border border-blue-700 hover:bg-blue-700 hover:text-white focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-full text-sm p-2.5 text-center inline-flex items-center dark:border-blue-500 dark:text-blue-500 dark:hover:text-white dark:focus:ring-blue-800 dark:hover:bg-blue-500">
+ <button id="recent-email-refresh" @onclick="LoadRecentEmailsAsync" type="button" class="text-blue-700 border border-blue-700 hover:bg-blue-700 hover:text-white focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-full text-sm p-2.5 text-center inline-flex items-center dark:border-blue-500 dark:text-blue-500 dark:hover:text-white dark:focus:ring-blue-800 dark:hover:bg-blue-500">
Refresh
</button>
</div>
@@ -137,7 +137,7 @@
/// </summary>
private bool IsAliasVaultDomain(string email)
{
- return Config.SmtpAllowedDomains.Any(x => email.EndsWith(x));
+ return Config.SmtpAllowedDomains.Exists(x => email.EndsWith(x));
}
private async Task LoadRecentEmailsAsync()
diff --git a/src/AliasVault.Client/entrypoint.sh b/src/AliasVault.Client/entrypoint.sh
index 8651a6c25..db89bc6a4 100755
--- a/src/AliasVault.Client/entrypoint.sh
+++ b/src/AliasVault.Client/entrypoint.sh
@@ -14,7 +14,7 @@ sed -i "s|http://localhost:5092|${API_URL}|g" /usr/share/nginx/html/appsettings.
# in order to be able to receive emails.
# Convert comma-separated list to JSON array
-json_array=$(echo $domains | awk '{split($0,a,","); printf "["; for(i=1;i<=length(a);i++) {printf "\"%s\"", a[i]; if(i<length(a)) printf ","} printf "]"}')
+json_array=$(echo $SMTP_ALLOWED_DOMAINS | awk '{split($0,a,","); printf "["; for(i=1;i<=length(a);i++) {printf "\"%s\"", a[i]; if(i<length(a)) printf ","} printf "]"}')
# Use sed to update the SmtpAllowedDomains field in appsettings.json
sed -i.bak "s|\"SmtpAllowedDomains\": \[.*\]|\"SmtpAllowedDomains\": $json_array|" /usr/share/nginx/html/appsettings.json
diff --git a/src/Services/AliasVault.SmtpService/AliasVault.SmtpService.csproj b/src/Services/AliasVault.SmtpService/AliasVault.SmtpService.csproj
index 4b503b865..7b6060041 100644
--- a/src/Services/AliasVault.SmtpService/AliasVault.SmtpService.csproj
+++ b/src/Services/AliasVault.SmtpService/AliasVault.SmtpService.csproj
@@ -9,6 +9,16 @@
<DockerfileContext>..\..\..</DockerfileContext>
</PropertyGroup>
+ <PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
+ <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
+ <DocumentationFile>bin\Debug\net8.0\AliasVault.SmtpService.xml</DocumentationFile>
+ </PropertyGroup>
+
+ <PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
+ <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
+ <DocumentationFile>bin\Release\net8.0\AliasVault.SmtpService.xml</DocumentationFile>
+ </PropertyGroup>
+
<ItemGroup>
<AdditionalFiles Include="..\..\stylecop.json" Link="stylecop.json" />
</ItemGroup>
@@ -19,6 +29,10 @@
<PackageReference Include="MimeKit" Version="4.7.1" />
<PackageReference Include="NUglify" Version="1.21.9" />
<PackageReference Include="SmtpServer" Version="10.0.1" />
+ <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.556">
+ <PrivateAssets>all</PrivateAssets>
+ <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
+ </PackageReference>
</ItemGroup>
<ItemGroup>
diff --git a/src/Services/AliasVault.SmtpService/Handlers/DatabaseMessageStore.cs b/src/Services/AliasVault.SmtpService/Handlers/DatabaseMessageStore.cs
index 008b47ae1..9cdad7ed2 100644
--- a/src/Services/AliasVault.SmtpService/Handlers/DatabaseMessageStore.cs
+++ b/src/Services/AliasVault.SmtpService/Handlers/DatabaseMessageStore.cs
@@ -5,32 +5,27 @@
// </copyright>
//-----------------------------------------------------------------------
-using Cryptography;
-using SmtpServer.Mail;
-
namespace AliasVault.SmtpService.Handlers;
using System.Buffers;
using System.Net.Mail;
using System.Text.RegularExpressions;
using AliasServerDb;
+using Cryptography;
using Microsoft.EntityFrameworkCore;
using MimeKit;
using NUglify;
using SmtpServer;
+using SmtpServer.Mail;
using SmtpServer.Protocol;
using SmtpServer.Storage;
-/// <summary>
-/// Custom exception for when the email parsing fails to find the "to" address in the email.
-/// </summary>
-public class EmailParseMissingToException(string message) : Exception(message);
-
/// <summary>
/// Database message store.
/// </summary>
/// <param name="logger">ILogger instance.</param>
/// <param name="config">Config instance.</param>
+/// <param name="dbContextFactory">IDbContextFactory instance.</param>
public class DatabaseMessageStore(ILogger<DatabaseMessageStore> logger, Config config, IDbContextFactory<AliasServerDbContext> dbContextFactory) : MessageStore
{
/// <summary>
@@ -93,10 +88,15 @@ public class DatabaseMessageStore(ILogger<DatabaseMessageStore> logger, Config c
}
// Check if the local part of the toAddress is a known alias (claimed by a user)
- var dbContext = await dbContextFactory.CreateDbContextAsync(cancellationToken);
- var userEmailClaim = await dbContext.UserEmailClaims.FirstOrDefaultAsync(x =>
- x.AddressLocal == toAddress.User.ToLowerInvariant() &&
- x.AddressDomain == toAddress.Host.ToLowerInvariant());
+ var dbContext = await dbContextFactory.CreateDbContextAsync(CancellationToken.None);
+ var toAddressLocal = toAddress.User.ToLowerInvariant();
+ var toAddressDomain = toAddress.Host.ToLowerInvariant();
+ var userEmailClaim = await dbContext.UserEmailClaims
+ .FirstOrDefaultAsync(
+ x =>
+ x.AddressLocal == toAddressLocal &&
+ x.AddressDomain == toAddressDomain,
+ CancellationToken.None);
if (userEmailClaim is null)
{
@@ -115,8 +115,10 @@ public class DatabaseMessageStore(ILogger<DatabaseMessageStore> logger, Config c
}
// Retrieve user public encryption key from database
- var userPublicKey = await dbContext.UserEncryptionKeys.FirstOrDefaultAsync(x =>
- x.UserId == userEmailClaim.UserId && x.IsPrimary);
+ var userPublicKey = await dbContext.UserEncryptionKeys.FirstOrDefaultAsync(
+ x =>
+ x.UserId == userEmailClaim.UserId && x.IsPrimary,
+ CancellationToken.None);
if (userPublicKey is null)
{
@@ -136,8 +138,10 @@ public class DatabaseMessageStore(ILogger<DatabaseMessageStore> logger, Config c
// Set the "to" for the email to the actual one we are looping through now.
var insertedId = await InsertEmailIntoDatabase(message, new MailAddress(toAddress.AsAddress()), userPublicKey);
- logger.LogInformation("Email for {ToAddress} successfully saved into database with ID {insertedId}.",
- toAddress.User + "@" + toAddress.Host, insertedId);
+ logger.LogInformation(
+ "Email for {ToAddress} successfully saved into database with ID {insertedId}.",
+ toAddress.User + "@" + toAddress.Host,
+ insertedId);
}
return SmtpResponse.Ok;
@@ -149,36 +153,15 @@ public class DatabaseMessageStore(ILogger<DatabaseMessageStore> logger, Config c
}
}
- /// <summary>
- /// Insert email into database.
- /// </summary>
- /// <param name="message">MimeMessage to save into database.</param>
- /// <param name="toAddress">The recipient for this mail.</param>
- /// <param name="userEncryptionKey">The public key of the user to encrypt the mail contents with.</param>
- private async Task<int> InsertEmailIntoDatabase(MimeMessage message, MailAddress toAddress, UserEncryptionKey userEncryptionKey)
- {
- var dbContext = await dbContextFactory.CreateDbContextAsync();
-
- var newEmail = ConvertMimeMessageToEmail(message, toAddress);
- newEmail = EmailEncryption.EncryptEmail(newEmail, userEncryptionKey);
-
- // Insert the email into the database.
- await dbContext.Emails.AddAsync(newEmail);
- await dbContext.SaveChangesAsync();
-
- return newEmail.Id;
- }
-
/// <summary>
/// Convert MimeMessage to Email database object.
/// </summary>
/// <param name="message">MimeMessage object.</param>
/// <param name="toAddress">The recipient for this mail.</param>
/// <returns>Email object.</returns>
- /// <exception cref="EmailParseMissingToException"></exception>
private static Email ConvertMimeMessageToEmail(MimeMessage message, MailAddress toAddress)
{
- string from = "";
+ var from = string.Empty;
try
{
@@ -191,19 +174,19 @@ public class DatabaseMessageStore(ILogger<DatabaseMessageStore> logger, Config c
string fromLocal;
string fromDomain;
+
// Try to extract from address firstly from "from" in the mail.
try
{
MailAddress fromAddress = new MailAddress(message.From.FirstOrDefault()?.ToString() ?? string.Empty);
fromLocal = fromAddress.User;
fromDomain = fromAddress.Host;
-
}
catch
{
// If this fails, then simply use a blank value
- fromLocal = "";
- fromDomain = "";
+ fromLocal = string.Empty;
+ fromDomain = string.Empty;
}
// Create email object
@@ -243,8 +226,8 @@ public class DatabaseMessageStore(ILogger<DatabaseMessageStore> logger, Config c
/// Extracts a preview of the email message body to be used in the email listing preview in the UI.
/// This so the client does not need to load the full email body.
/// </summary>
- /// <param name="email"></param>
- /// <returns></returns>
+ /// <param name="email">Email to extract preview for.</param>
+ /// <returns>Email preview as string.</returns>
private static string ExtractMessagePreview(Email email)
{
var messagePreview = string.Empty;
@@ -252,16 +235,16 @@ public class DatabaseMessageStore(ILogger<DatabaseMessageStore> logger, Config c
try
{
- if (email.MessagePlain != null && !String.IsNullOrEmpty(email.MessagePlain) && email.MessagePlain.Length > 3)
+ if (email.MessagePlain != null && !string.IsNullOrEmpty(email.MessagePlain) && email.MessagePlain.Length > 3)
{
// Replace any newline characters with a space
string plainToPlainText = Regex.Replace(email.MessagePlain, @"\t|\n|\r", " ", RegexOptions.NonBacktracking);
// Remove all "-" or "=" characters if there are 3 or more in a row
- plainToPlainText = Regex.Replace(plainToPlainText, @"-{3,}|\={3,}", "", RegexOptions.NonBacktracking);
+ plainToPlainText = Regex.Replace(plainToPlainText, @"-{3,}|\={3,}", string.Empty, RegexOptions.NonBacktracking);
// Remove any non-printable characters
- plainToPlainText = Regex.Replace(plainToPlainText, @"[^\u0020-\u007E]", "", RegexOptions.NonBacktracking);
+ plainToPlainText = Regex.Replace(plainToPlainText, @"[^\u0020-\u007E]", string.Empty, RegexOptions.NonBacktracking);
// Replace multiple spaces with a single space
plainToPlainText = Regex.Replace(plainToPlainText, @"\s+", " ", RegexOptions.NonBacktracking);
@@ -278,13 +261,13 @@ public class DatabaseMessageStore(ILogger<DatabaseMessageStore> logger, Config c
string htmlToPlainText = Uglify.HtmlToText(email.MessageHtml).ToString();
// Replace any newline characters with a space
- htmlToPlainText = Regex.Replace(htmlToPlainText, @"\t|\n|\r", " ", RegexOptions.NonBacktracking);
+ htmlToPlainText = Regex.Replace(htmlToPlainText, @"\t|\n|\r", string.Empty, RegexOptions.NonBacktracking);
// Remove all "-" or "=" characters if there are 3 or more in a row
- htmlToPlainText = Regex.Replace(htmlToPlainText, @"-{3,}|\={3,}", "", RegexOptions.NonBacktracking);
+ htmlToPlainText = Regex.Replace(htmlToPlainText, @"-{3,}|\={3,}", string.Empty, RegexOptions.NonBacktracking);
// Remove any non-printable characters
- htmlToPlainText = Regex.Replace(htmlToPlainText, @"[^\u0020-\u007E]", "", RegexOptions.NonBacktracking);
+ htmlToPlainText = Regex.Replace(htmlToPlainText, @"[^\u0020-\u007E]", string.Empty, RegexOptions.NonBacktracking);
// Replace multiple spaces with a single space
htmlToPlainText = Regex.Replace(htmlToPlainText, @"\s+", " ", RegexOptions.NonBacktracking);
@@ -307,8 +290,8 @@ public class DatabaseMessageStore(ILogger<DatabaseMessageStore> logger, Config c
/// <summary>
/// Create an EmailAttachment object from a MimeEntity attachment.
/// </summary>
- /// <param name="attachment"></param>
- /// <returns></returns>
+ /// <param name="attachment">MimeEntity attachment.</param>
+ /// <returns>EmailAttachment object.</returns>
private static EmailAttachment CreateEmailAttachment(MimeEntity attachment)
{
byte[] fileBytes = GetAttachmentBytes(attachment);
@@ -316,18 +299,18 @@ public class DatabaseMessageStore(ILogger<DatabaseMessageStore> logger, Config c
return new EmailAttachment
{
Bytes = fileBytes,
- Filename = attachment.ContentDisposition?.FileName ?? "",
+ Filename = attachment.ContentDisposition?.FileName ?? string.Empty,
MimeType = attachment.ContentType.MimeType,
Filesize = fileBytes.Length,
- Date = DateTime.Now
+ Date = DateTime.Now,
};
}
/// <summary>
/// Get the attachment bytes from a MimeEntity attachment.
/// </summary>
- /// <param name="attachment"></param>
- /// <returns></returns>
+ /// <param name="attachment">MimeEntity attachment.</param>
+ /// <returns>Attachment byte array.</returns>
private static byte[] GetAttachmentBytes(MimeEntity attachment)
{
using (var memory = new MemoryStream())
@@ -344,4 +327,24 @@ public class DatabaseMessageStore(ILogger<DatabaseMessageStore> logger, Config c
return memory.ToArray();
}
}
+
+ /// <summary>
+ /// Insert email into database.
+ /// </summary>
+ /// <param name="message">MimeMessage to save into database.</param>
+ /// <param name="toAddress">The recipient for this mail.</param>
+ /// <param name="userEncryptionKey">The public key of the user to encrypt the mail contents with.</param>
+ private async Task<int> InsertEmailIntoDatabase(MimeMessage message, MailAddress toAddress, UserEncryptionKey userEncryptionKey)
+ {
+ var dbContext = await dbContextFactory.CreateDbContextAsync();
+
+ var newEmail = ConvertMimeMessageToEmail(message, toAddress);
+ newEmail = EmailEncryption.EncryptEmail(newEmail, userEncryptionKey);
+
+ // Insert the email into the database.
+ await dbContext.Emails.AddAsync(newEmail);
+ await dbContext.SaveChangesAsync();
+
+ return newEmail.Id;
+ }
}
diff --git a/src/Services/AliasVault.SmtpService/Program.cs b/src/Services/AliasVault.SmtpService/Program.cs
index c9e63546c..8d51dfb5a 100644
--- a/src/Services/AliasVault.SmtpService/Program.cs
+++ b/src/Services/AliasVault.SmtpService/Program.cs
@@ -9,15 +9,15 @@ using System.Data.Common;
using System.Reflection;
using System.Security.Cryptography.X509Certificates;
using AliasServerDb;
+using AliasVault.Logging;
using AliasVault.SmtpService;
using AliasVault.SmtpService.Handlers;
+using AliasVault.SmtpService.Workers;
+using AliasVault.WorkerStatus.ServiceExtensions;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using SmtpServer;
using SmtpServer.Storage;
-using AliasVault.Logging;
-using AliasVault.SmtpService.Workers;
-using AliasVault.WorkerStatus.ServiceExtensions;
var builder = Host.CreateApplicationBuilder(args);
builder.Configuration.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
@@ -70,8 +70,7 @@ builder.Services.AddSingleton(
.Port(587, false)
.AllowUnsecureAuthentication()
.Certificate(CreateCertificate())
- .SupportedSslProtocols(System.Security.Authentication.SslProtocols.Tls12)
- );
+ .SupportedSslProtocols(System.Security.Authentication.SslProtocols.Tls12));
}
else
{
@@ -81,8 +80,7 @@ builder.Services.AddSingleton(
.Port(25, false))
.Endpoint(serverBuilder =>
serverBuilder
- .Port(587, false)
- );
+ .Port(587, false));
}
return new SmtpServer.SmtpServer(options.Build(), provider.GetRequiredService<IServiceProvider>());
@@ -117,14 +115,12 @@ builder.Services.AddSingleton(
return cert;
}
- }
-);
+ });
// -----------------------------------------------------------------------
// Register hosted services via Status library wrapper in order to monitor and control (start/stop) them via the database.
// -----------------------------------------------------------------------
builder.Services.AddStatusHostedService<SmtpServerWorker, AliasServerDbContext>(Assembly.GetExecutingAssembly().GetName().Name!);
-// -----------------------------------------------------------------------
var host = builder.Build();
diff --git a/src/Services/AliasVault.SmtpService/Workers/SmtpServerWorker.cs b/src/Services/AliasVault.SmtpService/Workers/SmtpServerWorker.cs
index 66bae290b..09e9c3a21 100644
--- a/src/Services/AliasVault.SmtpService/Workers/SmtpServerWorker.cs
+++ b/src/Services/AliasVault.SmtpService/Workers/SmtpServerWorker.cs
@@ -7,6 +7,11 @@
namespace AliasVault.SmtpService.Workers;
+/// <summary>
+/// A worker for the SMTP server.
+/// </summary>
+/// <param name="logger">ILogger instance.</param>
+/// <param name="smtpServer">SmtpServer instance.</param>
public class SmtpServerWorker(ILogger<SmtpServerWorker> logger, SmtpServer.SmtpServer smtpServer) : BackgroundService
{
/// <inheritdoc />
diff --git a/src/Tests/AliasVault.E2ETests/AliasVault.E2ETests.csproj b/src/Tests/AliasVault.E2ETests/AliasVault.E2ETests.csproj
index f0d5ce876..ea7b1b9b4 100644
--- a/src/Tests/AliasVault.E2ETests/AliasVault.E2ETests.csproj
+++ b/src/Tests/AliasVault.E2ETests/AliasVault.E2ETests.csproj
@@ -49,6 +49,7 @@
<ProjectReference Include="..\..\AliasVault.Admin\AliasVault.Admin.csproj" />
<ProjectReference Include="..\..\AliasVault.Api\AliasVault.Api.csproj" />
<ProjectReference Include="..\..\Databases\AliasServerDb\AliasServerDb.csproj" />
+ <ProjectReference Include="..\AliasVault.IntegrationTests\AliasVault.IntegrationTests.csproj" />
<ProjectReference Include="..\Server\AliasVault.E2ETests.Client.Server\AliasVault.E2ETests.Client.Server.csproj" />
</ItemGroup>
diff --git a/src/Tests/AliasVault.E2ETests/Tests/Client/EmailDecryptionTest.cs b/src/Tests/AliasVault.E2ETests/Tests/Client/EmailDecryptionTest.cs
new file mode 100644
index 000000000..366368d6c
--- /dev/null
+++ b/src/Tests/AliasVault.E2ETests/Tests/Client/EmailDecryptionTest.cs
@@ -0,0 +1,153 @@
+//-----------------------------------------------------------------------
+// <copyright file="EmailDecryptionTest.cs" company="lanedirt">
+// Copyright (c) lanedirt. All rights reserved.
+// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace AliasVault.E2ETests.Tests.Client;
+
+using AliasVault.IntegrationTests.SmtpServer;
+using MailKit.Net.Smtp;
+using MailKit.Security;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.Extensions.Hosting;
+using MimeKit;
+
+/// <summary>
+/// End-to-end tests for making sure errors and warnings in API are logged to database.
+/// </summary>
+[TestFixture]
+[Category("ClientTests")]
+[NonParallelizable]
+public class EmailDecryptionTest : ClientPlaywrightTest
+{
+ /// <summary>
+ /// The test host instance.
+ /// </summary>
+ private IHost _testHost = null!;
+
+ /// <summary>
+ /// The test host builder instance.
+ /// </summary>
+ private TestHostBuilder _testHostBuilder = null!;
+
+ /// <summary>
+ /// Setup logic for every test.
+ /// </summary>
+ /// <returns>Task.</returns>
+ [SetUp]
+ public async Task Setup()
+ {
+ // Start the SMTP server test host so we can send emails to it and test encryption/decryption.
+ _testHostBuilder = new TestHostBuilder();
+ _testHost = _testHostBuilder.Build(ApiDbContext.Database.GetDbConnection());
+ await _testHost.StartAsync();
+ }
+
+ /// <summary>
+ /// Test if received email encrypted by server can be successfully decrypted by client.
+ /// </summary>
+ /// <returns>Async task.</returns>
+ [Test]
+ public async Task EmailEncryptionDecryptionTest()
+ {
+ // Create credential which should automatically create claim on server during database sync.
+ const string serviceName = "Test Service";
+ const string email = "[email protected]";
+ await CreateCredentialEntry(new Dictionary<string, string>
+ {
+ { "service-name", serviceName },
+ { "email", email },
+ });
+
+ // Assert that the claim was created on the server.
+ var claim = await ApiDbContext.UserEmailClaims.Where(x => x.Address == email).FirstOrDefaultAsync();
+ Assert.That(claim, Is.Not.Null, "Claim for email address not found in database. Check if credential creation and claim creation are working correctly.");
+
+ // Assert that the users public key was created on the server.
+ var publicKey = await ApiDbContext.UserEncryptionKeys.Where(x => x.UserId == claim.UserId).FirstOrDefaultAsync();
+ Assert.That(publicKey, Is.Not.Null, "Public key for user not found in database. Check if public key creation is working correctly.");
+ Assert.That(publicKey.PublicKey.Length, Is.GreaterThanOrEqualTo(100), "Public key exists but length does not match expected. Check if public key creation is working correctly.");
+
+ // Email the SMTP server which will save the email in encrypted form in the database..
+ var message = new MimeMessage();
+ message.From.Add(new MailboxAddress("Test Sender", "[email protected]"));
+ message.To.Add(new MailboxAddress("Test Recipient", email));
+ const string textSubject = "Encrypted Email Subject";
+ const string textBody = "This is a test email plain.";
+ message.Subject = textSubject;
+ message.Body = new BodyBuilder { TextBody = textBody }.ToMessageBody();
+ await SendMessageToSmtpServer(message);
+
+ // Assert that email was received by the server.
+ var emailReceived = await ApiDbContext.Emails.FirstOrDefaultAsync(x => x.To == email);
+ Assert.That(emailReceived, Is.Not.Null, "Email not received by server. Check SMTP server and email encryption/decryption logic.");
+
+ // Assert that subject is not stored as plain text in the database.
+ Assert.That(emailReceived.Subject, Does.Not.Contain(textSubject), "Email subject stored as plain text in database. Check email encryption logic.");
+
+ // Attempt to click on email refresh button to get new emails.
+ // Id = recent-email-refresh
+ await Page.Locator("id=recent-email-refresh").First.ClickAsync();
+
+ // Wait for 1 sec
+ await Task.Delay(1000);
+
+ // Check if the email is visible on the page now.
+ var emailContent = await Page.TextContentAsync("body");
+ Assert.That(emailContent, Does.Contain(textSubject), "Email not (correctly) decrypted and displayed on the page. Check email decryption logic.");
+ }
+
+ /// <summary>
+ /// Test that adding a credential with email domain that is not in the known list to not get added as claim.
+ /// </summary>
+ /// <returns>Async task.</returns>
+ [Test]
+ public async Task EmailUnknownDomainNoClaimTest()
+ {
+ // Create credential which should automatically create claim on server during database sync.
+ const string serviceName = "Test Service";
+ const string email = "[email protected]";
+ await CreateCredentialEntry(new Dictionary<string, string>
+ {
+ { "service-name", serviceName },
+ { "email", email },
+ });
+
+ // Assert that the claim was created on the server.
+ var claim = await ApiDbContext.UserEmailClaims.FirstOrDefaultAsync(x => x.Address == email);
+
+ Assert.That(claim, Is.Null, "Claim for unknown email address domain found in database. Check if claim creation domain check is working correctly.");
+ }
+
+ /// <summary>
+ /// Tear down logic for every test.
+ /// </summary>
+ /// <returns>Task.</returns>
+ [TearDown]
+ public async Task TearDown()
+ {
+ await _testHost.StopAsync();
+ _testHost.Dispose();
+ }
+
+ /// <summary>
+ /// Sends a message to the SMTP server.
+ /// </summary>
+ /// <param name="message">MimeMessage to send.</param>
+ private static async Task SendMessageToSmtpServer(MimeMessage message)
+ {
+ using var client = new SmtpClient();
+
+ await client.ConnectAsync("localhost", 2525, SecureSocketOptions.None);
+ try
+ {
+ await client.SendAsync(message);
+ }
+ finally
+ {
+ await client.DisconnectAsync(true);
+ }
+ }
+}
diff --git a/src/Tests/AliasVault.IntegrationTests/SmtpServer/SmtpServerTests.cs b/src/Tests/AliasVault.IntegrationTests/SmtpServer/SmtpServerTests.cs
index 871d5f46b..2b34f3ebd 100644
--- a/src/Tests/AliasVault.IntegrationTests/SmtpServer/SmtpServerTests.cs
+++ b/src/Tests/AliasVault.IntegrationTests/SmtpServer/SmtpServerTests.cs
@@ -20,11 +20,13 @@ public class SmtpServerTests
{
/// <summary>
/// Example public key for RSA encryption tests. This is a public key generated by the JSInterop on the client.
+ /// We use this here to also test the server-side decryption implementation, even though this isn't a real-world scenario.
/// </summary>
public const string PublicKey = "{\"alg\":\"RSA-OAEP-256\",\"e\":\"AQAB\",\"ext\":true,\"key_ops\":[\"encrypt\"],\"kty\":\"RSA\",\"n\":\"lW8fRfSvLQiK9uZgm_kFjHMY1SedAZlVvZ_8d_d5oqWezQhan8-Y10Qvx0NMe57sQB3ePnShJFNE33w83kgRNkOyxKJ2FOVKtRptd7CgwIt_l9TPjdrB0J0hFn9b1eit2vpQlOdP_Wa8WvW2eVdXYEMWuBU4-aj8vY2qzcmBc-HhJX-Me9oXhUscJxeqMP4_sNiN7D4I0enrmYicB3JQMhUIwMmNt-0srHTdSvHh_6vFZMqB9ohfh2D9Q0BzYcI8rGEy1RTYsmF1zYyoOOzeRGOcKCVNeLO9LZxfAdm1Eq5zv47uw543cxCZXIZPlXOVriMEtTRwaGzE_3RZmpGJqw\"}";
/// <summary>
/// Example private key for RSA encryption tests. This is a private key generated by the JSInterop on the client.
+ /// We use this here to also test the server-side decryption implementation, even though this isn't a real-world scenario.
/// </summary>
public const string PrivateKey = "{\"alg\":\"RSA-OAEP-256\",\"d\":\"KLByToUaseNym1oNkkrTRPQOHfREXywWWaTXhP8AwtXgEKomqv9G-c6aR-K-T6btY2P-oPj268I0rbnRhSEQdrsmUT5_cp8goYGJrx6MFwGlA32x6klXnus6GDsjkXJi7I5eJL17XV99CDOBtTagFxkNdaBpvClUcHTDvncQ5bGAIrNqS7KADoi-E19BxiW_GcSJiVT4H8kDHCkcgTjZx4rKJjTPqqJOLg_poDrvnTJbsjcXP80kQ1AAENRAvDGhSWzP0IYtP1DM_2FzM1s1b_SrUsS3KiO8drR2Kv-PSOvncpaNVnZGElGCraJ3B2Mm-dr3vFjkyWeWPceqyhtYoQ\",\"dp\":\"ttxRg6uB2YLWfkPKUkzAaBWniZDHM4silJX3IgexA5GJBd9GIhUiVEolc_MgmieQbZ10CC65wqcHVv82lgCeqxYHxHWLxxJCrOpvkFlYE8wr_WqOPQEzYKv3KsL6s6Fj7Pbv9WehWpXdlbJUm4Cy5cgUkdH6PXiwBSvfhCQGrYk\",\"dq\":\"YFqlDAVTfvTR2bMJulvWzd_at81CsEmR-lPo91h-3cLpxcLDOlrTP-d3Ass2I4r1PtBT1bKuuHeQ6fZmHH55a6m8XxPEs2BuIxlh9RiFfWbd66969UOnItuawf0rfGneKt1zl4st60T3KXd8-ECrLxdsvOYpOEuNzvIY_b3qitE\",\"e\":\"AQAB\",\"ext\":true,\"key_ops\":[\"decrypt\"],\"kty\":\"RSA\",\"n\":\"lW8fRfSvLQiK9uZgm_kFjHMY1SedAZlVvZ_8d_d5oqWezQhan8-Y10Qvx0NMe57sQB3ePnShJFNE33w83kgRNkOyxKJ2FOVKtRptd7CgwIt_l9TPjdrB0J0hFn9b1eit2vpQlOdP_Wa8WvW2eVdXYEMWuBU4-aj8vY2qzcmBc-HhJX-Me9oXhUscJxeqMP4_sNiN7D4I0enrmYicB3JQMhUIwMmNt-0srHTdSvHh_6vFZMqB9ohfh2D9Q0BzYcI8rGEy1RTYsmF1zYyoOOzeRGOcKCVNeLO9LZxfAdm1Eq5zv47uw543cxCZXIZPlXOVriMEtTRwaGzE_3RZmpGJqw\",\"p\":\"yUdbuDwmVwKhou5xXUxJfi1eOjN-5F88wtyR4LpgU2OvZ7m-er4hpXx5I2E-KTVX_iIp0Q9VDXhHH-WkN3qg20RXjRoxwgrggYbfdIYdrB-2kbMamq5cOf2XbXGEO8PoDXYoZprIB0EhrD4qVVykPUYg5El0hIKPdfs9LNoOEzs\",\"q\":\"vg93lGTurG0EY179tPr6Qe3ttKEN9zvQ97dZ9034DOWDoWLe-iMKG1-yKmkG4uwC8QqNnm1mPz7EqOuHPPGVTTib9NA4JdM27PUHSPKDUvp0cV4LhF6e-W7tMFk8WbJ2ACqkqhZHYgm-FDkZBCpnehNegTxipLluKa79G__ZHFE\",\"qi\":\"fnI3Wh5aYuxI0R18NTeFKjo1P7_Ck65Gc9O3CmeqiIe58EJaXQEcdwdSOG8aVmn03szXLHEnp7anNIH63f0ericbRYdCQVhcQpvsXzEM_sp4aYmwz45palrjlY4Jc6G6XQn3FwiqqRDvpnXdsunnQ62HHhxmslaEMYHQyLng2ss\"}";
@@ -98,11 +100,8 @@ public class SmtpServerTests
[TearDown]
public async Task TearDown()
{
- if (_testHost != null)
- {
- await _testHost.StopAsync();
- _testHost.Dispose();
- }
+ await _testHost.StopAsync();
+ _testHost.Dispose();
}
/// <summary>
@@ -111,7 +110,7 @@ public class SmtpServerTests
[Test]
public async Task SingleEmailPlain()
{
- // Send an email to the SMTP server.
+ // Email the SMTP server.
var message = new MimeMessage();
message.From.Add(new MailboxAddress("Test Sender", "[email protected]"));
message.To.Add(new MailboxAddress("Test Recipient", "[email protected]"));
diff --git a/src/Tests/AliasVault.IntegrationTests/SmtpServer/TestHostBuilder.cs b/src/Tests/AliasVault.IntegrationTests/SmtpServer/TestHostBuilder.cs
index 853bf414c..a1d720949 100644
--- a/src/Tests/AliasVault.IntegrationTests/SmtpServer/TestHostBuilder.cs
+++ b/src/Tests/AliasVault.IntegrationTests/SmtpServer/TestHostBuilder.cs
@@ -5,13 +5,12 @@
// </copyright>
// -----------------------------------------------------------------------
-using AliasVault.SmtpService.Handlers;
-using AliasVault.SmtpService.Workers;
-
namespace AliasVault.IntegrationTests.SmtpServer;
using System.Data.Common;
using AliasServerDb;
+using AliasVault.SmtpService.Handlers;
+using AliasVault.SmtpService.Workers;
using SmtpService;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.DependencyInjection;
@@ -60,8 +59,20 @@ public class TestHostBuilder
public IHost Build()
{
// Create a persistent in-memory database for the duration of the test.
- _dbConnection = new SqliteConnection("DataSource=:memory:");
- _dbConnection.Open();
+ var dbConnection = new SqliteConnection("DataSource=:memory:");
+ dbConnection.Open();
+
+ return Build(dbConnection);
+ }
+
+ /// <summary>
+ /// Builds the SmtpService test host with a provided database connection.
+ /// </summary>
+ /// <returns></returns>
+ public IHost Build(DbConnection dbConnection)
+ {
+ // Create a persistent in-memory database for the duration of the test.
+ _dbConnection = dbConnection;
var builder = Host.CreateDefaultBuilder()
.ConfigureServices((context, services) =>
@@ -81,7 +92,7 @@ public class TestHostBuilder
});
services.AddTransient<IMessageStore, DatabaseMessageStore>();
- services.AddSingleton<global::SmtpServer.SmtpServer>(
+ services.AddSingleton<SmtpServer>(
provider =>
{
var options = new SmtpServerOptionsBuilder()