Skip to content

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

10.8 KB
Raw Blame
//-----------------------------------------------------------------------
// <copyright file="EmailController.cs" company="aliasvault">
// Copyright (c) aliasvault. All rights reserved.
// Licensed under the AGPLv3 license. See LICENSE.md file in the project root for full license information.
// </copyright>
//-----------------------------------------------------------------------

namespace AliasVault.Api.Controllers.V1.Email;

using AliasServerDb;
using AliasVault.Api.Controllers.Abstracts;
using AliasVault.Auth.IpAddress;
using AliasVault.Shared.Models.WebApi.V1.Email;
using Asp.Versioning;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

/// <summary>
/// Email controller for retrieving emails from the database.
/// </summary>
/// <param name="logger">ILogger instance.</param>
/// <param name="dbContextFactory">DbContext instance.</param>
/// <param name="userManager">UserManager instance.</param>
/// <param name="ipBlockListService">IpBlockListService used to shadow-block email retrieval from blocked IPs.</param>
[ApiVersion("1")]
public class EmailController(ILogger<EmailController> logger, IAliasServerDbContextFactory dbContextFactory, UserManager<AliasVaultUser> userManager, IpBlockListService ipBlockListService) : AuthenticatedRequestController(userManager)
{
    /// <summary>
    /// Get the email with the specified ID.
    /// </summary>
    /// <param name="id">The email ID to open.</param>
    /// <returns>List of aliases in JSON format.</returns>
    [HttpGet(template: "{id:int}", Name = "GetEmail")]
    public async Task<IActionResult> GetEmail(int id)
    {
        await using var context = await dbContextFactory.CreateDbContextAsync();

        var (email, personalDecryptionKey, errorResult) = await AuthenticateAndRetrieveEmailAsync(id, context);
        if (errorResult != null)
        {
            return errorResult;
        }

        var returnEmail = new EmailApiModel
        {
            Id = email!.Id,
            Subject = email.Subject,
            FromDisplay = email.From,
            FromDomain = email.FromDomain,
            FromLocal = email.FromLocal,
            ToDomain = email.ToDomain,
            ToLocal = email.ToLocal,
            Date = email.Date,
            DateSystem = email.DateSystem,
            SecondsAgo = (int)DateTime.UtcNow.Subtract(email.DateSystem).TotalSeconds,
            MessageHtml = email.MessageHtml,
            MessagePlain = email.MessagePlain,
            MessageSource = email.MessageSourceBytes is not null ? Convert.ToBase64String(email.MessageSourceBytes) : email.MessageSource,
            EncryptedSymmetricKey = personalDecryptionKey!.EncryptedSymmetricKey,
            EncryptionKey = personalDecryptionKey.VaultManifestDeliveryKey.PublicKey,
        };

        // Add attachment metadata (without the filebytes)
        var attachments = await context.EmailAttachments.Where(x => x.EmailId == email.Id).Select(x => new AttachmentApiModel()
        {
            Id = x.Id,
            Email_Id = x.EmailId,
            Filename = x.Filename,
            MimeType = x.MimeType,
            Filesize = x.Filesize,
        }).ToListAsync();

        returnEmail.Attachments = attachments;

        return Ok(returnEmail);
    }

    /// <summary>
    /// Deletes an email for the current user.
    /// </summary>
    /// <param name="id">The email ID to delete.</param>
    /// <returns>A response indicating the success or failure of the deletion.</returns>
    [HttpDelete(template: "{id:int}", Name = "DeleteEmail")]
    public async Task<IActionResult> DeleteEmail(int id)
    {
        await using var context = await dbContextFactory.CreateDbContextAsync();

        var (email, _, errorResult) = await AuthenticateAndRetrieveEmailAsync(id, context);
        if (errorResult != null)
        {
            return errorResult;
        }

        // Delete the email - attachments will be cascade deleted
        context.Emails.Remove(email!);

        try
        {
            await context.SaveChangesAsync();
            return Ok();
        }
        catch (Exception ex)
        {
            // Log the exception
            logger.LogError(ex, "An error occurred while deleting email with ID {id}.", id);
            return StatusCode(500, "An error occurred while deleting the email.");
        }
    }

    /// <summary>
    /// Get the attachment bytes for the specified email and attachment ID.
    /// </summary>
    /// <param name="id">The email ID.</param>
    /// <param name="attachmentId">The attachment ID.</param>
    /// <returns>Attachment bytes in encrypted form.</returns>
    [HttpGet(template: "{id:int}/attachments/{attachmentId:int}", Name = "GetEmailAttachment")]
    public async Task<IActionResult> GetEmailAttachment(int id, int attachmentId)
    {
        await using var context = await dbContextFactory.CreateDbContextAsync();

        var (email, _, errorResult) = await AuthenticateAndRetrieveEmailAsync(id, context);
        if (errorResult != null)
        {
            return errorResult;
        }

        // Find the requested attachment
        var attachment = await context.EmailAttachments
            .FirstOrDefaultAsync(x => x.Id == attachmentId && x.EmailId == email!.Id);

        if (attachment == null)
        {
            return NotFound("Attachment not found.");
        }

        // Return the encrypted bytes as opaque binary. The original MIME type would be
        // misleading since the payload is AES ciphertext, not a renderable file.
        return File(attachment.Bytes, "application/octet-stream", attachment.Filename);
    }

