Skip to content

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

Add E2E test in .NET that tests the chrome extension (#541)

Leendert de Borstf8194708a036
diff --git a/.github/workflows/dotnet-e2e-misc-tests.yml b/.github/workflows/dotnet-e2e-misc-tests.yml
deleted file mode 100644
index 7f5ee5124..000000000
--- a/.github/workflows/dotnet-e2e-misc-tests.yml
+++ /dev/null
@@ -1,46 +0,0 @@
-# This workflow will test if running the E2E Misc tests via Playwright CLI works.
-name: .NET E2E Misc Tests (Playwright)
-
-on:
- push:
- branches: [ "main" ]
- pull_request:
- branches: [ "main" ]
-
-jobs:
- misc-tests:
- timeout-minutes: 60
- runs-on: ubuntu-latest
- steps:
- - uses: actions/checkout@v4
-
- - name: Setup .NET
- uses: actions/setup-dotnet@v4
- with:
- dotnet-version: 9.0.x
-
- - name: Install dependencies
- run: dotnet workload install wasm-tools
-
- - name: Build
- run: dotnet build
-
- - name: Start dev database
- run: ./install.sh configure-dev-db start
-
- - name: Ensure browsers are installed
- run: pwsh src/Tests/AliasVault.E2ETests/bin/Debug/net9.0/playwright.ps1 install --with-deps
-
- - name: Run remaining tests with retry
- uses: nick-fields/retry@v3
- with:
- timeout_minutes: 60
- max_attempts: 3
- command: dotnet test src/Tests/AliasVault.E2ETests --no-build --verbosity normal --filter "Category!=AdminTests&Category!=ClientTests"
-
- - name: Upload Test Results
- if: always()
- uses: actions/upload-artifact@v4
- with:
- name: misc-test-results
- path: TestResults-Misc.xml
diff --git a/browser-extensions/chrome/package.json b/browser-extensions/chrome/package.json
index fed5e340d..a076953ac 100644
--- a/browser-extensions/chrome/package.json
+++ b/browser-extensions/chrome/package.json
@@ -9,7 +9,7 @@
"lint": "eslint src",
"lint:fix": "eslint src --fix",
"build": "npm run lint && vite build && npm run build:content-css",
- "watch": "concurrently \"npm run lint -- --watch\" \"vite\"",
+ "watch": "vite build --watch",
"build:content-css": "tailwindcss -i ./src/styles/contentScript.css -o ./dist/contentScript.css --config tailwind.content.config.js"
},
"keywords": [],
diff --git a/browser-extensions/chrome/src/App.tsx b/browser-extensions/chrome/src/App.tsx
index c4862e036..a7b4e3c7b 100644
--- a/browser-extensions/chrome/src/App.tsx
+++ b/browser-extensions/chrome/src/App.tsx
@@ -74,6 +74,7 @@ const App: React.FC = () => {
<div className="border-b border-gray-200 dark:border-gray-700">
<div className="flex justify-between items-center px-4 py-3">
<button
+ id="back"
onClick={() => setShowSettings(false)}
className="text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200"
>
@@ -98,6 +99,7 @@ const App: React.FC = () => {
</div>
{!isLoggedIn ? (
<button
+ id="settings"
onClick={toggleSettings}
className="p-2 text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700"
>
@@ -105,6 +107,7 @@ const App: React.FC = () => {
</button>
) : (
<span
+ id="logout"
onClick={handleLogout}
className="cursor-pointer text-gray-500 dark:text-gray-400"
>
diff --git a/browser-extensions/chrome/src/pages/Settings.tsx b/browser-extensions/chrome/src/pages/Settings.tsx
index 2df2d45bf..2adf93757 100644
--- a/browser-extensions/chrome/src/pages/Settings.tsx
+++ b/browser-extensions/chrome/src/pages/Settings.tsx
@@ -81,6 +81,7 @@ const Settings: React.FC = () => {
Custom API URL
</label>
<input
+ id="custom-api-url"
type="text"
value={customUrl}
onChange={handleCustomUrlChange}
diff --git a/browser-extensions/chrome/vite.config.js b/browser-extensions/chrome/vite.config.js
index b6b500993..0cb2d9eeb 100644
--- a/browser-extensions/chrome/vite.config.js
+++ b/browser-extensions/chrome/vite.config.js
@@ -55,10 +55,6 @@ export default defineConfig({
format: 'es'
}
},
- watch: {
- include: ['src/**'],
- exclude: ['node_modules/**']
- },
outDir: 'dist',
},
resolve: {
diff --git a/src/Tests/AliasVault.E2ETests/Common/AdminPlaywrightTest.cs b/src/Tests/AliasVault.E2ETests/Common/AdminPlaywrightTest.cs
index 411b88af9..5aaa3ab51 100644
--- a/src/Tests/AliasVault.E2ETests/Common/AdminPlaywrightTest.cs
+++ b/src/Tests/AliasVault.E2ETests/Common/AdminPlaywrightTest.cs
@@ -36,7 +36,10 @@ public class AdminPlaywrightTest : PlaywrightTest
{
await Page.CloseAsync();
await Context.CloseAsync();
- await Browser.CloseAsync();
+ if (Browser != null)
+ {
+ await Browser.CloseAsync();
+ }
await _webAppFactory.DisposeAsync();
}
diff --git a/src/Tests/AliasVault.E2ETests/Common/ClientPlaywrightTest.cs b/src/Tests/AliasVault.E2ETests/Common/ClientPlaywrightTest.cs
index a099662d8..b104d92b6 100644
--- a/src/Tests/AliasVault.E2ETests/Common/ClientPlaywrightTest.cs
+++ b/src/Tests/AliasVault.E2ETests/Common/ClientPlaywrightTest.cs
@@ -61,11 +61,14 @@ public class ClientPlaywrightTest : PlaywrightTest
/// </summary>
/// <returns>Async task.</returns>
[OneTimeTearDown]
- public async Task OneTimeTearDown()
+ public virtual async Task OneTimeTearDown()
{
await Page.CloseAsync();
await Context.CloseAsync();
- await Browser.CloseAsync();
+ if (Browser != null)
+ {
+ await Browser.CloseAsync();
+ }
await _apiFactory.DisposeAsync();
await _clientFactory.DisposeAsync();
diff --git a/src/Tests/AliasVault.E2ETests/Common/PlaywrightTest.cs b/src/Tests/AliasVault.E2ETests/Common/PlaywrightTest.cs
index e63f9dd73..95e150aeb 100644
--- a/src/Tests/AliasVault.E2ETests/Common/PlaywrightTest.cs
+++ b/src/Tests/AliasVault.E2ETests/Common/PlaywrightTest.cs
@@ -39,7 +39,7 @@ public abstract class PlaywrightTest
/// <summary>
/// Gets or sets the Playwright browser instance.
/// </summary>
- protected IBrowser Browser { get; set; } = null!;
+ protected IBrowser? Browser { get; set; }
/// <summary>
/// Gets or sets the Playwright browser context.
@@ -86,6 +86,10 @@ public abstract class PlaywrightTest
{
throw;
}
+ catch (ArgumentException)
+ {
+ throw;
+ }
catch (Exception ex)
{
currentRetry++;
@@ -179,7 +183,7 @@ public abstract class PlaywrightTest
/// Setup the Playwright browser and context based on settings defined in appsettings.json.
/// </summary>
/// <returns>Task.</returns>
- protected async Task SetupPlaywrightBrowserAndContext()
+ protected virtual async Task SetupPlaywrightBrowserAndContext()
{
// Set Playwright headless mode based on appsettings.json value.
var configuration = new ConfigurationBuilder()
diff --git a/src/Tests/AliasVault.E2ETests/Tests/Extensions/ChromeExtensionTests.cs b/src/Tests/AliasVault.E2ETests/Tests/Extensions/ChromeExtensionTests.cs
new file mode 100644
index 000000000..96de53e55
--- /dev/null
+++ b/src/Tests/AliasVault.E2ETests/Tests/Extensions/ChromeExtensionTests.cs
@@ -0,0 +1,175 @@
+//-----------------------------------------------------------------------
+// <copyright file="ChromeExtensionTests.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.Extensions;
+
+/// <summary>
+/// End-to-end tests for the Chrome extension. We extend from ClientPlaywrightTest as extension tess requires
+/// mutating things via the client too to test all extension functionality properly such as syncing vaults.
+/// </summary>
+[Parallelizable(ParallelScope.Self)]
+[Category("ExtensionTests")]
+[TestFixture]
+public class ChromeExtensionTests : ClientPlaywrightTest
+{
+ private string _extensionPath = string.Empty;
+
+ /// <summary>
+ /// Tests if the extension can load a vault and a previously created credential entry is present.
+ /// </summary>
+ /// <returns>Async task.</returns>
+ [Test]
+ public async Task ExtensionCredentialExists()
+ {
+ // Create a new alias with service name = "Test Service".
+ var serviceName = "Test Service";
+ await CreateCredentialEntry(new Dictionary<string, string>
+ {
+ { "service-name", serviceName },
+ });
+
+ var extensionPopup = await LoginToExtension();
+
+ // Assert extension loaded vault successfully and service name is present.
+ await extensionPopup.WaitForSelectorAsync("text=" + serviceName);
+ var pageContent = await extensionPopup.TextContentAsync("body");
+ Assert.That(pageContent, Does.Contain(serviceName));
+ }
+
+ /// <summary>
+ /// Setup the Playwright browser and context based on settings defined in appsettings.json.
+ /// </summary>
+ /// <returns>Task.</returns>
+ protected override async Task SetupPlaywrightBrowserAndContext()
+ {
+ // Make sure the extension is built and ready to use.
+ ExtensionSetup();
+
+ var playwright = await Playwright.CreateAsync();
+
+ // Launch persistent context with the extension loaded
+ Context = await playwright.Chromium.LaunchPersistentContextAsync(
+ userDataDir: string.Empty, // Empty string means temporary directory
+ new BrowserTypeLaunchPersistentContextOptions
+ {
+ Headless = false,
+ Args = new[]
+ {
+ "--disable-extensions-except=" + _extensionPath,
+ "--load-extension=" + _extensionPath,
+ },
+ ServiceWorkers = ServiceWorkerPolicy.Allow,
+ });
+ }
+
+ /// <summary>
+ /// Find the solution root directory by walking up from the current assembly location.
+ /// </summary>
+ /// <param name="startPath">The starting directory.</param>
+ /// <returns>The solution root directory.</returns>
+ private static string FindSolutionRoot(string startPath)
+ {
+ var directory = new DirectoryInfo(startPath);
+ while (directory != null && !File.Exists(Path.Combine(directory.FullName, "AliasVault.sln")))
+ {
+ directory = directory.Parent;
+ }
+
+ if (directory == null)
+ {
+ throw new DirectoryNotFoundException("Could not find solution root directory");
+ }
+
+ return directory.FullName;
+ }
+
+ /// <summary>
+ /// Sets up the extension by running npm install and build.
+ /// </summary>
+ private void ExtensionSetup()
+ {
+ // Get the solution directory by walking up from the current assembly location
+ var currentDir = Path.GetDirectoryName(typeof(ChromeExtensionTests).Assembly.Location)
+ ?? throw new InvalidOperationException("Current directory not found");
+ var solutionDir = FindSolutionRoot(currentDir);
+
+ // Construct absolute path to extension directory
+ var extensionDir = Path.GetFullPath(Path.Combine(solutionDir, "browser-extensions", "chrome"));
+ var distDir = Path.GetFullPath(Path.Combine(extensionDir, "dist"));
+ var manifestPath = Path.Combine(distDir, "manifest.json");
+
+ // Verify the dist directory exists and contains required files
+ if (!Directory.Exists(distDir) || !File.Exists(manifestPath))
+ {
+ throw new ArgumentException($"Chrome extension dist directory and/or manifest.json not found at {distDir}. Please run 'npm install && npm run build' in {extensionDir}.");
+ }
+
+ _extensionPath = distDir.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
+ }
+
+ /// <summary>
+ /// Open the extension popup, configure the API URL and login with the test credentials.
+ /// </summary>
+ /// <returns>Task.</returns>
+ private async Task<IPage> LoginToExtension()
+ {
+ // Use reflection to access the ServiceWorkers property
+ List<object> serviceWorkers;
+ try
+ {
+ var serviceWorkersProperty = Context.GetType().GetProperty("ServiceWorkers");
+ var serviceWorkersEnumerable = serviceWorkersProperty?.GetValue(Context) as IEnumerable<object>;
+
+ if (serviceWorkersEnumerable == null)
+ {
+ throw new InvalidOperationException("Could not find extension service workers");
+ }
+
+ serviceWorkers = serviceWorkersEnumerable.ToList();
+ if (!serviceWorkers.Any())
+ {
+ throw new InvalidOperationException("No extension service workers found");
+ }
+ }
+ catch (Exception ex)
+ {
+ Console.WriteLine($"Failed to get service workers, check if the extension is loaded properly: {ex.Message}");
+ throw;
+ }
+
+ // Get the first service worker's URL using reflection
+ var firstWorker = serviceWorkers[0];
+ var urlProperty = firstWorker.GetType().GetProperty("Url");
+ var url = urlProperty?.GetValue(firstWorker) as string;
+
+ var extensionId = url?.Split('/')[2]
+ ?? throw new InvalidOperationException("Could not find extension service worker URL");
+
+ // Open popup in a new page
+ var extensionPopup = await Context.NewPageAsync();
+ await extensionPopup.GotoAsync($"chrome-extension://{extensionId}/index.html");
+
+ // Configure API URL in settings first
+ await extensionPopup.ClickAsync("button[id='settings']");
+
+ // Select "Self-hosted" option first
+ await extensionPopup.SelectOptionAsync("select", ["custom"]);
+
+ // Fill in the custom URL input that appears
+ await extensionPopup.FillAsync("input[id='custom-api-url']", ApiBaseUrl);
+
+ // Go back to main page
+ await extensionPopup.ClickAsync("button[id='back']");
+
+ // Test vault loading with username and password
+ await extensionPopup.FillAsync("input[type='text']", TestUserUsername);
+ await extensionPopup.FillAsync("input[type='password']", TestUserPassword);
+ await extensionPopup.ClickAsync("button:has-text('Login')");
+
+ return extensionPopup;
+ }
+}