    /// <summary>
    /// Delete multiple emails.
    /// </summary>
    /// <param name="model">Request model.</param>
    /// <returns>A EmailBulkResponse instance representing the result of the asynchronous operation.</returns>
    [HttpDelete(template: "bulk", Name = "BulkDelete")]
    public async Task<IActionResult> BulkDelete([FromBody] EmailBulkRequest model)
    {
        await using var context = await dbContextFactory.CreateDbContextAsync();

        var user = await GetCurrentUserAsync();
        if (user is null)
        {
            return Unauthorized("Not authenticated.");
        }

        // Sanitize input
        model.Ids = [.. model.Ids.Where(id => id > 0).Distinct()];

        if (model.Ids.Count == 0)
        {
            // Nothing to delete
            return StatusCode(304);
        }

        // For each email ID, validate if user has access and if email exists
        foreach (int emailId in model.Ids)
        {
            var (_, _, errorResult) = await RetrieveEmailAsync(emailId, user, context);
            if (errorResult != null)
            {
                return errorResult;
            }
        }

        try
        {
            await context.Emails
                .Where(e => model.Ids.Contains(e.Id))
                .Where(e => context.EmailClaims.Any(c => c.Address == e.To.Trim().ToLower() && c.State != EmailClaimState.Removed && c.VaultManifest!.OwnerGroupId == user.PersonalGroupId))
                .ExecuteDeleteAsync();
        }
        catch (Exception ex)
        {
            logger.LogError(ex, "An error occurred while deleting the emails.");
            return StatusCode(500);
        }

        EmailBulkResponse returnValue = new()
        {
            SuccessfulEmailIds = model.Ids,
        };
        return Ok(returnValue);
    }

    /// <summary>
    /// Authenticates the user and retrieves the requested email.
    /// </summary>
    /// <param name="id">The email ID to retrieve.</param>
    /// <param name="context">The database context.</param>
    /// <returns>A tuple containing the email, the decryption key belonging to the caller's personal keys, and an IActionResult if there's an error.</returns>
    private async Task<(Email? Email, EmailDecryptionKey? PersonalDecryptionKey, IActionResult? ErrorResult)> AuthenticateAndRetrieveEmailAsync(int id, AliasServerDbContext context)
    {
        var user = await GetCurrentUserAsync();
        if (user is null)
        {
            return (null, null, Unauthorized("Not authenticated."));
        }

        return await RetrieveEmailAsync(id, user, context);
    }

    /// <summary>
    /// Retrieves the requested email for an already authenticated user.
    /// </summary>
    /// <param name="id">The email ID to retrieve.</param>
    /// <param name="user">The authenticated AliasVault user.</param>
    /// <param name="context">The database context.</param>
    /// <returns>A tuple containing the email, the decryption key belonging to the caller's personal keys, and an IActionResult if there's an error.</returns>
    private async Task<(Email? Email, EmailDecryptionKey? PersonalDecryptionKey, IActionResult? ErrorResult)> RetrieveEmailAsync(int id, AliasVaultUser user, AliasServerDbContext context)
    {
        // Retrieve email from database.
        var email = await context.Emails
            .Include(x => x.Attachments)
            .Include(x => x.DecryptionKeys)
            .ThenInclude(d => d.VaultManifestDeliveryKey)
            .FirstOrDefaultAsync(x => x.Id == id);

        if (email is null)
        {
            return (null, null, NotFound("Email not found."));
        }

        // Shadow-block: when active, emails received after the block took effect behave as if they do not exist.
        var shadowCutoff = await ipBlockListService.GetShadowBlockCutoffAsync(user, IpAddressUtility.GetRawIpAddressFromContext(HttpContext));

        // Hide emails received after a shadow-block took effect.
        if (shadowCutoff is not null && email.DateSystem > shadowCutoff.Value)
        {
            return (null, null, NotFound());
        }

        // See if this user has a valid claim to the email address.
        var normalizedEmailAddress = email.To.Trim().ToLower();
        var emailClaim = await context.EmailClaims
            .Where(x => x.Address == normalizedEmailAddress)
            .FirstOrDefaultAsync(x => x.State != EmailClaimState.Removed && x.VaultManifest!.OwnerGroupId == user.PersonalGroupId);

        if (emailClaim is null)
        {
            return (null, null, Unauthorized("User does not have a claim to this email address."));
        }

        // Serve the decryption key belonging to the caller's personal keys.
        var personalKeyIds = await context.VaultManifestDeliveryKeys
            .Where(k => context.VaultManifests.Any(m => m.ManifestId == k.VaultManifestId && m.OwnerGroupId == user.PersonalGroupId))
            .Select(k => k.Id)
            .ToListAsync();
        var personalDecryptionKey = email.DecryptionKeys.Where(d => personalKeyIds.Contains(d.VaultManifestDeliveryKeyId)).OrderBy(d => d.VaultManifestDeliveryKeyId).FirstOrDefault();
        if (personalDecryptionKey is null)
        {
            return (null, null, NotFound("Email not found."));
        }

        return (email, personalDecryptionKey, null);
    }
}